Top 50 Java Interview Questions for Freshers (2026 Updated with Answers)

February 10, 2026 305 views min read

Here is the complete guide in the same format you provided, with code snippets and content added for all 50 questions. The design and structure are identical to your original. ---

1️⃣ What is Java?

Java is a high-level, object-oriented programming language developed by Sun Microsystems in 1995 and currently maintained by Oracle. It is designed to be platform-independent, secure, robust, and portable. The most important feature of Java is its "Write Once, Run Anywhere" capability. This means that once Java source code is compiled into bytecode, it can run on any platform that has a Java Virtual Machine (JVM).

Java follows object-oriented programming principles such as encapsulation, inheritance, polymorphism, and abstraction. It is widely used for enterprise-level applications, web services, Android development, banking systems, and distributed systems.

Java uses automatic memory management through garbage collection, which reduces memory leaks and improves stability.

Example:

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

This program demonstrates class structure and the main method, which is the entry point of execution.


2️⃣ What are the main features of Java?

Java provides several important features that make it powerful and widely adopted:

  • Platform Independent

  • Object-Oriented

  • Secure

  • Robust

  • Multithreaded

  • Distributed

  • Automatic Memory Management

Platform independence is achieved through JVM. Java is object-oriented because everything is based on classes and objects. It includes built-in security features such as bytecode verification and runtime security checks.

Java is robust because it uses strong memory management, exception handling, and type checking. It supports multithreading, allowing multiple threads to execute simultaneously.

These features make Java ideal for large-scale enterprise applications and backend development.


3️⃣ Explain JVM, JRE, and JDK.

JVM (Java Virtual Machine) is responsible for executing Java bytecode. It converts bytecode into machine-specific instructions.

JRE (Java Runtime Environment) contains JVM and required libraries to run Java programs.

JDK (Java Development Kit) includes JRE, compiler (javac), and development tools.

Structure:

  • JDK = JRE + Development Tools

  • JRE = JVM + Libraries

  • JVM = Executes bytecode

When you write a Java program, it is compiled by the JDK into bytecode. That bytecode runs inside the JVM.


4️⃣ What is OOP in Java?

Object-Oriented Programming (OOP) is a programming paradigm based on objects and classes. Java follows four main OOP principles:

  • Encapsulation

  • Inheritance

  • Polymorphism

  • Abstraction

OOP improves modularity, reusability, scalability, and maintainability of code. Instead of writing procedural code, Java organizes logic around real-world entities.

Example:

 
 
class Car {
String brand;
void start() {
System.out.println("Car Started");
}
}
 

Here, Car is a class, and start() represents behavior.


5️⃣ What is Encapsulation?

Encapsulation is the process of wrapping data and methods inside a class and restricting direct access to data. In Java, encapsulation is implemented using private variables and public getter/setter methods.

Benefits:

  • Data hiding

  • Security

  • Better control over data

  • Improved maintainability

Example:

 
 
class Student {
private int marks;

public void setMarks(int marks) {
this.marks = marks;
}

public int getMarks() {
return marks;
}
}
 

Here, marks cannot be accessed directly. It is accessed through methods.


6️⃣ What is Inheritance?

Inheritance allows one class to acquire properties and behavior of another class. It promotes code reuse.

In Java, inheritance is achieved using the extends keyword.

Example:

 
 
class Animal {
void eat() {
System.out.println("Eating");
}
}

class Dog extends Animal {
void bark() {
System.out.println("Barking");
}
}
 

Dog inherits eat() from Animal.

Types:

  • Single

  • Multilevel

  • Hierarchical

Java does not support multiple inheritance using classes to avoid ambiguity.


7️⃣ What is Polymorphism?

Polymorphism means "many forms." It allows methods to behave differently based on context.

Types:

  • Compile-time polymorphism (Method Overloading)

  • Runtime polymorphism (Method Overriding)

Example (Overloading):

 
 
class Calculator {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
}
 

Example (Overriding):

 
 
class Parent {
void show() {
System.out.println("Parent");
}
}
class Child extends Parent {
void show() {
System.out.println("Child");
}
}
 

8️⃣ What is Abstraction?

Abstraction hides internal implementation details and shows only essential features.

In Java, abstraction is achieved using:

  • Abstract classes

  • Interfaces

Example:

 
 
abstract class Shape {
abstract void draw();
}

class Circle extends Shape {
void draw() {
System.out.println("Drawing Circle");
}
}
 

The user only knows draw() exists, not its internal implementation.


9️⃣ What is the difference between == and equals()?

== compares memory references.

equals() compares content (if overridden).

Example:

 
 
String a = new String("Java");
String b = new String("Java");

System.out.println(a == b); // false
System.out.println(a.equals(b)); // true
 

== checks whether both objects refer to same memory location.


🔟 What is Constructor?

A constructor is a special method used to initialize objects. It has the same name as the class and does not have a return type.

Types:

  • Default constructor

  • Parameterized constructor

Example:

 
 
class Person {
String name;

Person(String name) {
this.name = name;
}
}
 

Constructor runs automatically when object is created.


1️⃣1️⃣ What is String immutability in Java?

In Java, String objects are immutable, which means once a String object is created, its value cannot be changed. If you modify a String, a new object is created instead of changing the existing one.

This design improves security, performance, and thread safety. For example, Strings are used in class loading, networking, and file paths. If Strings were mutable, they could be altered after validation, leading to security risks.

Another benefit is the String Constant Pool. When you create a String using double quotes, Java checks if the same value already exists in the pool. If yes, it reuses the existing object, saving memory.

Example:

 
 
String a = "Java";
String b = a.concat(" Interview");

System.out.println(a); // Java
System.out.println(b); // Java Interview
 

Here, a remains unchanged. A new object is created for b.


1️⃣2️⃣ What is the difference between String, StringBuilder, and StringBuffer?

All three are used to handle strings, but they differ in mutability and thread safety.

  • String → Immutable

  • StringBuilder → Mutable, not thread-safe

  • StringBuffer → Mutable, thread-safe

If you are modifying strings frequently, using StringBuilder is more efficient than String because it avoids creating multiple objects.

StringBuffer is synchronized, meaning it is safe for multi-threaded environments but slightly slower than StringBuilder.

Example:

 
 
StringBuilder sb = new StringBuilder("Hello");
sb.append(" World");
System.out.println(sb);
 

Use:

  • String → when value does not change

  • StringBuilder → single-threaded modification

  • StringBuffer → multi-threaded modification


1️⃣3️⃣ What is Exception Handling in Java?

Exception handling is a mechanism to handle runtime errors and maintain normal program flow. Java uses try, catch, finally, throw, and throws keywords.

Types of Exceptions:

  • Checked Exceptions (compile-time)

  • Unchecked Exceptions (runtime)

  • Errors

Example:

 
 
try {
int a = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
} finally {
System.out.println("Execution Completed");
}
 

The finally block always executes, whether an exception occurs or not.

Exception handling improves robustness and prevents program crashes.


1️⃣4️⃣ What is the difference between Checked and Unchecked Exceptions?

Checked Exceptions are checked at compile time. The compiler forces you to handle them using try-catch or throws.

Examples:

  • IOException

  • SQLException

Unchecked Exceptions occur at runtime and are not checked at compile time.

Examples:

  • NullPointerException

  • ArithmeticException

Example:

 
 
FileReader file = new FileReader("file.txt"); // Checked Exception
 

You must handle it, otherwise compilation fails.

Unchecked exceptions usually occur due to logical errors in code.


1️⃣5️⃣ What is the Collection Framework?

The Collection Framework in Java provides predefined classes and interfaces to store and manipulate data.

Main interfaces:

  • List

  • Set

  • Queue

  • Map

List allows duplicates.
Set does not allow duplicates.
Map stores key-value pairs.

Example:

 
 
import java.util.ArrayList;

ArrayList<String> list = new ArrayList<>();
list.add("Java");
list.add("Python");
System.out.println(list);
 

Collections provide dynamic sizing and built-in methods for sorting, searching, and iteration.


1️⃣6️⃣ Difference between ArrayList and LinkedList?

ArrayList:

  • Uses dynamic array

  • Fast for random access

  • Slow for insertion/deletion in middle

LinkedList:

  • Uses doubly linked list

  • Fast for insertion/deletion

  • Slower for random access

Example:

 
 
ArrayList<Integer> arr = new ArrayList<>();
LinkedList<Integer> list = new LinkedList<>();
 

Choose based on requirement:

  • Frequent reads → ArrayList

  • Frequent insert/delete → LinkedList


1️⃣7️⃣ What is HashMap?

HashMap is a class that implements the Map interface and stores data in key-value pairs.

Features:

  • Allows one null key

  • Allows multiple null values

  • Not thread-safe

  • No guaranteed order

HashMap works on hashing. It calculates a hash code for keys and stores them in buckets.

Example:

 
 
import java.util.HashMap;

HashMap<Integer, String> map = new HashMap<>();
map.put(1, "Java");
map.put(2, "Python");
System.out.println(map.get(1));
 

HashMap provides O(1) average time complexity for get and put operations.


1️⃣8️⃣ What is the difference between HashMap and HashTable?

HashMap:

  • Not synchronized

  • Allows one null key

  • Faster

HashTable:

  • Synchronized

  • Does not allow null key or value

  • Slower

Example:

 
 
HashMap<String, String> map = new HashMap<>();
Hashtable<String, String> table = new Hashtable<>();
 

In modern applications, HashMap is preferred. For thread safety, use ConcurrentHashMap.


1️⃣9️⃣ What is the final keyword in Java?

The final keyword is used to restrict modification.

It can be used with:

  • Variables → value cannot change

  • Methods → cannot be overridden

  • Classes → cannot be inherited

Example:

 
 
final int num = 10;
// num = 20; // Error

final class Test {}
 

Final improves security and prevents accidental modification.


2️⃣0️⃣ What is static keyword?

The static keyword belongs to the class rather than the object.

Static:

  • Variables

  • Methods

  • Blocks

Static members are shared among all objects.

Example:

 
 
class Counter {
static int count = 0;
Counter() {
count++;
}
}
 

Static methods cannot access non-static variables directly.


2️⃣1️⃣ What is this keyword?

The this keyword refers to the current object of the class.

Uses:

  • Differentiate instance variable from local variable

  • Call another constructor

  • Pass current object

Example:

 
 
class Student {
int age;

Student(int age) {
this.age = age;
}
}
 

Here, this.age refers to instance variable.


2️⃣2️⃣ What is super keyword?

The super keyword refers to parent class object.

Uses:

  • Access parent class variable

  • Call parent method

  • Call parent constructor

Example:

 
 
class Parent {
void show() {
System.out.println("Parent");
}
}

class Child extends Parent {
void show() {
super.show();
System.out.println("Child");
}
}
 

2️⃣3️⃣ What is method overloading?

Method overloading means same method name with different parameters in the same class.

Example:

 
 
class Math {
int add(int a, int b) {
return a + b;
}
int add(int a, int b, int c) {
return a + b + c;
}
}
 

It is compile-time polymorphism.


2️⃣4️⃣ What is method overriding?

Method overriding means redefining parent class method in child class.

Rules:

  • Same method name

  • Same parameters

  • Same return type

Example:

 
 
class Parent {
void show() {
System.out.println("Parent");
}
}

class Child extends Parent {
void show() {
System.out.println("Child");
}
}
 

It is runtime polymorphism.


2️⃣5️⃣ What is Multithreading?

Multithreading allows multiple threads to run simultaneously within a program.

Benefits:

  • Better CPU utilization

  • Improved performance

  • Concurrent execution

Example:

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

public class Test {
public static void main(String[] args) {
MyThread t = new MyThread();
t.start();
}
}
 

Multithreading is used in servers, games, and real-time systems.


2️⃣6️⃣ What is the difference between abstract class and interface?

An abstract class is a class that cannot be instantiated and may contain both abstract and non-abstract methods. An interface defines a contract that classes must implement.

Key differences:

  • Abstract class can have constructors; interface cannot.

  • Abstract class supports instance variables; interface only has public static final constants.

  • A class can extend only one abstract class but implement multiple interfaces.

Example:

 
 
interface Animal {
void sound();
}

abstract class Dog {
abstract void bark();
}
 

Use abstract class when classes share common behavior. Use interface when defining capabilities.


2️⃣7️⃣ What is Garbage Collection in Java?

Garbage Collection (GC) is an automatic memory management process in Java. It removes unused objects from heap memory.

When an object has no reference pointing to it, it becomes eligible for garbage collection.

Example:

 
 
public class GCExample {
public static void main(String[] args) {
GCExample obj = new GCExample();
obj = null; // eligible for GC
System.gc();
}
}
 

GC improves memory efficiency and prevents memory leaks. However, developers cannot force garbage collection — System.gc() is only a request.


2️⃣8️⃣ What is the difference between stack and heap memory?

Stack Memory:

  • Stores method calls and local variables

  • Faster access

  • Automatically managed

Heap Memory:

  • Stores objects

  • Shared across threads

  • Managed by Garbage Collector

Example:

 
 
int x = 10; // Stack
String s = "Java"; // Object stored in Heap
 

Stack is short-lived; heap is long-lived.


2️⃣9️⃣ What is Serialization in Java?

Serialization is the process of converting an object into a byte stream to store or transmit it.

To serialize, a class must implement Serializable interface.

Example:

 
 
import java.io.*;

class Student implements Serializable {
int id;
String name;
}
 

Deserialization converts byte stream back to object.

Used in:

  • File storage

  • Networking

  • Session management


3️⃣0️⃣ What is the transient keyword?

The transient keyword prevents a variable from being serialized.

Example:

 
 
class User implements Serializable {
String username;
transient String password;
}
 

Here, password will not be saved during serialization.


3️⃣1️⃣ What is Comparable interface?

Comparable is used for natural sorting. It contains compareTo() method.

Example:

 
 
import java.util.*;

class Student implements Comparable<Student> {
int marks;

Student(int marks) {
this.marks = marks;
}

public int compareTo(Student s) {
return this.marks - s.marks;
}
}
 

Used for default sorting logic.


3️⃣2️⃣ What is Comparator interface?

Comparator is used for custom sorting logic.

Example:

 
 
import java.util.*;

Comparator<Student> comp = (s1, s2) -> s1.marks - s2.marks;
 

Difference:

  • Comparable → Single sorting logic

  • Comparator → Multiple sorting logic


3️⃣3️⃣ What is the difference between throw and throws?

throw:

  • Used to explicitly throw an exception.

throws:

  • Declares exceptions that a method may throw.

Example:

 
 
void check(int age) throws Exception {
if (age < 18) {
throw new Exception("Not Eligible");
}
}
 

3️⃣4️⃣ What is Singleton class?

Singleton ensures only one object of a class is created.

Example:

 
 
class Singleton {
private static Singleton instance = new Singleton();

private Singleton() {}

public static Singleton getInstance() {
return instance;
}
}
 

Used in logging, configuration, caching.


3️⃣5️⃣ What is the difference between break and continue?

break:

  • Terminates loop.

continue:

  • Skips current iteration.

Example:

 
 
for(int i=1; i<=5; i++){
if(i==3) continue;
System.out.println(i);
}
 

3️⃣6️⃣ What is method reference in Java?

Method reference provides shorthand for lambda expressions.

Example:

 
 
list.forEach(System.out::println);
 

Improves readability.


3️⃣7️⃣ What is Lambda expression?

Lambda allows writing anonymous functions.

Example:

 
 
Runnable r = () -> {
System.out.println("Running");
};
 

Introduced in Java 8.


3️⃣8️⃣ What is Stream API?

Stream API processes collections in functional style.

Example:

 
 
import java.util.*;

List<Integer> list = Arrays.asList(1,2,3,4);

list.stream()
.filter(n -> n%2==0)
.forEach(System.out::println);
 

Used for filtering, mapping, reducing data.


3️⃣9️⃣ What is Optional class?

Optional helps avoid NullPointerException.

Example:

 
 
Optional<String> name = Optional.ofNullable(null);
System.out.println(name.orElse("Default"));
 

4️⃣0️⃣ What is volatile keyword?

volatile ensures visibility of changes across threads.

Example:

 
 
volatile boolean flag = true;
 

Used in multithreading.


4️⃣1️⃣ What is synchronization?

Synchronization controls thread access to shared resources.

Example:

 
 
synchronized void display() {
System.out.println("Synchronized");
}
 

Prevents race conditions.


4️⃣2️⃣ What is deadlock?

Deadlock occurs when two threads wait for each other's resources.

Example scenario:
Thread A holds lock1, waits for lock2.
Thread B holds lock2, waits for lock1.

Avoid using proper lock ordering.


4️⃣3️⃣ What is fail-fast iterator?

Fail-fast iterator throws ConcurrentModificationException if collection is modified during iteration.

Example:

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

ArrayList uses fail-fast behavior.


4️⃣4️⃣ What is ConcurrentHashMap?

Thread-safe version of HashMap.

Example:

 
 
ConcurrentHashMap<String, String> map = new ConcurrentHashMap<>();
 

Better performance than Hashtable.


4️⃣5️⃣ What is Java 8 default method?

Default method allows method implementation inside interface.

Example:

 
 
interface Test {
default void show() {
System.out.println("Default Method");
}
}
 

4️⃣6️⃣ What is functional interface?

Functional interface has exactly one abstract method.

Example:

 
 
@FunctionalInterface
interface MyInterface {
void display();
}
 

Used with lambda expressions.


4️⃣7️⃣ What is reflection in Java?

Reflection allows inspection and modification of class structure at runtime.

Example:

 
 
Class<?> cls = Class.forName("Student");
 

Used in frameworks like Spring, Hibernate.


4️⃣8️⃣ What is JDBC?

JDBC (Java Database Connectivity) connects Java with databases.

Steps:

  1. Load driver

  2. Establish connection

  3. Execute query

  4. Close connection

Example:

 
 
Connection con = DriverManager.getConnection(url, user, pass);
 

4️⃣9️⃣ What is Spring Framework?

Spring is a powerful Java framework for enterprise applications.

Features:

  • Dependency Injection

  • AOP

  • MVC architecture

Used in backend development.


5️⃣0️⃣ What is REST API in Java?

REST API is a web service following REST principles.

In Java, commonly built using Spring Boot.

Example:

 
 
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello() {
return "Hello World";
}
}
 

Used for backend services and microservices.

Share: