Tutorials Logic, IN +91 8092939553 info@tutorialslogic.com
FAQs Support
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Interview Questions Website Development
Compiler Tutorials

Core Java Interview Questions

Core Java

Top 25 Core Java Interview Questions

Curated questions covering OOP, JVM internals, collections, multithreading, Java 8/21 features, and more.

01

What are the four pillars of Object-Oriented Programming in Java?

  • Encapsulation — bundling data and methods that operate on that data within a class, hiding internal state.
  • Inheritance — a class (child) acquires properties and behaviours of another class (parent) using the extends keyword.
  • Polymorphism — the ability of an object to take many forms; achieved via method overloading (compile-time) and overriding (runtime).
  • Abstraction — hiding implementation details and exposing only essential features via abstract classes or interfaces.
02

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

  • JVM (Java Virtual Machine) — executes Java bytecode; platform-specific but provides platform independence for Java programs.
  • JRE (Java Runtime Environment) — JVM + core libraries needed to run Java applications.
  • JDK (Java Development Kit) — JRE + development tools (compiler javac, debugger, javadoc) needed to develop Java applications.
03

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

  • String — immutable; every modification creates a new object. Best for constant strings.
  • StringBuilder — mutable, not thread-safe. Best for single-threaded string manipulation (faster).
  • StringBuffer — mutable, thread-safe (synchronized methods). Use in multi-threaded contexts.
Example
StringBuilder sb = new StringBuilder("Hello");
sb.append(" World");
System.out.println(sb.toString()); // Hello World

String s = "Hello";
s.concat(" World"); // original s unchanged
System.out.println(s); // Hello
04

What are primitive data types in Java?

Java has 8 primitive types: byte (8-bit), short (16-bit), int (32-bit), long (64-bit), float (32-bit), double (64-bit), char (16-bit Unicode), and boolean (true/false). They are stored on the stack and are not objects.

05

What is the difference between ArrayList and LinkedList?

  • ArrayList — backed by a dynamic array; O(1) random access, O(n) insertion/deletion in the middle.
  • LinkedList — doubly-linked list; O(n) random access, O(1) insertion/deletion at head/tail.
  • Use ArrayList for frequent reads; LinkedList for frequent insertions/deletions at ends.
Example
List<String> arrayList = new ArrayList<>();
arrayList.add("Java");
arrayList.get(0); // O(1)

List<String> linkedList = new LinkedList<>();
linkedList.add("Java");
((LinkedList<String>) linkedList).addFirst("First"); // O(1)
06

How does HashMap work internally in Java?

HashMap uses an array of buckets. When you put a key-value pair, it computes hashCode() of the key, maps it to a bucket index, and stores the entry. Collisions are handled via a linked list (Java 7) or a balanced tree (Java 8+, when bucket size > 8). It resizes when the load factor (default 0.75) is exceeded.

Example
Map<String, Integer> map = new HashMap<>();
map.put("one", 1);
map.put("two", 2);
System.out.println(map.get("one")); // 1
System.out.println(map.containsKey("two")); // true
07

What are generics in Java and why are they useful?

Generics allow classes, interfaces, and methods to operate on typed parameters, providing compile-time type safety and eliminating the need for explicit casting.

Example
// Without generics
List list = new ArrayList();
list.add("hello");
String s = (String) list.get(0); // cast required

// With generics
List<String> list = new ArrayList<>();
list.add("hello");
String s = list.get(0); // no cast needed
08

What is exception handling in Java? Explain checked vs unchecked exceptions.

  • Checked exceptions — must be declared with throws or caught at compile time (e.g., IOException, SQLException).
  • Unchecked exceptions — subclasses of RuntimeException; not required to be caught (e.g., NullPointerException, ArrayIndexOutOfBoundsException).
  • Errors — serious problems not meant to be caught (e.g., OutOfMemoryError, StackOverflowError).
Example
try {
    int result = 10 / 0;
} catch (ArithmeticException e) {
    System.out.println("Caught: " + e.getMessage());
} finally {
    System.out.println("Always runs");
}
09

What is the difference between Thread and Runnable in Java?

Thread is a class; Runnable is a functional interface. Implementing Runnable is preferred because Java supports single inheritance — your class can extend another class while still implementing Runnable.

Example
// Using Runnable (preferred)
Runnable task = () -> System.out.println("Running in: " + Thread.currentThread().getName());
Thread t = new Thread(task);
t.start();

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

What is the synchronized keyword in Java?

synchronized ensures that only one thread can execute a block or method at a time, preventing race conditions. It can be applied to instance methods, static methods, or specific code blocks.

Example
class Counter {
    private int count = 0;
    public synchronized void increment() {
        count++;
    }
    public int getCount() { return count; }
}
11

What are lambda expressions in Java 8?

Lambda expressions provide a concise way to implement functional interfaces (interfaces with a single abstract method). They enable functional programming style in Java.

Example
// Before Java 8
Runnable r = new Runnable() {
    public void run() { System.out.println("Hello"); }
};

// Java 8 lambda
Runnable r = () -> System.out.println("Hello");

// With parameters
List<String> names = Arrays.asList("Bob", "Alice", "Charlie");
names.sort((a, b) -> a.compareTo(b));
12

What is the Stream API in Java 8?

The Stream API allows functional-style operations on collections. Streams are lazy, can be parallelised, and support operations like filter, map, reduce, collect, and sorted.

Example
List<Integer> nums = Arrays.asList(1, 2, 3, 4, 5, 6);
int sumOfEvens = nums.stream()
    .filter(n -> n % 2 == 0)
    .mapToInt(Integer::intValue)
    .sum();
System.out.println(sumOfEvens); // 12
13

What is Optional in Java 8?

Optional is a container object that may or may not contain a non-null value. It helps avoid NullPointerException by forcing explicit handling of absent values.

Example
Optional<String> opt = Optional.ofNullable(getName());
String name = opt.orElse("Unknown");
opt.ifPresent(n -> System.out.println("Name: " + n));
14

What are records in Java 16+?

Records are a concise way to declare immutable data classes. The compiler auto-generates constructor, getters, equals(), hashCode(), and toString().

Example
record Point(int x, int y) {}

Point p = new Point(3, 4);
System.out.println(p.x()); // 3
System.out.println(p);     // Point[x=3, y=4]
15

What are sealed classes in Java 17+?

Sealed classes restrict which classes can extend or implement them, providing more control over class hierarchies. They work well with pattern matching.

Example
sealed interface Shape permits Circle, Rectangle, Triangle {}

record Circle(double radius) implements Shape {}
record Rectangle(double w, double h) implements Shape {}
record Triangle(double base, double height) implements Shape {}
16

What are virtual threads in Java 21?

Virtual threads (Project Loom) are lightweight threads managed by the JVM rather than the OS. They allow millions of concurrent threads without the overhead of platform threads, greatly simplifying high-throughput concurrent applications.

Example
// Create a virtual thread
Thread vt = Thread.ofVirtual().start(() -> {
    System.out.println("Virtual thread: " + Thread.currentThread().isVirtual());
});
vt.join();
17

How does garbage collection work in Java?

The JVM automatically reclaims memory occupied by objects that are no longer reachable. The heap is divided into Young Generation (Eden + Survivor spaces) and Old Generation. Minor GC collects the Young Generation; Major/Full GC collects the Old Generation. Common collectors include G1GC (default in Java 9+), ZGC, and Shenandoah.

18

What are access modifiers in Java?

  • private — accessible only within the same class.
  • default (no modifier) — accessible within the same package.
  • protected — accessible within the same package and subclasses.
  • public — accessible from anywhere.
19

What is the difference between abstract class and interface?

  • Abstract class — can have state (fields), constructors, and concrete methods. A class can extend only one abstract class.
  • Interface — all fields are public static final; methods are public abstract by default (Java 8+ allows default/static methods). A class can implement multiple interfaces.
  • Use abstract class for shared state/behaviour; use interface for defining a contract.
20

What is the static keyword in Java?

static members belong to the class rather than any instance. Static fields are shared across all instances. Static methods can be called without creating an object. Static blocks run once when the class is loaded.

Example
class MathUtils {
    public static final double PI = 3.14159;
    public static int square(int n) { return n * n; }
}
System.out.println(MathUtils.PI);
System.out.println(MathUtils.square(5)); // 25
21

What is the final keyword in Java?

  • final variable — value cannot be changed after initialisation (constant).
  • final method — cannot be overridden by subclasses.
  • final class — cannot be subclassed (e.g., String, Integer).
22

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

"==" compares object references (memory addresses). equals() compares object content. For String and wrapper classes, always use equals() for value comparison.

Example
String a = new String("hello");
String b = new String("hello");
System.out.println(a == b);       // false (different objects)
System.out.println(a.equals(b));  // true  (same content)
23

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

If two objects are equal according to equals(), they must have the same hashCode(). The reverse is not required. Violating this contract breaks HashMap and HashSet behaviour. Always override both together.

24

What is autoboxing and unboxing in Java?

Autoboxing is the automatic conversion of a primitive type to its wrapper class (e.g., int → Integer). Unboxing is the reverse. This happens automatically in assignments and collections.

Example
List<Integer> list = new ArrayList<>();
list.add(42);          // autoboxing: int -> Integer
int val = list.get(0); // unboxing: Integer -> int
25

What is try-with-resources in Java?

try-with-resources (Java 7+) automatically closes resources that implement AutoCloseable at the end of the try block, eliminating the need for a finally block to close streams.

Example
try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
    String line;
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }
} catch (IOException e) {
    e.printStackTrace();
}
// br is automatically closed here

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.