Top 50 Core Java Interview Questions and Answers

In this article, we have listed 50 Core Java interview questions and answers to help you review key concepts and improve your confidence. The questions cover important areas like object-oriented programming, exception handling, collections, multithreading, and more.

This guide is designed to support your interview preparation by giving you clear and practical answers to common questions. Let’s get started.

1. What is Java?

Java is a high-level, object-oriented programming language that is designed to be platform-independent, meaning you can write code once and run it anywhere with the Java Virtual Machine (JVM).

It’s easy to learn for beginners and widely used for building web, mobile, and enterprise applications. Java is known for its robustness, security features, and versatility. It supports modular and reusable code through its object-oriented principles, and it comes with a rich set of libraries and frameworks to streamline development.

You may also get a question like What are the key features of Java?

Refer to this article: Main Features of Java ( Explained with Examples )

2. What is the Java Virtual Machine (JVM)?

Answer:
The JVM is a virtual machine that executes Java bytecode. It converts bytecode into machine-specific code and handles tasks like memory management, garbage collection, and security. The JVM is what makes Java platform-independent.

Why is the JVM Important?

The JVM makes Java a platform-independent language. It allows developers to write code once and run it anywhere. The JVM also handles memory management, security, and performance optimization, making Java applications reliable and efficient.

3. What is the difference between JDK, JRE, and JVM?

JDK (Java Development Kit)

🧑‍💻 JDK is the full toolbox for Java developers.

What it includes:

  • JRE (which includes JVM)
  • Java compiler (javac)
  • Debugger (jdb)
  • Other dev tools (like jar, javadoc, etc.)
Use JDK when you want to WRITE, COMPILE, and RUN Java programs.

JRE (Java Runtime Environment)

⚙️ JRE is a software package that contains everything needed to run a Java program.

What it includes:

  • JVM (Java Virtual Machine)
  • Libraries and class files needed at runtime (like rt.jar)
  • Other supporting files

What it doesn’t include:

  • Compiler (javac)
  • Development tools

JVM (Java Virtual Machine)

🧠 JVM is the brain behind Java.

What it does:

  • It runs Java bytecode (compiled .class files).
  • Converts bytecode into machine-specific instructions.
  • Provides features like: Garbage collection, Memory management, Security and runtime optimization.

4. What is a class and an object in Java?

Answer:

  • A class is a blueprint or template for creating objects. It defines properties and behaviors.
  • An object is an instance of a class. It holds real values for the properties defined in the class.

Example:

class Car {
String color;
void drive() {
System.out.println("Driving...");
}
}

Car myCar = new Car(); // object
myCar.color = "Red";
myCar.drive();

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

Answer:
The main() method is the entry point of any Java application. It has a specific signature that the JVM looks for when starting a program.

public static void main(String[] args) {
// code to run
}
  • public – accessible from anywhere
  • static – no need to create an object to call it
  • void – does not return any value
  • String[] args – receives command-line arguments

6. What is the difference between primitive and non-primitive data types?

7. What is a constructor in Java?

Answer:
A constructor is a special method used to initialize objects. It has the same name as the class and no return type. It is called automatically when an object is created.

public class Student {
String name;
Student(String n) {
name = n;
}
}

Java also provides a default constructor if none is defined.

8. What is method overloading?

Answer:
Method overloading means defining multiple methods with the same name but different parameters (number, type, or order).

void print(int a) { }
void print(String s) { }
void print(int a, String s) { }

It increases the readability and flexibility of the program.

9. What is the use of the this keyword in Java?

The this keyword refers to the current object. It is used when instance variables are shadowed by method or constructor parameters.

class Employee {
String name;
Employee(String name) {
this.name = name; // refers to instance variable
}
}

10. What is garbage collection in Java?

Garbage collection is a process in which the JVM automatically removes unused or unreachable objects from memory to free up space. It helps manage memory efficiently and prevents memory leaks.

You can suggest garbage collection using:

System.gc();

But the JVM decides when to actually run it.

11. What are the four main principles of Object-Oriented Programming (OOP) in Java?

The four key principles of OOP are:

  • Encapsulation: Hiding internal details and exposing only essential features using classes and access modifiers.
  • Abstraction: Hiding complex implementation and showing only necessary details using abstract classes or interfaces.
  • Inheritance: Reusing code by deriving a new class from an existing one.
  • Polymorphism: Ability to take many forms — method overloading (compile-time) and method overriding (runtime).

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

Answer:

  • == checks reference equality — whether two references point to the same object.
  • .equals() checks value equality — whether two objects have the same content (when overridden properly).

Example:

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

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

13. What are access modifiers in Java?

Answer:
Access modifiers control the visibility of classes, methods, and variables. Java provides four main access levels:

14. What is the difference between static variables and instance variables?

