Top Java Programming Interview Questions

What is Java? 

Java is the high-level programming language that was developed by James Gosling in the year 1982. It is based on the principles of object-oriented programming and can be used to develop large-scale applications.

This article lists some of the most important Questions and Answers for Java programming which will set you apart in the interview process. Java is used by approx 10 Million developers worldwide to develop applications for 15 Billion devices supporting Java.

There could be multiple aspects of a question, they’ve been answered separately, so go through all the questions carefully to crack the interview.

Java programming interview questions:

Explain JDK, JRE and JVM?

It stands for Java Development Kit.It stands for Java Runtime Environment.It stands for Java Virtual Machine.
It is the tool necessary to compile, document and package Java programs.JRE refers to a runtime environment in which Java bytecode can be executed.It is an abstract machine. It is a specification that provides a run-time environment in which Java bytecode can be executed.
It contains JRE + development tools.It’s an implementation of the JVM which physically exists.JVM follows three notations: Specification, Implementation, and Runtime Instance.

Explain public static void main(String args[]) in Java.

main() in Java is the entry point for any Java program. It is always written as public static void main(String[] args).

  • public: Public is an access modifier, which is used to specify who can access this method. Public means that this Method will be accessible by any Class.
  • static: It is a keyword in java which identifies it is class-based. main() is made static in Java so that it can be accessed without creating the instance of a Class. In case, main is not made static then the compiler will throw an error as main() is called by the JVM before any objects are made and only static methods can be directly invoked via the class. 
  • void: It is the return type of the method. Void defines the method which will not return any value.
  • main: It is the name of the method which is searched by JVM as a starting point for an application with a particular signature only. It is the method where the main execution occurs.
  • String args[]: It is the parameter passed to the main method.

Why Java is platform independent?

Java is called platform independent because of its byte codes which can run on any system irrespective of its underlying operating system.

\Why Java is not 100% Object-oriented?

Java is not 100% Object-oriented because it makes use of eight primitive data types such as boolean, byte, char, int, float, double, long, short which are not objects.

What are wrapper classes in Java?

Wrapper classes convert the Java primitives into the reference types (objects). Every primitive data type has a class dedicated to it. These are known as wrapper classes because they “wrap” the primitive data type into an object of that class. Refer to the below image which displays different primitive type, wrapper class and constructor argument.

What are constructors in Java?

In Java, constructor refers to a block of code which is used to initialize an object. It must have the same name as that of the class. Also, it has no return type and it is automatically called when an object is created.

There are two types of constructors:

  1. Default Constructor: In Java, a default constructor is the one which does not take any inputs. In other words, default constructors are the no argument constructors which will be created by default in case you no other constructor is defined by the user. Its main purpose is to initialize the instance variables with the default values. Also, it is majorly used for object creation. 
  2. Parameterized Constructor: The parameterized constructor in Java, is the constructor which is capable of initializing the instance variables with the provided values. In other words, the constructors which take the arguments are called parameterized constructors.

What is singleton class in Java and how can we make a class singleton?

Singleton class is a class whose only one instance can be created at any given time, in one JVM. A class can be made singleton by making its constructor private.

What is the difference between Array list and vector in Java?

Array List is not synchronized. Vector is synchronized.
Array List is fast as it’s non-synchronized.Vector is slow as it is thread safe.
If an element is inserted into the Array List, it increases its Array size by 50%.Vector defaults to doubling size of its array.
Array List does not define the increment size.Vector defines the increment size.
Array List can only use Iterator for traversing an Array List.Vector can use both Enumeration and Iterator for traversing.

What is the difference between equals() and == in Java?

Equals() method is defined in Object class in Java and used for checking equality of two objects defined by business logic.

“==” or equality operator in Java is a binary operator provided by Java programming language and used to compare primitives and objects. public boolean equals(Object o) is the method provided by the Object class. The default implementation uses == operator to compare two objects. For example: method can be overridden like String class. equals() method is used to compare the values of two objects.

Can java be said to be the complete object-oriented programming language?

It is not wrong if we claim that java is the complete object-oriented programming language. Because Everything in Java is under the classes. And we can access that by creating the objects.

But also if we say that java is not a completely object-oriented programming language because it has the support of primitive data types like int, float, char, boolean, double, etc.

Now for the question: Is java a completely object-oriented programming language? We can say that – Java is not a pure object-oriented programming language, because it has direct access to primitive data types. And these primitive data types don’t directly belong to the Integer classes.

How is Java different from C++?

  • C++ is only a  compiled language, whereas Java is compiled as well as an interpreted language.
  • Java programs are machine-independent whereas a c++ program can run only in the machine in which it is compiled. 
  • C++ allows users to use pointers in the program. Whereas java doesn’t allow it. Java internally uses pointers. 
  • C++ supports the concept of Multiple inheritances whereas Java doesn’t support this. And it is due to avoiding the complexity of name ambiguity that causes the diamond problem.

Pointers are used in C/ C++. Why does Java not make use of pointers?

Pointers are quite complicated and unsafe to use by beginner programmers. Java focuses on code simplicity, and the usage of pointers can make it challenging. Pointer utilization can also cause potential errors. Moreover, security is also compromised if pointers are used because the users can directly access memory with the help of pointers.

Thus, a certain level of abstraction is furnished by not including pointers in Java. Moreover, the usage of pointers can make the procedure of garbage collection quite slow and erroneous. Java makes use of references as these cannot be manipulated, unlike pointers.

What do you understand by an instance variable and a local variable?

Instance variables are those variables that are accessible by all the methods in the class. They are declared outside the methods and inside the class. These variables describe the properties of an object and remain bound to it at any cost.

All the objects of the class will have their copy of the variables for utilization. If any modification is done on these variables, then only that instance will be impacted by it, and all other class instances continue to remain unaffected.

What is a ClassLoader?

A classloader in Java is a subsystem of Java Virtual Machine, dedicated to loading class files when a program is executed; ClassLoader is the first to load the executable file.

Java has Bootstrap, Extension, and Application classloaders.

What are the Memory Allocations available in JavaJava?

Java has five significant types of memory allocations.

  • Class Memory
  • Heap Memory
  • Stack Memory
  • Program Counter-Memory
  • Native Method Stack Memory

What are the differences between Heap and Stack Memory in Java?

Stack is generally used to store the order of method execution and local variables. In contrast, Heap memory is used to store the objects. After storing, they use dynamic memory allocation and deallocation.

Will the program run if we write static public void main?

Yes, the program will successfully execute if written so. Because, in Java, there is no specific rule for the order of specifiers

What is the default value stored in Local Variables?

Neither the Local Variables nor any primitives and Object references have any default value stored in them. 

What is an Association?

An Association can be defined as a relationship that has no ownership over another. For example, a person can be associated with multiple banks, and a bank can be related to various people, but no one can own the other.

What do you mean by aggregation?

The term aggregation refers to the relationship between two classes best described as a “whole/part” and “has-a” relationship. This kind is the most specialized version of an association relationship. It contains the reference to another class and is said to have ownership of that class.

Define Copy Constructor in Java

A Copy Constructor in Java is a constructor that initializes an object through another object of the same class.

What is a Marker Interface?

An empty interface in Java is referred to as a Marker interface. Serializable and Cloneable are some famous examples of Marker Interface. 

What is JCA in Java?

Java Cryptography Architecture gives a platform and provides architecture and application programming interfaces that enable decryption and encryption. 

Developers use Java Cryptography Architecture to combine the application with the security applications. Java Cryptography Architecture helps in implementing third party security rules and regulations. 

Java Cryptography Architecture uses the hash table, encryption message digest, etc. to implement the security.

Explain JPA in Java.

The Java Persistence API enables us to create the persistence layer for desktop and web applications. Java Persistence deals in the following:

  1. Java Persistence API
  2. Query Language
  3. Java Persistence Criteria API
  4. Object Mapping Metadata

Explain the different authentications in Java Servlets.

Authentication options are available in Servlets: There are four different options for authentication in servlet:

  • Basic Authentication: 

Usernames and passwords are given by the client to authenticate the user.

  • Form-based authentication: 

In this, the login form is made by the programmer by using HTML.

  • Digest Authentication: 

It is similar to basic authentication, but the passwords are encrypted using the Hash formula. Hash Formula makes digest more secure.

  • Client certificate Authentication:

It requires that each client accessing the resource has a certificate that it sends to authenticate itself. Client Authentication requires the SSL protocol.

What is Object Cloning?

An ability to recreate an object entirely similar to an existing object is known as Object Cloning in Java. Java provides a clone() method to clone a current object offering the same functionality as the original object.

OOPS Java Interview Questions

Question: What is Object-Oriented Programming? 

Answer: OOPs is a programming paradigm centred around objects rather than functions. It is not a tool or a programming language it is a paradigm that was designed to overcome the flaws of procedural programming. There are many languages that follow OOPs concepts, some popular ones are Java, Python, Ruby and more. Some frameworks also follow OOPs concepts, Angular is one such framework.

Question: Could you explain the Oops concepts?

Answer: Following are the various OOPS Concepts:

  • Abstraction– Representing essential features without the need to give out background details. The technique is used for creating a new suitable data type for some specific application
  • Aggregation– All objects have their separate lifecycle, but ownership is present. No child object can belong to some other object except for the parent object
  • Association– The relationship between two objects, where each object has its separate lifecycle. There is no ownership
  • Class– A group of similar entities
  • Composition– Also called the death relationship, it is a specialized form of aggregation. Child objects don’t have a lifecycle. As such, they automatically get deleted if the associated parent object is deleted
  • Encapsulation– Refers to the wrapping up of data and code into a single entity. Allows the variables of a class to be only accessible by the parent class and no other classes
  • Inheritance– When an object acquires the properties of some other object, it is called inheritance. It results in the formation of a parent-child relationship amongst classes involved. Offers a robust and natural mechanism of organizing and structuring software
  • Object– Denotes an instance of a class. Any class can have multiple instances. An object contains the data as well as the method that will operate on the data
  • Polymorphism– refers to the ability of a method, object, or variable to assume several forms

Decision Making Java Interview Questions

Questions: Differentiate between break and continue


Used with both loop and switch statementUsed with only loop statements.
It terminates the loop or switch block.It does not terminate but skips to the next iteration.

Classes, Objects, and Methods Java Interview Questions

Question: What is an Object?

Answer: An instance of a Java class is known as an object. Two important properties of a Java object are behaviour and state. An object is created as soon as the JVM comes across the new keyword.

Question: Define classes in Java 

Answer: A class is a collection of objects of similar data types. Classes are user-defined data types and behave like built-in types of a programming language. 

Syntax of a class: 

class Sample{
member variables

Example of Class:

public class Shape
String Shape name;
void area()
void volume ()
void num_sides()

Question: Explain what are static methods and variables?

Answer: A class has two sections one declares variables, and other declares method, and these are called instance variables and instance methods, respectively. They are termed so because every time a class is instantiated, a new copy of each of them is created. 

Variables and methods can be created that are common to all objects and accessed without using a particular object by declaring them static. Static members are also available to be used by other classes and methods. 

Question: What do you mean by Constructor?

Answer: A constructor is a method that has the same name as that of the class to which it belongs. As soon as a new object is created, a constructor corresponding to the class gets invoked. Although the user can explicitly create a constructor, it is created on its own as soon as a class is created. This is known as the default constructor. Constructors can be overloaded.

Note: – If an explicitly-created constructor has a parameter, then it is necessary to create another constructor without a parameter.

Question: Please explain Local variables and Instance variables in Java.

Answer: Variables that are only accessible to the method or code block in which they are declared are known as local variables. Instance variables, on the other hand, are accessible to all methods in a class. While local variables are declared inside a method or a code block, instance variables are declared inside a class but outside a method. Even when not assigned, instance variables have a value that can be null, 0, 0.0, or false. This isn’t the case with local variables that need to be assigned a value, where failing to assign a value will yield an error. Local variables are automatically created when a method is called and destroyed as soon as the method exits. For creating instance variables, the new keyword must be used.

Question: Please explain Method Overriding in Java?

Answer: Method Overriding in Java allows a subclass to offer a specific implementation of a method that has already been provided by its parent or superclass. Method overriding happens if the subclass method and the Superclass method have:

  • The same name
  • The same argument
  • The same return type

Question: What do you mean by Overloading?

Answer: Overloading is the phenomenon when two or more different methods (method overloading) or operators (operator overloading) have the same representation. For example, the + operator adds two integer values but concatenates two strings. Similarly, an overloaded function called Add can be used for two purposes

  1. To add two integers
  2. To concatenate two strings

Unlike method overriding, method overloading requires two overloaded methods to have the same name but different arguments. The overloaded functions may or may not have different return types.

Question: What role does the final keyword play in Java? What impact does it have on a variable, method, and class?

Answer: The final keyword in Java is a non-access modifier that applies only to a class, method, or variable. It serves a different purpose based on the context where it is used.

  • With a class

When a class is declared as final, then it is disabled from being subclassed i.e., no class can extend the final class.

  • With a method

Any method accompanying the final keyword is restricted from being overridden by the subclass.

  • With a variable

A variable followed by the final keyword is not able to change the value that it holds during the program execution. So, it behaves like a constant.

Arrays, Strings and Vectors Java Interview Questions

Question: Could you draw a comparison between Array and ArrayList?

Answer: An array necessitates for giving the size during the time of declaration, while an array list doesn’t necessarily require size as it changes size dynamically. To put an object into an array, there is the need to specify the index. However, no such requirement is in place for an array list. While an array list is parameterized, an array is not parameterized.

Question: Please explain the difference between String, String Builder, and String Buffer.

Answer: String variables are stored in a constant string pool. With the change in the string reference, it becomes impossible to delete the old value. For example, if a string has stored a value “Old,” then adding the new value “New” will not delete the old value. It will still be there, however, in a dormant state. In a String Buffer, values are stored in a stack. With the change in the string reference, the new value replaces the older value. The String Buffer is synchronized (and therefore, thread-safe) and offers slower performance than the String Builder, which is also a String Buffer but is not synchronized. Hence, performance is fast in String Builder than the String Buffer.

Questions: What is String Pool in Java?

Answer: The collection of strings stored in the heap memory refers to the String pool. Whenever a new object is created, it is checked if it is already present in the String pool or not. If it is already present, then the same reference is returned to the variable else new object is created in the String pool, and the respective reference is returned.

How to reverse a String in Java?

It might be surprising, but there is no reverse() utility method in the String class. But, it’s a very simple task. We can create a character array from the string and then iterate it from the end to start. We can append the characters to a string builder and finally return the reversed string.

public class StringPrograms {

	public static void main(String[] args) {

		String str = "123";

	public static String reverse(String in) {
		if (in == null)
			throw new IllegalArgumentException("Null is not valid input");

		StringBuilder out = new StringBuilder();

		char[] chars = in.toCharArray();

		for (int i = chars.length - 1; i >= 0; i--)

		return out.toString();

Java Program to check if a vowel is present in the string?

We can use regular expression to check if the string contains vowels or not.

public class StringContainsVowels {

	public static void main(String[] args) {

		System.out.println(stringContainsVowels("Hello")); // true
		System.out.println(stringContainsVowels("TV")); // false


	public static boolean stringContainsVowels(String input) {

		return input.toLowerCase().matches(".*[aeiou].*");



Java program to check if the given number is Prime?

We can write a simple program to divide the given number “n” from 2 to n/2 and check the remainder. If the remainder is 0, then it’s not a prime number.

public class PrimeNumberCheck {

	public static void main(String[] args) {

		System.out.println(isPrime(19)); // true
		System.out.println(isPrime(49)); // false

	public static boolean isPrime(int n) {
		if (n == 0 || n == 1) {
			return false;
		if (n == 2) {
			return true;
		for (int i = 2; i <= n / 2; i++) {
			if (n % i == 0) {
				return false;

		return true;

But, this is not very memory and time-efficient. For a given number N, if there is a prime number M between 2 to √N (square root of N) that evenly divides it, then N is not a prime number.

Fibonacci Series using recursion

We can use a for loop to print fibonacci series.

public static void printFibonacciSeries(int count) {
	int a = 0;
	int b = 1;
	int c = 1;
	for (int i = 1; i <= count; i++) {
		System.out.print(a + ", ");
		a = b;
		b = c;
		c = a + b;

The fibonacci number is generated by adding the previous two numbers – F(N) = F(N-1) + F(N-2). We can use recursion to print fibonacci series.

public class FibonacciNumbers {
	public static int fibonacci(int n) {
		if (n <= 1)
			return n;
		return fibonacci(n - 1) + fibonacci(n - 2);

	public static void main(String args[]) {
		int n = 10;

How to remove Whitespaces from String

We can use Character.isWhitespace() method to remove whitespaces from the string.

String removeWhiteSpaces(String input){
	StringBuilder output = new StringBuilder();
	char[] charArray = input.toCharArray();
	for(char c : charArray) {
		if (!Character.isWhitespace(c))
	return output.toString();

How to remove leading and trailing whitespaces from a string?

Java String class contains two methods to remove leading and trailing whitespaces – trim(), and strip(). The strip() method was added to the String class in Java 11. However, the strip() method uses Character.isWhitespace() method to check if the character is a whitespace. This method uses Unicode code points whereas the trim() method identifies any character having codepoint value less than or equal to ‘U+0020’ as a whitespace character.

The strip() method is the recommended way to remove whitespaces because it uses the Unicode standard.

String s = "  abc  def\t";
s = s.strip();

Since String is immutable, we have to assign the strip() output to the string.

How to Create a Deadlock Scenario Programatically?

Deadlock is a special scenario in the multi-threaded environment where two or more threads are blocked forever. The deadlock situation arises with at least two threads and two or more threads. Let’s write a simple program to create a deadlock.

public class ThreadDeadlock {

    public static void main(String[] args) throws InterruptedException {
        Object obj1 = new Object();
        Object obj2 = new Object();
        Object obj3 = new Object();
        Thread t1 = new Thread(new SyncThread(obj1, obj2), "t1");
        Thread t2 = new Thread(new SyncThread(obj2, obj3), "t2");
        Thread t3 = new Thread(new SyncThread(obj3, obj1), "t3");


class SyncThread implements Runnable{
    private Object obj1;
    private Object obj2;

    public SyncThread(Object o1, Object o2){
    public void run() {
        String name = Thread.currentThread().getName();
        System.out.println(name + " acquiring lock on "+obj1);
        synchronized (obj1) {
         System.out.println(name + " acquired lock on "+obj1);
         System.out.println(name + " acquiring lock on "+obj2);
         synchronized (obj2) {
            System.out.println(name + " acquired lock on "+obj2);
         System.out.println(name + " released lock on "+obj2);
        System.out.println(name + " released lock on "+obj1);
        System.out.println(name + " finished execution.");
    private void work() {
        try {
        } catch (InterruptedException e) {

All the three threads will be able to acquire a lock on the first object. But, they are using the shared resources and started in such a way that they will keep on waiting indefinitely to acquire the lock on the second object. We can use the java thread dump to detect the deadlocks. 

Revese a Linked List?

LinkedList descendingIterator() returns an iterator that iterates over the element in the reverse order. We can use this iterator to create a new Linked List with elements in the reverse order.

LinkedList<Integer> ll = new LinkedList<>();


LinkedList<Integer> ll1 = new LinkedList<>();



Merge Sort in Java?

Merge sort is one of the most efficient sorting algorithms. It works on the principle of Divide and Conquers. It is based on the idea of breaking down a list into several sub-lists until each sublist consists of a single element. Then merging those sublists in a manner that results in a sorted list.

public class MergeSort {

	public static void main(String[] args) {

		int[] arr = { 70, 50, 30, 10, 20, 40, 60 };

		int[] merged = mergeSort(arr, 0, arr.length - 1);

		for (int val : merged) {
			System.out.print(val + " ");


	public static int[] mergeTwoSortedArrays(int[] one, int[] two) {

		int[] sorted = new int[one.length + two.length];

		int i = 0;
		int j = 0;
		int k = 0;

		while (i < one.length && j < two.length) {

			if (one[i] < two[j]) {
				sorted[k] = one[i];
			} else {
				sorted[k] = two[j];

		if (i == one.length) {

			while (j < two.length) {
				sorted[k] = two[j];

		if (j == two.length) {

			while (i < one.length) {
				sorted[k] = one[i];

		return sorted;


	public static int[] mergeSort(int[] arr, int lo, int hi) {

		if (lo == hi) {
			int[] br = new int[1];
			br[0] = arr[lo];

			return br;

		int mid = (lo + hi) / 2;

		int[] fh = mergeSort(arr, lo, mid);
		int[] sh = mergeSort(arr, mid + 1, hi);

		int[] merged = mergeTwoSortedArrays(fh, sh);

		return merged;


Remove all occurrences of a given character from input String?

String class doesn’t have any method to remove characters. We can use the replace() method to create a new string without the given character.

String str1 = "abcdABCDabcdABCD";
str1 = str1.replace("a", ""); 

System.out.println(str1); // bcdABCDbcdABCD

The string is immutable in Java. All the string manipulation methods return a new string. So, it’s necessary that we assign it to another variable.

How to get distinct characters and their count in a String?

We can create the character array from the string. Then iterate over it and create a HashMap with the character as key and their count as value.

String str1 = "abcdABCDabcd";

char[] chars = str1.toCharArray();

Map<Character, Integer> charsCount = new HashMap<>();

for(char c : chars) {
	if(charsCount.containsKey(c)) {
		charsCount.put(c, charsCount.get(c)+1);
		charsCount.put(c, 1);

System.out.println(charsCount); // {a=2, A=1, b=2, B=1, c=2, C=1, d=2, D=1}

How to prove String is immutable programatically?

String s1 = "Java"; // "Java" String created in pool and reference assigned to s1

String s2 = s1; //s2 is also having the same reference to "Java" in the pool

System.out.println(s1 == s2); // proof that s1 and s2 have same reference

s1 = "Python"; 
//s1 value got changed above, so how String is immutable?

//well, in the above case a new String "Python" got created in the pool
//s1 is now referring to the new String in the pool 
//BUT, the original String "Java" is still unchanged and remains in the pool
//s2 is still referring to the original String "Java" in the pool

// proof that s1 and s2 have different reference
System.out.println(s1 == s2); 

// prints "Java" supporting the fact that original String value is unchanged, hence String is immutable

Write a Program to showcase inheritance?

class Animal {
	String color;

class Cat extends Animal {
	void meuw(){

Write a Program to show try catch example?

Let’s look at a simple try-catch block code.

try {
	FileInputStream fis = new FileInputStream("test.txt");
}catch(FileNotFoundException e) {

From Java 7 onwards, We can also catch multiple exceptions in a single catch block. It’s useful when we have the same code in all the catch blocks.

public static void foo(int x) throws IllegalArgumentException, NullPointerException {
	// some code

public static void main(String[] args) {
	try {
	} catch (IllegalArgumentException | NullPointerException e) {

Write a code to show NullPointerException

If we are calling a function on the “null”, it will throw NullPointerException.

public static void main(String[] args) {
	printString(null, 3);

static void printString(String s, int count){
	for (int i = 0 ; i < count; i++) {
		System.out.println(s.toUpperCase()); // Exception in thread "main" java.lang.NullPointerException

That’s why it’s better to have null check in place for early validation.

static void printString(String s, int count){
	if(s == null) return;
	for (int i = 0 ; i < count; i++) {

We can also throw IllegalArgumentException based on the project requirements.

How to use forEach() method?

The forEach() method provides a shortcut to perform an action on all the elements of an iterable. Let’s say we have to iterate over the list elements and print it.

List<String> list = new ArrayList<>();

Iterator<String> it = list.iterator();

while (it.hasNext()) {

We can use forEach() method with lambda expression to reduce the code size.

List<String> list = new ArrayList<>();


Write an interface with default and static method?

Java 8 introduced default and static methods in interfaces. This has bridged the gap between interfaces and abstract classes.

public interface Interface1 {
	// regular abstract method
	void method1(String str);
	default void log(String str){
		System.out.println("I1 logging::"+str);
	static boolean isNull(String str) {
		System.out.println("Interface Null Check");

		return str == null ? true : "".equals(str) ? true : false;

Find 5 mistakes in the following code snippet


public class String Programs {

	static void main(String[10] args) {
		String s = "abc"
  1. Package name can’t have hyphens.
  2. Class name can’t have whitespaces.
  3. The main method is not public, so it won’t run.
  4. The main method argument shouldn’t specify the size.
  5. The semicolon is missing in the string definition.

Advanced Java Interview Questions

Interfaces and Abstract Classes Java Interview Questions

Question: What do you know about Interface in Java?

Answer: A Java interface is a template that has only method declarations and not method implementations. It is a workaround for achieving multiple inheritances in Java. Some worth remembering important points regarding Java interfaces are:

  • A class that implements the interface must provide an implementation for all methods declared in the interface
  • All methods in an interface are internally public abstract void
  • All variables in an interface are internally public static final
  • Classes do not extend but implement interfaces

Question: How is an Abstract class different from an Interface?

Answer: There are several differences between an Abstract class and an Interface in Java, summed up as follows:

  • Constituents – An abstract class contains instance variables, whereas an interface can contain only constants.
  • Constructor and Instantiation – While an interface has neither a constructor nor it can be instantiated, an abstract class can have a default constructor that is called whenever the concrete subclass is instantiated.
  • Implementation of Methods – All classes that implement the interface need to provide an implementation for all the methods contained by it. A class that extends the abstract class, however, doesn’t require implementing all the methods contained in it. Only abstract methods need to be implemented in the concrete subclass.
  • Type of Methods – Any abstract class has both abstract as well as non-abstract methods. Interface, on the other hand, has only a single abstract method.

Question: Please explain what do you mean by an Abstract class and an Abstract method?

Answer: An abstract class in Java is a class that can’t be instantiated. Such a class is typically used for providing a base for subclasses to extend as well as implementing the abstract methods and overriding or using the implemented methods defined in the abstract class. To create an abstract class, it needs to be followed by the abstract keyword. Any abstract class can have both abstract as well as non-abstract methods. A method in Java that only has the declaration and not implementation is known as an abstract method. Also, an abstract method name is followed by the abstract keyword. Any concrete subclass that extends the abstract class must provide an implementation for abstract methods.

Questions: What is multiple inheritance? Does Java support multiple inheritance? If not, how can it be achieved?

Answer: If a subclass or child class has two parent classes, that means it inherits the properties from two base classes, it is multiple inheritances. Java does not multiple inheritances as in case if the parent classes have the same method names, then at runtime, it becomes ambiguous, and the compiler is unable to decide which method to execute from the child class.

Packages Java Interview Questions

Question: What are the packages in Java? State some advantages of Packages in Java?

Answer: Packages are Java’s way of grouping a variety of classes and/or interfaces together. The functionality of the objects decides how they are grouped. Packagers act as “containers” to classes.

Enlisted below are the advantages of Packages:

  1. Classes of other programs can be reused.
  2. Two classes with the same can exist in two different packages.
  3. Packages can hide classes, thus denying access to certain programs and classes meant for internal use only.
  4. They also separate design from coding.

Multithreading Java Interview Questions

Question: How do you make a thread in Java? Give examples.

Answer: To make a thread in Java, there are two options:

  • Extend the Thread Class  The thread is available in the java.lang.Thread class. To make a thread, you need to extend a thread class and override the run method. For example,
public class Addition extends Thread {
public void run() {

A disadvantage of using the thread class is that it becomes impossible to extend any other classes.

Nonetheless, it is possible to overload the run() method in the class

  • Implement Runnable Interface – Another way of making a thread in Java is by implementing a runnable interface. For doing so, there is the need to provide the implementation for the run() method that is defined in the
interface. For example,
public class Addition implements Runnable {
public void run() {

Question: Why do we use the yield() method?

Answer: The yield() method belongs to the thread class. It transfers the currently running thread to a runnable state and also allows the other threads to execute. In other words, it gives equal priority threads a chance to run. Because yield() is a static method, it does not release any lock.

Question: Can you explain the thread lifecycle in Java?

Answer: The thread lifecycle has the following states and follows the following order:

  • New – In the very first state of the thread lifecycle, the thread instance is created, and the start() method is yet to be invoked. The thread is considered alive now.
  • Runnable – After invoking the start() method, but before invoking the run() method, a thread is in the runnable state. A thread can also return to the runnable state from waiting or sleeping state.
  • Running – The thread enters the running state after the run() method is invoked. This is when the thread begins execution.
  • Non-Runnable – Although the thread is alive, it is not able to run. Typically, it returns to the runnable state after some time.
  • Terminated – The thread enters the terminated state once the run() method completes its execution. It is not alive now.

Question: When is the Runnable interface preferred over thread class and vice-versa?

Answer: In Java, it is possible to extend only one class. Hence, the thread class is only extended when no other class needs to be extended. If it is required for a class to extend some other class than the thread class, then we need to use the Runnable interface.

Question: Please draw a comparison between notify() and notifyAll() methods.

Answer: The notify() method is used for sending a signal to wake up a single thread in the waiting pool. Contrarily, the notifyAll() method is used for sending a signal to wake up all threads in a waiting pool.

Question: How will you distinguish processes from threads?

Answer: There are several fundamental differences between a process and a thread, stated as follows:

  • Definition – A process is an executing instance of a program whereas, a thread is a subset of a process.
  • Changes – A change made to the parent process doesn’t affect child processes. However, a change in the main thread can yield changes in the behavior of other threads of the same process.
  • Communication – While processes require inter-process communication for communicating with sibling processes, threads can directly communicate with other threads belonging to the same process.
  • Control – Processes are controlled by the operating system and can control only child processes. On the contrary, threads are controlled by the programmer and are capable of exercising control over threads of the same process to which they belong.
  • Dependence – Processes are independent entities while threads are dependent entities
  • Memory – Threads run in shared memory spaces, but processes run in separate memory spaces.

Question: What is the join() method? Give an example.

Answer: We use the join() method for joining one thread with the end of the currently running thread. It is a non-static method and has an overloaded version. Consider the example below:

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

The main thread starts execution in the example mentioned above. As soon as the execution reaches the code t.start(), then the thread t starts its stack for execution. The JVM switches between the main thread and the thread there. Once the execution reaches the t.join(), then the thread t alone is executed and allowed to complete its task. Afterward, the main thread resumes execution.

Question: How do you make a thread stop in Java?

Answer: There are three methods in Java to stop the execution of a thread:

  • Blocking – This method is used to put the thread in a blocked state. The execution resumes as soon as the condition of the blocking is met. For instance, the ServerSocket.accept() is a blocking method that listens for incoming socket connection and resumes the blocked thread only when a connection is made.
  • Sleeping – This method is used for delaying the execution of the thread for some time. A thread upon which the sleep() method is used is said to enter the sleep state. It enters the runnable state as soon as it wakes up i.e., the sleep state is finished. The time for which the thread needs to enter the sleep state is mentioned inside the braces of the sleep() method. It is a static method.
  • Waiting – Although it can be called on any Java object, the wait() method can only be called from a synchronized block.

Exception Handling Java Interview Questions

Question: Could you explain various types of Exceptions in Java? Also, tell us about the different ways of handling them.

Answer: Java has provision for two types of exceptions:

  • Checked Exceptions – Classes that extend Throwable class, except Runtime exception and Error, are called checked exceptions. Such exceptions are checked by the compiler during the compile time. These types of exceptions must either have appropriate try/catch blocks or be declared using the throws keyword. ClassNotFoundException is a checked exception.
  • Unchecked Exceptions – Such exceptions aren’t checked by the compiler during the compile time. As such, the compiler doesn’t necessitate handling unchecked exceptions. Arithmetic Exception and ArrayIndexOutOfBounds Exception are unchecked exceptions.

Exceptions in Java are handled in two ways:

Declaring the throws keyword – We can declare the exception using throws keyword at the end of the method. For example:

class ExceptionCheck{
public static void main(String[] args){
public void add() throws Exception{

Using try/catch – Any code segment that is expected to yield an exception is surrounded by the try block. Upon the occurrence of the exception, it is caught by the catch block that follows the try block. For example,

class ExceptionCheck{
public static void main (String[] args) {
public void add(){
catch(Exception e)

Question: Is it possible to write multiple catch blocks under a single try block?

Answer: Yes, it is possible to write several catch blocks under a single try block. However, the approach needs to be from specific to general. Following example demonstrates the same:

public class Example {
public static void main(String args[]) {
try {
int a[]= new int[10];
a[10]= 10/0;
catch(ArithmeticException e)
System.out.println("Arithmetic exception in first catch block");
catch(ArrayIndexOutOfBoundsException e)
System.out.println("Array index out of bounds in second catch block");
catch(Exception e)
System.out.println("Any exception in third catch block");

Question: How does the throw keyword differ from the throws keyword?

Answer: While the throws keyword allows declaring an exception, the throw keyword is used to explicitly throw an exception. Checked exceptions can’t be propagated with throw only, but throws allow doing so without the need for anything else. The throws keyword is followed by a class, whereas the throw keyword is followed by an instance. The throw keyword is used within the method, but the throws keyword is used with the method signature. Furthermore, it is not possible to throw multiple exceptions, but it is possible to declare multiple exceptions.

Question: Explain various exceptions handling keywords in Java?


There is two crucial exception handling keywords in Java, followed by the third keyword final, which may or may not be used after handling exceptions.


If and when a code segment has chances of having and abnormality or an error, it is placed within a try block. When the exception is raised, it is handled and caught by the catch block.

Try block must have a catch() or a final() or both blocks after it.


When an exception is raised in the try block, it is handled in the catch block.


This block is executed regardless of the exception. It can be placed either after try{} or catch {} block.

Question: Explain exception propagation?

Answer: The method at the top of the stack throws an exception if it is not caught. It moves to the next method and goes on like this until caught.


public class Sum()
public static void main(String args[])
public void addition()

The stack of the above code is:


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

File Handling Java Interview Questions

Question: Does an empty file name with .java extension a valid file name?

Answer: Yes, Java permits to save our java file by .java only. It is compiled by javac .java and run by java class name.

Let’s take a simple example:

public class Any()
public static void main(String args[])
System.out.println("Hello Java File here!");

To compile:

To run: Java Any

Collections Java Interview Questions

Question: What do you mean by Collections in Java? What are the constituents of Collections in Java?

Answer: A group of objects in Java is known as collections. Java.util package contains, along with date and time facilities, internationalization, legacy collection classes, etc., the various classes and interfaces for collecting. Alternatively, collections can be considered as a framework designed for storing the objects and manipulating the design in which the objects are stored. You can use collections to perform the following operations on objects:

  • Deletion
  • Insertion
  • Manipulation
  • Searching
  • Sorting

Following are the various constituents of the collections framework:

  • Classes – Array List, Linked List, Lists, and Vector
  • Interfaces – Collection, List, Map, Queue, Set, Sorted Map, and Sorted Set
  • Maps – HashMap, HashTable, LinkedHashMap, and TreeMap
  • Queues – Priority Queue
  • Sets – Hash Set, Linked Hash Set, and Tree Set

Question: How will you differentiate HashMap from HashTable?

Answer: HashMap in Java is a Map-based collection class, used for storing key & value pairs. It is denoted as HashMap<Key, Value> or HashMap<K, V> HashTable is an array of a list, where each list is called a bucket. Values contained in a HashTable are unique and depend on the key. Methods are not synchronized in HashMap, while key methods are synchronized in HashTable. However, HashMap doesn’t have thread safety, while HashTable has the same. For iterating values, HashMap uses iterator and HashTable uses enumerator. HashTable doesn’t allow anything that is null, while HashMap allows one null key and several null values. In terms of performance, HashTable is slow. Comparatively, HashMap is faster.

Question: Please explain Map and their types in Java.

Answer: A Java Map is an object that maps keys to values. It can’t contain duplicate keys, and each key can map to only one value. In order to determine whether two keys are the same or distinct, Map makes use of the equals() method. There are 4 types of Map in Java, described as follows:

  • HashMap – It is an unordered and unsorted map and hence, is a good choice when there is no emphasis on the order. A HashMap allows one null key and multiple null values and doesn’t maintain any insertion order.
  • HashTable – Doesn’t allow anything null and has methods that are synchronized. As it allows for thread safety, the performance is slow.
  • LinkedHashMap – Slower than a HashMap but maintains insertion order and has a faster iteration.
  • TreeMap – A sorted Map providing support for constructing a sort order using a constructor.

Question: What do you mean by Priority Queue in Java?

Answer: Priority queue, like a regular queue, is an abstract data type except having a priority associated with each element contained by it. The element with the high priority is served before the element with low priority in a priority queue. Elements in a priority queue are ordered either according to the comparator or naturally. The order of the elements in a priority queue represents their relative priority.

Question: What is Set in Java? Also, explain its types in a Java Collections.

Answer: In Java, a Set is a collection of unique objects. It uses the equals() method to determine whether two objects are the same or not. Various types of Set in Java Collections are:

  1. Hash Set– An unordered and unsorted set that uses the hash code of the object for adding values. Used when the order of the collection isn’t important
  2. Linked Hash Set– This is an ordered version of the hash set that maintains a doubly-linked list of all the elements. Used when iteration order is mandatory. Insertion order is the same as that of how elements are added to the Set.
  3. Tree Set– One of the two sorted collections in Java, it uses Read-Black tree structure and ensures that the elements are present in the ascending order.

Question: What is ordered and sorted concerning collections?


  1. Ordered

It means that values are stored in a collection in a specific order, but the order is independent of the value. Eg. List

  1. Sorted

It means the collection has an order which is dependent on the value of an element.

Eg. SortedSet

Miscellaneous Java Interview Questions 

Question: Please explain the various types of garbage collectors in Java?

Answer: The Java programming language has four types of garbage collectors:

  1. Serial Garbage Collector– Using only a single thread for garbage collection, the serial garbage collector works by holding all the application threads. It is designed especially for single-threaded environments. Because serial garbage collector freezes all application threads while performing garbage collection, it is most suitable for command-line programs only. For using the serial garbage collector, one needs to turn on the -XX:+UseSerialGC JVM argument.
  2. Parallel Garbage Collector – Also known as the throughput collector, the parallel garbage collector is the default garbage collector of the JVM. It uses multiple threads for garbage collection, and like a serial garbage collector freezes all application threads during garbage collection.
  3. CMS Garbage Collector– Short for Concurrent Mark Sweep, CMS garbage collector uses multiple threads for scanning the heap memory for marking instances for eviction, followed by sweeping the marked instances. There are only two scenarios when the CMS garbage collector holds all the application threads:
    1. When marking the referenced objects in the tenured generation space
    2. If there is some change in the heap memory while performing the garbage collection, CMS garbage collector ensures better application throughput over parallel garbage collectors by using more CPU. For using the CMS garbage collector, the XX:+USeParNewGC JVM argument needs to be turned on.

Question: What do you understand by Synchronization in Java? What is its most significant disadvantage?

Answer: If several threads try to access a single block of code, then there is an increased chance of producing inaccurate results. Synchronization is used to prevent this. Using the synchronization keyword makes a thread need a key to access the synchronized code. Simply, synchronization allows only one thread to access a block of code at a time. Each Java object has a lock, and every lock has only one key. A thread can access a synchronized method only if it can get the key to the lock of the object. Following example demonstrates synchronization:

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

Note: It is recommended to avoid implementing synchronization for all methods. This is because when only one thread can access the synchronized code, the next thread needs to wait. Consequently, it results in slower performance of the program.

Question: Can you tell the difference between execute(), executeQuery(), and executeUpdate()?


  • execute() – Used for executing an SQL query. It returns TRUE if the result is a ResultSet, like running Select queries, and FALSE if the result is not a ResultSet, such as running an Insert or an Update query.
  • executeQuery() – Used for executing Select queries. It returns the ResultSet, which is not null, even if no records are matching the query. The executeQuery() method must be used when executing select queries so that it throws the java.sql.SQLException with the ‘executeQuery method cannot be used for update’ message when someone tries to execute an Insert or Update statement.
  • executeUpdate() – Used for executing Delete/Insert/Update statement or DDL statements that returns nothing. The output varies depending on whether the statements are Data Manipulation Language (DML) statements or Data Definition Language (DDL) statements. The output is an integer and equals the total row count for the former case, and 0 for the latter case.

Note: The execute() method needs to be used only in a scenario when there is no certainty about the type of statement. In all other cases, either use executeQuery() or executeUpdate() method.

Answer: Following code demonstrates deleting a cookie in JSP:

Cookie mycook = new Cookie("name1","value1");
Cookie killmycook = new Cookie("mycook1","value1");
killmycook . set MaxAge ( 0 );
killmycook . set Path ("/");
killmycook . addCookie ( killmycook 1 );

Question: Write suitable code examples to demonstrate the use of final, final, and finalize.

AnswerFinal:  The final keyword is used for restricting a class, method, and variable. A final class can’t be inherited, a final method is disabled from overriding, and a final variable becomes a constant i.e., its value can’t be changed.

class FinalVarExample {
public static void main( String args[])
final int a=10;
a=50; /* Will result in an error as the value can’t be changed now*/

Finally: Any code inside the final block will be executed, irrespective of whether an exception is handled or not.

class FinallyExample {
public static void main(String args[]){
try {
int x=100;
catch(Exception e) {
finally {
System.out.println("finally block is executing");}

Finalize: The finalize method performs the clean up just before the object is garbage collected.

class FinalizeExample {
public void finalize() {
System.out.println("Finalize is called");
public static void main(String args[])
FinalizeExample f1=new FinalizeExample();
FinalizeExample f2=new FinalizeExample();
f1= NULL;

Question: What purpose do the Volatile variable serve in Java?

Answer: The value stored in a volatile variable is not read from the thread’s cache memory but from the main memory. Volatile variables are primarily used during synchronization.

Question: Please compare Serialization with Deserialization in Java.

Answer: Serialization is the process by which Java objects are converted into the byte stream. Deserialization is the exact opposite process of serialization where Java objects are retrieved from the byte stream. A Java object is serialized by writing it to an ObjectOutputStream and deserialized by reading it from an ObjectInputStream.

Question: What do you understand by OutOfMemoryError in Java?

Answer: Typically, the OutOfMemoryError exception is thrown when the JVM is not able to allocate an object due to running out of memory. In such a situation, no memory could be reclaimed by the garbage collector. There can be several reasons that result in the OutOfMemoryError exception, out of which most notable ones are:

  • Holding objects for too long
  • Trying to process too much data at the same time
  • Using a third-party library that caches strings
  • Using an application server that doesn’t perform a memory cleanup post the deployment
  • When a native allocation can’t be satisfied

That completes the list of top Java interview questions.

Good luck with the interviews!

Hope you learned something from this post.

Follow Programming Articles for more!

About ᴾᴿᴼᵍʳᵃᵐᵐᵉʳ

Linux and Python enthusiast, in love with open source since 2014, Writer at, India.

View all posts by ᴾᴿᴼᵍʳᵃᵐᵐᵉʳ →