BTI Beyond The Interviews

Languages · 16 sections

Java

OOP, collections, concurrency, streams, and the JVM — the Java interview core (Java 25 LTS).

Free · full sheet 156 cards Updated 24 Oct 2026

Basics & Types

Primitive types

8 primitives: byte, short, int, long, float, double, char, boolean. Each has a fixed size (int 4 bytes). Not objects; stored by value. Prefer int over short/byte unless memory-critical.

int x = 42;
double d = 3.14;
char c = 'A';
boolean ok = true;

Wrapper classes

Byte, Short, Integer, Long, Float, Double, Character, Boolean. Enable primitives in collections and generics. Provide parsing (Integer.parseInt) and constants (Integer.MAX_VALUE).

Autoboxing / unboxing

Automatic conversion between primitive and wrapper. int→Integer (boxing), Integer→int (unboxing). Beware NPE on unboxing null and performance in tight loops.

Integer x = 5;        // boxing
int y = x;             // unboxing
List<Integer> list = new ArrayList<>();
list.add(5);           // autoboxed

Integer caching

Integer.valueOf caches -128..127 by default; the upper bound can be raised with -XX:AutoBoxCacheMax. So == may appear to work outside 127 on some JVMs—never rely on it. Always use equals() for value comparison.

Integer a = 127, b = 127;
a == b;   // true (cached by default)
Integer c = 128, d = 128;
c == d;   // not guaranteed; depends on -XX:AutoBoxCacheMax
c.equals(d); // true

String is immutable

String cannot be changed; operations return new String. Enables String pool sharing, thread-safety, and safe use as HashMap key. Use StringBuilder for mutable concatenation.

String pool

Literals are interned in the string pool. new String("x") creates a new heap object. intern() adds/reuses pool entry. == compares references; equals compares content.

String a = "hi";
String b = "hi";
a == b;            // true (pooled)
String c = new String("hi");
a == c;            // false
a.equals(c);       // true

var (Java 10+)

Local variable type inference. Type inferred from initializer; must be initialized. Not a keyword type—still statically typed. Improves readability for complex generics.

var list = new ArrayList<String>();
var map = Map.of("a", 1, "b", 2);
// var x;  // error: no initializer

Arrays vs ArrayList

Array: fixed size, primitive-friendly, covariant (runtime checks). ArrayList: resizable, generics, richer API. Convert with Arrays.asList / toArray.

final variables

final means assign-once. For primitives, value fixed. For references, reference fixed but object mutable. Effective final (never reassigned) needed for lambda capture.

Operators: == vs equals

== compares references for objects, values for primitives. equals() compares logical equality (override in your classes). Always use equals for object content. For enums, == is fine (singletons).

Ternary and short-circuit

?: conditional. && and || short-circuit (skip right side if result known). & and | evaluate both. Use short-circuit to guard nulls: if (s != null && s.length() > 0).

Type casting

Widening (int→long) implicit. Narrowing (long→int) requires explicit cast; may lose data. Object casts checked at runtime.

long l = 5;          // widening
int i = (int) l;     // narrowing
Object o = "str";
Integer n = (Integer) o; // throws ClassCastException at runtime

StringBuilder vs StringBuffer

StringBuilder: mutable, not thread-safe, fast. StringBuffer: mutable, synchronized (thread-safe), slower. Use StringBuilder unless sharing across threads; for concatenation in loops always StringBuilder.

StringBuilder sb = new StringBuilder();
sb.append("hi").append(' ').append(42);
String s = sb.toString(); // "hi 42"

String formatting

String.format / formatted (Java 15+) uses %s, %d, %f, %n. Prefer formatted for readability; Locale-sensitive. For simple concat use + or StringBuilder.

String msg = "User %s is %d".formatted(name, age);
// or String.format(Locale.US, "%.2f", 3.14159)

String interning and hashCode caching

String.hashCode() is cached after first computation (immutable). intern() returns the canonical pool reference. == on interned strings works but equals is preferred for clarity.

String s = new String("hi").intern();
"hi" == s; // true
int h = "hi".hashCode(); // cached

OOP

Four pillars

Encapsulation (private fields + accessors), inheritance (extends), polymorphism (overriding/overloading), abstraction (interfaces/abstract classes).

interface vs abstract class

Interface: contract, multiple inheritance, default/static/private methods (private since Java 9), no instance state (only constants). Abstract class: partial impl, instance state, single inheritance. Prefer interface for API contracts; use abstract class when sharing state/constructor logic. (Current LTS: Java 25.)

default methods (Java 8)

Interfaces can provide method bodies with default. Enables API evolution without breaking implementers. Resolve conflicts via InterfaceName.super.method().

interface Foo { default void hi() { System.out.println("hi"); } }
class Bar implements Foo {}  // inherits hi()

static methods in interfaces

Java 8+ allows static methods in interfaces, callable as Interface.method(). Not inherited by implementers. Useful for factory/helper methods.

abstract class

Cannot be instantiated; may have abstract (unimplemented) methods and concrete methods/fields. Subclass must implement all abstract methods or be abstract itself.

Polymorphism

Runtime dispatch: subclass overrides superclass method; call resolved by actual object type. Compile-time overloading: same name, different params.

Animal a = new Dog();
a.speak(); // Dog.speak() (runtime)

Method overriding rules

Same signature, covariant return allowed, cannot reduce visibility, cannot throw broader checked exceptions. Use @Override to catch typos.

final class / method

final class prevents subclassing (String, Integer). final method prevents overriding. Use for security, immutability, or performance hints.

this and super

this: current instance; this() calls another constructor. super: parent reference; super() calls parent constructor (must be first statement). Use super.method() to call overridden parent method.

Constructors

No return type, name = class. Default constructor provided if none defined. Chaining via this(). If you define any constructor, default is not generated.

Initialization order

Full order: parent static fields/blocks → child static fields/blocks → parent instance field initializers & instance blocks → parent constructor → child instance field initializers & instance blocks → child constructor. Static init runs once per class on first use.

Nested classes

Static nested: no enclosing instance, can access static members. Inner (non-static): holds reference to outer, accesses instance members. Local/anonymous: inside methods.

Immutability & defensive copying

Immutable objects (final fields, no setters, defensive copies) are thread-safe and safe HashMap keys. For mutable components, copy on construction and on access; return unmodifiable views.

public List<String> items() { return List.copyOf(items); }
// constructor: this.items = List.copyOf(items);

Collections

List / Set / Map overview

List: ArrayList (array, fast random access), LinkedList (nodes, fast insert/remove). Set: HashSet (hash), TreeSet (sorted), LinkedHashSet (insertion order). Map: HashMap, TreeMap, LinkedHashMap.

ArrayList vs LinkedList

ArrayList: O(1) get, O(n) insert middle, cache-friendly. LinkedList: O(n) get, O(1) insert at known node, more memory. Usually ArrayList wins; use LinkedList only for frequent head/tail ops (or ArrayDeque).

HashMap internals

Array of buckets. hash(key) → index. Collision: linked list → red-black tree when bucket size ≥8 (and table ≥64). Load factor 0.75 → resize 2×. Average O(1).

Map<String,Integer> m = new HashMap<>();
m.put("a", 1);
// int h = key.hashCode(); hash = h ^ (h >>> 16);

HashMap null keys

HashMap allows one null key and null values. Hashtable and ConcurrentHashMap do not allow null keys/values (NullPointerException).

ConcurrentHashMap

Thread-safe map with fine-grained locking (bucket-level, Java 8+). No global lock; better concurrency than Hashtable/synchronizedMap. Does not allow null keys/values.

TreeMap / NavigableMap

Sorted by key (natural or Comparator). O(log n) ops. Supports subMap, headMap, tailMap, ceilingKey, floorKey, higherKey. Keys must be Comparable or Comparator provided.

Set implementations

HashSet: hash-based, O(1), no order. LinkedHashSet: insertion order. TreeSet: sorted. EnumSet: bit-vector, very fast for enums.

Queue / Deque

Queue: FIFO (offer/poll/peek). Deque: double-ended. ArrayDeque (array-backed, fast) preferred over LinkedList and Stack. PriorityQueue: heap, natural/comparator ordering.

Deque<Integer> dq = new ArrayDeque<>();
dq.offerLast(1); dq.offerFirst(0);
int x = dq.pollFirst(); // 0

Fail-fast iterators

Modifying collection during iteration (except iterator.remove) → ConcurrentModificationException. Use iterator.remove(), removeIf, copy-on-write collections, or stream.

Iterator<String> it = list.iterator();
while (it.hasNext()) { if (cond) it.remove(); }
list.removeIf(x -> x < 0); // safe

Comparable vs Comparator

Comparable: natural ordering (compareTo, inside class). Comparator: external (compare, lambda). Use Comparator for multiple/custom sort orders.

list.sort(Comparator.comparing(User::getAge)
  .thenComparing(User::getName));

equals/hashCode contract

Equal objects (equals true) must have equal hashCode. Used by hash-based collections. If you override equals, override hashCode. Use Objects.equals/hashCode.

Collections utility

