Tuesday 21 February 2017

Java Collection Basic Questions Part 1

1) What is Collection ? A collection — sometimes called a container — is simply an object that groups multiple elements into a single un... thumbnail 1 summary
1) What is Collection ?

A collection — sometimes called a container — is simply an object that groups multiple elements into a single unit. Collections are used to store, retrieve, manipulate, and communicate aggregate data.For example; a jar of chocolates, list of names etc.

2) What is a Collections Framework ?

The Java Collections Framework is a collection of interfaces and classes which helps in storing and processing the data efficiently. This framework has several useful classes which have tons of useful functions which makes a programmer task super easy.

3) What are the benefits of Java Collections Framework ?

Reduced development effort by using core collection classes rather than implementing our own collection classes.
Code quality is enhanced with the use of well tested collections framework classes.
Reduced effort for code maintenance by using collection classes shipped with JDK.
Reusability and Interoperability(the ability of computer systems or software to exchange and make use of information).

4) What is the root interface in collection hierarchy ?

The root interface of Collection hierarchy in Java is Collection interface.
But the Collection interface extends Iterable interface. Due to this some people consider Iterable interface as the root interface.

Iterable interface is present in java.lang package but Collection interface is present in java.util package. Oracle Java API docs mention that Collection interface is a member of the Java Collections framework.Whereas, Iterable interface is not stated as a part of Java Collections framework in Java docs.Due to this Collection interface is the root of Collections Framework.

5) What is the benefit of Generics in Collections Framework?

Java 1.5 came with Generics and all collection interfaces and implementations use it heavily. Generics allow us to provide the type of Object that a collection can contain, so if you try to add any element of other type it throws compile time error.
This avoids ClassCastException at Runtime because you will get the error at compilation. Also Generics make code clean since we don’t need to use casting and instanceof operator.

6) What is the difference between Collection and Collections ?

Collection Interface :

Collection is a root level interface of the Java Collection Framework. Most of the classes in Java Collection Framework inherit from this interface. List, Set and Queue are main sub interfaces of this interface. JDK doesn’t provide any direct implementations of this interface. But, JDK provides direct implementations of it’s sub interfaces. ArrayList, Vector, HashSet, LinkedHashSet, PriorityQueue are some indirect implementations of Collection interface. Map interface, which is also a part of java collection framework, doesn’t inherit from Collection interface. Collection interface is a member of java.util package.

Collections Class:

Collections is an utility class in java.util package. It consists of only static methods which are used to operate on objects of type Collection. For example, it has the method to find the maximum element in a collection, it has the method to sort the collection, it has the method to search for a particular element in a collection. Below is the list of some important methods of Collections class.

7) Which are some common methods in Collections utility class?

Collections.max() - This method returns maximum element in the specified collection.
Collections.min() - This method returns minimum element in the given collection.
Collections.sort() - This method sorts the specified collection.
Collections.shuffle() - This method randomly shuffles the elements in the specified collection.
Collections.synchronizedCollection() - This method returns synchronized collection backed by the specified collection.
Collections.binarySearch() - This method searches the specified collection for the specified object using binary search algorithm.
Collections.disjoint() - This method returns true if two specified collections have no elements in common.
Collections.copy() - This method copies all elements from one collection to another collection.
Collections.reverse()- This method reverses the order of elements in the specified collection.

8) Which collection classes are synchronized or thread-safe ?

Stack, Properties , Vector and Hashtable can be used in multi threaded environment because they are synchronized classes (or thread-safe).

9) Name the core Collection  interfaces ?

The core collection interfaces encapsulate different types of collections, which are shown in the figure below.

10) What is an Iterator?

Iterator interface provides methods to iterate over any Collection. We can get iterator instance from a Collection using iterator() method. Iterator takes the place of Enumeration in the Java Collections Framework. Iterators allow the caller to remove elements from the underlying collection during the iteration. Java Collection iterator provides a generic way for traversal through the elements of a collection and implements Iterator Design Pattern.

11) What is difference between Enumeration and Iterator interface?

Iterator interface is introduced from JDK 1.2 where as Enumeration interface is there from JDK 1.0.

This is the main difference between Enumeration and Iterator interface. Enumeration only traverses the Collection object. You can’t do any modifications to Collection while traversing the Collection using Enumeration. Where as Iterator interface allows us to remove an element while traversing the Collection object. Iterator has remove() method which is not there in the Enumeration interface. Below is the list of Enumeration and Iterator methods.

Enumeration is a legacy interface used to traverse only the legacy classes like Vector, HashTable and Stack. Where as Iterator is not a legacy code which is used to traverse most of the classes in the collection framework. For example, ArrayList, LinkedList, HashSet, LinkedHashSet, TreeSet, HashMap, LinkedHashMap, TreeMap etc.

As Iterator is fail-fast in nature and doesn’t allow modification of a collection by other threads while iterating, it is considered as safe and secure than Enumeration.

12) Why Iterator don’t have a method to get next element directly without moving the cursor?

It can be implemented on top of current Iterator interface but since it’s use will be rare, it doesn’t make sense to include it in the interface that everyone has to implement.

13) What are different ways to iterate over a list?

There are 5 ways you can iterate through List :
For Loop
  • Advanced For Loop
  • Iterator
  • While Loop
  • Collections’s stream() util (Java8)
package interviewguess.com.tutorial;
 
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
 
/**
 * @author interviewguess.blogspot.com
 */
 
public class InterviewGuessIterateThroughList {
 
 public static void main(String[] argv) {
 
  // create list
  List list = new ArrayList();
 
  // add 4 different values to list
  list.add("Apple");
  list.add("Orange");
  list.add("Banana");
  list.add("Mango");
 
  // iterate via "for loop"
  System.out.println("==> For Loop Example.");
  for (int i = 0; i < list.size(); i++) {
   System.out.println(list.get(i));
  }
 
  // iterate via "New way to loop"
  System.out.println("\n==> Advance For Loop Example..");
  for (String temp : list) {
   System.out.println(temp);
  }
 
  // iterate via "iterator loop"
  System.out.println("\n==> Iterator Example...");
  Iterator iterator = list.iterator();
  while (iterator.hasNext()) {
   System.out.println(iterator.next());
  }
 
  // iterate via "while loop"
  System.out.println("\n==> While Loop Example....");
  int i = 0;
  while (i < list.size()) {
   System.out.println(list.get(i));
   i++;
  }
 
  // collection stream() util: Returns a sequential Stream 
                // with this collection as its source
  System.out.println("\n==> collection stream() util....");
  list.forEach((temp) -> {
   System.out.println(temp);
  });
 }
}

Tuesday 14 February 2017

Multithreading Interview Questions

1) What is the difference between Process and Thread? A process is a self contained execution environment and it can be seen as a program... thumbnail 1 summary
1) What is the difference between Process and Thread?

A process is a self contained execution environment and it can be seen as a program or application whereas Thread is a single task of execution within the process. Java runtime environment runs as a single process which contains different classes and programs as processes. Thread can be called lightweight process. Thread requires less resources to create and exists in the process, thread shares the process resources.

2) What is Multithreading in Java ?

Multithreading in java is a process of executing multiple threads simultaneously.

Thread is basically a lightweight sub-process, a smallest unit of processing. Multiprocessing and multithreading, both are used to achieve multitasking.

But we use multithreading than multiprocessing because threads share a common memory area. They don't allocate separate memory area so saves memory, and context-switching between the threads takes less time than process.

Java Multithreading is mostly used in games, animation etc.

3) What are the different ways of creating thread?

