1. The difference between synchronized method and synchronized block is selection of lock on which critical section is locked. Synchronized method depending upon whether its a static method or non static locks on either class level lock or object lock.
  2. Class level lock is one for each class and represented by class literal e.g. String.class. Object level lock is provided by current object e.g. this instance, You should never mix static and non static synchronized method in Java
  3. On the other hand synchronized block locks on monitor evaluated by expression provided as parameter to synchronized block.
  4. One significant difference between synchronized method and block is that, Synchronized block generally reduce scope of lock. As scope of lock is inversely proportional to performance, its always better to lock only critical section of code. One of the best example of using synchronized block is double checked locking in Singleton pattern where instead of locking whole getInstance() method we only lock critical section of code which is used to create Singleton instance.
  5. Synchronized block provide granular control over lock(“very detailed control”, meaning you can control a lot of specific aspects), as you can use arbitrary any lock to provide mutual exclusion to critical section code. On the other hand synchronized method always lock either on current object represented by this keyword or class level lock, if its static synchronized method.
  6. Synchronized block can throw throw java.lang.NullPointerException if expression provided to block as parameter evaluates to null, which is not the case with synchronized methods.
  7. In case of synchronized method, lock is acquired by thread when it enter method and released when it leaves method, either normally or by throwing Exception. On the other hand in case of synchronized block, thread acquires lock when they enter synchronized block and release when they leave synchronized block.
public class SycnronizationExample 
{

	public synchronized void lockedByThis()
        {
        System.out.println(" This synchronized method is locked by current" instance of object i.e. this");
        }

	public static synchronized void lockedByClassLock() 
        {
	System.out.println("This static synchronized method is locked by class level lock of this class i.e. SychronizationExample.class");
	}

	public void lockedBySynchronizedBlock()
        {
           System.err.println("This line is executed without locking");     
           Object obj = String.class; //class level lock of Stirng class
     
          synchronized(obj)
          {
            System.out.println("synchronized block, locked by lock represented using obj variable");
          }
         }
}

Why not use for(int i=0; i< v.size();i++){}?

For loops are expensive to the processor when the collection reaches large sizes, as many operations are done just to compute the first line:

For Loop

  1. int i = 0 is an assignment and creation (2 operations)
  2. i get size, check value of i, and compare (3 operations)
  3. i++ gets i then adds 1 to it [++i is only 2 operations] this one (3 operations)
  4. 7/8 operations in total, each time the loop runs through

While Loop

  1. where an enumeration or iterator uses a while(){}
  2. while(v.hasNext()) has next true or false (1 operation)
  3. while(v.hasMoreElements()) has more true or false (1 operation)
  4. Only one operation per repeat of this loop

Iterator
Iterator is the interface and found in the java.util package.It has three methods

  1. hasNext()
  2. next()
  3. remove()

Enumeration
Enumeration is also an interface and found in the java.util package .An enumeration is an object that generates elements one at a time. It is used for passing through a collection, usually of unknown size.The traversing of elements can only be done once per creation.

It has following methods

  1. hasMoreElements()
  2. nextElement()

An iterator over a collection. Iterator takes the place of Enumeration in the Java collections framework.Iterators differ from enumerations by allowing the caller to remove elements from the underlying collection during the iteration.

HashMap vs HashTable

  1. HashMap is non synchronized and not thread safe.On the other hand, HashTable is thread safe and synchronized.
  2. Hashmap allows one null key and any number of null values, while Hashtable do not allow null keys and null values in the HashTable object.
  3. Hashmap object values are iterated by using iterator .HashTable is the only class other than vector which uses enumerator to iterate the values of HashTable object.The iterator in Hashmap is fail-fast iterator while the enumerator for Hashtable is not.if the Hashtable is structurally modified at any time after the iterator is created in any way except the iterator’s own remove method , then the iterator will throw ConcurrentModification Exception.
    Structural modification means adding or removing elements from the Collection object (here hashmap or hashtable) . Thus the enumerations returned by the Hashtable keys and elements methods are not fail fast.
  4. Hashmap is much faster and uses less memory than Hashtable as former is unsynchronized . Unsynchronized objects are often much better in performance in compare to synchronized object like Hashtable in single threaded environment.

Similarities Between HashMap and Hashtable

