Tuesday, February 21, 2012

Core Java Interview Questions

In this post I have noted down some good java interview questions. These may not be the toughest questions but still come handy at the time of interview. I have also provided some link if you want more interview questions. Aand YES all Comments/feedbacks are weclomed :)

Question We have static block, constructor block and instance block. In what order will they be executed? Example adopted from here.
class Grandparent {
    // Static init block
    static {
        System.out.println("static - grandparent");

    // Instance init block
        System.out.println("instance - grandparent");

    // Constructor
    public Grandparent() {
        System.out.println("constructor - grandparent");
class Child extends Parent {
    // Constructor
    public Child() {
        System.out.println("constructor - child");

    // Static init block
    static {
        System.out.println("static - child");

    // Instance init block
        System.out.println("instance - child");
Answer: The block execution order is as:
The static initializer for a class gets run when the class is loaded. The class is first loaded when you first access it, either to create an instance, or to access a static method or field.The instance block is executed right after call to super() in constructor. The output for above example is:
static - grandparent
static - parent
static - child
instance - grandparent
constructor - grandparent
instance - parent
constructor - parent
instance - child
constructor - child

Question Can we have private constructor in Java? If yes why do we need it?
Answer: Yes we can have. It is useful when we class contains only static utility methods or only constants or type safe enumerations or is singleton. More here.

Question What do we mean by mutable and immutable object? Is String class immutable?
Answer: If we have a reference to an instance of an object and we are able to alter the content of that instance then instance is mutable (mutable object) but if we cannot alter the content then it is immutable object. String may seem mutable as we can change its content but actually it is immutable because whenever we try to change the content of String instance it creates a new String object with new value and assign it to the older reference. Also immutable objects are inherently thread-safe and need no synchronization.

Question Why is String class immutable and what are the benefits of that?
Answer: There are multiple reasons for it. Some of them are: it allows JVM to maintain String pool, it makes it thread safe etc. Check the following links for more:

Question Can we say all final classes are immutable?
Answer: NO. Final class has only on restirction that it cannot be sub-classed. It does not say anything about its content being altered.

public final class FinalMutable {
  int value;
  public void setValue(int v) { value=v; }
  public int getValue() { return value; }

Mutability is mainly concerned about the alteration of the content of the instance of that class from outside. Even in String class in java we have a field hash that is mutable and it is in fact computed and stores when hashCode() is called for the first time.
However class is still mutable as the hash field cannot be accessed directly or modified from outside of the class. http://stackoverflow.com/questions/1630321/are-all-final-class-immutable

Question What do we mean by abstract method and abstract class?
Answer: Abstract method:
1. Method does not have any body means it is declared but not implemented.
2. It cannot have curly braces (even empty) and should close with semicolon.
3. Subclasses are forced to implement this method (provided class is concrete and not abstract).
4. If there is even a single abstract method in the class, the class must be declared abstract.
5. A method cannot be abstract and (final/private/static)
Abstract Class:
1.If we have an abstract method then it must be declared abstract.
2.But we can have a abstract class without any abstract methods or having both types of methods (abstract and non-abstract).
3. The first concrete subclass of an abstract class must implement all abstract method of the superclass.
4. An abstract class can never be instantiated as its sole purpose is to be subclassed.

Question Why an abstract method can be final/private/static?
Answer: An abstract method has no implementation and supposed to be implemented by the subclass. If it must be implemented by subclass then it must support overriding behavior and should be available to subclass. If it were final it could not be changed. If it were private it would not be visible to subclass. If it were static it would be bound to the whole class and cannot be overridden in subclass.
Abstract => BIG NO for final/private/static.

Question What are the differences between an abstract class and interface?
Answer: An interface is 100% abstract class and all its variables are public,static and final and all its member functions are public and abstract. A class cannot extend more than one class but can implement more than one interfaces.
1) Unlike interfaces, abstract classes can contain fields that are not static and final, and they can contain implemented methods. Such abstract classes are similar to interfaces, except that they provide a partial implementation, leaving it to subclasses to complete the implementation. If an abstract class contains only abstract method declarations, it should be declared as an interface instead.
2)Multiple interfaces can be implemented by classes anywhere in the class hierarchy, whether or not they are related to one another in any way. Think of Comparable or Cloneable, for example.

3)Abstract classes are most commonly subclassed to share pieces of implementation. A single abstract class is subclassed by similar classes that have a lot in common (the implemented parts of the abstract class), but also have some differences (the abstract methods).

Question Can we have an abstract class implementing an interface? Can a class implement an interface and extends another class?
Answer: Yes we can have an abstract class that implements some of the methods of the interface. But it is not recommended as the class may miss some of the methods of interface and may not provide any implementation. Moreover even compiler will not complain as it assumes you may be providing some concrete class for this class.
If we have one class extending another class and implementing an interface we can implement it like:
class A extends B implements C

Question: What are various access level modifiers in Java?
Answer: The access level modifiers control the access of a field or method to other classes.There are two levels of access control:
  • At the top level—public, or package-private (no explicit modifier).
  • At the member level—publicprivateprotected, or package-private (no explicit modifier).
A public class means (it is open to public) this class is visible to all classes in the project. If a class has default or no modifier then it is package-private means visible to classes in same package.
For members other than these two (public and default) we also have private and protected modifiers. A protected member is visible to all the subclasses even to the subclasses out of this package. A private is visible in its own class.The following table shows the access to members permitted by each modifier.
Access Levels
no modifierYYNN
source: http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html

Question What are volatile and transient modifiers in Java?
Answer: The two access modifiers can be applied to fields of a class. So lets see when a variable is assigned any of these modifiers.
Transient: If a field is marked as Transient then this field won't be serialized at the time of serialization of the instance of the class (assume it implements Serializable interface). All other fields in that instance will be serialized and de-serialized normally. The Transient field at the time of de-serialization will be assigned default value (null for reference variables and zero or false for primitive types).
Volatile:  In java we can have multiple threads and each thread has its own copy of variable. Whenever any thread performs any operation only its local copy is affected. But consider a situation where we have a variable count, and we want all modifications by all thread for this variable are synchronous and consistent. In this case 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. 

Question: Can we serialize a volatile field? Can we use synchronized with it?
Answer: Volatile is a normal variable only so it can be serialized. Volatile is generally used to announce that this variable can be used by multiple threads. If we declare any variable volatile it means: 
1.The value of this variable will never be cached thread-locally: all reads and writes will go straight to "main memory";
2.Access to the variable acts as though it is enclosed in a synchornized block, synchronized on itself.

Get a global lock on the variableGet a global lock on the monitor
Update the one variable from main memoryUpdate all shared variables that have been accessed from main memory

Process some statements
Write any change of the one variable back to main memoryWrite all shared variables that have been changed back to main memory
Release the lockRelease the lock


Question: What is the use of Final keyword?
Answer: In very simple terms final means it is constant and so cannot be changed (even among multiple threads). We can have the following:
1. Final Class level variable: A field declared as final in a class must be assigned value only once in each constructor, and afterwards it cannot change.
2. Final Method: The method cannot be changed in any ways. It cannot be overridden by sub-classes as well.
3. Final Class: If a class is final then no class can extend this class. 
4. Final Object: If an object(instance) is final then once instantiated, its reference cannot be changed.

Question: If we declare our class (or variable) final we will gain better performance. Do you agree?
Answer: NO. This has been a very good myth having no proof as such. Check here.

Question: Why do we need to override equals() if we override hashCode()?
Answer: The implementation of the equals(..) method in the Object class is very shallow as it uses the == operator for comparison. So if we compares two objects for equality then unless we override equals(), the expression obj1.equals(obj2) returns true if they refer to same object.
Actually there is contract that if two objects are equal then they must have identical hashcode value also. Note that it does not say that if two objects have equal hashcode they had to be identical. They may be lying in same bucket but with different value. Hashing retrieval is mainly two step process: 1) Find the right bucket (using hashCode()) and 2) Search the bucket for the right element.

Question: Why transient variables make a mess with equals() and hashCode()
Answer: The transient variables will not be saved and will get their default value at the time of de-serialization and that makes the mess. So either keep the variables non-transient or dont use them for equality or hashcode.

Question: Why don't we call run() method directly? Why do we call start() which in turn calls run() method?
Answer: The run() is not a regular method. If we call the run() method directly, it will simply execute in the caller’s thread instead of as its own thread. Instead, we should call the start() method, which schedules the thread with the JVM.

Question: Questions about singleton design pattern in Java.

[This post is updated at regular intervals.]

Read part2 Here.

Good Links:
Interview Questions:
Other good links:


Anonymous said...

Please add more questions. I like this blog as it helps in my preparation of interview.

jaylen watkins said...

Thanks for the core java interview questions.

Interview Questions

Akhil said...

You're welcomed Jaylen. Not getting enough time now a days but surely will add some more good questions on core java :)

top 30 core java interview questions and answers said...

thanks akhil for posting these questions here..i would like to add a few more questions like:

Why Map does not extend Collection interface
Why don’t we call run() method directly? Why do we call start() method which in turn calls run() method?
what is the purpose and use of ThreadLoacal class in java

Anonymous said...

Can you provide some interview questions hybernation?

Java String object

Akhil Mittal said...

I don't have many questions on hibernate, but will try.

Abderrahmen Ben Mariem said...

Thanks for the great post.
I suggest this core java interview questions: