Java Interview Questions

How do we find version of java in our machine?

Terminal Command: java -version

What is the difference between JVM, JDK and JRE?

JVM: Java Virtual Machine 

It is an abstract machine which provides the runtime environment in which java byte code can be executed.JVMs are available for many hardware and software platforms (so JVM is platform dependent).

JRE : Java Runtime Environment 

JRE stands for Java Runtime Environment. It is the implementation of JVM.

JDK : Java Development Kit - It contains JRE + development tools.

What is class?

A class is a template/Blueprint for creating object.

What is object?

An object is a software bundle of variables and related methods.

OOPS- APIE-Abstraction, Polymorphism, Inheritance and, Encapsulation

Abstraction is a process of hiding the implementation details and showing only functionality to the user.

Abstraction lets you focus on what the object does instead of how it does it.

Method: An abstract method is a method that is declared, but contains no method body

Abstract: Class - Abstract classes which contains one or more Abstract method

Polymorphism: Poly means many forms. 


1- Code Reusability

2- Code defined in one class to be reused in another class.

Inheritance represents the IS-A relationship, also known as parent-child relationship.

Encapsulation: Data in the class is hidden away from all the other classes

What is inheritance?

Code Reusability - Code defined in one class to be reused in another class.

Why?- To use polymorphism. To promote code reuse

one object acquires all the properties and behaviors of parent object.

Can a class extends multiple classes in java?

No, one class cannot extends two classes in Java to avoid confusion. (Diamond complex)


1- Interfaces are like a 100% abstract superclass that defines the method subclass must support.

2- Defines a contract that implemented class must support

3- All methods in interface are abstract 

4- A concrete class must implements the interface

5- Any concrete class that implements that interface must agree to write code for   Interface

6- All methods in interfaces are public and abstract

7- All variable in interface must be public, static, and final- ( can declare constant only)

8- Interface can be implemented by any class, from any inheritance tree.

Interface constant - public , static , and final

Why are interface variables static, final, and public by default in Java?

Since interface does not have a direct object, the only way to access them is using a class that implements interface,  and hence that is why if interfaces variables exist , it should be static otherwise it won't be accessible at all to outside world. Now since it is static, it can hold only one value and any classes that implements it can change it and hence it will be all mess. So if at all there is an interface variable, it will be implicitly static, final, and public.

Kind of exceptions in java

1- Checked - Checked exceptions are those which java compiler forces us to catch. - FileNotFoundException

2- Unchecked - Happens at runtime, No errors at compile time. For Eg: ArrayOutOfBoundExceptions

Difference between final, finally , finalize

1 Final- Final is a keyword. Variable declared as final cannot be changed. Java classes declared as final cannot be extended. Final methods cannot be overridden,

2 Finally- Finally is a block. The finally block always executes when the try block executes.

3 Finalize - Finalize is a method used by garbage collector.

Difference between == and equals method

1. ==  (Reference / Address comparison c)  

Comparing two object references using == evaluates to true only when both reference refer to same object. Looks for location. 

String obj1 = new String (“xyz”);

String obj2 = new String (“xyz”);

(obj1==ob2) - False because reference are different.

2. equals() method - Content Comparison 

Looks for content, not the location 

String obj1 = new String(“xyz”);

String obj2 = new String (“xyz”);

(obj1.equals(ob2)) - true because content are same.

Define Static

Static Keyword is used to refer the common property of all objects. All static members exist before you make a new instance of class.

What is static variable, method?

The static variable can be used to refer the common property of all objects (that is not unique for each object) e.g. company name of employees, college name of students etc. The static variable gets memory only once in class area at the time of class loading.

Static method- Static methods are method that does not require an object to call the method. You can call static methods by using class name.   

• A static method belongs to the class rather than object of a class.

• A static method can be invoked without the need for creating an instance of a class.

• static method can access static data member and can change the value of it.

Public static void main -- explain each one of these

1 Public- When a method declared as public, it means all other class can access the method . 

2 Static : No instance needed to call main method because of its static nature 

3 Void means there is no return value

4 Main- Method name ( Name of the method )

Types of Class Access Modifiers

1- Default -  Can only be seen by all the classes in the same packages

2- private-  Class does not have private access 

3- public- All classes from all other packages can access to public class , but that class need to import package. 

4- protected- Class does not have protected access 

Non Access- 

1.Abstract- Abstract class can  never be instantiated, have to be extended. Then why ? because the class might be just too well abstract. 

2. strictfp- IEEE 754 standard rules for floating points 

3. Final class cannot be subclass/Extend, Then Why? - when we need absolutely guarantee that none of the method in that class ever be overridden.  For example String class.   We can create Final class only in case of safety and security.



Accessible in the same package

Accessible in different package






Yesonly if the class extends the main class








What is polymorphism in java?

Polymorphism means many form or polymorphic.

There are to type of polymorphism in Java

1. Runtime Polymorphism: 

Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an overridden method is resolved at runtime rather than compile-time.

In this process, an overridden method is called through the reference variable of a superclass.

2. Compile time polymorphism: If you overload static method in java, it is the example of compile time polymorphism

We can perform polymorphism in java by method overloading and method overriding.    

1- Overriding - Is the concept of having methods of same name and same signature/parameter/argument in the different classes.

7a) why we override the method? - Ans-: Benefit of overriding is the ability to define behavior that’s specific to a particular subclass type. 

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

Difference Between Abstract class and Interface?

1. Interface may implement several interfaces but abstract class may extend only one abstract class.

2. Interface can have abstract method only. On the other hand abstract class can have abstract and non-abstract methods.

3. Variables declared in a java Interfaces is by default final. An abstract class can have non-final variable.

4. Java interface should be implemented using keywords “implements”, A java abstract class should be extended using keyword “extends”.

Why do we need interface?

In Java to implement multiple inheritances we use interfaces.

If we have a abstract class why do we need interface?

Implementing an interface is more flexible that extending an abstract class. You can only extend a single class but you can implement many interfaces. Class variables, however, only have one copy of the variable(s) shared with all instances of the class.

Difference between class variable and instance variable?

Instance Variables: Instance variable used by Object to store their state :

Instance variables belong to an instance of a class. Another way of saying that is instance variables belong to an object, since an object is an instance of a class. Every object has its own copy of the instance variables.

Class Variable:

These are also known as static member variables and there's only one copy of that variable that is shared with all instances of that class. If changes are made to that variable, all other instances will see the effect of the changes.

What is static variable/Method/?

Static variable is also called class variable.  Used to hold a value that may be common to all instance of a class.

- Static method- Static methods are method that does not require an object to call the method. 

You can call static methods by using class name. 

Can constructor be a private?

Yes, a constructor can be private.

Tell me the way of accessing some method in class?

1. Accessing a method using reference of class

2. Through Inheritance

What is Wrapper class? How many wrapper classes in java tell me the name?

Wrapper classes are classes that allow primitive types to be accessed as objects.

Wrapper class for every primitives in java - 8 wrapper class

Boolean, Byte, Character, Double, Float, Integer, Long, and Short

Difference BetweenString, String Builder, and String Buffer?

1. String is immutable whereas StringBuffer and StringBuilder are mutable.

2. StringBuffer is synchronized,StringBuilder is not.         

3. StringBuilder is faster than StringBuffer

4.Use string when the object value is not going to change.

Give 5 method’s name of object class?


Difference b/w array and arraylist?

ArrayList and Vector both use Array as a data structure internally. However there are few difference in the way they store and process the data.

(1) Synchronization - ArrayList is non synchronized which means multiple threads can work on  ArrayList at the same time. On the other hand vector is synchronized.

(2) Resize-ArrayList grows by 50% while vector grows to double its size.

(3) Performance- ArrayList gives better performance as it is non synchronize

What are pass by reference and pass by value?

Java is always pass-by-value. The difficult thing can be to understand that Java passes objects as references and those references are passed by value.

What is constructor?

Constructor in java is a special type of method that is used to initialize the object.

Java constructor is invoked at the time of object creation. It constructs the values i.e. provides data for the object that is why it is known as constructor.

Default constructor provides the default values to the object like 0, null etc. depending on the type.

1. Constructor name must be same as its class name

2. Constructor must have no explicit return type

There are two types of constructors:

1. Default constructor (no-arg constructor)

2. Parameterized constructor

Does constructor return any values: Yes, Current class instance

What is the difference between a constructor and a method?

Constructor: Constructor is special method, which runs every time when you create an instance of the class.

A constructor is a block of code with the same name of its defining class without return type.

• A constructor is used to create objects of a class. A method is an ordinary member in a class.

• Constructor does not have a return type. A method should have a return type.

• Constructor name is the name of the class. A method name should not be the name of the class

• Constructor is invoked at the time of creation of the class. Method need to be invoked in another method by using the dot operator.

• Constructor can not have ‘return’ statement. All methods that return non-void return type should have ‘return’ statement.

Can you explain why a constructor doesn't have return type?

The primary goal of a constructor is to create an object. Though the constructor resembles a method, its explicit purpose is to initialize the instance variables. Hence a constructor does not have return type. 

What is exceptions handling?

The exception handling in java is one of the powerful mechanism to handle the runtime errors so that normal flow of the application can be maintained.

The core advantage of exception handling is to maintain the normal flow of the application.

What are Checked and UnChecked Exception?

1 Checked- the classes that extend Throwable class except RuntimeException and Error are known as checked exceptions e.g.IOException, SQLException etc. Checked exceptions are checked at compile-time..

2- the classes that extend RuntimeException are known as unchecked exceptions e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at compile-time rather they are checked at runtime.

  ex:- ArrayOutOfBoundsExcception,NullPointerException,ArithmaticException,DivideByZeroException.

Use of Finally?

Finally- finally is a block. The finally block always executes when the try block executes.

Try, Catch and Finally combinations-

Try- try is used to define a block of code in which exceptions may occur. This is also called guarded region

Catch- A block of code that handles exceptions.

Finally- finally is a block. The finally block always executes when the try block executes.

What is serialization? And how do I serialize an object in a file?

Process of storing contains of object into a file known as serialization.

What is a singleton class?

Singleton class means that any given time only one instance of the class is present, in one JVM.

Can Abstract class can have a constructor?

Abstract class can have a constructor. But as we can't instantiate abstract class, we can't access it through the object.

What is this reference?

The reference this always refers to the currently object. 

Can access modifiers be applied to local variables?

No (Limited scope)

1- only one modifier that can ever be applied to local variables- Final

What is synchronized methods?

Synchronized method can be accessed by only one thread at a time. For example Methods of StringBuffer class.

What is shadowing reference to local variable?

Declare a local variable with the same name as instance variable known as shadowing.

Why we use enum?

To restrict a variable to having few predefined values.

Benefit of encapsulation?

Encapsulation gives you ability to make change in your implementation code without breaking the code of others who use your code.

Is reference variable can be declare as a interface type?

Yes, reference variable can be declared both class type and interface type. If the variable declared as an interface type, it can reference any object of any class that implements the interface.

Define variable Scope-

1 Static Variable ( Class Variable)- have the longest scope , created when class is loaded to JVM,  

2 Instance Variable,- created when new instance is created

3 Local Variable- As long as their method remains on the stack.

What is use of synchronized keyword?

Synchronized is the keyword for methods. 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.

What is transient variable?

If you mark an instance variable as transient, you are telling to JVM to skip this variable at the time of serialization. 

Explain variable of the Interface?

Variables of the Interface are always public,static and final.  Static - because Interface cannot have any instance. and final - because we do not need to change it. 

What is difference between Error and Exception?

An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error. These JVM errors and you can not repair them at runtime.Though error can be caught in catch block but the execution of application will come to a halt and is not recoverable.

While exceptions are conditions that occur because of bad input etc. e.g. FileNotFoundException will be thrown if the specified file does not exist. Or a NullPointerException will take place if you try using a null reference. In most of the cases it is possible to recover from an exception (probably by giving user a feedback for entering proper values etc.)

Difference between Throw and Throws?

Throws is a keyword (method signature). When a method is capable of causing an exception and if that method cannot handle it then this exception class must be specified in the method signature using throws clause so that the caller of this method can handle this exception. Throw is used to throw an exception explicitly

Difference between array and array list?

1. The capacity of an Array is fixed on the other hand ArrayList can increase and decrease size dynamically.

2. An Array is a collection of similar item on the other hand ArrayList can hold item of different type

3. An Array can have multiple dimensions whereas ArrayList always has one dimension

What are the different states of a thread's life cycle?

The different states of threads are as follows:

1. New – The thread is in new state if you create an instance of Thread class but before the invocation of start() method.

2. Runnable – The thread is in runnable state after invocation of start() method, but the thread scheduler has not selected it to be the running thread. 

3. Running – The thread is in running state if the thread scheduler has selected it.

4. Waiting/Blocked/Sleeping – This is the state when the thread is still alive, but is currently not eligible to run.

5. Dead – A thread is in terminated or dead state when its run() method exits.

Why string class is final or immutable in java?

One advantage of immutable objects is that

You can share duplicates by pointing them to a single instance.

1. Security: the system can hand out sensitive bits of read-only information without worrying that they will be altered

2. Performance: immutable data is very useful in making things thread-safe.

3. Safety and Security.

Why are interface variables static and final by default?

Static - Interface can not be instantiated.

No instance exists. 

Final - Non Changeable  

What are the primitives data types in java

There are 8 types of primitives in Java 

1. boolean, the type whose values are either true or false

2. char, the character type whose values are 16-bit Unicode characters

The arithmetic types:

The integral types:




The floating-point types:



What is composition?

Holding the reference of the other class within some other class is known as composition.

What are Super keywords?

The super keyword in java is a reference variable, which is used to refer immediate parent class object.

Whenever you create the instance of subclass, an instance of parent class is created implicitly which is referred by super reference variable.Super can be used to refer immediate parent class instance variable.Super can be used to invoke immediate parent class method.Super() can be used to invoke immediate parent class constructor.

What is Upcasting in Java?

When a reference variable of Parent class refers to the object of Child class, it is known as upcasting. For example:

class A {


class B extends A{


A a = new B(); // This is know as Upcasting 

What is a purpose of toString() method in java?

1. toString() method belongs to object class.

2. Print method make calls to toString method. 

3. It will called once when we try to print object

4. By default it will print classNmae@Hexadecimal.

5. toString()method is used to read meaningful details about the object

What is serialization?

Serialization in java is a mechanism of writing the state of an object into a byte stream.

What is multithreading?

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

What is thread , provide two ways create a thread in java?

A thread is a lightweight sub process, a smallest unit of processing. It is a separate path of execution.

How to create thres

1- Implementing runnable interface

2- Extending Thread class

Types of Threads

User Threads and Daemon Threads

Diff : JVM exits an application only when all user threads are complete. 

JVM does not care about letting daemon threads complete. 

Example of the Daemon thread is the Garbage Collector run by jvm to reclaim the unused memory by the application. The Garbage collector code runs in a Daemon thread which terminates as all the user threads are done with their execution

Methods in Thread class to manage threads. ( creating , starting, and pausing )

start() , yield() , sleep() , run() 

What is difference between thread and process?

Differences between threads and processes are:-

1. Threads share the address space of the process that  created it; processes have their own address.

2. Threads have direct access to the data segment of its process; processes have their own copy of the data segment of the parent process.

3. Threads can directly communicate with other threads of its process; processes must use interprocess communication to communicate with sibling processes.

4. Threads have almost no overhead; processes have considerable overhead.

5. New threads are easily created; new processes require duplication of the parent process.

What all constructors are present in the Thread class?

Thread( )

Thread(Runnable target)

Thread(Runnable target, String name)

Thread(String name)

What is use of synchronized keyword?

synchronized keyword can be applied to static and nonstatic 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

Can a class have both Synchronized and non-synchronized methods?

Yes a class can have both synchronized and non-synchronized methods.

What is race condition?

Race condition occurs when , multiple threads can access the same resource. Resource for example - object’s instance variable. 

Why do we override hashCode and equals method?

To save object of my class as a key to hashmap. 


1. ArrayList implements List Interface 

2. ArrayList can contains duplicate items 

3. Maintains insertion order

4. ArrayList Class in not synchronized 

5. Allows random access because it uses indexing 

6. Manipulation is slow because lot of shifting requires after removing of items. 

What are the constructor for ArrayList ?

There are three constructor in ArrayList 

1. ArrayList() - Build empty arrayList

2. ArrayList( Collection c ) - initialize by collection c

3. ArrayList(int capacity ) -  initialize by initial capacity of array


1. Can contains duplicate

2. Maintains insertion order

3. Non synchronized 

4. Manipulation is fast because no shifting requires 

What is the difference between ArrayList and Vector?

1. ArrayList is not synchronized but Vector is. 

2. ArrayList increases its size by 50%, vector doubles its size. 

What is the difference between ArrayList and LinkedList?

1. ArrayList uses a dynamic array and LinkedList uses doubly linked list. 

2. Arraylist is not efficient for manipulation becauses a lot of shifting is required. LinkedList is efficient for manipulation. 

3. Arraylist is better to store and fetch data. Linked is better to manipulate data. 

What is the difference Iterator and List Iterator?

1. Iterator traverses the elements in forward direction only. ListIterator traverses the element in backward and forward directions both. 

2. Iterator can be used in List, set and Queue. ListIterator can be used in List only. 

What is the difference between Iterator and Enumeration?

1. Iterator can traverse legacy and non-legacy elements. Enumeration can traverse only legacy element. 

2. Iterator is fail-fast. Enumeration is not fail-fast. 

3. Iterator is slower than Enumeration.

What is the difference between List and Set?

List can contain duplicate elements.

What is the difference between Set and Map?

Set - value 

Map - Key value pair 

What is the difference between HashSet and HashMap?

HashSet - contains value 

HashMap - Key value pair

What is the difference between HashMap and TreeMap?

HashMap maintains no order but TreeMap maintains ascending order.

What is the difference between HashMap and HashTable?

1. HashMap is not synchronized, HashTable is synchronized. 

2. HashMap can contain one null key and multiple null values , Hashtable cannot contains any null key or null value. 

What is the difference between Collection and Collections?

1. Collection is interface whereas Collections is a class. 

2. Collection interface provides normal functionality of data structure to List ,Set and Queue. But Collections class is to sort and synchronize collection elements. 

What is the difference between Comparable and Comparator?

1. Comparable provides only one sort of sequence. Comparator provides multiple sort of sequences. 

2. Comparable provides one method named CompareTo(). Comparator provides one method named compare().

3. Comparable found in java.lang package. Comparator found in java.util package. 

What does the hashCode() method?

Returns hash code value of the object. ( AN integer Number )

What are the advantages of generic collection?

If we use generic class, we don’t need type casting. It is typesafe and checked at compile time.