1.What Is an Angular Component?
An Angular application is a tree of Angular components.The component contains the data & user interaction logic that defines how the View looks and behaves. A view in Angular refers to a template (HTML).Components are like the basic building block in an Angular application.Components are defined using the @component decorator. A component has a selector, template, style and other properties, using which it specifies the metadata required to process the component. Angular components are a subset of directives. Unlike directives, components always have a template and only one component can be instantiated per an element in a template.

Components consist of three main building block

  1. Template
  2. Class
  3. MetaData

2.Angularjs vs Angular
Angularjs and Angular should be treated as two different frameworks. Here are few comparisons as below

>

AngularJS Angular
Controllers WebComponents
AngularJS is written in JavaScript.

Angular uses Microsoft’s TypeScript language, which is a superset of ECMAScript 6 (ES6). This has the combined advantages of the TypeScript features, like type declarations, and the benefits of ES6, like iterators and lambdas.
AngularJS is based on model-view-controller(MVC) Design and MVVM(Model-view-view-model) by two way data binding .In AngularJS the MVC pattern is implemented in JavaScript and HTML. The view is defined in HTML, while the model and controller are implemented in JavaScript. The controller accepts input, converts it into commands and sends the commands to the model and the view Angular 2 is more of component based architecture. You can assume everything as component like directives, services and so on. While directives and services are actually for the support of base components, they are also defined in similar fashion. A base component contains of dependencies, a view details and class declaration which may be considered as controller. So a well defined component consist of individual set of MVC architecture.Angular 2, controllers and $scope were replaced by components and directives. Components are directives with a template. They deal with a view of the application and logic on the page.
HTML markup is the View, Controller is the Controller & the Service (when it used to retrieve data) is the model. template is the View, class is the Controller & the Service (when it used to retrieve data) is the model.
To bind an image/property or an event with AngularJS, you have to remember the right ng directive. Angular focuses on “( )” for event binding and “[ ]” for property binding.
No Mobile Support Angular 2 and 4 both feature mobile support.
2-way binding, AngularJS reduced the development effort and time. However, by creating more processing on the client side, page load was taking considerable time. Angular implements unidirectional tree-based change detection and uses Hierarchical Dependency Injection system. This significantly boosts performance for the framework.
two-way data binding in Angular 2 is supported using the event and the property binding. We can use ngModel directive to use two-way data binding.

3.What are Directives
Directives are something that introduce new syntax / markup. They are markers on the DOM element which provides some special behavior to DOM elements and tells AngularJS’s HTML compiler to attach.

There are three kinds of directives in an Angular 2 application.
Components
Angular Component also refers to a directive with a template which deals with View of the Application and also contains the business logic. It is very useful to divide your Application into smaller parts. In other words, we can say that Components are directives that are always associated with the template directly.

Structural directives
Structural directives are able to change the behavior of DOM by adding and removing DOM elements. The directive NgFor, NgSwitch, and NgIf is the best example of structural directives.

Attribute directives
Attribute directives are able to change the behavior of DOM. The directive NgStyle is an example of Attribute directives which are used to change styles elements at the same time.

4.Difference between Component and Directive
Directives
Directives add behaviour to an existing DOM element or an existing component instance. One example use case for a directive would be to log a click on an element.

import {Directive} from '@angular/core';

@Directive({
    selector: "[logOnClick]",
    hostListeners: {
        'click': 'onClick()',
    },
})
class LogOnClick {
    constructor() {}
    onClick() { console.log('Element clicked!'); }
}
<button logOnClick>I log when clicked!</button>

Components
A component, rather than adding/modifying behaviour, actually creates its own view (hierarchy of DOM elements) with attached behaviour. An example use case for this might be a contact card component:

import {Component, View} from '@angular/core';

@Component({
  selector: 'contact-card',
  template: `
    <div>
      <h1>{{name}}</h1>
      <p>{{city}}</p>
    </div>
  `
})
class ContactCard {
  @Input() name: string
  @Input() city: string
  constructor() {}
}
<contact-card [name]="'foo'" [city]="'bar'"></contact-card>
Directive Component
They are used to create behavior to an existing DOM element. A component is a directive with a template and the @Component decorator is actually a @Directive decorator extended with template-oriented features. It used to shadow DOM to create encapsulates visual behavior. It is used to create UI widgets.
They help us to create re-usable components It helps us to break up our application in smaller component
We cannot create pipes using Attribute / Structural directive Pipes can be defined by component
We can define many directive per DOM element We can present only one component per DOM element
@directive keyword is used to define metadata @component keyword is used to define metadata

