Most asked Java interview questions by top MNCs like TCS, CTS, Baker Hughes, IBS, HCL...

If you have attended to couple of Java interviews, you know that there are some questions which is asked frequently. It will good for every Java developer to make a list of these for a reference and revision. These are the questions which you simply can't afford to miss, especially at freshers level. They appear at various stage of Java interviews. I will add some more questions in this list, but for now let's start with these 10 questions.

Difference between '==' and 'equals'?


·         The ‘==’ Operator

ü  In Java, when the “==” operator is used to compare 2 objects, it checks to see if the objects refer to the same place in memory.

Ex:

String s1 = new String("abc");

String s2 = new String("abc");

If (s1 == s2) {

System.out.println("s1==s2 is TRUE");

} else {

System.out.println("s1==s2 is FALSE");
}

Output
s1==s2 is FALSE

ü  Now the variables of primitive data types contains the value itself while the reference types contains reference to heap area which stores the actual content. Consider the following code snippet:
Ex:
Integer a = 1;
int b = 1;
If (a == b) {
System.out.println("a==b is TRUE");
} else {
System.out.println("a==b is FALSE");
}

Output
a==b is TRUE

Instead of Integer a = 1, the compiler will substitute the following code:

Integer a = Integer.valueOf(1);

The static method valueOf() returns a wrapper object instance that wraps the provided primitive value. This procedure is called autoboxing, where the compiler constructs a wrapper class out of a primitive type.

When using such a wrapper object is compared with a primitive variable using equality operator a == b the compiler actually changes it to the following:

a.intValue() == b;

Where intValue() returns the primitive value wrapped by the wrapper object (which is called unboxing) i.e. it unboxes the primitive value and make the expression equivalent to comparing two primitives. This is why the equality operator then returned true.

     ·         The ‘equals()’ Method

ü  The ‘equals()’ method is defined in the Object class, from which every class is either a direct or indirect descendant. 
ü  The ‘equals()’ method is meant to compare the contents of 2 objects, and not their location in memory.
ü  This behaviour is accomplished by overriding the ‘equals()’ method, where the object contents are compared instead of the object locations.
ü  It is important to understand that, by default ‘equals()’ method will behave same as the “==” operator and compare the object locations. But, when overriding the ‘equals()’ method, you should compare the values of the object instead.
EX:
String s1 = new String("xyz");
String s1 = new String("xyz");
If (s1.equals(s2)) {
System.out.printlln("s1==s2 is TRUE");
} else {
System.out.println("s1==s2 is FALSE");
}

Output
s1==s2 is TRUE

What is overriding? Is that possible to override a static function?


·      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.

·     No you cannot override a static method in java. Overriding depends on having an instance of a class. A static method is not associated with any instance of a class, so the concept is not applicable.

Ex:

static class Class1 {

public static int Method1(){

return 0;

}

}



static class Class2 extends Class1 {
public static int Method1(){
return 1;
}
}

public static class Main {
public static void main(String[] args){
Class1.Method1(); //Instance of the class is not created here.
Class2.Method1();
}
}

What is overloading? Is that possible to overload a static function?


·        If a class has multiple methods having same name, but different parameters, it is known as Method Overloading.

·         Yes, you can overload a static method. But you cannot overload two methods in Java if they differ only by static keyword.

What is a Singleton class? How is it implemented?


·         Singleton is one of the design patterns in Java.
·         It restricts the instantiation of a class and ensures that only one instance of the class exists in the JVM.
·         The singleton class must provide a global access point to get the instance of the class.
·         Implementation:
ü  Create a private constructor to restrict the instantiation of the class from other classes.
ü  Create a private static variable of the class that is the only instance of the class.
ü  Create a public static method that returns the instance of the class.
Ex:
public class MySingleTon {

           // Create a private static variable
private static MySingleTon myObj;

 // Create private constructor
private MySingleTon(){

}

// Create a static method to get instance.
public static MySingleTon getInstance() {

if (myObj == null) {
myObj = new MySingleTon();
}

return myObj;
}

public void foo(){
System.out.println("Hello…");
}

public static void main(String a[]){
MySingleTon st = MySingleTon.getInstance();
st.foo();
}
}

What is the use of finally block?


·       finally block is used to execute a set of statements that must be executed even if an exception happens like closing a socket connection, stream etc.

·         finally block is always executed whether exception is handled or not.

·         finally block follows try or catch block.

Ex:

public class Test {

        public static void main(String args[]) {

try {

int data=25/0;

System.out.println(data);

} catch(ArithmeticException e) {
System.out.println(e);
}
finally {
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
       } 
·    FYI: finally block is executed even if there is a return statement in try or catch block. But if there is a System.exit(0) statement in try or catch block, then finally block will not be executed.

How to restrict a class, function or variables from inheriting/overriding/reassigning?


·    In order to restrict a class from being inherited, or a function from being overridden or a variable from reassigning, use a final keyword before class/function/variable as shown below:
ü  Class
public final class Test {

}
ü  Function
public final int version(){

return 10;
}

ü  Variable

final int maxLimit = 100;

Difference between mutable and immutable classes?


·         Immutable Object



ü  An Immutable object is a kind of object whose state cannot be modified after it is created.  If we want to modify the data then a new object is created.

ü  For example, String objects are immutable, that means whenever you want to modify the String object then it creates a new object.



String name = ”Michael ”; //One object having Michael as data
String fullname = name.concat("Percy"); // another object as Michael Percy as data

ü  Immutable objects are by default thread safe.

·         Mutable Objects

ü  An object is mutable when you can change its value and it actually creates a new reference in memory of this object.
ü  User defined class objects are mutable.
ü  StringBuffer, StringBuilder classes are mutable.

Difference between String, StringBuffer and StringBuilder?


·         String

ü  It is immutable, if you try to alter their values, another object gets created.

Ex: Suppose you are assigning String S1 = "ABC" then a memory is allocated to S1, say S1 is stored in LOC_1000. Now you are re-assigning the same variable to some other value, S1 = "DEF". Here rather than replacing the existing value another memory location is allocated for the new content, say LOC_1001. So now we have "ABC" in LOC_1000 and "DEF" in LOC_1001. Now, try assigning another string say String S2 = "ABC". Since the content of both S1 and S2 are same, rather than allocating a new memory location, S2 in pointed to LOC_1000.

ü  String is thread safe. String cannot be used by two threads simultaneously.

ü  If your string is not going to change use a String class because a String object is immutable.

ü  The object created using String is stored in constant string pool.



·         StringBuffer



ü  It is mutable, means one can change the value of the object.

Ex: If StringBuffer S1 = "ABC" is allocated in LOC_1000 then S1 = "DEF" will replace the existing value in LOC_1000 with "DEF".

ü  Each method in StringBuffer is synchronized that is StringBuffer is thread safe. But the performance of the StringBuffer hits due to thread safe property. Since each method can be accessed by one thread at a time.
ü  If your string can change, and will be accessed from multiple threads, use a StringBuffer because StringBuffer is synchronous so you have thread-safety.
ü  The object created through StringBuffer is stored in the heap.

·         StringBuilder

ü  It is mutable, means one can change the value of the object.
ü  StringBuilder is not thread safe. But it is faster than StringBuffer since it is not thread safe.
ü  If there are lots of logic and operations in the construction of the string and accessed only from a single thread, using a StringBuilder is good enough.
ü  The object created through StringBuilder is stored in the heap.

Difference between Interface and Abstract class?

Abstract class and interface both are used to achieve abstraction where we can declare the abstract methods. Abstract class and interface both can't be instantiated.
·        Abstract Class

ü  A class that is declared using “abstract” keyword is known as abstract class.
ü  In abstract class you can have concrete methods (methods with body) as well along with abstract methods (without an implementation, without braces, and followed by a semicolon).
ü  Abstract class declaration:
abstract class AbstractDemo {
   // Concrete method: body and braces
   public void myMethod(){
      //Statements here
   }
   // Abstract method: without body and braces
   abstract public void anotherMethod();
}
ü  Since abstract class allows concrete methods as well, it does not provide 100% abstraction. You can say that it provides partial abstraction. 
ü  If the class is having few abstract methods and few concrete methods then declare it as abstract class.
·        Interfaces

ü  An interface can have methods and variables just like the class but the methods declared in interface are by default abstract (only method signature, no body). Interfaces are used for 100% abstraction.
ü  Since methods in interfaces do not have body, they have to be implemented by the class before you can access them.
ü  The class that implements interface must implement all the methods of that interface.
ü  Using interfaces we can achieve multiple inheritance, as a class can implement more than one interfaces, however it cannot extend more than one classes.
ü  Interface declaration
interface MyInterface
{
   /* All the methods are public abstract by default
    * Note down that these methods are not having body
    */
   public void method1();
   public void method2();
}

What are marker interfaces? Explain Serializable interface?

  • Marker interface is an empty interface with no field or methods.
  • Serializable, Clonnable and Remote interface are examples of marker interface.
  • Marker interface in Java e.g. Serializable, Clonnable and Remote is used to indicate something to compiler or JVM that the class implementing any of these would have some special behaviour. Hence, if the JVM sees a class is implementing the Serializable interface it does some special operation on it and writes the state of the object into object stream.
  • A normal interface specifies functionality which an implementing class must implement. But a marker interface does not follow that pattern. On the other side, the implementing class defines the behaviour.
  • The serializable interface provides a mechanism of object serialization where an object is represented as a sequence of bytes.

1 comment: