Interview GURU

Java interview questions

There are most popular Java interview questions asked in many companies.

1. What are the features in JAVA?

  • Oops concepts
    • Object-oriented
    • Inheritance
    • Encapsulation
    • Polymorphism
    • Abstraction
  • Platform independent: A single program works on different platforms without any modification.
  • High Performance: JIT (Just In Time compiler) enables high performance in Java. JIT converts the bytecode into machine language and then JVM starts the execution.
  • Multi-threaded: A flow of execution is known as a Thread. JVM creates a thread which is called main thread. The user can create multiple threads by extending the thread class or by implementing Runnable interface.

2. How does Java enable high performance?

Java uses Just In Time compiler to enable high performance. JIT is used to convert the instructions into bytecodes.

3. What do you mean by Constructor?

The points given below explain what a Constructor is in detail:
  • When a new object is created in a program a constructor gets invoked corresponding to the class.
  • The constructor is a method which has the same name as class name.
  • If a user doesn’t create a constructor implicitly a default constructor will be created.
  • The constructor can be overloaded.
  • If the user created a constructor with a parameter then he should create another constructor explicitly without a parameter.

4. What is meant by Local variable and Instance variable?

Local variables are defined in the method and scope of the variables that have existed inside the method itself.

An instance variable is defined inside the class and outside the method and scope of the variables exist throughout the class.

5. What is a Class?

All Java codes are defined in a class. A Class has variables and methods.

Variables are attributes which define the state of a class.

Methods are the place where the exact business logic has to be done. It contains a set of statements (or) instructions to satisfy the particular requirement.

public class Addition { //Class name declaration 
    //Variable declaration 
    int a = 5; 
    int b= 5; 

    public void add() { 
    //Method declaration int c = a+b; 

6. What is an Object?

An instance of a class is called object. The object has state and behavior.

Whenever the JVM reads the “new()” keyword then it will create an instance of that class.

public class Addition {    
    public static void main(String[] args) {   
         Addion add = new Addition();
        //Object creation     

7. What are the Oops concepts?

Oops concepts include:
  • Inheritance
  • Encapsulation
  • Polymorphism
  • Abstraction
  • Interface

8. What is Inheritance?

Inheritance means one class can extend to another class. So that the codes can be reused from one class to another class.

Existing class is known as Super class whereas the derived class is known as a sub class.

Super class:
public class Manupulation() {}
Sub class:
public class Addition extends Manipulation(){}

Inheritance is applicable for public and protected members only. Private members can’t be inherited.

9. What is Encapsulation?

Purpose of Encapsulation:
  • Protects the code from others.
  • Code maintainability.

We are declaring ‘a' as an integer variable and it should not be negative.

public class Addition() { 
int a=5; 
If someone changes the exact variable as “a = -5” then it is bad.

In order to overcome the problem we need to follow the below steps:
  • We can make the variable as private or protected one.
  • Use public accessor methods such as set<property> and get<property>.
So that the above code can be modified as:

public class Addition() { 
private int a = 5; //Here the variable is marked as private 

10. What is Polymorphism?

Polymorphism means many forms.

A single object can refer the super class or sub-class depending on the reference type which is called polymorphism.


Public class Manipulation() { //Super classpublic 
    void add(){}

public class Addition extends Manipulation(){ // Sub classpublic 
    void add(){}
    public static void main(String args[]) {
        Manipulation addition = new Addition();//Manipulation is reference type and Addition is reference type
Using Manipulation reference type we can call the Addition class “add()” method. This ability is known as Polymorphism.

Polymorphism is applicable for overriding and not for overloading.

11. What is meant by Method Overriding?

Method overriding happens if the sub class method satisfies the below conditions with the Super class method:
  • Method name should be same
  • Argument should be same
  • Return type also should be same
The key benefit of overriding is that the Sub class can provide some specific information about that sub class type than the super class.


public class Manipulation{ //Super class
    public void add(){

Public class Addition extends Manipulation(){
    Public void add(){
    Public static void main(String args[]){
    Manipulation addition = new Addition(); //Polimorphism is applied
    addition.add(); // It calls the Sub class add() method
addition.add() method calls the add() method in the Sub class and not the parent class. So it overrides the Super class method and is known as Method Overriding.

12. What is meant by Overloading?

Method overloading happens for different classes or within the same class.

For method overloading, subclass method should satisfy the below conditions with the Super class method (or) methods in the same class itself:
  • Same method name
  • Different argument type
  • May have different return types


public class Manipulation{ //Super class
    public void add(String name){ //String parameter

Public class Addition extends Manipulation(){
    Public void add(){//No Parameter
    Public void add(int a){ //integer parameter
    Public static void main(String args[]){
    Addition addition = new Addition(); 
Here the add() method having different parameters in the Addition class is overloaded in the same class as well as with the super class.

Note: Polymorphism is not applicable for method overloading.

13. What is meant by Interface?

Multiple inheritance cannot be achieved in java. To overcome this problem Interface concept is introduced.

An interface is a template which has only method declarations and not the method implementation.


Public abstract interface IManupulation { //Interface declaration
Public abstract void add();//method declaration

public abstract void subtract();

  • All the methods in the interface are internally public abstract void.
  • All the variables in the interface are internally public static final that is constants.
  • Classes can implement the interface and not extends.
  • The class which implements the interface should provide an implementation for all the methods declared in the interface.

public class Manupulation implements IManupulation { //Manupulation class uses the interface

Public void add(){ …………… } 
Public void subtract(){ ……………. } 

14. What is meant by Abstract class?

We can create the Abstract class by using “Abstract” keyword before the class name. An abstract class can have both “Abstract” methods and “Non-abstract” methods that are a concrete class.

Abstract method:

The method which has only the declaration and not the implementation is called the abstract method and it has the keyword called “abstract”. Declarations are the ends with a semicolon.

public abstract class Manupulation {

public abstract void add();//Abstract method declaration

Public void subtract(){}
  • An abstract class may have a Non- abstract method also.
  • The concrete Subclass which extends the Abstract class should provide the implementation for abstract methods.

15. Difference between String, String Builder, and String Buffer.

String: String variables are stored in “constant string pool”. Once the string reference changes the old value that exists in the “constant string pool”, it cannot be erased.

More details...

16. Explain about Public and Private access specifiers.

Methods and instance variables are known as members.

More details...

17. Difference between Default and Protected access specifiers.

Default: Methods and variables declared in a class without any access specifiers are called default.

Default members in Class A are visible to the other classes which are inside the package and invisible to the classes which are outside the package.

So Class A members are visible to the Class B and invisible to the Class C.



Protected is same as Default but if a class extends then it is visible even if it is outside the package.

Class A members are visible to Class B because it is inside the package. For Class C it is invisible but if Class C extends Class A then the members are visible to the Class C even if it is outside the package.

18. Difference between Abstract class and Interface.

Difference between Abstract Class and Interface are as follows:

Abstract Class:
  • Abstract classes have a default constructor and it is called whenever the concrete subclass is instantiated.
  • Contains Abstract methods as well as Non-Abstract methods.
  • The class which extends the Abstract class shouldn’t require implementing all the methods, only Abstract methods need to be implemented in the concrete sub-class.
  • Abstract Class contains instance variables.

  • Doesn’t have any constructor and couldn’t be instantiated.
  • Abstract method alone should be declared.
  • Classes which implement the interface should provide the implementation for all the methods.
  • The interface contains only constants.

19. What is mean by Collections in Java?

Collection is a framework that is designed to store the objects and manipulate the design to store the objects.

Collections are used to perform the following operations:
  • Searching
  • Sorting
  • Manipulation
  • Insertion
  • Deletion

A group of objects is known as collections. All the classes and interfaces for collecting are available in Java utile package.

20. What are all the Classes and Interfaces that are available in the collections?

Given below are the Classes and Interfaces that are available in Collections:

  • Collection
  • List
  • Set
  • Map
  • Sorted Set
  • Sorted Map
  • Queue

  • Lists:
  • Array List
  • Vector
  • Linked List

  • Hash set
  • Linked Hash Set
  • Tree Set

  • Hash Map
  • Hash Table
  • Tree Map
  • Linked Hashed Map

  • Priority Queue

21. What is meant by Ordered and Sorted in collections?

It means the values that are stored in a collection is based on the values that are added to the collection. So we can iterate the values from the collection in a specific order.

Sorting mechanism can be applied internally or externally so that the group of objects sorted in a particular collection is based on properties of the objects.

22. Explain about the different lists available in the collection.

Values added to the list is based on the index position and it is ordered by index position. Duplicates are allowed.

Types of Lists are:

Array List:
  • Fast iteration and fast Random Access.
  • It is an ordered collection (by index) and not sorted.
  • It implements Random Access Interface.

It is same as Array List.
  • Vector methods are synchronized.
  • Thread safety.
  • It also implements the Random Access.
  • Thread safety usually causes a performance hit.

Vector also maintains the insertion order and accepts the duplicates.

Linked List:
  • Elements are doubly linked to one another.
  • Performance is slow than Array list.
  • Good choice for insertion and deletion.
  • In Java 5.0 it supports common queue methods peek( ), Pool ( ), Offer ( ) etc.

Maintains the insertion order and accepts the duplicates.

23. Explain about Set and their types in a collection?

Set cares about uniqueness. It doesn’t allow duplications. Here “equals ( )” method is used to determine whether two objects are identical or not.

Hash Set:
  • Unordered and unsorted.
  • Uses the hash code of the object to insert the values.
  • Use this when the requirement is “no duplicates and don’t care about the order”.

Doesn’t follow any insertion order. Duplicates are not allowed.

Linked Hash set:
  • An ordered version of the hash set is known as Linked Hash Set.
  • Maintains a doubly-Linked list of all the elements.
  • Use this when the iteration order is required.

Maintains the insertion order in which they have been added to the Set. Duplicates are not allowed.

Tree Set:
  • It is one of the two sorted collections.
  • Uses “Read-Black” tree structure and guarantees that the elements will be in an ascending order.
  • We can construct a tree set with the constructor by using comparable (or) comparator.

TreeSet sorts the elements in an ascending order. And duplicates are not allowed.

24. Explain about Map and their types.

Map cares about unique identifier. We can map a unique key to a specific value. It is a key/value pair. We can search a value, based on the key. Like set, Map also uses “equals ( )” method to determine whether two keys are same or different.

Hash Map:
  • Unordered and unsorted map.
  • Hashmap is a good choice when we don’t care about the order.
  • It allows one null key and multiple null values.

Duplicate keys are not allowed in Map.

Doesn’t maintain any insertion order and is unsorted.

Hash Table:
  • Like vector key, methods of the class are synchronized.
  • Thread safety and therefore slows the performance.
  • Doesn’t allow anything that is null.

Duplicate keys are not allowed.

 Linked Hash Map:
  • Maintains insertion order.
  • Slower than Hash map.
  • Can expect a faster iteration.

Duplicate keys are not allowed.

  • Sorted Map.
  • Like Tree set, we can construct a sort order with the constructor.

It is sorted in ascending order based on the key. Duplicate keys are not allowed.

25. Explain the Priority Queue.

Queue Interface

Priority Queue: Linked list class has been enhanced to implement the queue interface. Queues can be handled with a linked list. Purpose of a queue is “Priority-in, Priority-out”.

Hence elements are ordered either naturally or according to the comparator. The elements ordering represents their relative priority.

26. What is mean by Exception?

An Exception is a problem that can occur during the normal flow of an execution. A method can throw an exception when something wails at runtime. If that exception couldn’t be handled, then the execution gets terminated before it completes the task.

If we handled the exception, then the normal flow gets continued. Exceptions are a subclass of java.lang.Exception.

Example for handling Exception:
try {
//Risky codes are surrounded by this block
} catch(Exception e) {
//Exceptions are caught in catch block

27. What are the types of Exceptions?

Two types of Exceptions are explained below in detail.

Checked Exception:

These exceptions are checked by the compiler at the time of compilation. Classes that extend Throwable class except Runtime exception and Error are called checked Exception.

Checked Exceptions must either declare the exception using throes keyword (or) surrounded by appropriate try/catch.

E.g. ClassNotFound Exception

Unchecked Exception:

These exceptions are not checked during the compile time by the compiler.  The compiler doesn’t force to handle these exceptions.

It includes:
  • Arithmetic Exception
  • ArrayIndexOutOfBounds Exception

28. What are the Advantages of Exception handling?

Given below are the advantages:

  • The normal flow of the execution won’t be terminated if exception got handled
  • We can identify the problem by using catch declaration

29. What are Exception handling keywords in Java?

Given below are the two Exception Handling Keywords:

When a risky code is surrounded by a try block. An exception occurring in the try block is caught by a catch block. Try can be followed either by catch (or) finally (or) both. But any one of the blocks is mandatory.

This is followed by try block. Exceptions are caught here.

This is followed either by try block (or) catch block. This block gets executed regardless of an exception. So generally clean up codes are provided here.

30. Explain about Exception Propagation.

Exception is first thrown from the method which is at the top of the stack. If it doesn’t catch, then it pops up the method and moves to the previous method and so on until they are got.

This is called Exception propagation.

public class Manipulation {
    public static void main(String[] args) {

public void add() {

From the above example, the stack looks like as shown below:

If an exception occurred in the addition() method is not caught, then it moves to the method add(). Then it is moved to the main() method and then it will stop the flow of execution. It is called Exception Propagation.

31. What is the final keyword in Java?

Final variable:

Once a variable is declared as final, then the value of the variable could not be changed. It is like a constant.


final int = 12;

Final method:

A final keyword in a method that couldn’t be overridden. If a method is marked as a final, then it can’t be overridden by the subclass.

Final class:

If a class is declared as final, then the class couldn’t be subclassed. No class can extend the final class.

32. What is a Thread?

In Java, the flow of a execution is called Thread. Every java program has at least one thread called main thread, the Main thread is created by JVM. The user can define their own threads by extending Thread class (or) by implementing Runnable interface. Threads are executed concurrently.

33. How do you make a thread in Java?

There are two ways available in order to make a thread.

#1) Extend Thread class:

Extending a Thread class and override the run method. The thread is available in java.lang.thread.

Public class Addition extends Thread {
    public void run () {}
The disadvantage of using a thread class is that we cannot extend any other classes because we have already extend the thread class. We can overload the run () method in our class.

#2) Implement Runnable interface:

Another way is implementing the runnable interface. For that we should provide the implementation for run () method which is defined in the interface.

Public class Addition implements Runnable {
    public void run () {}

34. Explain about join () method.

Join () method is used to join one thread with the end of the currently running thread.

public static void main (String[] args) {
    Thread t = new Thread ();
    t.start ();
    t.join ();

From the above code, the main thread started the execution. When it reaches the code t.start() then ‘thread t’ starts the own stack for the execution. JVM switches between the main thread and ‘thread t’.

Once it reaches the code t.join() then ‘thread t’ alone is executed and completes its task, then only main thread started the execution.

It is a non-static method. Join () method has overloaded version. So we can mention the time duration in join () method also “.s”.

35. What does yield method of the Thread class do?

A yield () method moves the currently running thread to a  runnable state and allows the other threads for execution. So that equal priority threads have a chance to run. It is a static method. It doesn’t release any lock.

Yield () method moves the thread back to the Runnable state only, and not the thread to sleep (), wait () (or) block.

public static void main (String[] args) {
    Thread t = new Thread ();t.start ();
public void run() {

36. Explain about wait () method.

wait () method is used to make the thread to wait in the waiting pool. When a wait () method is executed during a thread execution then immediately the thread gives up the lock on the object and goes to the waiting pool. Wait () method tells the thread to wait for a given amount of time.

Then the thread will wake up after notify () (or) notify all () method is called.

Wait() and the other above-mentioned methods do not give the lock on the object immediately until the currently executing thread completes the synchronized code. It is mostly used in synchronization.

public static void main (String[] args) {
    Thread t = new Thread ();
    t.start ();

    Synchronized (t) {

37. Difference between notify() method and notifyAll() method in Java.

Given below are few differences between notify() method and notifyAll() method
notify() is used to send a signal to wake up a single thread in the waiting pool.
notifyAll() sends the signal to wake up all the threads in a waiting spool.

38. How to stop a thread in java? Explain about sleep () method in a thread?

We can stop a thread by using the following thread methods.
  • Sleeping
  • Waiting
  • Blocked

More details...

39. When to use Runnable interface Vs Thread class in Java?

If we need our class to extend some other classes other than the thread then we can go with the runnable interface because in java we can extend only one class.

If we are not going to extend any class then we can extend the thread class.

40. Difference between start() and run() method of thread class.

Start() method creates new thread and the code inside the run () method is executed in the new thread. If we directly called the run() method then a new thread is not created and the currently executing thread will continue to execute the run() method.

41. What is Multi-threading?

Multiple threads are executed simultaneously. Each thread starts their own stack based on the flow (or) priority of the threads.

More details...

42. Explain thread life cycle in Java.

Thread has the following states:
  • New
  • Runnable
  • Running
  • Non-runnable (Blocked)
  • Terminated

More details...

43. What is Synchronization?

Synchronization makes only one thread to access a block of code at a time. If multiple thread accesses the block of code, then there is a chance for inaccurate results at the end. To avoid this issue, we can provide synchronization for the sensitive block of codes.

The synchronized keyword means that a thread needs a key in order to access the synchronized code.

Locks are per objects. Every Java object has a lock. A lock has only one key. A thread can access a synchronized method only if the thread can get the key to the objects lock.

For this, we use “Synchronized” keyword.


public class ExampleThread implements Runnable{
    public static void main (String[] args){
        Thread t = new Thread ();
        t.start ();
    public void run(){

44. What is the disadvantage of Synchronization?

Synchronization is not recommended to implement all the methods. Because if one thread accesses the synchronized code then the next thread should have to wait. So it makes slow performance on the other end.

45. What is meant by Serialization?

Converting a file into a byte stream is known as Serialization. The objects in the file is converted to the bytes for security purposes. For this, we need to implement interface. It has no method to define.

Variables that are marked as transient will not be a part of the serialization. So we can skip the serialization for the variables in the file by using a transient keyword.

46. What is the purpose of a transient variable?

Transient variables are not part of the serialization process. During deserialization, the transient variables values are set to default value. It is not used with static variables.

transient int numbers;

47. Which methods are used during Serialization and Deserialization process?

ObjectOutputStream and ObjectInputStream classes are higher level package. We will use them with lower level classes FileOutputStream and FileInputStream.

ObjectOutputStream.writeObject —->Serialize the object and write the serialized object to a file.

ObjectInputStream.readObject —> Reads the file and deserializes the object.

To be serialized, an object must implement the serializable interface. If superclass implements Serializable, then the subclass will automatically be serializable.

48. What is the purpose of a Volatile Variable?

Volatile variable values are always read from the main memory and not from thread's cache memory. This is used mainly during synchronization. It is applicable only for variables.

volatile int number;

49. Difference between Serialization and Deserialization in Java.

Serialization is the process which is used to convert the objects into byte stream.
An object is serialized by writing it an ObjectOutputStream.
Deserialization is the opposite process of serialization where we can get the objects back from the byte stream.
An object is deserialized by reading it from an ObjectInputStream.

50. What is SerialVersionUID?

Whenever an object is Serialized, the object is stamped with a version ID number for the object class. This ID is called the  SerialVersionUID. This is used during deserialization to verify that the sender and receiver that are compatible with the Serialization.