All certifications / OCP Java / Cheat sheet
OCP Java 1Z0-831 (Java SE 25) cheat sheet
Domain 1: Handling date, time, text, numeric and boolean values (12%)
Exam tips
- Scan every numeric literal for three things: a leading 0 (octal), a missing L or f suffix on a value that needs it, and an underscore touching a prefix, suffix or decimal point.
- When you see == between two Integer variables, check whether both values fall in -128 to 127. If they do, expect true; if not, expect false. If one side is a primitive, it is a plain numeric comparison.
- Evaluate operands strictly left to right, tracking each variable's value on paper after every ++ or --. For compound assignment, remember the hidden cast: it compiles where the long form would not.
- When a question assigns an arithmetic result to byte, short or char, look for promotion to int. It only compiles with a cast, a compound assignment, or when the whole expression is a constant that fits.
- Before choosing an answer, write down the return type of each Math call. Most Math questions are really compile-error questions about round returning long or pow returning double.
- Look for string method calls whose return value is not assigned. Because String is immutable, the original variable is unchanged, and that is usually the whole point of the question.
- Track one StringBuilder object through every line, applying each call even when its result is not assigned. Then check the index math: every range method uses an exclusive end.
- The closing delimiter's position controls indentation: if it is on its own line and further left than the content, the difference becomes leading spaces. If it is on the last content line, there is no final newline.
- When a date-time method call is not assigned, the object is unchanged. Also check that the method exists on that type: LocalDate has no plusHours, and LocalTime has no plusDays.
- Remember Period for dates (P...Y...M...D) and Duration for times (PT...H...M...S). Across a DST change, plusDays keeps the wall-clock time, while plusHours(24) keeps the exact elapsed time.
Key terms
- Primitive type
- One of the eight built-in value types (byte, short, int, long, float, double, char, boolean) that are not objects.
- Literal
- A fixed value written in source code, such as 42, 3.5f, 'x' or 0b1010.
- Octal literal
- A whole-number literal with a leading 0, read in base 8, so 010 equals 8.
- Default value
- The value a field or array element gets automatically: 0, false, '\u0000' or null. Local variables have none.
- Wrapper class
- An immutable class such as Integer or Double that holds one primitive value as an object.
- Autoboxing
- The automatic conversion of a primitive to its wrapper, done by the compiler through valueOf.
- Unboxing
- The automatic conversion of a wrapper to its primitive; throws NullPointerException if the reference is null.
- Integer cache
- A pool of Integer objects for at least -128 to 127 that Integer.valueOf reuses, which makes == appear to work for small values.
- Operator precedence
- The rules that decide which operator in an unparenthesized expression is applied first.
- Postfix increment
- x++: the expression yields the old value, then x is increased by one.
- Compound assignment
- An operator like += that combines an operation with assignment and casts the result back to the left operand's type.
- Short-circuit evaluation
- && and || skip evaluating the right operand when the left operand already determines the result.
- Widening conversion
- An automatic conversion to a type with a larger range, such as int to long or float to double.
- Narrowing conversion
- A conversion to a type with a smaller range, which needs an explicit cast unless it is a fitting compile-time constant.
- Numeric promotion
- The rule that operands of arithmetic operators are converted to a common type of at least int before the operation.
- Compile-time constant
- An expression whose value the compiler knows, such as a literal or a final variable initialized with a literal.
- Math.round
- Rounds to the nearest whole number with halves toward positive infinity; returns long for a double argument and int for a float.
- Math.floor / Math.ceil
- Return the double just at or below (floor) or at or above (ceil) the argument, moving toward negative or positive infinity.
- Math.pow
- Raises a double base to a double exponent and always returns a double.
- Overloading by type
- abs, max and min have int, long, float and double versions, so the result type follows the promoted argument types.
- Immutability
- The property that an object's state cannot change after creation; String methods return new strings instead.
- String pool
- A JVM area that stores one shared copy of each string literal and compile-time constant string.
- substring(begin, end)
- Returns the characters from begin up to but not including end.
- isBlank
- Returns true if a string is empty or contains only whitespace characters.
- StringBuilder
- A mutable, non-synchronized sequence of characters whose methods change the object in place.
- Method chaining
- Calling one method on the result of another; it works with StringBuilder because mutating methods return this.
- replace(start, end, str)
- Removes the characters from start to end (exclusive) and inserts str there.
- Capacity
- The amount of storage a StringBuilder has reserved, which is separate from its current length.
- Text block
- A multi-line String literal delimited by three double quotes, with content starting on the line after the opening delimiter.
- Incidental whitespace
- Common leading indentation that the compiler strips from every line of a text block.
- Line continuation
- A backslash at the end of a text block line, which removes the line break so the next line joins it.
- \s escape
- An escape for a single space that survives the stripping of trailing whitespace.
- LocalDate
- An immutable date (year, month, day) with no time of day and no time zone.
- LocalDateTime
- A date and time without a zone, so it does not identify a single global instant.
- ZonedDateTime
- A date and time with a ZoneId, which identifies an exact moment and applies that zone's offset and daylight saving rules.
- Instant
- A point on the UTC timeline measured from the epoch 1970-01-01T00:00:00Z.
- Period
- A date-based amount of time in years, months and days, printed like P1Y2M3D.
- Duration
- A time-based amount stored as seconds and nanoseconds, printed like PT2H30M.
- DST gap
- The skipped local hour when clocks spring forward; a time inside it is shifted forward by the gap length.
- DST overlap
- The repeated local hour when clocks fall back; ZonedDateTime keeps the earlier offset by default.
Domain 2: Controlling program flow (8%)
Exam tips
- Ignore indentation. Count statements: without braces, only one statement belongs to the if or else, and every else binds to the nearest unmatched if.
- Find where execution enters the switch, then keep going downward past every label until you hit break or the closing brace. A default in the middle still falls through.
- In a switch expression, look for three errors: a missing default for int or String selectors, a block branch without yield, and a return or break used to leave the expression.
- Read pattern cases top to bottom and pick the first that matches, checking the guard too. A null selector throws NullPointerException unless there is a case null label.
- Order pattern cases from specific to general: subtypes before supertypes, guarded before unguarded, constants before type patterns, default last.
- Check whether the condition is tested before or after the body: while and for can run zero times, do-while always runs at least once. Also check that do-while ends with a semicolon.
- Ask which loop each break or continue refers to. With no label it is always the innermost loop; with a label it is the loop that carries that label. Remember that continue in a for loop still runs the update.
- Treat if(false) and while(false) differently: the first compiles, the second does not. For locals, trace every path, including a loop that runs zero times and an if without else.
Key terms
- Conditional expression
- The ternary operator cond ? a : b, which evaluates to one of two values depending on a boolean.
- Dangling else
- The rule that an else attaches to the closest unmatched if, regardless of indentation.
- Boolean condition
- An expression of type boolean or Boolean, the only kind accepted by if, while and the ternary operator.
- Empty statement
- A lone semicolon; after if(...) it becomes the entire body of the if.
- Fall-through
- In a colon-form switch, execution continuing into the next case's statements when there is no break.
- case label
- A compile-time constant that marks an entry point in a switch.
- default label
- The entry point used when no case matches; it may appear anywhere in the switch.
- Selector expression
- The value in switch(...) that is compared with the case labels.
- Switch expression
- A switch that evaluates to a value; it must be exhaustive and cannot fall through when using arrow labels.
- Arrow label
- case X -> ..., a label whose right side is a single expression, block or throw, with no fall-through.
- yield
- A statement that supplies the value of a switch expression from inside a block or a colon-style group.
- Exhaustiveness
- The requirement that a switch expression handles every possible value of its selector.
- Type pattern
- A pattern like String s that matches when the value is an instance of the type and binds it to a variable.
- Record pattern
- A pattern like Point(int x, int y) that matches a record and extracts its components.
- Guard
- A when clause after a pattern that adds a boolean condition for the case to match.
- case null
- A label that lets a pattern switch handle a null selector instead of throwing NullPointerException.
- Dominance
- A case is dominated when an earlier case matches every value it could match, which makes it unreachable and is a compile error.
- Exhaustive switch
- A switch whose cases cover every possible selector value, required for switch expressions and pattern switches.
- Unconditional pattern
- A pattern that matches every value of the selector's type, such as case Object o for an Object selector.
- MatchException
- The runtime exception an exhaustive switch throws if it meets a value its compiled cases do not cover, such as a newly added subtype.
- do-while loop
- A loop that runs its body once before testing the condition, so it always executes at least once.
- Enhanced for loop
- for (T x : source), which visits each element of an array or Iterable without an index.
- Iterable
- The interface that lets an object be used as the source of an enhanced for loop.
- Infinite loop
- A loop whose condition never becomes false, such as while(true) or for(;;), usually exited with break or return.
- break
- Ends the innermost enclosing loop or switch, or the labeled statement it names.
- continue
- Skips the rest of the current iteration of the innermost loop, or of the labeled loop it names.
- Label
- An identifier followed by a colon placed before a statement so that break or continue can target it.
- Nested loop
- A loop inside another loop; an unlabeled break or continue affects only the inner one.
- Unreachable statement
- A statement the compiler can prove will never execute, which is a compile-time error in Java.
- Definite assignment
- The compiler rule that a local variable must be assigned on every path before it is read.
- Constant expression
- An expression the compiler can evaluate, such as true or a final variable holding a literal, used in reachability analysis.
- Missing return statement
- The error reported when a non-void method can reach its end without returning a value.
Domain 3: Using object-oriented concepts in Java (20%)
Exam tips
- Statics run once, parent before child. For each new object: parent's initializers and constructor body, then child's initializers, then child's constructor body. Initializers run in source order.
- In a prologue, allowed means parameters, locals, static calls, throwing and assigning this class's fields. Not allowed means reading fields, calling instance methods, super.x, return, or putting super(...) inside a block.
- Instance methods follow the object; fields and static methods follow the reference type. For overriding, check signature, covariant return, access not narrower, and no new broader checked exceptions.
- Interface methods are public, whether written or not, so implementations must be public. Static interface methods are called only through the interface name, and duplicate defaults must be resolved with an override.
- Record accessors are named after the components (name(), not getName()). In a compact constructor, reassign the parameters, never this.field, and never declare a parameter list.
- Every permitted subclass needs exactly one of final, sealed or non-sealed, unless it is a record or enum, which are implicitly final. Unnamed-module code must keep them in the same package.
- Enum constructors are private and run once per constant at class initialization. valueOf is case-sensitive and throws IllegalArgumentException, and the constant list needs a semicolon when members follow.
- Creating an inner class from outside needs an outer object: outer.new Inner(). A static nested class uses new Outer.Nested(). Captured locals must be effectively final.
- After &&, the pattern variable is usable; after ||, it is not. With a negated test that returns or throws, the variable is in scope after the if statement.
- For var, check each line for: a field or parameter use, a missing initializer, a null or {array} initializer, or several variables in one declaration. Each is a compile error.
- Count reachable objects, not variables. Draw references on paper line by line, and remember that System.gc() guarantees nothing.
Key terms
- Default constructor
- The no-argument constructor the compiler adds only when a class declares no constructors.
- Static initializer
- A static { } block that runs once when the class is initialized.
- Instance initializer
- A { } block in the class body that runs for every new object, before the constructor body but after the superclass constructor.
- Pass by value
- Java copies each argument into the parameter; for objects, the copied value is the reference.
- Prologue
- The statements in a constructor before the explicit super(...) or this(...) call, which cannot use the object being constructed.
- Epilogue
- The statements after the explicit constructor call, where the object can be used normally.
- Early construction context
- The prologue and constructor-call arguments, where references to the current instance are restricted.
- Explicit constructor invocation
- A super(...) or this(...) statement that chains to another constructor.
- Overriding
- Redefining an inherited instance method with the same signature; the object's runtime type decides which version runs.
- Overloading
- Declaring methods with the same name but different parameter lists; the compiler picks one from argument types.
- Hiding
- Declaring a static method or a field with the same name as one in the parent; the reference type decides which is used.
- Covariant return type
- An overriding method's return type that is a subtype of the overridden method's return type.
- Abstract method
- A method with no body that concrete subclasses or implementing classes must implement.
- Default method
- An interface instance method with a body that implementing classes inherit and may override.
- Static interface method
- A method belonging to the interface itself, called only as InterfaceName.method().
- Private interface method
- A helper method with a body that is visible only inside the interface.
- Record component
- A name and type in a record header; each becomes a private final field and a public accessor.
- Canonical constructor
- The constructor whose parameters match the record components in order and that assigns every field.
- Compact constructor
- A canonical constructor written without a parameter list, used to validate or normalize parameters before fields are assigned automatically.
- Accessor method
- The generated method named after a component, such as x(), that returns its value.
- Sealed class
- A class or interface that allows only the direct subtypes named in its permits clause (or in the same file).
- permits clause
- The list of classes or interfaces allowed to directly extend or implement a sealed type.
- non-sealed
- A modifier for a permitted subclass that reopens the hierarchy so any class may extend it.
- Exhaustive hierarchy
- A closed set of subtypes that lets the compiler verify a switch handles every case.
- Enum
- A special class with a fixed set of named instances declared at the top of its body.
- values()
- A generated static method returning an array of all enum constants in declaration order.
- valueOf(String)
- Returns the constant with the exact given name, or throws IllegalArgumentException.
- ordinal()
- The zero-based position of a constant in its declaration.
- Static nested class
- A class declared static inside another class; it needs no outer instance and is created with new Outer.Nested().
- Inner class
- A non-static member class whose instances are tied to an outer instance and can access its members.
- Anonymous class
- An unnamed class declared and instantiated in a single expression, extending one class or implementing one interface.
- Effectively final
- A local variable that is never reassigned after initialization, which makes it usable from local classes and lambdas.
- Pattern matching for instanceof
- An instanceof test that also binds the value to a new variable of the tested type when it matches.
- Pattern variable
- The variable declared by a pattern, such as s in o instanceof String s.
- Flow scoping
- The rule that a pattern variable is in scope only where the compiler can prove the match succeeded.
- Record pattern
- A pattern such as Point(int x, int y) that tests for a record type and binds its components.
- Encapsulation
- Keeping fields private and controlling access to an object's state through methods.
- Immutable object
- An object whose state cannot change after construction, such as a String or a well-designed record.
- Defensive copy
- A copy of a mutable input or output that prevents outside code from changing an object's internal state.
- var
- A reserved type name that makes the compiler infer a local variable's type from its initializer.
- Garbage collector
- The JVM component that automatically reclaims memory used by unreachable objects.
- Eligible for garbage collection
- An object that no live thread can reach from any GC root; it may be collected at any later time or never.
- GC root
- A starting point for reachability, such as a local variable in an active method or a static field.
- Island of isolation
- A group of objects that reference each other but cannot be reached from any root, so all are eligible.
Domain 4: Handling exceptions (8%)
Exam tips
- Memorize the split: RuntimeException and Error subtypes are unchecked; every other Exception is checked. IOException and FileNotFoundException are checked; NumberFormatException is unchecked.
- The return value is fixed when return in try executes; finally runs afterwards and can only replace it by returning itself. A return or throw in finally hides any earlier exception.
- In a multi-catch, check two things: that no type is a subclass of another in the list, and that the variable is never assigned. Either mistake is a compile error.
- Subclass before superclass, always. And a specific checked exception can only be caught if something in the try can throw it; Exception, Throwable and unchecked types are always allowed.
- Trace the order: open in declaration order, body, close in reverse order, then catch, then finally. Resource variables are final and not visible in catch or finally.
- In try-with-resources, the body's exception wins and close exceptions become suppressed. In a plain finally, a new exception replaces the original, which is lost.
- For an override, allowed checked exceptions are: the same, narrower, fewer or none. Never new and never broader. Unchecked exceptions are always allowed.
- The parent class decides everything: extends Exception means checked, extends RuntimeException means unchecked. Constructors are not inherited, so write each one you need and call super.
Key terms
- Throwable
- The root class of everything that can be thrown, with direct subclasses Error and Exception.
- Checked exception
- A subclass of Exception, but not of RuntimeException, that must be caught or declared.
- Unchecked exception
- RuntimeException, Error or any of their subclasses, which the compiler does not require you to handle.
- Handle-or-declare rule
- The compiler requirement that code throwing a checked exception either catches it or lists it in throws.
- try block
- A block containing code that might throw, followed by catch and/or finally blocks.
- catch block
- A handler that runs when an exception of its declared type (or a subtype) is thrown in the try.
- finally block
- A block that runs after try and catch whatever happens, unless the JVM exits.
- Exception propagation
- An uncaught exception leaving the current method and moving up the call stack to the caller.
- Multi-catch
- A catch block listing several exception types separated by |, sharing one handler and one variable.
- Related types
- Exception types where one is a subclass of another; they cannot both appear in the same multi-catch.
- Implicitly final parameter
- The multi-catch variable, which cannot be reassigned inside the block.
- Precise rethrow
- Rethrowing a caught, unmodified exception variable so the method only needs to declare the specific types that can actually occur.
- Catch order
- The top-to-bottom sequence in which catch blocks are checked; the first matching one runs.
- Unreachable catch block
- A handler the compiler proves can never run, either because an earlier block catches its type or because the try cannot throw it.
- Most specific first
- The rule of writing subclass exception handlers before superclass handlers.
- Checked exception analysis
- The compiler's tracking of which checked exceptions a try block can throw, based on method throws clauses and throw statements.
- try-with-resources
- A try statement that declares resources in parentheses and closes them automatically at the end of the block.
- AutoCloseable
- The interface with a single close() method that a resource must implement to be used in try-with-resources.
- Closeable
- A subinterface of AutoCloseable used by I/O classes whose close() throws IOException.
- Reverse close order
- Resources are closed in the opposite order of declaration, last opened first closed.
- Suppressed exception
- An exception thrown while closing a resource that is attached to the primary exception instead of replacing it.
- Primary exception
- The exception that actually propagates; in try-with-resources, the one thrown by the try block if there is one.
- getSuppressed()
- A Throwable method returning an array of the exceptions suppressed by this one.
- getCause()
- A Throwable method returning the exception that caused this one, which is different from suppressed exceptions.
- throws clause
- The part of a method or constructor header that declares the checked exceptions it may pass to callers.
- throw statement
- A statement that throws one exception object, as in throw new IOException().
- Narrower exception
- A subclass of an exception type, which an overriding method may declare in place of the parent type.
- Contract
- The promises a method's signature makes to callers, including which checked exceptions they must handle.
- Custom exception
- An application-defined class that extends Exception, RuntimeException or one of their subclasses.
- Exception chaining
- Wrapping a caught exception as the cause of a new exception so the original details are kept.
- Cause
- The Throwable passed to an exception's constructor and returned by getCause().
- super(message)
- The constructor call that passes a detail message to the parent exception class.
Domain 5: Working with arrays and collections (10%)
Exam tips
- For binarySearch on a missing value, find the index where it would be inserted, negate it, and subtract one. If the array is not sorted, the answer is 'undefined'.
- Learn the queue pairs: add/offer, remove/poll, element/peek. The first of each throws on failure, the second returns false or null. push and pop on a Deque work at the front.
- Mutating a List.of, Set.of or Map.of collection compiles but throws UnsupportedOperationException. Arrays.asList allows set but not add or remove, and writes through to the array.
- Check the reference type first: Set and Collection references do not have getFirst. Then check the implementation: TreeSet and TreeMap reject addFirst and putFirst, unmodifiable lists reject all changes, and empty collections throw NoSuchElementException.
- Check the return value asked for: putIfAbsent returns the old value (null when it inserted), while merge and computeIfAbsent return the current value. A null result from merge's function removes the key.
- Read comparator chains left to right, and apply reversed() to everything before it in the chain. compareTo and compare return negative, zero or positive, not only -1, 0 and 1.
- In a TreeSet or TreeMap, compareTo returning 0 means duplicate, regardless of equals. headSet excludes its bound, tailSet includes it, and lower/higher are strict while floor/ceiling are not.
- Exam questions often show list.add(...) on a List<? extends Something> and ask whether it compiles. It does not (except for null). With ? super, adding the bound type compiles, but assigning get() to anything more specific than Object does not.
- For a List<Integer>, a plain int argument always means index. Look for Integer.valueOf, a cast to Integer or Object, or an Integer variable to spot the by-value version.
Key terms
- Array
- A fixed-length object holding elements of one type, accessed by a zero-based index.
- Shallow copy
- A copy of an array whose elements are the same object references as the original.
- Insertion point
- The index where a missing key would be inserted; binarySearch returns -(insertion point) - 1 for it.
- Arrays.mismatch
- Returns the first index at which two arrays differ, or -1 if they are equal.
- List
- An ordered collection that allows duplicates and index-based access, such as ArrayList or LinkedList.
- Set
- A collection with no duplicate elements, such as HashSet, LinkedHashSet or TreeSet.
- Map
- A structure of unique keys mapped to values that is not a Collection, such as HashMap or TreeMap.
- Deque
- A double-ended queue supporting insertion and removal at both ends, usable as a queue or a stack.
- Unmodifiable collection
- A collection whose mutator methods throw UnsupportedOperationException, such as those from List.of.
- UnsupportedOperationException
- The runtime exception thrown when a collection does not support a modifying operation.
- Fixed-size list
- The list returned by Arrays.asList, which supports set but not add or remove.
- Unmodifiable view
- A read-only wrapper, such as Collections.unmodifiableList, that still reflects changes to the underlying collection.
- SequencedCollection
- A Java 21 interface for collections with a defined encounter order, providing first/last operations and reversed().
- SequencedSet
- A sequenced collection with no duplicates, implemented by LinkedHashSet and inherited by SortedSet.
- SequencedMap
- A map with a defined entry order, implemented by LinkedHashMap and extended by SortedMap.
- reversed()
- Returns a reverse-ordered view of a sequenced collection or map that reflects later changes.
- getOrDefault
- Returns the mapped value if the key is present, otherwise the supplied default, without modifying the map.
- putIfAbsent
- Stores a value only when the key is absent or mapped to null, and returns the previous value.
- computeIfAbsent
- Computes and stores a value from the key only when the key is absent or mapped to null, returning the current value.
- merge
- Stores a value for an absent key, or combines it with the existing value using a function; a null result removes the key.
- Comparable
- An interface a class implements to define its natural ordering through compareTo.
- Comparator
- A separate object that defines an ordering through compare, allowing several orders for one type.
- thenComparing
- A Comparator method that adds a secondary key used only when the first comparison is a tie.
- Stable sort
- A sort that keeps equal elements in their original relative order.
- Natural ordering
- The order defined by an element's own compareTo method from the Comparable interface.
- NavigableSet
- A sorted set interface with methods such as floor, ceiling, headSet and tailSet, implemented by TreeSet.
- floor / ceiling
- The greatest element less than or equal to, or the least element greater than or equal to, a given value.
- headSet / tailSet
- Views of the elements below a bound (exclusive by default) or at and above a bound (inclusive by default).
- Type parameter
- A placeholder such as T declared in angle brackets on a class, interface or method and replaced by a type argument at each use.
- Bounded type parameter
- A type parameter restricted with extends, such as <T extends Comparable<T>>, so the code can call methods of the bound.
- Upper-bounded wildcard
- ? extends X: accepts X or any subtype; safe for reading as X, but only null can be added.
- Lower-bounded wildcard
- ? super X: accepts X or any supertype; safe for adding X values, but reads return Object.
- Type erasure
- The compiler removes generic type arguments after checking them, so they are not available at run time.
- remove(int index)
- Removes and returns the element at the given position; throws IndexOutOfBoundsException for a bad index.
- remove(Object o)
- Removes the first element equal to o and returns true if one was removed, false otherwise.
- Overload resolution phases
- The compiler first tries matches without boxing, then with boxing and unboxing, then with varargs.
- removeIf
- A Collection method that removes every element matching a Predicate and returns true if anything was removed.
Domain 6: Working with streams and lambda expressions (16%)
Exam tips
- Match method names to interfaces: get for Supplier, accept for Consumer, apply for Function and the operators, test for Predicate. Questions often call the wrong method, such as predicate.apply(x), which does not compile.
- Check three things in every lambda question: parentheses rules for parameters, braces with return and semicolons, and whether any captured local variable is reassigned anywhere in the method, even after the lambda.
- Remember range excludes the end and rangeClosed includes it, and that a stream is single use. A question that stores a stream in a variable and calls two terminal operations on it ends in IllegalStateException.
- Trace output questions element by element, not operation by operation, and check whether there is a terminal operation at all. Also watch for sorted on an infinite stream, which hangs even with a later limit.
- Know the return types: count is long, min, max, findFirst, findAny and single-argument reduce return Optional, the match methods return boolean, and allMatch on an empty stream is true.
- toMap without a merge function throws IllegalStateException on a duplicate key. counting() produces Long, and averagingX produces Double; exam answers often use Integer instead.
- average() always returns OptionalDouble, sum() on IntStream returns int, and OptionalInt uses getAsInt(). Answers that assign average() to a double or call get() on an OptionalInt do not compile.
- The classic trap: orElse(expensiveCall()) runs expensiveCall() even when the Optional has a value; orElseGet does not. Also, Optional.of(null) throws immediately, while ofNullable(null) is empty.
- Distinguish fold from scan by output size: fold emits one element at the end, scan emits one per input element. For windows, fixed does not overlap and its last window can be short; sliding overlaps.
- For output questions on parallel streams, forEach order is unpredictable, findAny is unpredictable, but collect/toList keep encounter order. A reduce with a non-identity starting value gives a different result in parallel.
Key terms
- Functional interface
- An interface with exactly one abstract method, which a lambda or method reference can implement.
- Supplier<T>
- Takes no arguments and returns a T through get().
- Predicate<T>
- Takes a T and returns a boolean through test(); composable with and, or and negate.
- UnaryOperator<T>
- A Function<T, T> whose input and output types are the same; its method is apply.
- BinaryOperator<T>
- A BiFunction<T, T, T> that combines two values of the same type into one; used by reduce.
- Lambda expression
- An anonymous function written as parameters -> body that implements a functional interface.
- Effectively final
- A local variable that is never reassigned after it is initialized, so a lambda or inner class may capture it.
- Bound method reference
- A reference on a specific object, such as System.out::println, whose receiver is fixed when the reference is created.
- Unbound method reference
- A reference such as String::length where the first argument supplied at call time becomes the receiver.
- Constructor reference
- ClassName::new, which creates a new object using the constructor that matches the target interface's parameters.
- Stream source
- Where the elements come from, such as a collection, array, Stream.of values, a range or a generator.
- IntStream.range
- Produces ints from the start up to but not including the end.
- IntStream.rangeClosed
- Produces ints from the start up to and including the end.
- Stream.iterate
- Builds a stream from a seed and a function applied repeatedly; the two-argument form is infinite, the three-argument form stops when a predicate fails.
- Infinite stream
- A stream with no natural end, made by generate or two-argument iterate, which needs a short-circuiting operation to finish.
- Lazy evaluation
- Intermediate operations run only when a terminal operation pulls elements through the pipeline.
- flatMap
- Maps each element to a stream and concatenates the resulting streams into a single stream.
- Stateful operation
- An intermediate operation such as sorted or distinct that must track elements it has already seen.
- Short-circuiting operation
- An operation such as limit that can finish without processing every element.
- peek
- An intermediate operation that performs an action on each element as it passes, mainly for debugging.
- Terminal operation
- The final operation of a pipeline that triggers processing and produces a result or side effect.
- reduce
- Combines the elements into a single value with an accumulator, optionally starting from an identity value.
- Identity value
- A starting value that does not change the result when combined, such as 0 for addition or "" for concatenation.
- collect
- A mutable reduction that gathers elements into a container, usually via a Collector.
- Stream.toList()
- A terminal operation that returns an unmodifiable List of the stream's elements.
- groupingBy
- A collector that groups elements by a classifier into a Map whose values are lists or the result of a downstream collector.
- partitioningBy
- A collector that splits elements into a Map<Boolean, ...> with both true and false keys always present.
- Downstream collector
- A collector passed to groupingBy or partitioningBy that processes each group, such as counting or mapping.
- Merge function
- A BinaryOperator given to toMap that decides the value when two elements map to the same key.
- joining
- A collector that concatenates strings with an optional delimiter, prefix and suffix.
- IntStream
- A stream of primitive int values with numeric operations such as sum, average and summaryStatistics.
- OptionalDouble
- An Optional-like container for a double, returned by average() on primitive streams; read with getAsDouble().
- boxed()
- Converts a primitive stream into a stream of the matching wrapper objects.
- IntSummaryStatistics
- An object holding count, sum, min, max and average computed in a single pass.
- mapToInt
- Converts a Stream<T> into an IntStream using a ToIntFunction.
- Optional.of
- Creates an Optional holding a non-null value; throws NullPointerException if the value is null.
- Optional.ofNullable
- Creates an Optional that is empty if the value is null and full otherwise.
- orElse
- Returns the value or a fallback; the fallback expression is evaluated every time.
- orElseGet
- Returns the value or calls a Supplier to produce a fallback only when empty.
- orElseThrow
- Returns the value or throws: NoSuchElementException with no argument, or a supplied exception.
- Gatherer
- An object describing a custom intermediate stream operation through an initializer, integrator, combiner and finisher.
- windowFixed
- A built-in gatherer that groups elements into non-overlapping lists of a fixed size, with a possibly shorter last list.
- windowSliding
- A built-in gatherer that emits overlapping lists of a fixed size, advancing one element at a time.
- fold
- A built-in gatherer that combines all elements into a single result emitted when the stream ends.
- scan
- A built-in gatherer that emits the running result after each element, like a cumulative sum.
- Parallel stream
- A stream whose operations run on multiple threads, by default in the common ForkJoinPool.
- forEachOrdered
- A terminal operation that processes elements in encounter order even in a parallel stream.
- Associative operation
- An operation where grouping does not matter, (a op b) op c = a op (b op c), required for correct parallel reduce.
- Stateful lambda
- A lambda that reads or modifies shared mutable state during stream execution, which is unsafe in parallel.
Domain 7: Packaging and deploying Java code (7%)
Exam tips
- Exports controls ordinary access and applies at compile and run time; opens controls reflection at run time only. If an exported method's signature uses another module's types, that dependency should be requires transitive.
- Keep the directive owners straight: uses goes in the consumer, provides ... with goes in the provider, and the interface's package must be exported by whoever defines it. The implementation's package does not need to be exported.
- Automatic modules come from plain JARs on the module path; the unnamed module comes from anything on the class path. Named modules can require automatic modules but never the unnamed module.
- The run syntax is java -p path -m module/package.Class. Remember -d means output directory for javac but describe-module for java.
- An ambiguity from two module imports is reported only where the simple name is used, and a single-type import fixes it. Also remember module imports bring in types from transitively required modules.
- If a class has both main(String[]) and main(), the String[] version is chosen. A private main is not launchable, and an instance main needs a non-private no-argument constructor.
- In source mode the first top-level class in the file is launched, arguments after the file name go to main, and no class files are produced. Multi-file support finds other classes as source files by package directory.
- Match tool to job: jar packages, jdeps analyzes, jlink builds a runtime. jlink works only with named modules, never automatic modules or the class path.
Key terms
- module-info.java
- The module declaration file at the root of a module's sources, naming the module and its directives.
- requires transitive
- Declares a dependency and makes it readable to every module that requires this module (implied readability).
- exports
- Makes a package's public types accessible to other modules; optionally limited with a to clause.
- opens
- Allows runtime deep reflection, including private members, on a package without granting compile-time access.
- Strong encapsulation
- The rule that non-exported packages are inaccessible to other modules even if their classes are public.
- Service interface
- The type, usually an interface in an exported package, that consumers depend on and providers implement.
- uses
- A module directive in the consumer declaring that it looks up implementations of a service with ServiceLoader.
- provides ... with
- A module directive in the provider naming the service interface and the implementation class that supplies it.
- ServiceLoader
- The class that discovers and instantiates service providers at run time via load, iteration, findFirst or stream.
- ServiceLoader.Provider
- A handle to a provider that exposes type() without instantiation and get() to create the instance.
- Module path
- The list of locations searched for modules, set with --module-path or -p, where module rules are enforced.
- Named module
- A module with a module-info.class on the module path that reads only what it requires and exposes only what it exports.
- Automatic module
- A non-modular JAR on the module path; it gets a derived name, exports all packages and reads all modules.
- Unnamed module
- The module containing all class path code; it reads everything and exports everything but cannot be required.
- Automatic-Module-Name
- A manifest attribute that sets a stable name for a JAR used as an automatic module.
- --module-path (-p)
- The option for javac and java that lists directories or JARs containing modules.
- --module (-m)
- The java option that names the module to run, optionally with /MainClass.
- --describe-module (-d)
- A java option that prints a module's descriptor; not the same as javac's -d output directory.
- --module-source-path
- A javac option for compiling several modules at once from one source tree with a folder per module.
- --list-modules
- A java option that lists the observable modules and their versions.
- Module import declaration
- import module M; which imports on demand all public top-level types in packages M exports, including those from its transitive dependencies.
- Ambiguous simple name
- A type name that two imports provide from different packages; using it without qualification is a compile error.
- Shadowing
- When a more specific import or declaration hides a name that a broader import would otherwise supply.
- Single-type import
- An import naming one class, such as import java.util.List;, which takes priority over on-demand and module imports.
- Instance main method
- A non-static main method, with or without a String[] parameter, that the launcher calls on a newly created instance.
- Compact source file
- A source file with top-level fields and methods not enclosed in a class, which the compiler wraps in an implicit final class.
- Implicitly declared class
- The unnamed-package final class the compiler creates for a compact source file; code cannot refer to it by name.
- java.lang.IO
- A class with static console helpers print, println and readln, available without an import.
- Source-file mode
- Running java with a .java file name so the launcher compiles the source in memory and runs it without writing class files.
- Multi-file source program
- A source-mode program whose other classes are found as .java files under the launched file's directory and compiled on demand.
- --source
- A launcher option setting the language version for source mode; required for files that do not end in .java.
- Shebang file
- An executable script whose first line starts with #! and names the java launcher, run directly by the operating system.
- jar
- The JDK tool that creates, lists, extracts and updates JAR archives and can record a main class.
- jdeps
- The JDK dependency analyzer that reports package and module dependencies and internal API use.
- jlink
- The JDK tool that assembles named modules and their dependencies into a custom runtime image.
- Runtime image
- A self-contained directory with a JVM and only the modules an application needs.
- Manifest
- The META-INF/MANIFEST.MF file inside a JAR holding metadata such as Main-Class.
Domain 8: Managing concurrent code execution (9%)
Exam tips
- Runnable's method is run(), it returns void and cannot throw checked exceptions. daemon() and priority() are available on platform builders; virtual threads are always daemon.
- Virtual threads improve scalability for blocking, I/O-heavy tasks, not raw CPU speed. Do not pool them; limit access to scarce resources with a Semaphore instead. They are always daemon threads.
- execute returns void and takes only a Runnable; submit returns a Future. shutdown does not wait, awaitTermination waits, and close() does both. Exceptions inside a task reach you wrapped in ExecutionException from get().
- Calling run() does not create a thread, so Thread.currentThread() inside it is the caller. Calling start() twice throws IllegalThreadStateException. Unless code uses join or another coordination tool, output order between threads is unpredictable.
- volatile gives visibility but not atomicity, so volatile count++ is still unsafe. Synchronized instance methods lock this and static ones lock the Class object; two methods only exclude each other if they use the same lock.
- incrementAndGet returns the new value and getAndIncrement returns the old one. Always unlock in finally, and only after a successful lock or tryLock; unlocking a lock you do not hold throws IllegalMonitorStateException.
- Modifying an ArrayList while iterating it throws ConcurrentModificationException; a CopyOnWriteArrayList does not, and the loop sees the old snapshot. ConcurrentHashMap rejects null keys and values. put/take block, offer/poll do not.
- Deadlocked threads are BLOCKED or WAITING; livelocked threads are RUNNABLE and busy. The standard deadlock fix in answer choices is acquiring locks in a consistent order.
- Scoped values have no set method; the only way to change the visible value is to rebind in a nested scope. get() outside any binding throws NoSuchElementException, so use isBound or orElse when the value may be missing.
Key terms
- Runnable
- A functional interface with void run() that represents a task with no result and no checked exceptions.
- Thread.Builder
- A fluent API, obtained with Thread.ofPlatform() or Thread.ofVirtual(), for configuring and creating threads.
- unstarted
- A Thread.Builder method that creates a configured thread without starting it.
- Daemon thread
- A background thread that does not prevent the JVM from exiting.
- join
- A Thread method that makes the caller wait until that thread terminates.
- Platform thread
- A Java thread backed one to one by an operating system thread for its whole lifetime.
- Virtual thread
- A lightweight JVM-managed thread that unmounts from its carrier while blocked so the carrier can run other work.
- Carrier thread
- A platform thread on which the JVM mounts virtual threads to execute them.
- newVirtualThreadPerTaskExecutor
- An Executors factory method returning an ExecutorService that starts a new virtual thread for each task.
- Pinning
- A state where a blocked virtual thread cannot unmount from its carrier, reducing scalability.
- Callable<V>
- A task interface with V call() throws Exception, returning a result and allowed to throw checked exceptions.
- Future<V>
- A handle to a pending result, with get, get with timeout, isDone and cancel.
- ExecutionException
- The checked exception thrown by Future.get when the task itself threw; the original exception is its cause.
- shutdown
- Stops an executor accepting new tasks while letting submitted tasks complete, without waiting.
- awaitTermination
- Blocks until all tasks complete after shutdown or a timeout expires, returning whether it terminated.
- Thread.State
- The enum of thread states: NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING and TERMINATED.
- BLOCKED
- The state of a thread waiting to acquire a monitor lock for a synchronized block or method.
- TIMED_WAITING
- The state of a thread waiting with a time limit, as in sleep or join with a timeout.
- IllegalThreadStateException
- Thrown when start() is called on a thread that has already been started.
- Interrupt
- A cooperative signal that sets a thread's interrupt flag and wakes it from sleep, wait or join with InterruptedException.
- Race condition
- A bug where the outcome depends on the timing of threads accessing shared mutable data.
- Intrinsic lock (monitor)
- The lock built into every object, acquired by synchronized blocks and methods.
- synchronized method
- A method whose body runs while holding the lock on this, or on the Class object for static methods.
- Visibility
- Whether a write by one thread is guaranteed to be seen by reads in another thread.
- volatile
- A field modifier guaranteeing visibility and ordering of reads and writes, but not atomicity of compound operations.
- AtomicInteger
- An int wrapper with atomic, lock-free operations such as incrementAndGet and compareAndSet.
- Compare-and-swap (CAS)
- An atomic hardware operation that updates a value only if it still equals an expected value.
- ReentrantLock
- An explicit Lock implementation that the holding thread can re-acquire, released by matching unlock calls.
- tryLock
- A Lock method that tries to acquire the lock without blocking, or within a timeout, and returns whether it succeeded.
- IllegalMonitorStateException
- Thrown when a thread unlocks a lock it does not hold.
- ConcurrentHashMap
- A thread-safe map allowing concurrent reads and writes, with weakly consistent iterators and no null keys or values.
- CopyOnWriteArrayList
- A thread-safe list that copies its array on each write; iterators use a snapshot and never throw ConcurrentModificationException.
- BlockingQueue
- A queue whose put and take methods wait for space or elements, used for producer-consumer handoff.
- Weakly consistent iterator
- An iterator that tolerates concurrent modification without throwing and may or may not reflect changes made after it was created.
- Deadlock
- Two or more threads each waiting forever for a lock held by another, forming a cycle.
- Starvation
- A thread is perpetually denied access to a resource it needs because other threads keep getting it.
- Livelock
- Threads stay active, repeatedly responding to one another, but make no progress.
- Lock ordering
- A prevention technique where all threads acquire multiple locks in the same global order.
- Thread dump
- A snapshot of every thread's state and stack, used to find deadlocks and blocked threads.
- ScopedValue
- A value bound for the duration of a call and readable by all code in that call's dynamic scope, then automatically unbound.
- ScopedValue.where
- Creates a binding of a scoped value key to a value, followed by run or call to execute code with it.
- Dynamic scope
- The set of code executed during a call, including methods called indirectly, where a binding is visible.
- ThreadLocal
- A variable with a separate mutable value per thread that persists until removed.
- Rebinding
- Binding an already bound scoped value to a new value in a nested where(...).run(...) call.
Domain 9: Using the Java I/O API (6%)
Exam tips
- Resolving an absolute path returns it unchanged, relativize throws IllegalArgumentException when mixing absolute and relative paths, and normalize never checks the disk. Most Path methods do not require the file to exist.
- createDirectory fails if the directory exists or the parent is missing; createDirectories handles both. copy and move fail on an existing target unless REPLACE_EXISTING is given. delete throws for a missing file; deleteIfExists returns false.
- readAllLines returns a List and closes the file; lines returns a Stream that you must close. writeString without options truncates existing content, and APPEND alone fails if the file is missing.
- list is one level and excludes the start directory; walk is recursive and includes the start directory; find requires maxDepth and a BiPredicate taking attributes. All return streams that must be closed.
- End-of-data signals differ: read() returns -1, readLine() returns null. Classes ending in Stream handle bytes; Reader and Writer handle characters. Closing the outer wrapper closes the inner stream.
- System.console() can return null, so exam code that calls a method on it without checking may throw NullPointerException. readPassword returns char[], and System.out and System.err are PrintStreams.
- On deserialization, transient and static fields are not read from the stream, field initializers do not run, and the Serializable class's constructors are not called; only the first non-serializable superclass's no-arg constructor runs.
- Resources close in reverse order, before catch and finally. An exception from close after a body exception is suppressed, not thrown. Files.lines, list, walk and find return streams you must close; readAllLines and writeString do not need it.
Key terms
- Path
- An interface representing a file system location as a sequence of name elements, optionally with a root.
- resolve
- Joins a path to another; returns the argument unchanged if the argument is absolute.
- relativize
- Builds a relative path from one path to another; both must be absolute or both relative.
- normalize
- Removes . elements and name/.. pairs by string logic without accessing the file system.
- toRealPath
- Returns the actual path with links resolved, throwing IOException if the file does not exist.
- Files.createDirectories
- Creates a directory and all missing parents, without failing if the directory already exists.
- FileAlreadyExistsException
- Thrown when an operation would create or overwrite a path that already exists without permission to replace it.
- REPLACE_EXISTING
- A StandardCopyOption that lets copy or move overwrite an existing target.
- ATOMIC_MOVE
- A move option requesting an all-or-nothing move, failing if the file system cannot guarantee it.
- DirectoryNotEmptyException
- Thrown when trying to delete a directory that still contains entries.
- Files.readAllLines
- Reads an entire file into a List<String>, one element per line, and closes the file.
- Files.lines
- Returns a lazily populated Stream<String> of the file's lines that must be closed after use.
- Files.writeString
- Writes a CharSequence to a file, by default creating it or truncating existing content.
- StandardOpenOption.APPEND
- An open option that writes at the end of an existing file instead of replacing its content.
- UncheckedIOException
- An unchecked wrapper for an IOException, used when I/O fails inside stream processing.
- Files.list
- Returns a lazy Stream<Path> of the direct entries of one directory, without recursion.
- Files.walk
- Returns a lazy depth-first Stream<Path> of a directory tree, including the start path, optionally limited by maxDepth.
- Files.find
- Walks a tree to a required maxDepth and returns paths matching a BiPredicate<Path, BasicFileAttributes>.
- BasicFileAttributes
- An interface exposing size, timestamps and file type information read with the directory entry.
- FOLLOW_LINKS
- A FileVisitOption that makes walk and find follow symbolic links.
- Byte stream
- An InputStream or OutputStream that transfers raw bytes, suited to binary data.
- Character stream
- A Reader or Writer that transfers characters, decoding and encoding bytes with a charset.
- InputStreamReader
- A bridge that wraps a byte InputStream and decodes it into characters using a charset.
- BufferedReader
- A Reader that buffers input and provides readLine(), which returns null at end of file.
- flush
- Forces any buffered output to be written to the underlying destination.
- System.in
- The standard input stream, an InputStream usually connected to the keyboard.
- System.err
- The standard error stream, a PrintStream intended for error and diagnostic messages.
- Console
- A class obtained from System.console() for interactive text input and output, which may be null when unavailable.
- readPassword
- A Console method that reads input without echoing it and returns a char array.
- printf
- A method that writes formatted output using specifiers such as %s, %d, %.2f and %n.
- Serializable
- A marker interface that allows instances of a class to be written and read by object streams.
- transient
- A field modifier that excludes the field from serialization; it is restored with its default value.
- serialVersionUID
- A private static final long version identifier checked during deserialization to detect incompatible class versions.
- NotSerializableException
- Thrown at run time when writing an object that has a non-transient field whose type is not serializable.
- ObjectInputFilter
- A mechanism to restrict which classes and how much data may be deserialized, used to defend against unsafe input.
- try-with-resources
- A try statement that declares AutoCloseable resources and closes them automatically in reverse order.
- AutoCloseable
- An interface with close() throws Exception, required for resources in try-with-resources.
- Closeable
- An I/O interface that extends AutoCloseable with close() throws IOException.
- Suppressed exception
- An exception thrown while closing a resource after the body already threw, attached to the original via addSuppressed.
- Resource-backed stream
- A Stream such as those from Files.lines, list, walk or find that holds an open handle and must be closed.
Domain 10: Implementing localization (4%)
Exam tips
- The string form is language_COUNTRY with lowercase language and uppercase country, language always first. Locale.setDefault changes the JVM only. Use Locale.of rather than the deprecated constructors.
- Order: requested locale (language_country, then language), then default locale (language_country, then language), then base. For missing keys, only the chosen bundle's parents are searched, never the default locale's bundles.
- Know which factory to use, that percent multiplies by 100, that the default rounding is HALF_EVEN, and that parse throws the checked ParseException but accepts text with trailing garbage after a valid number.
- Without changing fraction digits, compact formats round to a whole number using HALF_EVEN, so 1,234,567 is 1M and 1,500 is 2K. Numbers under 1,000 print unchanged in US English.
- MM is month and mm is minutes; HH is 24-hour and hh is 12-hour. Formatting a LocalDate with time letters throws UnsupportedTemporalTypeException, and a bad parse throws the unchecked DateTimeParseException.
- Placeholders are zero-based and can be reused or reordered. A lone apostrophe breaks the pattern, so write two single quotes. Numbers are formatted with locale grouping even without a format type.
Key terms
- Locale
- An object identifying a language and optional country and variant, used by locale-sensitive classes.
- Language code
- A lowercase ISO 639 code such as en or fr that forms the first part of a locale.
- Country code
- An uppercase ISO 3166 code such as US or CA identifying the region of a locale.
- Locale.of
- The factory method for creating a Locale from a language and optional country and variant.
- Default locale
- The locale the JVM uses when none is given, initialized from the operating system and changeable with Locale.setDefault.
- Resource bundle
- A set of locale-specific key-value resources loaded by base name and locale with ResourceBundle.getBundle.
- Base name
- The common prefix of a bundle family, such as Messages, to which locale suffixes like _fr_CA are added.
- Default (base) bundle
- The bundle file with no locale suffix, used as the final fallback and the root of every parent chain.
- Parent chain
- The sequence of less specific bundles, such as fr_CA to fr to base, searched for a key missing from the chosen bundle.
- MissingResourceException
- An unchecked exception thrown when no bundle is found or a key is missing from the bundle and its parents.
- NumberFormat
- An abstract locale-sensitive class for formatting and parsing numbers, obtained through factory methods.
- getCurrencyInstance
- Returns a NumberFormat that formats values as currency for a locale, with its symbol and standard decimal places.
- HALF_EVEN
- The default rounding mode that rounds exact halves to the nearest even digit.
- ParseException
- A checked exception thrown when text cannot be parsed as a number or date.
- DecimalFormat
- A concrete NumberFormat that formats using a pattern of 0, #, comma and period symbols.
- CompactNumberFormat
- A NumberFormat subclass that formats numbers in short locale-specific forms such as 1K or 1 thousand.
- NumberFormat.Style.SHORT
- The compact style that uses abbreviated suffixes such as K, M and B in US English.
- NumberFormat.Style.LONG
- The compact style that spells out the magnitude, such as thousand or million.
- getCompactNumberInstance
- The NumberFormat factory method that returns a compact formatter for a locale and style.
- DateTimeFormatter
- An immutable, thread-safe class that formats and parses java.time values using ISO constants, localized styles or patterns.
- FormatStyle
- An enum of SHORT, MEDIUM, LONG and FULL used for locale-specific date and time layouts.
- ofPattern
- Creates a formatter from pattern letters such as yyyy-MM-dd HH:mm, optionally with a Locale.
- DateTimeParseException
- An unchecked exception thrown when text cannot be parsed into a date or time.
- UnsupportedTemporalTypeException
- Thrown when formatting requires a field the value does not have, such as hours on a LocalDate.
- MessageFormat
- A java.text class that builds locale-aware messages by substituting arguments into indexed placeholders.
- Placeholder
- A {n} element in a pattern replaced by argument n, optionally with a format type such as number or date.
- Format type
- The second part of a placeholder, such as number, date, time or choice, controlling how the argument is formatted.
- Quoting
- In MessageFormat, a single quote starts a literal section; two single quotes produce one apostrophe.
- ChoiceFormat
- A format used through the choice type that selects text based on numeric ranges, useful for simple plurals.
Study OCP Java for free
Lessons, quizzes, exam simulations and hands-on labs.
Open the OCP Java study planLessons, quizzes, exam simulations and hands-on labs.