31.How will you make a HashMap of Unique Objects(Object with same Attributes should not be added more than once) or Mutable class does not allow override of HashCode and Equals?

If two objects are same then they must return same value in hashcode() and equals() method whenever invoked.It is not necessary that two different object must have different hashcode values. it might be possible that they share common hash bucket.

JVM assigns unique hashcode value to each object when they are created in memory and if developers don’t override the hashcode method then there is no way the two object returns same hashcode value.

Without HashCode

package com.mugil.org.qs;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class Question31 
{
	public static void main(String[] args) 
	{
		Map hmStudents = new HashMap();
		
		Student objStudent1 = new Student();
		objStudent1.setName("Abdul");
		objStudent1.setAge(23);
		
		hmStudents.put(objStudent1, "Playboy");
		
		Student objStudent2 = new Student();
		objStudent2.setName("Joseph");
		objStudent2.setAge(23);
		
		hmStudents.put(objStudent2, "Upcoming Playboy");
		
		
		Student objStudent4 = new Student();
		objStudent4.setName("Joseph");
		objStudent4.setAge(23);
		
		hmStudents.put(objStudent4, "Playboy");
		
		
		Iterator it = hmStudents.entrySet().iterator();
		
	    while (it.hasNext()) 
	    {
	        Map.Entry pair = (Map.Entry)it.next();
	        System.out.println(((Student)pair.getKey()).getName() + " = " + pair.getValue());
	        
	    }
	}
}

class Student
{
	String Name;
	Integer Age;
	
	public String getName() {
		return Name;
	}
	public void setName(String name) {
		Name = name;
	}
	public Integer getAge() {
		return Age;
	}
	public void setAge(Integer age) {
		Age = age;
	}	
}

Output
Joseph = Playboy
Abdul = Playboy
Joseph = Upcoming Playboy

With HashCode Object with same value gets replaced

class Student
{
	String Name;
	Integer Age;
	
	public String getName() {
		return Name;
	}
	public void setName(String name) {
		Name = name;
	}
	public Integer getAge() {
		return Age;
	}
	public void setAge(Integer age) {
		Age = age;
	}
	
	
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((Age == null) ? 0 : Age.hashCode());
		result = prime * result + ((Name == null) ? 0 : Name.hashCode());
		return result;
	}
	
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Student other = (Student) obj;
		if (Age == null) {
			if (other.Age != null)
				return false;
		} else if (!Age.equals(other.Age))
			return false;
		if (Name == null) {
			if (other.Name != null)
				return false;
		} else if (!Name.equals(other.Name))
			return false;
		return true;
	}	
}

Output
Joseph = Playboy
Abdul = Playboy

32.Why List<Parent> is not same as List<Child> ?
Let’s say we allow a List to be a subtype of List.Consider the following example:We allow a List to be a subtype of List. Consider the following example:

   List<String> stringList = new ArrayList<String>;
   List<Object> objectList = stringList; //this does compile only if List<String> where subtypes of List<Object>
   objectList.add(new Object());
   String s = stringList.get(0);// attempt to assign an Object to a String and the Java compiler has to prevent these cases.

In the above code you can see adding Parent and Child class within the same List may result in scenario where you wont be
able to guess whether its a Parent or Child.

If Foo is a subtype (subclass or subinterface) of Bar, and G is some generic type declaration, it is not the case that G is a subtype of G.

It’s useful to make comparison to arrays.
List is not subclass of List But Dog[] is subclass of Animal[]
Arrays are reifiable and covariant. Reifiable means their type information is fully available at runtime. Therefore arrays provide runtime type safety but not compile-time type
safety.

   // All compiles but throws ArrayStoreException at runtime at last line
    Dog[] dogs = new Dog[10];
    Animal[] animals = dogs; // compiles
    animals[0] = new Cat(); // throws ArrayStoreException at runtime

It’s vice versa for generics:Generics are erased and invariant. Therefore generics can’t provide runtime type safety, but they provide compile-time type safety.
In the code below if generics were covariant it will be possible to make heap pollution at line 3.

    List<Dog> dogs = new ArrayList<>();
    List<Animal> animals = dogs; // compile-time error, otherwise heap pollution
    animals.add(new Cat());

 

33.What is the difference between instanceof and getclass()
instanceof tests whether the object reference on the left-hand side (LHS) is an instance of the type on the right-hand side (RHS) or some subtype.
getClass() == … tests whether the types are identical.

34.What are different reference types in java

  1. Strong References : We can create an object and then assign it to a reference. Note that if the object has a strong reference, this object is never be garbage collected.
    MyClass obj = new MyClass ();  
    
  2. Weak References :This type of reference is used in WeakHashMap to reference the entry objects.If JVM detects an object with only weak references (i.e. no strong or soft references linked to any object object), this object will be marked for garbage collection.
  3. Soft References :even if the object is free for garbage collection then also its not garbage collected, until JVM is in need of memory badly.The objects gets cleared from the memory when JVM runs out of memory
  4. Phantom References :A special reference which says that the object was already finalized, and the garbage collector is ready to reclaim its memory.Before removing them from the memory, JVM puts them in a queue called ‘reference queue’ . They are put in a reference queue after calling finalize() method on them

35.Difference betwen connection timeout and socket timeout?
A connection timeout is the maximum amount of time that the program is willing to wait to setup a connection to another process.A connection timeout occurs only upon starting the TCP connection. This usually happens if the remote machine does not answer. This means that the server has been shut down, you used the wrong IP/DNS name or the network connection to the server is down.
A socket timeout is the timeout when waiting for individual packets. A socket timeout is dedicated to monitor the continuous incoming data flow. If the data flow is interrupted for the specified timeout the connection is regarded as stalled/broken. if you have a socket timeout of 1 second, and a response comprised of 3 IP packets, where each response packet takes 0.9 seconds to arrive, for a total response time of 2.7 seconds, then there will be no timeout.

36.Why we need to do serialization when the same can be done by using file streams?
Serialized objects maintain state in space, they can be transferred over the network, file system, etc
you could save your data to a text file on the computer, then have a program that reads that info, and based on the file, you could have your
program respond differently. if you use Serializable then you can easily load your Object graph to memory. For example you have a Student class
which have a Deportment. So if you serialize your Student then the Department also be saved.

Serializing on the other hand, puts things directly into computer language. It’s like you’re telling a Spanish computer something in Spanish, rather than telling it something in French, forcing it to learn French, then save things into its native Spanish by translating everything.
Serialization is also faster, because in Java, objects are handled on the heap, and take much longer than if they were represented as primitives on the stack.

37.What is Functional Interface?
Functional interfaces have a single functionality to exhibit. For example, a Comparable interface with a single method compareTo is used for comparison purpose
Functional Interface is an interface which has one and only one abstract method. Apart from abstract method it can have any number of default and static methods which have an implementation and are not abstract and overriden method from Object.These interfaces are also called Single Abstract Method Interfaces. Few Functional Interfaces are Comparable, Runnable etc.More details here

38.What are marker interfaces?
Marker Interface in java is an interface with no fields or methods within it. It is used to convey to the JVM that the class implementing an interface of this category will have some special behavior.

Few Marker interface are as below

  1. Searilizable interface
  2. Cloneable interface
  3. Remote interface used for RMI
  4. ThreadSafe interface

Marker interface in Java e.g. Serializable, Clonnable, and Remote are used to indicate something to compiler or JVM that the class implementing any of these would have some special behavior. Hence, if the JVM sees a Class is implementing the Serializable interface it does some special operation on it and writes the state of the object into object stream. This object stream is then available to be read by another JVM. Similarly, if JVM finds that a class is implementing Cloneable interface, it performs some special operation in order to support cloning.

