1. AnnotationSessionFactoryBean is used to create session factory if hibernate pojo are annotated
  2. AnnotationSessionFactoryBean is a factory that produces SessionFactory automatically.This is used when you create a sessionFactory object of Hibernate from Spring
     <bean id="sessionFactory" class="org.springframework.orm.hibernate3.
    annotation.AnnotationSessionFactoryBean">
       <property name="dataSource" ref="dataSource"/>
       <property name="annotatedClasses">
         <list>
           <value>test.package.Foo</value>
           <value>test.package.Bar</value>
         </list>
       </property>
     </bean>
    
  3. This session factory is assigned to all dao beans and hibernate template to do database transaction.
    <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.
    HibernateTemplate">
    	<property name="sessionFactory">
    	  <ref bean="sessionFactory" />
    	</property>
    </bean>
    <bean id="pageDao" class="com.concretepage.dao.PageDaoImpl">
        <property name="hibernateTemplate">
    	  <ref bean="hibernateTemplate" />
    	</property>
    </bean>
    

Single Dispatch

SingleDispatch.java

public class SingleDispatch 
{
	public void print()
	{
	  System.out.println("Single Dispatch");	
	}

 	public static void main(String[] args) 
	{
	  SingleDispatch objSingleDis = new SingleDispatch();
 	  objSingleDis.print();	
        }
}

Dynamic Dispatch
Dynamic dispatch is the same thing which we do in strategy pattern.The actual method which is called is known at the runtime

Account.java

public interface Account 
{
  public void calculateinterest();
}

SavingsAccount.java

public class SavingsAccount implements Account
{
	@Override
	public void calculateinterest() {
		System.out.println("Intrest is 8%");
	}
}

LoanAccount.java

public class LoanAccount implements Account
{
	@Override
	public void calculateinterest() {
		System.out.println("Intrest is 11.5%");
	}

}

CalculateInterest.java

public class CalculateInterest 
{
	public static void main(String[] args) 
	{
		Account objSavAcc = new SavingsAccount();
		Account objLoanAcc = new LoanAccount();
		
		objSavAcc.calculateinterest();
		objLoanAcc.calculateinterest();
	}
}

What is Multiple Dispatch
Account.java

public class Account 
{	
	public void calculateinterest() {
		System.out.println("Intrest is 11.5%");
	}
	
	public void calculateinterest(int prePayment) {
		System.out.println("Intrest is 11.5% with prePayment");
	}
	
	public void calculateinterest(int prePayment, boolean floatingIntrest) {
		System.out.println("Intrest is 11.5% with floatingIntrest");
	}
}

Now in the above example we have a Account class where the functions are overloaded.Now when the code gets executed then the methods are chosen based on the parameters passed.

public class CalculateInterest 
{
	public static void main(String[] args) 
	{
		Account objAcc = new Account();		
		
		objAcc.calculateinterest();
		objAcc.calculateinterest(23);
		objAcc.calculateinterest(23, true);
	}
}

Output

Intrest is 11.5%
Intrest is 11.5% with prePayment
Intrest is 11.5% with floatingIntrest

Now Java doesn’t supports multiple dispatch as above.The above code is an example of overloading.

Overloading vs Multiple Dispatch
The Difference between overloading and Multiple Dispatch is when the method to be called is decided at compile time then it is Overloading, if the method is decided at runtime then it is multiple dispatch

What is Double Dispatching?
In Double Dispatching the choosing of the method happens dynamically twice.In the below example the method is chosen similar to strategy pattern first time during call of viewReport method and again during choosing which printReport method to be called based on the class type its is called similar to

Staff.java

public interface Staff 
{
	void viewReport(Report objReport);
}

Teacher.java

public class Teacher implements Staff
{
	@Override
	public void viewReport(Report objReport) 
	{
                System.out.println("View Report of Teacher");
		objReport.printReport(this);
	}
}

Principal.java

public class Principal implements Staff
{
	@Override
	public void viewReport(Report objReport) 
	{		
                System.out.println("View Report of Principal");
		objReport.printReport(this);		
	}
}

Report.java

public class Report 
{
	public void printReport(Teacher objTeacher)
	{
		System.out.println("Can print report of her class"); 
	}
	
