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
Clear explanations. Worked examples. Practice with reasoning. Original text · CC BY-SA 4.0 Code · MIT
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
Ability to save text files and use a terminal
A Java Development Kit supporting Java 17 or newer; these examples use Java 17 APIs and avoid preview features
No framework, dependency manager or previous object-oriented language is required
What you will be able to do
Compile and launch a small Java program with a clear version target
Trace primitive values, references, method calls and object mutation
Model domain invariants with classes, interfaces and records
Choose collections and implement a consistent equality/hash contract
Validate files and report failures without hiding defects
Use tests, bounded tasks and evidence-based performance investigation
Build a complete command-line reading ledger with deterministic output
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
This edition targets Java 17 language features and standard-library APIs. Newer release features such as virtual threads are not required or silently assumed.
Examples were compiled for Java 17 and run on Eclipse Temurin OpenJDK 17.0.21.1+2 on macOS aarch64. All 16 Java source files compiled; expected outputs, the ledger contract checks, and the listed file-failure cases passed. Re-run the checks when using a different JDK or platform.
This is a practical foundation, not a complete treatment of the JVM, the Java Memory Model, cryptography, enterprise frameworks or production deployment.
Original explanations and diagrams are licensed separately from linked reference material. Optional videos stay at official publisher or university hosts.
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.
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.
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 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.
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.
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);
}
}
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.
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.
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 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.
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);
}
}
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.
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);
}
}
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 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.
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.
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);
}
}
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.
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 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.
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.
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));
}
}
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 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.
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());
}
}
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.
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.
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 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.
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()));
}
}
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.
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 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.
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")));
}
}
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.
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)));
}
}
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.
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.
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);
}
}
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 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.
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.
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 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.
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.
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 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.
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.
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");
}
}
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.
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.
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();
}
}
}
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.
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.
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 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.
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.
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 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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.