Quick Reference
The key points of all twenty chapters on one page. Use it to preview the book, or to review a chapter after reading it.
Part I Foundations
javaccompiles.javainto platform-neutral bytecode (.class). A platform-specific JVM runs it: load → verify → interpret → JIT-compile the hot parts.- Objects live on the heap, method calls on per-thread stacks. Class metadata moved from PermGen to Metaspace in Java 8.
- Java 11 dropped the separate JRE download; Java 9's
jlinkbuilds trimmed runtimes instead. - Every class file records its Java version: major − 44. Mismatch →
UnsupportedClassVersionError. Compile with--release N. - Running Java got lighter:
jshell(9),java Hello.java(11), multi-file launch (22), and in Java 25, a whole program can bevoid main() { IO.println("Hi"); }.
2 Types, Variables and Conversions
- Eight primitives with fixed sizes on every platform:
byte8 bits,short16,char16 (unsigned),int32,long64,float32,double64, plusboolean. Everything else is a reference. - Widening (small → big) is automatic. Narrowing needs a cast and silently drops bits:
(byte) 130is-126. UseMath.addExact(Java 8) when overflow must fail loudly. byte + byteis anint. Arithmetic onbyte,shortandcharalways happens inint.- Fields get default values, local variables don't. Use
BigDecimalfor money, neverdouble. var(Java 10) infers a local's type._(Java 22) names a variable you never use. UTF-8 is the default charset since Java 18.
- Expressions evaluate left to right; precedence decides grouping.
i++ + ++iwithi = 5is12. - Integer
/truncates toward zero and%takes the sign of the dividend:-7 % 3is-1. UseMath.floorMod(Java 8) for a remainder that's never negative. &&and||short-circuit;&and|always evaluate both sides.>>keeps the sign,>>>fills with zeros.switchgrew up: strings (Java 7), arrows and switch expressions withyield(Java 14), type patterns, guards andcase null(Java 21).- No new arithmetic or logical operators arrived between Java 7 and 27; Java 8's
->and::are syntax for lambdas and method references.instanceofgained patterns (Java 16), which removed most casts.
Part II Objects
4 Classes, Objects and References
- A class is a blueprint; an object is an instance created at run time with
new, always on the heap. - A reference variable holds a reference to an object, not the object. Copying a reference shares the object.
- Printing an object shows
ClassName@plus its hash code in hex. That's not a memory address. ==compares references;equals()compares meaning, but only if the class overrides it.- A data class needed hand-written
equals,hashCodeandtoStringin Java 7. A record (Java 16) generates them:record Money(String currency, long cents) {}.
5 Constructors, static and Initializer Blocks
- A constructor initializes a new object. If you write none, the compiler adds a no-argument one.
- Order: static blocks run once when the class initializes; then, for each object, instance initializers run, then the constructor body.
this(...)calls another constructor of the same class;super(...)calls the parent's. Until Java 25 one of them had to be the very first statement.staticmembers belong to the class, shared by all objects. Static methods have nothis.- Since Java 7, a class needs a
mainto be launched; its static block no longer runs first. - Java 25 (flexible constructor bodies): you can validate and prepare arguments before
super(...).
- Java is always pass-by-value. For objects, the value passed is a reference, so a method can change the object but can't make the caller's variable point elsewhere.
- Overloading = same name, different parameter lists. The return type alone doesn't count. The compiler picks the overload from static types.
- Overriding = a subclass replaces an inherited method. The JVM picks the override from the object's runtime type (dynamic binding).
- Static methods are hidden, not overridden.
- Varargs (Java 5) accept zero or more arguments. Method references (Java 8) such as
Integer::parseIntturn a method into a value.
class Car extends Vehicle: a class has one parent class. Every chain ends atjava.lang.Object.- Parent constructors always run first: each constructor begins with
this(...)orsuper(...), and the compiler insertssuper()if you write neither. - Fields are hidden (the reference type decides); methods are overridden (the object decides).
finalstops extension or overriding. Sealed classes and interfaces (Java 17) allow extension only by a listed set of types, which makesswitchexhaustive (Java 21).- Prefer composition (a class has another object) over inheritance unless the relationship is truly "is-a."
- An abstract class can't be instantiated. It can have constructors, fields, concrete methods and abstract methods.
- An interface is a contract. Its fields are always
public static finalconstants. - Java 8 added
defaultandstaticmethods to interfaces; Java 9 addedprivateones. That's howList.sortandCollection.streamwere added without breaking existing implementations. - If two interfaces give a class the same default method, the class must override it and can pick one with
Walker.super.move(). - An interface with exactly one abstract method is a functional interface, and a lambda can implement it (Java 8).
Part III Organizing Code
9 Packages, Access and Modules
- A package is a namespace and a folder:
package com.trail.util;lives incom/trail/util/. Compile withjavac -d outto build the folder tree. - Four access levels:
private< package-private (no keyword) <protected<public.protectedfrom another package works only through inheritance. - Before Java 9,
publicmeant "anyone on the classpath." Modules (module-info.java) addrequiresandexports, so a public class in an unexported package is invisible outside its module. - Since Java 16/17, JDK internals are strongly encapsulated;
--illegal-accessis gone. - Java 25 added
import module java.base;to import every package a module exports in one line.
- Static nested class: a class inside a class, with no tie to an outer object.
- Inner class: tied to an outer object (
outer.new Inner()), and sees its fields. - Local and anonymous classes live inside a method. Since Java 8 they (and lambdas) can use local variables that are effectively final; before, those variables had to be declared
final. - Lambdas (Java 8) replace one-method anonymous classes. Inside a lambda,
thismeans the enclosing object. - Java 16 let inner classes declare static members, even
main, and allowed local records, enums and interfaces.
Part IV Data and Memory
- An array has a fixed length, set at creation. Elements get default values.
arr.lengthis a field. - A 2-D array is an array of arrays; rows can have different lengths.
- Arrays are covariant: a
String[]is anObject[], and storing the wrong type fails at run time withArrayStoreException. Generic collections catch it at compile time. Arrays.asListis fixed-size;List.of(Java 9) is unmodifiable and rejectsnull.- Java 21 sequenced collections added
getFirst(),getLast(),addFirst()andreversed()to lists, ordered sets and ordered maps.
12 Garbage Collection and Memory
- An object becomes eligible for collection when no chain of references from a GC root (live stack variables, static fields, active threads) reaches it. Cycles don't keep objects alive.
System.gc()is only a request.finalize()was deprecated in Java 9 and marked for removal in Java 18. Usetry-with-resources, andCleaner(Java 9) as a safety net.- Collectors: Parallel was the server default in Java 7; G1 became the default in Java 9; ZGC and Shenandoah became production-ready in Java 15; CMS was removed in Java 14.
- Java 27 makes G1 the default everywhere and turns on compact object headers by default.
Part V Errors and Text
13 Exceptions
Throwablesplits intoError(don't catch) andException.RuntimeExceptionand its subclasses are unchecked; other exceptions are checked and must be caught or declared withthrows.- Catch blocks are tried top to bottom, so put subclasses before their parents.
finallyalways runs, except when the JVM stops (System.exit, a crash). Areturninfinallyoverrides thetry's return.- Java 7: try-with-resources, multi-catch and suppressed exceptions. Java 9: try-with-resources on an existing effectively final variable.
- Java 14/15: helpful
NullPointerExceptionmessages name the exactnullexpression.
Stringis immutable: methods likeconcatandtoUpperCasereturn a new string. UseStringBuilder(Java 5) to build text in loops.- String literals are pooled and shared.
new String("x")always creates a new object. Compare withequals(), never==. - Java 7 moved the pool from PermGen to the heap. Java 9 introduced compact strings and faster
+concatenation. - New methods:
String.join(8),isBlank,strip,repeat,lines(11),formatted(15). - Text blocks (Java 15) are multi-line literals with
""". String templates were previewed in Java 21–22 and withdrawn.
- Each primitive has a wrapper class:
Integer,Long,Double,Character,Boolean… Collections and generics need objects, so they hold wrappers. - Autoboxing (Java 5) converts between them automatically:
Integer i = 10;callsInteger.valueOf(10). Integer.valueOfcaches -128 to 127, so==happens to work for small values and fails for larger ones. Always compare wrappers withequals.- Unboxing
nullthrowsNullPointerException.Long.valueOf(1).equals(1)isfalse. new Integer(10)was deprecated in Java 9, marked for removal in Java 16, and reprieved in Java 25: still deprecated, but no longer scheduled for removal. UseInteger.valueOfor autoboxing either way.
Part VI Modern Java
- A stream pipeline is source → intermediate operations → one terminal operation:
list.stream().filter(…).map(…).toList()(Java 8;toList()Java 16). - Streams are lazy: nothing runs until the terminal operation, and elements flow through one at a time, so
findFirstcan stop early. - Collectors group, partition, count and join:
groupingBy,partitioningBy,joining. Optional(Java 8) represents "maybe a value." Use it for return types, not fields or parameters.- Later additions:
takeWhile,dropWhile, boundediterate(9),teeing(12),mapMulti(16), and gatherers (24) for custom intermediate operations.
- Java 7's
Dateis mutable,Calendarmonths start at 0,Date.getYear()counts from 1900, andSimpleDateFormatisn't thread-safe. - Java 8's
java.time(JSR 310) has immutable, thread-safe types:LocalDate,LocalTime,LocalDateTime,ZonedDateTime,Instant,Duration,Period. - Pick by meaning: a birthday is a
LocalDate, a meeting is aZonedDateTime, a log timestamp is anInstant. ZonedDateTimehandles daylight saving time correctly.DateTimeFormatteris immutable and safe to share.
18 Concurrency
- Two threads updating the same variable can lose updates. Fix it with
synchronized, locks, or atomic classes such asAtomicInteger(Java 5). - Don't manage threads by hand: use an
ExecutorService(Java 5). Combine async results withCompletableFuture(Java 8). - Virtual threads (Java 21) are cheap threads managed by the JVM. Millions can block on I/O at once. Use one per task:
Executors.newVirtualThreadPerTaskExecutor(). - Scoped values (Java 25) share per-call context safely; they're a better
ThreadLocal. - Structured concurrency treats related tasks as one unit. It's still a preview in Java 27.
- Records (Java 16): immutable data carriers with generated constructor, accessors,
equals,hashCodeandtoString. Validate in a compact constructor. - Sealed interfaces (Java 17): a closed set of alternatives, such as
Card,UpiorCash. - Record patterns (Java 21) deconstruct records in
switchandinstanceof:case Card(String last4, long cents). - Over a sealed type,
switchis exhaustive: nodefault, and adding a new alternative becomes a compile error everywhere it's unhandled. _(Java 22) ignores parts you don't need. Primitive patterns are still in preview in Java 27.
- HTTP Client (Java 11) replaced
HttpURLConnection; Java 26 added HTTP/3. jwebserverandSimpleFileServer(Java 18) serve static files for testing.jdepsfinds the modules your code needs;jlink(Java 9) builds a runtime with only those;jpackage(Java 16) makes native installers.- JDK Flight Recorder became free and open source in Java 11: low-overhead production profiling.
- Markdown doc comments (
///, Java 23),@snippet(Java 18), and ahead-of-time caches (Java 24–25) round out the toolbox.