	public void printReport(Principal objPrincipal)
	{
		System.out.println("Can print report of all the class");
	}
}

ShowReport.java

public class ShowReport 
{
	public static void main(String[] args) 
	{
		Principal objPrincipal = new Principal();
		Teacher objTeacher   = new Teacher();
		objPrincipal.viewReport(new Report());
		objTeacher.viewReport(new Report());
	}
}

Output.java

View Report of Principal
Can print report of all the class
View Report of Teacher
Can print report of her class

In statically typed languages, including Java, the biggest difference between dispatch and overloading is that overloading is based on the static type of parameters (i.e. the choice of which method is actually called is decided at compile-time), while dispatch is based on the dynamic types (i.e. the decision is made at runtime). (Such languages usually don’t support multiple dispatch.)

Another Example of Double Dispatch is Serialization.In Serialization the class which is Serializable calls the methods with itself as an argument.In the below example the writeObject method dispatches the call back to the ObjectOutputStream thus making this a double dispatch. ObjectOutputStream delegates back MuxPrinter the responsibility of writing its state onto stream. By Doing this ObjectOutputStream has decoupled itself from our object objMuxPrt.

public class MuxPrinter implements Serializable
{

}

MuxPrinter objMuxPrt = new MuxPrinter();
ObjectOutputStream oos = new ObjectOutputStream();
oos.writeObject(objMuxPrt);  

Array Implementation
CustomArray.java

package com.mugil.alg;

public class CustomArray {
	private int[] arrNum = new int[50];
	private int arrSize = 10;
	
	public static void main(String[] args) {
		CustomArray objCustomArray = new CustomArray();
		System.out.println("---------------");
		System.out.println("Array Initialized");
		objCustomArray.initializeArray();
		objCustomArray.printArray();
		
		System.out.println("---------------");
		System.out.println("Search for No(Index) - " + objCustomArray.getNumIndex(8));
		
		System.out.println("---------------");
		System.out.println("Delete Called");
		objCustomArray.deleteArrayByIndex(5);		
		objCustomArray.printArray();
		
		
		System.out.println("---------------");
		System.out.println("Insert Called");
		objCustomArray.insertArray(20);		
		objCustomArray.printArray();
		
		
	}
	
	public void initializeArray()
	{	
		for (int i = 0; i < arrSize; i++) {
			arrNum[i]  = (int)(Math.random()*10); 
		}
	}
	
	public void printArray()
	{
		
		System.out.print("Array - ");
		for (int i = 0; i < getArraySize(); i++) {
			System.out.print(arrNum[i]);
			System.out.print(" ");
		}		
		System.out.println();
	}
	
	
	//Linear Search
	//Use this if you want to find all the
	//all the places where the element Occurs
	public String getNumIndex(int pNum)
	{
		String NumPOS = "";
		
		for (int i = 0; i < getArraySize(); i++) {
			if(pNum == arrNum[i])
			{
				NumPOS +=  i + " ";
			}
		}
		
		if(NumPOS == "")
		 NumPOS = "None";
		
		return NumPOS;
	}
	
	
	public int getArraySize()
	{
		return arrSize;
	}
	
	public void deleteArrayByIndex(int pPOS)
	{
		
		for (int i = pPOS; i < getArraySize(); i++) {
				arrNum[i] = arrNum[i+1]; 
		}
		
		arrSize--;
	}
	
	public void insertArray(int pNum)
	{
		arrNum[arrSize] = pNum;		
		arrSize++;	
	}
}

Why LinkedList is Faster than ArrayList?
Adding Element in middle of ArrayList requires reshuffling of other elements.Whereas in Linked list only two nodes(Nodes between which the element is added) needs to be changed.

Types of LinkedList?

  1. singly linked list
  2. doubly-linked list
  3. Circular linked list

singly linked list doubly-linked list
Pros:Simple in implementation, requires relatively lesser memory for storage, assuming you need to delete/insert (at) next node – deletion/insertion is faster. Can be iterated in forward as well as reverse direction. In case of needing to delete previous node, there is no need to traverse from head node, as the node to be deleted can be found from ‘.previous’ pointer.
Cons:Cannot be iterated in reverse, need to maintain a handle to the head node of the list else, the list will be lost in memory. If you’re deleting previous node or inserting at previous node, you will need to traverse list from head to previous node to be able to carry out those operations – O(N) time Relatively complex to implement, requires more memory for storage (1 ‘.previous’ pointer per node). Insertions and deletions are relatively more time consuming (assigning/reassigning ‘.previous’ pointer for neighbor nodes)

Time complexity of a linked list

Operation Metrics
Indexing O(n)
Inserting / Deleting at end O(1) or O(n)
Inserting / Deleting in middle O(1) with iterator O(n) with out

The time complexity for the Inserting at the end depends if you have the location of the last node, if you do, it would be O(1) other wise you will have to search through the linked list and the time complexity would jump to O(n).

Two Dimensional Arrays (Array of Arrays)

 //Seating Arrangement for 20 Seats
 int arrSeating[][] = new int[4][5];

 //No of Items Produced in Hr By Days in Month
 int arrProdHrByDaysInMonth[][] = new int[30][24];

Two Dimensional Arrays(Array of Arrays of Arrays)

 //No of Items Produced in Hr By Days in Month by Month
 int arrProdHrByDaysInMonth[][][] = new int[12][30][24];

Jagged Arrays
array of arrays such that member arrays can be of different sizes

Looping through ArrayList

         	//Iterate over Collection
		for (Iterator iterator = arrNames.iterator(); iterator.hasNext();) {
			String object = (String) iterator.next();
			System.out.println(object);
		}			
		
		//Iterate over array or Collection
		for (String string : arrNames) {
			System.out.println(string);
		}		
		
		//Iterate over array 
		for (int i = 0; i < arrNames.size(); i++) {
			System.out.println(arrNames.get(i));
		}
		
		//Iterate over array using Temporary Variable
		for (int i = 0; i < arrNames.size(); i++) {
			String string = arrNames.get(i);
			System.out.println(string);
		}

Which one of the Above method is Faster?
All the methods are of same speed since the Traditional for loop uses Iterator inside.The performance difference is noted when there is change in data structure while doing random access like linkedlist is slower than arraylist when you use a traditional for loop since to traverse a 6th element in list it should start from all again

When there is a sorted Array and you should do a search in the sorted array then using BinarySearch is faster than Linear Search

The whole concept of serialization works on versioning. If you save a class object using one version of the class but attempt to deserialize using a newer or different version of the class deserialization might fail.

When you class structure can change in between you serialize the instance and go again to de-serialize it. Changed structure of class will cause JVM to give exception while de-serializing process.This problem can be solved only by adding a unique serial version id to class. It will prevent the compiler to throw the exception by telling that both classes are same, and will load the available instance variables only.

The serialization runtime associates with each serializable class a version number, called a serialVersionUID, which is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization. If the receiver has loaded a class for the object that has a different serialVersionUID than that of the corresponding sender’s class, then deserialization will result in an InvalidClassException. A serializable class can declare its own serialVersionUID explicitly by declaring a field named “serialVersionUID” that must be static, final, and of type long

 static final long serialVersionUID = 69L;

If a serializable class does not explicitly declare a serialVersionUID, then the serialization runtime will calculate a default serialVersionUID value for that class based on various aspects of the class, as described in the Java(TM) Object Serialization Specification

System is a class, that has a public static field out. So it’s more like

class System 
{
    public static PrintStream out;
}

class PrintStream
{
    public void println ...
}

This is a slight oversimplification, as the PrintStream class is actually in the java.io package, but it’s good enough to show the relationship of stuff.

  1. Internally an ArrayList uses an Object[] Array.
           private transient Object[] elementData;
         
  2. As you add items to an ArrayList, the list checks to see if the backing array has room left. If there is room, the new item is just added at the next empty space. If there is not room, a new, larger, array is created, and the old array is copied into the new one.
  3. When we actually create an arrayList following piece of code is executed –
      this.elementData=new Object[initial capacity];
         
  4. ArrayList can be created in two ways-

    List<String> myList=new ArrayList<String>();
     
  5. When we create an ArrayList in this way, default constructor is invoked and will internally create an array of Object with default size, which is 10.

    List<String> myList=new ArrayList<String>(5);
     

    When we create an ArrayList in this way, constructor with an integer argument is invoked and will internally create an array of Object with the size, specified in the constructor argument, which happens to be 5 in this case.

  6. Inside add() method Check is made, before adding element into the array it will check what is the current size of filled elements and what is the maximum size of the array. If size of filled elements is greater than maximum size of the array then size of the array must be increased. But we know that the size of the array cannot be increased dynamically.

    So what happens internally is a new Array is created with size 1.5*currentSize and the data from old Array is copied into this new Array.

Internally an ArrayList uses an Object[].

Capacity vs Size

The capacity is how many elements the list can potentially accommodate without reallocating its internal structures.

The size is the number of elements in the list

If you allocate a new array with arr = new Employee[100], the size of that array (arr.length) is going to be 100. It has 100 elements. All the elements are initially null (as this is an array of object references), but still, there are 100 elements.

If you do something like list = new ArrayList (100), and try to check list.size(), you’ll get 0. There are no elements in the list.

Internally, it’s true that the ArrayList allocates enough place to put 100 items before it needs to extend its capacity, but that’s an internal implementation detail, and the list presents its content to you as “no items stored”. Only if you actually do list.add(something), you’ll have items in the list.

So although the list allocates storage in advance, the API with which it communicates with the program tells you there are no items in it. The null items in its internal array are not available to you – you cannot retrieve them or change them.

An ArrayList is just one way to represent an abstract list, and the capacity of an ArrayList is an implementation detail of how the system implements the logical list.

An ArrayList stores the elements of a list by using an actual array “under the covers.” The actual realization of the array in computer memory has a certain size when it is allocated; this size is the ArrayList’s capacity. The ArrayList emulates a variable-sized list by storing the logical length of the list in addition to the fixed-length array. Thus if you have an ArrayList with a capacity 10 which contains 4 logical elements, the ArrayList can be represented as a length and an array

(4) | e1 | e2 | e3 | e4 | __ | __ | __| __ | __ | __ |

where the (4) is the logical length of the list and ‘__’ represent data that is ignored because it is not part of the logical list. If you attempt to access the 5th element of this ArrayList, it will throw an exception because it knows that the fifth element has not been initialized. If we then append an extra element e5 to the list, the ArrayList becomes

(5) | e1 | e2 | e3 | e4 | e5 | __ | __ | __ | __ | __ |

Note that the capacity has not changed, while the logical length has, because the underlying array is still able to handle all the data in the logical list.

If you manage to add more than ten elements to this list, the ArrayList will not break. The ArrayList is an abstraction meant to be compatible with all array operations. Rather, the ArrayList changes its capacity when its logical length exceeds its original capacity. If we were to add the elements (a1, a2, …, a7) to the above list, the resulting ArrayList might look like

(12) | e1 | e2 | e3 | e4 | e5 | a1 | a2 | a3 | a4 | a5 | a6 | a7 | __ | __ | __ | __ | __ | __ | __ | __ |

with a capacity of 20.

Once you have created an ArrayList, you can ignore the capacity in all programming that follows; the logic is unaffected. However, the performance of the system under certain kinds of operations can be affected. Increasing the capacity, for instance, might well involved allocating a larger array, copying the first array into the second and then performing the operations. This can be quite slow compared to, e.g. the same operation on a linked list. Thus it is sensible to choose the capacity of an ArrayList to be bigger than, or at least comparable to, the actual number of elements expected in the real runtime environment.

Is there a Way to Create ArrayList of Fixed size in Java

 List<String> fixedSizeList = Arrays.asList(new String[100]);

You cannot insert new Strings to the fixedSizeList (it already has 100 elements). You can only set its values like this:

fixedSizeList.set(7, "new value");

What would be the Output of the Following Code

List<Employee> employees = new ArrayList<>(100);
int size = employes.size();

size will be 0 while the initial capacity is 100.

Yes. An interface can extend multiple interfaces, as shown here:

interface Maininterface extends inter1, inter2, inter3{  
  // methods
}

A single class can also implement multiple interfaces

interface A
{
    void test();
}

interface B 
{
    void test();
}

class C implements A, B
{
    @Override
    public void test() {

    }     
}

Single implementation works for both.