  1. Insertion Order :Both HashMap and Hashtable does not guarantee that the order of the map will remain constant over time. Instead use LinkedHashMap, as the order remains constant over time.
  2. Map interface :Both HashMap and Hashtable implements Map interface .
  3. Put and get method :Both HashMap and Hashtable provides constant time performance for put and get methods assuming that the objects are distributed uniformly across the bucket.
  4. Internal working :Both HashMap and Hashtable works on the Principle of Hashing . We have already discussed how hashmap works in java .

When to use HashMap and Hashtable?
Single Threaded Application
HashMap should be preferred over Hashtable for the non-threaded applications. In simple words , use HashMap in unsynchronized or single threaded applications .

Multi Threaded Application
We should avoid using Hashtable, as the class is now obsolete in latest Jdk 1.8 . Oracle has provided a better replacement of Hashtable named ConcurrentHashMap. For multithreaded application prefer ConcurrentHashMap instead of Hashtable.

An instance is eligible for garbage collection when null is assigned to it. These are choices made by the JVM implementer.

class Animal 
{
    public static void main(String[] args) 
    {
        Animal lion = new Animal();
        System.out.println("Main is completed.");
    }

    protected void finalize() {
        System.out.println("Rest in Peace!");
    }
}

During compilation process as an optimization technique the Java compiler can choose to assign null value to an instance, so that it marks that instance can be evicted.

In the above class, lion instance is never uses beyond the instantiation line. So the Java compiler as an optimzation measure can assign lion = null just after the instantiation line. So, even before SOP’s output, the finalizer can print ‘Rest in Peace!’. We cannot prove this deterministically as it depends on the JVM implementation and memory used at runtime.

Being an automatic process, programmers need not initiate the garbage collection process explicitly in the code. System.gc() and Runtime.gc() are hooks to request the JVM to initiate the garbage collection process.

When we are writing a performance benchmark we may call System.gc() in between runs

Just before evicting an instance and reclaiming the memory space, the Java garbage collector invokes the finalize() method of the respective instance so that the instance will get a chance to free up any resources held by it. Though there is a guarantee that the finalize() will be invoked before reclaiming the memory space, there is no order or time specified. The order between multiple instances cannot be predetermined, they can even happen in parallel. Programs should not pre-mediate an order between instances and reclaim resources using the finalize() method.Any uncaught exception thrown during finalize process is ignored silently and the finalization of that instance is cancelled.

Final Example]

  1. Final is used to apply restrictions on class, method and variable. Final class can’t be inherited, final method can’t be overridden and final variable value can’t be changed.
  2. Final is a keyword.
class FinalEg
{
   public static void main(String[] args) 
   {
      final int x = 600;
      x = 400;// Compile Time Error
    }
}

Finally Example

  1. Finally is used to place important code, it will be executed whether exception is handled or not.
  2. Finally is a block.
class FinallyEg
{
	public static void main(String[] args) 
	{
		try {
			int x = 500;
		} catch (Exception e) {
			System.out.println(e);
		} finally {
			System.out.println("finally block is executed");
		}
	}
}

Finalize Example

  1. Finalize is used to perform clean up processing just before object is garbage collected.
  2. Finalize is a method.
class FinalizeEg 
{
	public void finalize() 
        {
	   System.out.println("finalize called");
	}

	public static void main(String[] args) 
        {
		FinalizeExample f1 = new FinalizeExample();
		FinalizeExample f2 = new FinalizeExample();
		f1 = null;
		f2 = null;
		System.gc();
	}
}

Difference between throw and throws in Java

void doCalc() throws ArithmeticException
{  
   .
   .
   throw new ArithmeticException("sorry");  
}  

throw

  1. Java throw keyword is used to explicitly throw an exception.
  2. Checked exception cannot be propagated using throw only.
  3. Throw is followed by an instance.
  4. Throw is used within the method.
  5. You cannot throw multiple exceptions.

throws

  1. Java throws keyword is used to declare an exception.
  2. Checked exception can be propagated with throws.
  3. Throws is followed by class.
  4. Throws is used with the method signature.
  5. You can declare multiple exceptions e.g.
    public void method()throws IOException,SQLException.

Similarities: Both StringBuilder and StringBuffer are mutable. That means you can change the content of them, with in the same location.

Differences: StringBuffer is mutable and synchronized as well. Where as StringBuilder is mutable but not synchronized by default.

Meaning of synchronized (synchronization): When some thing is synchronized, then multiple threads can access, and modify it with out any problem or side effect. StringBuffer is synchronized, so you can use it with multiple threads with out any problem.

Which one to use when? StringBuilder : When you need a string, which can be modifiable, and only one thread is accessing and modifying it. StringBuffer : When you need a string, which can be modifiable, and multiple threads are accessing and modifying it.

Note : Don’t use StringBuffer unnecessarily, i.e., don’t use it if only one thread is modifying and accessing it because it has lot of locking and unlocking code for synchronization which will unnecessarily take up CPU time. Don’t use locks unless it is required.

Simply use StringBuilder unless you really are trying to share a buffer between threads. StringBuilder is the unsynchronized (less overhead = more efficient)

When a String is there and you add use concat like one below

  
 String x = "Java";
 x.concat("Rules !");
 sysout(x);

Now in the above there would be 2 string object created with output Java.When you used append in stringBuilder or stringBuffer the changes were applied over the object itself

  
 StringBuiler x = new StringBuiler("Java");
 x.append("Rules !");
 sysout(x);

the output would be Java Rules !

I will give you an example first:

public interface LoginAuth{
   public String encryptPassword(String pass);
   public void checkDBforUser();
}

Now suppose you have 3 databases in your application. Then each and every implementation for that database needs to define the above 2 methods:

public class DBMySQL implements LoginAuth{
          // Needs to implement both methods
}
public class DBOracle implements LoginAuth{
          // Needs to implement both methods
}
public class DBAbc implements LoginAuth{
          // Needs to implement both methods
}

But what if encryptPassword() is not database dependent, and it’s the same for each class? Then the above would not be a good approach.

Instead, consider this approach:

public abstract class LoginAuth{
   public String encryptPassword(String pass){
            // Implement the same default behavior here 
            // that is shared by all subclasses.
   }

   // Each subclass needs to provide their own implementation of this only:
   public abstract void checkDBforUser();
}

Now in each child class, we only need to implement one method – the method that is database dependent.

Technical Differences

  1. Implementing an interface consumes very little CPU, because it’s not a class, just a bunch of names, and therefore there is no expensive look-up to do. It’s great when it matters such as in embedded devices
  2. Abstract classes, unlike interfaces, are classes. They are more expensive to use because there is a look-up to do when you inherit from them.
  3. Abstract classes can have constants, members, method stubs (methods without a body) and defined methods, whereas interfaces can only have constants and methods stubs.
  4. Methods and members of an abstract class can be defined with any visibility, whereas all methods of an interface must be defined as public (they are defined public by default).
  5. When inheriting an abstract class, a concrete child class must define the abstract methods, whereas an an abstract class can extend another abstract class and abstract methods from the parent class don’t have to be defined.
  6. Similarly, an interface extending another interface is not responsible for implementing methods from the parent interface. This is because interfaces cannot define any implementation.
  7. A child class can only extend a single class (abstract or concrete), whereas an interface can extend or a class can implement multiple other interfaces.
  8. A child class can define abstract methods with the same or less restrictive visibility, whereas a class implementing an interface must define the methods with the exact same visibility (public).

Consider using abstract classes if :
You want to share code among several closely related classes.
You expect that classes that extend your abstract class have many common methods or fields, or require access modifiers other than public (such as protected and private).
You want to declare non-static or non-final fields.

Consider using interfaces if :

You expect that unrelated classes would implement your interface. For example,many unrelated objects can implement Serializable interface.
You want to specify the behaviour of a particular data type, but not concerned about who implements its behaviour.
You want to take advantage of multiple inheritance of type.

abstract class establishes “is a” relation with concrete classes. interface provides “has a” capability for classes.

  1. The Way aspect function calls are made are through proxy classes internally
  2. Internally the Spring framework creates proxy classed and calls to the code generated as per the xml are run in proxy class methods before the actual class are called
  3. In the below example in DrawingApp.java I try to create a object for the class circle by invoking factoryService getBean Method
  4. This method returns a Object of class ShapeServiceProxy with the custom methods for xml code added

ShapeService.java

package com.mugil.shapes;

public class ShapeService {
	private Circle objCircle;
	private Triangle objTriangle;
		
	public Circle getObjCircle() {
		return objCircle;
	}
	public void setObjCircle(Circle objCircle) {
		this.objCircle = objCircle;
	}
	public Triangle getObjTriangle() {
		return objTriangle;
	}
	public void setObjTriangle(Triangle objTriangle) {
		this.objTriangle = objTriangle;
	}	
}

ShapeServiceProxy.java

package com.mugil.shapes;

public class ShapeServiceProxy extends ShapeService {
	
	public Circle getObjCircle() {
		new LoggingAspect().getLogMessage();
		return super.getObjCircle();
	}
}

DrawingApp.java

package com.mugil.shapes;

public class DrawingApp
 {
	public static void main(String[] args) 
        {
		FactoryService objFactSer = new FactoryService();
		ShapeService objSS = (ShapeService)objFactSer.getBean("ShapeService");
		objSS.getObjCircle();
	}
}

FactoryService.java

package com.mugil.shapes;

public class FactoryService {
	
	public Object getBean(String className)
	{
		if(className.equals("Circle"))
			return new Circle();
		else if(className.equals("Triangle"))
			return new Triangle();
		else if(className.equals("DrawingApp"))
			return new DrawingApp();
		else if(className.equals("ShapeService"))
			return new ShapeServiceProxy();
			
		return null;
	}
}