39.What is the Difference between String Literal and String Object?How it is stored in memory?

String s1 = "abc"; 
String s2 = "123";
String obj1 = new String("abc");
String obj2 = new String("def");
String obj3 = new String("456);

JVM allocates some memory specially meant for string literals. This part of the heap memory is called string constants pool.String literals s1 and s2 will go to string constant pool, objects obj1, obj2, obj3 to the heap. All of them, will be referenced from the Stack.”abc” will appear in heap and in string constant pool. Why is String s1 = “abc” and String obj1 = new String(“abc”) will be created this way? It’s because String obj1 = new String(“abc”) explicitly creates a new and referentially distinct instance of a String object and String s1 = “abc” may reuse an instance from the string constant pool if one is available.

40.What are ways of object creation in Java?

  1. Using new Keyword

    Employee objEmp = new Employee(); 
    
  2. Using newInstance

    Class cls = Class.forName("Employee"); 
    Employee obj =  (Employee) cls.newInstance(); 
    
  3. Using clone() method

    public class Employee implements Cloneable 
    { 
        @Override
        protected Object clone() throws CloneNotSupportedException 
        { 
            return super.clone(); 
        }     
      
        public static void main(String[] args) 
        { 
            Employee obj1 = new Employee(); 
            try
            { 
                Employee obj2 = (Employee) obj1.clone();       
            } 
            catch (CloneNotSupportedException e) 
            { 
                e.printStackTrace(); 
            } 
        } 
    } 
    
  4. Using deserialization
    Refere Here
  5. Using newInstance() method of Constructor class(Reflection)

    Constructor<Employee> constructor = Employee.class.getDeclaredConstructor();
    Employeer = constructor.newInstance();
    r.setName("GeeksForGeeks");
    System.out.println(r.name);
    

41.When overriding a method, why can I increase access but not decrease it?
It’s a fundamental principle in OOP: the child class is a fully-fledged instance of the parent class, and must, therefore, present at least the same interface as the parent class. Making protected/public things less visible would violate this idea; you could make child classes unusable as instances of the parent class. Lets take the below code

class Person{
 public void display(){
      //some operation
    }
 }

class Employee extends Person{
   private void display(){
       //some operation
   }
 }

Calling Overridden method

Person p=new Employee();

Here p is the object reference with type Person(superclass) when we are calling p.display(). As the access modifier is more restrictive, the object reference p cannot access child object of type Employee

42.What if the same method is there in Abstract class and in interface?

public interface Intr {
    public void add();
}

public abstract class Abs {
    public void add() {
        System.out.println("Abs.m1()");
    }
    // public abstract void m1();
}

public class A extends Abs implements Intr {

    @Override
    public void add() {
        // which method am I overriding, well it is Abs.m1() but why?
        // if method implemented is Abs.add(), then why I am not getting error for Intr.add() not implemented.
    }
}

In the above implementation at the sametime, we are fulfilling the abstract class requirements and the interface requirements.it might make sense to move the implements Intr up to the abstract class definition. Though the abstract class method would be overridden first.

43.When you add a date Field to Immutable class despite it being declared as final it is modifiable as in below code, How will you create an immutable class with date field in it?

date = getDate();
date.setYear(2010); // allowed!

In the below code we have used defensive copying by sending the values of the date field and sending a copy of the date for accessing its value.

Solution

public Date getDate() {
    // Not correct.
    return this.date; // This will make your class mutable.

    // Instead use, 
    return new Date(this.date.getTime()); // This will make sure your date field cannot be changed.
}

44.What is Defensive Copying?
Lets take the code as below

class Point {
  final int x;
  final int y;

  Point(int x, int y) {
    this.x = x;
    this.y = y;
  }

  Point(Point p) {
    this(p.x, p.y);
  }
}
  1. In the above code note how the constructor Point(Point p) takes a Point and makes a copy of it – that’s a copy constructor.
  2. This is a defensive copy because the original Point is protected from change by taking a copy of it
// A simple point.
Point p1 = new Point(3,42);
// A new point at the same place as p1 but a completely different object.
Point p2 = new Point(p1);

Using the above code you never have two references to the same object by accident

Q1:What would be the output for the following Program?

Output:

True
False
False

Question1.java

public class Question1 
{
	public static void main(String[] args) 
	{
		String Name1 = "Mugil";
		String Name2 = "Mugil";
		String Name3 = new String("Mugil");
		String Name4 = new String("Mugil");
		
		System.out.println(Name1 == Name2);
		System.out.println(Name2 == Name3);
		System.out.println(Name3 == Name4);
	}
}

Output

true
false
false

Q2: there is a arraylist with Employee objects in it. The list contains duplicate Employee objects, Now i need to remove the duplicate objects from the list.how do you do that?
Override equals and hashcode and use equals method to compare two objects.If the class is coming from jar or uneditable use extends and override the hashcode and equals method
Question2.java

import java.util.ArrayList;
import java.util.List;

public class Question2 
{
	public static void main(String[] args) 
	{
		List<Employee> arrEmp = new ArrayList<Employee>();
		
		Employee objEmp1 = new Employee();
		objEmp1.setName("Mugil");
		objEmp1.setEmpId(101);
		
		Employee objEmp2 = new Employee();
		objEmp2.setName("Mugil");
		objEmp2.setEmpId(101);
		
		Employee objEmp3 = new Employee();
		objEmp3.setName("mugil");
		objEmp3.setEmpId(101);
		
		
		System.out.println("Both Object are Equal - " + objEmp1.equals(objEmp2));
		System.out.println("Both Object are Equal - " + objEmp3.equals(objEmp2));
		
	}
}

Question2.java

class Employee
{
	String Name;
	int EmpId;
	
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + EmpId;
		result = prime * result + ((Name == null) ? 0 : Name.hashCode());
		return result;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Employee other = (Employee) obj;
		if (EmpId != other.EmpId)
			return false;
		if (Name == null) {
			if (other.Name != null)
				return false;
		} else if (!Name.equals(other.Name))
			return false;
		return true;
	}
	public String getName() {
		return Name;
	}
	public void setName(String name) {
		Name = name;
	}
	public int getEmpId() {
		return EmpId;
	}
	public void setEmpId(int empId) {
		EmpId = empId;
	}
}