Extend the Thread class and override the run() method in your class. Create an instance of the subclass and invoke the start() method on it, which will create a new thread of execution.
public class NewThread extends Thread{
  public void run(){ 
    // the code that has to be executed in a separate new thread goes here
    } 
    public static void main(String [] args){ 
    NewThread c = new NewThread(); 
    c.start(); 
  }              
}

Implements the Runnable interface.The class will have to implement the run() method in the Runnable interface. Create an instance of this class. Pass the reference of this instance to the Thread constructor a new thread of execution will be created.
public class NewThread implements Runnable{
  public void run(){ 
  // the code that has to be executed in a separate new thread goes here
    } 
  public static void main(String [] args){ 
     NewThread c = new NewThread(); 
     Thread t = new Thread(c);
     t.start();
    }
}

4) What is Life cycle of a Thread (Thread States)?

The different states of threads are as follows:

New – When a thread is instantiated it is in New state until the start() method is called on the thread instance. In this state the thread is not considered to be alive.
Runnable – The thread enters into this state after the start method is called in the thread instance. The thread may enter into the Runnable state from Running state. In this state the thread is considered to be alive.
Running – When the thread scheduler picks up the thread from the Runnable thread’s pool, the thread starts running and the thread is said to be in Running state.
Waiting/Blocked/Sleeping – In these states the thread is said to be alive but not runnable. The thread switches to this state because of reasons like wait method called or sleep method has been called on the running thread or thread might be waiting for some i/o resource so blocked.
Terminated – When the thread finishes its execution i.e. the run() method execution completes, it is said to be in dead state. A dead state can not be started again. If a start() method is invoked on a dead thread a runtime exception will occur.

5) What is use of synchronized keyword?

Synchronized keyword can be applied to static/non-static methods or a block of code. Only one thread at a time can access synchronized methods and if there are multiple threads trying to access the same method then other threads have to wait for the execution of method by one thread. Synchronized keyword provides a lock on the object and thus prevents race condition.
public void synchronized method(){} 
  public void synchronized staticmethod(){}
  public void myMethod(){
     synchronized (this){ 
        //synchronized keyword on block of code
     }
  }

6) What is Static synchronization & non static synchronization?

A synchronized method or block works on a given monitor. Synchronized non-static methods all synchronize on the Java instance of a class. Each instance has a lock monitor. For the case of static methods, what object does static synchronized methods use for locking? The static synchronized statements obtain a lock on the Class object.
If you make any static method as synchronized, the lock will be on the class not on object.

7) What is a volatile keyword?

In general each thread has its own copy of variable, such that one thread is not concerned with the value of same variable in the other thread. But sometime this may not be the case. Consider a scenario in which the count variable is holding the number of times a method is called for a given class irrespective of any thread calling, in this case irrespective of thread access the count has to be increased so the count variable is declared as volatile.

The copy of volatile variable is stored in the main memory, so every time a thread access the variable even for reading purpose the local copy is updated each time from the main memory. The volatile variable also have performance issues.

8) Why wait(), notify() and notifyAll() methods are defined in Object class not Thread class?

It is because they are related to lock and object has a lock.

9) Why wait(), notify(), notifyAll() must be called inside a synchronized method/block?

We use wait(), notify(), or notifyAll() method mostly for inter-thread communication in Java.
One thread is waiting after checking a condition e.g. In the classic Producer-Consumer problem, the Producer thread waits if the buffer is full and Consumer thread notify Producer thread after it creates a space in the buffer by consuming an element.

Calling notify() or notifyAll() methods issues a notification to a single or multiple thread that a condition has changed and once notification thread leaves synchronized block, all the threads which are waiting fight for object lock on which they are waiting and lucky thread returns from wait() method after reacquiring the lock and proceed further. Read More....

10) What is ThreadLocal variables? How can it be used?

Below are some key points about ThreadLocal variables

  • A thread-local variable effectively provides a separate copy of its value for each thread that uses it.
  • ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread
  • In case when multiple threads access a ThreadLocal instance, separate copy of Threadlocal variable is maintained for each thread.
  • Common use is seen in DAO pattern where the DAO class can be singleton but the Database connection can be maintained separately for each thread. (Per Thread Singleton)
11) What is the difference between yield() and sleep()?

yield() method pauses the currently executing thread temporarily for giving a chance to the remaining waiting threads of the same priority to execute. If there is no waiting thread or all the waiting threads have a lower priority then the same thread will continue its execution. The yielded thread when it will get the chance for execution is decided by the thread scheduler whose behavior is vendor dependent. If doesn't release the lock on the objects acquired.
sleep() allows the thread to go to sleep state for x milliseconds. When a thread goes into sleep state it doesn’t releases the lock.

12) What is the difference between wait() and sleep()?

The major difference is that wait() releases the lock or monitor while sleep() doesn’t releases any lock or monitor while waiting. Wait is used for inter-thread communication while sleep is used to introduce pause on execution

13) What is join() method?

The join() method waits for a thread to die. In other words, it causes the currently running threads to stop executing until the thread it joins with completes its task.

14) Is it possible to start a thread twice?

No, there is no possibility to start a thread twice. If you does so, an IllegalThreadStateException is thrown.

Monday 13 February 2017

Why wait(), notify(), notifyAll() must be called inside a synchronized method/block

We use wait(), notify(), or notifyAll() method mostly for inter-thread communication in Java. One thread is waiting after checking a condi... thumbnail 1 summary
We use wait(), notify(), or notifyAll() method mostly for inter-thread communication in Java.
One thread is waiting after checking a condition e.g. In the classic Producer-Consumer problem, the Producer thread waits if the buffer is full and Consumer thread notify Producer thread after it creates a space in the buffer by consuming an element.

Calling notify() or notifyAll() methods issues a notification to a single or multiple thread that a condition has changed and once notification thread leaves synchronized block, all the threads which are waiting fight for object lock on which they are waiting and lucky thread returns from wait() method after reacquiring the lock and proceed further.

Let's understand the problem with an example :
One thread read data from a buffer and one thread write data into buffer. The reading data thread needs to wait until the writing data thread completly write a block data into the buffer. The wirting data thread needs to wait until the reading data thread completly read the data from the buffer. If wait(), notify(), and notifyAll() methods can be called by a ordinary method , the reading thread calls wait() and the thread is being added to waiting queue . At just the same moment, the writing thread calls notify() to signal the condition changes.So due to Race Condition the reading thread misses the change and waits forever.

Now let's think how does this potential race condition get resolved? This race condition is resolved by using synchronized keyword and locking provided by Java. In order to call the wait (), notify () or notifyAll () methods in Java, we must have obtained the lock for the object on which we're calling the method.

Since the wait() method in Java also releases the lock prior to waiting and reacquires the lock prior to returning from the wait() method, we must use this lock to ensure that checking the condition (reading is complete or not) and setting the condition (you can write) is atomic which can be achieved by using synchronized method or block in Java.

Note : We call wait (), notify () or notifyAll method in Java from synchronized method or synchronized block in Java to avoid:

1) IllegalMonitorStateException in Java which will occur if we don't call wait (), notify () or notifyAll () method from synchronized context.

2) Any potential race condition between wait and notify method in Java.

Thursday 9 February 2017

How does clone method work

java.lang.Object provides default implementation of clone() method in Java. It's declared as protected and native in Object class, so i... thumbnail 1 summary
java.lang.Object provides default implementation of clone() method in Java. It's declared as protected and native in Object class, so implemented in native code. Since its convention to return clone() of an object by calling super.clone() method, any cloning process eventually reaches to java.lang.Object clone() method. This method, first checks if the corresponding object implements Cloneable interface, which is a marker interface. If that instance doesn't implement Cloneable then it throws CloneNotSupportedException in Java, a checked exception, which is always required to be handled while cloning an object.
In java, if a class needs to support cloning it has to do following things:

A) You must implement Cloneable interface.
B) You must override clone() method from Object class. [Its weird. clone() method should have been in Cloneable interface.]

Java docs about clone() method are given below (formatted and extract).
/*
Creates and returns a copy of this object. The precise meaning of  "copy" may depend on the class of the object.
The general intent is that, for any object x, the expression:
1) x.clone() != x will be true //guarantees that cloned object will have separate memory address assignment.
2) x.clone().getClass() == x.getClass() will be true, but these are not absolute requirements.//original and cloned objects should have same class type, but it is not mandatory.
3) x.clone().equals(x) will be true, this is not an absolute requirement.//original and cloned objects should have be equal using equals() method, but it is not mandatory.
*/

Lets see an Example :
public class MyClone {
    int x;
    public static void main(String[] args) throws
       CloneNotSupportedException {
        MyClone c = new MyClone();
        MyClone a = (MyClone) c.clone();  // Type-cast is required
    }
}

Because clone() is a part of the Object class, and Object won't implement the Cloneable interface, when our own class will not implement the Cloneable interface, the JVM will not know that this class is eligible for cloning, so CloneNotSupportedException comes out.

Only two thing are possible when we say MyClone a = (MyClone) c.clone();:

Either it will return the cloned object.

Or it will throw CloneNotSupportedException.

As it is clear that it is not mandatory to implement clone() in your class when you want to clone the object, if you don't, the clone() method in Object is declared protected — only subclasses and members of the same package will be able to invoke clone() on the object. If you want to change that, you should override it and make it public.

Checks before the clone() method call:
if(c instanceof Cloneable) {
    MyClone a = (MyClone) c.clone();
}

Note: No constructor gets called when clone() gets called. It's our responsibility to properly set all the member variables of that class.

Implementation
Room.java
public class Room {
 private String roomSize;
 public Room(String roomSize){
  this.roomSize = roomSize;
}
 //Any Getters-Setters goes here
}
Flat.java
public class Flat implements Cloneable {
 private String flatNumber;
 private Room room;
 public Flat(String size,Room room){
   this.size = size;
   this.room = room;
 }
 public Object clone() {
  try {
   return (Flat)super.clone();
 }
  catch (CloneNotSupportedException e) {
   System.out.println("CloneNotSupportedException comes out : "
   +e.getMessage());
  }
 }
//Any Getters-Setters goes here
}
Main.java
public class Main {
  public static void main(String[] args) {
   Room room = new Room("40 X 40");
   Flat flat1 = new Flat(403 , room);
   Flat flat2 = (Flat)flat1.clone();
  }
}

Here super.clone() is getting called inside clone(). As we know, clone() is declared in Object, so it is inherited by every Java object. Calling super.clone() copies our superclass' fields and makes bitwise copies of the fields. This known as shallow copy, which means when you copy Flat using clone(), the field's flatNumber is getting copied with their respective values, but room is copied by reference — bit by bit, the memory address is getting copied.

Any changes you make to room of the original object will be reflected in the cloned object and vice versa. To solve this, we need deep copy. Now, we need to change the Room class as well implement the "Cloneable" interface and clone() method, then call the clone() method of the Room object inside the clone() method of the Flat object.

New Implementation
Room.java
public class Room {
    private String roomSize;
    public Room(String roomSize){
       this.roomSize = roomSize;
   }
    public Object clone() {
       try {
         return (Room)super.clone();
     }
      catch (CloneNotSupportedException e) {
       System.out.println("CloneNotSupportedException comes out : "
    +e.getMessage());
     }
   }
   //Any Getters-Setters goes here
}
Flat.java
public class Flat implements Cloneable {
    private String flatNumber;
 private Room room;
 public Flat(String size,Room room){
   this.size = size;
   this.room = room;
 }
    public Object clone() {
      Flat flat = null;
      try {
         flat = (Flat)super.clone();
     }
      catch (CloneNotSupportedException e) {
          System.out.println("CloneNotSupportedException comes out : "
    +e.getMessage());
     }
     flat.room = (Room) room.clone();
         return flat;
   }
    //Any Getters-Setters goes here
}
Main.java
public class Main {
    public static void main(String[] args) {
       Room room = new Room("40 X 40");
       Flat flat1 = new Flat(403, room);
       Flat flat2 = (Flat)flat1.clone();
   }
}

I hope that this will give a better understanding of cloning and its implementation.

Tuesday 7 February 2017

String Interview Questions

1) What is string constant pool? String objects are most used data objects in Java. Hence, java has a special arrangement to store t... thumbnail 1 summary
1) What is string constant pool?

String objects are most used data objects in Java. Hence, java has a special arrangement to store the string objects. String Constant Pool is one such arrangement. String Constant Pool is the memory space in heap memory specially allocated to store the string objects created using string literals. In String Constant Pool, there will be no two string objects having the same content.
Whenever you create a string object using string literal, JVM first checks the content of the object to be created. If there exist an object in the string constant pool with the same content, then it returns the reference of that object. It doesn’t create a new object. If the content is different from the existing objects then only it creates new object.

2) What is special about string objects as compared to objects of other derived types?

One special thing about string objects is that you can create string objects without using new operator i.e using string literals. This is not possible with other derived types (except wrapper classes). One more special thing about strings is that you can concatenate two string objects using ‘+’. This is the relaxation java gives to string objects as they will be used most of the time while coding. And also java provides string constant pool to store the string objects.

3) What do you mean by mutable and immutable objects?

Immutable objects are like constants. You can’t modify them once they are created. They are final in nature. Where as mutable objects are concerned, you can perform modifications to them.

4) Why string objects are immutable in java?

String is immutable for several reasons, here is a summary:

  • Security: parameters are typically represented as String in network connections, database connection urls, usernames/passwords etc. If it were mutable, these parameters could be easily changed.
  • Synchronization and concurrency: making String immutable automatically makes them thread safe thereby solving the synchronization issues.
  • Caching: when compiler optimizes your String objects, it sees that if two objects have same value (a="test", and b="test") and thus you need only one string object (for both a and b, these two will point to the same object).
  • Class loading: String is used as arguments for class loading. If mutable, it could result in wrong class being loaded (because mutable objects change their state).

That being said, immutability of String only means you cannot change it using its public API. You can in fact bypass the normal API using reflection.

5) How many ways we can create the string object?

There are two ways to create the string object, by string literal and by new keyword.
We can create String object using new operator like any normal java class or we can use double quotes (string literal) to create a String object.
String str = new String("abc");
String str1 = "abc";

When we create a String using double quotes, JVM looks in the String pool to find if any other String is stored with same value. If found, it just returns the reference to that String object else it creates a new String object with given value and stores it in the String pool.
When we use new operator, JVM will create a new string object in normal(non pool) heap memory and the literal "abc" will be placed in the string constant pool. The variable str will refer to the object in heap(non pool).

6) Which one will you prefer among “==” and equals() method to compare two string objects?

I prefer equals() method because it compares two string objects based on their content. That provides more logical comparison of two string objects. If you use “==” operator, it checks only references of two objects are equal or not. It may not be suitable in all situations. So, rather stick to equals() method to compare two string objects.
String s1 = "JAVA";
 
String s2 = "JAVA";
s1 == s2 —> will return true as both are pointing to same object in the constant pool.
s1.equals(s2) —> will also return true as both are referring to same object.
String s1 = new String("JAVA");
 
String s2 = new String("JAVA");
s1 == s2 —> will return false because s1 and s2 are referring to two different objects in the memory.
s1.equals(s2) —> will return true as both the objects have same content.

7) What is Difference Between String , StringBuilder And StringBuffer Classes?

String
String is immutable  ( once created can not be changed )object  . The object created as a String is stored in the  Constant String Pool  .
Every immutable object in Java is thread safe ,that implies String is also thread safe . String can not be used by two threads simultaneously.
String  once assigned can not be changed.
String  demo = " hello " ;
// The above object is stored in constant string pool 
// and its value can not be modified.

demo="Bye" ;     //new "Bye" string is created in constant pool 
// and referenced by the demo variable            
// "hello" string still exists in string constant pool and its value 
// is not overrided but we lost reference to the  "hello"string  

StringBuffer
StringBuffer is mutable means one can change the value of the object . The object created through StringBuffer is stored in the heap . StringBuffer  has the same methods as the StringBuilder , but each method in StringBuffer is synchronized that is StringBuffer is thread safe .
Due to this it does not allow  two threads to simultaneously access the same method . Each method can be accessed by one thread at a time .
But being thread safe has disadvantages too as the performance of the StringBuffer hits due to thread safe property . Thus  StringBuilder is faster than the StringBuffer when calling the same methods of each class.
StringBuffer value can be changed , it means it can be assigned to the new value . Nowadays its a most common interview question ,the differences between the above classes .
String Buffer can be converted to the string by using
toString() method.
StringBuffer demo1 = new StringBuffer("Hello") ;
// The above object stored in heap and its value can be changed .
demo1=new StringBuffer("Bye");
// Above statement is right as it modifies the value 
// which is allowed in the StringBuffer

StringBuilder
StringBuilder  is same as the StringBuffer , that is it stores the object in heap and it can also be modified . The main difference between the StringBuffer and StringBuilder is that StringBuilder is also not thread safe.
StringBuilder is fast as it is not thread safe .  
StringBuilder demo2= new StringBuilder("Hello");
// The above object too is stored in the heap and its value can be 
// modified
demo2=new StringBuilder("Bye"); 
// Above statement is right as it modifies the value which is 
// allowed in the StringBuilder

8) How to create Immutable class?

To create immutable class in java, you have to do following steps.
  • Declare the class as final so it can’t be extended.
  • Make all fields private so that direct access is not allowed.
  • Don’t provide setter methods for variables
  • Make all mutable fields final so that it’s value can be assigned only once.
  • Initialize all the fields via a constructor performing deep copy.
  • Perform cloning of objects in the getter methods to return a copy rather than returning the actual object reference.
import java.util.HashMap;
import java.util.Iterator;

public final class FinalClassExample {

 private final int id;
 
 private final String name;
 
 private final HashMap testMap;
 
 public int getId() {
  return id;
 }


 public String getName() {
  return name;
 }

 /**
  * Accessor function for mutable objects
  */
 public HashMap getTestMap() {
  //return testMap;
  return (HashMap) testMap.clone();
 }

 /**
  * Constructor performing Deep Copy
  * @param i
  * @param n
  * @param hm
  */
 
 public FinalClassExample(int i, String n, HashMap hm){
  System.out.println("Performing Deep Copy for Object 
                initialization");
  this.id=i;
  this.name=n;
  HashMap tempMap=new HashMap();
  String key;
  Iterator it = hm.keySet().iterator();
  while(it.hasNext()){
   key=it.next();
   tempMap.put(key, hm.get(key));
  }
  this.testMap=tempMap;
 }
 
 
 /**
  * Constructor performing Shallow Copy
  * @param i
  * @param n
  * @param hm
  */
 /**
 public FinalClassExample(int i, String n, HashMap hm){
  System.out.println("Performing Shallow Copy for Object 
                initialization");
  this.id=i;
  this.name=n;
  this.testMap=hm;
 }
 */
 
 /**
  * To test the consequences of Shallow Copy and how to avoid it
         * with Deep Copy for creating immutable classes
  * @param args
  */
 public static void main(String[] args) {
  HashMap h1 = new HashMap();
  h1.put("1", "first");
  h1.put("2", "second");
  
  String s = "original";
  
  int i=10;
  
  FinalClassExample ce = new FinalClassExample(i,s,h1);
  
  //Lets see whether its copy by field or reference
  System.out.println(s==ce.getName());
  System.out.println(h1 == ce.getTestMap());
  //print the ce values
  System.out.println("ce id:"+ce.getId());
  System.out.println("ce name:"+ce.getName());
  System.out.println("ce testMap:"+ce.getTestMap());
  //change the local variable values
  i=20;
  s="modified";
  h1.put("3", "third");
  //print the values again
  System.out.println("ce id after local variable change:"
                +ce.getId());
  System.out.println("ce name after local variable change:"
                +ce.getName());
  System.out.println("ce testMap after local variable change
                :"+ce.getTestMap())
  
  HashMap hmTest = ce.getTestMap();
  hmTest.put("4", "new");
  
  System.out.println("ce testMap after changing variable 
                from accessor methods:"+ce.getTestMap());

 }

}
Output of the above immutable class in java example program is:

Performing Deep Copy for Object initialization
  • true
  • false
  • ce id:10
  • ce name:original
  • ce testMap:{2=second, 1=first}
  • ce id after local variable change:10
  • ce name after local variable change:original
  • ce testMap after local variable change:{2=second, 1=first}
  • ce testMap after changing variable from accessor methods:{2=second, 1=first}

Now let’s comment the constructor providing deep copy and uncomment the constructor providing shallow copy. Also uncomment the return statement in getTestMap() method that returns the actual object reference and then execute the program once again.

Performing Shallow Copy for Object initialization
  • true
  • true
  • ce id:10
  • ce name:original
  • ce testMap:{2=second, 1=first}
  • ce id after local variable change:10
  • ce name after local variable change:original
  • ce testMap after local variable change:{3=third, 2=second, 1=first}
  • ce testMap after changing variable from accessor methods:{3=third, 2=second, 1=first, 4=new}
  • As you can see from the output, HashMap values got changed because of shallow copy in the constructor and providing direct reference to the original object in the getter function.

Monday 6 February 2017

Exception Handling Interview Questions

1) What is Exception Handling? Exceptions are events that occur during the execution of programs that disrupt the normal flow of instruct... thumbnail 1 summary
1) What is Exception Handling?

Exceptions are events that occur during the execution of programs that disrupt the normal flow of instructions.When an exception occurs program processing gets terminated and doesn’t continue further. In such cases we get a system generated error message.

In Java, an exception is an object that wraps an error event that occurred within a method and contains:

  • Information about the error including its type
  • The state of the program when the error occurred
  • Optionally, other custom information
  • Exception objects can be thrown and caught.
Exception can occur at runtime (known as runtime exceptions) as well as at compile-time (known Compile-time exceptions).

There can be several reasons for an exception. For example, following situations can cause an exception – Opening a non-existing file, Network connection problem, Operands being manipulated are out of prescribed ranges, class file missing which was supposed to be loaded and so on.

2) What is difference between error and exception ? 

Errors indicate serious problems and abnormal conditions that most applications should not try to handle. Error defines problems that are not expected to be caught under normal circumstances by our program. For example memory error, hardware error, JVM error etc.
Exceptions are conditions within the code. A developer can handle such conditions and take necessary corrective actions. Few examples –
DivideByZero exception , NullPointerException , ArithmeticException , ArrayIndexOutOfBoundsException

Advantages : 

  • Exception handling allows us to control the normal flow of the program by using exception handling in program.
  • It throws an exception whenever a calling method encounters an error providing that the calling method takes care of that error.
  • It also gives us the scope of organizing and differentiating between different error types using a separate block of codes. This is done with the help of try-catch blocks.
3) What are Types of exceptions?

There are two types of exceptions

Checked exceptions
All exceptions other than Runtime Exceptions are known as Checked exceptions as the compiler checks them during compilation to see whether the programmer has handled them or not. If these exceptions are not handled/declared in the program, it will give compilation error.
Examples of Checked Exceptions :-
  • ClassNotFoundException
  • IllegalAccessException
  • NoSuchFieldException
  • EOFException etc.
Unchecked Exceptions
Runtime Exceptions are also known as Unchecked Exceptions as the compiler do not check whether the programmer has handled them or not but it’s the duty of the programmer to handle these exceptions and provide a safe exit.
These exceptions need not be included in any method’s throws list because compiler does not check to see if a method handles or throws these exceptions.
Examples of Unchecked Exceptions:-
  • ArithmeticException
  • ArrayIndexOutOfBoundsException
  • NullPointerException
  • NegativeArraySizeException etc.
4) What is Exception hierarchy?


5) Is it possible to have try block without a catch block?

It is not necessary that each try block must be followed by a catch block. It should be followed by either a catch block OR a finally block. And whatever exceptions are likely to be thrown should be declared in the throws clause of the method.

6) What is Finally Block?

A finally statement must be associated with a try statement. It identifies a block of statements that needs to be executed regardless of whether or not an exception occurs within the try block.
After all other try-catch processing is complete, the code inside the finally block executes. It is not mandatory to include a finally block at all, but if you do, it will run regardless of whether an exception was thrown and handled by the try and catch parts of the block.
In normal execution the finally block is executed after try block. When any exception occurs first the catch block is executed and then finally block is executed.
An exception in the finally block, exactly behaves like any other exception.
The code present in the finally block executes even if the try or catch block contains control transfer statements like return, break or continue.
Note :
The circumstances that prevent execution of the code in a finally block are:
  • The death of a Thread
  • Using of the System. exit() method.
  • Due to an exception arising in the finally block.
7) What is difference between throw and throws?
Throw keyword
  • throw is used to explicitly throw an exception.
  • checked exceptions can not be propagated with throw only.
  • throw is followed by an instance.
  • throw is used within the method.
  • You cannot throw multiple exception
Throws keyword
  • throws is used to declare an exception.
  • checked exception can be propagated with throws.
  • throws is followed by class.
  • throws is used with the method signature.
  • You can declare multiple exception e.g. public void method()throws IOException,SQLException.
8) What is exception propagation ?

An exception is first thrown from the top of the stack and if it is not caught, it drops down the call stack to the previous method,If not caught there, the exception again drops down to the previous method, and so on until they are caught or until they reach the very bottom of the call stack.This is called exception propagation.
Note :
  • By default Unchecked Exceptions are forwarded in calling chain (propagated).
  • By default, Checked Exceptions are not forwarded in calling chain (propagated).
9) How to handle ExceptionHandling with MethodOverriding ?

An overriding method (the method of child class) can throw any unchecked exceptions, regardless of whether the overridden method (method of base class) throws exceptions or not. However the overriding method should not throw checked exceptions that are new or broader than the ones declared by the overridden method. The overriding method can throw those checked exceptions, which have less scope than the exception(s) declared in the overridden method. Read More....

Saturday 4 February 2017

Java Basic Questions Part 2

1) What is Runtime Polymorphism? Polymorphism is the capability of an action or method to do different things based on the object that... thumbnail 1 summary
1) What is Runtime Polymorphism?

Polymorphism is the capability of an action or method to do different things based on the object that it is acting upon. In other words, polymorphism allows you define one interface and have multiple implementation. This is one of the basic principles of object oriented programming.
The method overriding is an example of runtime polymorphism. You can have a method in subclass overrides the method in its super classes with the same name and signature. Java virtual machine determines the proper method to call at the runtime, not at the compile time.It is also know as Dynamic method dispatch.
Let's take a look at the following example:
class Animal {
  void whoAmI() {
    System.out.println("I am a generic Animal.");
  }
}
class Dog extends Animal {
  void whoAmI() {
    System.out.println("I am a Dog.");
  }
}
class Cow extends Animal {
  void whoAmI() {
    System.out.println("I am a Cow.");
  }
}
class Snake extends Animal {
  void whoAmI() {
    System.out.println("I am a Snake.");
  }
}

class RuntimePolymorphismDemo {

  public static void main(String[] args) {
    Animal ref1 = new Animal();
    Animal ref2 = new Dog();
    Animal ref3 = new Cow();
    Animal ref4 = new Snake();
    ref1.whoAmI();
    ref2.whoAmI();
    ref3.whoAmI();
    ref4.whoAmI();
  }
}
In the example, there are four variables of type Animal (e.g., ref1, ref2, ref3, and ref4). Only ref1 refers to an instance of Animal class, all others refer to an instance of the subclasses of Animal. From the output results, you can confirm that version of a method is invoked based on the actually object's type.

In Java, a variable declared type of class A can hold a reference to an object of class A or an object belonging to any subclasses of class A. The program is able to resolve the correct method related to the subclass object at runtime. This is called the runtime polymorphism in Java. This provides the ability to override functionality already available in the class hierarchy tree. At runtime, which version of the method will be invoked is based on the type of actual object stored in that reference variable and not on the type of the reference variable.

2) What is abstraction?

Abstraction is the concept of exposing only the required essential characteristics and behavior with respect to a context.
Hiding of data is known as data abstraction. In object oriented programming language this is implemented automatically while writing the code in the form of class and object.
Real Life Example of Abstraction
Abstraction shows only important things to the user and hides the internal details, for example, when we ride a car, we only know about how to ride cars but can not know about how it work? And also we do not know the internal functionality of a car.

Note: Data abstraction can be used to provide security for the data from the unauthorized methods.In Java language data abstraction can achieve using class.
class Customer
{
int account_no;
float balance_Amt;
String name;
int age;
String address;
void balance_inquiry()
{
/* to perform balance inquiry only account number
is required that means remaining properties 
are hidden for balance inquiry method */
}
void fund_Transfer()
{
/* To transfer the fund account number and 
balance is required and remaining properties 
are hidden for fund transfer method */
}

3) Difference between abstraction and encapsulation?

First difference between Abstraction and Encapsulation is that, Abstraction is implemented in Java using interface and abstract class while Encapsulation is implemented using private, package-private and protected access modifier.

Encapsulation is also called data hiding.

Design principles "programming for interface than implementation" is based on abstraction and "encapsulate whatever changes" is based upon Encapsulation.

4) What is abstract class?

Abstract classes are classes that contain one or more abstract methods. An abstract method is a method that is declared, but contains no implementation. Abstract classes may not be instantiated, and require subclasses to provide implementations for the abstract methods. Let's look at an example of an abstract class, and an abstract method.

Suppose we were modeling the behavior of animals, by creating a class hierachy that started with a base class called Animal. Animals are capable of doing different things like flying, digging and walking, but there are some common operations as well like eating and sleeping. Some common operations are performed by all animals, but in a different way as well. When an operation is performed in a different way, it is a good candidate for an abstract method (forcing subclasses to provide a custom implementation). Let's look at a very primitive Animal base class, which defines an abstract method for making a sound (such as a dog barking, a cow mooing, or a pig oinking).

Note : that the abstract keyword is used to denote both an abstract method, and an abstract class. Now, any animal that wants to be instantiated (like a dog or cow) must implement the makeNoise method - otherwise it is impossible to create an instance of that class. Let's look at a Dog and Cow subclass that extends the Animal class.
public abstract Animal
{
   public void eat(Food food)
   {
        // do something with food.... 
   }

   public void sleep(int hours)
   {
        try
 {
  // 1000 milliseconds * 60 seconds * 60 minutes * hours
  Thread.sleep ( 1000 * 60 * 60 * hours);
 }
 catch (InterruptedException ie) { /* ignore */ } 
   }

   public abstract void makeNoise();
}

public Dog extends Animal
{
   public void makeNoise() { System.out.println ("Bark! Bark!"); }
}

public Cow extends Animal
{
   public void makeNoise() { System.out.println ("Moo! Moo!"); }
}

Now you may be wondering why not declare an abstract class as an interface, and have the Dog and Cow implement the interface. Sure you could - but you'd also need to implement the eat and sleep methods. By using abstract classes, you can inherit the implementation of other (non-abstract) methods. You can't do that with interfaces - an interface cannot provide any method implementations.

5) What is Interface?

An interface is a reference type, similar to a class, which can be declared by using interface keyword. Interfaces can contain only constants, method signatures, default methods, static methods, and nested types. Method bodies exist only for default methods and static methods. Like abstract classes, Interfaces cannot be instantiated—they can only be implemented by classes or extended by other interfaces. Interface is a common way to achieve full abstraction in Java.
Notice how the Cat class must implement the inherited abstract methods in the interface. Furthermore, notice how a class can practically implement as many interfaces as needed (there is a limit of 65,535 due to JVM Limitation).
public interface NoiseMaker {
    String makeNoise(); //interface methods are public by default
}

public interface FoodEater {
    void eat(Food food);
}

public class Cat implements NoiseMaker, FoodEater { 
    @Override
    public String makeNoise() {
        return "meow";
    }

    @Override
    public void eat(Food food) {
        System.out.println("meows appreciatively");
    }
}

NoiseMaker noiseMaker = new Cat(); // Valid
FoodEater foodEater = new Cat(); // Valid
Cat cat = new Cat(); // valid

Cat invalid1 = new NoiseMaker(); // Invalid
Cat invalid2 = new FoodEater(); // Invalid

Rules : 

  • All variables declared in an interface are public static final
  • All methods declared in an interface methods are public abstract (This statement is valid only through Java 7. From Java 8, you are allowed to have methods in an interface, which need not be abstract; such methods are known as default methods)
  • Interfaces cannot be declared as final
  • If more than one interface declares a method that has identical signature, then effectively it is treated as only one method and you cannot distinguish from which interface method is implemented
  • A corresponding Interface_Name.class file would be generated for each interface, upon compilation
6) Can you declare an interface method static?

No, because methods of an interface is abstract by default, and static and abstract keywords can't be used together.

7) What is marker interface?

An interface that have no data member and method is known as a marker interface.For example Serializable, Cloneable etc.
Read : How to implement Cloneable interface ?

8) What is difference between abstract class and interface?

Abstract class
  • An abstract class can have method body (non-abstract methods).
  • An abstract class can have instance variables.
  • An abstract class can have constructor.
  • An abstract class can have static methods.
  • You can extends one abstract class.
Interface
  • Interface have only abstract methods.
  • An interface cannot have instance variables.
  • Interface cannot have constructor.
  • Interface cannot have static methods.
  • ou can implement multiple interfaces
9) What if same package/class import twice?

One can import the same package or same class multiple times. Neither compiler nor JVM complains about it.But the JVM will internally load the class only once no matter how many times you import the same class.

10) What do you mean by static import ?

Static import is a feature introduced in the Java programming language that allows members (fields and methods) defined in a class as public static to be used in Java code without specifying the class in which the field is defined.
import static java.lang.System.out;
import static java.lang.Math.*;
class Demo2{
   public static void main(String args[])
   {
      //instead of Math.sqrt need to use only sqrt
      double var1= sqrt(5.0);
      //instead of Math.tan need to use only tan
      double var2= tan(30);
      //need not to use System in both the below statements
      out.println("Square of 5 is:"+var1);
      out.println("Tan of 30 is:"+var2);
   }
}

Output:
Square of 5 is:2.23606797749979
Tan of 30 is:-6.405331196646276

11) What is nested class?

A class within another class is known as Nested class. The scope of the nested is bounded by the scope of its enclosing class.

Static Nested Class

A satic nested class is the one that has static modifier applied. Because it is static it cannot refer to non-static members of its enclosing class directly. Because of this restriction static nested class is seldom used.

Non-static Nested class
Non-static Nested class is most important type of nested class. It is also known as Inner class. It has access to all variables and methods of Outer class and may refer to them directly. But the reverse is not true, that is, Outer class cannot directly access members of Inner class.
One more important thing to notice about an Inner class is that it can be created only within the scope of Outer class. Java compiler generates an error if any code outside Outer class attempts to instantiate Inner class.
class Outer
{
 int count;
 public void display()
 {
  Inner in=new Inner();
  in.show();
 }

 class Inner
 {
  public void show()
  {
   System.out.println("Inside inner "+(++count));
  } 
 }
}

class Test
{
 public static void main(String[] args)
 {
  Outer ot=new Outer();
  Outer.Inner in= ot.new Inner();
  in.show();
 }
}
Output : Inside inner 1

12) What is anonymous class?

Anonymous inner classes of Java are called anonymous because they have no name. They are anonymous and inline. Anonymous classes are essentially inner classes and defined within some other classes. However, the way anonymous classes are written in Java code may look weird but anonymous inner classes facilitate programmers to declare and instantiate the class at the same time. Another important point to note about anonymous inner classes is that they can be used only once on the place they are coded. In other words, if you want to create only one sub-classed object of a class, then you need not to give the class a name and you can use anonymous inner class in such a case. Anonymous inner classes can be defined not just within a method, but even within an argument to a method. Anonymous inner classes cannot have explicit constructors declared because they have no name to give the constructor.
public interface Hello {

 public void sayHello();
}

Hello is an interface, let’s see how we can create an anonymous class implementation of Hello interface.
public class AnonymousExample {

 //nested anonymous class
 public static Hello hello = new Hello() {

  @Override
  public void sayHello() {
   System.out.println("Hello nested anonymous class");
  }
 };
 
 public static void main(String[] args) {
  
  //anonymous class inside method
  Hello h = new Hello() {

   @Override
   public void sayHello() {
    System.out.println("Hello anonymous class");
   }
  };
  
  h.sayHello();
  
  AnonymousExample.hello.sayHello();
 }

}

Above Hello class can be an abstract class also.

13) What is nested interface ?

An interface i.e. declared within another interface or class is known as nested interface. The nested interfaces are used to group related interfaces so that they can be easy to maintain. The nested interface must be referred by the outer interface or class. It can't be accessed directly.
interface Showable{  
  void show();  
  interface Message{  
   void msg();  
  }  
}  
class TestNestedInterface1 implements Showable.Message{  
 public void msg(){System.out.println("Hello nested interface");}  
  
 public static void main(String args[]){  
  Showable.Message message=new TestNestedInterface1();//upcasting here  
  message.msg();  
 }  
}  

  • Nested interface must be public if it is declared inside the interface but it can have any access modifier if declared within the class.
  • Nested interfaces are declared static implicitely.
14) Can an Interface have a class?

Yes you can have a class inside an interface
The class can even access the variable that's defined in the interface and the super interfaces.

Friday 3 February 2017

Java Basic Questions Part 1

1) What is the Difference Between JVM, JDK and JRE ? JVM The Java Virtual machine (JVM) is the virtual machine that run the Java by... thumbnail 1 summary
1) What is the Difference Between JVM, JDK and JRE ?

JVM

The Java Virtual machine (JVM) is the virtual machine that run the Java bytecodes. The JVM doesn't understand Java source code, that's why you compile your *.java files to obtain *.class files that contain the bytecodes understandable by the JVM. It's also the entity that allows Java to be a "portable language" (write once, run anywhere). Indeed there are specific implementations of the JVM for different systems (Windows, Linux, MacOS,....), the aim is that with the same bytecodes they all give the same results.

Java Runtime Environment (JRE)

The Java Runtime Environment (JRE) provides the libraries, the Java Virtual Machine, and other components to run applets and applications written in the Java programming language. In addition, two key deployment technologies are part of the JRE: Java Plug-in, which enables applets to run in popular browsers; and Java Web Start, which deploys standalone applications over a network. It is also the foundation for the technologies in the Java 2 Platform, Enterprise Edition (J2EE) for enterprise software development and deployment. The JRE does not contain tools and utilities such as compilers or debuggers for developing applets and applications.

Java Development Kit (JDK)

The JDK is a superset of the JRE, and contains everything that is in the JRE, plus tools such as the compilers and debuggers necessary for developing applets and applications.


2) How many types of memory areas are allocated by JVM?



Class(Method) Area

Class(Method) Area stores per-class structures such as the runtime constant pool, field and method data, the code for methods.

Heap

It is the runtime data area in which objects are allocated.

Stack

Java Stack stores frames.It holds local variables and partial results, and plays a part in method invocation and return.
Each thread has a private JVM stack, created at the same time as thread.
A new frame is created each time a method is invoked. A frame is destroyed when its method invocation completes.

Program Counter Register

PC (program counter) register. It contains the address of the Java virtual machine instruction currently being executed.

Native Method Stack

It contains all the native methods used in the application.

3) What is JIT compiler?

Just-In-Time(JIT) compiler:It is used to improve the performance. JIT compiles parts of the byte code that have similar functionality at the same time, and hence reduces the amount of time needed for compilation.Here the term “compiler” refers to a translator from the instruction set of a Java virtual machine (JVM) to the instruction set of a specific CPU.

4) What is classloader in java?

The java.lang.ClassLoader is an abstract class that can be subclassed by applications that need to extend the manner in which the JVM dynamically loads classes. Constructors in java.lang.ClassLoader (and its subclasses) allow you to specify a parent when you instantiate a new class loader. If you don't explicitly specify a parent, the virtual machine's system class loader will be assigned as the default parent. In other words, the ClassLoader class uses a delegation model to search for classes and resources. Therefore, each instance of ClassLoader has an associated parent class loader, so that when requested to find a class or resources, the task is delegated to its parent class loader before attempting to find the class or resource itself. The loadClass() method of the ClassLoader performs the following tasks, in order, when called to load a class:

If a class has already been loaded, it returns it. Otherwise, it delegates the search for the new class to the parent class loader. If the parent class loader doesn't find the class, loadClass() calls the method findClass() to find and load the class. The finalClass() method searches for the class in the current class loader if the class wasn't found by the parent class loader.

5) What is constructor in java?

A constructor in Java is a block of code similar to a method that's called when an instance of an object is created. Here are the key differences between a constructor and a method: A constructor doesn't have a return type. The name of the constructor must be the same as the name of the class.

6) Does constructor return any value?

So when you call the constructor using a new keyword you get an object. Though it doesnt explicitly return something but instead it creates or constructs something which you can use as an instance of a class. yes, it is the current class instance. (We cannot use return type yet it returns a value).

7) What is static variable and static final variables?

Static variable’s value is same for all the object(or instances) of the class or in other words you can say that all instances(objects) of the same class share a single copy of static variables.

class StaticVariable
{
   static int count=0;
   public void increment()
   {
       count++;
   }
   public static void main(String args[])
   {
       StaticVariableobj1=new StaticVariable();
       StaticVariableobj2=new StaticVariable();
       obj1.increment();
       obj2.increment();
       System.out.println("Obj1: count is="+obj1.count);
       System.out.println("Obj2: count is="+obj2.count);
   }
}

Output:
Obj1: count is=2
Obj2: count is=2

As you can see in the above example that both the objects of class, are sharing a same copy of static variable that’s why they displayed the same value of count.

Static variables are initialized when class is loaded.
Static variables in a class are initialized before any object of that class can be created.
Static variables in a class are initialized before any static method of the class runs.

Static final variables are constants.


public class MyClass{
   public static final int MY_VAR=27;
}

The above code will execute as soon as the class MyClass is loaded, before static method is called and even before any static variable can be used.
The above variable MY_VAR is public which means any class can use it. It is a static variable so you won’t need any object of class in order to access it. It’s final so this variable can never be changed in this or in any class.

final variable always needs initialization, if you don’t initialize it would throw a compilation error.

8) What is static method?

It is a method which belongs to the class and not to the object(instance)
A static method can access only static data. It can not access non-static data (instance variables)
A static method can call only other static methods and can not call a non-static method from it.
A static method can be accessed directly by the class name and doesn’t need any object
Syntax: <class-name>.<method-name>
A static method cannot refer to this or super keywords in anyway

9) Why main method is static?

This is neccesary because main() is called by the JVM before any objects are made. Since it is static it can be directly invoked via the class. Similarly, we use static sometime for user defined methods so that we need not to make objects. void indicates that the main() method being declared does not return a value.

10) What is static block?

Static block is a set of statements, which will be executed by the JVM before execution of main method.
At the time of class loading if we want to perform any activity we have to define that activity inside static block because this block execute at the time of class loading.
In a class we can take any number of static block but all these blocks will be execute from top to bottom.
Note : In real time application static block can be used whenever we want to execute any instructions or statements before execution of main method.

11) What is difference between static method and instance method?

The main difference is an instance method belongs to an object while a static method belongs to the class.
Which means to access an instance method you need to make an object out of a java class and the object has instance methods and instance variables which are accessible through the object. (object reference)
The static methods and variables do not need an object. They are accessed through the class. (class reference)
public class Student{ 
 private String name;
 
 //instance method to set the name of the student object
 public String setName(String name){
  this.name = name;
 }
 
 //static method to get a student object with the given name
 public static Student getStudent(String name){
  //... code to get the Student with the given name from DB
  return student;
 }
}
 
class StudentDemo{
 public static void main(String args[]){
  //create Student object
  Student student1 = new Student();
  
  //access instance method through the object
  //this will set the name of the Student object we created
  student1.setName("John Doe");
 
  //access static method through the class
  Student.getStudent("Jane Doe");
 }
}

12) What is this in java?

Here is given the 6 usage of java this keyword.

  • this keyword can be used to refer current class instance variable.
  • this() can be used to invoke current class constructor.
  • this keyword can be used to invoke current class method (implicitly)
  • this can be passed as an argument in the method call.
  • this can be passed as argument in the constructor call.
  • this keyword can also be used to return the current class instance.
Note: Call to this() must be the first statement in constructor.


13) What is Inheritance?

Inheritance by definition means to aquire the properties / state and behaviour of an other class.
To achieve Inheritance it is necessary that IS-A relation should be present, because every sub-class IS-A super class. Inheritance can be achieved using keyword extends. Eg: Class B extends Class A //means Class B can show its own behaviour as well as Class A behaviour.

Example:
package com.InterviewGuess

public class Flying

{
 public void wings() //non-static method in class A

{ System.out.println(“Show Wings”);

}
}

public class Landing extends
class Flying

{
 public void wheels() //non-static method in class B

{ System.out.println(“Show Wheels”);

}
 }

 class Run

 {
  public static void main(String[] args)

  {
   Landing objlan = new Landing();

   // object type of Landing class is created (because non-static
   // method cannot be directly called from a static method).

   objlan.wings(); // Executes wings() method

   objlan.wheels(); // Executes wheels() method

  }
}

OUTPUT: Show Wings Show Wheels

Here when Flight is Flying it has got only Wings when it is Landing it shows the behaviour of Flying as well as Landing. ie. When Landing type object is created, it can use both the method - wings() in class Flying as well as wheels() in class Landing, because Class Landing extends Class Flying.

Hence Landing (sub-class) IS-A Flying (super-class) or it can be said that Landing class Inherits everything present within Flying class. This is known as Inheritance.
NOTE: Static Members (Methods/Variables) cannot be inherited because only one copy is present, which is loaded during class loading.
A child-class / sub-class cannot have more than 1 parent-class / super-class). ie Multiple inheritance is not possible in java.
Multilevel inheritance is possible. 1 parent-class can have many child-classes.
If a class is declared as static / final it cannot be inherited by any other class.

14) Which class is the superclass for every class?

java.lang.Object is the superclss of every class.

The Mthod which present in Object class are :

  • public final Class getClass() : returns the Class class object of this object. The Class class can further be used to get the metadata of this class.
  • public int hashCode() : returns the hashcode number for this object.
  • public boolean equals(Object obj) : compares the given object to this object.
  • protected Object clone() throws CloneNotSupportedException : creates and returns the exact copy (clone) of this object.
  • public String toString() : returns the string representation of this object.
  • public final void notify() : wakes up single thread, waiting on this object's monitor.
  • public final void notifyAll() : wakes up all the threads, waiting on this object's monitor.
  • public final void wait(long timeout)throws InterruptedException : causes the current thread to wait for the specified milliseconds, until another thread notifies (invokes notify() or notifyAll() method).
  • public final void wait(long timeout,int nanos)throws InterruptedException : causes the current thread to wait for the specified milliseconds and nanoseconds, until another thread notifies (invokes notify() or notifyAll() method).
  • public final void wait()throws InterruptedException : causes the current thread to wait, until another thread notifies (invokes notify() or notifyAll() method).
  • protected void finalize()throws Throwable : is invoked by the garbage collector

15) What is super in java?

It(super) is a keyword.

It is used inside a sub-class method definition to call a method defined in the super class. Private methods of the super-class cannot be called. Only public and protected methods can be called by the super keyword.
Calling exactly super() is always redundant. It's explicitly doing what would be implicitly done otherwise. That's because if you omit a call to the super constructor, the no-argument super constructor will be invoked automatically anyway. Not to say that it's bad style; some people like being explicit.

However, where it becomes useful is when the super constructor takes arguments that you want to pass in from the subclass.
public class Animal {
   private final String noise;
   protected Animal(String noise) {
      this.noise = noise;
   }

   public void makeNoise() {
      System.out.println(noise);
   }
}

public class Pig extends Animal {
    public Pig() {
       super("Oink");
    }
}

16) Why can't this() and super() both be used together in a constructor?

Because this(...) will call another constructor in the same class whereas super() will call a super constructor. If there is no super() in a constructor the compiler will add one implicitly.
Thus if both were allowed you could end up calling the super constructor twice.

17) What is object cloning?

The object cloning is a way to create exact copy of an object. For this purpose, clone() method of Object class is used to clone an object. The java.lang.Cloneable interface must be implemented by the class whose object clone we want to create.
Read : How does clone method work ?

18) What is method overloading?

Method Overloading is a feature that allows a class to have two or more methods having same name, if their argument lists are different. Constructor overloading that allows a class to have more than one constructors having different argument lists.

  • Argument lists could differ in –
  • Number of parameters.
  • Data type of parameters.
  • Sequence of Data type of parameters.

Method overloading is also known as Static Polymorphism.
Points to Note:

  • Static Polymorphism is also known as compile time binding or early binding.
  • Static binding happens at compile time. Method overloading is an example of static binding where binding of method call to its definition happens at Compile time.

19) Can we overload main() method?

You can overload the main() method, but only public static void main(String[] args) will be used when your class is launched by the JVM. For example:
public class InterviewGuess{
    public static void main(String[] args) {
        System.out.println("main(String[] args)");
    }

    public static void main(String arg1) {
        System.out.println("main(String arg1)");
    }

    public static void main(String arg1, String arg2) {
        System.out.println("main(String arg1, String arg2)");
    }
}

That will always print main(String[] args) when you run java Test ... from the command line, even if you specify one or two command-line arguments.

You can call the main() method yourself from code, of course - at which point the normal overloading rules will be applied.

20) What is method overriding?

When a method in a sub class has same name and type signature as a method in its super class, then the method is known as overridden method. Method overriding is also referred to as runtime polymorphism. The key benefit of overriding is the abitility to define method that's specific to a particular subclass type.For Example
class Animal
{
 public void eat()
 {
  System.out.println("Generic Animal eating");
 }
}

class Dog extends Animal
{
 public void eat()   //eat() method overriden by Dog class.
 {
  System.out.println("Dog eat meat");
 }
}

As you can see here Dog class gives it own implementation of eat() method. Method must have same name and same type signature.
NOTE : Static methods cannot be overridden because, a static method is bounded with class where as instance method is bounded with object.

21) What is final variable?

In Java, when final keyword is used with a variable of primitive data types (int, float, .. etc), value of the variable cannot be changed.

For example following program gives error because i is final.
public class Test {
    public static void main(String args[]) {
        final int i = 10;
        i = 30; // Error because i is final.
    }
}

When final is used with non-primitive variables (Note that non-primitive variables are always references to objects in Java), the members of the referred object can be changed. final for non-primitive variables just mean that they cannot be changed to refer to any other object 
class Test1 {
   int i = 10;
}
 
public class Test2 {
    public static void main(String args[]) {
      final Test1 t1 = new Test1();
      t1.i = 30;  // Works
    }
}

22) What is final method?

A final method cannot be overridden or hidden by subclasses. This is used to prevent unexpected behavior from a subclass altering a method that may be crucial to the function or consistency of the class.

23)What is final class?

Java class with final modifier is called final class in Java. Final class is complete in nature and can not be sub-classed or inherited. Several classes in Java are final e.g. String, Integer and other wrapper classes. Here is an example of final class in java
final class PrivateAccount{

}

class SavingsAccount extends PrivateAccount{  //compilation error: cannot
                                     //inherit from final class
}

24) When is it appropriate to use blank final variables?

This is useful to create immutable objects:
public class InterviewGuess {
    private final Color color;

    public InterviewGuess(Color c) {this.color = c};
}

InterviewGuess is immutable (once created, it can't change because color is final). But you can still create various InterviewGuess's by constructing them with various colors.

25) Can you declare the main method as final?

Sure, it can be declared final! It doesn't matter if it is declared final, the JVM will still find it and run it, and the compiler doesn't care. Yes We can declare main method final. If we make this final it can not be override.Hence we can't use it in its child class.

26) Overriding a method with different return types in java?

You can return a different type, as long as it's compatible with the return type of the overridden method. Compatible means: it's a subclass, sub-interface, or implementation of the class or interface returned by the overridden method.

And that's logical. If a method returns an Animal, and your derived class returns a Cow, you're not breaking the contract of the superclass method, since a Cow is an Animal. If the derived class returns a Banana, that isn't correct anymore, since a Banana is not an Animal.
class ShapeBuilder {
    ...
    public Shape build() {
    ....
}

class CircleBuilder extends ShapeBuilder{
    ...
    @Override
    public Circle build() {
    ....
}