Friday, June 20, 2014
This article contains common java interview questions and answers and is essential to have a clear understanding of these before taking up any java interview.

What is autoboxing and auto-unboxing?

Autoboxing is the process of automatically encapsulating a primitive data type into its equivalent wrapper object avoiding the need for explicit construction.

e.g.) Here we don't explicitly construct the Integer object. Java handles the autoboxing of primitive type int to Integer object.

int j = 10;
Integer j = i;

Auto-unboxing is the process of automatically extracting value from a object (wrapper object).

e.g.) Here we extract the value of the Integer object to primitive type variable without explicitly calling a method like intValue().

Integer i = 10;
int j = i;

What is difference between overloading and overriding?

Overloading means having two or more methods with the same name in the same class with different arguments. Overloaded methods must change the argument list. Which method would be invoked is determined at the compiled time.

Overriding is when the sub-class declares a method with the same name and argument list as one of its super class. Argument list doesn't change in overriding. Which method would be invoked depends on the object type and happens at run-time.

What is difference between String, StringBuilder and StringBuffer?

Strings are constant and their values cannot be changed once created. Since String object is immutable. It is recommended to use StringBuffer or StringBuilder when many changes need to be performed on the String. Whenever any operations are performed on the String object it is important to note that a new String object is being created.

StringBuffer is like a String but can be modified. StringBuffer is thread safe and all the methods are synchronized.

StringBuilder is equivalent to StringBuffer and is for use by single thread. Since the methods are not synchronized it is faster.

Is Java pass by value or pass by reference?

Java is always pass by value. When objects are used Java copies and passes the references by value. This is often confused and best explained with examples.

In this example below arg1 and arg2 point to the original StringBuilder objects and they hold a reference. In the swap1 function we are actually swapping the reference values between arg1 and arg2 and hence the original contents of the StringBuilder objects in main are not modified. In the swap2 function are actually modifying the content of objects to which arg1 and arg2 point and hence the content of objects in main are modified.

public class PassValueTest {
 
   private static void swap1(StringBuilder arg1, StringBuilder arg2) {
     StringBuilder temp = arg2;
     arg2 = arg1;
     arg1 = temp;  
   }
 
   private static void swap2(StringBuilder arg1, StringBuilder arg2) {
     String temp = arg2.toString();
     arg2.replace(0, arg2.length(), arg1.toString());
     arg1.replace(0, temp.length(), temp);
   }
 
   public static void main(String[] args) {
     StringBuilder str1 = new StringBuilder("Hello");
     StringBuilder str2 = new StringBuilder("World");
     System.out.println("Before swap = " + str1 + " " + str2);
  
     swap1(str1, str2);
     System.out.println("After swap1 = " + str1 + " " + str2);
  
     swap2(str1, str2);
     System.out.println("After swap2 = " + str1 + " " + str2);
   }
}

Output:-
Before swap = Hello World
After swap1 = Hello World
After swap2 = World Hello

What are immutable classes?

Immutable classes are are Java classes whose objects cannot be modified once created. Examples include the wrapper classes Integer, Float etc. It is important to note that String is also an immutable class. Whenever any operation is performed on a String object a new instance of String object is being created.

To make a user defined class immutable:
  • Don't provide an setter methods.
  • Make all the class members final and private.
  • Prevent sub-classes overriding methods by declaring the class as final.
Example:-
final public class MyExample {
   private final int x;
 
   public MyExample(int x) {
     this.x = x;
   }

   public void printx() {
     System.out.println(x);
   }
}

What are Wrapper classes?

Wrapper classes refers to classes associated with primitive data types. Examples include Integer for int, Boolean for bool etc. These classes allow to treat primitive types as though they are objects.

Example:-
Integer iObj = new Integer(100);
int i = iObj.intValue();

What are Marker interfaces?

Marker interfaces are used signify compatibility with certain operations. Marker interface do not declare any methods. Typical examples of marker interfaces are java.io.Serializable and Clonable. They do not contain any methods but classes must implement Serializable interface in-order to be serialized and de-serialized.

What are bytecodes? Explain.

Bytecodes is the machine language of the Java Virtual Machine (JVM). In Java the source code is written in plain text files. (.java files). The javac compiler converts the source files into .class files which contains the bytecodes. Bytecodes generated is not native to the processor. When the java launcher tool is used the application program is launched along with an instance of JVM which converts the bytecodes into processor specific instructions. The JVM insulates the application program from the underlying hardware.

What is the difference between Strings created with new() and those done as literal assignments?

When String objects are created using the new() they get created on the Heap. When String objects are created using literal assignments they go to a string pool. Significance of using literal assignments is that if an object already exists in the pool with the same literal, instead of creating a new object the previously created object gets returned. String object supports an intern() method which can be used to move to the pool.

Example:-
public static void main(String[] args) {
  String literal1 = "Hello";
  String object1 = new String("Hello").intern();
  String object2 = new String("Hello");
  if ( literal1 == object1 )
    System.out.println("They are same.");
  else
    System.out.println("They are different.");
  
  if ( literal1 == object2 )
    System.out.println("They are same");
  else
    System.out.println("They are different.");  
}

Output:-
They are same.
They are different.

What is the significance of final keyword when applied on classes, methods and variables?

final classes cannot be extended to create sub classes.
final methods cannot be overridden by sub classes.
final variables cannot be changed once initialized.

What is re-entrant synchronization?

Consider an example of a synchronized method which is called recursively by a thread. In this case the thread acquires the lock which it already owns. Allowing a thread to acquire the same lock more than once is called re-entrant synchronization.

What are the approaches to create threads in Java?

There are 2 approaches to create threads in Java.

(1) Runnable object
In this approach, the class implements Runnable interface which defines a single method run. The Runnable object is passed to the thread constructor. Using the Runnable object is the most general approach because the Runnable object can subclass another class other than Thread.

public class MyRunnable implements Runnable {
  public void run() {
    System.out.println("I am thread!");
  }
  
  public static void main(String[] args) {
    Thread t = new Thread(new MyRunnable());
    t.start();
  }
}

(2) Subclass Thread
In this approach, the class extends the Thread class. This is simple to use but limited in the sense that the class must be descendant of Thread.

public class MyThread extends Thread {
  public void run() {
    System.out.println("I am thread!");
  }
  
  public static void main(String[] args) {
    Thread t = new MyThread();
    t.start();
  }
}

Explain the concept of synchronization in Java?

In a multithreaded program, when 2 or more threads try to access a common resource there needs to be a way to ensure that only one thread uses the resource at a time. The process by which this is achieved is called synchronization. Java provides language constructs to achieve using synchronized keyword.

To understand synchronization better it is necessary to learn the concept of monitor. Monitor is an object that acts as a mutually exclusive lock. Only one thread can own a monitor at a time. A thread acquires a lock on the monitor to access a shared resource. All other threads attempting to access the shared resource will wait until first thread exits the monitor.

What are synchronized methods in Java?

Synchronized methods is one the two synchronization idioms available in Java. In synchronized methods synchronized keyword is added at the method level. It is not possible for two invocations of the synchronized methods on the same object to interleave. When one thread is executing a synchronized method all other threads that invoke the synchronized methods block. Synchronized methods also ensures that state of the changes in the object is visible to all threads (happens before relationship) when the methods exits.

Example:-
public class ThreadSync {

 class MyCounter {
  int count = 0;
  MyCounter() {   
  }
  public synchronized void increment() {
   count = count + 1;
  }
 }
 
 class MyThread extends Thread {
  MyCounter counter = null;
  MyThread(MyCounter counter) {
   this.counter = counter;
  }
  public void run() {
   counter.increment();
  }
 }
 
 public static void main(String[] args) {
  ThreadSync ts = new ThreadSync();
  MyCounter counter = ts.new MyCounter();
  Thread t1 = ts.new MyThread(counter);
  Thread t2 = ts.new MyThread(counter);
  t1.start();
  t2.start();
 }
}

What are synchronized statements in Java?

Synchronized statements is another approach of achieving synchronization in Java. This approach needs an object that provides the lock.

There are 2 scenarios where synchronized statements would be useful.
1) When we are working with third party libraries which are not multi-threaded and we don't have access to source code then synchronized statement blocks could be used to achieve thread safety.
2) Synchronized statements are also useful for improving concurrency with fine-grained synchronization where the entire method need not be synchronized but only certain lines of the method.

Example:-
public class ThreadSync {

 class MyCounter {
  private int count = 0;
  private Object lock = new Object();
  MyCounter() {}
  public void increment() {
   synchronized(lock) {
    count = count + 1;
   }
  }
 }
 
 class MyThread extends Thread {
  MyCounter counter = null;
  MyThread(MyCounter counter) {
   this.counter = counter;
  }
  public void run() {
   counter.increment();
  }
 }
 
 public static void main(String[] args) {
  ThreadSync ts = new ThreadSync();
  MyCounter counter = ts.new MyCounter();
  Thread t1 = ts.new MyThread(counter);
  Thread t2 = ts.new MyThread(counter);
  t1.start();
  t2.start();
 }
}

What is the difference between throw and throws in Java exception handling?

  • throw is used to manually throw an exception.
  • throws is used to specify any exceptions that is thrown out of a method.
Example:-
public void calculate() throws ArithmeticException {
}

What is the significance of finally block in Java exception handling?

  • finally block is specified after a try/ catch block and executed after a try block is completed.
  • finally block is always executed independent of whether Exception is generated or not.
  • Typically used in scenarios like closing file handles etc. to prevent resource leaks.
  • Adding cleanup code in finally block is a good practice.
Example:-
public static void java6FileCopy() {
  FileInputStream fis = null;
  FileOutputStream fos = null;
  try {
    fis = new FileInputStream(new File("resources/input.txt"));
    fos = new FileOutputStream(new File("resources/output.txt"));
    int data = fis.read();
        while (data != -1)
        {          
            fos.write(data);
            data = fis.read();
        }
  } 
  catch ( IOException e ) {
    e.printStackTrace();
  }
  finally {
    try {
      if ( fis != null ) fis.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
    try {
      if ( fos != null ) fos.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

Can Java Enumerations have instance variables and method?

  • Yes, in Java enums are treated as class types.
  • enums can have constructor, instance variables and methods.
  • One primary difference compared to classes is enums are not created using new().
  • Each enumeration constant is treated as an object.
  • Constructor would be called for each enum constant.
Example:-
public enum DefectStates {
 New(10), Assigned(20), Open(30), Resolved(40), Closed(50);
 
 private int val;
 DefectStates(int val) {
  this.val = val;
  System.out.println("Constructor: " + val);
 }
 public int getVal() { return val; }
 
 public static void main(String[] args) {
  DefectStates ds = DefectStates.New;
 }
}
Output:-
Constructor: 10
Constructor: 20
Constructor: 30
Constructor: 40
Constructor: 50

What is the difference between process based and thread based multitasking?

Process based multitasking

  1. Process is a program in  executing. Executing two or more programs simultaneously is called process based multitasking. 
  2. Process is heavy weight.
  3. Context switching from one process to another process is expensive.
  4. Process have different address space.
  5. Inter process communication is expensive.

Thread based multitasking

  1. If two or more tasks are performed concurrently in a single program then it is called thread based multitasking.
  2. Thread are light weight.
  3. Context switching from one thread to another thread is less expensive.
  4. Threads share the same address space.
  5. Inter thread communication is less expensive.

What is the significance of super keyword in Java?

super keyword in Java is used in two scenarios.
  1. To invoke a super class constructor. With super(), the super class no-argument constructor is called. With super(parameters) the super class constructor with matching parameter list is called.
  2. To access super class members. If any of the super class method is overridden then super keyword can be used to refer to the hidden field.
Both these scenarios are explained in this example below.

Base class
public class MyBase {

 private int data1;
 private int data2;
 
 public MyBase(int data1, int data2) {
  this.data1 = data1;
  this.data2 = data2;
  System.out.println("MyBase");
 }
 
 protected void print() {
  System.out.println("data1 = " + data1);
  System.out.println("data2 = " + data2);
 }
}

Derived class
public class MyDerived extends MyBase {
   
   private int data3;
 
   public MyDerived(int data1, int data2, int data3) {
    // Invoke super class constructor with 2 args
    super(data1, data2);   
    this.data3 = data3;
    System.out.println("MyDerived");
   }
   
   public void print() {
    // Invoked base class method which is overridden
    super.print();
    System.out.println("data3 = " + data3);
   }
   
   public static void main(String[] args) {
    MyDerived d = new MyDerived(10, 20, 30);
    d.print();
   }
}

Output
MyBase
MyDerived
data1 = 10
data2 = 20
data3 = 30

What is the difference between Runnable and Callable tasks?

The Callable interface is similar to Runnable, in that both are designed for classes whose instances are potentially executed by another thread. Main difference is that Runnable object cannot return a value whereas a Callable can return. Refer these tutorials on Runnable and Callable.

4 comments :

Contact Form

Name

Email *

Message *

Back to Top