155+ Java Interview Questions and Answers (2026 Updated)

Java remains one of the most widely used programming languages for building web, mobile, and enterprise applications. Its platform independence, reliability, and strong community support make it a preferred choice for developers worldwide. 

With companies hiring Java developers across backend, Android, and cloud roles, a clear understanding of core concepts and coding skills matters more than ever. Practising Java interview questions helps you revise important topics such as OOP, collections, exception handling, multithreading, and modern Java features. It also builds confidence and sharpens your problem solving. 

In this blog, you will find the most commonly asked questions, expert answers, and useful tips. Everything is grouped by topic and experience level, so freshers and experienced developers can both find what they need and prepare with ease. 

Java Interview Questions for Freshers & Beginners

Below are some commonly asked Java interview questions and answers for freshers that cover the basic concepts of Java. These questions can help you strengthen your fundamentals and prepare effectively for technical interviews. 

If you have recently completed a Java course or are looking for your first Java developer role, reviewing the questions below will help you gain confidence and improve your interview readiness. You can also revise the basics with our complete Java tutorial before you begin. 

1. What is Java? Explain its meaning and definition.

Java is a high-level, object-oriented programming language used to develop web applications, mobile apps, desktop software, games, and enterprise applications. It is known for its platform independence, which means Java programs can run on any system that has a Java Virtual Machine (JVM)

Java was created by James Gosling and his team at Sun Microsystems, and was publicly released in 1995. It is secure, reliable, and easy to learn. Its "Write Once, Run Anywhere" (WORA) capability and extensive library support make it one of the most popular programming languages in the world. 

2. The syntax of Java is based on which programming language?

C and C++ programming languages form the basis of Java syntax. 

3. How is Java platform independent?

This is one of the most common Java interview questions asked in technical interviews. To answer it correctly, you should understand how Java programs can run on different operating systems without requiring any modifications. 

Platform independent means that a Java program can be written on one machine and executed on different operating systems without any changes. This is possible because Java code is compiled into bytecode, which is executed by the Java Virtual Machine (JVM). Since each platform has its own JVM, the same bytecode can run anywhere without hardware compatibility issues. 

4. When was Java developed?

Java development began in 1991, and first public release was 1995. 

5. Who developed the Java programming language?

Java was developed by James Gosling, a Canadian computer scientist, while working at Sun Microsystems. He is widely known as the founder of Java. Later, Sun Microsystems was acquired by Oracle Corporation.

6. What does ‘write once run anywhere’ mean in Java?

Write once, run anywhere, or WORA in Java means that it is a coding language where you write a program for some purpose only once and then use it or run it across multiple operating systems. For instance, you can write a program and run it on Windows, macOS, Android, Linux, etc.  

“Java’s write once, run anywhere” term was first initiated by Sun Microsystems, where the founder of this language used to work. This characteristic makes Java a portable programming language. 

Also Read: Top 70+ HTML Interview Questions and Answers 

7. What is Java programming used for? Explain its primary applications.

There is a wide range of use cases of Java programming language. Below are its main applications: 

a) Mobile App Development

Despite the introduction of Kotlin, Java is still used as a reliable programming language for Android app development. This coding language has the software development kits (SDKs) and libraries that are required to develop mobile apps.

b) Chatbot Development

Another use of Java is in chatbot development. Smart chatbots that use natural language processing (NLP) can be built using this programming language.

c) Development of Games

One of the most important applications of Java is in building games or gaming apps. Some of the world-famous games like Minecraft, Spiral Knights, SimCity, Saints Row 2, Asphalt 3, FIFA 11, Wakfu, Tokyo City Nights and many more are built on Java.

d) Cloud Computing

The "Write Once, Run Anywhere" characteristic of Java makes it highly suitable for cloud applications. Many cloud platforms and distributed systems rely on Java because of its portability, scalability, and reliability. 

e) Big Data

Big data platforms or tools heavily depend on Java, and it is considered a language on which the future of big data relies. This is because of its features that enable faster processing of large sets of data. 

f) Enterprise-grade Web Applications

Java is widely used to develop enterprise-grade web applications. Its high performance, scalability, security, and support for a wide range of server-side technologies make it a popular choice for large-scale software development. 

Many organizations use Java for enterprise applications, and popular platforms such as LinkedIn and IRCTC are built using Java technologies. 

g) Internet of Things (IoT)

In IoT technology, sensors and smart devices collect and process data to perform different tasks. Many of these devices run applications developed using the Java programming language because of its reliability and platform independence. 

h) Artificial Intelligence (AI)

As one of the most suitable programming languages for artificial intelligence (AI) projects, Java can be used to develop intelligent solutions. For instance, it is great for building search algorithms, neural networks, ML-based services, deep learning applications, etc.  

8. What is Java Virtual Machine (JVM)?

The Java Virtual Machine (JVM) is a software environment that executes Java bytecode and enables Java programs to run on different operating systems. It acts as a bridge between the Java program and the underlying hardware, making Java platform independent.

9. What is Java Runtime Environment (JRE)?

The Java Runtime Environment (JRE) is the environment required to run Java applications. It sits between the operating system and the Java program. 

The JRE contains:

  • The Java Virtual Machine (JVM) 
  • The core Java class libraries (java.lang, java.util, java.io, and others) 
  • Supporting files and configuration needed at runtime 

Important point for modern interviews: Oracle stopped distributing a separate, standalone JRE from Java 11 onwards. Instead, applications ship with the JDK, or a custom, trimmed-down runtime image is created using the jlink tool. The Java Plug-in (the browser plugin) and Java Web Start were also removed in Java 11. 

Relationship to remember: JRE = JVM + class libraries, and JDK = JRE + development tools. 

10. What is Java SE (Standard Edition)?

Java Standard Edition, abbreviated as Java SE, is a computing platform on which programmers and developers build and deploy Java-based projects. This platform comes with plenty of Java libraries and APIs, including Java.util, Java.net, Java.math, Java.io, and many more. 

11. What are operators in Java?

This is also one of the basic questions for Java interviews that tests your understanding of fundamental programming concepts. 

Java operators are symbols used to perform different operations on variables and values. Each operator has a specific purpose or functionality. 

For example, the + operator is used for addition, - for subtraction, * for multiplication, and / for division. 

12. What are the different types of Java operators?

You can classify the operators in Java into five categories, as mentioned below: 

a) Java Arithmetic operators

Arithmetic operators are used to perform mathematical calculations on numeric values.

Addition 
Subtraction 
Multiplication 
Division 
Modulo 

b) Java Unary operators

Unary operators are used to perform operations on a single operand, such as increasing or decreasing its value.  

Unary minus (-) To make a value negative 
Unary plus (+) Generally not used as values are positive by default 
Increment (++) To increase the value by 1 
Decrement (--) To decrease the value by 1 
Inverting (!) To invert the value 

c) Java Assignment operators

Assignment operators are used to assign values to variables and perform operations while updating the variable's value. 

Operator Presentation Meaning 
X = Y X = Y 
+= X += Y X = X + Y 
-= X -= Y X = X - Y 
*= X *= Y X = X * Y 
%= X %= X = X % Y 

d) Java Relational or comparison operators

Relational or comparison operators are used to compare two values in Java. They check conditions such as equality, inequality, greater than, less than, greater than or equal to, and less than or equal to.  

These operators return a boolean value (true or false) based on the comparison result. 

Operator Meaning 
== Is equal to 
!= Is not equal to 
Is greater than 
Is lesser than 
>= Is greater than or equal to 
<= Is less than or equal to 

e) Java Logical operators

Logical operators are used to combine or modify conditions in Java. They help make decisions based on multiple conditions and return a boolean value (true or false). 

Operator Meaning 
&& Logical AND 
|| Logical OR 
Logical NOT 

f) Java Bitwise operators

Bitwise operators work on individual bits of integer values. 

Operator Meaning 
Bitwise AND 
Bitwise OR 
Bitwise XOR 
Bitwise complement (inverts every bit) 

g) Java Shift operators

Shift operators move the bits of a number left or right. 

Operator Meaning 
<< Left shift 
>> Signed right shift, preserves the sign bit 
>>> Unsigned right shift, always fills with 0 

h) Java Ternary operator

The ternary operator ? : is a shorthand for an if-else statement. 

java 

int max = (a > b) ? a : b;

i) instanceof operator 

The instanceof operator checks whether an object is an instance of a particular class or interface and returns a boolean.

java 

if (obj instanceof String) { 
    // obj is a String 
}

Since Java 16, pattern matching for instanceof allows the check and the cast in a single step: 

java 

if (obj instanceof String s) { 
    System.out.println(s.length()); 
}

13. What is JIT compiler in Java?

The JIT (Just-In-Time) compiler is a component of the JVM. It converts frequently executed bytecode into native machine code at runtime, so that the JVM can run the compiled code directly instead of interpreting the same bytecode repeatedly. 

How it fits into execution:

  1. javac compiles the source code into bytecode (.class files). 
  2. The JVM loads the bytecode and begins executing it through the interpreter. 
  3. The JIT compiler identifies "hot" methods, the ones being called repeatedly, and compiles them to native machine code. 
  4. Subsequent calls run the compiled native code, which significantly improves performance. 

This is why Java applications typically get faster after they have been running for a while, a behaviour often called "warming up". 

14. What is a Java class?

class in Java is a blueprint or template used to create objects. It defines the properties (data members) and behaviors (methods) that objects of that class will have. 

In simple terms, a class represents a category, while objects are the individual items that belong to that category. All objects created from the same class share similar characteristics and behaviors. 

For example, in an online shopping store, "Mobile" can be a class, while different smartphones are objects. Although the smartphones may vary in brand and model, they all have common features such as a camera, RAM, calling functionality, and messaging capabilities. 

15. What is a package in Java?

package in Java is a collection of related classes, interfaces, and sub-packages that are grouped together based on their functionality. It helps organize code in a structured manner and makes large applications easier to manage. 

The main purpose of using packages is to improve code organization, prevent naming conflicts, and provide access control for classes and interfaces. 

There are two types of packages in Java:

  • Built-in packages 
  • User-defined packages 

Built-in packages, such as Java.lang, Java.util, Java.io, and Java.net, are provided by the Java API and contain commonly used classes and interfaces. Developers can also create their own packages, known as user-defined packages, to organize application-specific code. 

16. What are keywords in Java?

Keywords in Java programming are actually some predefined words in syntax that a programmer can’t use in the form of classes, methods, identifiers, or variables. These are also known as reserved words in Java. 

17. How many keywords are there in Java?

Java has 52 reserved keywords that have predefined meanings and cannot be used as identifiers such as variable names, class names, or method names. 

Keywords in Java:

abstract, assert, boolean, break, byte, case, catch, char, class, const (unused), continue, default, do, double, else, enum, extends, final, finally, float, for, goto (unused), if, implements, import, instanceof, int, interface, long, native, new, package, private, protected, public, return, short, static, strictfp, super, switch, synchronized, this, throw, throws, transient, try, void, volatile, and while. 

18. What are the key features of Java?

It is one of the basic Java interview questions for freshers, and sometimes for experienced professionals as well.

Here are the top 10 features of Java that you must know:

a) Simple, Clean, Easy to Learn

One of the best things about Java is that it is easy to learn and understand, even for beginners. Its syntax is simple as it is based on basic languages like C++. The code written in Java is also clean and easy to run. 

b) Object-oriented Programming Language

Java is an object-oriented programming language because it is based on classes and objects. It supports key OOP concepts such as encapsulation, inheritance, polymorphism, and abstraction. 

c) Java is Both Compiled and Interpreted

Java is both a compiled and interpreted language. The source code is first compiled into bytecode, which is then interpreted and executed by the Java Virtual Machine (JVM). 

d) Java is Platform Independent

This is one of the top features of Java programming. The meaning of platform-independent here is that you can write a Java program on one machine and execute it on other machines or platforms. It has become possible because of the BYTE code.  

e) Portability

Java is portable because of its platform independence and architecture-neutral design. Java programs are compiled into bytecode, which can run on any system that has a Java Virtual Machine (JVM). This allows the same code to be executed on different hardware and operating systems without modification. 

f) Robust Programming Language

The abilities of Java, like garbage collection and exception handling, make it a solid programming language.  

g) Highly Secure

Java is known for its strong security features, which help developers build reliable and secure applications. Features such as bytecode verification, automatic memory management, and runtime security checks reduce common security risks, making Java a popular choice for enterprise-grade application development. 

h) Java Multithreading Features

The multithreading feature helps in writing code that can perform multiple tasks simultaneously. Moreover, the thread tasks consume less processing power and memory.  

i) Easy Interpretation

Regardless of the computer architecture, Java programs can be run and interpreted on any type of machine. You can call it architecture-neutral language.  

j) High Performance

Java offers high performance through features such as the Just-In-Time (JIT) compiler, which converts bytecode into native machine code at runtime. This helps Java applications run faster and more efficiently. 

19. What is an object in Java?

Since Java is an object-oriented programming language, classes and objects are among its most important concepts. Understanding objects is essential for answering many Java interview questions. 

An object is an instance of a class in Java. It is created from a class using the new keyword. Every object has its own identity, state (attributes), and behavior (methods), similar to real-world entities. 

Example: If Car is a class, then a specific car such as a Honda City can be considered an object. The car's color and model represent its state, while actions like starting, stopping, and accelerating represent its behavior. 

20. What is the difference between Java and JavaScript?

There are several differences between Java and JavaScript. Whether you are a fresher or an experienced professional, this is among the top Java interview questions for you. Below, we have provided a tabular comparison of Java vs JavaScript so that it becomes easier for you to understand the main differences. 

Java JavaScript 
Object-oriented programming language. Multi-paradigm scripting language with prototype-based objects. 
Statically typed. Variables must be declared with a type. Dynamically typed. Types are resolved at runtime. 
Strongly typed. Loosely typed, with implicit type coercion. 
Compiled to bytecode, then executed by the JVM. Interpreted and JIT-compiled by a JavaScript engine such as V8. 
Runs on the JVM. Needs the JDK to compile and a runtime to execute. Runs in a browser engine or in a server runtime such as Node.js. 
Supports multithreading through the Thread class and the Executor framework. Single-threaded event loop model. Concurrency is handled through async callbacks, Promises, and Web Workers. 
Objects are created from classes. Objects are prototype-based, though class syntax has been available since ES6. 
Higher memory consumption. Lower memory consumption. 
Files use the .java extension. Files use the .js extension. 
Mainly used for backend, enterprise, and Android development. Used for both frontend and backend development. 

Recommended Professional
Certificates

21. Which Java class is considered a superclass of all other classes?

The Object class is the superclass of all classes in Java. Every Java class directly or indirectly inherits from the Object class. 

22. Is it possible for a class to extend itself?

No, a class cannot extend itself in Java. Allowing a class to inherit from itself would create a cyclic inheritance relationship, which is not permitted by the Java compiler

23. What is the difference between Java and C++ programming?

Another important topic among the questions asked in Java interviews is the difference between Java and C++ programming languages. Understanding these differences can help you answer technical interview questions more confidently. To make it easier to understand, we have provided the following comparison between Java and C++. 

Java C++ 
Platform independent Platform dependent 
Uses both a compiler and JVM interpreter Uses a compiler 
Automatic memory management through Garbage Collection Manual memory management 
Supports object-oriented programming Supports both procedural and object-oriented programming 
Does not support pointers directly Supports pointers 
Does not support the goto statement Supports the goto statement 
Developed by James Gosling Developed by Bjarne Stroustrup 
Used for web, mobile, desktop, and enterprise applications Commonly used for system software, game development, and high-performance applications 
Rich standard library and APIs Large collection of standard libraries 
Follows the "Write Once, Run Anywhere" principle Requires separate compilation for different platforms 

24. Explain the difference between JDK, JRE, and JVM

One of the most common Java basic interview questions for freshers is understanding the difference between JDK, JRE, and JVM. The table below provides a simple comparison of their features and functions: 

JDK JRE JVM 
Java Development Kit Java Runtime Environment Java Virtual Machine 
A software development kit used to develop, compile, and debug Java applications. A runtime environment used to run Java applications. A virtual machine that executes Java bytecode and enables platform independence. 
Contains development tools such as the compiler, debugger, and documentation tools. Contains JVM and class libraries required to run Java programs. Responsible for loading, verifying, and executing Java bytecode. 
Platform-dependent. Platform-dependent. Platform-independent. 
Primarily used during application development. Primarily used for running Java applications. Provides the execution engine for Java programs. 
JDK = JRE + Development Tools JRE = JVM + Class Libraries Part of the JRE that executes Java bytecode. 

25. Is it possible to assign a superclass to a subclass in Java?

No, a superclass object cannot be directly assigned to a subclass reference in Java because a superclass does not contain all the properties and methods of its subclass. 

26. How to print text in Java?

The println() and print() methods are used to display text in Java. 

a) println() Example

The println() method prints the text and moves the cursor to the next line. 

public class Main { 
    public static void main(String[] args) { 
        System.out.println("Hi There!"); 
        System.out.println("Welcome to Java!"); 
        System.out.println("Let's learn Java Interview Questions!"); 
    } 
}
Output:
Hi There! 
Welcome to Java! 
Let's learn Java Interview Questions!

b) print() Example

The print() method prints the text without moving to a new line. 

public class Main { 
    public static void main(String[] args) { 
        System.out.print("Hi There! "); 
        System.out.print("I am learning Java."); 
    } 
}
Output:
Hi There! I am learning Java.

27. What is the main() method in Java?

The main() method is the entry point of a Java program. The Java Virtual Machine (JVM) starts program execution from the main() method. Without it, a standalone Java application cannot run. 

Syntax:

public static void main(String[] args)
  • public – Accessible from anywhere. 
  • static – Can be called without creating an object. 
  • void – Does not return any value. 
  • String[] args – Stores command-line arguments passed to the program. 

28. What are variables in Java?

Variables in Java are named memory locations used to store data values. They allow a program to store, modify, and retrieve information during execution. Each variable must be declared with a specific data type, such as int, float, char, or String. 

Example:

int age = 25; 
String name = "John";

In this example, age and name are variables that store an integer value and a string value, respectively. 

29. What are the different data types in Java?

Data types in Java specify the type of data that a variable can store. Java data types are broadly divided into two categories:

1. Primitive Data Types

These are predefined data types provided by Java. 

  • byte 
  • short 
  • int 
  • long 
  • float 
  • double 
  • char 
  • boolean 

2. Non-Primitive Data Types

These data types are created by the programmer and can store multiple values or complex data. 

  • String 
  • Arrays 
  • Classes 
  • Interfaces 
  • Objects 

Java uses these data types to define the kind of value a variable can hold and the operations that can be performed on it. 

30. What is type casting in Java?

Type casting in Java is the process of converting a value from one data type to another. It is commonly used when working with different numeric data types.

There are two types of type casting in Java:

1. Widening Casting (Implicit) – Converts a smaller data type to a larger data type automatically. 

Example: int to long, float to double 

2. Narrowing Casting (Explicit) – Converts a larger data type to a smaller data type manually using a cast operator. 

Example: double to int, long to short 

Example:

double num = 10.5; 
int value = (int) num;

In this example, the double value 10.5 is converted to the int value 10. 

31. What is the difference between primitive and non-primitive data types in Java?

Primitive and non-primitive data types differ in terms of how they store data and their functionality. The table below highlights the main differences:

Primitive Data Types Non-Primitive Data Types 
Store simple values directly. Store references to objects. 
Predefined by Java. Created by programmers or provided by Java libraries. 
Have a fixed size. Size can vary depending on the data. 
Cannot call methods. Can have methods and properties. 
Faster and use less memory. Generally require more memory. 
Examples: int, char, boolean, double. Examples: String, Arrays, Classes, Interfaces, Objects. 

32. What is the difference between a class and an object in Java?

A class is a blueprint or template used to define the properties and behaviors of objects, whereas an object is an instance of a class that contains actual data and can perform actions defined by the class. The table below clearly shows the differences between a class and an object: 

Class Object 
A blueprint or template for creating objects. An instance of a class. 
Defines attributes and methods. Contains actual values for attributes. 
Does not occupy memory until objects are created. Occupies memory when created. 
Used to create multiple objects. Represents a real-world entity. 
Example: Car Example: Honda City, Hyundai i20 

Example: If Car is a class, then a specific car such as Honda City is an object created from that class. 

33. What are comments in Java?

Comments in Java are non-executable lines of text used to explain code, improve readability, and make programs easier to understand. The Java compiler ignores comments during program execution. 

Java supports three types of comments:

  • Single-line comment: // This is a comment 
  • Multi-line comment: /* This is a multi-line comment */ 
  • Documentation comment: /** This is a documentation comment */ 

Comments help developers understand the purpose and functionality of the code without affecting its execution. 

34. What is the use of the static keyword in Java?

This is one of the most asked Java interview questions because the static keyword is a fundamental concept used in class-level programming. 

The static keyword is used to declare class-level variables, methods, blocks, and nested classes. A static member belongs to the class rather than an object, which means it can be accessed without creating an instance of the class. This helps save memory and allows shared access across all objects of the class. 

35. What are command-line arguments in Java?

Command-line arguments are values passed to a Java program when it is executed from the command line. These arguments are stored in the String[] args parameter of the main() method and can be used to provide input to the program at runtime. 

Example:

public class Main { 
    public static void main(String[] args) { 
        System.out.println("Hello " + args[0]); 
    } 
}

If the program is run as:

Java Main John

Output:

Hello John

In this example, John is passed as a command-line argument and stored in args[0]. 

36. What is the use of the new keyword in Java?

The new keyword in Java is used to create objects of a class. When an object is created using new, memory is allocated for the object, and its constructor is called to initialize it. 

Example:

Car car = new Car();

In this example, the new keyword creates an object of the Car class and assigns its reference to the car variable. 

37. Is Java a pure object-oriented language?

No, Java is not a pure object-oriented language. The main reason is that Java supports eight primitive data types (byte, short, int, long, float, double, char, boolean) which are not objects. 

Other reasons commonly cited:

  • Static methods and variables belong to the class, not to any object, and can be used without creating an object. 
  • Wrapper classes exist precisely because primitives are not objects. 

Languages such as Smalltalk and Ruby, where everything is an object, are considered pure object-oriented. 

38. Is Java pass by value or pass by reference?

Java is always pass by value. There is no pass by reference in Java. 

The confusion arises with objects. When an object is passed to a method, a copy of the reference is passed, not the object itself. This means:

  • Modifying the object's contents inside the method does affect the original object, because both references point to the same object. 
  • Reassigning the parameter to a new object inside the method does not affect the original, because only the copy of the reference was changed. 
static void modify(StringBuilder sb) { 
    sb.append(" World");              // affects the original 
    sb = new StringBuilder("New");    // does NOT affect the original 
}

39. Why does Java not support pointers?

Java deliberately omits explicit pointers for three reasons: 

  • Security. Pointers allow direct memory access, which would let code read or modify memory it should not have access to. 
  • Simplicity. Pointer arithmetic is a common source of bugs and is difficult for beginners. 
  • Garbage collection. The garbage collector needs to track all references reliably. Arbitrary pointer arithmetic would make this impossible. 

Java uses references instead, which point to objects but cannot be manipulated arithmetically.

40. What is the difference between instance variables, local variables, and class variables?

Instance Variable Local Variable Class (Static) Variable 
Declared inside a class but outside any method. Declared inside a method, constructor, or block. Declared inside a class with the static keyword. 
Each object has its own copy. Exists only while the method executes. One copy shared by all objects. 
Gets a default value automatically. Has no default value, must be initialised before use. Gets a default value automatically. 
Stored in the heap with the object. Stored on the thread's stack. Stored in the method area, allocated when the class loads. 
Accessed using an object reference. Accessible only within its block. Accessed using the class name. 

41. What are the default values of variables in Java?

Type Default Value 
byte, short, int, long 
float, double 0.0 
char '\u0000' (null character) 
boolean false 
Any object reference null 

An important qualifier: these defaults apply only to instance and static variables. Local variables have no default value and cause a compile-time error if used before being assigned. 

42. Can we override static, private, and final methods in Java?

  • Static methods: no. A subclass can declare a static method with the same signature, but this is method hiding, not overriding. Which method runs is decided at compile time based on the reference type, not at runtime based on the object. 
  • Private methods: no. Private methods are not inherited and are not visible to the subclass, so a method with the same name in the subclass is simply a new, unrelated method. 
  • Final methods: no. The final keyword explicitly prevents overriding. 

43. What is a marker interface in Java?

A marker interface is an interface with no methods and no fields. Its only purpose is to mark or tag a class so that the JVM or a framework can treat it differently at runtime. 

Common examples:

  • Serializable — marks a class as eligible for serialisation 
  • Cloneable — marks a class as safe to clone 
  • Remote — marks a class for RMI 

In modern Java, annotations are generally preferred over marker interfaces, because they carry metadata and do not affect the type hierarchy. 

44. What are varargs in Java?

Varargs, short for variable arguments, allow a method to accept any number of arguments of a given type. It was introduced in Java 5 and uses three dots after the type. 

public int sum(int... numbers) { 
    int total = 0; 
    for (int n : numbers) total += n; 
    return total; 
} 
 
sum();              // valid 
sum(1, 2);          // valid 
sum(1, 2, 3, 4);    // valid

45. What is a covariant return type?

A covariant return type allows an overriding method in a subclass to return a more specific type than the method it overrides. This was introduced in Java 5. 

class Animal { 
    Animal reproduce() { return new Animal(); } 
} 
 
class Dog extends Animal { 
    @Override 
    Dog reproduce() { return new Dog(); }   // returns Dog, not Animal 
}

It removes the need for the caller to downcast the result, which makes the code cleaner and type-safe. 

46. What is a singleton class and how do you implement it?

A singleton class is one that allows only a single instance to exist for the entire application. It is used for shared resources such as configuration objects, logging, and connection pools. 

Thread-safe implementation using double-checked locking: 

class Singleton { 
    private static volatile Singleton instance; 
    private Singleton() {} 
 
    public static Singleton getInstance() { 
        if (instance == null) { 
            synchronized (Singleton.class) { 
                if (instance == null) { 
                    instance = new Singleton(); 
                } 
            } 
        } 
        return instance; 
    } 
}

The volatile keyword is essential here, otherwise a partially constructed object could be visible to another thread. 

Simplest and safest implementation, using an enum: 

java 

enum Singleton { 
    INSTANCE; 
    public void doSomething() { } 
}

The enum approach is recommended because it is thread-safe by default and is protected against reflection and serialisation attacks. 

47. What is the order of execution of static blocks, instance blocks, and constructors?

This appears frequently as an output-based interview question. The order is:

  1. Static variables and static blocks, in the order they appear, once when the class is first loaded 
  2. Instance variables and instance blocks, in the order they appear 
  3. Constructor 

Steps 2 and 3 repeat for every object created. Step 1 runs only once.

java 

class Demo { 
    static { System.out.println("1. Static block"); } 
    { System.out.println("2. Instance block"); } 
    Demo() { System.out.println("3. Constructor"); } 
 
    public static void main(String[] args) { 
        new Demo(); 
        new Demo(); 
    } 
} 
// Output: 1, 2, 3, 2, 3

Java String Interview Questions

1. What is the String Pool in Java?

The String Pool, also called the String Constant Pool, is a special storage area inside heap memory where Java stores string literals. Its purpose is to save memory by reusing string objects instead of creating duplicates. 

When you create a string using a literal, Java first checks whether an identical string already exists in the pool. If it does, the existing reference is returned. If it does not, a new string is created in the pool. 

String s1 = "Java"; 
String s2 = "Java"; 
System.out.println(s1 == s2);   // true, both point to the same pooled object

2. Why is String immutable in Java?

This is one of the most frequently asked Java interview questions for experienced developers. String is immutable, meaning once a String object is created its value cannot be changed. There are four main reasons for this design. 

  • String Pool: Pooling only works if strings cannot change. If one reference could modify a shared string, every other reference pointing to it would be affected. 
  • Security: Strings are used for usernames, database URLs, file paths, and network connections. If they were mutable, a value could be changed after a security check but before it is used. 
  • Thread safety: Immutable objects are inherently thread-safe. A String can be shared across threads with no synchronisation. 
  • Hashcode caching: String caches its hashcode after the first calculation. This makes String extremely efficient as a HashMap key, which would not be possible if the value could change. 

3. What is the difference between creating a String using a literal and using the new keyword?

String Literal new String() 
String s = "Java"; String s = new String("Java"); 
Stored in the String Pool. Always creates a new object in heap memory. 
Reused if the same value already exists in the pool. A new object is created even if an identical string already exists. 
More memory efficient. Uses more memory. 
String s1 = "Java"; 
String s2 = "Java"; 
String s3 = new String("Java"); 
 
System.out.println(s1 == s2);        // true, same pooled object 
System.out.println(s1 == s3);        // false, different memory locations 
System.out.println(s1.equals(s3));   // true, same content

4. What does the intern() method do in Java?

The intern() method moves a string into the String Pool, or returns the existing pooled reference if a string with the same value is already there. 

String s1 = new String("Java"); 
String s2 = s1.intern(); 
String s3 = "Java"; 
 
System.out.println(s1 == s3);   // false 
System.out.println(s2 == s3);   // true

It is useful when working with a large number of duplicate strings, for example strings read from a file or database, because interning them reduces memory usage. 

5. Why is a character array preferred over String for storing passwords?

Because String is immutable, a password stored in a String stays in memory until the garbage collector removes it, and you have no control over when that happens. If a memory dump is taken during that window, the password is visible in plain text. 

A character array can be explicitly overwritten as soon as it is no longer needed. 

java 

char[] password = getPassword(); 
// use the password 
Arrays.fill(password, ' ');   // wiped immediately 

This is also why JPasswordField.getPassword() returns a char[] and not a String.

6. What is the difference between == and equals() when comparing strings?

The == operator compares references, meaning it checks whether two variables point to the same object in memory. The equals() method compares the actual character content of the strings. 

String s1 = new String("Java"); 
String s2 = new String("Java"); 
 
System.out.println(s1 == s2);        // false, different objects 
System.out.println(s1.equals(s2));   // true, same content

For comparing string values, always use equals(). Use equalsIgnoreCase() when case should not matter. 

7. Why does String override equals() and hashCode()?

The default equals() inherited from Object compares references, which would make two strings with identical content compare as unequal. String overrides equals() to compare content instead. 

It also overrides hashCode() because the equals and hashCode contract requires that two objects considered equal must return the same hashcode. Without this, strings would not work correctly as keys in HashMap or HashSet. 

8. Which is faster for string concatenation, String, StringBuilder, or StringBuffer?

StringBuilder is fastest, followed by StringBuffer, with String being by far the slowest for repeated modification. 

  • Concatenating with String in a loop creates a new object on every iteration, which is very expensive. 
  • StringBuilder modifies the same internal character array and is not synchronised, so it has no locking overhead. 
  • StringBuffer does the same thing but is synchronised, which makes it thread-safe but slower. 
// Avoid this 
String result = ""; 
for (int i = 0; i < 1000; i++) { 
    result += i;    // creates 1000 objects 
} 
 
// Use this 
StringBuilder sb = new StringBuilder(); 
for (int i = 0; i < 1000; i++) { 
    sb.append(i);   // modifies one object 
}

Use StringBuilder in single-threaded code, and StringBuffer only when the same object is genuinely shared across threads. 

Note: String handling questions often come with a small code snippet, so it helps to practise running them yourself. You can test all of these examples in our online Java compiler without setting anything up locally.

Java Collections Framework Interview Questions

1. How does HashMap work internally in Java?

This is one of the most commonly asked advanced Java interview questions. A HashMap stores data as key-value pairs using an array of buckets.

How a value is stored: 

  1. The hashCode() of the key is calculated. 
  2. The hash is spread further to reduce collisions, using h ^ (h >>> 16). 
  3. The bucket index is calculated as (n - 1) & hash, where n is the array length. 
  4. The entry is stored in that bucket as a Node containing the hash, key, value, and a reference to the next node. 

How collisions are handled:

When two keys map to the same bucket, the entries are chained together in a linked list. From Java 8 onwards, if a single bucket grows to 8 or more nodes and the table capacity is at least 64, that bucket is converted into a red-black tree. This improves worst-case lookup from O(n) to O(log n). The bucket reverts to a linked list if it shrinks back to 6 nodes. 

Default values to remember:

  • Default initial capacity: 16 
  • Default load factor: 0.75 
  • Resize trigger: when size exceeds capacity multiplied by load factor, the table capacity is doubled and all entries are rehashed. 

How a value is retrieved:

The same hash and index calculation is performed, then the bucket is searched. equals() is used to identify the correct key within the bucket. 

2. What is the contract between equals() and hashCode()?

The contract has three rules:

  • If two objects are equal according to equals(), they must return the same hashCode(). 
  • If two objects have the same hashCode(), they are not necessarily equal. This is a hash collision and is normal. 
  • The hashCode() of an object must return the same value consistently, as long as the fields used in equals() have not changed. 

Why it matters: if you override equals() without overriding hashCode(), objects that are logically equal will land in different buckets in a HashMap or HashSet. The result is that you can put an object into a map and then fail to retrieve it with an equal key. 

This is why equals() and hashCode() must always be overridden together. 

3. What is the difference between HashMap, Hashtable, and ConcurrentHashMap?

HashMapHashtableConcurrentHashMap
Not synchronised. Synchronised on every method. Thread-safe using fine-grained locking. 
Fastest in single-threaded use. Slowest, because the entire map is locked. Fast in multi-threaded use. 
Allows one null key and multiple null values. Does not allow null keys or values. Does not allow null keys or values. 
Introduced in Java 1.2. Legacy class from Java 1.0. Introduced in Java 5. 
Iterators are fail-fast. Enumerations are not fail-fast. Iterators are weakly consistent, they do not throw ConcurrentModificationException. 
Use in single-threaded code. Effectively obsolete, avoid in new code. Use in multi-threaded code. 

Point worth adding: in Java 7, ConcurrentHashMap used segment-level locking with a default concurrency level of 16. From Java 8 it uses CAS operations and synchronises only on the head node of an individual bucket, which allows far higher concurrency. 

4. What is the difference between fail-fast and fail-safe iterators?

Fail-Fast Fail-Safe 
Throws ConcurrentModificationException if the collection is structurally modified during iteration. Does not throw an exception. 
Iterates over the original collection directly. Iterates over a copy or a snapshot of the collection. 
Detects changes using an internal modCount field. Changes made during iteration are not reflected. 
Used by ArrayList, HashMap, HashSet, Vector. Used by CopyOnWriteArrayList, ConcurrentHashMap. 
No extra memory overhead. Higher memory use, because a copy may be maintained. 
List<String> list = new ArrayList<>(List.of("a", "b", "c")); 
for (String s : list) { 
    if (s.equals("b")) { 
        list.remove(s);   // throws ConcurrentModificationException 
    } 
}

To remove safely during iteration, use the iterator's own remove() method or removeIf(). 

5. How does an ArrayList grow dynamically?

An ArrayList is backed by an internal array that is replaced with a larger one when it becomes full. 

  1. The default capacity is 10, allocated lazily on the first add() call. 
  2. When the array is full, a new array is created with a capacity of 1.5 times the old capacity, calculated as oldCapacity + (oldCapacity >> 1). 
  3. All existing elements are copied into the new array. 
  4. The new element is added. 

So the capacity grows 10, 15, 22, 33, and so on. Because resizing is infrequent, the cost of add() is described as amortised constant time. 

If you know roughly how many elements you will store, passing an initial capacity to the constructor avoids repeated resizing. 

6. What is the difference between Iterator and ListIterator?

IteratorListIterator
Traverses in the forward direction only. Traverses both forward and backward. 
Can be used with List, Set, and Map. Can be used with List only. 
Cannot obtain the index of an element. Provides nextIndex() and previousIndex(). 
Can only remove elements. Can add, remove, and replace elements using add() and set(). 
Methods: hasNext(), next(), remove(). Adds hasPrevious(), previous(), add(), set(). 

7. What is the difference between Collection and Collections?

Collection is an interface at the root of the collections hierarchy. List, Set, and Queue all extend it, and it defines core methods such as add(), remove(), and size().

Collections is a utility class in java.util that contains only static helper methods for working with collections, such as sort(), reverse(), shuffle(), min(), max(), unmodifiableList(), and synchronizedList().

8. What is the difference between a Queue and a Deque?

Queue follows FIFO (First In First Out). Elements are added at the tail and removed from the head. Common implementations are LinkedList, PriorityQueue, and ArrayDeque.

A Deque, short for double-ended queue, allows insertion and removal at both ends. It can therefore be used as either a queue (FIFO) or a stack (LIFO). ArrayDeque is the standard implementation and is the recommended replacement for the legacy Stack class.

Deque<Integer> deque = new ArrayDeque<>(); 
deque.addFirst(1); 
deque.addLast(2); 
deque.pollFirst(); 
deque.pollLast();

9. How can you make a collection thread-safe or read-only in Java?

Thread-safe: 

java 

List<String> syncList = Collections.synchronizedList(new ArrayList<>()); 
Map<String, String> syncMap = Collections.synchronizedMap(new HashMap<>()); 
 
// Preferred for concurrent use 
List<String> cowList = new CopyOnWriteArrayList<>(); 
Map<String, String> concurrentMap = new ConcurrentHashMap<>();

Read-only: 

java 

List<String> readOnly = Collections.unmodifiableList(list); 
List<String> immutable = List.of("a", "b", "c");   // Java 9 and later 

Attempting to modify a read-only collection throws UnsupportedOperationException.

Expand the existing Comparable vs Comparator answer with this code 

java 

// Comparable, natural ordering, defined inside the class 
class Employee implements Comparable<Employee> { 
    int id; 
    String name; 
 
    public int compareTo(Employee other) { 
        return this.id - other.id; 
    } 
} 
Collections.sort(employeeList); 
 
// Comparator, custom ordering, defined outside the class 
Comparator<Employee> byName = (e1, e2) -> e1.name.compareTo(e2.name); 
Collections.sort(employeeList, byName); 
 
// Java 8 shorthand 
employeeList.sort(Comparator.comparing(e -> e.name));

Intermediate Java Interview Questions for Experienced (2-5 Years)

If you have 2–5 years of experience in Java development and are preparing for a job change, it is important to have a strong understanding of core Java concepts and their practical applications. 

Below are some of the most asked core Java interview questions and answers for experienced professionals. These questions can help you refresh your knowledge and prepare confidently for technical interviews. 

1. What is multithreading in Java?

Multithreading in Java is the process of executing multiple threads concurrently within a single program. It allows different parts of a program to run simultaneously, improving performance and making better use of CPU resources. 

The main purpose of multithreading is to create lightweight threads that can perform multiple tasks at the same time, resulting in faster and more efficient program execution. 

2. Which class is used for multithreading in Java?

Java provides several ways to create and manage threads. The main ones are: 

1. Extending the Thread class 

java 

class MyThread extends Thread { 
    public void run() { 
        System.out.println("Thread running"); 
    } 
} 
new MyThread().start();

2. Implementing the Runnable interface (preferred) 

java 

class MyTask implements Runnable { 
    public void run() { 
        System.out.println("Thread running"); 
    } 
} 
new Thread(new MyTask()).start();

3. Implementing Callable when the task needs to return a result or throw a checked exception. It is used with an ExecutorService and returns a Future. 

4. Using the ExecutorService from java.util.concurrent, which manages a pool of threads instead of creating them manually. This is the recommended approach in production code. 

Runnable is generally preferred over extending Thread because a Java class can implement multiple interfaces but can extend only one class. Extending Thread uses up that one inheritance slot. 

Suggested Reading: ReactJS Interview Questions and Answers

3. What is Java applet?

An applet was a small Java program embedded in a web page and executed inside a browser through a Java plugin. It was used to add dynamic content to web pages in the early years of Java. 

Applets are obsolete and no longer part of Java. The timeline is: 

  • Java 9 (2017): the Applet API was deprecated (JEP 289). 
  • Java 11 (2018): the appletviewer tool, the Java Plug-in, and Java Web Start were removed. Browsers had already dropped plugin support by then. 
  • Java 17 (2021): the Applet API was deprecated for removal (JEP 398). 
  • JDK 26 (2026): the entire java.applet package was removed (JEP 504). Java 25 is the last release that contains it. 

4. What is garbage collection in Java?

Garbage collection is one of the most important and commonly discussed topics in Java interviews. It is the process of automatically managing memory in Java applications. 

The Garbage Collector (GC) automatically identifies and removes objects that are no longer being used by the program. This frees up memory in the heap and helps optimize memory usage, improving the overall performance of Java applications. 

5. What if you use Java keywords as a variable or identifier?

Java keywords are reserved words and cannot be used as variable names, class names, method names, or other identifiers. If a keyword is used as an identifier, the program will generate a compile-time error. 

6. What is inheritance in Java?

Inheritance is an object-oriented programming (OOP) concept in Java that allows one class to acquire the properties and methods of another class. The class that inherits is called the subclass (child class), and the class being inherited from is called the superclass (parent class). 

Inheritance promotes code reusability, reduces duplication, and helps create a hierarchical relationship between classes. In Java, inheritance is implemented using the extends keyword. 

7. What is polymorphism in Java?

This is yet another important concept in the list of top Java interview questions and answers related to OOPS. 

Polymorphism in Java is an object-oriented programming (OOP) concept that means "many forms." In Java, it refers to the ability of a method, object, or class to take different forms and perform different actions based on the context. 

Polymorphism allows the same method name to behave differently for different objects or parameters. For example, a method can display different messages or perform different operations depending on the values or objects passed to it. This helps improve code flexibility, reusability, and maintainability. 

8. What is encapsulation in Java?

If you are preparing for Java interview questions for 3 years experience or more, encapsulation is one of the important concepts you should understand. 

Encapsulation in Java is the process of combining data (variables) and the methods that operate on that data into a single unit, known as a class. It also helps protect the data by restricting direct access from outside the class and allowing controlled access through methods such as getters and setters. 

An important point to remember is that encapsulation helps achieve data hiding. Once variables are declared as private, they cannot be accessed directly by other classes, which improves security and maintains the integrity of the data. 

9. What is serialization in Java?

Serialization in Java is the process of converting an object into a byte stream so that it can be stored in a file, transferred over a network, or saved for later use.

When needed, the byte stream can be converted back into an object through a process called deserialization. Serialization is commonly used for data storage, object persistence, and communication between applications. 

10. What is Java JDBC?

JDBC (Java Database Connectivity) is an API that enables Java applications to connect to and interact with databases. It allows developers to establish database connections, execute SQL queries, retrieve data, and update records directly from a Java program. 

JDBC acts as a communication bridge between a Java application and a database. With the appropriate JDBC driver, developers can connect to various databases such as MySQL, Oracle, PostgreSQL, and SQL Server. Because it is widely used in database-driven applications, JDBC is an important topic in core Java interview questions for experienced professionals. 

11. What is Java enum?

Enum in Java stands for enumeration. It is a data type that comes with a set of pre-defined constant values. These values are separated by a comma. The enum concept was brought to this programming as part of Java 5. For declaring the enums, the enum keyword is used. 

12. What is constructor overloading in Java?

The role of constructors in Java is to initialize the state of an object. When a class contains multiple constructors with different parameter lists, it is called constructor overloading. 

Constructor overloading allows a class to create and initialize objects in different ways based on the arguments passed during object creation. As a result, a single class can have multiple constructors to handle different initialization requirements. 

13. What is copy constructor in Java?

A copy constructor is a constructor that creates a new object by copying the values of another object of the same class. Java does not provide built-in copy constructors. 

14. Which keyword in Java is used to inherit a class? 

The extends keyword is used in Java to inherit a class. It allows a subclass to acquire the properties and methods of its parent class. 

Also Read: Java Full Stack Developer Roadmap: Full Learning Path 

15. What are the top benefits of inheritance in Java?

The following are the main benefits of Java inheritance: 

  • Code reusability 
  • Method overriding 
  • Ability to achieve runtime polymorphism 
  • Optimize duplicate code 
  • Improve the redundancy of the app 
  • Code flexibility so that it can be changed easily 

16. What are the different memory areas assigned by JVM?

The JVM allocates memory into five main areas to manage program execution efficiently: 

  • Method Area (Class Area) – Stores class metadata, methods, and static variables. 
  • Heap Memory – Stores objects and instance variables created during program execution. 
  • Stack Memory – Stores local variables, method calls, and execution frames for each thread. 
  • Program Counter (PC) Register – Keeps track of the current instruction being executed by a thread. 
  • Native Method Stack – Supports the execution of native (non-Java) methods. 

17. What are access modifiers in Java?

As a programming enthusiast, you should know about the access modifiers while preparing for the Java interview questions and answers.  

As the name suggests, the access modifiers in Java are used to manage the access level for classes, variables, methods, constructors, etc. The access can be changed or specified using these access modifiers.

Access modifiers are of four types:

  • Public 
  • Private 
  • Default 
  • Protected  

18. How many types of inheritance are there in Java?

There are five types of Java inheritance: 

  • Single-level inheritance 
  • Multi-level Inheritance 
  • Hierarchical Inheritance 
  • Multiple Inheritance 
  • Hybrid Inheritance 

19. Can you restrict an object from inheriting its subclass? If yes, how?

Yes, a class can be restricted from being inherited by using the final keyword. A class declared as final cannot be extended by any other class. 

Example:

final class Vehicle { 
}

In this example, the Vehicle class cannot be inherited by another class. 

20. How can we remove duplicate elements from a list of numbers in Java 8?

In Java 8, duplicate elements can be removed from a list using the distinct() method of the Stream API. This method returns a stream containing only unique elements. 

Example:

List<Integer> numbers = Arrays.asList(1, 2, 2, 3, 4, 4, 5); 
List<Integer> uniqueNumbers = numbers.stream() 
                                     .distinct() 
                                     .collect(Collectors.toList());

In this example, the distinct() method removes duplicate values and returns a list containing only unique elements. 

21. What is abstraction in Java?

Abstraction is an object-oriented programming (OOP) concept that hides implementation details and shows only the essential features of an object to the user. 

In Java, abstraction is achieved using abstract classes and interfaces. It helps reduce complexity, improve code maintainability, and focus on what an object does rather than how it does it. 

22. What is the difference between an abstract class and an interface in Java?

Both abstract classes and interfaces are used to achieve abstraction in Java, but they differ in several ways. 

Abstract Class Interface
Declared using the abstract keyword. Declared using the interface keyword. 
Can contain both abstract and concrete methods. Primarily contains abstract methods (can also have default and static methods). 
Can have instance variables and constructors. Cannot have constructors and typically contains constants. 
A class can extend only one abstract class. A class can implement multiple interfaces. 
Used when classes share common state and behavior. Used to define a common contract or capability. 

Abstract classes are suitable when related classes share common functionality, while interfaces are ideal for defining behaviors that multiple unrelated classes can implement. 

23. What is method overloading in Java?

Java Method overloading is a feature that allows a class to have multiple methods with the same name but different parameter lists. The methods can differ in the number, type, or order of parameters. 

Method overloading helps improve code readability and flexibility by allowing the same method to perform similar operations with different inputs. It is an example of compile-time polymorphism in Java. 

24. What is method overriding in Java?

Java Method overriding is a feature where a subclass provides its own implementation of a method that is already defined in its superclass. The overriding method must have the same name, return type, and parameters as the method in the parent class. 

Method overriding allows a subclass to modify or extend the behavior of an inherited method. It is an example of runtime polymorphism in Java. 

25. What is the difference between compile-time polymorphism and runtime polymorphism?

Compile-time polymorphism and runtime polymorphism are two types of polymorphism in Java. The table below highlights their key differences. 

Compile-Time PolymorphismRuntime Polymorphism
Achieved through method overloading. Achieved through method overriding. 
Resolved by the compiler during compilation. Resolved by the JVM during program execution. 
Also known as static binding or early binding. Also known as dynamic binding or late binding. 
Inheritance is not required. Inheritance is required. 
Faster execution because the method call is determined at compile time. Slightly slower because the method call is determined at runtime. 
Example: Multiple methods with the same name but different parameters. Example: A subclass providing its own implementation of a parent class method. 

26. What is the this keyword in Java?

The this keyword in Java refers to the current object of a class. It is used to access the current object's variables, methods, and constructors. 

The this keyword is commonly used to distinguish instance variables from local variables, call another constructor within the same class, and pass the current object as an argument to a method or constructor.

27. What is exception handling in Java?

Exception handling in Java is a mechanism used to handle runtime errors and prevent a program from terminating unexpectedly. It allows developers to detect, manage, and recover from exceptional situations during program execution. 

Java provides the try, catch, finally, throw, and throws keywords for exception handling. By handling exceptions properly, programs can continue running smoothly even when errors occur. 

28. What is the difference between checked and unchecked exceptions in Java?

Checked and unchecked exceptions differ in how they are handled by the Java compiler. 

Checked Exceptions Unchecked Exceptions 
Checked at compile time. Checked at runtime. 
Must be handled using try-catch or declared with throws. Handling is optional. 
Subclasses of Exception (excluding RuntimeException). Subclasses of RuntimeException. 
Occur due to external factors such as file or database issues. Usually occur because of programming errors. 
Examples: IOException, SQLException. Examples: NullPointerException, ArithmeticException. 

Checked exceptions help ensure error handling during compilation, while unchecked exceptions indicate issues that are typically fixed in the program logic. 

29. What is the difference between Array and ArrayList in Java?

Arrays and ArrayLists are both used to store collections of elements, but they differ in several ways. 

ArrayArrayList
Has a fixed size once created. Can grow or shrink dynamically. 
Can store primitive data types and objects. Stores objects only (wrapper classes for primitives). 
Faster in performance due to fixed size. Slightly slower because of dynamic resizing. 
Length is accessed using the length property. Size is accessed using the size() method. 
Part of the core Java language. Part of the Java Collections Framework. 
Elements are accessed using indexes. Elements are accessed using methods such as get() and set(). 

Arrays are suitable when the size is known in advance, while ArrayLists are preferred when the number of elements can change dynamically. 

30. What is the purpose of the try-catch-finally block in Java?

The try-catch-finally block in Java is used for exception handling. It helps a program handle runtime errors gracefully and continue execution without crashing. 

  • try – Contains the code that may throw an exception. 
  • catch – Handles the exception if one occurs in the try block. 
  • finally – Contains code that is always executed, whether an exception occurs or not. 

Using try-catch-finally improves program reliability and ensures that important cleanup tasks, such as closing files or database connections, are performed properly. 

Advanced Java Interview Questions and Answers for Experienced (5-10 Years)

If you have 5–10 years of experience in Java development, the questions below will help you prepare for advanced technical interviews. These commonly asked topics focus on deeper Java concepts and real-world application knowledge. 

1. What is the difference between heap memory and stack memory in Java?

Two types of memory are used in the Java Virtual Machine (JVM). One is heap memory, and another is stack memory.  

The primary difference between the two is that heap memory’s role is to store objects, whereas stack memory stores local variables and the order of method execution. The following tabular comparison shows all the key differences between the both. While preparing for Java interview questions and answers, ensure to understand this concept well. 

Heap Memory Stack Memory 
Stores objects and their instance variables. Stores method frames, local variables, and reference variables. 
Shared by all threads in the application. Each thread gets its own separate stack. 
Larger in size. Much smaller in size. 
Memory is allocated when an object is created and reclaimed automatically by the garbage collector. Memory is allocated and released automatically as method frames are pushed and popped. 
No fixed allocation order. Follows LIFO (Last In First Out) order. 
Access is comparatively slower. Access is faster. 
Objects stay in memory as long as they are reachable. Local variables are destroyed as soon as the method returns. 
Size is configured using -Xms and -Xmx. Size is configured using -Xss. 
Running out of space throws OutOfMemoryError: Java heap space. Running out of space throws StackOverflowError, usually from deep or infinite recursion. 

2. Which are the most widely used Java IDEs and development tools?

First, a clarification that interviewers appreciate: the actual Java compiler is javac, which ships with the JDK. The tools listed below are IDEs and development environments that use javac under the hood. 

Most widely used Java IDEs:

  • IntelliJ IDEA — the most popular Java IDE in professional use 
  • Eclipse — long-established open-source IDE with a large plugin ecosystem 
  • Visual Studio Code — with the Extension Pack for Java 
  • NetBeans — Apache-maintained open-source IDE 
  • Android Studio — the official IDE for Android development, built on IntelliJ 
  • JDeveloper — Oracle's IDE, used mainly with Oracle enterprise products 

Teaching-focused IDEs:

  • BlueJ and jGRASP, both designed for students learning Java 

Supporting build and productivity tools:

  • Maven and Gradle for build automation and dependency management 
  • JUnit for unit testing

3. What is the difference between equals() method and equality (==) operator in Java?

There are a number of key differences between the equals method and the equality operator in Java. The primary difference is that one is a method, and another is an operator. 

Such tricky concepts are usually asked when you have some experience in this field. So, you need to study the core Java interview questions and answers for experienced professionals really well. 

For this question, we have created a tabular comparison to help you understand the differences between the equals method and equality operator in Java. 

Equals() Method Equality Operator (==) 
It is a method It is an operator 
Its role is for comparing the content of an object Its role is for comparing the reference values and objects 
It can be overridden Can’t be overridden 
Can’t be used with primitives Can be used with primitives 

4. Can you inherit static members to a subclass?

Yes, static members are inherited by subclasses in Java. However, they belong to the class rather than an object and are typically accessed using the class name. 

Example: 

class Parent { 
    static int value = 10; 
} 
 
class Child extends Parent { 
}

In this example, Child can access value because it inherits the static member from Parent. 

Suggested Reading: Java Syllabus (Curriculum): Full Course Outline 

5. Can you override a final method in Java?

No, a final method cannot be overridden in Java. When a method is declared with the final keyword, subclasses are not allowed to provide their own implementation of that method. 

6. How to declare an infinite loop in Java?

An infinite loop is a loop that continues to execute indefinitely because its condition never becomes false. In Java, infinite loops can be created using while, for, and do-while loops. 

a) Infinite while Loop

while (true) { 
    // code 
}

b) Infinite for Loop

for (;;) { 
    // code 
}

c) Infinite do-while Loop

do { 
    // code 
} while (true);

All three loops run continuously until they are terminated using a break statement or the program is stopped externally. 

7. What are the roles of final, finally, and finalize keywords in Java?

There are several keywords in Java, and three commonly confused keywords are final, finally, and finalize. The table below highlights their differences: 

final finally finalize 
Used to apply restrictions on classes, methods, and variables. Used in exception handling. A method on Object that the garbage collector could call before reclaiming an object. Deprecated for removal. 
Can be applied to classes, methods, and variables. Used with try-catch blocks. Associate Associated with objects, not with classes or variables. d with objects. 
A final variable cannot be reassigned, a final method cannot be overridden, and a final class cannot be inherited. Executes whether an exception occurs or not. Was intended for cleanup before garbage collection, but execution was never guaranteed. 
Applied when it is declared. Executes after the try-catch block completes. Deprecated since Java 9 and deprecated for removal in Java 18. 

8. When to use the super keyword in Java?

The super keyword in Java is used to refer to the immediate parent class of a subclass. It is commonly used to access parent class variables, invoke parent class methods, and call the parent class constructor. 

Using the super keyword helps a subclass access members of its superclass, especially when the parent and child classes have variables or methods with the same name. 

9. What is a ClassLoader in Java?

A Java ClassLoader is used to load the classes in JRE in a dynamic manner. It is an important component in the Runtime Environment that loads the class into the memory part of the JRE. 

It is because of ClassLoaders that the JRE doesn’t have to have information about the files loaded to it.  

10. What are the different types of ClassLoaders in Java?

Java uses three built-in ClassLoaders, and the middle one changed in Java 9. 

a) Bootstrap ClassLoader

Loads the core Java classes. In Java 8 and earlier it loaded classes from rt.jar. From Java 9 onward it loads the core platform modules such as java.base. It is written in native code and is the parent of all other ClassLoaders. 

b) Platform ClassLoader (called the Extension ClassLoader in Java 8 and earlier)

In Java 8 and earlier, the Extension ClassLoader loaded classes from the JDK extensions directory (jre/lib/ext). That directory and the Extension ClassLoader were removed in Java 9 and replaced by the Platform ClassLoader, which loads the Java SE platform modules that are not loaded by the Bootstrap ClassLoader. It is a child of the Bootstrap ClassLoader. 

c) System ClassLoader (also called the Application ClassLoader)

Loads the application's own classes from the classpath or module path. It is a child of the Platform ClassLoader and is the one that loads the code you write. 

ClassLoaders follow the delegation model: a request is passed up to the parent first, and only if the parent cannot find the class does the child attempt to load it. 

11. Is it possible to access the members of a subclass if you create a superclass’ object?

No, it is not possible. A superclass object can access only the members defined in the superclass. Subclass-specific members cannot be accessed through it. 

12. How to define a functional interface in Java?

functional interface in Java can be defined using the @FunctionalInterface annotation. Introduced in Java 8, it ensures that the interface contains only one abstract method. 

13. How are lambda expressions and functional interfaces interrelated?

A functional interface is an interface that contains exactly one abstract method. It can be used as the target type for a lambda expression or a method reference

java 

@FunctionalInterface 
interface Calculator { 
    int operate(int a, int b); 
} 
 
Calculator add = (a, b) -> a + b;

The @FunctionalInterface annotation is optional. Any interface with a single abstract method is a functional interface whether or not it is annotated. What the annotation does is instruct the compiler to enforce the rule, so if someone later adds a second abstract method, the code fails to compile. This makes it a safety measure rather than a requirement. 

Runnable, Comparator, and Callable are all functional interfaces that existed long before Java 8 introduced the annotation. 

14. How many abstract methods can a functional interface have in Java 8?

A functional interface must have exactly one abstract method. That single method defines what the interface does and is what a lambda expression implements. 

Alongside that one abstract method, a functional interface may also contain:

  • Any number of default methods 
  • Any number of static methods 
  • Any number of private methods (Java 9 and later) 

None of these count towards the single-abstract-method rule, because they all have an implementation. 

15. What rules must be followed when defining a functional interface in Java 8?

Programmers need to follow these guidelines: 

  • The interface must contain exactly one abstract method. Adding a second one breaks the contract. 
  • The abstract method can have any name. There is no reserved name. 
  • Use the @FunctionalInterface annotation so the compiler enforces the rule. It is optional but strongly recommended. 
  • Default, static, and private methods are allowed and do not count as abstract methods. 
  • Redeclaring a public method of java.lang.Object, such as equals(), hashCode(), or toString(), does not count as an abstract method, because every implementing class already inherits an implementation from Object. 
  • A functional interface may extend another interface, but only if the combined result still has exactly one abstract method. 

16. What are the different types of functional interfaces in Java 8?

These are the main types of functional interface: 

  • Consumer 
  • Predicate 
  • Supplier 
  • Function (UnaryOperator and BinaryOperator) 

17. State the biggest difference between Map and FlatMap.

Both map() and flatMap() transform the elements of a stream, but they differ in how they handle the result. 

map() is a one-to-one transformation. It applies a function to each element and produces a stream with the same number of elements. If the function itself returns a stream or a collection, the result becomes a stream of streams, such as Stream<List<String>>, which is usually not what you want. 

flatMap() is a one-to-many transformation. It maps each element to a stream and then flattens all those streams into a single stream. 

Example:

List<List<String>> nested = Arrays.asList( 
    Arrays.asList("a", "b"), 
    Arrays.asList("c", "d") 
); 
 
// map produces a nested result 
Stream<Stream<String>> mapped = nested.stream().map(List::stream); 
 
// flatMap produces a single flat stream: a, b, c, d 
List<String> flat = nested.stream() 
                          .flatMap(List::stream) 
                          .collect(Collectors.toList());

In short: use map() when each element becomes exactly one new element, and use flatMap() when each element expands into multiple elements that need to be merged into one stream. 

18. What is the primary benefit for which one should use Metaspace over PermGen?

The main advantage of Metaspace over PermGen is where the memory lives and how it grows. 

PermGen was part of the Java heap and had a fixed maximum size set at JVM startup. If an application loaded more classes than that fixed space allowed, it would fail with java.lang.OutOfMemoryError: PermGen space, which was a common problem in applications that loaded many classes or redeployed frequently. 

Metaspace, introduced in Java 8, stores class metadata in native memory instead of the heap. It grows automatically as more classes are loaded, so the fixed-ceiling problem largely disappears. 

Metaspace is not unlimited, though. It is bounded by the native memory available to the process, and it can be explicitly capped using -XX:MaxMetaspaceSize. -XX:MetaspaceSize sets the initial threshold at which the first garbage collection of class metadata is triggered. If Metaspace is exhausted, the JVM throws OutOfMemoryError: Metaspace. 

19. What is the difference between composition and aggregation in Java?

Both composition and aggregation are associations in Java. The former is considered a strong association, while the latter is considered a weak association. Let’s understand the differences between them with the below tabular comparison: 

Aggregation Composition 
Weak  Strong 
There is a relationship between classes A class belongs to another class 
Interrelated classes can be independent Classes are dependent on each other. 
As the classes can be independent, it is great for reusing the code As the classes are not independent, code reusability becomes difficult  

20. What is synchronization in Java?

Synchronization in Java is a mechanism used to control access to shared resources when multiple threads are running simultaneously. It ensures that only one thread can access a synchronized block or method at a time, preventing data inconsistency and thread interference. 

Synchronization helps maintain data integrity and enables safe communication between threads in multithreaded applications. 

21. What is the difference between a process and a thread in Java?

A process and a thread are both units of execution, but they differ in how they use system resources and memory. 

Process Thread 
An independent program in execution. A lightweight unit of execution within a process. 
Has its own memory space and resources. Shares memory and resources with other threads in the same process. 
Creation and execution are relatively slower. Creation and execution are faster. 
Communication between processes is more complex. Threads can communicate easily through shared memory. 
More resource-intensive. Less resource-intensive. 

22. What is the difference between String, StringBuilder, and StringBuffer in Java?

Below are the key differences between String, StringBuilder, and StringBuffer in Java: 

String StringBuilder StringBuffer 
Immutable (cannot be modified after creation). Mutable (can be modified). Mutable (can be modified). 
Slower when performing frequent string modifications. Faster than String and StringBuffer. Slower than StringBuilder due to synchronization. 
Thread-safe because it is immutable. Not thread-safe. Thread-safe (synchronized). 
Creates a new object for every modification. Modifies the existing object. Modifies the existing object. 
Suitable for fixed string values. Suitable for single-threaded applications. Suitable for multi-threaded applications. 

23. What is reflection in Java?

Reflection in Java is a feature that allows a program to inspect and manipulate classes, methods, fields, and constructors at runtime. It enables developers to examine object details and invoke methods dynamically without knowing their names at compile time. 

Reflection is commonly used in frameworks, debugging tools, testing libraries, and dependency injection mechanisms. 

24. What is the use of the transient keyword in Java?

The transient keyword in Java is used to exclude a variable from the serialization process. When an object is serialized, transient variables are not saved and are ignored by the JVM. 

This keyword is commonly used for sensitive or temporary data that should not be stored or transferred during serialization. 

25. What is the difference between Comparable and Comparator in Java?

Below are the key differences between Comparable and Comparator in Java: 

ComparableComparator
Used to define the natural ordering of objects. Used to define custom ordering of objects. 
Implemented using the Comparable interface. Implemented using the Comparator interface. 
Contains the compareTo() method. Contains the compare() method. 
Sorting logic is defined inside the class. Sorting logic is defined in a separate class or lambda expression. 
Allows only one sorting sequence. Allows multiple sorting sequences. 
Example: Sort employees by ID. Example: Sort employees by name, salary, or age. 

26. What is the purpose of the volatile keyword in Java?

The volatile keyword ensures that a variable's value is always read from and written to the main memory. 

  • It makes changes made by one thread immediately visible to other threads. 
  • It helps prevent data inconsistency and visibility issues in multithreaded applications. 
  • It is commonly used for shared variables accessed by multiple threads. 

27. What is deadlock in Java?

Deadlock in Java is a situation where two or more threads are blocked indefinitely because each thread is waiting for a resource that is held by another thread. 

  • Occurs when multiple threads wait for each other to release resources. 
  • Causes the program to stop making progress. 
  • Commonly happens in multithreaded applications with improper synchronization. 

Can be prevented by managing resource locks carefully and maintaining a consistent lock order. 

28. What is the difference between shallow copy and deep copy in Java?

The following table compares shallow copy and deep copy in Java: 

Shallow Copy Deep Copy 
Copies the object's fields but shares references to nested objects. Copies the object and all referenced objects recursively. 
Changes to referenced objects affect both original and copied objects. Changes to copied objects do not affect the original object. 
Faster and uses less memory. Slower and requires more memory. 
Creates a partial copy of the object. Creates a completely independent copy of the object. 
Commonly implemented using clone() with default behavior. Requires manual copying of referenced objects. 

29. What is the difference between throw and throws in Java?

This is also one of the most common Java advanced interview questions, as exception handling is a fundamental concept that every experienced Java developer should understand. 

The throw keyword is used to explicitly throw an exception within a method or block of code. On the other hand, the throws keyword is used in a method declaration to specify the exceptions that the method may throw during execution. 

In simple terms, throw is used to generate an exception, whereas throws is used to declare and pass the responsibility of handling an exception to the calling method. 

30. What are immutable objects in Java?

Immutable objects in Java are objects whose state cannot be modified after creation. Once initialized, their data remains unchanged throughout their lifetime, making them thread-safe, secure, and reliable. The String class is a common example of an immutable object.

31. What is autoboxing and unboxing in Java?

Autoboxing is the automatic conversion of a primitive data type into its corresponding wrapper class object, while unboxing is the automatic conversion of a wrapper class object back to its primitive data type. These features simplify data handling and reduce the need for manual conversions in Java. 

32. What is the difference between List, Set, and Map in Java?

The table below highlights the key differences between List, Set, and Map in Java: 

ListSetMap
Stores elements in an ordered sequence. Stores unique elements only. Stores data as key-value pairs. 
Allows duplicate elements. Does not allow duplicate elements. Keys must be unique, but values can be duplicated. 
Maintains insertion order. May or may not maintain insertion order, depending on the implementation. Stores mappings between keys and values. 
Elements are accessed by index. Elements are accessed through iteration. Values are accessed using keys. 
Examples: ArrayList, LinkedList, Vector. Examples: HashSet, LinkedHashSet, TreeSet. Examples: HashMap, LinkedHashMap, TreeMap. 

33. What is the difference between ArrayList and LinkedList in Java?

The table below highlights the key differences between ArrayList and LinkedList in Java: 

ArrayListLinkedList
Uses a dynamic array to store elements. Uses a doubly linked list to store elements. 
Faster for accessing elements by index. Slower for random access. 
Insertion and deletion are slower, especially in the middle of the list. Insertion and deletion are faster. 
Requires less memory overhead. Requires more memory to store node links. 
Better for frequent read operations. Better for frequent insert and delete operations. 
Implements the List interface. Implements both List and Deque interfaces. 

34. What is the difference between HashSet and TreeSet in Java?

The table below highlights the key differences between HashSet and TreeSet in Java: 

HashSetTreeSet
Stores elements using a hash table. Stores elements using a tree structure (Red-Black Tree). 
Does not maintain any order of elements. Stores elements in sorted order. 
Provides faster insertion, deletion, and search operations. Generally slower due to sorting operations. 
Allows one null element. Does not allow null elements. 
Suitable when ordering is not required. Suitable when sorted data is required. 
Implements the Set interface. Implements the NavigableSet and SortedSet interfaces. 

36. What is the difference between Runnable interface and Thread class in Java?

The table below highlights the key differences between the Runnable interface and the Thread class in Java:

Runnable InterfaceThread Class
Defined as an interface. Defined as a class. 
Requires implementing the run() method. Requires extending the Thread class and overriding the run() method. 
Supports multiple inheritance because a class can implement multiple interfaces. Does not support multiple inheritance because Java classes can extend only one class. 
Separates the task from the thread execution mechanism. Combines both the task and thread execution mechanism. 
Preferred for better code flexibility and reusability. Less flexible due to class inheritance limitations. 
Executed by passing the object to a Thread instance. Executed by creating and starting a subclass of Thread. 

37. What is a wrapper class in Java?

wrapper class in Java is a class that converts a primitive data type into an object. Each primitive type has a corresponding wrapper class, such as Integer for int, Double for double, Character for char, and Boolean for boolean. 

Wrapper classes are useful when working with collections, generics, and APIs that require objects instead of primitive data types. 

Note: Once you have gone through these advanced topics, it is worth checking how much you actually remember. Try our Java quiz to identify the areas that still need revision before your interview.

Java Coding Interview Questions

Almost every Java interview includes at least one coding round. The questions below are the ones that come up most often, along with the approach interviewers expect. For a wider set of practice problems, go through our collection of Java programs covering strings, arrays, patterns, and collections. 

1. Write a Java program to reverse a string without using the reverse method

public class ReverseString { 
    public static String reverse(String str) { 
        char[] chars = str.toCharArray(); 
        int left = 0, right = chars.length - 1; 
        while (left < right) { 
            char temp = chars[left]; 
            chars[left++] = chars[right]; 
            chars[right--] = temp; 
        } 
        return new String(chars); 
    } 
}

Time complexity O(n), space complexity O(n). 

2. Write a Java program to check whether a string is a palindrome

public static boolean isPalindrome(String str) { 
    int left = 0, right = str.length() - 1; 
    while (left < right) { 
        if (str.charAt(left++) != str.charAt(right--)) { 
            return false; 
        } 
    } 
    return true; 
}

Using two pointers avoids creating a reversed copy, so space complexity is O(1). 

3. Write a Java program to check whether two strings are anagrams

public static boolean isAnagram(String a, String b) { 
    if (a.length() != b.length()) return false; 
    int[] count = new int[256]; 
    for (int i = 0; i < a.length(); i++) { 
        count[a.charAt(i)]++; 
        count[b.charAt(i)]--; 
    } 
    for (int c : count) { 
        if (c != 0) return false; 
    } 
    return true; 
}

The counting approach runs in O(n). Sorting both strings also works but is O(n log n). 

4. Write a Java program to find the first non-repeating character in a string

public static char firstNonRepeating(String str) { 
    Map<Character, Integer> counts = new LinkedHashMap<>(); 
    for (char c : str.toCharArray()) { 
        counts.put(c, counts.getOrDefault(c, 0) + 1); 
    } 
    for (Map.Entry<Character, Integer> e : counts.entrySet()) { 
        if (e.getValue() == 1) return e.getKey(); 
    } 
    return '\0'; 
}

LinkedHashMap is used because insertion order must be preserved to find the first such character. 

5. Write a Java program to find the missing number in an array from 1 to n

public static int findMissing(int[] arr) { 
    int n = arr.length + 1; 
    int expectedSum = n * (n + 1) / 2; 
    int actualSum = 0; 
    for (int num : arr) actualSum += num; 
    return expectedSum - actualSum; 
}

Runs in O(n) time and O(1) space, which is what the interviewer is checking for. 

6. Write a Java program to remove duplicates from a list

// Using Set 
List<Integer> unique = new ArrayList<>(new LinkedHashSet<>(list)); 
 
// Using Streams 
List<Integer> unique = list.stream() 
                           .distinct() 
                           .collect(Collectors.toList());

LinkedHashSet preserves insertion order, whereas HashSet does not. 

7. Write a Java program to count the occurrences of each character in a string

Map<Character, Long> counts = str.chars() 
    .mapToObj(c -> (char) c) 
    .collect(Collectors.groupingBy(c -> c, Collectors.counting()));

Being able to give both a loop-based and a Streams-based solution is what distinguishes a strong candidate here. 

Note: Solving problems under time pressure is a different skill from writing code at your own pace. Working through structured Java coding challenges is the closest practice you can get to an actual interview round.

List of Java 8 Interview Questions

Java 8 is among the newest versions of this programming language. The Java 8 interview questions can be asked to a candidate with any experience level. Undoubtedly, the level of questions will be according to your experience range. 

Here are some of the most common interview questions on Java 8:

  • What are the new features in Java SE 8?
  • What are some of the main benefits of using Java 8?
  • Define optional class. 
  • What is a functional interface in Java 8? 
  • Define MetaSpace. 
  • What is the meaning of the String::ValueOf expression? 
  • Explain the concept of streams in Java 8. 
  • What is Nashorn in Java 8? 
  • How is MetaSpace different from PermGen? 
  • What do you mean by method reference? 
  • Explain intermediate and terminal operations. 
  • Which are the most used terminal operations? 
  • Is it possible for a functional interface to inherit another interface? 
  • What is the difference between findFirst() and findAny()? 
  • Which are the key components of a Java stream? 
  • Which functional interfaces come pre-defined in Java 8? 
  • What does type interface mean? 
  • State the syntax of a lambda expression. 
  • What is the difference between collection and stream? 
  • Explain the role of JJS in Java 8. 

Find Java 8 interview questions and answers by clicking on the linked write-up 

Practice Java Programs for Interview Preparation

For more Java Programs to practice, visit our Java Programs page.

Article by

Virendra Soni

Virendra is an SEO Content Writer with 7+ years of experience in blogging, content marketing, SEO, and content editing. He holds a B.Tech. in Electronics and Communication Engineering (ECE) and has worked across the IT and EdTech industries. Virendra specializes in creating SEO-friendly, user-focused content that drives organic traffic and improves search rankings. His mantra is simple: keep it clear, make it memorable, and create content that both readers and search engines love.
Share This Article
Leave a comment
Your email address will not be published. Required fields are marked *

Leave a Reply

Your email address will not be published. Required fields are marked *

Save my name, email, and website in this browser for the next time I comment.

Comments (0)

No comments yet.