OCP Java 21 Final Review: Exam-Day Checklist and Mock Exams (OCP 21)
The last stop before the 1Z0-830 exam: a chapter-by-chapter checklist of the rules that decide most questions, a time plan for 50 questions in 120 minutes, how to review mock exams, and three full 50-question mock exams.
kvi5hnuCode Sprout team member10 min readOn this page
You've worked through 92 articles, about 90 quizzes and 14 chapter reviews. This last article turns all of that into exam readiness: a compact checklist of the rules behind most questions, a plan for the 120 minutes, and three full mock exams of 50 questions each with the real exam's 68% pass mark.

How to use the mock exams
- Take each mock under exam conditions: 120 minutes in one sitting, with no IDE, no compiler, no notes and no searching. A plain sheet of paper stands in for the exam's scratch board.
- Afterwards, review every question you missed and every question you guessed, even if the guess was right. For each one, write down the rule you didn't know ("
List.ofrejectsnullelements"), not the letter of the answer. Then reread that article's Exam traps box. - Wait at least a day before the next mock, so you're not just remembering answers.
- Book the real exam when you score 80% or more on two mocks. The pass mark is 68%, but real questions can be phrased more awkwardly than any practice question, so a margin helps.
The three mocks are:
- Mock exam 1: 50 questions across all objectives
- Mock exam 2: 50 different questions, with somewhat more multi-select
- Mock exam 3: 50 questions, weighted toward the areas candidates find hardest (streams, concurrency, generics, modules, I/O)
The checklist: rules that decide most questions
Read this list the day before the exam. Each line is a rule that has appeared in several forms across the course. If one surprises you, go back to that chapter.
Building blocks and operators (chapters 1–2)
- A local variable must be definitely assigned before use. Fields and array elements get defaults.
varneeds an initializer, can't benullalone, and works only for locals. - Numeric promotion:
byte,shortandchararithmetic givesint.intoverflow wraps silently. Integer division truncates toward zero, and%takes the sign of the left operand. - Compound assignment (
+=) casts implicitly, but plain assignment doesn't: withshort s = 1;,s = s + 1;doesn't compile, whiles += 1;does. i++evaluates to the old value.&&and||short-circuit, while&and|don't.
Decisions and loops (chapter 3)
- Old-style
switchfalls through withoutbreak. Arrow-form cases never fall through. Aswitchexpression must be exhaustive and yields a value.yieldbelongs inside a block. - Pattern
switch: dominance order matters (a broader pattern can't come before a narrower one).case nullmust be written explicitly, and a sealed hierarchy can be exhaustive withoutdefault. - Unreachable code after
break,continue,returnorwhile(true)with nobreakis a compile error.
Core APIs (chapter 4)
Stringis immutable, so a method call whose result is ignored changes nothing.StringBuilderis mutable and its methods chain.==compares references, so pooled literals and compile-time constants match, butnew Stringdoesn't.Integercaches -128 to 127.BigDecimal.equalscompares scale too (2.0isn't equal to2.00), so compare values withcompareTo.java.timetypes are immutable.Periodcounts days, months and years, whileDurationcounts seconds and nanoseconds. Text blocks strip incidental indentation.
Methods and class design (chapters 5–7)
- Overload resolution tries an exact match first, then widening, then boxing, then varargs. Java is always pass-by-value, including for references.
- Initialization order: superclass static parts, subclass static parts, then for each object the superclass instance initializers and constructor, followed by the subclass's.
- Overriding: the same signature, a covariant return type, access no more restrictive, and no new or broader checked exceptions. Static methods are hidden, not overridden, and fields are never polymorphic.
- Records:
finalfields, accessors,equals,hashCodeandtoStringare generated. A compact constructor can't assign the fields directly withthis.x.sealedrequirespermits, or subclasses in the same file. Each subclass isfinal,sealedornon-sealed. - Interfaces: fields are
public static final. Methods can bedefault,staticorprivate. A class must override adefaultmethod it inherits from two interfaces.
Lambdas, collections and generics (chapters 8–9)
- Variables captured by a lambda must be effectively final. Know the shapes of the main functional interfaces:
Supplier,Consumer,Function,Predicate, theBiandUnary/Binaryversions, and the primitive versions. List.of,Set.ofandMap.ofare unmodifiable and rejectnull, andSet.of/Map.ofreject duplicates.Arrays.asListis fixed-size but its elements can be set.TreeSetandTreeMapneedComparableelements or aComparator. Generics are invariant: aList<Integer>isn't aList<Number>. Use? extendsto read and? superto write.
Streams (chapter 10)
- Nothing runs until a terminal operation. A stream can be used only once.
findFirst,anyMatchandlimitshort-circuit. Collectors.toMapthrows on duplicate keys without a merge function.groupingBybuilds aHashMapunless you ask for a different map.partitioningByalways has bothtrueandfalsekeys.Optional.get()on an emptyOptionalthrowsNoSuchElementException. UseorElse(always evaluated),orElseGet(lazy) ororElseThrow.
Exceptions and localization (chapter 11)
- Checked exceptions must be caught or declared. A multi-catch can't list related types, and its variable is implicitly final. Resources close in reverse order before
catchandfinallyrun. If thetryblock already threw, exceptions from closing are attached to it as suppressed exceptions. - A
returninfinallyoverrides everything.Locale,NumberFormat,DateTimeFormatterpatterns and resource-bundle lookup order are all tested.
Modules (chapter 12)
- In
module-info.java:requires(andtransitive),exports ... to,opens,uses,provides ... with. Automatic modules come from plain JARs on the module path, and the unnamed module is the class path. Knowjdeps,jlinkand the--module-pathand-moptions.
Concurrency (chapter 13)
start()begins a new thread, whilerun()runs on the current one. Shut down everyExecutorService, or use try-with-resources since Java 19.Future.get()blocks.count++isn't atomic. UseAtomicInteger,synchronizedor aLock, and remember thatunlock()belongs infinally. Parallel streams make no ordering promise unless you useforEachOrdered.
I/O (chapter 14)
FileandPathobjects don't touch the disk until a method does.resolve,relativizeandnormalizeare pure path arithmetic.Filesmethods throwNoSuchFileExceptionandFileAlreadyExistsException, unless an option likeREPLACE_EXISTINGchanges that.read()returns-1at the end andreadLine()returnsnull. Never closeSystem.out. Serialization skips constructors except the first non-serializable parent's no-arg constructor, and records' canonical constructors.
Exam-day plan
- 50 questions, 120 minutes works out to about 2.4 minutes each. Use the plan from article 1: a first pass of about 90 minutes that answers everything and marks the doubtful ones, then a second pass on the marked questions, and a hard stop with 5 minutes left to make sure nothing is blank. Unanswered questions score zero, and there's no penalty for guessing.
- Multi-select questions say how many answers to choose. Make sure you've selected exactly that many.
- For every code question, check in this order: does it compile? (imports, checked exceptions, unreachable code, types, effectively final), then does it throw? (null, casts, unmodifiable collections, closed resources, index bounds), and only then trace the output.
- When an option says "does not compile", find the exact line. If you can't point to one, that option is probably a distractor.
- Assume each question shows everything needed, with the usual imports, unless it says otherwise or the missing import is itself the point (article 1 covers these assumptions).
What's current
- 1Z0-830 tests Java 21 and is still offered. 1Z0-831 tests Java 25 and adds the features in article 92. The checklist above applies to both.
- Oracle sometimes adjusts the question count, time and pass mark. Check the official exam page when you book. This course follows the published 50 questions, 120 minutes and 68%.
- Practise on a current JDK with
javac --release 21, so the compiler enforces exactly the Java 21 rules.
Exam traps from this article
A complete example
The program below is a "trap sampler". Each line runs one classic exam rule from a different chapter and prints what really happens. Read each rule, predict the result, then compare it with the output. Any line you got wrong points straight to a chapter to review. The class suppresses two -Xlint warnings (lossy-conversions, fallthrough) on purpose, because those warnings flag the very traps on display.
import java.math.BigDecimal;
import java.time.*;
import java.util.*;
import java.util.function.*;
import java.util.stream.*;
public class Solution {
static int line;
static void show(String rule, Object result) {
System.out.printf(Locale.ROOT, "%2d. %-46s -> %s%n", ++line, rule, result);
}
static String overload(long x) { return "long"; }
static String overload(Integer x) { return "Integer"; }
static String overload(int... x) { return "varargs"; }
@SuppressWarnings("finally")
static int tryFinally() {
try { return 1; } finally { return 2; } // finally's return wins (and hides exceptions)
}
static StringBuilder order = new StringBuilder();
static class Parent {
static { order.append("Ps "); }
{ order.append("Pi "); }
Parent() { order.append("Pc "); }
}
static class Kid extends Parent {
static { order.append("Ks "); }
{ order.append("Ki "); }
Kid() { order.append("Kc"); }
}
sealed interface Coin permits Gold, Silver { }
record Gold(int grams) implements Coin { }
record Silver(int grams) implements Coin { }
static String value(Coin c) {
return switch (c) { // exhaustive: no default needed
case Gold g when g.grams() > 10 -> "heavy gold";
case Gold g -> "gold";
case Silver s -> "silver";
};
}
@SuppressWarnings({"lossy-conversions", "fallthrough"}) // these traps are deliberate; javac -Xlint warns about both
public static void main(String[] args) {
System.out.println("-- Chapters 1-3: building blocks, operators, decisions");
show("int overflow wraps silently", Integer.MAX_VALUE + 1);
show("integer division and remainder sign", (-7 / 2) + " " + (-7 % 2));
short s = 10;
s += 5.7; // compound assignment casts implicitly
show("short s = 10; s += 5.7", s);
int i = 3;
i = i++ + ++i; // 3 + 5
show("i = 3; i = i++ + ++i", i);
show("'a' + 1 and \"\" + 'a' + 1", ('a' + 1) + " " + ("" + 'a' + 1));
int day = 2;
var sb = new StringBuilder();
switch (day) { case 1: sb.append("one "); case 2: sb.append("two "); case 3: sb.append("three "); break; default: sb.append("other"); }
show("old switch falls through without break", sb.toString().strip());
System.out.println("-- Chapter 4: core APIs");
String a = "java", b = "ja" + "va", c = new String("java");
show("compile-time constant pooled; new String not", (a == b) + " " + (a == c) + " " + a.equals(c));
String t = "trim";
t.toUpperCase(); // result ignored: Strings are immutable
show("t.toUpperCase() without assignment", t);
show("StringBuilder is mutable, methods chain", new StringBuilder("abc").reverse().insert(1, "-").append('!'));
Integer x1 = 127, x2 = 127, y1 = 128, y2 = 128;
show("Integer cache: 127 == 127, 128 == 128", (x1 == x2) + " " + (y1 == y2));
show("BigDecimal equals vs compareTo", new BigDecimal("2.0").equals(new BigDecimal("2.00")) + " "
+ (new BigDecimal("2.0").compareTo(new BigDecimal("2.00")) == 0));
LocalDate d = LocalDate.of(2028, 2, 28);
d.plusDays(1); // immutable: result ignored
show("LocalDate is immutable; leap year 2028", d + " " + d.plusDays(1));
show("text block strips incidental indentation", """
one
two""".replace("\n", "|"));
System.out.println("-- Chapters 5-7: methods, class design, beyond classes");
show("overload(5): widening beats boxing/varargs", overload(5));
show("try { return 1 } finally { return 2 }", tryFinally());
new Kid();
show("init order: statics, then instance per class", order);
show("sealed + pattern switch with guard", value(new Gold(12)) + ", " + value(new Gold(3)) + ", " + value(new Silver(5)));
record Point(int x, int y) { }
show("records: equals by components", new Point(1, 2).equals(new Point(1, 2)) + " " + new Point(1, 2));
System.out.println("-- Chapters 8-10: lambdas, collections, streams");
List<Integer> fixed = Arrays.asList(1, 2, 3);
fixed.set(0, 9);
show("Arrays.asList: set works, add doesn't", fixed + " " + attempt(() -> fixed.add(4)));
show("List.of is unmodifiable and rejects null", attempt(() -> List.of(1).set(0, 2)) + " / "
+ attempt(() -> List.of((Object) null)));
var seen = new ArrayList<Integer>();
Stream<Integer> lazy = Stream.of(1, 2, 3).peek(seen::add);
show("no terminal operation, no work", "peeked " + seen.size());
show("then a short-circuit terminal op", lazy.filter(n -> n > 1).findFirst().orElse(-1) + ", peeked " + seen);
show("groupingBy + counting (TreeMap)", Stream.of("ant", "bee", "cat", "eel", "fox", "gnu")
.collect(Collectors.groupingBy(w -> w.charAt(1), TreeMap::new, Collectors.counting())));
Function<Integer, Integer> twice = n -> n * 2, plus3 = n -> n + 3;
show("andThen vs compose", twice.andThen(plus3).apply(5) + " " + twice.compose(plus3).apply(5));
show("Optional.empty().orElseGet", Optional.<String>empty().map(String::length).orElseGet(() -> -1));
System.out.println("-- Chapter 11+: exceptions and the rest");
show("unchecked from a stream lambda", attempt(() -> Stream.of("7", "x").map(Integer::parseInt).toList()));
show("Duration vs Period", Duration.ofMinutes(90) + " " + Period.ofMonths(14).normalized());
}
static String attempt(Supplier<?> action) {
try {
return String.valueOf(action.get());
} catch (RuntimeException e) {
return e.getClass().getSimpleName();
}
}
}
Output:
-- Chapters 1-3: building blocks, operators, decisions
1. int overflow wraps silently -> -2147483648
2. integer division and remainder sign -> -3 -1
3. short s = 10; s += 5.7 -> 15
4. i = 3; i = i++ + ++i -> 8
5. 'a' + 1 and "" + 'a' + 1 -> 98 a1
6. old switch falls through without break -> two three
-- Chapter 4: core APIs
7. compile-time constant pooled; new String not -> true false true
8. t.toUpperCase() without assignment -> trim
9. StringBuilder is mutable, methods chain -> c-ba!
10. Integer cache: 127 == 127, 128 == 128 -> true false
11. BigDecimal equals vs compareTo -> false true
12. LocalDate is immutable; leap year 2028 -> 2028-02-28 2028-02-29
13. text block strips incidental indentation -> one| two
-- Chapters 5-7: methods, class design, beyond classes
14. overload(5): widening beats boxing/varargs -> long
15. try { return 1 } finally { return 2 } -> 2
16. init order: statics, then instance per class -> Ps Ks Pi Pc Ki Kc
17. sealed + pattern switch with guard -> heavy gold, gold, silver
18. records: equals by components -> true Point[x=1, y=2]
-- Chapters 8-10: lambdas, collections, streams
19. Arrays.asList: set works, add doesn't -> [9, 2, 3] UnsupportedOperationException
20. List.of is unmodifiable and rejects null -> UnsupportedOperationException / NullPointerException
21. no terminal operation, no work -> peeked 0
22. then a short-circuit terminal op -> 2, peeked [1, 2]
23. groupingBy + counting (TreeMap) -> {a=1, e=2, n=2, o=1}
24. andThen vs compose -> 13 16
25. Optional.empty().orElseGet -> -1
-- Chapter 11+: exceptions and the rest
26. unchecked from a stream lambda -> NumberFormatException
27. Duration vs Period -> PT1H30M P1Y2M
Points to notice:
- Line 3:
s += 5.7compiles and truncates to 15, buts = s + 5.7wouldn't compile. - Line 4:
i++ + ++iwithi = 3is3 + 5. The final assignment replaces the effect of both increments. - Line 7:
"ja" + "va"is a compile-time constant, so it's pooled and equals"java"by==. - Line 14:
overload(5)pickslong, because widening is tried before boxing and varargs. - Line 16: all static initializers run first (parent, then child). Then, for the object, the parent's instance initializer and constructor run, followed by the child's.
- Lines 21 and 22: without a terminal operation
peeknever ran.findFirstthen stopped after the second element. - Line 27:
Period.normalized()turns 14 months into 1 year and 2 months, andDurationprints in ISO-8601 form.
Common questions
How many mocks should I pass before booking? Two at 80% or more under exam conditions is a solid signal. One high score straight after reviewing the same questions isn't.
What if I keep failing one area?
Take that chapter's review quiz again, reread the articles in that chapter, and write small programs that test each rule with javac --release 21. Compiling your own guesses is the fastest way to fix a misunderstanding.
Are the mock questions harder than the real exam? They're designed to be at the same level: long code, several rules combined in one question, and distractors built from common mistakes. The real exam's wording can be less direct, so leave yourself a margin.
Summary
- Take three mock exams under exam conditions, review every miss and guess down to the rule, and book when you reach 80% on two of them.
- On exam day, plan a 90-minute first pass, a second pass on marked questions and a hard stop with 5 minutes left, and leave no blanks.
- For every code question, check compilation, then exceptions, then output.
- The checklist above condenses the most-tested rules of all 14 chapters.
Practice quiz
Test yourself with the final review quiz: 10 exam-style questions with explanations. Then take the three mock exams: Mock exam 1, Mock exam 2 and Mock exam 3, each with 50 questions, a 120-minute limit and a 68% pass mark.
Previous: Java 22 to 25: What's New After the OCP 21 Exam (1Z0-831)
Related reading
- Java 22 to 25: What's New After the OCP 21 Exam (1Z0-831)
- Java Files Advanced: Attributes, walk, find, lines and mark/reset (OCP 21)
- Java Console and User Interaction: System.in, System.out, System.err and Console (OCP 21)
- Java Serialization: Serializable, transient, serialVersionUID and Records (OCP 21)
- Java Reading and Writing Files: I/O Streams, Buffered Readers and Files Methods (OCP 21)

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.