Top 25 Core Java Interview Questions
Curated questions covering OOP, collections, multithreading, JVM, generics, streams, and Java best practices.
What are the main features of Java?
Java is object-oriented, platform-independent (Write Once Run Anywhere via JVM), strongly typed, multithreaded, garbage-collected, and secure. It follows the principle of WORA through bytecode compiled to run on any JVM.
What is the difference between JDK, JRE, and JVM?
- JVM (Java Virtual Machine) — executes Java bytecode; platform-specific.
- JRE (Java Runtime Environment) — JVM + standard libraries; needed to run Java programs.
- JDK (Java Development Kit) — JRE + compiler (javac) + tools; needed to develop Java programs.
What are the four pillars of OOP in Java?
- Encapsulation — bundling data and methods; using access modifiers (private, protected, public).
- Inheritance — child class inherits from parent using extends.
- Polymorphism — same method name, different behaviour (overloading and overriding).
- Abstraction — hiding implementation details using abstract classes and interfaces.
What is the difference between an abstract class and an interface?
- Abstract class — can have implemented methods, constructors, and instance variables; single inheritance.
- Interface — only abstract methods (Java 8+ allows default/static methods); multiple implementation.
- Use interfaces for contracts; abstract classes for shared base implementation.
interface Drawable { void draw(); }
abstract class Shape { abstract double area(); }
class Circle extends Shape implements Drawable {
public void draw() { System.out.println("Drawing circle"); }
public double area() { return Math.PI * r * r; }
}
What is the difference between == and .equals() in Java?
== compares object references (memory addresses) for objects, and values for primitives. .equals() compares the content/value of objects. Always use .equals() for String and object comparisons.
What is the difference between String, StringBuilder, and StringBuffer?
- String — immutable; each modification creates a new object; thread-safe.
- StringBuilder — mutable; not thread-safe; faster for single-threaded string manipulation.
- StringBuffer — mutable; thread-safe (synchronized); slower than StringBuilder.
What is the Java Collections Framework?
The Collections Framework provides interfaces and classes for storing and manipulating groups of objects. Key interfaces: List (ArrayList, LinkedList), Set (HashSet, TreeSet), Map (HashMap, TreeMap), Queue (LinkedList, PriorityQueue).
What is the difference between ArrayList and LinkedList?
- ArrayList — backed by a dynamic array; O(1) random access; O(n) insertion/deletion in middle.
- LinkedList — doubly linked list; O(n) random access; O(1) insertion/deletion at ends.
- Use ArrayList for frequent reads; LinkedList for frequent insertions/deletions.
What is the difference between HashMap and Hashtable?
- HashMap — not synchronized; allows one null key and multiple null values; faster.
- Hashtable — synchronized (thread-safe); no null keys or values; legacy class.
- Use ConcurrentHashMap for thread-safe operations instead of Hashtable.
What is multithreading in Java?
Multithreading allows concurrent execution of multiple threads within a program. Create threads by extending Thread or implementing Runnable. Java provides synchronization, locks, and the java.util.concurrent package for thread management.
class MyTask implements Runnable {
public void run() { System.out.println("Running in thread"); }
}
Thread t = new Thread(new MyTask());
t.start();
What is the difference between synchronized and volatile?
- synchronized — ensures only one thread executes a block at a time; provides mutual exclusion and visibility.
- volatile — ensures visibility of variable changes across threads; does not provide atomicity or mutual exclusion.
What are Java generics?
Generics enable type-safe collections and methods. They allow classes and methods to operate on typed parameters, catching type errors at compile time rather than runtime.
List<String> names = new ArrayList<>();
names.add("Alice");
String name = names.get(0); // no cast needed
public <T> T getFirst(List<T> list) { return list.get(0); }
What are Java 8 streams?
Streams provide a functional approach to processing collections. They support lazy evaluation, pipeline operations (filter, map, reduce), and parallel processing.
List<String> result = names.stream()
.filter(n -> n.startsWith("A"))
.map(String::toUpperCase)
.sorted()
.collect(Collectors.toList());
What are lambda expressions in Java?
Lambda expressions (Java 8+) provide a concise way to implement functional interfaces (interfaces with a single abstract method). They enable functional programming patterns.
// Before Java 8
Comparator<String> comp = new Comparator<String>() {
public int compare(String a, String b) { return a.compareTo(b); }
};
// Lambda
Comparator<String> comp = (a, b) -> a.compareTo(b);
What is the difference between checked and unchecked exceptions?
- Checked exceptions — must be declared or caught; extend Exception (not RuntimeException). E.g., IOException, SQLException.
- Unchecked exceptions — extend RuntimeException; do not need to be declared. E.g., NullPointerException, ArrayIndexOutOfBoundsException.
What is the finally block?
The finally block always executes after try/catch, regardless of whether an exception occurred. Used for cleanup operations like closing resources. Java 7+ try-with-resources is preferred for AutoCloseable resources.
What is the difference between method overloading and overriding?
- Overloading — same method name, different parameters in the same class; resolved at compile time (static polymorphism).
- Overriding — subclass provides a different implementation of a parent method; resolved at runtime (dynamic polymorphism).
What is the static keyword in Java?
static members belong to the class, not instances. Static variables are shared across all instances. Static methods can be called without creating an object. Static blocks run once when the class is loaded.
What is the final keyword in Java?
- final variable — value cannot be changed (constant).
- final method — cannot be overridden in subclasses.
- final class — cannot be subclassed (e.g., String, Integer).
What is garbage collection in Java?
Java automatically manages memory through garbage collection. The JVM identifies and removes objects that are no longer reachable. Algorithms include Serial, Parallel, G1, and ZGC. You cannot force GC but can suggest it with System.gc().
What is the difference between Stack and Heap memory?
- Stack — stores method frames, local variables, and references; LIFO; thread-specific; automatically managed.
- Heap — stores objects and class instances; shared across threads; managed by garbage collector.
What are Java design patterns?
- Creational: Singleton, Factory, Builder, Prototype.
- Structural: Adapter, Decorator, Proxy, Facade.
- Behavioural: Observer, Strategy, Command, Iterator.
What is the Singleton pattern?
Singleton ensures only one instance of a class exists. Thread-safe implementation uses double-checked locking or enum.
public 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;
}
}
What is Optional in Java 8?
Optional is a container that may or may not contain a non-null value. It avoids NullPointerException and makes null handling explicit.
Optional<String> name = Optional.ofNullable(getName());
String result = name.orElse("Unknown");
name.ifPresent(n -> System.out.println(n));
What is the difference between Comparable and Comparator?
- Comparable — implemented by the class itself (compareTo method); defines natural ordering.
- Comparator — external comparison logic; allows multiple sort orders; passed to sort methods.
// Comparator
List<Person> people = ...;
people.sort(Comparator.comparing(Person::getAge).thenComparing(Person::getName));