Java Materials
← Core Java

Core Java · Language and concurrency gaps

Study collection internals, exception handling, fixed-capacity queues, volatile publication, strings, serialization, cloning and singleton identity.

ArrayList, LinkedList and ArrayDeque

Definition:

A list represents an ordered sequence. A deque exposes insertion and removal at both ends.

Explanation:

Choose indexed access for random reads, a deque for stacks and queues, and a linked structure only when its access pattern justifies allocation and pointer traversal.

Illustration image:

ArrayList [A B C] → Insert X before B → Shift [B C] right → [A X B C]. ArrayList [A B C]Insert X before BShift [B C] right[A X B C]
ArrayList [A B C] → Insert X before B → Shift [B C] right → [A X B C].

Example:

Worked example · excerpt unless noted
var xs = new java.util.ArrayList<>(java.util.List.of("A", "B", "C"));
xs.add(1, "X");
var deque = new java.util.ArrayDeque<>(xs);
System.out.println(deque.removeFirst()); // A

Internal working:

OpenJDK ArrayList stores references in an array and shifts a suffix on middle insertion. ArrayDeque advances circular indices and expands when needed; LinkedList holds separate doubly linked nodes. Resize can make an individual append linear even when amortized append is constant.

Interview questions:

Why can LinkedList be slow even when insertion is constant time?

Insertion at an already-known node is cheap, but locating index i generally requires traversal and each node adds memory overhead.

HashMap, HashSet and collision handling

Definition:

Hash-based containers use a hash to narrow lookup and equality to distinguish keys.

Explanation:

Use immutable, stable keys. Equal keys must have equal hash codes; equal hashes can belong to distinct keys.

Illustration image:

FB and Ea → Same String hash → Equals says different → Two entries in one bin. FB and EaSame String hashEquals says differentTwo entries in one bin
FB and Ea → Same String hash → Equals says different → Two entries in one bin.

Example:

Worked example · excerpt unless noted
var keys = new java.util.HashSet<String>();
keys.add("FB"); keys.add("Ea");
System.out.println("FB".hashCode() == "Ea".hashCode()); // true
System.out.println(keys.size()); // 2

Internal working:

OpenJDK HashMap spreads bits, masks into a power-of-two table, compares keys in the selected bin and resizes at its load threshold. Collisions can treeify under implementation-specific conditions. HashSet stores its members as keys in a backing map.

Interview questions:

When does a mutable map key break lookup?

When fields that determine hash or equality change after insertion, so the lookup no longer reaches or recognizes the saved entry.

Ordering, views and iterators

Definition:

A view reflects the state of another collection; a snapshot captures a separate structural state.

Explanation:

Choose LinkedHashMap for encounter order, TreeMap for navigable sorted keys, and PriorityQueue for repeated removal by priority. Iterator order for a heap does not imply sorted output.

Illustration image:

Source [A B] → Unmodifiable view → Source adds C → View [A B C], copy [A B]. Source [A B]Unmodifiable viewSource adds CView [A B C], copy [A B]
Source [A B] → Unmodifiable view → Source adds C → View [A B C], copy [A B].

Example:

Worked example · excerpt unless noted
var source = new java.util.ArrayList<>(java.util.List.of("A", "B"));
var view = java.util.Collections.unmodifiableList(source);
var snapshot = java.util.List.copyOf(source);
source.add("C");
System.out.println(view + " / " + snapshot);

Internal working:

TreeMap navigation uses comparison rather than hash equality. A backed subList can be invalidated by uncoordinated structural changes in the parent. Fail-fast iterators are best-effort diagnostics, not synchronization. List.copyOf copies the structure, not mutable elements.

Interview questions:

Can an unmodifiable wrapper guarantee unchanged contents?

It blocks writes through the wrapper. A reference to the backing collection can still change what the view displays.

Exception boundaries, checked and unchecked failures

Definition:

An exception transfers control to a matching handler while preserving failure context.

Explanation:

Use checked exceptions where a caller can reasonably handle a declared failure. Translate lower-level failures into a meaningful boundary error and preserve their cause. Avoid broad catch-and-continue that returns plausible but incorrect data.

Illustration image:

Read file → IOException with cause → Service-level translation → Caller classifies recovery. Read fileIOException with causeService-level translationCaller classifies recovery
Read file → IOException with cause → Service-level translation → Caller classifies recovery.

Example:

Worked example · excerpt unless noted
static String readPolicy(java.nio.file.Path path) {
    try { return java.nio.file.Files.readString(path); }
    catch (java.io.IOException e) {
        throw new java.io.UncheckedIOException("Could not read policy", e);
    }
}

Internal working:

Throwing unwinds frames until a compatible handler is found. Catch order selects more specific handlers before broader ones. finally can alter the outcome if it throws or returns, so keep cleanup separate from result selection.

Interview questions:

When is retrying an exception unsafe?

A timed-out external write can have succeeded. Reuse an idempotency key or reconcile before repeating the effect.

Try-with-resources and suppressed exceptions

Definition:

Try-with-resources closes acquired AutoCloseable resources even when the body fails.

Explanation:

Close resources in the reverse order of acquisition. Inspect suppressed failures when cleanup also fails. Propagate or restore interruption at cancellation boundaries.

Illustration image:

Open A → Open B → Body throws → Close B then A. Open AOpen BBody throwsClose B then A
Open A → Open B → Body throws → Close B then A.

Example:

Worked example · excerpt unless noted
try (AutoCloseable resource = () -> { throw new Exception("close"); }) {
    throw new IllegalStateException("body");
} catch (Exception e) {
    System.out.println(e.getMessage() + "/" + e.getSuppressed()[0].getMessage());
}

Internal working:

The compiler supplies cleanup logic that preserves the primary exception. A close failure during body failure is attached to the primary exception. If initialization of resource B fails, resource A is still closed.

Interview questions:

What prints?

body/close. The primary exception remains the body failure.

BlockingQueue operation families

Definition:

BlockingQueue coordinates producers and consumers with immediate, blocking and bounded-wait methods.

Explanation:

offer and poll return a status or null immediately; put and take wait interruptibly; timed offer and poll wait up to a budget. add and remove can throw when the capacity or availability condition is not met.

Illustration image:

Producer offers C → Queue stores A and B → Offer returns false → Consumer takes A. Producer offers CQueue stores A and BOffer returns falseConsumer takes A
Producer offers C → Queue stores A and B → Offer returns false → Consumer takes A.

Example:

Worked example · excerpt unless noted
var q = new java.util.concurrent.ArrayBlockingQueue<String>(2);
q.put("A"); q.put("B");
System.out.println(q.offer("C")); // false
System.out.println(q.take());     // A

Internal working:

Implementations coordinate visibility across handoff, but capacity, ordering and synchronization differ. A bounded queue lets the producer observe overload. Decide how shutdown wakes producers and consumers rather than assuming the interface has a built-in close operation.

Interview questions:

When is put the wrong choice?

When blocking a latency-critical or event-loop thread is unacceptable. Use bounded wait, rejection, or explicit asynchronous admission.

Fixed-capacity and linked blocking queues

Definition:

Fixed capacity limits how many queued tasks can wait before producers must wait or reject.

Explanation:

Use ArrayBlockingQueue when you want a preallocated bounded FIFO. LinkedBlockingQueue can be bounded by constructor; its large default capacity is not a practical memory budget.

Illustration image:

The producer wraps to reuse slot 0. The consumer reads slot 1 first, so physical positions and FIFO order differ. One array, two moving cursorsBefore removalA0B1After take(A), then put(C)C0B1Take cursor: slot 0Take cursor: slot 1Logical dequeue order: B, C
The producer wraps to reuse slot 0. The consumer reads slot 1 first, so physical positions and FIFO order differ.

Example:

Worked example · excerpt unless noted
var q = new java.util.concurrent.ArrayBlockingQueue<String>(2);
q.add("A"); q.add("B");
q.remove(); q.add("C");
System.out.println(q.remove()); // B
System.out.println(q.remove()); // C

Internal working:

OpenJDK ArrayBlockingQueue coordinates circular put and take indices under one lock with notFull and notEmpty conditions. LinkedBlockingQueue stores nodes and uses separate endpoint locks with shared count coordination. SynchronousQueue has zero buffered capacity; it matches a producer and consumer directly.

Interview questions:

Does a fixed thread pool also bound its waiting queue?

The standard newFixedThreadPool factory fixes worker count but uses an effectively unbounded queue. Configure ThreadPoolExecutor with a bounded queue to constrain backlog.

Queue selection, thread pools and backpressure

Definition:

Backpressure limits admission when service capacity cannot absorb new arrivals.

Explanation:

FIFO, priority, delay, and direct handoff serve different workloads. Use PriorityBlockingQueue for ordered waiting work and DelayQueue for time eligibility; both are unbounded. LinkedTransferQueue can buffer ordinary offers or wait for receipt using transfer.

Illustration image:

2 core workers → 8 queued tasks → Grow up to 4 workers → Reject at saturation. 2 core workers8 queued tasksGrow up to 4 workersReject at saturation
2 core workers → 8 queued tasks → Grow up to 4 workers → Reject at saturation.

