Skip to main content

Exam Tips & Quick Reference

Exam: 1Z0-830 โ€” 50 questions, 90 minutes, passing score: 68%

This page is the cross-chapter cram sheet (mnemonics, matrices, top traps). For topic explanations and chapter-specific exam tables and traps, work through the numbered chapters from the OCP introduction (e.g. Chapter 1 through Chapter 14).


High-Frequency Exam Topics

1. Output Tracing Questions

The most common question type. Practice tracing code mentally:

// What is the output?
int x = 5;
int y = x++ * --x;
System.out.println(x + " " + y);
// Step 1: x++ โ†’ returns 5, x becomes 6
// Step 2: --x โ†’ x becomes 5, returns 5
// y = 5 * 5 = 25
// Output: 5 25

Strategy: Write variable values on paper as you trace.


2. Compile vs Runtime Errors

Know which errors are compile-time vs runtime:

ScenarioError Type
Wrong types in expressionCompile
Missing throws for checked exceptionCompile
ClassCastExceptionRuntime
NullPointerExceptionRuntime
ArrayIndexOutOfBoundsExceptionRuntime
Missing break in switch (wrong result)No error โ€” logical bug

3. Java 21 New Features (Heavily Tested)

FeatureChapterKey API/Syntax
Records7record Point(int x, int y) {}
Sealed classes7sealed, permits, final/non-sealed
Pattern matching instanceof3, 6if (obj instanceof String s)
Pattern matching switch3case Integer i when i > 0
Virtual threads13Thread.ofVirtual(), newVirtualThreadPerTaskExecutor()
SequencedCollection9getFirst(), getLast(), reversed()
Text blocks1Triple-quote """..."""

Quick-Fire Mnemonics

Access Modifiers (widest โ†’ narrowest)

Public โ†’ Protected โ†’ Package โ†’ Private
"Pretty Please Provide Privacy"

Primitive Types (by size)

Boolean, Byte, Short, Int, Long, Float, Double, Char
"Be Bold, Silly Idiots Love Feeling Dangerously Clever"

Exception Types

  • Checked โ†’ must Check (handle or declare)
  • Unchecked โ†’ no check needed (RuntimeException + subclasses)
  • Error โ†’ never catch

PECS (Generics Wildcards)

Producer Extends, Consumer Super

  • Read from it โ†’ ? extends T
  • Write to it โ†’ ? super T

Common Exam Traps

String Traps

String s = "hello";
s.toUpperCase(); // โŒ ignored! String is immutable
// โœ… Must reassign: s = s.toUpperCase();

String a = "test";
String b = new String("test");
a == b; // FALSE (different objects)
a.equals(b); // TRUE (same content)

Autoboxing / Integer Cache

Integer a = 127; Integer b = 127;
a == b; // TRUE (cached range -128 to 127)

Integer c = 128; Integer d = 128;
c == d; // FALSE (outside cache range)

Compound Assignment Hidden Cast

byte b = 10;
b = b + 1; // โŒ COMPILE ERROR โ€” int assigned to byte
b += 1; // โœ… compound assignment includes implicit cast

switch Fall-Through

int x = 2;
switch (x) {
case 1:
case 2: System.out.println("two"); // no break!
case 3: System.out.println("three");
}
// Prints "two" AND "three" (fall-through!)

finally Always Runs

int tricky() {
try { return 1; }
finally { return 2; } // overrides the try's return!
}
// Returns 2, not 1

var Limitations

var x; // โŒ must initialize
var y = null; // โŒ type cannot be inferred
class MyClass { var z = 10; } // โŒ no fields
void method(var p) { } // โŒ no parameters

Pre/Post Increment

int i = 5;
int result = i++ + ++i;
// i++ โ†’ returns 5, i=6
// ++i โ†’ i=7, returns 7
// result = 5 + 7 = 12, i = 7

Functional Interface Cheatsheet

InterfaceMethodIn โ†’ Out
Supplier<T>get()() โ†’ T
Consumer<T>accept(T)T โ†’ void
Function<T,R>apply(T)T โ†’ R
Predicate<T>test(T)T โ†’ boolean
UnaryOperator<T>apply(T)T โ†’ T
BinaryOperator<T>apply(T,T)T,T โ†’ T
BiFunction<T,U,R>apply(T,U)T,U โ†’ R

Stream Operations Reference

OperationTypeShort-circuit?
filterIntermediateNo
map/flatMapIntermediateNo
sorted/distinctIntermediateNo
limit/skipIntermediatelimit yes
peekIntermediateNo
forEachTerminalNo
count/sumTerminalNo
collectTerminalNo
reduceTerminalNo
findFirst/findAnyTerminalYes
anyMatch/noneMatch/allMatchTerminalYes
min/maxTerminalNo

Collections Quick Comparison

CollectionOrderDuplicatesNullThread-Safe
ArrayListInsertionYesYesNo
LinkedListInsertionYesYesNo
HashSetNoneNoOne nullNo
LinkedHashSetInsertionNoOne nullNo
TreeSetSortedNoNoNo
HashMapNoneKeys: NoOne null keyNo
LinkedHashMapInsertionKeys: NoOne null keyNo
TreeMapSortedKeys: NoNo null keyNo
ArrayDequeFIFO/LIFOYesNoNo
ConcurrentHashMapNoneKeys: NoNoYes
CopyOnWriteArrayListInsertionYesYesYes

Module System Quick Reference

module com.myapp {
requires java.sql; // needs this module
requires transitive java.xml; // my users also get java.xml
requires static lombok; // compile-time only
exports com.myapp.api; // accessible to all
exports com.myapp.spi to partner; // accessible only to partner
opens com.myapp.model; // deep reflection allowed
uses com.spi.Service; // I'm a consumer
provides com.spi.Service with com.myapp.ServiceImpl; // I'm a provider
}

Operator Precedence Cheatsheet

1. () Parentheses (highest)
2. expr++ expr-- Post-unary
3. ++expr --expr - ! ~ Pre-unary
4. (type) Cast
5. * / % Multiply / divide / modulo
6. + - Add / subtract
7. << >> >>> Shift
8. < > <= >= instanceof Relational
9. == != Equality
10. & Bitwise AND
11. ^ Bitwise XOR
12. | Bitwise OR
13. && Conditional AND (short-circuit)
14. || Conditional OR (short-circuit)
15. ? : Ternary
16. = += -= *= /= etc. Assignment (lowest)

Code Output Tracing โ€” Step-by-Step Method

When asked "what is the output?", follow this exact process:

Step 1: Identify all variable declarations and their initial values.
Step 2: Trace each expression left-to-right using operator precedence.
Step 3: Note side effects (++, --) โ€” post happens after value is used, pre happens before.
Step 4: Follow any control flow (if, switch, loops).
Step 5: Check for inheritance โ€” which actual type is the object? That determines which method runs.

// Example to trace:
int a = 3, b = 5;
int c = a++ * --b + a;
// Step 1: a=3, b=5
// Step 2: a++ โ†’ uses 3, then a becomes 4
// Step 3: --b โ†’ b becomes 4, uses 4
// Step 4: 3 * 4 = 12
// Step 5: + a (a is now 4) = 12 + 4 = 16
// c = 16, a = 4, b = 4

Top 20 Exam Traps Across All Chapters

Must-Know Traps
// 1. String immutability
String s = "hello";
s.toUpperCase(); // ignored! s is still "hello"

// 2. Integer cache boundary
Integer a = 127; Integer b = 127; // a == b โ†’ true
Integer c = 128; Integer d = 128; // c == d โ†’ false

// 3. Compound assignment includes cast
byte b = 10;
b = b + 1; // โŒ compile error
b += 1; // โœ… implicit cast

// 4. switch fall-through
switch(x) { case 1: case 2: System.out.println("1or2"); case 3: System.out.println("3"); }
// If x==1 or x==2: prints BOTH "1or2" AND "3" (fall-through!)

// 5. finally overrides return
int f() { try { return 1; } finally { return 2; } } // always returns 2

// 6. var limitations
var x; // โŒ not initialized
var y = null; // โŒ type unknown
class C { var z = 1; } // โŒ no fields

// 7. Abstract class can have constructor (but can't be instantiated directly)
abstract class A { A() {} } // โœ…

// 8. Record accessors have NO "get" prefix
record Point(int x, int y) {}
new Point(1,2).x(); // โœ…
new Point(1,2).getX(); // โŒ NoSuchMethodError

// 9. Enum constructor is always private
enum Color { RED; public Color() {} } // โŒ compile error (can't be public)

// 10. Multi-catch cannot catch related types
catch (IOException | FileNotFoundException e) {} // โŒ related hierarchy

// 11. Streams are single-use
Stream<String> s = Stream.of("a","b");
s.count(); s.count(); // โŒ IllegalStateException on second call

// 12. Optional.get() throws on empty
Optional<String> o = Optional.empty();
o.get(); // โŒ NoSuchElementException

// 13. List.of() is immutable
List<String> l = List.of("a","b");
l.add("c"); // โŒ UnsupportedOperationException

// 14. TreeSet/TreeMap rejects null
new TreeSet<>().add(null); // โŒ NullPointerException

// 15. volatile โ‰  atomic
volatile int count = 0;
count++; // NOT thread-safe even with volatile

// 16. Static method called on null reference doesn't NPE
String s = null;
s.valueOf(42); // โœ… compiles and runs โ€” resolved to String.valueOf(42)

// 17. Files.lines() must be closed
Stream<String> lines = Files.lines(path); // resource leak if not closed!

// 18. transient fields are null after deserialization
transient String pwd = "secret"; // pwd == null after readObject()

// 19. Pattern matching variable scope
if (!(obj instanceof String s)) {
// s is NOT in scope here
} else {
s.length(); // โœ… s is in scope in the else branch
}

// 20. requires transitive gives implied readability
module A { requires transitive B; }
module C { requires A; } // C can use types from B without explicit requires B

Inheritance & Polymorphism Decision Tree

Is the method static?
โ”œโ”€โ”€ YES โ†’ Method HIDING (resolved at compile time by reference type)
โ””โ”€โ”€ NO โ†’ Method OVERRIDING (resolved at runtime by object type)

Is the member a field?
โ””โ”€โ”€ ALWAYS โ†’ Field HIDING (resolved at compile time by reference type)

What runs: Parent p = new Child(); p.method();
โ”œโ”€โ”€ method() is static โ†’ Parent.method() (hiding)
โ””โ”€โ”€ method() is instance โ†’ Child.method() (overriding)

Exception Flow Decision Table

ScenarioWhat Propagates
try throws, catch catches, no finallyNothing propagates
try throws, catch catches, finally throwsfinally exception propagates; catch exception lost
try throws, catch catches, finally returnsfinally return value used; exception swallowed
try throws, no matching catch, finally runsOriginal exception propagates after finally
try-with-resources: body throws, close() throwsBody exception propagates; close() exception becomes suppressed
try-with-resources: body OK, close() throwsclose() exception propagates normally

Access Modifier Matrix

Where accessed fromprivatepackageprotectedpublic
Same classโœ…โœ…โœ…โœ…
Same package, different classโŒโœ…โœ…โœ…
Different package, subclassโŒโŒโœ…*โœ…
Different package, non-subclassโŒโŒโŒโœ…

* protected in a subclass from a different package: only accessible through inheritance (via this or the subclass type), NOT via a parent-type reference.


Java 21 New Features โ€” Exam Highlights

FeatureSinceKey SyntaxExam Focus
Records16record Point(int x, int y) {}Accessors without get, immutability, compact constructor
Sealed classes17sealed class Shape permits Circle, Rect {}final/sealed/non-sealed subclasses, exhaustive switch
Pattern matching instanceof16if (o instanceof String s && s.length() > 3)Variable scope rules
Pattern matching switch21case Integer i when i > 0 ->Guard with when, null case, dominance
Virtual threads21Thread.ofVirtual().start(r)Best for I/O-bound; pinning with synchronized
SequencedCollection21.getFirst(), .getLast(), .reversed()New interface on List/Deque/LinkedHashSet
Text blocks15"""..."""Indentation stripping, trailing whitespace
switch expressions14int x = switch(n) { case 1 -> 10; default -> 0; }yield in block, exhaustiveness

Generics Wildcard Decision Guide

Do you need to READ from the collection?
โ””โ”€โ”€ Use ? extends T (upper bounded โ€” Producer Extends)
List<? extends Number> โ†’ can call .get(), returns Number
Cannot add (except null)

Do you need to WRITE to the collection?
โ””โ”€โ”€ Use ? super T (lower bounded โ€” Consumer Super)
List<? super Integer> โ†’ can add Integer and subtypes
.get() returns Object

Need both read and write?
โ””โ”€โ”€ Use a concrete type: List<Number>

Unbounded wildcard ?
โ””โ”€โ”€ Only when method doesn't care about element type at all
void printList(List<?> list) { list.forEach(System.out::println); }

Concurrency Quick Decision Guide

ScenarioBest Tool
Fire-and-forget background taskExecutorService.execute(Runnable)
Task with return valueExecutorService.submit(Callable) โ†’ Future
Chained async operationsCompletableFuture
Thread-safe counterAtomicInteger / AtomicLong
Mutual exclusionsynchronized or ReentrantLock
Visibility only (flag)volatile boolean
Thread-safe mapConcurrentHashMap
Thread-safe list for read-heavyCopyOnWriteArrayList
Many I/O tasks (Java 21)Executors.newVirtualThreadPerTaskExecutor()
Wait for N tasks to completeCountDownLatch
Synchronize N threads at a barrierCyclicBarrier

Last-Minute Checklist

Before your exam, confirm you know:

Primitives & Variables

  • All 8 primitive types, sizes, and defaults
  • long literal needs L; float literal needs f
  • var only for local variables; must initialize; can't be null
  • Underscore in literals: not at start, end, or beside decimal point

Operators

  • Pre-increment returns new value; post-increment returns original
  • &&/|| short-circuit; &/| do not
  • Compound assignment (+=) includes an implicit cast
  • NaN != NaN is always true

Control Flow

  • switch cannot use long, float, double, boolean
  • Arrow -> in switch: no fall-through; yield in block form
  • do-while body always runs at least once
  • break LABEL exits the labeled outer loop

OOP

  • super() must be first in child constructor; cannot combine with this()
  • Abstract class can have constructors; cannot be instantiated
  • final class cannot be extended; final method cannot be overridden
  • Fields are hidden (compile-time), not overridden (runtime)
  • Override: same/wider access; same/narrower exception; covariant return

Interfaces, Records, Enums, Sealed

  • Interface constants are implicitly public static final
  • Record accessors: x() not getX(); fields are private final
  • Enum constructor is always private
  • Sealed subclasses must be final, sealed, or non-sealed

Lambdas & Streams

  • Functional interface = exactly 1 abstract method
  • Effectively final: variable never reassigned after capture
  • andThen: current then next; compose: argument first then current
  • Stream is single-use; intermediate ops are lazy
  • allMatch/noneMatch return true for empty streams; anyMatch returns false
  • Optional.get() throws if empty โ€” prefer orElse/orElseGet

Collections

  • List.of() is immutable; ArrayList is mutable
  • TreeSet/TreeMap reject null; HashMap allows one null key
  • ArrayDeque rejects null; LinkedList allows it
  • poll() returns null if empty; remove() throws

Exceptions

  • Checked: must handle or declare; Unchecked: optional
  • try-with-resources: close in reverse order, BEFORE catch/finally
  • Multi-catch: types must be unrelated (no parent-child)
  • finally return overrides try return and swallows exceptions

Modules

  • exports = compile+runtime access; opens = reflection only
  • requires transitive = implied readability for dependents
  • Automatic module: JAR on module-path, no module-info.java
  • Unnamed module: classpath code; can't be required by name

Concurrency

  • start() creates thread; run() executes in current thread
  • volatile = visibility only; synchronized = visibility + atomicity
  • Virtual threads best for I/O-bound; avoid synchronized on I/O paths
  • ConcurrentHashMap does not allow null keys or values

I/O

  • Path methods are string operations โ€” no file system I/O
  • Files.lines() / Files.walk() return streams โ€” must close!
  • readLine() returns null at EOF, not an exception
  • transient and static fields are NOT serialized
  • Missing serialVersionUID change โ†’ InvalidClassException

Good luck on the exam! ๐ŸŽฏ You've got this!

๐Ÿ“–
Track Page Progress0 / 635 Read
Knowledge Base Completion0%