5.Directive Lifecycle

For the Directives there are three hooks provided for different event based on which we can take actions upon
ngOnChanges – It occurs when Angular sets data bound property. Here, we can get current and previous value of changed object. It is raised before the initialization event for directive.

ngOnInit – It occurs after Angular initializes the data-bound input properties.

ngDoCheck – It is raised every time when Angular detects any change.

ngOnDestroy – It is used for cleanup purposes and it is raised just before Angular destroys the directive. It is very much important in memory leak issues by un-subscribing observables and detaching event handlers.

6.What are Types of Databinding in Angular

  1. Interpolation / String Interpolation (one-way data binding)
  2. Property Binding (one-way data binding)
  3. Event Binding (one-way data binding)
  4. Two-Way Binding

7.What is Interpolation?
Interpolation(one-way data binding) allows you to define properties in a component class, and communicate these properties to and from the template.
nterpolation is a technique that allows the user to bind a value to a UI element.Interpolation binds the data one-way. This means that when value of the field bound using interpolation changes, it is updated in the page as well. It cannot change the value of the field. An object of the component class is used as data context for the template of the component. So the value to be bound on the view has to be assigned to a field in the component class.String Interpolation uses template expressions in double curly {{ }} braces to display data from the component, the special syntax {{ }}, also known as moustache syntax. The {{ }} contains JavaScript expression which can be run by Angular and the output will be inserted into the HTML.

          {{value}}  
Component----------->DOM

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'stockMarket';
}

app.component.html

<h1>
    Welcome to {{ title }}!
</h1>

8.What is Property Binding (one-way data binding)?
Property binding is used to bind values to the DOM properties of the HTML elements. Like interpolation, property binding is a one-way binding technique. Property bindings are evaluated on every browser event and any changes made to the objects in the event, are applied to the properties.There are 3 types of Property Binding

app.component.ts

import {Component} from '@angular/core';

@Component({
selector: 'my-app',
template:'
<h1>My First Angular App</h1>
<img [src]="imageUrl">
<img bind-src="imageUrl">'
})

export class AppComponent { 
imageUrl = 'http://codethataint.com/images/sample.jpg';
}
  1. Component property binding works within component element to bind parent component property into child component property. In the diagram the arrows and rectangles in red color are displaying the functionality related to component property binding.
  2. Element property binding works within HTML element and it binds a component property to a DOM property. In the diagram the arrows and rectangle in green color are displaying the functionality related to element property binding.
  3. Directive property binding works within HTML element with angular directives such as NgClass and NgStyle. In directive property binding a component property or any angular expression is bound to angular directive. In the diagram the arrows and rectangles in light blue color are displaying the functionality related to directive property binding.

9.What is Event Binding(one-way data binding)?
Event binding allows us to work in reverse from property binding. We can send information from the view, to the component class. Such information usually involves a click, hover or typing.

import {Component} from '@angular/core';

@Component({
selector: 'my-app',
template:'
<h1>My First Angular App</h1>
<img [src]="imageUrl" (click)='myMethod()'>
<img [src]="imageUrl" on-click='myMethod()'>'
})

myMethod() {
   console.log('Hey!');
}

10.What is Two way Binding?
Two-way data binding really just boils down to event binding and property binding.

<input [(ngModel)]="username">
<p>Hello {{username}}!</p>

The above code turns out to be

<input [value]="username" (input)="username = $event.target.value">
<p>Hello {{username}}!</p>
  1. [value]=”username” – Binds the expression username to the input element’s value property
  2. (input)=”expression” – Is a declarative way of binding an expression to the input element’s input event (yes there’s such event)
  3. username = $event.target.value – The expression that gets executed when the input event is fired
  4. $event – Is an expression exposed in event bindings by Angular, which has the value of the event’s payload

11.What is the Difference between One way Data Binding and Two Way Data Binding

One Way Data Binding Two Way Data Binding
In one-way data binding, the value of the Model is inserted into an HTML (DOM) element and there is no way to update the Model from the View. In two-way binding automatic synchronization of data happens between the Model and the View (whenever the Model changes it will be reflected in the View and vice-versa)
One way data Binding flow would be
(Model($scope) –> View)
Two way data Binding flow would be
(Model($scope) –> View and View –> Model($scope))
Angular 1 and Angular 2:

<h2 ng-bind="student.name"></h2>
<h2 [innerText]="student.name"></h2></pre>
Angular 1 and Angular 2:

<input ngModel="student.name"/>
<input [(ngModel)]="student.name"/></pre>

12.What is Dirty Checking?
Angular checks whether a value has changed in view and not yet synchronized across the app.Our Angular app keeps track of the values of the current watches. Angular walks down the $watch list, and, if the updated value has not changed from the old value, it continues down the list. If the value has changed, the app records the new value and continues down the $watch list.

Angular has a concept of ‘digest cycle’. You can consider it as a loop. In which Angular checks if there are any changes to all the variables watched by all the $scopes(internally $watch() and $apply() functions are getting bonded with each variable defined under $scope).So if you have $scope.myVar defined in your controller (that means this variable ‘myVar’ was marked for being watched) then you are explicitly telling Angular to monitor the changes on ‘myVar’ in each iteration of the loop. So when the value of ‘myVar’ changes, every time $watch() notices and execute $apply() to apply the changes in DOM.

How it Works
First Cycle

  1. Get a watch from list
  2. Check whether item has been changed
  3. If there is no change in item then
  4. No Action taken, move to next item in watch list

Second Cycle

  1. Get a watch from list
  2. Check whether item has been changed
  3. If there is Change in an item
  4. DOM needs to be updated, return to digest loop

14.What is difference between [ngClass] and [class]?
When multiple classes should potentially be added, the NgClass prefer NgClass. NgClass should receive an object with class names as keys and expressions that evaluate to true or false as values

<div [ngClass]="myClasses">
  ...
</div>
myClasses = {
  important: this.isImportant,
  inactive: !this.isActive,
  saved: this.isSaved,
  long: this.name.length > 6
}

If you want to apply a single class to DOM element rather than multiple classes go for [Class]

<div [class]="isGreen?'green':'cyan'">
  ...
</div>

The Other way of applying class is using Singular Version of Class Binding
.In this method either class style would be applied or it would be left without anystyle

<div [class.green]="expression()">
  ...
</div>

The expression is a function which returns true or false value.If true then green style would be applied or no style would be applied

15.What is difference between ngStyle and ngClass?
ng-style is used to interpolate javascript object into style attribute, not css class and And ng-class directive translates your object into class attribute.

[ngStyle]="{'font-size':24}"
[ngClass]="{'text-success':true}"

15.What is Service?

16.What is Provider?

17.What is difference between Factory vs Service vs Provider?

18.Difference between @Inject vs @Injectable

19.What are Reactive Forms

20.How Dependency Injection is done in Angular?

21.Difference between Subscribe, Transform, Map and Filter?

22.Navigator vs Router

23.What is Lazy Loading in Angular

24.What is Difference between Subscribe and Promise?

25.Lifecycle of Angular App

26.How to Create Custom Event in Angular?

27.What are different style Encapsulation in Angular?
ViewEncapsulation.Emulated – This is default, keep styles scoped to the components where they are added even though the styles are all added collected in the head of the page when components are loaded.
ViewEncapsulation.None – Uses global CSS without any encapsulation,When this value is specified, Angular simply adds the unmodified CSS styles to the head section of the HTML document and lets the browser figure out how to apply the styles using the normal CSS precedence rules.
ViewEncapsulation.Native – the browsers native implementation ensures the style scoping.If the browser doesn’t support shadow DOM natively, the web-components polyfills are required to shim the behavior.Check for browser support before enabling it. This is similar to ViewEncapsulation.Emulated but the polyfills are more expensive because of they polyfill lots of browser APIs even when most of them are never used.

The Native and None values should be used with caution. Browser support for the shadow DOM feature is so limited that using the Native option is sensible only if you are using a polyfill library that provides compatibility for other browsers.

The None option adds all the styles defined by components to the head section of the HTML document and lets the browser figure out how to apply them. This has the benefit of working in all browsers, but the results are unpredictable, and there is no isolation between the styles defined by different components.

28.What is View Projection?
Projection is useful when we want the user to decide the input of the Component something like carousel where the inputs could be image, text or page which doesnot have much to do with component logic.
Lets say we have a button text which needs to be decided by the parent component dynamically.In such case we will pass the text of button as parameter to selector of child component like one below

parent.component.ts

<app-parentcounter>Increment Counter From Parent</app-parentcounter>

child.component.ts

<button (click)="increaseCounter()">
  <ng-content></ng-content>
 </button>

ng-content in child tells its a argument which should be passed from parent component. There are two advantages of using ng-content.

  1. The value could be decided at runtime by passing as paremeter
  2. The Button could be used multiple times with different text

Spring Version 4

  1. Spring Framework 4.0 provides support for several Java 8 features
  2. Java EE version 6 or above with the JPA 2.0 and Servlet 3.0 specifications
  3. Groovy Bean Definition DSL- external bean configuration using a Groovy DSL
  4. Core Container Improvements
    1. The @Lazy annotation can now be used on injection points, as well as on @Bean definitions.
    2. The @Description annotation has been introduced for developers using Java-based configuration
    3. Using generics as autowiring qualifiers
    4. Beans can now be ordered when they are autowired into lists and arrays. Both the @Order annotation and Ordered interface are supported.
    5. A generalized model for conditionally filtering beans has been added via the @Conditional annotation

Spring Version 5

  1. Functional programming with Kotlin
  2. Reactive Programming Model.The Reactive Streams API is officially part of Java 9. In Java 8, you will need to include a dependency for the Reactive Streams API specification.
  3. @Nullable and @NotNull annotations will explicitly mark nullable arguments and return values. This enables dealing null values at compile time rather than throwing NullPointerExceptions at runtime.
  4. Spring Framework 5.0 now supports candidate component index as an alternative to classpath scanning..Reading entities from the index rather than scanning the classpath.Loading the component index is cheap. Therefore the startup time with the index remains constant as the number of classes increase. While for a compoent scan the startup time increases significantly.
  5. requires Java 8 as a minimum JDK version.Spring 5 is fully compatible with Java 9.
  6. Servlet 3.1,JMS 2.0,JPA 2.1,Hibernate5,JAX-RS 2.0,Bean Validation 1.1,JUnit 5

Java 7 Features:

  1. Usage of Strings in Switch Statement
  2. Diamond Operator – the diamond operator allows you to write more compact (and readable) code by saving repeated type arguments
  3. Try with Resources
  4. Multiple Exception Handling
  5. Suppressed Exceptions
  6. Allows Binay Literals – Binary Literal are expressing Integer Values in terms of Binary Value by adding the prefix 0b or 0B to the integral value.For more on BinayLiteral click here

Java 8 Features:

  1. Lambda Expressions
  2. Java Stream API for Bulk Data Operations on Collections.
  3. Static and Default method in Functional Interfaces
  4. forEach() method in Iterable interface
  5. Functional Interfaces
  6. Collection API improvements

Java 9 Features:

  1. Factory Methods for Immutable List, Set, Map and Map.Entry
  2. Private methods in Interfaces
  3. Reactive Streams
  4. JShell: the interactive Java REPL

Java 10 Features:

  1. Local-Variable Type Inference
  2. Application Class-Data Sharing
  3. default set of root Certification Authority (CA) certificates in the JDK
  4. Garbage Collector Interface

Java 11 Features:

  1. Java 11 JDK is not free for usage on commercial purpose
  2. No need to compile.typing >>Java in command prompt will compile and run java
  3. Remove the Java EE and CORBA Modules –
  4. Java String Methods – isBlank(), lines(), strip(), stripLeading(), stripTrailing()

Java 17 Features:

  1. LTS support and licenses Java 17 LTS is the latest long-term support release for the Java SE platform
  2. Pattern matching for the switch case
  3. Sealed classes and interfaces. Sealed classes and interfaces restrict which other classes or interfaces may extend or implement them.
    sealed class Human permits Manish, Vartika, Anjali 
    {    
        public void printName() 
        { 
            System.out.println("Default"); 
        } 
    } 
    
    non-sealed class Manish extends Human 
    { 
        public void printName() 
        { 
            System.out.println("Manish Sharma"); 
        } 
    } 
    

Why Lambda Expressions

Now Lets Iterate through the simple ArrayList

Without Lambda Expressions

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);

for (int number : numbers) 
{
    System.out.println(number);
}

We iterate the collection externally, explicitly pulling out and processing the items one by one. Now through Lambda Expressions, we are using an internal iteration the JIT compiler could optimize it processing the items in parallel or in a different order. These optimizations are impossible if we iterate the collection externally as we are used to doing in Java and more in general with the imperative programming.

With Lambda Expressions

numbers.forEach((Integer value) -> System.out.println(value));

(or)

numbers.forEach(value -> System.out.println(value));

Apart from the above reason Lambdas allows us to

  • Enable to treat functionality as a method argument, or code as data.
  • A function that can be created without belonging to any class.
  • A lambda expression can be passed around as if it was an object and executed on demand.
  • It reduces the line of code.
  • It Supports Sequential and Parallel execution by passing behavior in methods with collection stream API
  • Using Stream API and lambda expression we can achieve higher efficiency (parallel execution) in the case of bulk operations on collections

Java 8 Lambda uses JVM Opcode – invokedynamic

The Following code will result in Anonymous class being created when you compile the code.
So if you have 10 anonymous classes then it would be 10 more classes like(ClassName$1.class,ClassName$2.class….ClassName$10.class) in the final jar.

AccountService accountServiceAnonymous = new AccountService(){
    public void createAccount(){
        Account account = new Account();
        save(account);
    }
};

But Java 8 lambda uses invokedynamic to call lambdas thus if you have 10 lambdas it will not result in any anonymous classes thus reducing the final jar size.

AccountService accountServiceLambda = () -> {
    Account account = new Account();
    save(account);
}

Append and Prepend Using Regular Expressions

Append Operation

Find What    : ^[A-Z].*
Replace With : $&~
Search Mode  : Regular Expressions

Input

Apple
Mango
Orange

Output

Apple~
Mango~
Orange~

Prepend Operation

Find What    : ^[A-Z].*
Replace With : ~$&
Search Mode  : Regular Expressions

Input

Apple
Mango
Orange

Output

~Apple
~Mango
~Orange

Replace Empty Lines

Edit -> Line Operations -> Remove Empty Lines

Prepending based on Certain Condition(Lines Starting with Numbers)

Find What    : ^[1-9;].*
Replace With : $&?
Search Mode  : Regular Expressions

Input

1.How are you
Good
2.What is your Name
Mugil

Output

1.How are you?
Good
2.What is your Name?
Mugil
ஓம் பூர் புவஸ்ஸூவ
தத் சவிதுர்வரேண்யம்
பர்கோ தேவஸ்ய தீமஹி
தியோ யோ ந: ப்ரசோதயாத்|

காயத்திரி’ என்னும் ஒலியின் அளவைக் கொண்டு இந்த மந்திரம் இயற்றப்பட்டதால் “காயத்திரி மந்திரம்”.நமது புத்தியை இயங்கச் செய்யும் பரமாத்மாவை நாம் வணங்குவோம் என்பது சுருக்கமான பொருள்.சூரியனுடைய ஒளியை தியானிக்கின்றோம் என்பதால் கண்களை மூடிய நிலையில் சூரிய ஒளியில் நின்று இதைச் சொல்ல வேண்டும் என்பது யதார்த்தமான விஷயம்

Om Bhuur-Bhuvah Svah
Tat-Savitur-Varennyam |
Bhargo Devasya Dhiimahi
Dhiyo Yo Nah Pracodayaat ||

Full long version

Om bhUH, Om bhuvaH, Om svaH, Om mahaH, Om janaH, Om tapaH, Om satyam
Om tat savitur varenyaM, bhargo, devasya dhImahi, dhIyo yo naH, prachodayAt
Om Apo jyotiH rasoamRitaM brahma, bhur bhuvas svar Om.

A Japanese soap factory had a problem: they sometimes shipped empty boxes, without the soap inside. This was due to the way the production line was set up, and people with experience in designing production lines will tell you how difficult it is to have everything happen with timings so precise that every single unit coming out of it is perfect 100% of the time. Customers who come all the way to the supermarket would end up buying someone else’s product.

Understanding how important that was, the CEO of the soap factory got the top people in the company together and they decided to start a new project, in which they would hire an external engineering company to solve their empty boxes problem, as their engineering department was already too stretched to take on any extra effort.

The project followed the usual process: budget and project sponsor allocated, RFP, third-parties selected, and six months (and $8 million) later they had a fantastic solution — on time, on budget, high quality and everyone in the project had a great time. They solved the problem by using some high-tech precision scales that would sound a bell and flash lights whenever a soap box weighing less than it should. The line would stop, and someone had to walk over and yank the defective box out of it, pressing another button when done.

A while later, the CEO decides to have a look at the ROI of the project: amazing results! No empty boxes ever shipped out of the factory after the scales were put in place. Very few customer complaints, and they were gaining market share. “That’s some money well spent!” – he says, before looking closely at the other statistics in the report. It turns out, the number of defects picked up by the new high precision scales was “zero” after three weeks of production use. It should’ve been picking up at least a dozen a day, so maybe there was something wrong with the report. He filed a bug against it, and after some investigation, the engineers come back saying the report was actually correct. The scales really weren’t picking up any defects, because all boxes that got to that point in the conveyor belt were good.

Puzzled, the CEO travels down to the factory, and walks up to the part of the line where the high precision scales were installed. A few feet before it, there was a $ 20 desk fan, blowing the empty boxes out of the belt and into a bin.

“Oh, that — one of the guys put it there ’cause he was tired of walking over every time the bell rang”, says one of the workers.
Moral of the Story: Everyone has a “solution” sometimes requiring an expenditure of “8 million bucks”. It requires an engineer with a high spirit of innovation and ingenuity to come up with a “$ 20 – simple cost-effective solution”!

Below is a code example of CustomClass Loader which Servers use internally for HotCode Swap without restarting the server.When you change the Quote in ServerImpl.java file the file should be reloaded by selecting the RELOAD option while running Client.java

IServer.java

public interface IServer {
	public String getQuote();
}

ServerImpl.java

public class ServerImpl implements IServer{
	@Override
    public String getQuote() {
        return "Its Working Man";
    }
}

Client.java

import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Client {
    static ClassLoader cl;
    static IServer server;

    public static void reloadServer() throws Exception {
        URL[] urls = new URL[]{new URL("file:///D:/java/HotDeplyment/appclasses")};
        System.out.println("Reloaded.....");
        cl = new URLClassLoader(urls);
        server  = (IServer) cl.loadClass("com.mugil.org.ServerImpl").newInstance();
    }

    public static void main(String [] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        reloadServer();
        while (true) {
            System.out.print("Enter QUOTE, RELOAD, or QUIT: ");
            String cmdRead = br.readLine();
            String cmd = cmdRead.toUpperCase();
            if (cmd.equals("QUIT")) {
                return;
            } else if (cmd.equals("QUOTE")) {
                System.out.println( server.getQuote());
            } else if (cmd.equals("RELOAD")) {
            	reloadServer();
            }
        }
    }
}

The Above code is not working as windows is not clearing cached .class files or JAR files. So the alternative is to try with the below Custom Class Loader(MyURLClassLoader) which in turn extends URLClassLoader again.

MyURLClassLoader.java

import java.lang.reflect.Field;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Collection;
import java.util.jar.JarFile;

public class MyURLClassLoader extends URLClassLoader {

	public MyURLClassLoader(URL[] urls, ClassLoader parent) {
	    super(urls, parent);
	}

    /**
     * Closes all open jar files
     */
    public void close() {
        try {
            Class clazz = java.net.URLClassLoader.class;
            Field ucp = clazz.getDeclaredField("ucp");
            ucp.setAccessible(true);
            Object sunMiscURLClassPath = ucp.get(this);
            Field loaders = sunMiscURLClassPath.getClass().getDeclaredField("loaders");
            loaders.setAccessible(true);
            Object collection = loaders.get(sunMiscURLClassPath);
            for (Object sunMiscURLClassPathJarLoader : ((Collection) collection).toArray()) {
                try {
                    Field loader = sunMiscURLClassPathJarLoader.getClass().getDeclaredField("jar");
                    loader.setAccessible(true);
                    Object jarFile = loader.get(sunMiscURLClassPathJarLoader);
                    ((JarFile) jarFile).close();
                } catch (Throwable t) {
                    // if we got this far, this is probably not a JAR loader so skip it
                }
            }
        } catch (Throwable t) {
            // probably not a SUN VM
        }
        return;
    }
}

In the below code the CustomClass Loader is called to load the classes which inturn calls the Super Class loader which is again Loaders from URL Class Loader.Once it is done we have defined a custom close method which closes the JAR files or .class files which is loaded by class loader.

TestClassLoader.java

package com.mugil.org;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException;
import java.net.MalformedURLException;
import java.net.URL;

public class TestClassLoader {
	static ClassLoader cl;
    static IServer server;
	
	public static void main(String[] args) throws Exception {
		
		while(true) {
			try {
			BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
			TestClassLoader obj = new TestClassLoader();
			obj.loadAndInstantiate();			
			System.out.println(server.getQuote());			
			}
			catch (Exception e){
				
			}
			finally {
				try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
			}
		}    
	}
	
	void loadAndInstantiate() throws Exception {
	    MyURLClassLoader cl = null;
	    try {	    	
	        File file = new File("D:\\java\\HotDeplyment\\bin\\Sample.jar");
	        String classToLoad = "com.mugil.org.ServerImpl";
	        URL jarUrl = new URL("file:" + file.getAbsolutePath());
	        cl = new MyURLClassLoader(new URL[] {jarUrl}, getClass().getClassLoader());
	        Class loadedClass = cl.loadClass(classToLoad);
	        Object o = loadedClass.getConstructor().newInstance();
	        server  = (IServer) o;
	        
	    } finally {
	        if(cl != null)
	            cl.close();
	    } 
	}
}

Since the infinite while loop is called indefinitely with the thread sleep interval of every 3 seconds we replace the JAR file in the middle which takes the class from the new JAR file loaded.You need to change the ServerImpl.java file and build the JDK before you want to see the changes

Output

.
.
Its Working Man
Its Working Man
Its Working Man
Its Working Man
Its Working 
Its Working 
Its Working 
.
.

The Above code is not working either

Why Tomcat Server does not needs restart if changes are done in servlet and JSP?
Tomcat is capable of adding/modifying classpath to Web Application classloader at runtime. Tomcat will be having their custom Classloader implementation which allows them to add the classpaths at runtime.a new classloader is created for the Servlet/JSP with Application classloader as parent classloader. And the new classloader will load the modified class again.

It is always best to reload the entire application incase changes are done to servlet. If you were simply to reload one class, in isolation, you might break dependencies or miss some initialization steps. Therefore, it’s much safer to reload the entire application clicking deploy option in tomcat server.JSPs on the other hand, when properly coded, shouldn’t have anything in them by markup text. So reloading a single JSP, without reloading the entire app, should be safe. By default, tomcat is started in development mode, which means JSP-derived servlets recompiled when a change is detected.

In the web.xml you need to set the below config

<servlet>
   .
   .
    <!-- Add the following init-param -->
    <init-param>
        <param-name>development</param-name>
        <param-value>true</param-value>
    </init-param>
   .
   .
   .
</servlet>

In the Server.xml reloadable should be set to true

<Context path="/simple" docBase="webapps/simple"  debug="0" reloadable="true" ></Context>

More on how CustomClass loader works for Hot Deployment here

Simple Factory and Static Factory are not design patterns rather coding style. However factory pattern could be implemented by using any one of the coding style but they wont honor Open Closed Principle.

As per Open Closed Principle, Code should be open to extension and Closed to Changes. In both the above coding style we have to change either the if else or switch case if new implementation of abstract class is introduces.

Factory Pattern is a design pattern in object-oriented programming that lets subclasses decide which class to instantiate when creating an object

Now Factory pattern honors Open Closed Principle and does not need change to factory method

Factory Pattern vs Abstract Factory Pattern
One difference between the two is that with the Abstract Factory pattern, a class delegates the responsibility of object instantiation to another object via composition whereas the Factory Method pattern uses inheritance and relies on a subclass to handle the desired object instantiation