Example:

Worked example · excerpt unless noted
var workers = new java.util.concurrent.ThreadPoolExecutor(
    2, 4, 30, java.util.concurrent.TimeUnit.SECONDS,
    new java.util.concurrent.ArrayBlockingQueue<>(8),
    new java.util.concurrent.ThreadPoolExecutor.AbortPolicy());
workers.shutdown();

Internal working:

ThreadPoolExecutor creates core workers, offers to its work queue, then tries to grow up to maximum when insertion fails. Saturation triggers rejection. Observe queue age and service time, and use a rejection policy compatible with the producer thread.

Interview questions:

Why can CallerRunsPolicy be dangerous on an event loop?

It executes the rejected task on the submitting thread, so blocking work can stall unrelated requests.

Volatile, publication and lost updates

Definition:

A volatile field participates in the Java Memory Model’s visibility and ordering guarantees.

Explanation:

Use a volatile flag for simple publication or shutdown. Do not use volatile count++ for an exact counter, because the update reads, computes and writes in separate actions.

Illustration image:

Writer stores payload → Writer publishes ready=true → Reader observes ready → Reader sees earlier payload. Writer stores payloadWriter publishes ready=trueReader observes readyReader sees earlier payload
Writer stores payload → Writer publishes ready=true → Reader observes ready → Reader sees earlier payload.

Example:

Worked example · excerpt unless noted
class Mailbox {
    private String payload;
    private volatile boolean ready;
    void publish(String value) { payload = value; ready = true; }
    String read() { return ready ? payload : null; }
}

Internal working:

When a reader observes a volatile publication write, prior actions in the publishing thread are ordered before the reader’s subsequent actions by happens-before. Later mutations of referenced state still need their own coordination. AtomicInteger or a lock provides an indivisible increment.

Interview questions:

Can multiple writers use this as a repeatable queue?

No. This illustrates one-shot publication. Reuse and multiple producers require a protocol for ownership, updates and consumption.

String pool, immutability and Unicode

Definition:

String is an immutable text value with UTF-16-based indexing in its public API.

Explanation:

Use equals for text, intern for an explicit canonical reference when justified, and StringBuilder for repeated concatenation in a loop. Choose code points or grapheme processing deliberately for user-visible characters.

Illustration image:

Identity compares the two references. String.equals compares their text. Equal text, distinct object identityabPooled String: javaNew String: javaa == b → falsea.equals(b) → true
Identity compares the two references. String.equals compares their text.

Example:

Worked example · excerpt unless noted
String a = "java", b = new String("java");
System.out.println(a == b);       // false
System.out.println(a.equals(b));  // true
System.out.println("😀".length()); // 2 UTF-16 code units

Internal working:

Compile-time constant strings can share a pooled instance, while new String creates a new object. Modern OpenJDK compact strings may use Latin-1 byte storage internally without changing the UTF-16 public contract. A Unicode code point may require a surrogate pair.

Interview questions:

Does StringBuffer make a whole sequence of appends and checks atomic?

Individual synchronized methods do not guard a compound action unless its entire sequence shares a coordination boundary.

Serialization, deserialization and transient

Definition:

Java native serialization records an object graph and deserialization restores it under the applicable class and stream rules.

Explanation:

Serializable opts into native serialization. transient excludes normal instance field serialization, and static fields are class state. serialVersionUID is a compatibility identifier, not a business schema or a security policy.

Illustration image:

Default serialization writes the non-transient theme. Deserializing this example leaves the token at its default null value. Which fields survive Java serialization?theme = darktransient tokenStream: themetheme = darktoken = nullomitted
Default serialization writes the non-transient theme. Deserializing this example leaves the token at its default null value.

Example:

Worked example · excerpt unless noted
class Preferences implements java.io.Serializable {
    private static final long serialVersionUID = 1L;
    String theme = "dark";
    transient String accessToken;
}

Internal working:

Object streams preserve shared references within a stream. Default serializable fields are restored without running serializable class constructors; a required non-serializable superclass constructor participates. Avoid untrusted streams; for legacy inputs apply filters and validate values after decoding. Use explicit DTO formats across service boundaries.

Interview questions:

Does transient redact a secret everywhere?

No. It only affects default Java field serialization. Custom writers, JSON serializers and logs have their own rules.

Cloning, shallow vs deep copying

Definition:

A shallow copy duplicates the outer structure but retains references to mutable components.

Explanation:

Object.clone can produce a field-wise shallow copy when supported by Cloneable. Prefer a copy constructor or factory when you need explicit ownership and validation. Deep copy needs domain-specific treatment for shared nodes, cycles and external resources.

Illustration image:

Original object → Copy outer container → Both reference same mutable element → Mutation visible through both. Original objectCopy outer containerBoth reference same mutableelementMutation visible through both
Original object → Copy outer container → Both reference same mutable element → Mutation visible through both.

Example:

Worked example · excerpt unless noted
var original = new java.util.ArrayList<StringBuilder>();
original.add(new StringBuilder("A"));
var shallow = new java.util.ArrayList<>(original);
shallow.get(0).append("B");
System.out.println(original.get(0)); // AB

Internal working:

Object.clone does not call the ordinary constructors of the copied class. Arrays clone structurally but reference elements still point to their original objects. A deep snapshot copies the parts it owns and documents immutable values that can remain shared.

Interview questions:

Will List.copyOf prevent mutation of a StringBuilder element?

No. It prevents list mutation through the resulting reference, but its elements are still shared.

Singleton lifetime and ways it breaks

Definition:

A singleton limits instances within an explicitly defined scope, typically a class loader or dependency container.

Explanation:

Prefer an injected, stateless service for application dependencies. A JVM singleton can exist once per class loader, and a Spring singleton is ordinarily scoped to a bean definition and container. Neither gives one instance across deployed replicas.

Illustration image:

Class loader A → Its enum INSTANCE → Class loader B → Separate enum INSTANCE. Class loader AIts enum INSTANCEClass loader BSeparate enum INSTANCE
Class loader A → Its enum INSTANCE → Class loader B → Separate enum INSTANCE.

Example:

Worked example · excerpt unless noted
enum OrderPolicy {
    INSTANCE;
    boolean mayCancel(boolean dispatched) { return !dispatched; }
}

Internal working:

An initialization-on-demand holder and enum instance use class initialization for safe publication. Ordinary implementations can be duplicated by unsafe publication, cloning, reflection where access permits, or native deserialization unless identity is restored. Enum constants have built-in reflection and serialization protections for ordinary Java APIs, but still have class-loader scope.

Interview questions:

What happens if two containers or pods use this singleton for global coordination?

Each process or class-loader scope owns its own instance. Use an external coordination or durable consistency mechanism for a distributed invariant.

Singleton construction, reflection and readResolve

Definition:

A singleton implementation must define initialization, identity and the mechanisms that may create another instance.

Explanation:

A private constructor keeps ordinary source code from calling new. Reflection may bypass that boundary where module access permits. Implementing Cloneable or Serializable adds construction paths that a private constructor does not automatically control.

Illustration image:

First access → Holder initialized by JVM → Canonical instance returned → readResolve returns same instance. First accessHolder initialized by JVMCanonical instance returnedreadResolve returns same instance
First access → Holder initialized by JVM → Canonical instance returned → readResolve returns same instance.

Example:

Worked example · excerpt unless noted
final class Registry implements java.io.Serializable {
    private static final long serialVersionUID = 1L;
    private Registry() {}
    private static class Holder { static final Registry INSTANCE = new Registry(); }
    static Registry instance() { return Holder.INSTANCE; }
    private Object readResolve() { return instance(); }
}

Internal working:

The holder idiom relies on JVM class initialization. Double-checked locking needs a volatile instance and a second check under a lock. For a serializable singleton, readResolve can substitute the canonical instance after deserialization; an enum already preserves canonical identity in ordinary Java serialization.

Interview questions:

Does readResolve prevent reflective construction or create a single instance across the fleet?

No. It addresses native deserialization identity. Reflective access and distributed ownership require separate design.

StringBuilder, concatenation and exact character counts

Definition:

StringBuilder is a mutable buffer for assembling immutable String values.

Explanation:

Use a builder for incremental assembly in a loop. A single concatenation expression can already be optimized by the compiler and runtime, so benchmark actual code before making broad performance claims.

Illustration image:

Text fragments → Mutable builder storage → Final immutable string → Unicode-aware counting. Text fragmentsMutable builder storageFinal immutable stringUnicode-aware counting
Text fragments → Mutable builder storage → Final immutable string → Unicode-aware counting.

Example:

Worked example · excerpt unless noted
var builder = new StringBuilder();
for (String title : java.util.List.of("Java", "React")) {
    if (builder.length() > 0) builder.append(", ");
    builder.append(title);
}
System.out.println(builder.toString()); // Java, React

Internal working:

The Java 9+ javac implementation commonly emits invokedynamic string concatenation for expressions. Repeatedly growing a String accumulator can repeatedly copy text. Code points still differ from grapheme clusters that a user sees as one character.

Interview questions:

What does String.length measure?

UTF-16 code units, not code points or user-perceived characters.

Official documentation ↗

Back to top ↑