Skip to contents
OpenLearningTHE STUDY LIBRARY

In depth study guide · Edition 2026.12

Java: From Source Code to Reliable Applications

An illustrated Java 17 foundation with clear mental models, worked programs, practice, and a complete tested ledger

An original in-depth guide to Java execution, values, control flow, methods, collections, objects, interfaces, equality, generics, errors, streams, testing, concurrency, and a command-line project.

16 chapters12 diagrams32 practice tasks

Before you begin

How to use this guide

First-time Java learners and developers moving from a dynamically typed language who want to understand the rules behind the syntax.

Helpful background

What you will be able to do

A useful study rhythm

Read the explanation, close the book, and draw or explain the idea from memory. Predict each example before running or tracing it. Attempt the chapter exercises, compare your reasoning with the solution manual, and return to the source when an assumption changes.

For a first pass, follow the chapter order. For revision, use the contents and glossary. Assessment answers and exercise solutions are separated from the questions so you can retrieve an answer before seeing it. Internal links and bookmarks work in most PDF readers; the printed page number helps when reading on paper.

Scope and assumptions

Core explanations and original diagrams are available offline. External books, videos, and documentation remain at their publishers’ sites and may require an internet connection or a separate account.

Chapter 01

The Java toolchain without mystery

Know what compiles, what launches, and which version an example targets.

By the end of this chapter
  • Separate compilation from execution
  • Run a Java 17-targeted program
  • Identify the layer of a startup failure

What the tools actually do

Java source is text that a compiler checks and translates into class files containing bytecode and related information. A Java Virtual Machine loads and executes those classes. The Java Development Kit includes development tools such as javac as well as a runtime. Your editor helps write source, but it does not remove the distinction between a compilation error and a failure after the program starts. Identifying that stage makes troubleshooting much faster.

Start by checking java -version and javac -version in the same terminal. If one command works and the other does not, the installed or selected toolchain may be incomplete or inconsistent. An IDE can select a different JDK from the terminal, so record which one launches the project. This book targets Java 17 without preview features, even when you use a newer JDK capable of compiling for that target.

Go deeper: [2] Java 17 javac command · [1] Dev.java learning index

A complete first program

Save the example as Hello.java because the public top-level class is named Hello. Compile it with javac --release 17 Hello.java, then launch it with java Hello. The launcher receives a class name in this form, not Hello.class. The main method is the conventional entry point used by these examples. Its arguments parameter can receive command-line strings; it does not automatically parse them into domain values.

Read the first example in order: a whole-number value is stored, multiplication computes the total, and println displays text containing the result. Braces delimit blocks and semicolons terminate many statements. Consistent formatting is not optional decoration; it makes the structure readable even though Java does not use indentation as block syntax. Keep the first program small enough to explain every symbol before copying a larger application.

Compile: javac --release 17 Hello.java; run: java Hello java · Hello.java
public class Hello {
    public static void main(String[] args) {
        int sessions = 3;
        int minutes = sessions * 25;
        System.out.println("Study minutes: " + minutes);
    }
}
Expected result
Study minutes: 75

Go deeper: [2] Java 17 javac command · [3] Java Language Specification, JavaSE 17 edition

A repeatable investigation loop

Predict the output, compile, run and compare. If compilation fails, read the first useful diagnostic and inspect the named line; a missing brace earlier can make a later line look invalid. If execution fails, distinguish a launcher/classpath problem from an exception thrown inside the application. Repeatedly changing unrelated settings can turn one clear failure into several confusing ones. Keep the smallest source and command that reproduce the issue.

A source-file launch mode also exists in supported JDKs, but learning the explicit compile-and-launch sequence makes class files and tool versions visible. Larger projects add packages, dependency resolution and build tools; those are organization layers over the same underlying idea. Do not install a framework merely to print a value. Build a reliable feedback loop first, then add tools when the project has a concrete reason for them.

Source, compiler, and runtimeSource code is checked by javac, which writes class files. The java launcher starts a JVM that loads those files and executes the entry point.Hello.javaHuman-readable sourcejavac --release 17Check syntax, types and target APIsHello.classBytecode and class informationjava HelloStart the runtime and execute main
Source, compiler, and runtime. Source code is checked by javac, which writes class files. The java launcher starts a JVM that loads those files and executes the entry point.Scroll horizontally to read the full diagram on a small screen.

Go deeper: [2] Java 17 javac command · [1] Dev.java learning index

Keep these ideas

  • Compilation checks source and writes class files.
  • The JVM executes loaded classes; the launcher and compiler have different roles.
  • Record the language/API target and the actual toolchain used.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

1.1 · Practice task

Why does java Hello.class usually fail for this conventional launch command?

Hint: The launcher is receiving a name, not a filesystem extension.

Read the worked solution

1.2 · Practice task

Your IDE succeeds while javac in Terminal fails on a supported feature. What information should you compare?

Hint: Each environment can choose a different JDK.

Read the worked solution

Chapter 02

Types, references, arithmetic, and null

Understand what variables can contain and which numeric assumptions must be explicit.

By the end of this chapter
  • Trace copied references
  • Recognize integer overflow and division
  • Handle absence and parsing deliberately

Primitive values and object references

Java variables have declared types. Primitive types include boolean and the numeric primitives; a primitive variable contains a primitive value. A reference variable contains a reference to an object or null. Assigning one reference variable to another copies the reference value, not the entire object. Both variables can therefore identify the same mutable object. This distinction explains parameter behavior, collection contents and many surprising state changes.

A local variable must be definitely assigned before it is read. Fields and array elements have default initialization rules, but relying on those defaults can still obscure intent. The var syntax can infer a local variable’s static type from its initializer; it does not make the variable dynamically typed. Choose inference only when the resulting type is clear to a reader who is not asking the IDE for help every few seconds.

Go deeper: [4] Java 17 specification: types, values and variables

Numeric operations need a policy

Integral types such as int and long have fixed ranges. Ordinary integer arithmetic can overflow without throwing an exception, so choose an appropriate range and use checked arithmetic such as Math.addExact where an overflow must be reported. Integer division discards the fractional part toward zero. Casting the already-divided result to double does not recover a lost fraction; at least one operand must participate in floating-point division before the operation occurs.

Floating-point numbers approximate many decimal values. That can be appropriate for measurements, but financial calculations need a domain policy for units and rounding. BigDecimal supports decimal arithmetic, yet constructing one from an already-approximate double can preserve an unexpected binary approximation. Construct decimal input from text or use integral minor units where suitable, and specify rounding when an exact quotient is not representable.

Compare division before and after conversion java · ValuesDemo.java
public class ValuesDemo {
    public static void main(String[] args) {
        int total = 7;
        int count = 2;
        System.out.println(total / count);
        System.out.println((double) total / count);
        System.out.println((double) (total / count));
        System.out.println(Integer.MAX_VALUE + 1);
    }
}
Expected result
3
3.5
3.0
-2147483648

Go deeper: [4] Java 17 specification: types, values and variables · [17] Java 17 BigDecimal API · [15] Java 17 Math API

Null and conversions at a boundary

null means a reference does not identify an object. Calling an instance method through a null reference throws NullPointerException. Decide whether absence is permitted in each API; do not spread unexplained nulls through a program and hope callers remember every case. Objects.requireNonNull can fail early for a required collaborator, while Optional can model certain return-value absences. Neither replaces a clear contract about missing information.

Conversion is also a contract. Parsing text as an integer can fail because of syntax or range, and narrowing a number can lose information. Avoid sprinkling casts over a compile error until it disappears. First ask what values are permitted and which representation expresses them. The compiler prevents many incompatible operations, but it cannot infer that a duration must be nonnegative or that a user-entered quantity is within an application’s practical limit.

Go deeper: [13] Java 17 Objects API · [4] Java 17 specification: types, values and variables

Keep these ideas

  • Reference assignment shares an object unless a separate copy is made.
  • Fixed-width arithmetic and decimal approximation require deliberate handling.
  • Static types do not infer business ranges or missing-value rules.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

2.1 · Practice task

Why does (double)(7 / 2) produce 3.0 rather than 3.5?

Hint: The division happens before the outer cast.

Read the worked solution

2.2 · Practice task

A duration field uses int. Does the type alone prevent negative minutes or overflow in a long report total?

Hint: Representation rules and domain rules are different.

Read the worked solution

Chapter 03

Text, Unicode, equality, and parsing

Treat strings as immutable text and validate conversion at the program boundary.

By the end of this chapter
  • Compare contents correctly
  • Explain UTF-16 length limits
  • Separate parsing from domain validation

Strings are immutable values

A String represents text and cannot be changed in place. Methods that appear to modify it return a new string, so retain that result when needed. Concatenating a few readable pieces is fine; repeatedly appending in a large loop may justify StringBuilder. The important first question is whether you are creating a new value or changing an existing mutable object. That same distinction appears throughout Java collections and domain design.

Use equals to compare string contents. The == operator compares reference identity for reference types, so two independently created strings with the same text need not compare true with ==. String interning can make an incorrect identity comparison appear to work in a small example. Do not turn an implementation optimization into an application rule. For nullable text, decide a null policy or use a suitable null-safe comparison helper.

Go deeper: [12] Java 17 String API · [13] Java 17 Objects API

Characters, Unicode, and normalization

Java char is a UTF-16 code unit, not a universal visible-character unit. Some Unicode code points use two code units, and some visible symbols combine several code points. String.length therefore counts code units. Code-point APIs help when your operation is defined in terms of code points, but even that is different from counting user-perceived characters. Display width and internationalized editing require a more careful text model than an English-only index example.

Normalization rules must follow the application. Trimming surrounding whitespace may be reasonable for a topic label, while changing a case-sensitive password or filesystem path can be incorrect. When case conversion is intended to be locale-independent, choose that explicitly, for example with Locale.ROOT for a machine-oriented key. Preserve the original display text separately when user presentation matters. Text equality is a domain question before it is a method call.

Text crosses several boundariesThe original text can be retained while a normalized form is checked, parsed, validated and finally formatted for display. Each boundary answers a different question.Receive textArguments or file fieldsNormalizeApply only permitted transformationsParseRecognize a numeric representationValidateEnforce the domain rangeFormatPresent the accepted value
Text crosses several boundaries. The original text can be retained while a normalized form is checked, parsed, validated and finally formatted for display. Each boundary answers a different question.Scroll horizontally to read the full diagram on a small screen.

Go deeper: [12] Java 17 String API · [18] Java 17 Locale API

Parsing is not evaluation

Command-line arguments and file fields arrive as text. Integer.parseInt parses an integer representation and reports NumberFormatException for invalid or out-of-range input. It does not establish that the number is a valid age, duration or port for your application. Apply the relevant range rule after parsing, and give a message that tells the person which field needs repair. Avoid silently deleting unexpected characters to make a value parse.

Formatting is the final presentation step. A nicely rounded string does not retroactively change arithmetic performed with a floating-point value. Keep raw input, normalized text, parsed values and displayed output conceptually separate so mistakes can be traced to the right stage. Test empty text, whitespace, signs, non-ASCII letters and values just outside the intended range rather than only the happy-path word Java.

Content equality and explicit text conversion java · TextDemo.java
import java.util.Locale;

public class TextDemo {
    public static void main(String[] args) {
        String first = new String("Java");
        String second = new String("Java");
        System.out.println(first == second);
        System.out.println(first.equals(second));
        String key = "  JAVA  ".strip().toLowerCase(Locale.ROOT);
        int minutes = Integer.parseInt("25");
        System.out.println(key + ": " + minutes);
    }
}
Expected result
false
true
java: 25

Go deeper: [16] Java 17 Integer API · [12] Java 17 String API

Keep these ideas

  • String contents are compared with equals.
  • UTF-16 code units, code points and visible symbols differ.
  • Parsing and formatting do not replace domain validation.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

3.1 · Practice task

Two Strings both display Java. Why is == the wrong general content comparison?

Hint: The variables hold references.

Read the worked solution

3.2 · Practice task

A field accepts 0 through 600 minutes. List the checks after receiving a text argument.

Hint: Whitespace handling, syntax and range are separate steps.

Read the worked solution

Chapter 04

Conditions, loops, and boundaries

Make repeated work and decision rules easy to trace.

By the end of this chapter
  • Test inclusive boundaries
  • State a loop invariant
  • Choose element or index traversal

Branches express a partition of cases

An if statement selects behavior based on a Boolean condition. Use braces consistently even for a one-line branch so later edits cannot accidentally leave a statement outside the intended block. Logical and and or short-circuit: the right operand is evaluated only when needed to determine the Boolean result. That can protect a null-sensitive operation, but it does not make a complicated mixed condition easy to review. Name a meaningful predicate when it carries a domain idea.

For numeric thresholds, decide inclusivity before writing the comparison. A score category with a boundary at 60 needs tests at 59,60 and 61, as well as rejection tests outside the overall allowed range. An else-if chain chooses the first matching branch, so order matters when conditions overlap. Independent if statements serve a different purpose when several actions may all need to run.

Go deeper: [7] Java 17 specification: statements · [8] Java 17 specification: expressions

Loops and state invariants

A loop changes state through repeated steps. A classic for loop makes initialization, continuation and update visible; an enhanced for loop traverses array or Iterable elements without exposing an index. Prefer the enhanced form when the elements are all you need. Use an index when position itself has meaning, and remember that valid array indices run from zero through length minus one. The final endpoint is excluded in the conventional loop condition.

State an invariant to explain correctness. In a running total, the accumulated number equals the sum of accepted elements already processed. The empty case uses the initial accumulator and never enters the body. In a while loop, identify what makes progress toward stopping. A retry loop without a changing state or a bound can run forever when its external condition never improves.

Trace a filtered running total java · FlowDemo.java
public class FlowDemo {
    public static void main(String[] args) {
        int[] values = {25, -2, 40, 0};
        int total = 0;
        for (int value : values) {
            if (value < 0) {
                continue;
            }
            total += value;
        }
        System.out.println(total);
    }
}
Expected result
65

Go deeper: [7] Java 17 specification: statements

Clarity before compactness

break exits the nearest enclosing loop or applicable labeled statement, while continue moves to the next iteration of its target loop. Both can clarify exceptional cases, but a body with many scattered exits becomes difficult to trace. A small helper method can sometimes express a complex eligibility rule more cleanly than nested loops and flags. Do not replace clear control flow with a stream pipeline merely because the syntax looks more modern.

Avoid structural collection modification during enhanced iteration unless the chosen iterator contract permits the operation you use. For filtering, build a new result or use the collection’s documented removal operation. Test adjacent rejected values because they often reveal skipped-element bugs. Count nested-loop work as well: visiting every pair of two growing groups can multiply cost even if each individual statement seems cheap.

Loop reasoning in four statesA loop begins with a defined initial value, checks whether work remains, performs one step preserving the invariant and updates progress until termination.InitializeSet the accumulator and traversal stateCheckDetermine whether another item remainsProcessPreserve the invariant for one more itemAdvance or finishMove toward the end; expose the final result
Loop reasoning in four states. A loop begins with a defined initial value, checks whether work remains, performs one step preserving the invariant and updates progress until termination.Scroll horizontally to read the full diagram on a small screen.

Go deeper: [19] Java 17 List API · [20] Java 17 ArrayList API

Keep these ideas

  • Braces and named predicates make decisions reviewable.
  • The loop invariant explains accumulated state.
  • Validating an input range and classifying accepted values are separate operations.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

4.1 · Practice task

Why does i <= values.length fail when used to access values[i]?

Hint: The length is a count, not the final valid index.

Read the worked solution

4.2 · Practice task

Why should a score classifier reject 200 before applying score >= 90?

Hint: Classification assumes input belongs to the accepted domain.

Read the worked solution

Chapter 05

Methods, contracts, and pass-by-value

Separate reusable operations and explain how calls affect state.

By the end of this chapter
  • Write a behavioral contract
  • Trace parameter mutation and rebinding
  • Keep decomposition tied to responsibilities

A method is an operation with a contract

A method declares accepted parameter types and a return type, but those declarations are only part of its contract. Explain permitted ranges, nullability, state changes and reported failures. A method named totalMinutes should say whether it changes the supplied collection, how it treats empty input and whether overflow is checked. A caller should not have to inspect every line of the method to know how to use it safely.

A static method belongs to the class rather than to one instance and is a reasonable starting point for a pure calculation. An instance method can operate on a receiver’s state. Avoid using static mutable fields as a shortcut for passing results between methods: that hides dependencies and lets earlier calls change later behavior. Prefer explicit parameters and return values until shared state is truly part of the design.

Go deeper: [5] Java 17 specification: classes

Java passes values, including reference values

Java is pass-by-value. A primitive argument supplies a copy of its primitive value to the parameter. An object argument supplies a copy of its reference value. Reassigning that parameter does not reassign the caller’s variable, but mutating the shared object’s state can be observed by the caller. Calling this pass-by-reference obscures the important fact that the method cannot swap the caller’s reference variable merely by assigning its own parameter.

Use a small trace with one list and two names to make the behavior concrete. The method can append to the list both references identify, then rebind its local parameter to a new list. The append remains visible through the caller’s reference; the local rebinding does not. If an API must leave input unchanged, avoid mutation or create a documented defensive copy with the appropriate depth.

Mutation and local rebinding are different java · CallsDemo.java
import java.util.ArrayList;
import java.util.List;

public class CallsDemo {
    static void change(List<String> topics) {
        topics.add("Java");
        topics = new ArrayList<>();
        topics.add("Rust");
    }
    public static void main(String[] args) {
        List<String> topics = new ArrayList<>();
        topics.add("Python");
        change(topics);
        System.out.println(topics);
    }
}
Expected result
[Python, Java]

Go deeper: [8] Java 17 specification: expressions · [20] Java 17 ArrayList API

Overloading and useful decomposition

Overloading lets methods share a name with different parameter lists. Resolution depends on compile-time types and the applicable overload rules, which can become surprising when boxing, widening and null arguments interact. For beginner APIs, prefer a few clear signatures over a clever maze of nearly equivalent overloads. Return type alone cannot distinguish overloads, because a caller might use the invocation without assigning its result.

Decompose a program around stable responsibilities: parsing, validation, calculation and display. A very long method with unrelated Boolean switches often signals that those responsibilities have been mixed together. Write the simplest contract first, then add a parameter only when it represents a real input. Test the operation without interactive input or real files when those are not part of its meaning. That makes defects easier to localize and later interfaces easier to add.

Go deeper: [5] Java 17 specification: classes · [8] Java 17 specification: expressions

Keep these ideas

  • A signature needs a behavioral contract around it.
  • Java passes primitive values and reference values by value.
  • Small operations with explicit inputs reduce hidden coupling.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

5.1 · Practice task

Can a method swap two caller reference variables by assigning its own parameters? Why?

Hint: The parameter receives a copied reference value.

Read the worked solution

5.2 · Practice task

A sum method both asks for keyboard input and prints its answer. How would you make its calculation reusable?

Hint: Move environment-specific work to the boundary.

Read the worked solution

Chapter 06

Arrays, lists, sets, and maps

Select data structures by their contracts, including order and mutability.

By the end of this chapter
  • Choose an abstraction for a task
  • Recognize copies and backed views
  • Separate aggregation from ordering

Choose by the question you need to answer

An array has a fixed length and indexed elements of one declared component type. A List represents an ordered sequence with a size that may vary depending on the implementation. A Set represents distinct elements, and a Map associates keys with values. Choose the abstraction by the domain question: position, membership or keyed lookup. Turning a reading history into a set changes its meaning by discarding duplicate entries.

Generic collections use reference types, so List<Integer> uses wrapper objects rather than a primitive int element type. Boxing and unboxing are convenient conversions but can matter for memory, performance and null behavior. Unboxing a null Integer fails. Do not memorize collection names as if one implementation were always fastest; understand the operations your workload performs and the ordering or mutation contract the application needs.

Three collection questionsA list answers position-and-order questions, a set answers distinct membership questions, and a map answers key-to-value association questions. None replaces all the others.ListOrdered occurrences;duplicates can matterSetDistinct membership underequalityMapOne associated value per key
Three collection questions. A list answers position-and-order questions, a set answers distinct membership questions, and a map answers key-to-value association questions. None replaces all the others.Scroll horizontally to read the full diagram on a small screen.

Go deeper: [19] Java 17 List API · [21] Java 17 Set API · [22] Java 17 HashMap API

Mutability and views require attention

ArrayList is a common resizable-array implementation with efficient indexed access and amortized append behavior. Removing near the front shifts later elements. A list created by List.of is unmodifiable and rejects null elements. Arrays.asList returns a fixed-size view backed by the array rather than an ordinary independent growable ArrayList. Those similar-looking creation methods therefore support different operations and sharing behavior.

An unmodifiable outer list can still contain references to mutable objects. Likewise, a view can reflect changes made through another reference. Document whether an API returns a live view, a defensive copy or an immutable value structure. The word copy should always prompt the next question: how deep is it? A clear ownership policy prevents more confusion than adding extra collection conversions until one test stops failing.

Go deeper: [20] Java 17 ArrayList API · [19] Java 17 List API · [23] Java 17 Arrays API

Count with a mapping, order for display

A map is a natural representation for accumulating minutes by title. Each accepted record identifies a key and contributes to its total. Decide whether a repeated key combines values, replaces an earlier value or causes an error. HashMap does not promise a display order, so a deterministic report must sort keys or use a structure with the required ordering contract. Ordering is separate from the arithmetic.

Test empty collections, repeated keys, missing keys and null values where the selected implementation permits them. Avoid assuming that every Map implementation has the same null policy or iteration behavior. Use interface types in method contracts when callers only need interface operations, and select a concrete implementation where you create the value. That keeps the contract tied to required behavior instead of an incidental implementation choice.

Accumulate values and sort only for presentation java · CollectionsDemo.java
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

public class CollectionsDemo {
    public static void main(String[] args) {
        Map<String, Integer> totals = new HashMap<>();
        totals.merge("Python", 25, Integer::sum);
        totals.merge("Java", 20, Integer::sum);
        totals.merge("Python", 35, Integer::sum);
        System.out.println(new TreeMap<>(totals));
    }
}
Expected result
{Java=20, Python=60}

Go deeper: [22] Java 17 HashMap API · [19] Java 17 List API

Keep these ideas

  • Different collections preserve different information.
  • Factory methods, views and copies have different mutation contracts.
  • Deterministic presentation needs an explicit order.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

6.1 · Practice task

Why can List.of("Java").add("Python") fail even though the variable type is List<String>?

Hint: The interface does not promise that every implementation permits mutation.

Read the worked solution

6.2 · Practice task

Why should a HashMap-based report sort its keys before asserting exact output text?

Hint: Lookup semantics do not define display order.

Read the worked solution

Chapter 07

Classes, records, and valid states

Use encapsulation to protect meaning rather than to decorate fields.

By the end of this chapter
  • Establish invariants in construction
  • Explain final and shallow immutability
  • Avoid leaking mutable internals

Put rules beside state

A class can combine state with operations that preserve its rules. A reading session may require a nonblank title and a nonnegative duration. A constructor establishes those invariants, and every later state-changing method must preserve them. Declaring fields private prevents ordinary outside source code from accessing them directly, but encapsulation is more than mechanically generating getters and setters. A setter that accepts any value can simply move invalid mutation behind a method name.

Prefer meaningful operations such as recordSession or reserveSeat over exposing every internal data structure. The method can validate the request, perform the state change atomically at the domain level where appropriate, and return a useful result. Do not return a mutable internal list if callers must not alter it. A getter that leaks a live structure can bypass every carefully written validation method.

An invariant at every state boundaryConstruction establishes a valid state, public operations check requests and the resulting state continues to satisfy the same rules. Exposing raw mutation can break this route.Construction inputsUntrusted or unchecked valuesValidateReject blank titles and invalid durationsValid objectThe invariant is establishedPublic operationPreserve the rule on every change
An invariant at every state boundary. Construction establishes a valid state, public operations check requests and the resulting state continues to satisfy the same rules. Exposing raw mutation can break this route.Scroll horizontally to read the full diagram on a small screen.

Go deeper: [5] Java 17 specification: classes · [19] Java 17 List API

Construction and immutable components

A constructor has the class name and no declared return type. It prepares a new instance and should reject invalid inputs before exposing an invalid object to callers. Use Objects.requireNonNull for required references and domain-specific checks for their contents. A final field cannot be reassigned after permitted initialization, but an object referenced by that field can still be mutable. Immutability needs the whole reachable state policy, not only a keyword.

Records, available in Java 17, are useful for transparent data carriers with generated accessors, equality and representation. A compact constructor can normalize or validate components. Record components are final, yet a record holding a mutable list is not deeply immutable. Consider defensive copies and immutable component types when that is the intended contract. Do not use a record merely to avoid thinking about invariants or the meaning of equality.

A validated Java 17 record java · ObjectsDemo.java
import java.util.Objects;

public class ObjectsDemo {
    record Session(String title, int minutes) {
        Session {
            title = Objects.requireNonNull(title, "title").strip();
            if (title.isEmpty() || minutes < 0) {
                throw new IllegalArgumentException("invalid session");
            }
        }
    }
    public static void main(String[] args) {
        Session session = new Session(" Java ", 25);
        System.out.println(session.title() + ": " + session.minutes());
    }
}
Expected result
Java: 25

Go deeper: [5] Java 17 specification: classes · [6] Java 17 specification: record classes · [13] Java 17 Objects API

Identity, lifecycle, and simplicity

Some objects represent values, such as a duration and title pair; others represent entities whose identity persists while state changes, such as a library account. That distinction affects equality and update design. A class is not automatically an entity, and a database identifier is not required for every tiny object. Choose the model that makes the application’s questions easiest to answer correctly.

Keep construction side effects modest. Opening network connections or writing files inside every constructor can make object creation unexpectedly slow and hard to test. A factory or explicit application operation may better express work that can fail for environmental reasons. Start with a small validated object, show successful and rejected construction, then add behavior when a genuine state transition appears. A large inheritance diagram is not evidence that the domain model is useful.

Go deeper: [5] Java 17 specification: classes · [13] Java 17 Objects API

Keep these ideas

  • Encapsulation protects invariants through meaningful operations.
  • Final references and deeply immutable values are not the same guarantee.
  • Records reduce boilerplate but still need domain validation.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

7.1 · Practice task

A field is private final List<String>. Does that prove callers can never observe its contents changing?

Hint: The field reference and the list object are different state.

Read the worked solution

7.2 · Practice task

Why might a setMinutes method that accepts any int weaken encapsulation?

Hint: A method boundary should preserve the object’s rules.

Read the worked solution

Chapter 08

Interfaces, composition, and substitution

Model useful capabilities and keep implementation choices behind clear contracts.

By the end of this chapter
  • Distinguish composition and inheritance
  • Explain dynamic dispatch
  • Check behavioral substitutability

Interfaces describe capabilities

An interface describes a capability that several implementations can provide. A report formatter might promise to turn a validated summary into text without specifying whether it uses plain text or another representation. The caller depends on the operation it needs, and implementations supply compatible behavior. An interface is valuable when that boundary is meaningful; creating one for every class by habit adds names without necessarily reducing coupling.

A class can implement several interfaces, allowing different capabilities without forcing a single inheritance tree to describe every relationship. Use small contracts that explain accepted inputs, output meaning and failure conditions. Matching a method signature is necessary but not sufficient for substitution: an implementation that unexpectedly mutates input or refuses previously valid values can break a caller even though the compiler accepts the type relationship.

Go deeper: [9] Java 17 specification: interfaces · [5] Java 17 specification: classes

Composition versus inheritance

Composition gives an object collaborators and delegates selected work to them. A report service can receive a Formatter and keep record aggregation separate from presentation. That makes a test double or alternate formatter easy to supply without changing the aggregation logic. The dependency is explicit, and each component’s responsibility can remain small enough to explain in one sentence.

Inheritance says that a subclass is usable through its superclass contract and can customize permitted behavior. It is not simply a mechanism for stealing a few useful methods. A subclass that needs to disable most inherited operations may be signaling that the relationship is wrong. Prefer composition when you need one object’s behavior as a component, and use inheritance when a stable behavioral subtype relationship genuinely helps callers.

A stable capability boundaryThe report service calls an interface contract. Different formatters implement that capability while the aggregation logic remains independent of their concrete class names.Report serviceNeeds a formatting capabilityFormatter interfaceformat(title, minutes) contractPlain formatterOne compatible implementationAlternative formatterAnother implementation when required
A stable capability boundary. The report service calls an interface contract. Different formatters implement that capability while the aggregation logic remains independent of their concrete class names.Scroll horizontally to read the full diagram on a small screen.

Go deeper: [9] Java 17 specification: interfaces · [5] Java 17 specification: classes

Dynamic dispatch and a stable boundary

For an overridable instance method, the implementation selected at runtime depends on the actual receiver object. This is dynamic dispatch. It differs from overload resolution, which selects among signatures using compile-time information. Static methods are not dynamically overridden in the same way, so avoid treating all methods with the same name as interchangeable dispatch mechanisms. Use the Override annotation to let the compiler check an intended override.

The example keeps formatting behind a small interface. The reporting code only knows how to call format, so changing the implementation does not require an if statement for every formatter class. That does not mean you should invent ten implementations in advance. Start with the needed boundary, test its behavioral expectations, and add another implementation when the application has a concrete use for it.

Inject a capability instead of selecting concrete classes java · InterfaceDemo.java
public class InterfaceDemo {
    interface Formatter {
        String format(String title, int minutes);
    }
    static final class PlainFormatter implements Formatter {
        @Override
        public String format(String title, int minutes) {
            return title + ": " + minutes + " minutes";
        }
    }
    static String report(Formatter formatter) {
        return formatter.format("Java", 25);
    }
    public static void main(String[] args) {
        System.out.println(report(new PlainFormatter()));
    }
}
Expected result
Java: 25 minutes

Go deeper: [9] Java 17 specification: interfaces · [8] Java 17 specification: expressions

Keep these ideas

  • Interfaces expose capabilities and their behavioral expectations.
  • Composition makes collaborators explicit and replaceable.
  • Dynamic dispatch chooses an overridden implementation from the receiver.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

8.1 · Practice task

A subclass throws UnsupportedOperationException for most operations that its superclass promises. What design question should you ask?

Hint: Type compatibility alone does not prove a useful behavioral relationship.

Read the worked solution

8.2 · Practice task

How does passing a Formatter help test a report without checking concrete class names?

Hint: The report only needs one capability.

Read the worked solution

Chapter 09

Equality, hashing, and stable keys

Define logical sameness before placing your objects in collections.

By the end of this chapter
  • Distinguish identity and value equality
  • Preserve the hash contract
  • Avoid mutable key state

Identity and logical equality are different

Two variables may identify the same object, or they may identify different objects that your domain considers equivalent. The == operator checks reference identity for objects; equals expresses logical equality when the class provides an appropriate implementation. Object’s default equals uses identity. A value-oriented type usually needs equality based on its relevant components, while an entity may define equality through a stable identifier. Decide the meaning before generating methods.

A correct equals implementation follows a contract including reflexivity, symmetry, transitivity and consistency while the relevant state is unchanged. It must return false for null. Violating those rules makes ordinary collection behavior confusing because a lookup can depend on which comparison direction or sequence of operations happens to occur. Equality is a domain policy with mathematical obligations, not just a convenient way to make one test pass.

Go deeper: [14] Java 17 Object API · [13] Java 17 Objects API

Hashing must agree with equality

Hash-based collections use a hash value to narrow candidate locations and equality to distinguish matching keys. Equal objects must have equal hash codes. Unequal objects may share a hash code, so a hash is not a unique identifier and must not be treated as a secure fingerprint. When you override equals, implement the corresponding hashCode policy using the same stable equality-relevant state.

Do not mutate equality-relevant key state while an object is stored in a HashMap or HashSet. A later lookup may search using a different hash and fail to find an entry that is still present. Prefer immutable value keys or stable identifiers. Also distinguish reference aliasing from equality: creating a new key object with the same logical value should still find an equal key if the contract is designed for value lookup.

Hash lookup is a two-part contractA stable key produces a hash used to select candidates. Equality then identifies the matching logical key; collisions do not establish equality.Lookup keyA value with stable equality-relevant statehashCodeNarrow candidate locationsequalsIdentify a logically equal candidateAssociated valueReturn the matching mapping
Hash lookup is a two-part contract. A stable key produces a hash used to select candidates. Equality then identifies the matching logical key; collisions do not establish equality.Scroll horizontally to read the full diagram on a small screen.

Go deeper: [14] Java 17 Object API · [22] Java 17 HashMap API · [21] Java 17 Set API

A small record key and a numeric caveat

A record provides component-based equals and hashCode methods appropriate for many transparent value carriers. The example uses a stable course key, constructs a separate equal key and retrieves the stored value. That demonstrates why a map is keyed by logical meaning rather than necessarily by one object identity. It does not imply every record is automatically a suitable key; mutable components or a poorly chosen domain representation can still undermine the intended semantics.

Read the equality contract of library classes as well. BigDecimal equals considers both numeric value and scale, while compareTo can consider differently scaled representations numerically equal. Thus 2.0 and 2.00 illustrate that sorted-collection ordering and hash-based equality can answer subtly different questions. Choose a normalization and comparison policy suitable for the domain instead of assuming every numeric-looking class has exactly the same equality rules.

Separate equal keys can find the same map entry java · EqualityDemo.java
import java.util.HashMap;
import java.util.Map;

public class EqualityDemo {
    record CourseKey(String code) {}
    public static void main(String[] args) {
        Map<CourseKey, Integer> minutes = new HashMap<>();
        minutes.put(new CourseKey("java"), 25);
        System.out.println(minutes.get(new CourseKey("java")));
    }
}
Expected result
25

Go deeper: [6] Java 17 specification: record classes · [17] Java 17 BigDecimal API

Keep these ideas

  • Logical equality must obey a stable contract.
  • Equal values need equal hashes; collisions are allowed.
  • Immutable keys make lookup behavior easier to trust.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

9.1 · Practice task

Can two unequal objects have the same hashCode? What must a hash map do next?

Hint: Hashing narrows candidates rather than proving identity.

Read the worked solution

9.2 · Practice task

Why is changing a key’s courseCode after inserting it into a HashMap dangerous?

Hint: Lookup uses the current equality/hash behavior, while insertion happened under the old state.

Read the worked solution

Chapter 10

Generics without incantations

Reason about type relationships by tracing what a method may read and write.

By the end of this chapter
  • Explain invariance
  • Use a bounded reader
  • Avoid raw-type leaks

Generics communicate relationships between types

A generic type expresses relationships that would otherwise require casts and informal comments. List<String> says the list is intended to contain String references, so an attempt to add an Integer is rejected during ordinary type checking. The benefit is not only saving a cast at retrieval; it also states the producer-and-consumer relationship where data enters the collection. Keep that relationship visible in method signatures.

Java generics are invariant: List<Integer> is not a subtype of List<Number>. If it were, code accepting List<Number> could insert a Double into a list that another caller expects to contain only Integer values. This is a type-safety problem even though Integer itself is a subtype of Number. Distinguish a relationship between element types from a relationship between mutable containers of those elements.

Go deeper: [24] Dev.java generics and functional-programming learning route · [4] Java 17 specification: types, values and variables

Wildcards describe permitted use

A parameter such as List<? extends Number> can provide Number values to a reader, but the method cannot safely add an arbitrary Number because the actual element subtype is unknown. A parameter such as List<? super Integer> can accept Integer values, while reads are only safely known as Object without further information. These are use-site constraints, not mysterious spellings to memorize without tracing what an unsafe operation would allow.

A helpful shorthand is producer extends, consumer super, but apply it to the particular method’s perspective. A source that your method reads is producing values for that method. A destination that your method writes is consuming them. If both reading and writing require exactly one relationship, a named type parameter may communicate it better. Start with the least complicated signature that expresses the actual operation.

Read numeric values without claiming you can insert arbitrary numbers java · GenericsDemo.java
import java.util.List;

public class GenericsDemo {
    static double total(List<? extends Number> values) {
        double result = 0;
        for (Number value : values) {
            result += value.doubleValue();
        }
        return result;
    }
    public static void main(String[] args) {
        System.out.println(total(List.of(2, 3)));
        System.out.println(total(List.of(1.5, 2.5)));
    }
}
Expected result
5.0
4.0

Go deeper: [24] Dev.java generics and functional-programming learning route · [3] Java Language Specification, JavaSE 17 edition

Erasure and raw-type escape hatches

Much generic type information is checked at compile time and implemented through erasure; a generic declaration does not mean every type argument is a distinct runtime container class. Avoid raw types such as plain List because they discard useful checking and can allow incompatible values to enter. A later cast failure may then appear far from the original unsafe write, making the defect harder to diagnose.

Some runtime operations have restrictions, such as creating arrays of parameterized types or testing instanceof against a specific non-reifiable type argument. Do not respond to every restriction with an unchecked cast. First reconsider the data representation and whether a simpler collection or helper method expresses the requirement. When advanced interoperability truly needs an unchecked operation, isolate it, document why it is safe and test that boundary rather than spreading warnings across the project.

Go deeper: [4] Java 17 specification: types, values and variables · [24] Dev.java generics and functional-programming learning route

Keep these ideas

  • Generics state relationships where values enter and leave APIs.
  • Mutable generic containers are invariant for a reason.
  • Wildcards express safe use; raw types discard useful evidence.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

10.1 · Practice task

Why cannot a method taking List<? extends Number> safely add a Double?

Hint: The actual list might be a List<Integer>.

Read the worked solution

10.2 · Practice task

A raw List causes a ClassCastException far from where a wrong value was inserted. What is the first design repair?

Hint: Restore the type relationship at the write boundary.

Read the worked solution

Chapter 11

Exceptions, resources, and structured input

Report expected failures honestly and keep file handling separate from domain logic.

By the end of this chapter
  • Explain checked handling rules
  • Use try-with-resources
  • Distinguish format parsing from validation

Failure has a type and a context

Java reports many failures through exceptions. Checked exceptions must be caught or declared by applicable code; unchecked RuntimeException subclasses are not subject to that same compile-time obligation. This distinction is about language handling rules, not a universal ranking of severity or recoverability. An IOException can be an expected missing-file condition, while a NullPointerException often reveals a programming defect that should be fixed rather than hidden.

Catch a failure where you can respond usefully. A command boundary can translate an expected invalid file into a clear diagnostic and a nonzero status. A low-level parser may add a record number while preserving the original cause. Catching Exception and pretending the dataset was empty erases important distinctions and can produce a plausible but false successful report. Keep protected operations narrow enough that an unrelated defect is not mislabeled as bad input.

Go deeper: [10] Java 17 specification: exceptions · [25] Java 17 Files API

Resources have deterministic lifecycles

An open stream, reader or socket owns resources that should be released promptly. try-with-resources closes AutoCloseable resources when the block exits, including when an exception is thrown. Garbage collection manages object memory; it is not a promise that external resources will be released at the time your application needs them. Prefer the lifecycle construct that directly matches the resource contract.

Read and write text with an explicit character encoding when the format defines one. UTF-8 is a common portable choice, but invalid byte sequences and permission failures remain possible. A Path describes a location; it does not prove the file exists or remains unchanged between operations. For untrusted paths or large inputs, add appropriate size, location and concurrency assumptions rather than treating a convenient readAllLines call as a complete security design.

A reader closes even when processing fails java · ResourcesDemo.java
import java.io.BufferedReader;
import java.io.StringReader;
import java.io.IOException;

public class ResourcesDemo {
    public static void main(String[] args) throws IOException {
        String input = "Java\t25\nPython\t35\n";
        int total = 0;
        try (BufferedReader reader = new BufferedReader(new StringReader(input))) {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] fields = line.split("\t", -1);
                total += Integer.parseInt(fields[1]);
            }
        }
        System.out.println(total);
    }
}
Expected result
60

Go deeper: [25] Java 17 Files API · [26] Java 17 AutoCloseable API

Parsing and validation remain separate

A file reader gives you characters or lines, not validated application records. Specify the input format before writing split calls. Real CSV can contain quoted delimiters and newlines, so splitting on commas is not a general CSV parser. This book’s capstone deliberately uses a restricted tab-separated format with an exact header and no embedded tab characters in titles. The restriction is documented and tested instead of being disguised as full CSV support.

For a file update, distinguish complete content generation from replacing an existing destination. Writing directly over a valuable file can leave it truncated if work fails midway. A temporary file and a documented replacement policy can reduce partial-write exposure, while durability, backups and hostile filesystem races need additional treatment. Test missing files, malformed records, encoding problems and destination failures alongside the ordinary successful path.

A trustworthy file boundaryOpening and decoding are environmental steps; parsing establishes syntax and validation establishes domain meaning. Only accepted records reach the calculation.Open resourceA path and permissions may failDecode UTF-8Bytes become text under a declared formatParse record syntaxIdentify fields under a restricted grammarValidate valuesCheck titles, ranges and limitsUse accepted recordsCompute a complete result
A trustworthy file boundary. Opening and decoding are environmental steps; parsing establishes syntax and validation establishes domain meaning. Only accepted records reach the calculation.Scroll horizontally to read the full diagram on a small screen.

Go deeper: [25] Java 17 Files API · [10] Java 17 specification: exceptions

Keep these ideas

  • Catch where a specific useful response is possible.
  • Resource lifetime deserves an explicit scope.
  • A parser recognizes a format; a validator enforces application meaning.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

11.1 · Practice task

Why is catch(Exception e) { return List.of(); } a dangerous file-import fallback?

Hint: A missing dataset and a genuine empty dataset become indistinguishable.

Read the worked solution

11.2 · Practice task

Why does ordinary garbage collection not replace try-with-resources for an open file?

Hint: Memory lifetime and an external resource’s useful lifetime are different.

Read the worked solution

Chapter 12

Lambdas, streams, and deliberate pipelines

Use functional operations when they make data transformations easier to explain.

By the end of this chapter
  • Read a functional interface
  • Trace a lazy pipeline
  • Avoid unsafe external side effects

Behavior as a value

A functional interface has one abstract method and can serve as the target type of a lambda expression. A Predicate<String>, for example, represents a Boolean test of a string. The lambda supplies the behavior while the interface supplies the expected input and result relationship. This can make configurable filtering clearer than creating many tiny named classes, provided the lambda is short enough to understand at the call site.

A captured local variable must be final or effectively final. Capturing a reference does not make the referenced object immutable or thread-safe. A lambda that appends to an external mutable list still introduces a side effect and a coordination obligation if it runs concurrently. Keep behavior stateless where practical and do not infer safety from the compact syntax.

Go deeper: [27] Java 17 Predicate API · [8] Java 17 specification: expressions

A stream is a pipeline, not a container

A Stream describes a traversal and aggregate operations over a source. Intermediate operations such as filter and map are generally lazy; a terminal operation triggers the relevant processing. The stream does not own a new permanent copy of every element, and a consumed stream is not a reusable collection. Create a new stream from a repeatable source when another traversal is needed.

Explain a pipeline from left to right: source, selection, transformation and terminal result. If each stage has a clear responsibility, the code can be more readable than manual accumulator bookkeeping. If it hides nested branching, mutable external state and several unrelated actions, a loop may be better. Some optimizations can elide stages whose effects do not influence the result, so do not rely on incidental side effects in intermediate operations for essential application work.

A clear sequential pipeline java · StreamsDemo.java
import java.util.List;

public class StreamsDemo {
    public static void main(String[] args) {
        List<Integer> minutes = List.of(25, -1, 40, 0);
        int total = minutes.stream()
                .filter(value -> value >= 0)
                .mapToInt(Integer::intValue)
                .sum();
        System.out.println(total);
    }
}
Expected result
65
A sequential stream pipelineThe source provides elements, the filter chooses accepted values, mapping selects the numeric representation and a terminal sum produces one result.SourceList of duration valuesfilterKeep only values meeting the chosen rulemapToIntUse a primitive numeric streamsumConsume the pipeline into one total
A sequential stream pipeline. The source provides elements, the filter chooses accepted values, mapping selects the numeric representation and a terminal sum produces one result.Scroll horizontally to read the full diagram on a small screen.

Go deeper: [28] Java 17 Stream API

Parallel is not a free speed switch

A parallel stream can introduce concurrency, ordering differences and overhead. It is not automatically faster, especially for tiny inputs, blocking I/O or poorly splittable work. Behavioral parameters should satisfy the stream contract, including noninterference and appropriate statelessness. Appending to an ordinary shared ArrayList from a parallel pipeline is not a safe way to collect results.

Choose a collector or terminal operation that expresses the intended aggregate, and measure a representative workload before adding parallel execution. Keep resource-backed streams inside an appropriate try-with-resources scope when their API requires closing. In this foundation, sequential pipelines are enough to learn transformations and reductions without mixing in a concurrency model. Understanding one traversal precisely is more useful than benchmarking an accidental race.

Go deeper: [28] Java 17 Stream API · [20] Java 17 ArrayList API

Keep these ideas

  • Functional interfaces give lambdas a typed contract.
  • A stream is a consumable pipeline with lazy stages and a terminal result.
  • Parallel execution adds obligations; it does not certify speed or safety.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

12.1 · Practice task

Why cannot a consumed Stream normally be traversed again like a List?

Hint: The stream represents an operation pipeline and traversal state.

Read the worked solution

12.2 · Practice task

Why is externalList.add(value) inside a parallel forEach unsafe for an ordinary ArrayList?

Hint: Several tasks may mutate the same unsynchronized structure.

Read the worked solution

Chapter 13

Testing and debugging with useful evidence

Test contracts, isolate failures, and keep discovered edge cases.

By the end of this chapter
  • Write independent expected values
  • Separate test levels
  • Avoid disabled assertions as validation

Tests state observable promises

A useful test controls inputs, invokes a behavior and compares the observation with an independently justified expectation. For a reading total, choose small durations that can be added by hand. Do not calculate the expected result by copying the same production algorithm, because the two sides can share the same bug. Test names should explain the rule being checked rather than the private method or line number they happen to execute.

Include successful inputs, boundary inputs and the specified failure cases. A nonnegative-duration validator needs zero, a positive value and a negative rejection. A parser needs a valid row, a missing field and a malformed number. These tests serve as examples for future maintainers as well as alarms for defects. A large test count without meaningful boundaries is weak evidence.

Evidence at several scalesSmall contract tests isolate calculations; integration checks connect components; a command-level check verifies the actual user-facing invocation.Unit checksSmall operation with controlled inputsIntegration checksReal parser, validator and temporary resourceCommand checksArguments, output and exit statusUser observationClarity and behavior in the intended workflow
Evidence at several scales. Small contract tests isolate calculations; integration checks connect components; a command-level check verifies the actual user-facing invocation.Scroll horizontally to read the full diagram on a small screen.

Go deeper: [3] Java Language Specification, JavaSE 17 edition · [10] Java 17 specification: exceptions

Testing levels and controlled dependencies

A unit test focuses on a small behavior with controlled collaborators. An integration test checks a meaningful connection such as a real temporary file passing through parsing, validation and aggregation. A command-level test additionally checks arguments, output and status. These layers complement one another. Unit tests alone cannot prove the launcher invokes the intended application path, while a single end-to-end happy path rarely explains exactly which small contract failed.

Use temporary directories for filesystem tests and deterministic inputs for calculations. Avoid personal files, the current clock or a real network unless that environmental interaction is specifically under test. Inject a collaborator when it makes a dependency boundary meaningful, not merely to satisfy a testing fashion. Keep test code readable enough that a failed assertion helps you understand the intended behavior quickly.

Go deeper: [25] Java 17 Files API · [3] Java Language Specification, JavaSE 17 edition

Assertions and a standalone check harness

The Java assert statement can be disabled at runtime, so do not use it as the only validation of external data. Mature projects commonly use a test framework and a build runner. To keep the capstone dependency-free, this guide also shows a tiny check method that throws AssertionError unconditionally when a test expectation fails. It is a teaching harness, not a replacement for the discovery, reporting and isolation features of a full test framework.

When a defect is found, preserve its smallest reproducing input as a regression check, fix the behavior and inspect neighboring cases. Passing tests demonstrate selected contracts under the checked conditions; they do not prove the absence of all defects or establish thread safety. Avoid making an assertion weaker solely to obtain a green result. First determine whether the implementation or the stated requirement is wrong.

A dependency-free behavioral check java · ChecksDemo.java
public class ChecksDemo {
    static int total(int[] values) {
        int result = 0;
        for (int value : values) {
            if (value < 0) {
                throw new IllegalArgumentException("negative duration");
            }
            result = Math.addExact(result, value);
        }
        return result;
    }
    static void check(boolean condition, String message) {
        if (!condition) {
            throw new AssertionError(message);
        }
    }
    public static void main(String[] args) {
        check(total(new int[]{20, 40}) == 60, "two values");
        check(total(new int[]{}) == 0, "empty input");
        check(total(new int[]{0}) == 0, "observed zero");
        System.out.println("3 checks passed");
    }
}
Expected result
3 checks passed

Go deeper: [7] Java 17 specification: statements · [10] Java 17 specification: exceptions

Keep these ideas

  • Tests should express behavior with independently justified expectations.
  • Unit, integration and command checks answer different questions.
  • A regression case keeps a fixed defect from becoming a forgotten story.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

13.1 · Practice task

Why should a negative-duration input be rejected with ordinary control flow rather than only assert minutes >= 0?

Hint: Runtime assertion settings can change.

Read the worked solution

13.2 · Practice task

A unit test for aggregation passes, but the command prints the wrong file’s result. Which additional test level helps?

Hint: The connection from arguments to the loader was not covered.

Read the worked solution

Chapter 14

A first safe model of concurrency

Recognize shared-state risks and manage small tasks with explicit lifecycle rules.

By the end of this chapter
  • Distinguish tasks from threads
  • Explain a lost update
  • Bound and observe task execution

Tasks, threads, and shared state

Concurrency means several activities can make progress during overlapping periods; parallelism means work is actually executing at the same time. A thread is one execution mechanism, while a task is a unit of work your program wants completed. Keep those concepts separate. An executor can manage task execution without each caller manually creating and tracking a new thread. That abstraction still needs limits, lifecycle management and a clear policy for failed tasks.

Shared mutable state creates coordination problems. Incrementing a plain integer involves reading, computing and writing, so two threads can lose an update when those steps interleave. The fact that a short program often prints the expected total does not prove the operation is safe. Concurrency defects depend on timing and memory visibility as well as the apparent sequence in one source file.

Go deeper: [29] Java 17 ExecutorService API · [30] Java 17 AtomicInteger API

Atomicity, locks, and invariants

AtomicInteger provides atomic operations for one integer state, such as incrementAndGet. It does not automatically make a multi-field business operation atomic. A transfer that changes two balances needs a consistency strategy for both changes together; two separate atomic counters can still expose an invalid intermediate relationship. Choose synchronization around the invariant that must hold, rather than around whichever individual field is easiest to protect.

A synchronized block or method can provide mutual exclusion and specified visibility guarantees through a shared monitor. Every participant accessing the protected invariant must follow the same locking policy. Holding a lock while performing slow I/O can unnecessarily block unrelated progress, and inconsistent lock ordering can deadlock. Prefer avoiding shared mutable state when results can be computed independently and combined afterward.

Go deeper: [11] Java 17 specification: threads and locks · [30] Java 17 AtomicInteger API

Bound work and close the executor

The example uses a fixed-size executor and a small known number of tasks, waits for every Future, and shuts the executor down in finally. Future.get can report task failure through ExecutionException, so do not silently ignore it. Interruption is a cooperation signal; if code cannot handle it fully, preserve the interrupted status when appropriate and let the application decide how to stop. Cancelling a task is not a universal guarantee that arbitrary code has already stopped.

Do not read this small example as a production job system. A fixed number of worker threads does not automatically mean an unbounded submission queue is safe for unlimited requests. Real services need backpressure, bounded queues, timeouts and a rejection policy. This book uses Java 17 APIs, so it does not assume newer executor AutoCloseable behavior or virtual-thread APIs. Learn those separately with the release-specific documentation when they solve a concrete problem.

Wait for each bounded demonstration task, then shut down java · TasksDemo.java
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;

public class TasksDemo {
    public static void main(String[] args) throws Exception {
        AtomicInteger counter = new AtomicInteger();
        ExecutorService pool = Executors.newFixedThreadPool(2);
        try {
            List<Future<?>> tasks = new ArrayList<>();
            for (int i = 0; i < 4; i++) {
                tasks.add(pool.submit(() -> {
                    counter.incrementAndGet();
                }));
            }
            for (Future<?> task : tasks) {
                task.get();
            }
            System.out.println(counter.get());
        } finally {
            pool.shutdown();
        }
    }
}
Expected result
4

Go deeper: [29] Java 17 ExecutorService API · [11] Java 17 specification: threads and locks

Keep these ideas

  • Concurrent progress introduces ordering and visibility obligations.
  • Atomic fields do not automatically protect multi-field invariants.
  • Executors need bounded workload assumptions and an explicit shutdown policy.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

14.1 · Practice task

Does using two AtomicInteger fields make a transfer between them one atomic business operation?

Hint: Each field operation can be atomic while the relationship between fields is temporarily inconsistent.

Read the worked solution

14.2 · Practice task

Why must a program observe submitted Future results instead of only calling shutdown?

Hint: Task completion and task success are different facts.

Read the worked solution

Chapter 15

Project structure, performance, and delivery

Keep the build understandable and optimize only a measured, meaningful problem.

By the end of this chapter
  • Explain classpath and packaging roles
  • Recognize JVM benchmark pitfalls
  • Preserve behavior during performance changes

Organize a project around responsibilities

Packages group related types and participate in fully qualified names. A source file with package learning.ledger belongs in a matching project structure for ordinary tool conventions, and compiled classes can be written into a separate output directory with javac -d. The classpath tells tools where to find compiled classes and resources. A missing-class error can therefore be an organization or launch configuration problem rather than a defect in the class itself.

Use a build tool when dependency resolution, repeatable test execution and packaging justify it. The tool should record a release target and a reproducible workflow, not become an unexplained ritual. This book’s capstone stays in a small dependency-free shape so you can see the underlying compile and run steps. A future migration to Maven or Gradle should preserve the behavior tests rather than silently changing the application contract.

An explicit two-file compile and run workflow text
javac --release 17 -d out ReadingLedger.java ReadingLedgerChecks.java
java -cp out ReadingLedger sessions.tsv
java -cp out ReadingLedgerChecks
jar --create --file ledger.jar --main-class ReadingLedger -C out .
java -jar ledger.jar sessions.tsv
Expected result
These commands compile the capstone, run its report and checks, then package and launch a JAR. They require a suitable installed JDK.

Go deeper: [2] Java 17 javac command · [31] Java 17 jar command

Measure the actual bottleneck

Performance begins with the number and nature of operations. Repeated linear membership scans can become expensive as records grow, while a suitable set or map may reduce expected lookup work. Choosing a data structure changes memory use, ordering and equality obligations, so preserve those semantics when optimizing. Complexity is a model of growth, not a substitute for observing the intended workload.

Java execution can include class loading, compilation by the JVM, warmup and garbage collection. A single stopwatch measurement around a tiny loop can therefore be misleading. Use an appropriate benchmarking harness for serious microbenchmarks and a profiler for a whole application question. State the JDK, data size, warmup policy and measured operation with any result. Do not turn one laptop timing into a universal claim about a collection or language feature.

Go deeper: [20] Java 17 ArrayList API · [22] Java 17 HashMap API · [32] OpenJDK Java Microbenchmark Harness

Memory and operational habits

Garbage collection reclaims eligible object memory according to runtime behavior; it does not make memory unlimited or release every external resource promptly. Keeping unnecessary references in a long-lived collection can retain objects that are no longer useful. A growing cache needs a size and invalidation policy. Copying large structures for convenience may improve ownership clarity while increasing allocation pressure, so measure the tradeoff instead of assuming a keyword solves it.

Keep development habits practical: compile with useful warnings, run tests before packaging, inspect diagnostics rather than suppressing them broadly, and keep secrets out of source code and command examples. A JAR groups classes and resources; it does not automatically bundle a compatible runtime or every external dependency. Know what the receiving user must install, which entry point launches, and how the program reports a failure after deployment.

A repeatable delivery loopSource changes pass compilation and behavioral checks before packaging. A packaged artifact is then exercised through the same user-facing command contract.Source and configurationRecord the release targetCompileCheck types and APIsTestVerify contracts and boundary casesPackageGroup compiled classes and resourcesRun and observeCheck the real launch workflow
A repeatable delivery loop. Source changes pass compilation and behavioral checks before packaging. A packaged artifact is then exercised through the same user-facing command contract.Scroll horizontally to read the full diagram on a small screen.

Go deeper: [2] Java 17 javac command · [31] Java 17 jar command · [1] Dev.java learning index

Keep these ideas

  • Build organization should make compile, test and launch reproducible.
  • Performance claims need a workload and runtime context.
  • Packaging does not remove runtime, dependency or lifecycle requirements.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

15.1 · Practice task

Why is a successful JAR creation command not proof that another computer can run the application?

Hint: Packaging and runtime availability are separate concerns.

Read the worked solution

15.2 · Practice task

Why can a tiny one-run Java benchmark include costs unrelated to the steady-state operation you meant to measure?

Hint: The JVM and application may still be warming up.

Read the worked solution

Chapter 16

Capstone: a validated reading-ledger application

Connect the language and API concepts in a complete tool with a separate contract check program.

By the end of this chapter
  • Explain a restricted file format
  • Separate I/O and a pure core
  • Compile, test and extend one documented workflow

The complete application contract

Our Java capstone reads a deliberately restricted tab-separated ledger. The first line must be exactly title followed by one tab and minutes. Every later line contains one nonblank title, one tab and a nonnegative int duration. Titles are trimmed and grouped case-sensitively. Embedded tabs or line breaks are outside this format; it is not a general CSV parser. Empty datasets contain the header only and produce an explicit no-sessions message plus a zero total.

The loader caps the file size and line count for this small local exercise, validates all rows before reporting success and uses UTF-8. A byte-size check before readAllLines is a useful classroom bound under a stable local-file assumption, not protection against a hostile concurrent writer. A production upload endpoint would need stronger streaming and access controls. Totals use long and checked addition so numeric overflow cannot silently wrap into a believable answer.

Go deeper: [25] Java 17 Files API · [16] Java 17 Integer API · [15] Java 17 Math API

Trace the responsibility boundaries

The Session record validates and normalizes one accepted session. parseLines checks the exact header, row structure and numeric syntax, then constructs validated records. load owns filesystem access. summarize is a pure aggregation over accepted sessions, and render chooses deterministic sorted output. main handles the command boundary and expected errors. These separations let tests exercise most behavior without creating a real file.

Trace the fixture: Python 25 and Python 35 combine into 60, while Java 20 forms its own total. TreeMap determines the alphabetical title order for display. An invalid third row prevents any normal report from being printed. The command writes expected failure messages to standard error and exits with status 2. It does not swallow every Throwable, so unexpected programming defects are not mislabeled as an ordinary empty dataset.

The ledger’s validation-to-report pathThe loader produces text lines, the parser creates only valid Session objects, and a pure summary is rendered only after all required data succeeds.Arguments and loaderChoose a file; enforce local exercise limitsFormat parserRequire the exact restricted header and rowsSession validationTrim titles; reject invalid duration valuesPure summaryCombine values with checked arithmeticDeterministic reportSort titles and print only complete results
The ledger’s validation-to-report path. The loader produces text lines, the parser creates only valid Session objects, and a pure summary is rendered only after all required data succeeds.Scroll horizontally to read the full diagram on a small screen.

Go deeper: [22] Java 17 HashMap API · [13] Java 17 Objects API · [10] Java 17 specification: exceptions

Implementation, checks, and safe extensions

Save the source as ReadingLedger.java, create sessions.tsv with the shown literal tab separators, and compile with javac --release 17 ReadingLedger.java ReadingLedgerChecks.java. Launch with java ReadingLedger sessions.tsv. The expected report is Java:20 minutes, Python:60 minutes and Total:80 minutes, each on its own line with a space after the colon. The separate check program throws on a failed expectation even when Java assertions are disabled.

The included check program covers grouping, empty data, zero duration and rejection of malformed or invalid rows. The example was compiled for Java 17 and run on Temurin 17.0.21.1+2. Command-level checks also confirmed the sample report and explicit failure statuses for a missing path, malformed UTF-8, oversized input and the invalid rows discussed here. Repeat those checks in your own environment, then extend one contract at a time while retaining the original fixtures and failure expectations as regression evidence.

Complete dependency-free application; Java 17 target java · ReadingLedger.java
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.TreeMap;

public final class ReadingLedger {
    static final long MAX_BYTES = 1_000_000;
    static final int MAX_RECORDS = 10_000;

    record Session(String title, int minutes) {
        Session {
            title = Objects.requireNonNull(title, "title").strip();
            if (title.isEmpty() || minutes < 0) {
                throw new IllegalArgumentException("invalid title or duration");
            }
        }
    }

    static List<Session> parseLines(List<String> lines) {
        if (lines.isEmpty() || !lines.get(0).equals("title\tminutes")) {
            throw new IllegalArgumentException("expected header: title<TAB>minutes");
        }
        if (lines.size() - 1 > MAX_RECORDS) {
            throw new IllegalArgumentException("too many records");
        }
        List<Session> sessions = new ArrayList<>();
        for (int i = 1; i < lines.size(); i++) {
            String[] fields = lines.get(i).split("\t", -1);
            if (fields.length != 2) {
                throw new IllegalArgumentException("row " + (i + 1) + ": expected 2 fields");
            }
            try {
                int minutes = Integer.parseInt(fields[1]);
                sessions.add(new Session(fields[0], minutes));
            } catch (IllegalArgumentException error) {
                throw new IllegalArgumentException("row " + (i + 1) + ": " + error.getMessage(), error);
            }
        }
        return List.copyOf(sessions);
    }

    static List<Session> load(Path path) throws IOException {
        if (Files.size(path) > MAX_BYTES) {
            throw new IllegalArgumentException("file exceeds one-megabyte limit");
        }
        return parseLines(Files.readAllLines(path, StandardCharsets.UTF_8));
    }

    static Map<String, Long> summarize(List<Session> sessions) {
        Map<String, Long> totals = new TreeMap<>();
        for (Session session : sessions) {
            long previous = totals.getOrDefault(session.title(), 0L);
            totals.put(session.title(), Math.addExact(previous, session.minutes()));
        }
        return totals;
    }

    static String render(Map<String, Long> totals) {
        StringBuilder result = new StringBuilder();
        long grandTotal = 0;
        if (totals.isEmpty()) {
            result.append("No sessions.\n");
        }
        for (Map.Entry<String, Long> entry : new TreeMap<>(totals).entrySet()) {
            result.append(entry.getKey()).append(": ").append(entry.getValue())
                  .append(" minutes\n");
            grandTotal = Math.addExact(grandTotal, entry.getValue());
        }
        result.append("Total: ").append(grandTotal).append(" minutes\n");
        return result.toString();
    }

    public static void main(String[] args) {
        if (args.length != 1) {
            System.err.println("Usage: java ReadingLedger <sessions.tsv>");
            System.exit(2);
            return;
        }
        try {
            List<Session> sessions = load(Path.of(args[0]));
            String report = render(summarize(sessions));
            System.out.print(report);
        } catch (IOException | IllegalArgumentException | ArithmeticException error) {
            System.err.println("Error: " + error.getMessage());
            System.exit(2);
        }
    }
}
Expected result
Java: 20 minutes
Python: 60 minutes
Total: 80 minutes
Fixture: the separators below are literal tab characters text · sessions.tsv
title	minutes
Python	25
Java	20
Python	35
Run java ReadingLedgerChecks after compiling both source files java · ReadingLedgerChecks.java
import java.util.List;
import java.util.Map;

public final class ReadingLedgerChecks {
    static void check(boolean ok, String message) {
        if (!ok) {
            throw new AssertionError(message);
        }
    }
    static void rejects(List<String> lines) {
        try {
            ReadingLedger.parseLines(lines);
            throw new AssertionError("expected invalid input");
        } catch (IllegalArgumentException expected) {
            // The parser rejected the invalid contract example.
        }
    }
    public static void main(String[] args) {
        var rows = ReadingLedger.parseLines(List.of(
                "title\tminutes", "Python\t25", " Python \t35", "Java\t20"));
        check(ReadingLedger.summarize(rows).equals(Map.of("Python", 60L, "Java", 20L)),
                "group and normalize titles");
        check(ReadingLedger.render(Map.of()).equals("No sessions.\nTotal: 0 minutes\n"),
                "empty report");
        check(ReadingLedger.parseLines(List.of("title\tminutes", "Java\t0")).size() == 1,
                "zero duration");
        rejects(List.of("wrong header"));
        rejects(List.of("title\tminutes", "Java\t-1"));
        rejects(List.of("title\tminutes", "Java\tnot-a-number"));
        rejects(List.of("title\tminutes", " \t25"));
        rejects(List.of("title\tminutes", "Java\t25\textra"));
        System.out.println("8 contract checks passed");
    }
}
Expected result
8 contract checks passed

Go deeper: [2] Java 17 javac command · [25] Java 17 Files API · [10] Java 17 specification: exceptions

Keep these ideas

  • A complete application makes format limits and error statuses explicit.
  • Pure calculations and deterministic output simplify verification.
  • Compile for the stated release and repeat the contract and command-level checks in your own environment.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

16.1 · Practice task

Add a minimum-duration filter while ensuring invalid records never disappear silently. State the order of operations and two boundary checks.

Hint: A filter must operate after full required validation.

Read the worked solution

16.2 · Practice task

Add a new report format through the Formatter interface idea. Which existing tests should remain unchanged?

Hint: Aggregation and presentation are distinct contracts.

Read the worked solution

Practice with feedback

Worked solutions

These solutions show a valid line of reasoning. Compare assumptions and intermediate steps, rather than only the final number or output. Other implementations can be equally good when they preserve the stated contract.

Chapter 1 · The Java toolchain without mystery

Solution 1.1

Use java Hello after compiling Hello.java. The class-name launch form locates a class through the classpath. Passing the .class suffix changes the requested name instead of identifying the intended compiled file in the expected way.

Return to the task

Solution 1.2

Compare the IDE project JDK, its language/release setting, the terminal java and javac versions, and the command used to compile. Reproduce the smallest source with an explicit release target before changing application logic.

Return to the task

Chapter 2 · Types, references, arithmetic, and null

Solution 2.1

Both operands of 7 / 2 are integers, so the operation produces the integer 3. Casting that result gives 3.0. Use 7.0 / 2 or (double)7 / 2 so floating-point division happens before the fractional part is discarded.

Return to the task

Solution 2.2

No. int permits negative values and has a finite range. Validate accepted durations and accumulate in a suitable wider representation, using checked arithmetic when overflow must fail. A correct type declaration is only part of the application’s value contract.

Return to the task

Chapter 3 · Text, Unicode, equality, and parsing

Solution 3.1

Reference equality asks whether both variables identify the same object. Separate objects may carry equal text, while interning can make some literal examples accidentally share an object. Use equals for content and adopt an explicit null policy.

Return to the task

Solution 3.2

Apply the documented whitespace policy, parse the integer with a narrow NumberFormatException handler, then reject values below 0 or above 600. Test empty text,25x,600 and 601. Do not remove the x to manufacture a valid value that the user did not enter.

Return to the task

Chapter 4 · Conditions, loops, and boundaries

Solution 4.1

An array of length n has indices 0 through n-1. When i reaches n, values[i] is outside the array and throws ArrayIndexOutOfBoundsException. Use i < values.length for the ordinary full traversal, and test an empty array too.

Return to the task

Solution 4.2

The threshold is only meaningful after checking that the score is within its valid range, such as 0 through 100. Otherwise an impossible score receives an ordinary category and hides bad input. Test validity and category boundaries independently.

Return to the task

Chapter 5 · Methods, contracts, and pass-by-value

Solution 5.1

No. Reassigning the local parameters changes only those local variables. The method can return a new pair for the caller to assign, or mutate a shared holder with an explicit contract, but ordinary parameter reassignment cannot replace the caller’s variable bindings.

Return to the task

Solution 5.2

Have a pure method receive accepted numeric values and return the sum. Let a separate CLI layer read and validate text, call the calculation and display the returned result. Tests can then exercise empty and boundary inputs without simulating a terminal.

Return to the task

Chapter 6 · Arrays, lists, sets, and maps

Solution 6.1

List.of returns an unmodifiable list, and add throws UnsupportedOperationException. If growth is part of the intended contract, construct an ArrayList from the initial values. Do not remove immutability accidentally when callers should only observe data.

Return to the task

Solution 6.2

HashMap does not guarantee iteration order, so output order can be incidental. Sort the keys or present through a TreeMap when natural key order is the requirement. Keep tests focused on the chosen display contract rather than an observed bucket order.

Return to the task

Chapter 7 · Classes, records, and valid states

Solution 7.1

No. final prevents reassignment of the field, but the list may still mutate, and aliases can expose those changes. Use a defensive copy and an appropriate unmodifiable representation when required, while remembering that mutable elements can still be shared.

Return to the task

Solution 7.2

If negative minutes violate the invariant, an unrestricted setter permits an invalid state just as direct field access would. Validate the transition or expose a meaningful operation whose accepted values and failure behavior are explicit.

Return to the task

Chapter 8 · Interfaces, composition, and substitution

Solution 8.1

Ask whether the subclass truly satisfies the parent contract. It may need composition with a smaller capability interface instead of inheritance. Review which operations callers rely on and whether the subtype preserves their accepted inputs, effects and failure expectations.

Return to the task

Solution 8.2

A test can supply a small implementation that records its arguments or returns a predictable result. The report is checked against the interface behavior rather than a branch for each formatter type. Keep the fake faithful to the same input and output contract.

Return to the task

Chapter 9 · Equality, hashing, and stable keys

Solution 9.1

Yes. Hash collisions are permitted. The map still uses equality to distinguish candidate keys. A hash code alone is therefore not a unique object ID, and a correct implementation must preserve equal objects having equal hash codes.

Return to the task

Solution 9.2

The key can move logically to a different hash category without being physically reinserted. A lookup may fail even though the entry remains stored. Use immutable key state or remove and reinsert under a carefully defined update policy.

Return to the task

Chapter 10 · Generics without incantations

Solution 10.1

The wildcard promises that existing elements can be viewed as Number, but it does not reveal the exact accepted subtype for writes. Inserting a Double could violate an Integer-only list’s contract. Reading and writing require different guarantees.

Return to the task

Solution 10.2

Use a parameterized collection type and correct method signatures so ordinary compilation rejects incompatible writes. Do not merely add a stronger cast at the failing read; that hides neither the bad value nor the original lost type information.

Return to the task

Chapter 11 · Exceptions, resources, and structured input

Solution 11.1

It can hide malformed input, permission errors and programming defects under a successful empty result. Catch the expected failure types at a boundary, preserve their cause when adding context, and expose a failure status instead of claiming that no records existed.

Return to the task

Solution 11.2

Garbage collection does not guarantee prompt release at a specific point in control flow. try-with-resources deterministically attempts close when the scope exits, including exceptional exits. The resource still has its own close-failure behavior, which a robust application should understand.

Return to the task

Chapter 12 · Lambdas, streams, and deliberate pipelines

Solution 12.1

A terminal operation consumes the stream. Obtain a new stream from the original repeatable collection for another traversal, or deliberately materialize results if reuse justifies storage. Do not treat a stream reference as a cached collection.

Return to the task

Solution 12.2

ArrayList does not provide the required concurrent structural-mutation guarantees. Use a suitable stream collection operation or an explicitly designed concurrent structure where its semantics fit. Better still, first determine whether parallelism is useful for this workload at all.

Return to the task

Chapter 13 · Testing and debugging with useful evidence

Solution 13.1

Java assertions may be disabled, so external input could bypass the only check. Use an explicit condition that throws a documented exception or returns a validation result. Assertions can still document internal assumptions during development, but they are not the public input contract.

Return to the task

Solution 13.2

Add a command or integration test using a temporary input path and a distinctive expected result, then verify arguments, output and status together. Keep the small aggregation tests too, because they isolate a different responsibility.

Return to the task

Chapter 14 · A first safe model of concurrency

Solution 14.1

No. Updating one counter and then the other is still two operations. If the invariant concerns their combined state, use a coordination strategy covering the whole transition or redesign the state representation. Atomicity must match the business invariant.

Return to the task

Solution 14.2

Shutdown initiates lifecycle behavior but does not tell the caller that every task succeeded. Waiting on and inspecting futures exposes failures and permits a deliberate response. Add timeouts or cancellation policies where the workflow requires a bounded wait.

Return to the task

Chapter 15 · Project structure, performance, and delivery

Solution 15.1

The other computer still needs a compatible runtime or an explicitly distributed runtime image, correct dependencies and a valid entry point. Exercise the packaged launch command in the intended environment and verify its output and failure status.

Return to the task

Solution 15.2

Class loading, runtime compilation, initialization and garbage collection can dominate a small measurement. Use a suitable harness and a stated workload for serious comparisons, and profile the whole application before optimizing a guessed hotspot.

Return to the task

Chapter 16 · Capstone: a validated reading-ledger application

Solution 16.1

Parse and validate the threshold, load and validate every source row, then select sessions meeting the threshold before aggregation. Test a session exactly on the threshold and a malformed below-threshold record. The malformed record must still cause failure instead of being skipped before validation.

Return to the task

Solution 16.2

Keep parser, Session validation and summarize checks unchanged. Add output-specific tests for the new formatter and a command-level check for its selection option. If changing presentation forces you to rewrite aggregation expectations, inspect whether the responsibilities have become unnecessarily coupled.

Return to the task

Retrieve before you review

Final knowledge check

Choose one answer for each question and write a short reason. Use the explanation to find the assumption or misconception behind an error.

  1. 1. Which tool compiles the source in this guide?

    1. jar
    2. javac
    3. javadoc only
    4. The text editor itself
    Check answer and reasoning
  2. 2. What is the value of (double)(7 / 2)?

    1. 3.0
    2. 3.5
    3. 7.0
    4. A compile error in all cases
    Check answer and reasoning
  3. 3. Which operation normally compares String contents?

    1. ==
    2. hashCode alone
    3. equals
    4. Reference reassignment
    Check answer and reasoning
  4. 4. For an array of length n, which final nonnegative index is ordinarily valid when n > 0?

    1. n
    2. n + 1
    3. Always 0 only
    4. n - 1
    Check answer and reasoning
  5. 5. How does Java pass an object argument?

    1. By copying the entire object automatically
    2. By copying the reference value
    3. By allowing direct caller-variable rebinding
    4. By converting it to text
    Check answer and reasoning
  6. 6. Which statement about List.of is correct?

    1. It returns an unmodifiable list
    2. It always returns a growable ArrayList
    3. It guarantees deep immutability of all elements
    4. It permits every mutation
    Check answer and reasoning
  7. 7. What does a final reference field guarantee by itself?

    1. Every reachable object is deeply immutable
    2. The object is thread-safe
    3. The field cannot be reassigned after permitted initialization
    4. The reference must never be null
    Check answer and reasoning
  8. 8. Which fact is insufficient by itself for behavioral substitution?

    1. The implementation preserves accepted inputs
    2. The implementation preserves documented effects
    3. The implementation preserves failure expectations
    4. The compiler accepts the interface type
    Check answer and reasoning
  9. 9. What must hold when two objects are equal according to equals?

    1. They must be the same reference
    2. Their hash codes must be equal
    3. They must have different hashes
    4. Their toString output defines equality
    Check answer and reasoning
  10. 10. Why is List<Integer> not a subtype of List<Number>?

    1. A Number-accepting writer could insert a Double
    2. Integer is not a Number
    3. Java has no generic checking
    4. Lists contain only primitives
    Check answer and reasoning
  11. 11. What does try-with-resources primarily express?

    1. A guarantee that all code succeeds
    2. A replacement for input validation
    3. A resource scope with close behavior on exit
    4. Automatic retry of every exception
    Check answer and reasoning
  12. 12. What generally triggers work in a lazy stream pipeline?

    1. Declaring any local variable
    2. Creating a second reference
    3. Calling toString on the source
    4. A terminal operation
    Check answer and reasoning
  13. 13. Why is assert unsuitable as the only validation of untrusted input?

    1. It is always too slow
    2. It may be disabled at runtime
    3. It only accepts strings
    4. It always catches every exception
    Check answer and reasoning
  14. 14. Does one AtomicInteger automatically make a two-field business invariant atomic?

    1. No; coordination must cover the whole invariant
    2. Yes, even for unrelated fields
    3. Only when printed
    4. Only if its name includes atomic
    Check answer and reasoning
  15. 15. Which claim about a JAR is accurate?

    1. It always includes a full runtime
    2. It proves all tests passed
    3. It groups classes/resources but has separate runtime requirements
    4. It removes classpath and entry-point concerns in every deployment
    Check answer and reasoning
  16. 16. Why validate the complete required input before printing a complete report?

    1. To avoid using types
    2. To hide malformed records
    3. To eliminate failure statuses
    4. To avoid partial output looking like full success
    Check answer and reasoning

Assessment explanations

1. Answer B

javac

javac checks and compiles source; the java launcher starts execution.

Revisit the chapter · Return to the question

2. Answer A

3.0

Integer division happens before the outer conversion, so the lost fraction cannot be recovered.

Revisit the chapter · Return to the question

3. Answer C

equals

equals expresses content equality; reference identity and hashing answer different questions.

Revisit the chapter · Return to the question

4. Answer D

n - 1

The indices begin at zero and end one before the length.

Revisit the chapter · Return to the question

5. Answer B

By copying the reference value

The parameter receives a reference value copy. Shared-object mutation can still be observed.

Revisit the chapter · Return to the question

6. Answer A

It returns an unmodifiable list

The outer list is unmodifiable; element mutability remains a separate matter.

Revisit the chapter · Return to the question

7. Answer C

The field cannot be reassigned after permitted initialization

Final assignment rules do not recursively freeze the referenced object or validate nullability.

Revisit the chapter · Return to the question

8. Answer D

The compiler accepts the interface type

A matching type relationship still needs a compatible behavioral contract.

Revisit the chapter · Return to the question

9. Answer B

Their hash codes must be equal

Equal objects need equal hashes. Unequal objects may still collide.

Revisit the chapter · Return to the question

10. Answer A

A Number-accepting writer could insert a Double

Container invariance prevents writes that violate the narrower element contract.

Revisit the chapter · Return to the question

11. Answer C

A resource scope with close behavior on exit

It manages AutoCloseable lifecycles; it does not validate data or suppress the need to handle failures.

Revisit the chapter · Return to the question

12. Answer D

A terminal operation

Terminal operations consume the pipeline according to its semantics.

Revisit the chapter · Return to the question

13. Answer B

It may be disabled at runtime

Public validation must remain effective regardless of assertion enablement.

Revisit the chapter · Return to the question

14. Answer A

No; coordination must cover the whole invariant

Atomic single-variable operations do not combine independent field changes into one transaction.

Revisit the chapter · Return to the question

15. Answer C

It groups classes/resources but has separate runtime requirements

Packaging is distinct from compatible runtime availability and dependency/launch correctness.

Revisit the chapter · Return to the question

16. Answer D

To avoid partial output looking like full success

A later bad record should not leave earlier results presented as a complete successful report.

Revisit the chapter · Return to the question

Glossary

Atomicity
An operation’s indivisibility under its stated concurrency model. Chapter
AutoCloseable
Resource contract supporting explicit close behavior. Chapter
Boxing
Conversion between a primitive value and a corresponding wrapper representation. Chapter
Bytecode
Instructions stored in class files for execution by a JVM. Chapter
Checked exception
Exception subject to applicable compile-time catch-or-declare rules. Chapter
Classpath
Search configuration used to locate classes and resources. Chapter
Composition
Combining behavior through collaborators rather than subclassing. Chapter
Defensive copy
A deliberate copy preventing unwanted sharing through an API boundary. Chapter
Dynamic dispatch
Runtime selection of an overridden instance method based on the receiver. Chapter
Encapsulation
Designing access and operations to preserve internal rules. Chapter
Erasure
Translation strategy removing much generic type-argument detail after compile-time checking. Chapter
Executor
Abstraction managing the execution of submitted tasks. Chapter
Functional interface
An interface with one abstract method usable as a lambda target. Chapter
Future
Handle for observing a submitted computation’s result, completion or failure. Chapter
Hash collision
Different keys producing the same hash value. Chapter
Interface
A declared capability contract implemented by classes. Chapter
Invariance
Absence of an automatic subtype relationship between mutable generic containers of related element types. Chapter
Invariant
Rule that valid state or repeated operations preserve. Chapter
JAR
Archive grouping Java classes and resources with optional launch metadata. Chapter
JDK
Development kit including the compiler and other Java tools. Chapter
JVM
Runtime machine that loads and executes class bytecode under Java semantics. Chapter
List
Collection abstraction representing an ordered sequence. Chapter
Map
Association of keys with values. Chapter
Null
Reference value that identifies no object. Chapter
Overflow
An arithmetic result outside the representable numeric range. Chapter
Overloading
Several methods sharing a name with different applicable parameter signatures. Chapter
Parameter
Local input variable declared by a method. Chapter
Pass-by-value
Calling rule that supplies copied argument values to parameters. Chapter
Primitive
A language-defined non-reference value type such as int or boolean. Chapter
Record
A transparent data-carrier class form with generated component-oriented members. Chapter
Reference
A value identifying an object or representing null. Chapter
Regression check
An executable example preserving a previously fixed behavior. Chapter
Set
Collection abstraction representing distinct elements under equality. Chapter
Terminal operation
A stream operation that consumes a pipeline into a result or effect. Chapter
UTF-16 code unit
A16-bit unit used in the Java String representation model. Chapter
Wildcard
A type-use form expressing a bounded or unknown generic argument. Chapter

Read and watch with a purpose

Reading and video library

Use the chapter source links to choose a relevant next explanation. Each entry below states what it adds. Documentation links may evolve; edition 2026.12 records the assumptions used here.

  1. Dev.java learning index

    Oracle Java developer education · docs

    Official structured routes into Java; rolling index may include features newer than this edition.

    https://dev.java/learn/
  2. Java 17 javac command

    Oracle · docs

    Compiler invocation, release targets, output and classpath behavior.

    https://docs.oracle.com/en/java/javase/17/docs/specs/man/javac.html
  3. Java Language Specification, JavaSE 17 edition

    Oracle and Java language specification authors · docs

    Normative language rules when tutorial shorthand is insufficient.

    https://docs.oracle.com/javase/specs/jls/se17/html/index.html
  4. Java 17 specification: types, values and variables

    Oracle · docs

    Primitive/reference values, generics and variable rules.

    https://docs.oracle.com/javase/specs/jls/se17/html/jls-4.html
  5. Java 17 specification: classes

    Oracle · docs

    Fields, methods, constructors and class inheritance.

    https://docs.oracle.com/javase/specs/jls/se17/html/jls-8.html
  6. Java 17 specification: record classes

    Oracle · docs

    Record components, constructors and generated members.

    https://docs.oracle.com/javase/specs/jls/se17/html/jls-8.html#jls-8.10
  7. Java 17 specification: statements

    Oracle · docs

    Control flow, resource scopes and assertions.

    https://docs.oracle.com/javase/specs/jls/se17/html/jls-14.html
  8. Java 17 specification: expressions

    Oracle · docs

    Evaluation, conversions, method invocation and lambdas.

    https://docs.oracle.com/javase/specs/jls/se17/html/jls-15.html
  9. Java 17 specification: interfaces

    Oracle · docs

    Capabilities, interface methods and inheritance relationships.

    https://docs.oracle.com/javase/specs/jls/se17/html/jls-9.html
  10. Java 17 specification: exceptions

    Oracle · docs

    Checked and unchecked exception handling rules.

    https://docs.oracle.com/javase/specs/jls/se17/html/jls-11.html
  11. Java 17 specification: threads and locks

    Oracle · docs

    The formal memory-model and synchronization rules beyond this introductory chapter.

    https://docs.oracle.com/javase/specs/jls/se17/html/jls-17.html
  12. Java 17 String API

    Oracle · docs

    Text immutability, UTF-16 representation and content operations.

    https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/String.html
  13. Java 17 Objects API

    Oracle · docs

    Null checking and equality helper contracts.

    https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/Objects.html
  14. Java 17 Object API

    Oracle · docs

    equals and hashCode requirements.

    https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/Object.html
  15. Java 17 Math API

    Oracle · docs

    Checked arithmetic operations and numerical behavior.

    https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/Math.html
  16. Java 17 Integer API

    Oracle · docs

    Parsing, numeric range and wrapper behavior.

    https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/Integer.html
  17. Java 17 BigDecimal API

    Oracle · docs

    Decimal representation, rounding, equality and comparison.

    https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/math/BigDecimal.html
  18. Java 17 Locale API

    Oracle · docs

    Locale-sensitive behavior and the root locale.

    https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/Locale.html
  19. Java 17 List API

    Oracle · docs

    Sequence contracts and unmodifiable factories.

    https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/List.html
  20. Java 17 ArrayList API

    Oracle · docs

    Resizable-array behavior, complexity and synchronization caveats.

    https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/ArrayList.html
  21. Java 17 Set API

    Oracle · docs

    Distinct membership and equality obligations.

    https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/Set.html
  22. Java 17 HashMap API

    Oracle · docs

    Hash-based lookup, ordering limits and shared access.

    https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/HashMap.html
  23. Java 17 Arrays API

    Oracle · docs

    Array utilities and backed-list behavior.

    https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/Arrays.html
  24. Dev.java generics and functional-programming learning route

    Oracle Java developer education · docs

    Further guided study after the foundational wildcard explanation; rolling content.

    https://dev.java/learn/language/fp/
  25. Java 17 Files API

    Oracle · docs

    File operations, text reading and resource-related behavior.

    https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/nio/file/Files.html
  26. Java 17 AutoCloseable API

    Oracle · docs

    The resource lifecycle contract used by try-with-resources.

    https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/AutoCloseable.html
  27. Java 17 Predicate API

    Oracle · docs

    A small functional interface with Boolean output.

    https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/function/Predicate.html
  28. Java 17 Stream API

    Oracle · docs

    Laziness, stream consumption, side effects and parallel obligations.

    https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/stream/Stream.html
  29. Java 17 ExecutorService API

    Oracle · docs

    Task submission, futures, shutdown and interruption.

    https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/concurrent/ExecutorService.html
  30. Java 17 AtomicInteger API

    Oracle · docs

    Atomic single-integer operations and their scope.

    https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/concurrent/atomic/AtomicInteger.html
  31. Java 17 jar command

    Oracle · docs

    Archive creation and main-entry metadata.

    https://docs.oracle.com/en/java/javase/17/docs/specs/man/jar.html
  32. OpenJDK Java Microbenchmark Harness

    OpenJDK Code Tools project · docs

    A suitable starting point for serious JVM microbenchmark methodology.

    https://github.com/openjdk/jmh
  33. Inside Java Newscast: official video explanations

    Oracle Java developer relations · Watch / course

    Optional official short-form video discussions; choose an episode matching your JDK and topic rather than assuming every feature is in Java 17.

    https://inside.java/newscast
  34. Continue in the OpenLearning Java library

    OpenLearning · docs

    Platform chapters, practice and community improvement links.

    https://ankit-kotnala.github.io/OpenLearning/courses/java/

Continue on OpenLearning

Use the subject library to move between reading, practice, study material, and the wider topic map.

Make the explanation better

If a paragraph needs a clearer example, a command changes, or a diagram hides an important assumption, propose a correction in the open-source repository. Explain the issue and add a source or a reproducible example.

Editable book sources on GitHub

Original OpenLearning instructional text and diagrams: CC BY-SA 4.0. Original code: MIT. External material retains its own copyright and license. This book links to authorized resources; it does not relicense them.