`

Output

Both Object are Equal - true
Both Object are Equal - false

Q3:What will happen if you call return or System.exit in try or catch block?Will finally block execute?
Scenario 1: Positive Scenario with no System.exit()

package com.mugil.org.qs;

public class Question3 
{
	public static void main(String[] args) 
	{	
		System.out.println(getName());		
	}
	
	public static String getName() 
	{
		try {
			return "Mugil";
		} catch (Exception e) {
			throw new NullPointerException("return value is null");
		}finally {
			System.out.println("Finally Block Executed");
		}
	}
}

Output

Finally Block Executed
Mugil

Scenario 2 :System.exit() in try block before exception

package com.mugil.org.qs;

public class Question3 
{
	public static void main(String[] args) 
	{	
		System.out.println(getName());		
	}
	
	public static String getName() 
	{
		try {
			System.exit(1);
			throw new NullPointerException("return value is null");
		} catch (Exception e) {
			throw new NullPointerException("return value is null");
		}finally {
			System.out.println("Finally Block Executed");
		}
	}
}

If the System.exit(1) is used after throw new NullPointerException then it compiler will complain for unreachable code.
Finally will not get executed
Output(Blank Screen)


Scenario 3 :System.exit() in catch block before exception

package com.mugil.org.qs;

public class Question3 
{
	public static void main(String[] args) 
	{	
		System.out.println(getName());		
	}
	
	public static String getName() 
	{
		try {			
			throw new NullPointerException("return value is null");
		} catch (Exception e) {
			System.exit(1);
			throw new NullPointerException("return value is null");
		}finally {
			System.out.println("Finally Block Executed");
		}
	}
}

Output(Blank Screen)


The only times finally won’t be called are

  1. If you invoke System.exit();
  2. If the JVM crashes first;
  3. If there is an infinite loop
  4. If the host system dies; e.g. power failure, hardware error

Q3a:What are parameters of System.exit?

  • Zero(0) – when execution went fine – Everything Okay
  • Positive(1-127) – Something I expected could potentially go wrong went wrong anticipated exception – (bad command-line, can’t find file, could not connect to server)
  • Negative(values greater than 128) – Something I didn’t expect at all went wrong (system error – unanticipated exception – externally forced termination e.g. kill -9)

Q4:What is the difference between Iterator and ListIterator
When you loop through list use listiterator since it is faster then iterator. It can traverse in both directions. Iterator can be used over collections whereas list iterator call be used only for list

When you are simple moving through List but you are not modifying the List object foreach is more efficient.In case you want to perform operations on each element of list individually taking out the element in such case use Iterator.

ListIterator Iterator
ListIterator to traverse List only Iterator is used for traversing List and Set both.
ListIterator, we can traverse a List in both the directions (forward and Backward). traverse in only forward direction using Iterator
We cannot obtain indexes while using Iterator We can obtain indexes at any point of time while traversing a list using ListIterator. The methods nextIndex() and previousIndex() are used for this purpose.
We can add element at any point of time while traversing a list using ListIterator. We cannot add element to collection while traversing it using Iterator, it throws ConcurrentModificationException when you try to do it.
By using set(E e) method of ListIterator we can replace the last element returned by next() or previous() methods. We cannot replace the existing element value when using Iterator.
Methods of ListIterator:

add(E e)
hasNext()
hasPrevious()
next()
nextIndex()
previous()
previousIndex()
remove()
set(E e)

Methods of Iterator:

hasNext()
next()
remove()

Q5:What would be the output of Following Program?

package com.mugil.org.qs;

public class Question4 
{
	public static void main(String[] args) 
	{
		my m = new my(){};
		m.myMethod();
		System.out.println(m.getClass().getSuperclass());
	}
}

abstract class my
{
	public void myMethod()
	{
		System.out.println("Abstract");
	}
}

Ans:The reason for this any anonymous class which has the same name as abstract class would be child class of the abstract class

Q6:Why we are unable to add primitives as generic type?

//Allowed
List<Integer> arrAges = new ArrayList<Integer>();

//Not allowed
List<int> arrAges = new ArrayList<int>();

Ans:This is to maintain backwards compatibility with previous JVM runtimes in the sense it could be referred by parent class instance Object

Q7: What would be the Output of following program

package com.mugil.org.qs;

public class Question7 
{
	public static void main(String[] args) {
		System.out.println(getSomeNumber());
	}
	
	public static int getSomeNumber()
	{
		try{
			throw new RuntimeException();			
		}finally{
			return 1;
		}
	}
}

Output

1

Ans: Finally will run at any cause other than system.exit() call.

Q7a: What would be the Output of following program

package com.mugil.org.qs;

public class Question7a 
{
	public static void main(String[] args) 
	{
		if(isQAAssured())
		  System.out.println("QA Checked");
		else
		  System.out.println("QA is not Checked");
	}
	
	public static boolean isQAAssured()
	{
		try 
		{
			return true;
		}
		finally 
		{
			return false;
		}
	}
}

Output

QA is not Checked

Q7a: What would be the Output of following program

package com.mugil.org.qs;

public class Question8 
{
	public static void main(String[] args) 
	{
		javaHungry(null);
	}

	public static void javaHungry(Integer s)
	{
		System.out.println("Integer");
	}
	
	public static void javaHungry(Object s)
	{
		System.out.println("Object");
	}
	
	public static void javaHungry(String s)
	{
		System.out.println("String");
	}
}

Output

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	The method javaHungry(Integer) is ambiguous for the type Question8

Q8:The code wont compile since, To explain the things in details let have a look into the following code
Question8.java

package com.mugil.org.qs;

public class Question8 
{
	public static void main(String[] args) 
	{
		javaHungry(null);
	}

	/*public static void javaHungry(Integer s)
	{
		System.out.println("Integer");
	}*/
	
	public static void javaHungry(Object s)
	{
		System.out.println("Object");
	}
	
	public static void javaHungry(String s)
	{
		System.out.println("String");
	}
} 

Output

String

The reason the above code worked is java compiler tries to find out the method with most specific input parameters to invoke a method.We know that Object is the parent class of String, so the choice was easy. If more than one member method is both accessible and applicable to a method invocation … The Java programming language uses the rule that the most specific method is chosen.

Now when the same is used in the before code which has String and int.You will get compile time error as The method foo(Object) is ambiguous for the type Test because both String and Integer class have Object as parent class and there is no inheritance. So java compiler doesn’t consider any of them to be more specific, hence the method ambiguous call error.

What would be the output?

package com.mugil.org.qs;

public class Question8 
{
	public static void main(String[] args) 
	{
		callMe(null);
	}

	public static void callMe(Exception e) {
		System.out.println("Exception");
	}

	public static void callMe(NullPointerException ne) {
		System.out.println("NullPointerException");
	}

	
	public static void callMe(Object s)
	{
		System.out.println("Object");
	}
}

Output

NullPointerException

As above explained, here callMe(NullPointerException ne) is the most specific method because it’s inherited from Exception class and hence this code compiles fine and when executed prints “NullPointerException”.

What would be the output?

package com.mugil.org.qs;

public class Question9 
{
	public static void main(String[] args) 
	{
		System.out.println(methodOfA());
	}
	
	public static int methodOfA()
	{	
		return (true?null:1);
	}
}

Output

Exception in thread "main" java.lang.NullPointerException
	at com.mugil.org.qs.Question9.methodOfA(Question9.java:12)
	at com.mugil.org.qs.Question9.main(Question9.java:7)
  1. Now when you see the above code the first thing you notice is the code might throw compilation error.how a int can return a null.Whenever you return a primitive value from a method then it would be autoboxed to the wrapper type and sent back to calling method
  2. int is a primitive, null is not a value that it can take on. You could change the method return type to return java.lang.Integer and then you can return null, and existing code that returns int will get autoboxed.
  3. So the output would be runtimeexception that is NullPointerException

Q9:What would be the output?

package com.mugil.org.qs;

public class Question10 
{
	public static void main(String[] args) 
	{
		System.out.println("main1");
		main ("main2");
	}
	
	public static void main(String arg)
	{
	      System.out.println(arg);
	}
}

Output

main1
main2

Ans:Overloading static methods are allowed. Overloading is legal, Overriding is illegal since the static methods belong to a class and there could not be method with same name and parameters within the class

Q11:What would be the output?

package com.mugil.org.qs;

public class Question11 
{
	public static void main(String[] args) 
	{
		try 
		{
			printName();
			System.out.println("Inside Try Block");
		}
		catch (Exception e) 
		{
			System.out.println("Inside Exception Block");
		}
		finally 
		{
			System.out.println("Inside finally Block");
		}
	}
	
	public static void printName()
	{
		throw new Error();
	}
}

Output

Exception in thread "main" Inside finally Block
java.lang.Error
	at com.mugil.org.qs.Question11.printName(Question11.java:24)
	at com.mugil.org.qs.Question11.main(Question11.java:9)

Ans:-Control will go inside finally and Inside finally Block would be printed despite error.

Q11:What would be the output?

package com.mugil.org.qs;

public class Question12 
{
	public static void main(String[] args) 
	{
		Animal[] arrAnimal = {new Animal(), new Dog(),new Animal()};
		
		for (int i = 0; i < arrAnimal.length; i++) 
		{
			arrAnimal[i].doStuff();
		}
	}
}


class Animal
{
	public static void doStuff()
	{
		System.out.println("Animal Stuff");
	}
}

class Dog extends Animal
{
	public static void doStuff()
	{
		System.out.println("Dog Stuff");
	}	
}

Output

Animal Stuff
Animal Stuff
Animal Stuff

Ans:-Since the methods are static it belongs to class not objects, the reference types are ignored and the calling type are considered. In our case Animal.

Q12:Why Fail fast are not thread safe where as fail safe are thread safe?
Concurrent Modification: Concurrent Modification in programming is to modify an object concurrently when another task is already running over it. For example, in Java to modify a collection when another thread is iterating over it. Some Iterator implementations may choose to throw ConcurrentModificationException if this behavior is detected.

Iterators in java are used to iterate over the Collection objects.Fail-Fast iterators immediately throw ConcurrentModificationException if there is structural modification of the collection. Structural modification means adding, removing or updating any element from collection while a thread is iterating over that collection. Iterator on ArrayList, HashMap classes are some examples of fail-fast Iterator.Fail-Safe iterators don’t throw any exceptions if a collection is structurally modified while iterating over it. This is because, they operate on the clone of the collection, not on the original collection and that’s why they are called fail-safe iterators. Iterator on CopyOnWriteArrayList, ConcurrentHashMap classes are examples of fail-safe Iterator.

To know whether the collection is structurally modified or not, fail-fast iterators use an internal flag called modCount which is updated each time a collection is modified.Fail-fast iterators checks the modCount flag whenever it gets the next value (i.e. using next() method), and if it finds that the modCount has been modified after this iterator has been created, it throws ConcurrentModificationException.

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
 
public class FailFastExample {
    public static void main(String[] args)
    {
        Map<String, String> cityCode = new HashMap<String, String>();
        cityCode.put("Delhi", "India");
        cityCode.put("Moscow", "Russia");
        cityCode.put("New York", "USA");
 
        Iterator iterator = cityCode.keySet().iterator();
 
        while (iterator.hasNext()) {
            System.out.println(cityCode.get(iterator.next()));
 
            // adding an element to Map
            // exception will be thrown on next call
            // of next() method.
            cityCode.put("Istanbul", "Turkey");
        }
    }
}

Output

India
Exception in thread "main" java.util.ConcurrentModificationException
    at java.util.HashMap$HashIterator.nextNode(HashMap.java:1442)
    at java.util.HashMap$KeyIterator.next(HashMap.java:1466)
    at FailFastExample.main(FailFastExample.java:18)

Q13:What is Marshalling and Unmarshalling?
To marshall an object is to convert it into a form suitable for serialised storage or transmission; that is, to convert it from its native form within the JVM’s memory, into a form that could be sent down a wire, inserted into a file/database, etc. The specifics will vary depending on the form of marshalling involved; Java’s default serialisation mechanism is one way, but converting the object into an XML or JSON representation are equally valid.

Unmarshalling is just the reverse/other side of this process; taking a representation of the object created by marshalling, and using it to reconstitute an object instance within the JVM.

Q14:What will happen if we directly call run method?

class TestRunnable implements Runnable
{
    public static void main(String[] args)
    {
      TestRunnable nr = new TestRunnable();
      Thread t = new Thread(nr);
      t.setName("Fred");
      t.start();
    }

    public void run()
    {
      System.out.println("TestRunnable in " + Thread.currentThread().getName());
    }
}

Output if only start is called:

TestRunnable in Fred

Output if only run is called:

TestRunnable in main

Existing thread will stop it’s current execution and it will call the newly created thread for which you called run()

Q14:Why is char[] preferred over String for passwords?
Strings are immutable. That means once you’ve created the String, if another process can dump memory, there’s no way (aside from reflection) you can get rid of the data before garbage collection kicks in.Character arrays (char[]) can be cleared after use by setting each character to zero and Strings not. If someone can somehow see the memory image, they can see a password in plain text if Strings are used, but if char[] is used, after purging data with 0’s, the password is secure.With an array, you can explicitly wipe the data after you’re done with it. You can overwrite the array with anything you like, and the password won’t be present anywhere in the system, even before garbage collection.

Q15:Java is pass-by-value or pass-by-reference?
Java is pass-by-value.Value of reference(address) is passed as value.

public class Question13 
{
	public static void main(String[] args) 
	{
		Points objPoints = new Points();
		Question13 objQuestion13 = new Question13();
		objPoints.setPoint(10);
		
		System.out.println(objPoints.getPoint());
		objQuestion13.swap(objPoints);
		System.out.println(objPoints.getPoint());
		
		
		objQuestion13.swapValue(objPoints);
		System.out.println(objPoints.getPoint());
	}	
	
	public void swap(Points pobjPoints)
	{
		Points objPoints = new Points();
		objPoints.setPoint(30);
		pobjPoints = objPoints;
	}
	
	
	public void swapValue(Points pobjPoints)
	{	
		pobjPoints.setPoint(30);
	}
}


class Points
{
	Integer point;
	
	public Integer getPoint() {
		return point;
	}
	public void setPoint(Integer point) {
		this.point = point;
	}
}

Output

10
10
30
  1. In the above program in the swap method we are passing the reference as value.So inside swap method the reference is assigned to new value and nothing happens outside
  2. In the swapvalue method again reference is passed as parameter, but we change the value by setting the value inside the location, inside the container using the setter method. so the changes we do inside would be shown up outside

Q16:Why does StringBuffer/StringBuilder not override equals or hashCode?

String Name1=new String("Mugil");
		String Name2=new String("Mugil");
		
		Map<String, Integer> hmNames = new HashMap();
		hmNames.put(Name1, 30);
		hmNames.put(Name1, 48);
		
		for (Map.Entry<String,Integer> entry : hmNames.entrySet()) 
            System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());

Output

Key = Mugil, Value = 48
StringBuilder Name1 = new StringBuilder("Mugil");
		StringBuilder Name2 = new StringBuilder("Mugil");
		
		Map<StringBuilder, Integer> hmNames = new HashMap();
		hmNames.put(Name1, 30);
		hmNames.put(Name1, 25);
		
		for (Map.Entry<StringBuilder,Integer> entry : hmNames.entrySet()) 
           System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());

Output

Key = Mugil, Value = 25

overriding hashCode() for mutable objects, since modifying such an object that is used as a key in a HashMap could cause the stored value to be “lost.”.In other sense if you have overridden the hashcode then the class would become mutable like in first hashmap example where String becomes mutable incontext to hashMap.String are immutable, but when the same is used in hashMap it becomes mutable because strings having Same value despite having different memory locations replace the before string since they have hashcode and equals overridden in their class.

Q17:When do you prefer to use ibatis over hibernate
Hibernate works well for case Create/Update/Delete some complex domain entities.myBatis is great for fetch queries (case 2) where you just want an answer. Run analytic fetch queries (i.e. summation/aggregation queries).Hibernate would attempt to load the entire object graph and you’d need to start tuning queries with LazyLoading tricks to keep it working on a large domain. Conversely if you just want some analytic POJO page, the myBatis implementation of the same query would be trivial.

Q18:What is the difference between singleton scope in spring and singleton pattern?
One is scope of bean in spring container and another is design pattern, single object per jvm instance.

Q19:Why does Map interface not extend the Collection interface in the Java Collections Framework?
One of the reason is other than map, all the interfaces designed to store a single element. But map is storing the elements in the key value pair.So methods in Collection interface are incompatible for Map interface.Same argument goes for addAll(), remove(), removeAll() methods. So the main reason is the difference in the way data is stored in Map and Collections.

Q20:How to create a ArrayList of fixed size in java
Note the question again.The question is wrong.For arrayList we can only set the Capacity not Size.
Capacity is how many elements the list can potentially accommodate without reallocating its internal structures.When you call new ArrayList(10), you are setting the list’s initial capacity, not its size.Size is the number of elements in the list.So the question supposed to be how will you allocate arrayList with some number of capacity.

List<Integer> arr = new ArrayList<Integer>(10);
System.out.println(arr);
System.out.println(arr.size());

Output

[]
0

So from above code though the memory space for the arrayList has been allocated the size of the array is still 0.

Now I want to allocated ArrayList with Size 10 with initial values being 0 in that.

public static void main(String[] args) 
	{	
		ArrayList<Integer> arr = new ArrayList<Integer>(Collections.nCopies(10, 0));
		System.out.println(arr);
		System.out.println(arr.get(0));
	}

Output

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
0

Q21:Has anyone used ArrayBlockingQueue? How does it work ?
The ArrayBlockingQueue class implements the BlockingQueue interface. ArrayBlockingQueue is a bounded, blocking queue that stores the elements internally in an array. That it is bounded means that it cannot store unlimited amounts of elements. There is an upper bound on the number of elements it can store at the same time. You set the upper bound at instantiation time, and after that it cannot be changed.

BlockingQueue<String> queue = new ArrayBlockingQueue<String>(1024);
queue.put("1");
String string = queue.take();

Q21:What is the significance of the attribute delete orphan in hibernate
DELETE_ORPHAN means if an entity is removed from a related one-to-many collection, then not only disassociate it from the current entity, but delete it.Lets take a Employee and Address Model.If you do a Cascade Delete in the Employee then the Employee rows would be removed from the Employee table and the association between the Address and the Employee is removed. The Row in Address table still exist and its a orphan record not referred. Now when you do delete orphan also this row in the address table would also be deleted.
de-associating the parent and child relation and then immediately delete orphan records from db.

Q22:What is difference between pojo and javabean?
Please Refer Answer

Q23: Difference between comparator and comparable?
Please Refer Here

Q24: What is coercion polymorphism in java
For example, you divide an integer by another integer or a floating-point value by another floating-point value. If one operand is an integer and the other operand is a floating-point value, the compiler coerces (implicitly converts) the integer to a floating-point value to prevent a type error. (There is no division operation that supports an integer operand and a floating-point operand.) Another example is passing a subclass object reference to a method’s superclass parameter. The compiler coerces the subclass type to the superclass type to restrict operations to those of the superclass.

Q25: What is double dispatching
please refer here

Q26: How does cocurrentmodification exception occur while modifying array list. To be precise based on which indicator
When we iterate through the same list and when we try to modify the same list … Then we get the concurrent modification exception …
Fail fast iterator is used for iteration so we get that error.There is an indicator called modcount which is checked inbetween every operation to make sure whether List is modified or not.

Q27: How will you copy object attributes from one object to another or how to create a object which has replica of all attributes from another object ?
Cloning is a process of creating an exact copy of an existing object in the memory. In java, clone() method of java.lang.Object class is used for cloning process. This method creates an exact copy of an object on which it is called through field-by-field assignment and returns the reference of that object. Not all the objects in java are eligible for cloning process. The objects which implement Cloneable interface are only eligible for cloning process. Cloneable interface is a marker interface which is used to provide the marker to cloning process

Shallow copy
The shallow copy of an object will have exact copy of all the fields of original object. If original object has any references to other objects as fields, then only references of those objects are copied into clone object, copy of those objects are not created. That means any changes made to those objects through clone object will be reflected in original object or vice-versa. Shallow copy is not 100% disjoint from original object. Shallow copy is not 100% independent of original object.

Deep Copy
Deep copy of an object will have exact copy of all the fields of original object just like shallow copy. But in additional, if original object has any references to other objects as fields, then copy of those objects are also created by calling clone() method on them. That means clone object and original object will be 100% disjoint. They will be 100% independent of each other. Any changes made to clone object will not be reflected in original object or vice-versa.

clone is tricky to implement correctly.It’s better to use Defensive copying, copy constructors or static factory methods.

Refer Here

Q28: While doing hashing we use to have prime numbers to perform modulo operation?even when u generate equals and hashcode in eclipse for ur class you would get 31 as divisor, culd someone explain this?
What is Prime Number
A number that is divisible only by itself and 1.Primes are unique numbers. They are unique in that, the product of a prime with any other number has the best chance of being unique due to the fact that a prime is used to compose it. This property is used in hashing functions.Given a string “Samuel”, you can generate a unique hash by multiply each of the constituent digits or letters with a prime number and adding them up. This is why primes are used.

Now why is 31 used?
Using a prime of 31 gives a better distribution to the keys, and lesser no of collisions. If you take over 50,000 English words (formed as the union of the word lists provided in two variants of Unix), using the constants 31, 33, 37, 39, and 41 will produce less than 7 collisions in each case.Using P(31), as it’s the cheapest to calculate (because 31 is the difference of two powers of two). P(33) is similarly cheap to calculate, but it’s performance is marginally worse, and 33 is composite(3*11=33)

Q29:You are thrown with a chained exception, now you need to find the root cause for the exception, which method will you use to get the actual cause for the exception?

Throwable getCause(Throwable e) {
    Throwable cause = null; 
    Throwable result = e;

    while(null != (cause = result.getCause())  && (result != cause) ) {
        result = cause;
    }
    return result;
}

Same using Recursion

public static Throwable getRootCause(Throwable throwable) {
    if (throwable.getCause() != null)
        return getRootCause(throwable.getCause());

    return throwable;
}

Using ApacheUtils

Throwable getRootCause(Throwable throwable) 
String getRootCauseMessage(Throwable th) 

String is immutable for several reasons

Design Strings are created in a special memory area in java heap known as “String Intern pool”. If the String is not immutable, changing the String with one reference will lead to the wrong value for the other references.

Security: String is widely used as parameter for many java classes, e.g. network connection, opening files, etc. Were String not immutable, a connection or file would be changed and lead to serious security threat. Mutable strings could cause security problem in Reflection too, as the parameters are strings.

Synchronization and concurrency: making String immutable automatically makes them thread safe thereby solving the synchronization issues.

Caching: Since String is immutable, its hashcode is cached at the time of creation and it doesn’t need to be calculated again. This makes it a great candidate for key in a Map and it’s processing is fast than other HashMap key objects. This is why String is mostly used Object as HashMap keys. Above are some of the reasons I could think of that shows benefits of String immutability. It’s a great feature of Java String class and makes it special.

Class loading: Strings are used in java classloader and immutability provides security that correct class is getting loaded by Classloader. For example, think of an instance where you are trying to load java.sql.Connection class but the referenced value is changed to myhacked.Connection class that can do unwanted things to your database.

substring(), concat(), replace() etc are internally use String constructor for creating new string object.

To customize request parameter data binding, we can use @InitBinder annotated methods within our controller.

  1. The @InitBinder annotated methods will get called on each HTTP request if we don’t specify the ‘value’ element of this annotation.
  2. Each time this method is called a new instance of WebDataBinder is passed to it.
  3. To be more specific about which objects our InitBinder method applies to, we can supply ‘value’ element of the annotation @InitBinder. The ‘value’ element is a single or multiple names of command/form attributes and/or request parameters that this init-binder method is supposed to apply to.
    @InitBinder("User")
    public void customizeBinding (WebDataBinder binder) 
    {
      .
      .
      .
    }

@Controller
@RequestMapping("/register")
public class UserRegistrationController 
{
    @InitBinder("user")
    public void customizeBinding (WebDataBinder binder) 
    {
        SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");
        dateFormatter.setLenient(false);
        binder.registerCustomEditor(Date.class, "dateOfBirth", new CustomDateEditor(dateFormatter, true));
    }
    
    .
    . 
}

simpleDateFormat.setLenient(false); — Will check for out of range Date. For Example, If lenient is set to true, Aug 32 will be converted to Sep 1 .

To find the Variables assigned in JSP page use Windows->Show View->Display

  • In debug perspective: Window -> Show View -> Display
  • Put a break point in your code

Lets have a expression like one below

 <c:if test="${user.isSuccess}">
 .
 . 
 </c:if>

Now i need to find the value of user.isSuccess you can run the below code in in Display to see the values
set in the userObject

_jspx_page_context.findAttribute("user") 

It takes the value from the Page context and displays the values stored in the User Object

Note : The pageContext, _jspx_page_context are different variable names used for based on IDE while debugging JSP page.

In the Spring Container the underlying persistence unit(oracle, mysql) used can be conveyed in three ways

  1. Dialect
  2. Vendor
  3. Provider

Using Dialect in Spring(or)application.xml

<bean id="jpaDialect" class="org.springframework.orm.jpa.vendor.HibernateJpaDialect"/>

<bean id="emf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="jpaVendorAdapter">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
    </property>
....
</bean>

<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="emf"/>
    <property name="jpaDialect" ref="jpaDialect"/>
</bean>

We are telling ‘Spring’ to configure a transactionManager whose properties are entityManagerFactory and jpaDialect. Since these properties have to be specific to hibernate these are set according. The entityManagerFactory and jpaDialect are now set specifically to hibernate (or Vendor).

Dialect and Vendor Adapter works together

Notes:

  1. transactionManager needs entityManagerFactory and jpaDialect
  2. entityManagerFactory – defines database related properties
  3. jpaDialect – JpaDialect is an interface encapsulates certain functionality that standard JPA 1.0 does not offer, such as access to the underlying JDBC Connection.

Using Vendor in Spring(or)application.xml

<property name="jpaVendorAdapter">
    <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>

the VendorAdapter is injected in to transactionManager along with entityManager
Since you have provided the class as class=”org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter”/>, this allows Spring to plug in vendor-specific behavior into Spring’s EntityManagerFactory creators and it serves as single configuration point for all vendor-specific properties.It’s a custom implementation of spring’s own JpaVendorAdapter.

The reason it is so is the underlying database differs from application to application based on the needs and the underlying persistence unit which the developer would like to use I.E MySQL, Oracle.

Using Provider persistence-context.xml

org.hibernate.ejb.HibernatePersistence [/xml]

The tells spring to use the hibernate provider and the class org.hibernate.ejb.HibernatePersistence is Hibernate EJB3 persistence provider implementation.

Note:
Application works just by configuring persistence and provider because the vendor adapter is automatically passed by the persistence provided i.e. HibernatePersistence via the getPersistenceProvider in JpaVendorAdapter.

Provider + JpaVendorAdapter(Used getPersistenceProvider to get underlying Persistence technology in our case hibernate) -> Works
Dialect + JpaVendorAdapter -> Works
Provider + Dialect -> Doesn’t Works

Difference between configuring data source in persistence.xml and spring (or) application-context.xml files

persistence-context.xml

<persistence-unit name="LocalDB" transaction-type="RESOURCE_LOCAL">
    <class>domain.User</class>
    <exclude-unlisted-classes>true</exclude-unlisted-classes>
    <properties>
        <property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/>
        <property name="hibernate.connection.url" value="jdbc:hsqldb:hsql://localhost"/>
        <property name="hibernate.hbm2ddl.auto" value="create"/>
        <property name="hibernate.c3p0.min_size" value="5"/>
        ....
        <property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
    </properties>
</persistence-unit>

application-context.xml

<bean id="domainEntityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="persistenceUnitName" value="JiraManager"/>
    <property name="dataSource" ref="domainDataSource"/>
    <property name="jpaVendorAdapter">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
            <property name="generateDdl" value="false"/>
            <property name="showSql" value="false"/>
            <property name="databasePlatform" value="${hibernate.dialect}"/>
        </bean>
    </property>
</bean>

<bean id="domainDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
    <property name="driverClass" value="${db.driver}" />
    <property name="jdbcUrl" value="${datasource.url}" />
    <property name="user" value="${datasource.username}" />
    <property name="password" value="${datasource.password}" />
    <property name="initialPoolSize" value="5"/>
    <property name="minPoolSize" value="5"/>
    .....
</bean>

If you are using persistence.xml you’re creating your own connection pool and do not profit from the existing connection pool in the container. Thus even if you configured your container to, say, a max of 20 simultaneous connections to the database, you can’t guarantee this max as this new connection pool is not restrained by your configuration. Also, you don’t profit from any monitoring tools your container provides you.

If you are using spring (or) application.xml
If you’re also creating your own connection pool, with the same disadvantages as above. However, you can isolate the definition of this spring bean and only use it in test runs.Your best bet is to look up the container’s connection pool via JNDI. Then you are sure to respect the data source configurations from the container.

application-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:p="http://www.springframework.org/schema/p"
  xmlns:context="http://www.springframework.org/schema/context"
  xmlns:tx="http://www.springframework.org/schema/tx"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:aop="http://www.springframework.org/schema/aop"
  xmlns:jdbc="http://www.springframework.org/schema/jdbc"
  xsi:schemaLocation="
   http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans.xsd
   http://www.springframework.org/schema/aop
   http://www.springframework.org/schema/aop/spring-aop.xsd
   http://www.springframework.org/schema/tx
   http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
   http://www.springframework.org/schema/jdbc
   http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context-3.0.xsd">  
   
<context:component-scan base-package="mugil.org.*" />      
<tx:annotation-driven transaction-manager="transactionManager"/>
  
<bean id="transactionManager"
  class="org.springframework.orm.jpa.JpaTransactionManager">
     <property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>

<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
p:dataSource-ref="dataSource" p:persistenceUnitName="simple-jpa">
 </bean>
  
 <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/MUSIC_STORE"/>
        <property name="username" value="music_store"/>
        <property name="password" value="music_store"/>  
 </bean>     
</beans>

Dissection of application-context.xml

 <context:component-scan base-package="mugil.org.*" />
  1. This component-scan tag also enables the usage of JPA annotations.
  2. Enables the usage of JPA annotations(@Service, @Component, @Repository, @Controller and etc.,)
  3. annotation-config —> enables the usage of JPA annotations , only in the beans specified in the context.xml whereas (ii) component-scan —> scans through all the packages specified, records all the project beans having JPA annotations, into this context.xml. Therefore it enables JPA annotaion usage in (beans specified in context.xml)+(Project Beans).Inshort, component-scan extends annotation-config.

Note:
When we use component-scan in the app-context.xml, it’s not necessary to use annotation-config again.Even if both the tags are specified, it’s not a problem because, the spring container would take care of running the process only once.

 <tx:annotation-driven transaction-manager="transactionManager"/>
  1. It checks for @Transactional annotation in any of the classes. This tag is like a Transactional Switch that turns on the transactional behaviour.Here Transaction Manager is being injected
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
   <property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>

 <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/MUSIC_STORE"/>
        <property name="username" value="music_store"/>
        <property name="password" value="music_store"/>  
 </bean>     
  1. Here Transaction Manager is setup.EntityManagerFactory is being injected.
  2. Here EntityManagerFactory is setup .Data Source reference and Persistence UnitName Reference is specified.
  3. DB connection details are specified.
  4. Based on the PersistenceUnit name, the corresponding portion of persistence.xml is accessed (a Project can have multiple persistenceUnitNames)

persistence-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
             xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
  <persistence-unit name="simple-jpa" transaction-type="RESOURCE_LOCAL">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <class>mugil.pojo.MusicDetails</class>
    <exclude-unlisted-classes>true</exclude-unlisted-classes>
    <properties>
      <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/> 
      <property name="hibernate.show_sql" value="true"/>
      <property name="hibernate.max_fetch_depth" value="3"/> 
    </properties>
  </persistence-unit>
</persistence>

Dissection of persistence-context.xml

  1. persistence-unit – Defines the Name of the Persistence Unit
  2. provider – ORM tool by which the underlying persistence would be accessed
  3. class – Entity Class Names
  4. properties – Defining the underlying persistence technology and other properties would be configured here

Other Java Codes
DaoInterface.java

public interface IMusicStoreDao 
{
   public List getMusicList();
}

DaoImplementation.java

@Service(value = "MusicCollections")
@Repository(value = "MusicCollections")
@Transactional
public class MusicStoreDaoImpl implements IMusicStoreDao{
 
  @PersistenceContext(unitName = "simple-jpa")
    private EntityManager entityManager;
 
   @Override
     public List getMusicList(){
     List musicDetailsList= entityManager.createQuery("select c from MusicDetails c").getResultList();
     return musicDetailsList;
    }
}

Executer.java

public class Executer {
   public static void main(String[] args){
        ApplicationContext applicationContext=new ClassPathXmlApplicationContext("META-INF/app-context.xml");
        IMusicStoreDao musicStoreDao=(IMusicStoreDao) applicationContext.getBean("MusicCollections");
        System.out.println("MusicList: \n"+musicStoreDao.getMusicList());
    }
}

Reference:
Spring and JPA

Posted in JPA.
  1. Spring sits between the application classes and the O/R mapping tool, undertakes transactions, and manages connection objects.It translates the underlying persistence exceptions thrown by Hibernate to meaningful, unchecked exceptions of type DataAccessException. Moreover, Spring provides IoC and AOP, which can be used in the persistence layer
  2. Hibernate uses Template Pattern – To clean the code and provide more manageable code, Spring utilizes a pattern called Template Pattern. By this pattern, a template object wraps all of the boilerplate repetitive code. Then, this object delegates the persistence calls as a part of functionality in the template. In the Hibernate case, HibernateTemplate extracts all of the boilerplate code, such as obtaining a Session, performing transaction, and handing exceptions.
  3. With Spring, the HibernateTemplate object interacts with Hibernate. This object removes the boilerplate code from DAO implementations.Any invocation of one of HibernateTemplate’s methods throws the generic DataAccessException exception instead of HibernateException (a Hibernate-specific exception).Spring lets us demarcate transactions declaratively, instead of implementing duplicated transaction-management code.
  4. The HibernateTemplate class uses a SessionFactory instance internally to obtain Session objects for Hibernate interaction. Interestingly, you can configure the SessionFactory object via the Spring IoC container to be instantiated and injected into DAO objects.
  5. Spring provides its own exception hierarchy, which sits on the exception hierarchies of the O/R mapping tools.The Spring exception hierarchy is defined as a subclass of org.springframework.dao.DataAccessException. Spring catches any exception thrown in the underlying persistence technology and wraps it in a DataAccessException instance.The DataAccessException object is an unchecked exception, because it extends RuntimeException and you do not need to catch it if you do not want to.
  6. Spring provides distinct DAO base classes for the different data-access technologies it supports. When you use Hibernate with Spring, the DAO classes extend the Spring org.springframework.orm.hibernate3.support.HibernateDaoSupport class. This class wraps an instance of org.springframework.orm.hibernate3.HibernateTemplate, which in turn wraps an org.hibernate.SessionFactory instance.
    org.springframework.orm.hibernate3.support.HibernateDaoSupport   
                              |
       org.springframework.orm.hibernate3.HibernateTemplate
                              |
                 org.hibernate.SessionFactory   
      
  7. HibernateException is thrown for any failure when directly interacting with Hibernate. When Spring is used, HibernateException is caught by Spring and translated to DataAccessException for any persistence failure. Both exceptions are unchecked, so you do not need to catch them if you don’t want to do.
  8. DAO Implementation using DAOSupport
    StudentDao.java

    import java.util.Collection;
    
    public interface StudentDao 
    {
      public Student getStudent(long id);
      public Collection getAllStudents();
      public Collection findStudents(String lastName);
      public void saveStudent(Student std);
      public void removeStudent(Student std);
    }
    

    Using DAOSupport Object
    StudentDao.java

    import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
    import java.util.Collection;
    
    public class HibernateStudentDao extends HibernateDaoSupport implements StudentDao 
    {
      public Student getStudent(long id) 
      {
        return (Student) getHibernateTemplate().get(Student.class, new Long(id));
      }
    
      public Collection getAllStudents()
      {
        return getHibernateTemplate().find("from Student std order by std.lastName, std.firstName");
      }
    
    
      public Collection findStudents(String lastName) 
      {
        return getHibernateTemplate().find("from Student std where std.lastName like ?", lastName + "%");
      }
    
      public void saveStudent(Student std) 
      {
        getHibernateTemplate().saveOrUpdate(std);
      }
    
      public void removeStudent(Student std) 
      {
        getHibernateTemplate().delete(std);
      }
    }
    
  9. all of the persistent methods in the DAO class use the getHibernateTemplate() method to access the HibernateTemplate object.
  10. HibernateTemplate is a Spring convenience class that delegates DAO calls to the Hibernate Session API. This class exposes all of Hibernate’s Session methods, as well as a variety of other convenient methods that DAO classes may need. Because HibernateTemplate convenient methods are not exposed by the Session interface, you can use find() and findByCriteria() when you want to execute HQL or create a Criteria object.
  11. Using the HibernateDaoSupport class as the base class for all Hibernate DAO implementations would be more convenient, but you can ignore this class and work directly with a HibernateTemplate instance in DAO classes. To do so, define a property of HibernateTemplate in the DAO class, which is initialized and set up via the Spring IoC container.
  12. DAO Implementation Using HibernateTemplate

    import org.springframework.orm.hibernate3.HibernateTemplate;
    import java.util.Collection;
    
    public class HibernateStudentDao implements StudentDao 
    {
        
      HibernateTemplate hibernateTemplate;
    
      public Student getStudent(long id) 
      {
        return (Student) getHibernateTemplate().get(Student.class, new Long(id));
      }
    
      public Collection getAllStudents()
      {
        return getHibernateTemplate().find("from Student std order by std.lastName, std.firstName");
      }
    
      public Collection findStudents(String lastName) 
      {
        return getHibernateTemplate().find("from Student std where std.lastName like "+ lastName + "%");
      }
    
      public void saveStudent(Student std) 
      {
        getHibernateTemplate().saveOrUpdate(std);
      }
    
      public void removeStudent(Student std) 
      {
        getHibernateTemplate().delete(std);
      }
    
      public HibernateTemplate getHibernateTemplate() 
      {
        return hibernateTemplate;
      }
    
      public void setHibernateTemplate(HibernateTemplate hibernateTemplate) 
      {
        this.hibernateTemplate = hibernateTemplate;
      }
    }
     
  13. The DAO class now has the setHibernateTemplate() method to allow Spring to inject the configured HibernateTemplate instance into the DAO object.Moreover, the DAO class can abandon the HibernateTemplate class and use the SessionFactory instance directly to interact with Hibernate.

    Using SessionFactory Object

    import org.hibernate.HibernateException;
    import org.hibernate.Session;
    import org.hibernate.Query;
    import org.hibernate.SessionFactory;
    import org.springframework.orm.hibernate3.SessionFactoryUtils;
    
    import java.util.Collection;
    
    public class HibernateStudentDao implements StudentDao 
    {
      SessionFactory sessionFactory;
    
      public Student getStudent(long id) 
      {
        Session session = SessionFactoryUtils.getSession(this.sessionFactory, true);
        try {
          return (Student) session.get(Student.class, new Long(id));
        } catch (HibernateException ex) {
          throw SessionFactoryUtils.convertHibernateAccessException(ex);
        } finally {
          SessionFactoryUtils.closeSession(session);
        }
      }
    
      public Collection getAllStudents()
      {
        Session session = SessionFactoryUtils.getSession(this.sessionFactory, true);
        try {      
          Query query = session.createQuery("from Student std order by std.lastName, std.firstName");
          Collection allStudents = query.list();
          return allStudents;
        } catch (HibernateException ex) {
          throw SessionFactoryUtils.convertHibernateAccessException(ex);
        } finally {
          SessionFactoryUtils.closeSession(session);
        }
      }
    
      public Collection getGraduatedStudents()
      {
        Session session = SessionFactoryUtils.getSession(this.sessionFactory, true);
        try {
          Query query = session.createQuery("from Student std where std.status=1");
          Collection graduatedStudents = query.list();
          return graduatedStudents;
        } catch (HibernateException ex) {
          throw SessionFactoryUtils.convertHibernateAccessException(ex);
        } finally {
          SessionFactoryUtils.closeSession(session);
        }
      }
    
      public Collection findStudents(String lastName) 
      {
        Session session = SessionFactoryUtils.getSession(this.sessionFactory, true);
        try {
          Query query = session.createQuery("from Student std where std.lastName like ?");
          query.setString(1, lastName + "%");
          Collection students = query.list();
          return students;
        } catch (HibernateException ex) {
          throw SessionFactoryUtils.convertHibernateAccessException(ex);
        } finally {
          SessionFactoryUtils.closeSession(session);
        }
      }
    
      public void saveStudent(Student std) 
      {
        Session session = SessionFactoryUtils.getSession(this.sessionFactory, true);
        try {
          session.save(std);
        } catch (HibernateException ex) {
          throw SessionFactoryUtils.convertHibernateAccessException(ex);
        } finally {
          SessionFactoryUtils.closeSession(session);
        }
      }
    
      public void removeStudent(Student std) 
      {
        Session session = SessionFactoryUtils.getSession(this.sessionFactory, true);
        try {
          session.delete(std);
        } catch (HibernateException ex) {
          throw SessionFactoryUtils.convertHibernateAccessException(ex);
        } finally {
          SessionFactoryUtils.closeSession(session);
        }
      }
    
      public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
      }
    }
    
  14. In all of the methods above, the SessionFactoryUtils class is used to obtain a Session object. The provided Session object is then used to perform the persistence operation. SessionFactoryUtils is also used to translate HibernateException to DataAccessException in the catch blocks and close the Session objects in the final blocks. Note that this DAO implementation bypasses the advantages of HibernateDaoSupport and HibernateTemplate. You must manage Hibernate’s Session manually (as well as exception translation and transaction management) and implement much boilerplate code.
  15. org.springframework.orm.hibernate3.SessionFactoryUtils is a Spring helper class for obtaining Session, reusing Session within transactions, and translating HibernateException to the generic DataAccessException.
  16. In cases where you need to work directly with Session objects, you can use an implementation of the org.springframework.orm.hibernate3.HibernateCallback interface as the handler to work with Sessions.
  17. An implicit implementation of HibernateCallback is created and its only doInHibernate() method is implemented. The doInHibernate() method takes an object of Session and returns the result of persistence operation, null if none. The HibernateCallback object is then passed to the execute() method of HibernateTemplate to be executed. The doInHibernate() method just provides a handler to work directly with Session objects that are obtained and used behind the scenes.

    Using HibernateCallback

     public void saveStudent(Student std) 
     {
      HibernateCallback callback = new HibernateCallback() {
       public Object doInHibernate(Session session) throws 
    HibernateException, SQLException {
        return session.saveOrUpdate(std);
       }
      };
      getHibernateTemplate().execute(callback);  
     }
     

What is BeanFactory?
The BeanFactory is the actual container which instantiates, configures, and manages a number of beans.Let have a look at how spring works

How it Works

  1. When the application is Deployed the Spring framework reads the xml file and creates the objects.Those are the objects which you see in the Spring Container
  2. Now when you try to refer any of these objects from the outside object using the new method it will throw an exception since or when you try to create a object using new method, the spring container has no idea about the object which you are trying to access
  3. Now to access the object in the container you will use the BeanFactory Objects

BeanFactory is represented by org.springframework.beans.factory.BeanFactory interface.It is the main and the basic way to access the Spring container.Other ways to access the spring container such as ApplicationContext,ListableBeanFactory, ConfigurableBeanFactory etc. are built upon this BeanFactory interface.

BeanFactory interface defines basic functionality for the Spring Container like

  1. It is built upon Factory Design Pattern
  2. provides DI / IOC mechanism for the Spring.
  3. It loads the beans definitions and their property descriptions from some configuration source (for example, from XML configuration file) .
  4. Instantiates the beans when they are requested like beanfactory_obj.getBean(“beanId”).
  5. Wire dependencies and properties for the beans according to their configuration defined in configuration source while instantiating the beans.
  6. Manage the bean life cycle by bean lifecycle interfaces and calling initialization and destruction methods.

Note that BeanFactory does not create the objects of beans immediately when it loads the configuration for beans from configuration source.Only bean definitions and their property descriptions are loaded. Beans themselves are instantiated and their properties are set only when they are requested such as by getBean() method.

Different BeanFactory Implementations:

XmlBeanFactory using Constructor:

Resource res = new FileSystemResource("c:/beansconfig.xml");
BeanFactory bfObj = new XmlBeanFactory(res);
MyBean beanObj= (MyBean) bfObj.getBean("mybean");
  1. The XmlBeanFactory takes the resource object as Parameter
  2. bfObj points to the Spring Container from which you try to fetch the object
  3. mybean is the ID of the Object specified in the XML File
  4. In the above case BeanFactory loads the beans lazily.BeanFactory will read bean definition of a bean with id “mybean” from beansconfig.xml file, instantiates it and return a reference to that.
  5. There are tow implementation of Resource Intefrace. one is org.springframework.core.io.FileSystemResource as seen above and other is org.springframework.core.io.ClassPathResource which loads Loads the resource from classpath(shown below).
ClassPathResource resorce = new ClassPathResource ("beansconfig.xml");
BeanFactory factory = new XmlBeanFactory(resource);

ClassPathXmlApplicationContext:

ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext(
        new String[] {"applicationContext.xml", "applicationContext-part2.xml"});

//an ApplicationContext is also a BeanFactory.
BeanFactory factory = (BeanFactory) appContext;

null

Note BeanFactory is not recomended for use in latest Spring versions. It is there only for backward compatability. ApplicationContext is preferred over this because ApplicationContext provides more advance level features which makes an application enterprise level application.