Java — Cheat Sheet

Tags: java, jvm, oop, concurrency, spring, collections

Level: intermediate

TL;DR: Core Java interview essentials covering JVM memory model, OOP design, Collections API, and concurrency mechanics.

Key concepts

JVM memory divides into Heap for objects and Stack for method frames and local variables.

Garbage Collection clears unreachable heap objects using generational algorithms like G1 and ZGC.

String immutability ensures thread safety, security, and caching inside the JVM String Constant Pool.

Polymorphism enables runtime method dispatch via dynamic method lookup and inheritance or interfaces.

The equals() method evaluates object equivalence; hashCode() generates integer hash values for bucketed hashing collections.

Contract rule: if two objects are equal by equals(), they must return the identical hashCode().

HashMap stores key-value pairs in buckets, converting linked lists into red-black trees when collisions exceed threshold.

The final keyword prevents variable reassignment, method overriding, and class inheritance.

Java concurrency uses synchronized blocks, explicit Locks, and atomic primitives backed by CAS operations.

The Java Memory Model guarantees visibility and prevents instruction reordering across threads via volatile.

Typical questions and ready answers

Q: How does HashMap handle collisions internally?

R: It places colliding entries in a linked list inside the bucket. When bucket collisions exceed eight and capacity reaches 64, it transforms the list into a red-black tree for O(log⁡n)O(\log n)O(logn) lookups.

Q: What is the difference between Comparable and Comparator?

R: I implement Comparable via compareTo() inside the class for natural ordering. I use Comparator with compare() to define custom external sorting strategies.

Q: Why must you override both equals() and hashCode()?

R: If I override equals() without hashCode(), hash-based collections store equal objects in separate buckets, breaking lookups and deduplication guarantees.

Q: What does the volatile modifier guarantee?

R: It ensures variable reads and writes go directly to main memory rather than thread caches, enforcing visibility across threads without mutex locking.

Q: What separates checked exceptions from unchecked exceptions?

R: Checked exceptions extend Exception and must be handled or declared at compile time. Unchecked exceptions extend RuntimeException and indicate program logic errors.

Pitfalls and common mistakes

Comparing object or string equality with == reference comparison instead of .equals().

Modifying a collection during iteration without using Iterator.remove(), causing a ConcurrentModificationException.

Mutating fields used in hashCode() after inserting an object into a HashSet or HashMap.

Suppressing exceptions inside empty catch blocks or catching generic Throwable.

Autoboxing primitives repeatedly inside performance-critical loops, generating heavy garbage collection pressure.

Incrementing shared variables without volatile, atomic classes, or synchronization, causing lost updates.

Snippets and commands

// Idiomatic equals and hashCode implementation
public class Account {
    private final Long id;
    private final String accountNumber;

    public Account(Long id, String accountNumber) {
        this.id = id;
        this.accountNumber = accountNumber;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (!(obj instanceof Account account)) return false;
        return Objects.equals(id, account.id) &&
               Objects.equals(accountNumber, account.accountNumber);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, accountNumber);
    }
}

Java

// Thread-safe singleton using double-checked locking
public class ConnectionPool {
    private static volatile ConnectionPool instance;

    private ConnectionPool() {}

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

To review

[ ] Virtual threads and Project Loom execution model

[ ] Garbage collector tuning parameters for G1GC and ZGC

[ ] Modern language syntax: pattern matching, records, and sealed interfaces

[ ] Non-blocking workflows with CompletableFuture

[x] Java Collections Framework class hierarchy and complexity

[x] Concurrency utilities in java.util.concurrent

References

Oracle Java Language Specification

Joshua Bloch — Effective Java (3rd Edition)

Brian Goetz — Java Concurrency in Practice

Jarvis Interviews
Jarvis