Answer:

  • Static variables belong to the class, not to any object. Only one copy exists.
  • Instance variables belong to each object. Every object has its own copy.

Example:

class Counter {
static int count = 0;
int id;

Counter() {
count++;
id = count;
}
}

15. What is method overriding?

Answer:
Method overriding is when a subclass provides a new implementation for a method that is already defined in its superclass.

  • The method must have the same name, return type, and parameters.
  • The method in the subclass should not have less access than the superclass method.
  • Use the @Override annotation for clarity.

16. Can we override a static method in Java?

Answer:
No, we cannot truly override a static method. Static methods belong to the class, not objects, so method hiding occurs instead of overriding.

Example:

class A {
static void show() {
System.out.println("Class A");
}
}

class B extends A {
static void show() {
System.out.println("Class B");
}
}

Calling B.show() calls B’s version, but it’s not true polymorphism.

17. What is the purpose of the final keyword in Java?

Answer:
final is used to declare:

  • Final variable: Value cannot be changed after assignment.
  • Final method: Cannot be overridden.
  • Final class: Cannot be extended (e.g., String class).

18. What is a constructor overloading?

Answer:
Constructor overloading means defining multiple constructors in a class with different parameter lists. It allows objects to be initialized in different ways.

Example:

class Book {
Book() { }
Book(String title) { }
Book(String title, String author) { }
}

19. What is super keyword in Java?

Answer:
The super keyword is used to refer to the immediate parent class. It can be used to:

  • Call the parent class constructor: super()
  • Access parent class methods or variables: super.methodName()

20. What is the difference between compile-time and run-time polymorphism?

Answer:

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

Answer:

22. What is the purpose of the interface keyword in Java?

Answer:
An interface defines a contract that a class must follow. It contains method declarations without implementations (except for default/static methods). A class implements an interface using the implements keyword.

Example:

interface Vehicle {
void start();
}

class Car implements Vehicle {
public void start() {
System.out.println("Car started");
}
}

23. What is exception handling in Java?

Answer:
Exception handling is a mechanism to handle runtime errors and prevent the program from crashing. Java provides:

  • try block to write risky code
  • catch block to handle exceptions
  • finally block to execute code regardless of exceptions
  • throw to manually throw an exception
  • throws to declare exceptions

Example:

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

24. What is the difference between throw and throws?

Answer:

25. What is the difference between checked and unchecked exceptions?

Answer:

26. What is the use of finally block?

Answer:
The finally block is used to write clean-up code (like closing a file, releasing a database connection). It always executes whether an exception is thrown or not.

try {
// code
} catch (Exception e) {
// handle
} finally {
System.out.println("Always runs");
}

27. What are wrapper classes in Java?

In Java, wrapper classes are used to convert primitive types into objects.

Java is an object-oriented language, but primitive types like int, double, char are not objects.

So Java provides wrapper classes for each primitive data type to help you use them like objects.

Example:

int x = 10;
Integer obj = Integer.valueOf(x); // Boxing
int y = obj.intValue(); // Unboxing

28. What is autoboxing and unboxing in Java?

Answer:

  • Autoboxing: Automatic conversion of a primitive to a wrapper class object.
  • Unboxing: Automatic conversion of a wrapper class object back to a primitive.

Example:

Integer a = 10; // Autoboxing
int b = a; // Unboxing

Introduced in Java 5 to simplify code when using collections and generics.

29. What is the difference between String, StringBuilder, and StringBuffer?

Answer:

30. What is the difference between == and .equals() in the case of String?

Answer:

  • == compares references (memory locations).
  • .equals() compares values (actual characters in the string).

Example:

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

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

Always use .equals() for value comparison in strings.

31. What is the Java Collections Framework?

Answer:
The Java Collections Framework is a set of classes and interfaces that provide data structures and algorithms to store, retrieve, and manipulate data efficiently. It includes:

  • Interfaces like List, Set, Queue, Map
  • Implementations like ArrayList, HashSet, LinkedList, HashMap, etc.

It supports both generic and non-generic types and provides operations like sorting, searching, and iteration.

32. What is the difference between ArrayList and LinkedList?

Answer:

33. What is the difference between HashSet and TreeSet?

Answer:

34. What is the difference between Iterator and ListIterator?

Answer:

35. What are Generics in Java?

Answer:
Generics allow you to define classes, interfaces, and methods with type parameters. They enable compile-time type checking and eliminate the need for type casting.

Example:

List<String> names = new ArrayList<>();
names.add("Ravi");
String first = names.get(0); // No casting needed

Generics improve code safety and readability.

36. What is the difference between Comparable and Comparator?

Answer:

37. What is a thread in Java?

Answer:
A thread is a lightweight unit of execution in a program. Java supports multithreading, which allows multiple threads to run concurrently, improving performance in CPU-bound or I/O-bound tasks.

You can create threads in two ways:

  1. Extending Thread class
  2. Implementing Runnable interface

38. What is the difference between start() and run() methods in threads?

Answer:

39. What is synchronization in Java?

Answer:
Synchronization is used to control access to shared resources in a multithreaded environment. It prevents race conditions by allowing only one thread to access a block of code or object at a time.

You can use:

  • synchronized keyword on methods or code blocks
  • synchronized blocks with object references

Example:

synchronized void increment() {
count++;
}

40. What is a deadlock in Java?

Answer:
A deadlock is a situation where two or more threads are blocked forever, waiting for each other to release locks.

Example Scenario:

  • Thread A holds Lock 1 and waits for Lock 2
  • Thread B holds Lock 2 and waits for Lock 1

To avoid deadlocks:

  • Always acquire locks in the same order
  • Use timeout with tryLock() from java.util.concurrent.locks

41. What is an immutable class in Java?

Answer:
An immutable class is one whose objects cannot be modified once they are created. All the fields of an immutable object are final and set only once through the constructor.

Example:

public final class Student {
private final String name;

public Student(String name) {
this.name = name;
}

public String getName() {
return name;
}
}

The String class in Java is a common example of an immutable class.

42. What is the Java Memory Model?

Answer:
The Java memory model divides memory into different regions:

  • Heap: Stores objects and class instances
  • Stack: Stores method call frames and local variables
  • Method Area (MetaSpace): Stores class metadata
  • Program Counter Register: Holds the address of the current executing instruction
  • Native Method Stack: Used for native method calls

Understanding this model helps in optimizing memory usage and identifying memory leaks or performance bottlenecks.

43. Why is String immutable in Java?

Strings in Java are immutable by design. This design decision is about more than just simplicity.

Key reasons:

  • Security: Strings are often used in sensitive areas like file paths and network connections. If a string could be changed, it could lead to vulnerabilities.
  • Performance: Since immutable strings can be cached and reused, the JVM can optimize performance using a string pool.
  • Thread safety: Immutable objects are naturally thread-safe, which avoids the need for synchronization.

Example:

String s = "Hello";
s.concat(" World");
System.out.println(s); // prints "Hello"

s = s.concat(" World");
System.out.println(s); // prints "Hello World"

44. What is class loading in Java?

Answer:
Java uses Class Loaders to load .class files into memory when needed.

The three main class loaders are:

  • Bootstrap ClassLoader — loads core Java classes from the JDK
  • Extension ClassLoader — loads JDK extension libraries
  • Application ClassLoader — loads classes from the classpath

Java uses lazy loading, meaning classes are only loaded when they are first accessed.

45. What is the difference between compile-time and runtime errors?

Answer:

46. What are Lambda Expressions in Java?

Answer:
A lambda expression is simply a function without a name. It can even be used as a parameter in a function. Lambda Expressions facilitate functional programming and simplify development greatly.

The main use of Lambda expression is to provide an implementation for functional interfaces.

Syntax:

(parameter) -> expression

Example:

47. What is a Functional Interface?

Answer:
A functional interface is an interface that has exactly one abstract method. It can have default or static methods.

Java 8 introduced the @FunctionalInterface annotation to ensure this rule.

Example:

@FunctionalInterface
interface MyFunc {
void execute();
}

Common built-in functional interfaces: Runnable, Callable, Predicate, Function, Supplier, and Consumer.


48. What is the Stream API in Java?

Answer:
Stream API is used to process collections (like List or Set) in a functional style. It supports operations like filter, map, reduce, collect, and more.

Example:

List<String> names = List.of("Ram", "Shyam", "Ravi");
names.stream()
.filter(name -> name.startsWith("R"))
.forEach(System.out::println);

Streams help write clean, readable, and concise code for data processing.

49. What is Optional in Java?

Answer:
Optional is a container object used to avoid null checks and prevent NullPointerException.

Example:

Optional<String> name = Optional.ofNullable(getName());
name.ifPresent(System.out::println);

It encourages writing null-safe code in a more readable way.

50. What are the design principles in OOP?

Some key OOP design principles include:

  1. Single Responsibility Principle (SRP)
  2. Open/Closed Principle (OCP)
  3. Liskov Substitution Principle (LSP)
  4. Interface Segregation Principle (ISP)
  5. Dependency Inversion Principle (DIP)
  6. Encapsulate What Varies
  7. DRY (Don’t Repeat Yourself)
  8. YAGNI (You Aren’t Gonna Need It)
  9. KISS (Keep It Simple, Stupid)
  10. Composition over Inheritance
  11. Dependency Injection

These principles guide developers toward creating clean, maintainable, and scalable systems.

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare