Tuesday, 23 June 2015


What is the difference between an abstract class and an interface and when should you use them?

In design, you want the base class to present only an interface for its derived classes. This means, you don’t want anyone to actually instantiate an object of the base class. You only want to upcast to it (implicit upcasting, which gives you polymorphic behavior), so that its interface can be used. This is accomplished by making that class abstract using the abstract keyword. If anyone tries to make an object of an abstract class, the compiler prevents it.
The interface keyword takes this concept of an abstract class a step further by preventing any method or function implementation at all. You can only declare a method or function but not provide the implementation. The class, which is implementing the interface, should provide the actual implementation. The interface is a very useful and
Commonly used aspect in OO design, as it provides the separation of interface and implementation and enables you to:

·         Capture similarities among unrelated classes without artificially forcing a class relationship.

·         Declare methods that one or more classes are expected to implement.

·         Reveal an object's programming interface without revealing its actual implementation.

·         Model multiple interface inheritance in Java, which provides some of the benefits of full on multiple inheritances, a feature that some object-oriented languages support that allow a class to have more than one superclass.

To avoid Diamond problem, we can use Interfaces.
This is called multiple inheritance and java doesn’t support this.

When to use an abstract class?

In case where you want to use implementation inheritance then it is
usually provided by an abstract base class. Abstract classes are excellent candidates inside of application frameworks. Abstract classes let you define some default behavior and force subclasses to provide any specific behavior. Care should be taken not to overuse implementation inheritance.

When to use an interface?

For polymorphic interface inheritance, where the client wants to only deal with a
type and does not care about the actual implementation use interfaces.

1.     If you need to change your design frequently, you should prefer using interface to abstract. CO Coding to an interface reduces coupling and interface inheritance can achieve code reuse with the help of object composition.

2.    The Spring framework’s dependency injection promotes code to an interface principle.


3.    Another justification for using interfaces is that they solve the ‘diamond problem’ of traditional multiple inheritance as shown in the figure. Java does not support multiple inheritance. Java only supports multiple interface inheritance. Interface will solve all the ambiguities caused by this ‘diamond problem’.


Access specifiers in Java
1.    Private -- Availabe within class
2.    Protected --Available within package+ In other packages in classes which are sub classed.
3.     Default -- Available package access
4.    Public --   Available anywhere
Static blocks, non static blocks, local variables and classes can’t be private.

For a class we can use only final, default, public keywords.
Synchronization

Only methods and blocks can be synchronized, not variables or classes.
A class can have both Synchronized and non-synchronized methods.
Once a thread acquires the lock on an object, no other thread can enter any of the synchronized methods in that class (for that object).
If two threads are using the same instance of the class to invoke the method, only one thread at a time will be able to execute the method.
A thread can acquire more than one lock.
If a thread goes to sleep, it holds any locks it has-it doesn't release them.
Static methods can be synchronized.
Ex: While creating Singleton object, static and synchronized method has to create.

What is volatile keyword?

The volatile modifier tells the compiler that the variable modified by volatile can be changed unexpectedly by other parts of your program. One of these situations involves multithreaded programs.  In a multithreaded program, sometimes, two or more threads share the same instance variable. For efficiency considerations, each thread can keep its own, private copy of such a shared variable. The real (or master) copy of the variable is updated at various times, such as when a synchronized method is entered. While this approach works fine, it may be inefficient at times. In some cases, all that really matters is that the master copy of a variable always reflects its current state. To ensure this, simply specify the variable as volatile, which tells the compiler that it must always use the master copy of a volatile variable (or, at least, always keep any private copies up to date with the master copy, and vice versa). Also, accesses to the master variable must be executed in the precise order in which they are executed on any private copy.

What is serialization? How I have to serialize java objects?
Serializable is a marker interface. It does not have any methods. When an object has to be transferred over a network (typically through rmi or EJB) or persist the state of an object to a file, the object Class needs to implement Serializable interface
What happens if an object is Serializable but it includes a reference to a non-serializable object  NotSerializableException at runtime
  1. Transient - These variables are not included in the process of serialization.
  1. The static variables belong to the class and not to an object they are not the part of the state of the object so they are not saved as the part of serialized object.
**To serialize an array or a collection all the members of it must be serializable

The Serializable interface relies on the Java runtime default mechanism to save an object's state. Writing an object is done via the writeObject() method in the ObjectOutputStream class (or the ObjectOutput interface). Writing a primitive value may be done through the appropriate write<datatype>() method. Reading the serialized object is accomplished using the readObject() method of the ObjectInputStream class, and primitives may be read using the various read<datatype>() methods.
Example
import java.io.*;
public class SerializationDemo {
public static void main(String args[]) {
// Object serialization
try {
MyClass object1 = new MyClass("Hello", -7, 2.7e10);
System.out.println("object1: " + object1);
FileOutputStream fos = new FileOutputStream("serial");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(object1);
oos.flush();
oos.close();
}
catch(Exception e) {
System.out.println("Exception during serialization: " + e);
System.exit(0);
}
// Object deserialization
try {
MyClass object2;
FileInputStream fis = new FileInputStream("serial");
ObjectInputStream ois = new ObjectInputStream(fis);
object2 = (MyClass)ois.readObject();
ois.close();
System.out.println("object2: " + object2);
}
catch(Exception e) {
System.out.println("Exception during deserialization: " +
e);
System.exit(0);
}
}
}
class MyClass implements Serializable {
String s;
int i;
double d;
public MyClass(String s, int i, double d) {
this.s = s;
this.i = i;
this.d = d;
}
public String toString() {
return "s=" + s + "; i=" + i + "; d=" + d;
}
}
 Can you Customize Serialization process or can you override default Serialization process in Java?

The answer is yes you can. We all know that for serializing an object ObjectOutputStream.writeObject (saveThisobject) is invoked and for reading object ObjectInputStream.readObject() is invoked but there is one more thing which Java Virtual Machine provides you is to define these two method in your class. If you define these two methods in your class then JVM will invoke these two methods instead of applying default serialization mechanism. You can customize behavior of object serialization and deserialization here by doing any kind of pre or post processing task. Important point to note is making these methods private to avoid being inherited, overridden or overloadedSince only Java Virtual Machine can call private method integrity of your class will remain and Java Serialization will work as normal.
 Suppose super class of a new class implement Serializable interface, how can you avoid new class to being serialized?
One of the tricky interview question in Serialization in Java. If Super Class of a Class already implements Serializable interface in Java then its already Serializable in Java, since you can not unimplemented an interface its not really possible to make it Non Serializable class but yes there is a way to avoid serialization of new class. To avoid java serialization you need to implement writeObject() and readObject() method in your Class and need to throw NotSerializableException from those method. This is another benefit of customizing java serialization process as described in above Serialization interview question and normally it asked as follow-up question as interview progresses
What is externalizer in java 1.5?
We can control the process of serialization by implementing the Externalizable interface instead of Serializable. This interface extends the original Serializable interface and adds writeExternal() and readExternal(). These two methods will automatically be called in your object's serialization and deserialization, allowing you to control the whole process.
There might be times when you have special requirements for the serialization of an object. For example, you may have some security-sensitive parts of the object, like passwords, which you do not want to keep and transfer somewhere. Or, it may be worthless to save a particular object referenced from the main object because its value will become worthless after restoring.
public interface Externalizable extends Serializable

What is serialVersionUID? What would happen if you don't define this?

SerialVersionUID is an ID which is stamped on object when it get serialized usually hashcode of object, you can use tool serialver to see serialVersionUID of a serialized object .  SerialVersionUID is used for version control of object. you can specify serialVersionUID in your class file also.  Consequence of not  specifying  serialVersionUID is that when you add or modify any field in class then already serialized class will not be able to recover because serialVersionUID generated for new class and for old serialized object will be different. Java serialization process relies on correct serialVersionUID for recovering state of serialized object and throws java.io.InvalidClassException in case of serialVersionUID mismatch.
One example of How Serialization can put constraints on your ability to change class is SerialVersionUID. If you don't explicitly declare SerialVersionUID then JVM generates its based upon structure of class which depends upon interfaces a class implements and several other factors which is subject to change. Suppose you implement another interface than JVM will generate a different SerialVersionUID for new version of class files and when you try to load old object object serialized by old version of your program you will get InvalidClassException.
Ex:
public final class EmailAddress implements Validator, Serializable {
    private static final long serialVersionUID = 1L;
………

Difference between ClassNotFoundException vs NoClassDefFoundError in Java?

Main difference between them is in their root cause. 

ClassNotFoundExcpetion comes when you try to load a class at runtime by using Class.forName() or loadClass() and requested class is not present in classpath for example when you try to load MySQL or Oracle driver class and their JAR is not availabe.

While in case of NoClassDefFoundError requested class was present at compile time but not  available at runtime.


UnSupportedClassVersionError is easy to differentiate because it’s related to version of classpath and usually comes when you compile your code in higher Java version and try to run on lower java version. Can be resolved simply by using one java version for compiling and running your application.

Monday, 22 June 2015

Exceptions?

Throwable
Error  Exception
           (checked)   runtime
                                    (unchecked)
                                                    
Difference between error and exception
Error such as OutOfMemory Error which no programmer can guess and can handle it. It depends on dynamically based on architecture, OS and server configuration. Whereas Exception, programmer can handle it and can avoid application's misbehavior. For example if your code is looking for a file which is not available then IOException is thrown.

Difference between checked and unchecked exceptions? Examples?

Checked                                      Unchecked
Subclass of Excepion                    Subclass of RuntimeException
Known that possibility of             Unchecked can be of logical problems in the code.
Exception will be thrown
Ex: SQL Excepiton
IOException
Clonenot supportedException              Ex : Nullpointer exception,AIOBE,ArithmeticE
Errors                                     
Virtualmachine Error
Outofmemory  Error
StaticOverflow Error
We have to use some access specifier in the subclass which has same or greater access than the superclass method specifies, reverse is the case for exceptions.

Ex:
Class A{
Void m1() throws RuntiemException;
}
Class B extends A
{
}
Valid
---------
Void m1(){ }
Protected void m1() throws Runtime Exception { }
Public void m1() throws AIOBE{}
Invalid
-------
Private void m1() throws Exception{}

Difference between throw and throws?

Throw is used to throw an exception manually where as throws is used in the case of checked exceptions to re-intimate the compiler that we have handled the exception. So throws is to be used at the time of defining a method and also at the time of calling that function which raises a checked exception.
Difference between final, finally and finalize methods?

Final-  is a keyword used to declare constants
Finally()-The finally block always executes when the try block exits, except
  1. System.exit(0) call.
  2. Runtime.exit(int)
Finalize() -method helps in garbage collection. A method that is invoked before an object is discarded by the garbage collector, allowing it to clean up its state
System.exit(0)
Terminates the currently running Java Virtual Machine. The argument serves as a status code; by convention, a nonzero status code indicates abnormal termination.
This method calls the exit method in class Runtime. This method never returns normally.
The call System.exit(n) is effectively equivalent to the call:
 Runtime.getRuntime().exit(n)

What does finally block does ?

There are 4 potential scenarios here:
1.         The try block runs to the end, and no exception is thrown.  In this scenario, the finally block will be executed after the try block.
2.         An exception is thrown in the try block, which is then caught in one of the catch blocks.  In this scenario, the finally block will execute right after the catch block executes.
3.         An exception is thrown in the try block and there's no matching catch block in the method that can catch the exception.  In this scenario, the call to the method ends, and the exception object   is thrown to the enclosing method - as in the method in which the   try-catch-finally blocks reside.  But, before the method ends, the finally block is executed.
4.  Before the try block runs to completion it returns to wherever the method was invoked.  But, before it returns to the invoking method, the code in the finally block is still executed.  So, remember that the code in the finally block will still be executed even if there is a return statement somewhere in the try block.
In Java, will the code in the finally block be called and run after a return statement is executed?
The code in a finally block will take precedence over the return statement.

For Example:

Code that shows finally runs after return
class SomeClass
{
    public static void main(String args[])
    {
        // call the proveIt method and print the return value
            System.out.println(SomeClass.proveIt());
    }
    public static int proveIt()
    {
            try { 
                        return 1; 
            } 
            finally { 
                System.out.println("finally block is run
            before method returns.");
            }
    }
}

Running the code above gives us this output:
finally block is run before method returns.
1

Very unique situations when finally will not run after return

The finally block will not be called after return in a couple of unique scenarios: if System.exit() is called first, or if the JVM crashes.
What if there is a return statement in the finally block as well?
If you have a return statement in both the finally block and the try block, then you could be in for a surprise. Anything that is returned in the finally block will actually override any exception or returned value that is inside the try/catch block. Here is an example that will help clarify what we are talking about:
public static int getANumber(){
    try{
        return 7;
    } finally {
        return 43;
    }
}
The code above will actually return the “43″ instead of the “7″, because the return value in the finally block (“43″) will override the return value in the try block (“7″).
Also, if the finally block returns a value, it will override any exception thrown in the try/catch block. Here is an example:
public static int getANumber(){
    try{
        throw new NoSuchFieldException();
    } finally {
        return 43;
    }
}
A return statement in the finally block is a bad idea.....
Running the method above will return a “43″ and the exception in the try block will not be thrown. This is why it is considered to be a very bad idea to have a return statement inside the finally block.

 




Thursday, 18 June 2015

Object Class

Class Object is the root of the class hierarchy. Every class has Object as a superclass. All objects, including arrays, implement the methods of this class.

Methods in Object class

  1. clone()
  2. equals(Object obj)
  3. finalize()
  4. hashCode()
  5. notify()
  6. notifyAll()
  7. wait()
  8. wait(long timeout)
  9. wait(long timeout, int nanos)


protected  Object clone()
          Creates and returns a copy of this object.
 boolean equals(Object obj)
          Indicates whether some other object is "equal to" this one.
protected  void finalize()
          Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.
 Class getClass()
          Returns the runtime class of an object.
 int hashCode()
          Returns a hash code value for the object.
 void notify()
          Wakes up a single thread that is waiting on this object's monitor.
 void notifyAll()
          Wakes up all threads that are waiting on this object's monitor.
 String toString()
          Returns a string representation of the object.
 void wait()
          Causes current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object.
 void wait(long timeout)
          Causes current thread to wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.
 void wait(long timeout, int nanos)
          Causes current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object, or some other thread interrupts the current thread, or a certain amount of real time has elapsed.
toString ()
If you print any object, java compiler internally invokes the toString() method on the object. So overriding the toString() method, returns the desired output, it can be the state of an object etc. depends on your implementation.

Advantage of the toString() method

By overriding the toString() method of the Object class, we can return values of the object, so we don't need to write much code.

Understanding problem without toString() method

Let's see the simple code that prints reference.
1.    class Student{  
2.     int rollno;  
3.     String name;  
4.     String city;  
5.      
6.     Student(int rollno, String name, String city){  
7.     this.rollno=rollno;  
8.     this.name=name;  
9.     this.city=city;  
10.  }  
11.   
12.  public static void main(String args[]){  
13.    Student s1=new Student(101,"Raj","lucknow");  
14.    Student s2=new Student(102,"Vijay","ghaziabad");  
15.      
16.    System.out.println(s1);//compiler writes here s1.toString()  
17.    System.out.println(s2);//compiler writes here s2.toString()  
18.  }  
19. }  
Output:Student@1fee6fc
       Student@1eed786
As you can see in the above example, printing s1 and s2 prints the hashcode values of the objects but I want to print the values of these objects. Since java compiler internally calls toString() method, overriding this method will return the specified values. Let's understand it with the example given below:

Example of toString() method

Now let's see the real example of toString() method.
1.    class Student{  
2.     int rollno;  
3.     String name;  
4.     String city;  
5.      
6.     Student(int rollno, String name, String city){  
7.     this.rollno=rollno;  
8.     this.name=name;  
9.     this.city=city;  
10.  }  
11.    
12.  public String toString(){//overriding the toString() method  
13.   return rollno+" "+name+" "+city;  
14.  }  
15.  public static void main(String args[]){  
16.    Student s1=new Student(101,"Raj","lucknow");  
17.    Student s2=new Student(102,"Vijay","ghaziabad");  
18.      
19.    System.out.println(s1);//compiler writes here s1.toString()  
20.    System.out.println(s2);//compiler writes here s2.toString()  
21.  }  
22. }  
Output:101 Raj lucknow
       102 Vijay ghaziabad