Collections.sort, reverse, shuffle, unmodifiableList, synchronizedList, singletonList, emptyList. List.of/Set.of/Map.of (Java 9+) create immutable collections.

Concurrency

Thread creation

Extend Thread or implement Runnable/Callable. Prefer ExecutorService over raw threads. Runnable returns void; Callable returns value and can throw.

Thread t = new Thread(() -> doWork());
t.start();
// or
ExecutorService ex = Executors.newFixedThreadPool(4);
Future<Integer> f = ex.submit(() -> 42);

synchronized

Intrinsic (monitor) lock on object (instance method) or class (static method). Reentrant. Provides mutual exclusion + visibility. Use for simple cases; prefer locks for flexibility.

synchronized (lock) { /* critical section */ }
public synchronized void m() { /* instance lock */ }

volatile

Visibility/ordering via happens-before: a write to a volatile variable happens-before every subsequent read of that variable. Prevents reordering around the access. Does NOT ensure atomicity (use Atomic* or synchronized for compound actions).

Atomic classes

AtomicInteger, AtomicReference, etc. use CAS (compare-and-swap) for lock-free atomic ops: incrementAndGet, compareAndSet. Better than synchronized for simple counters.

AtomicInteger c = new AtomicInteger();
c.incrementAndGet();
c.compareAndSet(1, 2);

ExecutorService

Thread pools: newFixedThreadPool, newCachedThreadPool, newSingleThreadExecutor, newScheduledThreadPool, newWorkStealingPool. Submit Runnable/Callable, get Future. Always shutdown().

CompletableFuture

Async composition: thenApply, thenCompose, thenCombine, exceptionally, whenComplete. Non-blocking chaining; better than Future. Use supplyAsync/runAsync with custom executor.

CompletableFuture.supplyAsync(() -> fetch())
  .thenApply(s -> parse(s))
  .thenAccept(r -> save(r))
  .exceptionally(ex -> { log(ex); return null; });

Locks (java.util.concurrent.locks)

ReentrantLock (tryLock, lockInterruptibly, fairness), ReadWriteLock (many readers, one writer), StampedLock (optimistic reads). More flexible than synchronized.

Condition variables

lock.newCondition() gives await/signal/signalAll for producer-consumer. Replaces Object.wait/notify with multiple condition queues.

Lock lock = new ReentrantLock();
Condition notFull = lock.newCondition(), notEmpty = lock.newCondition();
// producer: while (full) notFull.await(); ... notEmpty.signal();

CountDownLatch / CyclicBarrier

CountDownLatch: one-shot, await until count reaches 0 (start gate / completion). CyclicBarrier: reusable, threads wait for each other at a barrier point.

CountDownLatch start = new CountDownLatch(1);
// workers: start.await(); ...
start.countDown();

CyclicBarrier b = new CyclicBarrier(3, () -> System.out.println("go"));

Semaphore

Controls access to a resource with N permits. acquire/release. Use for rate limiting or bounding concurrency.

Semaphore sem = new Semaphore(4);
sem.acquire(); try { work(); } finally { sem.release(); }

ForkJoinPool

Work-stealing pool for divide-and-conquer (RecursiveTask/RecursiveAction). Powers parallel streams. Use for CPU-bound recursive tasks.

Thread safety of collections

Vector/Hashtable synchronized (legacy). Use ConcurrentHashMap, CopyOnWriteArrayList (read-heavy), BlockingQueue (producer-consumer). Collections.synchronizedXxx wraps but locks whole collection.

ThreadLocal

Per-thread variable; each thread has its own value. Use for request context, formatters. Always remove() in finally to avoid leaks in thread pools. InheritableThreadLocal propagates to child threads.

private static final ThreadLocal<User> CURRENT = new ThreadLocal<>();
try { CURRENT.set(user); work(); } finally { CURRENT.remove(); }

Deadlock detection

Deadlock: cyclic lock dependency. Detect via thread dump (jstack) looking for 'Found 1 deadlock', or ThreadMXBean.findDeadlockedThreads(). Avoid by consistent lock ordering and tryLock timeouts.

ThreadMXBean mx = ManagementFactory.getThreadMXBean();
long[] ids = mx.findDeadlockedThreads();
// or: jstack <pid>

Streams & Lambdas

Lambda syntax

(params) -> expression or { statements }. Functional interfaces (one abstract method) are lambda targets: Runnable, Comparator, Function, Predicate, Consumer, Supplier.

Stream pipeline

source → intermediate ops (filter, map, sorted, distinct, limit, skip, flatMap) → terminal (collect, forEach, reduce, count, findFirst, anyMatch). Lazy; terminal triggers execution.

List<String> names = users.stream()
  .filter(u -> u.getAge() >= 18)
  .map(User::getName)
  .sorted()
  .collect(Collectors.toList());

map vs flatMap

map: 1→1 transform. flatMap: 1→many then flatten. Use flatMap for nested collections/Optional.

List<List<Integer>> nested = ...
nested.stream().flatMap(List::stream).toList();

Collectors

toList, toSet, toMap, groupingBy, partitioningBy, joining, counting, summingInt, averagingDouble, toCollection. Collectors.teeing (Java 12) combines two collectors.

Map<Dept, List<User>> byDept =
  users.stream().collect(Collectors.groupingBy(User::getDept));
String csv = names.stream().collect(Collectors.joining(", "));

reduce

Combine elements into one value. reduce(identity, accumulator) or reduce(accumulator) (returns Optional). Associative for parallel streams.

int sum = nums.stream().reduce(0, Integer::sum);
Optional<Integer> max = nums.stream().reduce(Integer::max);

Optional

Container for nullable value; avoid null returns. orElse, orElseThrow, orElseGet, map, flatMap, filter, ifPresent. Don't call get() without isPresent().

Optional<User> u = repo.findById(id);
String name = u.map(User::getName).orElse("unknown");

Method references

Class::staticMethod, object::instanceMethod, Class::new (constructor), Class::instanceMethod (unbound, first arg is receiver).

Parallel streams

stream().parallel() uses common ForkJoinPool. Speeds up CPU-bound ops on large data. Avoid for I/O, small data, or stateful ops. Encounter order: forEach may run in arbitrary order—use forEachOrdered for ordered processing; collect/toList/findFirst retain encounter order on ordered sources.

Short-circuit terminals

findFirst, findAny, anyMatch, allMatch, noneMatch (and min/max) stop processing early; findAny is better for parallel streams. Note: limit (and skip) are short-circuiting *intermediate* ops, not terminals.

Primitive streams

IntStream, LongStream, DoubleStream avoid boxing. mapToInt, flatMapToInt. .boxed() to get Stream<Integer>. summaryStatistics() for min/max/sum/avg/count.

Stream creation

collection.stream(), Arrays.stream, Stream.of, Stream.generate (infinite), Stream.iterate, Files.lines, Pattern.splitAsStream.

Stateful vs stateless ops

Stateless: filter, map. Stateful: sorted, distinct, limit, skip (may buffer). Stateful ops can hurt parallel performance and memory.

JVM

Memory areas

Heap (objects), Stack (frames, per thread), Metaspace (class metadata, replaced PermGen in Java 8), PC register, Native method stack.

Heap generations

Young gen (Eden + Survivor S0/S1) → Old gen. Minor GC collects young; Major/Full GC collects old. Most objects die young (generational hypothesis).

GC algorithms

Serial, Parallel (throughput), G1 (default since JDK 9, region-based, predictable pauses), ZGC (generational by default since JDK 23; non-generational removed in JDK 24; ultra-low latency), Shenandoah (ultra-low latency). CMS removed in JDK 14. Choose via -XX:+UseG1GC etc.

GC tuning flags

-Xms/-Xmx (heap size), -Xmn (young gen), -XX:MaxGCPauseMillis, -XX:+HeapDumpOnOutOfMemoryError, -XX:OnOutOfMemoryError. Monitor with jstat, VisualVM, JFR.

Class loading

Bootstrap → Platform → Application classloaders. Parent-delegation: parent first. Lazy loading on first reference. Custom classloaders for isolation (plugins, app servers).

JIT compilation

HotSpot interprets bytecode, then JIT-compiles hot methods to native code (C1/C2). Tiered compilation. Deoptimization on assumption failure. Inlining, escape analysis.

Escape analysis

JIT determines if object escapes method/thread. If not, can stack-allocate, eliminate locks, or scalar-replace—reducing GC pressure.

Bytecode & javap

javac compiles to .class bytecode. javap -c disassembles. JVM executes bytecode; platform-independent. Check with javap -v for constant pool.

JMM (Java Memory Model)

Defines happens-before relationships: monitor unlock→lock, volatile write→read, thread start/join, static init. Programs correctly synchronized are data-race-free.

Profiling tools

jps, jstack (thread dumps), jmap (heap dump), jstat (GC stats), jcmd, Java Flight Recorder (JFR), async-profiler. Use for CPU, allocation, lock contention.

OOM types

Java heap space (heap full), Metaspace (class metadata), unable to create native thread (OS limits), GC overhead limit exceeded (spending >98% time in GC).

Java versions & LTS

LTS releases: 8, 11, 17, 21, 25 (current LTS). Feature releases every 6 months. Prefer latest LTS for new projects; check library support.

Exceptions

Checked vs unchecked

Checked (extends Exception, not RuntimeException): must handle/declare; for recoverable conditions. Unchecked (RuntimeException, Error): programming errors; no compile-time enforcement.

Error vs Exception

Error: serious JVM problems (OutOfMemoryError, StackOverflowError); don't catch. Exception: application-level; catchable. Throwable is root.

try-catch-finally

try block; catch by type (subclass first); finally always runs (cleanup). Return in finally overrides try return. Avoid heavy logic in finally.

try-with-resources

Auto-closes AutoCloseable/Closeable resources. Multiple resources; close in reverse order. Suppressed exceptions available via getSuppressed().

try (var in = new FileInputStream(f);
     var out = new FileOutputStream(g)) {
  in.transferTo(out);
}

multi-catch

catch (IOException | SQLException e) handles multiple types in one block. e is effectively final. Cleaner than duplicate catch blocks.

throw vs throws

throw: actually throws an exception instance. throws: declares method may throw checked exception(s).

Custom exception

Extend Exception (checked) or RuntimeException (unchecked). Provide constructors (message, cause). Use for domain-specific errors. Preserve cause chain.

class InsufficientFundsException extends RuntimeException {
  InsufficientFundsException(String msg, Throwable cause) { super(msg, cause); }
}

Exception chaining

Pass original exception as cause (new Ex(msg, cause)) to preserve stack trace. Use getCause() to unwrap. Avoid swallowing exceptions silently.

finally pitfalls

finally runs even on return/exception. If finally throws, it masks original exception. Prefer try-with-resources. Don't return from finally.

NPE (NullPointerException)

Thrown on dereferencing null. Java 14+ helpful NPE messages show which variable was null. Avoid via Optional, Objects.requireNonNull, null checks.

Best practices

Throw early, catch late. Don't catch Exception/Throwable broadly. Don't use exceptions for control flow. Log with context. Fail fast.

Generics

Generic class/method

Type parameters <T>. Compile-time type safety; no casts. T can be bounded: <T extends Number>. Generic methods declare <T> before return type.

class Box<T> { private T value; T get(){return value;} }
public static <T> T first(List<T> list){ return list.get(0); }

Type erasure

Generic type info removed at runtime; replaced by bound (Object if unbounded). Enables backward compat. Consequences: can't new T(), can't instanceof T, can't overload by type param.

Wildcards

? unbounded. ? extends T (upper bound): read T, can't write (except null). ? super T (lower bound): write T, read Object. PECS: Producer Extends, Consumer Super.

void copy(List<? super T> dest, List<? extends T> src) {
  for (T x : src) dest.add(x);
}

PECS rule

If a structure produces T (you read from it), use extends T. If it consumes T (you write to it), use super T. Collections.copy(dest, src): dest is super, src is extends.

Bounded type parameters

<T extends Comparable<T>> restricts T. Multiple bounds: <T extends A & B> (class first, then interfaces). Used for algorithms requiring capabilities.

Generic arrays

Cannot create generic arrays (new T[10] illegal). Use (T[]) new Object[n] with unchecked warning, or ArrayList<T>. Arrays are covariant; generics invariant.

Raw types

Using generic class without type args (List instead of List<String>) for backward compat. Loses type safety; compiler warnings. Avoid in new code.

Type tokens / Class<T>

Pass Class<T> to recover type at runtime (e.g., Gson.fromJson(json, Foo.class)). Workaround for erasure.

Recursive generics

Enum<E extends Enum<E>>. Enables type-safe compareTo and clone. Pattern: class Node<T extends Node<T>>.

class Node<T extends Node<T>> { T next; }
enum Color { RED, GREEN } // Enum<E extends Enum<E>>

Variance

Generics invariant: List<Integer> is not List<Number>. Arrays covariant: Integer[] is Number[]. Wildcards add use-site variance.

Modern Java

Records (Java 16)

Immutable data carrier: record Point(int x, int y) {}. Auto-generates constructor, accessors (x(), y()), equals, hashCode, toString. Records are only shallowly immutable: component references are final, but mutable component objects (e.g. a List) can still change—defensive-copy mutable components. Can add methods/validation in compact constructor.

record User(String name, int age) {
  public User { if (age < 0) throw new IllegalArgumentException(); }
}

Sealed classes (Java 17)

Restrict which classes can extend/implement: sealed class Shape permits Circle, Square. Subclasses must be final/sealed/non-sealed. Enables exhaustive pattern matching.

sealed interface Shape permits Circle, Square {}
final class Circle implements Shape {}
final class Square implements Shape {}

Pattern matching for instanceof (Java 16)

if (obj instanceof String s) { ... s ... } binds variable when true. Eliminates cast. Works with guards in switch.

Switch expressions (Java 14)

switch returns value; arrow labels; no fall-through; yield for blocks. Exhaustive with enums/sealed types.

int days = switch (month) {
  case 2 -> 28;
  case 4,6,9,11 -> 30;
  default -> 31;
};

Pattern matching in switch (Java 21)

case Integer i -> ..., case String s when s.isEmpty() -> ... . Exhaustive over sealed types; compiler checks coverage.

Text blocks (Java 15)

Multi-line string literals with """ ... """. Preserves newlines; stripIndent/translateEscapes. Great for SQL/JSON.

String sql = """
  SELECT id, name
  FROM users
  WHERE active = true
  """;

var in lambdas (Java 11)

Can use var in lambda params to add annotations: (var x, var y) -> x + y. Rare; useful for @Nonnull annotations.

String new methods (Java 11+)

isBlank, lines, strip/stripLeading/stripTrailing, repeat(n), indent(n). Java 12: transform, describeConstable.

Collections factory methods (Java 9+)

List.of, Set.of, Map.of, Map.ofEntries. Immutable; null elements not allowed; throw on mutation. Great for constants.

Stream additions

takeWhile/dropWhile (Java 9), ofNullable, iterate with predicate. Java 16: toList() terminal (unmodifiable). Java 22: Stream.gather (custom intermediate ops) preview; final in JDK 24 (Gatherers class).

Virtual threads (Java 21)

Lightweight; mount on carrier threads. Don't pool; create per task. As of JDK 24 (JEP 491) synchronized no longer pins carrier threads; pinning remains only for native/JNI frames. Great for high-throughput I/O servers.

try (var ex = Executors.newVirtualThreadPerTaskExecutor()) {
  for (var r : tasks) ex.submit(r);
}

Foreign Function & Memory (Java 22)

FFM API (Project Panama): call native code and manage off-heap memory without JNI. Arena for lifecycle; MemorySegment for data.

Unnamed variables and patterns (Java 22)

Use _ for variables/patterns you don't need. Improves readability and avoids unused-variable warnings.

for (var _ : list) count++;
try { ... } catch (Exception _) { /* ignore */ }

Record patterns (Java 21)

Deconstruct records in instanceof/switch: if (obj instanceof Point(int x, int y)) { ... }. Nested patterns supported.

if (obj instanceof Point(int x, int y)) {
  System.out.println(x + "," + y);
}

Sequenced collections (Java 21)

SequencedCollection/SequencedSet/SequencedMap add getFirst/getLast and reversed() view. ArrayList, LinkedList, TreeSet, LinkedHashMap implement them.

List<String> l = new ArrayList<>(List.of("a","b"));
String first = l.getFirst(); // "a"
List<String> rev = l.reversed(); // view

Structured concurrency (preview)

StructuredTaskScope (incubator/preview, Java 21+) treats a group of tasks as one unit: fork subtasks, join, propagate cancellation/failures. Cleaner than CompletableFuture for fan-out.

try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
  var f1 = scope.fork(() -> fetchA());
  var f2 = scope.fork(() -> fetchB());
  scope.join().throwIfFailed();
  return f1.get() + f2.get();
}

Scoped values (Java 25)

ScopedValue: immutable, thread-safe alternative to ThreadLocal for sharing context (request/user) within a bounded scope; works well with virtual threads. Finalized in Java 25.

private static final ScopedValue<User> CURRENT = ScopedValue.newInstance();
ScopedValue.where(CURRENT, user).run(() -> handle());

Compact source files / instance main (Java 25)

Java 25 (JEP 512) allows a source file with top-level methods and an instance main() without a class wrapper—great for scripts/learning. Implicitly imports java.base.

// Hello.java
void main() {
  println("Hello");
}

Common Gotchas

String concatenation in loops

s += x in loop creates O(n²) strings. Use StringBuilder or String.join / Collectors.joining.

Floating point precision

double/float binary; 0.1+0.2 != 0.3. Use BigDecimal for money. Compare with epsilon. Float is 7 digits; double 15.

new BigDecimal("0.1").add(new BigDecimal("0.2"))
  .compareTo(new BigDecimal("0.3")) == 0 // true

Integer overflow

Silent wraparound. int max 2,147,483,647. Use long or Math.addExact (throws on overflow). Check inputs.

NPE from unboxing

Integer x = null; int y = x; → NPE. Guard null before unboxing. Prefer primitives when null not needed.

Array covariance gotcha

Object[] arr = new String[1]; arr[0] = 1; compiles but throws ArrayStoreException at runtime. Generics avoid this.

hashCode/equals mismatch

If equals changed but hashCode not, objects land in wrong buckets → lookup fails. Always update both. Use records to auto-generate.

Mutable keys in HashMap

If a key's hashCode changes after insertion (mutable field), the entry becomes unreachable. Use immutable keys (String, Integer, records).

Static initialization order

Static fields initialize in declaration order; forward references to not-yet-initialized static fields yield default values. Avoid complex static init.

Resource leaks

Unclosed streams/connections. Use try-with-resources. Ensure close() in finally if manual. Watch for exceptions masking close.

Thread-unsafe SimpleDateFormat

SimpleDateFormat is not thread-safe. Use DateTimeFormatter (immutable, thread-safe) in java.time.

Stream reuse

Streams are single-use; terminal op consumes. Re-create from source. IllegalStateException on second terminal.

BigDecimal equals vs compareTo

BigDecimal.equals considers scale: new BigDecimal("1.0").equals(new BigDecimal("1")) is false. Use compareTo == 0 for value equality; hashCode differs by scale too.

new BigDecimal("1.0").compareTo(new BigDecimal("1")) == 0 // true
new BigDecimal("1.0").equals(new BigDecimal("1")) // false

Serialization pitfalls

Implement Serializable; serialVersionUID for versioning. Transient fields not serialized. Deserialization can create objects bypassing constructors; validate invariants (readObject). Prefer records/JSON for data transfer. Beware deserialization attacks.

private static final long serialVersionUID = 1L;
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
  in.defaultReadObject(); /* validate */
}

Date & Time (java.time)

LocalDate / LocalTime / LocalDateTime

Date/time without zone/offset. Immutable. Use for calendar dates and wall-clock times. Factory: now(), of(), parse().

LocalDate d = LocalDate.of(2026, 10, 23);
LocalDateTime dt = LocalDateTime.now();

Instant & ZonedDateTime

Instant: point on timeline (epoch seconds/nanos). ZonedDateTime: instant + zone rules. Convert between via atZone/withZoneSameInstant. Prefer Instant for storage, ZonedDateTime for display.

Instant now = Instant.now();
ZonedDateTime z = now.atZone(ZoneId.of("Europe/Paris"));

DateTimeFormatter

Immutable, thread-safe formatter. Use predefined (ISO_LOCAL_DATE) or pattern ("yyyy-MM-dd HH:mm"). parse/format. Replaces SimpleDateFormat.

DateTimeFormatter f = DateTimeFormatter.ofPattern("dd/MM/yyyy");
LocalDate.parse("23/10/2026", f);

Duration vs Period

Duration: time-based (hours/seconds/nanos) for instants. Period: date-based (years/months/days) for calendar dates. Don't mix; use the right one for plus/minus.

Instant t2 = t1.plus(Duration.ofMinutes(5));
LocalDate d2 = d1.plus(Period.ofDays(10));

java.time pitfalls

All java.time objects are immutable and thread-safe. Month is 1-based in of() but Month enum exists. Avoid legacy Date/Calendar. Convert legacy via toInstant/from.

I/O & NIO

Bytes vs chars

InputStream/OutputStream handle bytes; Reader/Writer handle chars (encoding). Always specify charset (UTF_8) instead of platform default.

Files.writeString(path, text, StandardCharsets.UTF_8);
String s = Files.readString(path, StandardCharsets.UTF_8);

java.nio.file.Files

Modern file API: readAllBytes, readString, writeString, copy, move, delete, walk, lines. Prefer over java.io.File. Path is the new abstraction.

Path p = Path.of("a.txt");
List<String> lines = Files.readAllLines(p);
Files.walk(Path.of("."))

NIO channels & buffers

Channel (FileChannel, SocketChannel) + ByteBuffer for non-blocking/async I/O. Buffers have flip/clear/compact. Use for high-throughput or direct (off-heap) buffers.

ByteBuffer buf = ByteBuffer.allocate(1024);
buf.put(data); buf.flip();
channel.write(buf);

Path vs File

Path (NIO.2) is preferred; File is legacy. Convert with toPath()/toFile(). Path supports WatchService, symbolic links, and better error messages.

Modules (JPMS)

module-info.java

Module descriptor declares name, requires, exports. Strong encapsulation: only exported packages are accessible. Java 9+.

module com.example.app {
  requires java.sql;
  exports com.example.api;
}

exports vs opens

exports: compile/runtime access to public types. opens: runtime-only (reflection) access, needed for frameworks (Jackson, Spring). Use opens for reflection-heavy libs.

Services (uses/provides)

ServiceLoader-based discovery: module declares uses Interface; provider module declares provides Interface with Impl. Decouples API from implementation.

uses com.example.spi.Plugin;
provides com.example.spi.Plugin with com.example.impl.PluginImpl;

jlink

Create custom runtime images with only needed modules: jlink --module-path ... --add-modules ... --output app. Smaller footprint; combine with jpackage for native installers.

Serialization

Serializable basics

Implement java.io.Serializable (marker). ObjectOutputStream.writeObject. Fields must be serializable or transient. Prefer records/JSON for new data transfer.

serialVersionUID

Version stamp for class compatibility. Declare explicitly to control evolution; mismatch → InvalidClassException. Increment on incompatible changes.

private static final long serialVersionUID = 1L;

transient & custom

transient skips field. Implement readObject/writeObject or readResolve for invariants. Deserialization bypasses constructors—validate in readObject.

private transient String cache;
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
  in.defaultReadObject();
}

Design Patterns

Singleton

One instance. Prefer enum singleton (thread-safe, serialization-safe) or holder idiom.

enum Singleton { INSTANCE; }

Builder

Construct complex objects step-by-step; immutable result; fluent API. Useful for many optional params.

User u = new User.Builder("Ada").age(30).build();

Factory method

Create objects via static factory (Foo.of/from/valueOf) instead of constructors: better names, caching, subtype control, validation.

public static User of(String name) { return new User(name); }

What's new in Java (21 → 25)

What are virtual threads (Java 21), and when do they help?

Lightweight JVM-managed threads (Thread.ofVirtual(), Executors.newVirtualThreadPerTaskExecutor()). Millions are possible. Good for blocking I/O-bound thread-per-request code; no benefit for CPU-bound work. Don't pool them.

Thread.ofVirtual().start(task);

try (var ex = Executors.newVirtualThreadPerTaskExecutor()) {
    ex.submit(task);   // one virtual thread per task, do not pool
}

What was 'pinning', and what changed in Java 24?

A virtual thread blocking inside synchronized pinned its carrier OS thread. JEP 491 (Java 24) lets virtual threads unmount inside synchronized, so the old advice "replace synchronized with ReentrantLock" is mostly obsolete. (Native/JNI frames can still pin.)

// pre-24: virtual thread blocks here -> carrier OS thread pinned
synchronized (lock) {
    blockingIo();     // JEP 491 (Java 24): now unmounts instead of pinning
}

Pattern matching for switch + record patterns (Java 21)?

Exhaustive switch over a sealed interface; record patterns deconstruct the components inline, so no default branch is needed.

sealed interface Shape permits Circle, Sq {}
record Circle(double r) implements Shape {}
record Sq(double s) implements Shape {}

double area(Shape s) { return switch (s) {
  case Circle(double r) -> Math.PI * r * r;
  case Sq(double x)     -> x * x; }; }   // exhaustive, no default needed

What's final in Java 25 (LTS, Sept 2025)?

Compact source files + instance void main() (JEP 512), flexible constructor bodies (statements before super(), JEP 513), module import declarations (import module java.base;, JEP 511), scoped values (JEP 506), compact object headers as a product feature (JEP 519). Structured concurrency is still preview.

// JEP 512: compact source file, instance main, no class boilerplate
void main() {
    System.out.println("hello");
}

// JEP 513: statements before super()
class A extends B {
    A(int x) { if (x < 0) throw new IAE(); super(x); }
}

Unnamed variables _ (final in Java 22)?

Ignore values you don't need: catch (Exception _), case Circle(_) ->, for (var _ : list).

try { ... } catch (Exception _) { }
case Circle(_) -> 0;
for (var _ : list) { count++; }

Stream Gatherers (final in Java 24)?

stream.gather(...) adds custom intermediate operations, e.g. Gatherers.windowFixed(3), windowSliding, fold, mapConcurrent. Fills the gaps that collect couldn't cover mid-stream.

stream.gather(Gatherers.windowFixed(3)).forEach(System.out::println);
stream.gather(Gatherers.fold(() -> 0, Integer::sum));
stream.gather(Gatherers.mapConcurrent(8, this::call));

ScopedValue vs ThreadLocal?

ScopedValue is immutable, bound for a bounded scope (ScopedValue.where(KEY, v).run(...)), cheap to inherit by child virtual threads, with no leaks. ThreadLocal is mutable and leak-prone with pools/millions of threads.

ScopedValue.where(USER, user).run(() -> handle());
// immutable, scope-bounded, inherited by virtual threads, no remove() needed

Want this as flashcards? Study these 156 cards recall-first in the browser — flip, answer out loud, grade yourself.

Open the card deck