1Z0-830 — Oracle Java SE 21 Developer Professional Cheat Sheet

Cheat sheet: exam-prep reference for Oracle Java SE 21 Developer Professional (1Z0-830): Java 21 rules, APIs, modules, streams, JDBC, and traps.

Use the tables for a quick pre-exam check. Expand a topic’s notes for explanations, examples, and additional distinctions.

Scope and study context

Unless a question explicitly states that preview features are enabled, answer using standard Java SE 21 features only. Java 21 includes preview/incubator features, but exam-safe reasoning should not assume them.

  1. Review the tables and decision rules.
  2. Mark topics where you hesitate.
  3. Drill those topics in a question bank.
  4. Read explanations carefully, especially for compile-time errors and small output differences.

The real challenge on 1Z0-830 is rarely remembering one isolated API call. It is usually reading Java code exactly: scope, overload resolution, generics, stream laziness, exception flow, object identity, module visibility, concurrency behavior, and Java SE 21 language features.

High-yield topic map

AreaKnow coldCommon trap
Core languagenumeric promotion, var, initialization order, access control, overloading/overridingOverload chosen at compile time; override dispatched at runtime
OOPinterfaces, abstract classes, nested classes, enums, sealed types, recordsStatic methods are hidden, not overridden
Java 21 patternspattern matching for switch, record patterns, guarded patternsPattern dominance and null handling
Collections/genericsPECS, erasure, ordering, equality, mutability, sequenced collectionsList<?> is not a list you can add real elements to
Lambdas/streamsfunctional interfaces, method refs, lazy pipelines, collectors, OptionalorElse() evaluates eagerly; streams are single-use
Exceptionschecked vs unchecked, multi-catch, try-with-resources, suppressed exceptionsCatch order: specific before general
Modulesrequires, exports, opens, services, class path vs module pathPublic class is inaccessible outside module unless package is exported
Concurrencyexecutors, futures, synchronization, atomics, concurrent collections, virtual threadsvolatile gives visibility, not compound atomicity
I/O and NIO.2Path, Files, streams/readers/writers, resource closingnormalize() is syntactic; toRealPath() checks the file system
JDBCConnection, PreparedStatement, ResultSet, transactionsJDBC indexes are 1-based
Localization/timeLocale, ResourceBundle, DateTimeFormatter, Period, DurationMM is month; mm is minute
Secure codingimmutability, input validation, SQL injection, path traversalDo not expose mutable internals from records/classes

Compilation, execution, packages, and modules

Class path vs module path

ConceptClass pathModule path
Code locationUnnamed moduleNamed modules and automatic modules
Dependency modelAll visible classes searched by package/nameModule must read another module
EncapsulationPackage/public onlyModule exports control external access
Non-modular JARNormal class path entryAutomatic module with inferred name
Split packagesOften tolerated on class pathProblematic/invalid across resolved modules
Main run stylejava -cp ... pkg.Mainjava -p ... -m module/pkg.Main
Notes and examples
## Compile a modular application
javac --module-source-path src -d mods -m com.example.app

## Run a modular application
java --module-path mods -m com.example.app/com.example.app.Main

## Describe a modular JAR
jar --describe-module --file app.jar

Module directives

DirectiveMeaningExam use
requires m;Current module depends on mNeeded to compile against exported packages of m
requires transitive m;Re-export dependency to downstream modulesAPI module exposes types from another module
requires static m;Needed at compile time, optional at run timeCompile-only annotations or optional tooling
exports p;Public types in package p accessible to all reading modulesNormal API exposure
exports p to m;Qualified exportAPI visible only to named module(s)
opens p;Allows deep reflection at run timeFrameworks, serialization, dependency injection
opens p to m;Qualified reflective accessSafer than opening to everyone
uses S;Consumes service interface SWith ServiceLoader
provides S with Impl;Registers implementationProvider module declaration
open module m {}Opens all packages reflectivelyDoes not export all packages for compilation
module com.example.app {
    requires java.sql;
    requires transitive com.example.api;

    exports com.example.app.api;
    opens com.example.app.model to com.fasterxml.jackson.databind;

    uses com.example.spi.Reporter;
}

Module traps

TrapCorrect rule
public class is always accessibleOutside a named module, the package must also be exported
opens is the same as exportsopens is for deep reflection; exports is for compile-time/public access
Named modules can depend on class path codeNamed modules cannot read the unnamed module
requires transitive is always betterUse it only when your exported API exposes the dependency
Service provider must be exportedProvider package need not be exported just to be loaded as a service
Cyclic module dependencies are fineModule dependency cycles are not allowed

module-info.java

Example:

module com.example.app {
    requires com.example.service;
    exports com.example.api;
    opens com.example.model;
    uses com.example.spi.Plugin;
}
DirectiveMeaning
requiresThis module depends on another module.
requires transitiveDownstream modules also read the required module.
exportsMakes a package accessible at compile time and runtime to other modules.
exports ... toQualified export to specific modules.
opensAllows deep reflection at runtime.
opens ... toQualified opening to specific modules.
usesDeclares service consumption.
provides ... withDeclares service implementation.

High-yield distinction:

  • exports is about ordinary public type accessibility.
  • opens is about deep reflection.
  • A public class in a non-exported package is not necessarily accessible to other named modules.
  • The class path and module path have different visibility rules.

Core Java language rules

Declarations, access, and initialization

RuleRemember
Top-level type accesspublic or package-private only
Source file nameMust match the public top-level class/interface/record/enum name
Initialization orderSuperclass static, subclass static, superclass instance, superclass constructor, subclass instance, subclass constructor
Static membersBelong to class; can be hidden, not overridden
Instance initialization blocksRun before constructor body, after super()
final variableMust be assigned exactly once before use
protected outside packageAccessible through this, super, or a reference of the subclass type, not arbitrary superclass instances
Garbage collectionEligibility is based on reachability; System.gc() is only a request
Notes and examples

var quick rules

ValidInvalid / trap
Local variables with initializerFields, method parameters, method return types
Enhanced for variablesvar x; with no initializer
Lambda parameters when all explicit parameters use varMixing var and explicit/implicit lambda parameter styles
Inferred compile-time typeDynamic typing; it is not JavaScript-style var
var a = new int[] {1, 2};var a = {1, 2};
var names = List.of("Ada", "Linus");   // List<String>
var count = 10;                        // int, not Integer

// Valid: all lambda parameters use var
BiFunction<String, String, Integer> len =
        (var a, var b) -> a.length() + b.length();

Numeric, boolean, and text traps

TopicRule
Binary numeric promotionbyte, short, and char promote to int in arithmetic
Promotion orderdouble > float > long > int
Compound assignmentIncludes implicit cast: b += 1 can compile where b = b + 1 may not
Integer divisionTruncates toward zero
Floating NaNComparisons with NaN are false except !=
Wrapper equalityPrefer equals; do not rely on == object identity
String immutabilityConcatenation creates new strings unless optimized by compiler/runtime
StringBuilder.equalsDoes not compare contents unless overridden by another class; use toString() or compare manually
Text blocksPreserve newlines and use incidental indentation rules
_ identifierReserved; do not use as a variable name in standard Java 21 code

Control flow

FeatureKey exam rule
ifCondition must be boolean, not numeric
switch statementMay fall through with colon labels unless break, return, throw, etc.
switch expressionMust produce a value on every path; use yield in block arms
Arrow switch labelNo fall-through
forInit/update sections can contain comma-separated expressions
Enhanced forIterates arrays or Iterable; loop variable is a copy/reference, not the collection slot
LabelsWork with loops/blocks; break label exits labeled statement; continue label targets loop
int result = switch (grade) {
    case "A", "B" -> 1;
    case "C" -> {
        int adjusted = curve();
        yield adjusted;
    }
    default -> 0;
};

Primitives, wrappers, and promotion

ConceptQuick rule
Integer literalsDefault to int unless suffixed or context allows narrowing constant assignment.
Floating literalsDecimal floating literals default to double; use f/F for float.
Arithmetic promotionbyte, short, and char usually promote to int in arithmetic.
Compound assignmentx += y includes an implicit cast; x = x + y may not compile.
Wrapper comparison== compares references except when unboxing occurs. Prefer equals for value comparison.
AutoboxingCan create overload ambiguity or choose a less obvious method than widening.
null unboxingUnboxing null throws NullPointerException.

Common trap:

byte b = 1;
// b = b + 1;   // does not compile: int result
b += 1;         // compiles: implicit narrowing conversion

String, StringBuilder, and text blocks

Type/featureReview points
StringImmutable; methods return new strings. == checks reference identity.
String poolCompile-time constants may be interned; runtime concatenation may not be the same reference.
StringBuilderMutable; many methods return this; not synchronized.
StringBufferMutable and synchronized, but less commonly preferred.
Text blocksUse triple quotes; incidental indentation and final newline can affect exact output.

Watch for:

  • substring, replace, trim, strip, toLowerCase, and similar methods do not mutate the original String.
  • StringBuilder.equals() is not value-based like String.equals(). Unless overridden by a subclass, it uses object identity.
  • Text block questions may test spaces and newlines, not just visible words.

var rules

Valid useInvalid or restricted use
Local variable with initializerField declaration
Enhanced for variableMethod return type
Try-with-resources variableMethod parameter, except lambda parameters
Lambda parameters when all parameters use varvar x = null;
Annotated lambda parametersMixed lambda styles like (var a, b) -> ...

Examples:

var name = "java";        // String
var list = new ArrayList<String>();
// var value;             // does not compile
// var n = null;          // does not compile

var is not dynamic typing. The type is fixed at compile time.

Switch statements vs switch expressions

FeatureSwitch statementSwitch expression
Produces a valueNoYes
ExhaustivenessNot always requiredRequired
Arrow labelsAllowedAllowed
Colon labelsAllowed, may fall throughAllowed with care
Return from blockUse statementsUse yield for a value
int score = switch (grade) {
    case "A" -> 5;
    case "B" -> 4;
    default -> 0;
};

With a block:

int score = switch (grade) {
    case "A" -> {
        System.out.println("excellent");
        yield 5;
    }
    default -> 0;
};

Switch traps

TrapReview rule
Fall-throughColon-style labels can fall through unless break, return, throw, or similar control flow stops them. Arrow labels do not fall through.
ExhaustivenessSwitch expressions must cover all possible selector values.
default and nullTreat null deliberately. In Java SE 21 pattern switch code, look for case null; do not casually assume default is a null handler in ordinary switch reasoning.
Pattern dominanceA broader pattern before a narrower one can make the narrower case unreachable.
Guardswhen guards affect whether a pattern label applies.

OOP, interfaces, records, sealed classes, and patterns

Overloading vs overriding

FeatureOverloadingOverriding
ResolvedCompile timeRuntime
Based onReference type and argument typesActual object type
Return type onlyCannot overload by return type onlyCovariant return allowed
AccessAny valid overloadCannot reduce visibility
ExceptionsIndependentChecked exceptions must be same/narrower; unchecked flexible
Static methodsCan be overloadedHidden, not overridden
Private methodsCan be overloadedNot inherited; not overridden
final methodsCan be overloadedCannot be overridden
Notes and examples
class Parent {
    Number value() throws IOException { return 1; }
    static void label() {}
}

class Child extends Parent {
    @Override
    Integer value() throws FileNotFoundException { return 2; } // covariant + narrower
    static void label() {} // hides, does not override
}

Interface rules

RuleDetail
FieldsImplicitly public static final
Abstract methodsImplicitly public abstract unless default, static, or private
Default methodsInherited unless class/superclass method wins or conflict must be resolved
Static interface methodsCalled with interface name, not inherited as instance methods
Private interface methodsHelper methods for default/static methods
Conflict ruleClass wins; otherwise most specific interface wins; otherwise implementing class must override

Nested, local, and anonymous classes

TypeKey points
Static nested classNo enclosing instance required
Inner member classRequires enclosing instance; can access outer instance members
Local classDeclared inside block; can access effectively final local variables
Anonymous classExtends one class or implements one interface; cannot declare constructor
Lambda vs anonymous classIn lambda, this refers to enclosing instance; in anonymous class, this is the anonymous object

Enums

RuleDetail
Constants firstEnum constants must appear before fields/methods
ConstructorImplicitly private; never called with new
Methods/fieldsAllowed after semicolon
Per-constant behaviorConstants can override abstract/regular methods
APIvalues(), valueOf(String), name(), ordinal()
CollectionsPrefer EnumSet and EnumMap for enum keys/sets
TrapDo not persist or compare business meaning with ordinal()

Records

Records are transparent data carriers, but they are only shallowly immutable.

FeatureRule
Declarationrecord Point(int x, int y) {}
Generated membersPrivate final fields, public accessors x(), y(), canonical constructor, equals, hashCode, toString
InheritanceRecords are final and extend java.lang.Record
InterfacesRecords can implement interfaces
Extra fieldsStatic fields allowed; additional instance fields are not
Compact constructorValidate/normalize parameters; compiler assigns fields after body
Mutability trapA record component can reference a mutable object
record Money(BigDecimal amount, Currency currency) {
    Money {
        Objects.requireNonNull(amount);
        Objects.requireNonNull(currency);
        amount = amount.stripTrailingZeros(); // normalize parameter
    }
}

Sealed classes and interfaces

ModifierMeaning
sealedRestricts which classes/interfaces may directly extend/implement
permitsLists direct permitted subclasses unless inferable in same source context
final subclassStops the hierarchy
sealed subclassContinues restricted hierarchy
non-sealed subclassReopens extension below that type
sealed interface Shape permits Circle, Rectangle {}

record Circle(double radius) implements Shape {}
record Rectangle(double width, double height) implements Shape {}

Pattern matching and Java 21 switch

FeatureExam rule
instanceof patternPattern variable is in scope only where definitely matched
Record patternDeconstructs records, including nested record patterns
Pattern switchSupports type patterns and guarded patterns
GuardUse when, not a separate if label
DominanceBroader pattern before narrower pattern can make latter unreachable
ExhaustivenessSwitch expressions and pattern switches must cover all possibilities
nullWithout case null, a null selector throws NullPointerException
static String describe(Object obj) {
    return switch (obj) {
        case null -> "null";
        case String s when s.isBlank() -> "blank string";
        case String s -> "string: " + s;
        case Integer i -> "integer: " + i;
        case Point(int x, int y) -> "point " + x + "," + y;
        default -> "other";
    };
}

Records

Records are compact carriers for shallowly immutable data.

record Point(int x, int y) {}

The compiler provides:

  • private final fields for components
  • public accessor methods named x() and y()
  • canonical constructor
  • equals, hashCode, and toString

Record review table:

PointRule
InheritanceA record cannot extend another class and is implicitly final.
InterfacesA record can implement interfaces.
FieldsExtra instance fields are not allowed; static fields are allowed.
ConstructorsCanonical and compact constructors are common exam targets.
AccessorsAccessors are named after components, not getX().
MutabilityRecord fields are final, but referenced objects can still be mutable.

Compact constructor trap:

record Range(int start, int end) {
    Range {
        if (start > end) throw new IllegalArgumentException();
        // assignments to components happen automatically after this block
    }
}

Sealed classes and interfaces

Sealed types restrict which classes or interfaces can directly extend or implement them.

sealed interface Shape permits Circle, Rectangle {}

final class Circle implements Shape {}
non-sealed class Rectangle implements Shape {}

Rules to remember:

  • A sealed type lists permitted direct subclasses with permits, unless they are discoverable in the same compilation unit.
  • Each permitted direct subclass must declare exactly one of final, sealed, or non-sealed.
  • Sealed hierarchies support exhaustiveness checks in pattern switches.
  • Sealing controls direct inheritance, not object creation by itself.

Pattern matching

instanceof pattern:

if (obj instanceof String s) {
    System.out.println(s.length());
}

Pattern variable scope is flow-sensitive. The variable exists only where the compiler knows the pattern matched.

Common examples:

if (!(obj instanceof String s)) {
    return;
}
System.out.println(s.length()); // valid

Pattern switch:

String result = switch (obj) {
    case Integer i when i > 0 -> "positive integer";
    case Integer i -> "integer";
    case String s -> "string";
    case null -> "null";
    default -> "other";
};

Common traps:

  • Put narrower or guarded cases before broader cases.
  • case Object o can dominate later cases depending on selector type and exhaustiveness.
  • Guarded patterns with when are not the same as unguarded total patterns.
  • Record patterns deconstruct records but still follow type and scope rules.

Generics, arrays, and collections

Generics essentials

ConceptRule
Type erasureGeneric type info mostly removed at runtime
InvarianceList<Integer> is not a subtype of List<Number>
? extends TProducer: read as T; cannot add non-null values
? super TConsumer: can add T; read as Object
List<?>Read as Object; add only null
Generic arraysnew T[] and new List<String>[] are invalid
Reifiable typesRuntime-known types, such as raw types and unbounded wildcards
Raw typesCompile with warnings; can cause heap pollution
Erasure collisionCannot overload methods whose erased signatures conflict
Notes and examples

PECS: producer extends, consumer super.

static double total(List<? extends Number> nums) {
    return nums.stream().mapToDouble(Number::doubleValue).sum();
}

static void addDefaults(List<? super Integer> nums) {
    nums.add(1);
    nums.add(2);
}

Arrays vs collections

FeatureArraysGenerics/collections
VarianceCovariant: String[] is an Object[]Invariant: List<String> is not List<Object>
Runtime typeReifiedErased
Bad storeCan throw ArrayStoreExceptionUsually compile-time error
SizeFixedUsually dynamic
Primitive supportDirect: int[]Use wrappers or primitive streams

Collection selection matrix

NeedChooseNotes
Ordered, index-based, duplicatesArrayListFast random access; middle insert/remove can be costly
Frequent add/remove at endsArrayDequePreferred stack/queue implementation; no null elements
Unique elements, no order guaranteeHashSetRequires consistent equals/hashCode
Unique elements, insertion orderLinkedHashSetJava 21 sequenced behavior is useful
Unique sorted elementsTreeSetUses natural order or Comparator; compare consistency matters
Key-value lookupHashMapAllows one null key and null values
Key-value insertion orderLinkedHashMapUseful for predictable iteration/LRU-style patterns
Sorted keysTreeMapKeys must be comparable or comparator supplied
Enum keys/setsEnumMap, EnumSetCompact and efficient
Concurrent key-value accessConcurrentHashMapDoes not allow null keys/values
Read-heavy concurrent listCopyOnWriteArrayListWrites copy the array; expensive for frequent mutation
Producer/consumer handoffBlockingQueueCoordinates threads

Mutability and factory traps

APIBehavior
List.of, Set.of, Map.ofUnmodifiable; reject nulls; duplicate set elements/map keys fail
List.copyOfUnmodifiable copy; rejects nulls
Arrays.asList(array)Fixed-size list backed by array; set writes through; add/remove fail
Collections.unmodifiableList(list)Unmodifiable view backed by original list
Stream.toList()Unmodifiable result
Collectors.toList()No guaranteed implementation or mutability contract
Set duplicate logicBased on equals/hashCode for hash sets; comparator/compareTo for sorted sets

Sequenced collections in Java 21

InterfaceAdds/standardizesTypical implementations
SequencedCollection<E>getFirst, getLast, addFirst, addLast, removeFirst, removeLast, reversedList, Deque, linked collections
SequencedSet<E>Sequenced collection with uniquenessLinkedHashSet, sorted/navigable sets
SequencedMap<K,V>First/last entries and reversed viewLinkedHashMap, sorted/navigable maps

Generic type rules

ConceptQuick rule
InvarianceList<Integer> is not a subtype of List<Number>.
Upper bound? extends Number is good for reading Numbers, not adding arbitrary Numbers.
Lower bound? super Integer is good for adding Integers, reading as Object.
Raw typeDisables generic checking and can cause runtime ClassCastException.
Type erasureGeneric type parameters are mostly unavailable at runtime.
Generic arraysDirect creation like new List<String>[10] is not allowed.

PECS memory aid:

  • Producer extends: use ? extends T when the structure produces T values for you.
  • Consumer super: use ? super T when the structure consumes T values from you.

Collection factories and mutability

APIBehavior
List.of(...)Unmodifiable; rejects null.
Set.of(...)Unmodifiable; rejects null and duplicates.
Map.of(...)Unmodifiable; rejects null keys/values and duplicate keys.
Arrays.asList(array)Fixed-size list backed by the array; set allowed, add/remove not allowed.
List.copyOf(...)Unmodifiable copy; rejects null.
Collections.unmodifiableList(list)Unmodifiable view backed by original list. Changes to original may be visible.

Ordering and equality

CollectionOrderingDuplicate rule
ArrayListInsertion/index orderAllows duplicates
HashSetNo guaranteed iteration orderUses equals/hashCode
LinkedHashSetInsertion orderUses equals/hashCode
TreeSetSorted orderUses comparator or natural ordering
HashMapNo guaranteed key iteration orderOne value per key
LinkedHashMapPredictable encounter orderOne value per key
TreeMapSorted key orderComparator/natural ordering

Set/map trap: if compareTo or a comparator says two objects are equal, a TreeSet treats them as duplicates even if equals would differ.

Sequenced collections in Java SE 21

Java SE 21 adds sequenced collection abstractions for collections with a defined encounter order.

ConceptReview point
SequencedCollectionFirst/last access and reverse-order view concepts.
SequencedSetOrdered set behavior with first/last semantics.
SequencedMapOrdered map behavior with first/last entries and reversed views.
reversed()Often a view, so think about backing collection and mutability.

Do not assume every collection is sequenced. A hash-based collection without defined encounter order is different from an ordered collection.

Lambdas, method references, streams, and Optional

Functional interfaces

InterfaceMethodUse
Predicate<T>boolean test(T)Filtering, validation
Function<T,R>R apply(T)Mapping
Consumer<T>void accept(T)Side-effect operation
Supplier<T>T get()Lazy value creation
UnaryOperator<T>T apply(T)Same input/output type
BinaryOperator<T>T apply(T,T)Combine same-type values
Comparator<T>int compare(T,T)Sorting
Callable<V>V call() throws ExceptionTask with result/checked exception
Runnablevoid run()Task without result
Notes and examples

Primitive specializations avoid boxing: IntPredicate, IntFunction<R>, ToIntFunction<T>, IntSupplier, IntConsumer, IntUnaryOperator, ObjIntConsumer<T>.

Method reference forms

FormExampleEquivalent idea
StaticInteger::parseInts -> Integer.parseInt(s)
Bound instancename::toUpperCase() -> name.toUpperCase()
Unbound instanceString::lengths -> s.length()
ConstructorArrayList::new() -> new ArrayList<>()
Array constructorString[]::newn -> new String[n]

Stream pipeline rules

RuleDetail
SourceCollection, array, generator, file lines, etc.
Intermediate opsLazy; return another stream
Terminal opsTrigger processing and close the pipeline for reuse
Stateless opsmap, filter, peek
Stateful opssorted, distinct, limit, skip
Short-circuitingfindFirst, findAny, anyMatch, limit
Parallel streamsAvoid shared mutable state; ordering can reduce performance
Side effectsDangerous in map, filter, peek, especially parallel
Single useReusing a consumed stream throws IllegalStateException

Common stream operations

NeedOperation
Transform one-to-onemap
Transform one-to-manyflatMap
Primitive numeric streammapToInt, mapToLong, mapToDouble
Remove duplicatesdistinct
Sortsorted() or sorted(comparator)
Aggregate with identityreduce(identity, accumulator)
Mutable reductioncollect(...)
GroupCollectors.groupingBy
Partition by booleanCollectors.partitioningBy
Duplicate map keysUse Collectors.toMap(key, value, merge)
Map<Department, Long> counts =
    employees.stream()
             .filter(Employee::active)
             .collect(Collectors.groupingBy(
                 Employee::department,
                 Collectors.counting()
             ));

Map<String, Integer> salaryByName =
    employees.stream()
             .collect(Collectors.toMap(
                 Employee::name,
                 Employee::salary,
                 Integer::max
             ));

Optional traps

APIRule
get()Throws if empty; prefer safer methods
orElse(value)Eagerly evaluates value
orElseGet(supplier)Lazily calls supplier only if empty
orElseThrow()Throws NoSuchElementException if empty
mapWraps mapped result, empty if mapper returns null
flatMapMapper returns Optional directly
ifPresentOrElseHandles present and empty branches
Field/parameter useUsually avoid Optional as fields or parameters; best as return type

Exceptions and resource management

Exception hierarchy

TypeChecked?Must catch/declare?
ThrowableUsually yes, except Error/RuntimeException branchesUsually
ExceptionYes, except RuntimeException branchYes
RuntimeExceptionNoNo
ErrorNoNo; generally do not catch
Custom checked exceptionExtend ExceptionYes
Custom unchecked exceptionExtend RuntimeExceptionNo
Notes and examples

Catching and throwing rules

RuleExample/trap
Catch specific before generalcatch (IOException) before catch (Exception)
Multi-catch alternativesCannot be related by subclassing
Multi-catch variableEffectively final
Overriding checked exceptionsSame or narrower checked exceptions only
finallyRuns after try/catch unless VM exits or fatal termination
Return in finallyCan suppress/override earlier return or exception; avoid
Precise rethrowCompiler can infer narrower thrown types for effectively final catch variable

Try-with-resources

Resources must implement AutoCloseable or Closeable.

try (BufferedReader reader = Files.newBufferedReader(path);
     BufferedWriter writer = Files.newBufferedWriter(out)) {
    writer.write(reader.readLine());
}
RuleDetail
Close orderReverse declaration order
Resource variableEffectively final variables can be used as resources
Primary exceptionException from try body wins
Suppressed exceptionsExceptions from close() are attached to primary exception
AutoCloseable.closeCan throw Exception
Closeable.closeThrows IOException; close should be idempotent

Checked vs unchecked

TypeExamplesHandling
Checked exceptionsIOException, SQLExceptionMust be caught or declared.
Runtime exceptionsNullPointerException, IllegalArgumentException, ClassCastExceptionNot required to be caught or declared.
ErrorsOutOfMemoryError, StackOverflowErrorUsually not handled by application logic.

Try-with-resources

try (var in = Files.newBufferedReader(path);
     var out = Files.newBufferedWriter(otherPath)) {
    // use resources
}

Rules:

  • Resources must implement AutoCloseable or Closeable.
  • Resources close in reverse order of creation.
  • If both the try block and close operation throw, close exceptions may become suppressed exceptions.
  • Resource variables are effectively final inside the try block.

Catch and finally traps

TrapRule
Catch orderCatch more specific exceptions before more general ones.
Multi-catchAlternatives cannot have subclass/superclass relationships.
Multi-catch variableEffectively final.
finallyRuns after try/catch unless the JVM exits or similar extreme cases occur.
Return in finallyCan override a return or thrown exception; know it, but avoid it in real code.

Date/time, numerics, formatting, and localization

Date and time API

TypeRepresentsZone?
LocalDateDate onlyNo
LocalTimeTime onlyNo
LocalDateTimeDate and timeNo
ZonedDateTimeDate/time with time zone rulesYes
OffsetDateTimeDate/time with fixed offsetOffset only
InstantMachine timestampUTC instant
PeriodDate-based amountYears/months/days
DurationTime-based amountSeconds/nanos
ZoneIdRegion rules, such as Europe/ParisYes
ZoneOffsetFixed offset, such as +02:00Offset only
Notes and examples
TrapCorrect reasoning
LocalDateTime is a momentIt is not a global instant until combined with a zone/offset
Period.ofDays(1) equals Duration.ofDays(1)Around DST, calendar day and 24 hours can differ
Date/time types mutateJava time types are immutable
yyyy and YYYY are interchangeableYYYY is week-based year; use yyyy for calendar year
MM and mm are interchangeableMM month; mm minute
DateTimeFormatter fmt =
    DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")
                     .withLocale(Locale.US);

LocalDate date = LocalDate.parse("2026-06-18");
String text = LocalDateTime.now().format(fmt);

BigDecimal and numeric precision

NeedUse / avoid
Exact decimal money-like valuesBigDecimal
Construct exact decimalnew BigDecimal("0.10") or BigDecimal.valueOf(...)
Avoidnew BigDecimal(0.10) due binary floating approximation
Compare numeric valuecompareTo
Compare value and scaleequals
Division with non-terminating resultProvide scale/rounding mode
BigDecimal a = new BigDecimal("1.0");
BigDecimal b = new BigDecimal("1.00");

boolean sameNumber = a.compareTo(b) == 0; // true
boolean sameObjectValue = a.equals(b);    // false: scale differs

Localization

APIUse
LocaleLanguage, region, variant preferences
ResourceBundleLocale-specific messages/resources
NumberFormatNumber, percent, currency formatting
DateTimeFormatterLocale-aware date/time formatting
MessageFormatParameterized localized messages
CollatorLocale-sensitive string comparison
TrapRule
Hard-coded stringsUse resource bundles for localizable text
Missing bundle keyMissingResourceException
Default localeCan affect formatting/tests unexpectedly
MessageFormat quotesSingle quotes escape text; doubled single quote gives literal quote
Currency formattingLocale affects display format; currency itself may need explicit control

java.time

TypeRepresents
LocalDateDate without time zone
LocalTimeTime without date/time zone
LocalDateTimeDate and time without time zone
ZonedDateTimeDate and time with time zone
InstantMachine timestamp on UTC timeline
PeriodDate-based amount, such as years/months/days
DurationTime-based amount, such as seconds/nanos
  • java.time classes are immutable.
  • Months in LocalDate.of(year, month, day) are 1-based if using integers.
  • Prefer Month.JANUARY style in real code when clarity matters.
  • Period is date-based; Duration is time-based.
  • Time zones and daylight saving transitions can produce non-obvious results.

Formatting and localization

APIUse
DateTimeFormatterParse/format date-time values.
NumberFormatLocale-aware number, currency, percent formatting.
LocaleLanguage/country/variant identification.
ResourceBundleLocale-specific messages and resources.

Resource bundle review:

  • Lookup uses a fallback chain based on requested locale and base bundle.
  • Missing keys can throw MissingResourceException.
  • Localization questions often test which bundle is selected, not translation knowledge.

I/O, NIO.2, and serialization awareness

Byte vs character APIs

NeedAPI family
Binary bytesInputStream, OutputStream
Text charactersReader, Writer
Buffered byte I/OBufferedInputStream, BufferedOutputStream
Buffered text I/OBufferedReader, BufferedWriter
Formatted text outputPrintWriter, PrintStream
Object serializationObjectInputStream, ObjectOutputStream
Notes and examples
TrapCorrect rule
Reader/writer are for bytesThey are for characters
Platform default charset is always safePrefer explicit Charset, such as StandardCharsets.UTF_8
PrintWriter throws normal checked exceptions on writeIt often records errors; check checkError()
Serialization is safe for untrusted dataTreat deserialization of untrusted data as dangerous

NIO.2 Path and Files

APIUse
Path.of(...)Create a path object
resolveAppend/resolve child path
relativizePath from one path to another
normalizeRemove redundant . and .. syntactically
toAbsolutePathConvert to absolute path syntactically
toRealPathResolve real existing path, symlinks, file system checks
Files.existsExistence check; race-prone if followed by action
Files.copyCopy file/stream
Files.moveMove/rename
Files.deleteDelete or throw
Files.deleteIfExistsDelete if present
Files.walkRecursive lazy stream; close it
Files.listLazy directory stream; close it
Files.findRecursive search with predicate
try (Stream<Path> paths = Files.walk(root)) {
    paths.filter(Files::isRegularFile)
         .forEach(System.out::println);
}

Path traversal guard pattern

Path base = Path.of("/app/uploads").toRealPath();
Path candidate = base.resolve(userInput).normalize();

if (!candidate.startsWith(base)) {
    throw new SecurityException("Invalid path");
}

For existing files, use toRealPath() where appropriate to account for symbolic links and actual file-system resolution.

Path and Files

APIReview point
Path.of(...)Creates a path object; does not require the file to exist.
resolveCombines paths; if the second path is absolute, it may replace the first.
relativizeComputes relative path between compatible paths.
normalizeRemoves redundant . and .. where possible; does not access the file system.
toRealPathAccesses file system and resolves symbolic links depending on options.
Files.existsCan be affected by permissions and link options.
Files.linesReturns a lazy stream that should be closed.
Files.walkReturns a stream; close it, especially in long-running code.

Byte and character streams

Use caseCommon classes
Binary dataInputStream, OutputStream, Files.newInputStream
Character dataReader, Writer, Files.newBufferedReader
Buffered textBufferedReader, BufferedWriter
Object serialization conceptsObjectInputStream, ObjectOutputStream, Serializable
  • Byte streams are not character streams.
  • Character encoding matters when converting bytes to text.
  • Many I/O methods throw checked IOException.
  • Streams returned by file APIs may be lazy and need explicit closing or try-with-resources.

Concurrency and virtual threads

Threading building blocks

NeedAPI
Define no-result taskRunnable
Define result taskCallable<V>
Run task directlyThread
Manage task executionExecutorService
Delayed/periodic tasksScheduledExecutorService
Result handleFuture<V>
Completion pipelinesCompletableFuture
CPU work splittingFork/join, parallel streams
High-throughput blocking I/OVirtual threads
Shared-state protectionsynchronized, locks, atomics, concurrent collections
Notes and examples

Executors and futures

OperationMeaning
execute(Runnable)Fire-and-forget; no result
submit(Callable)Returns Future<V>
submit(Runnable)Returns Future<?>
Future.get()Blocks; wraps task exception in ExecutionException
cancel(true)Requests cancellation and may interrupt
shutdown()Stop accepting new tasks; existing tasks continue
shutdownNow()Attempts to interrupt/cancel queued/running tasks
awaitTerminationWaits after shutdown request

Virtual threads in Java 21

Virtual threads are standard in Java 21 and are useful for large numbers of blocking tasks.

try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
    Future<String> result = executor.submit(() -> fetchRemoteValue());
    System.out.println(result.get());
}
Choose virtual threads whenAvoid assuming
Many blocking I/O tasksThey make CPU-bound work faster automatically
Simple thread-per-request styleYou need large fixed thread pools
Code is mostly blocking APIsShared mutable state becomes safe
You want simpler concurrency codeSynchronization/pinning concerns disappear

Synchronization and memory visibility

ToolUseTrap
synchronizedMutual exclusion and visibilityLock is per object/class monitor
volatileVisibility for reads/writesNot atomic for count++
AtomicIntegerAtomic CAS-style updatesCompound invariants may still need locks
LongAdderHigh-contention countersNot for exact instantaneous value under concurrent updates
ReentrantLockExplicit lock/unlock, try-lockAlways unlock in finally
wait/notifyLow-level coordinationMust hold monitor; test condition in loop
sleepPause current threadDoes not release lock
joinWait for thread completionCan be interrupted
class Counter {
    private final AtomicInteger value = new AtomicInteger();

    int increment() {
        return value.incrementAndGet();
    }
}

Concurrent collections

CollectionUse
ConcurrentHashMapConcurrent key-value access; no null keys/values
CopyOnWriteArrayListMany reads, few writes
BlockingQueueProducer/consumer coordination
ConcurrentLinkedQueueNon-blocking queue
ConcurrentSkipListMapConcurrent sorted map

Core concurrency concepts

ConceptReview rule
ThreadRepresents an independent path of execution.
RunnableTask with no result and no checked exception from run.
Callable<V>Task with result and can throw checked exceptions.
ExecutorServiceManages task execution; remember shutdown.
FutureRepresents pending result; get can block and throw wrapped exceptions.
synchronizedProvides mutual exclusion and happens-before guarantees around monitor use.
volatileVisibility guarantee for reads/writes, not compound atomicity.
Atomic classesSupport atomic operations such as increment/compare-and-set.

Race condition trap:

count++; // read, add, write — not atomic

Use synchronization, locks, atomics, or concurrency-safe structures when shared mutable state is accessed by multiple threads.

Virtual threads in Java SE 21

Virtual threads are lightweight threads intended to make blocking, thread-per-task server-style code more scalable.

Review points:

  • Created with APIs such as Thread.startVirtualThread(...) or virtual-thread executors.
  • Useful for many blocking tasks, not for making CPU-bound algorithms automatically faster.
  • Avoid assuming thread identity, scheduling order, or timing.
  • Be careful with shared mutable state exactly as with platform threads.
  • Blocking while holding monitors or using certain native operations can reduce scalability.
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
    Future<String> f = executor.submit(() -> "done");
    System.out.println(f.get());
}

Concurrency traps

TrapCorrect reasoning
Calling run() directlyExecutes on current thread; does not start a new thread.
Calling start() twiceThrows IllegalThreadStateException.
Assuming output orderThread scheduling is not deterministic.
Ignoring interruptionInterrupted status and blocking methods matter.
Forgetting shutdown()Executor may keep application alive or leak resources.
Using non-thread-safe collectionsCan corrupt state or produce unpredictable results.
DeadlockCan occur when locks are acquired in inconsistent order.

JDBC quick reference

Core interfaces

InterfaceRole
DriverManagerObtain connections using JDBC URL
DataSourcePreferred managed connection factory in many applications
ConnectionDatabase session and transaction boundary
StatementStatic SQL; avoid for user input
PreparedStatementParameterized SQL; helps prevent SQL injection
CallableStatementStored procedures
ResultSetCursor over query results
SQLExceptionDatabase access error with SQL state/vendor code
Notes and examples

JDBC operation rules

RuleDetail
IndexingParameters and result-set column indexes are 1-based
CursorResultSet starts before first row; call next()
executeQueryFor SQL returning a ResultSet
executeUpdateFor DML/DDL returning update count
executeFor unknown/multiple result types
Auto-commitCommon default is auto-commit enabled on new connections
TransactionDisable auto-commit, then commit or rollback
ResourcesClose ResultSet, Statement, and Connection; use try-with-resources
BatchaddBatch, executeBatch
SQL injectionUse bind parameters, not string concatenation
String sql = "select name from employee where id = ?";

try (Connection con = dataSource.getConnection();
     PreparedStatement ps = con.prepareStatement(sql)) {

    ps.setLong(1, employeeId);

    try (ResultSet rs = ps.executeQuery()) {
        if (rs.next()) {
            return rs.getString("name");
        }
    }
}

Transaction pattern

try (Connection con = dataSource.getConnection()) {
    con.setAutoCommit(false);
    try {
        updateAccount(con, from);
        updateAccount(con, to);
        con.commit();
    } catch (SQLException e) {
        con.rollback();
        throw e;
    }
}

Core JDBC flow

Typical flow:

  1. Obtain Connection.
  2. Create PreparedStatement or Statement.
  3. Bind parameters if needed.
  4. Execute.
  5. Process ResultSet if returned.
  6. Commit/rollback when managing transactions.
  7. Close resources, usually with try-with-resources.
try (Connection con = dataSource.getConnection();
     PreparedStatement ps = con.prepareStatement(
         "select name from employee where id = ?")) {

    ps.setInt(1, id);

    try (ResultSet rs = ps.executeQuery()) {
        while (rs.next()) {
            System.out.println(rs.getString(1));
        }
    }
}

JDBC review table

TopicRule
Parameter indexesPreparedStatement parameters are 1-based.
Column indexesResultSet column indexes are 1-based.
CursorResultSet starts before the first row; call next().
executeQueryUsed for queries returning a result set.
executeUpdateUsed for DML/DDL-style operations returning an update count.
executeCan handle multiple result types; returns boolean indicating result set availability.
Auto-commitCommon default is auto-commit enabled; know when code disables it.
TransactionsUse commit and rollback when auto-commit is disabled.
SQL injectionPrefer PreparedStatement with bind parameters.

Common trap: PreparedStatement prevents SQL injection only when values are bound as parameters, not when user input is concatenated into SQL text before preparing.

Annotations and secure coding

Annotation rules

FeatureRule
RetentionSOURCE, CLASS, RUNTIME
TargetRestricts where annotation may appear
Element typesPrimitive, String, Class, enum, annotation, arrays of these
DefaultsAnnotation elements can declare default values
NullAnnotation element values cannot be null
Marker annotationNo elements
Single-value conventionElement named value may omit name
Repeatable annotationUses @Repeatable(container)
@InheritedApplies only to class inheritance, not methods/interfaces generally
Type-use annotationsCan target uses of types, not just declarations
Notes and examples
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface Audited {
    String value() default "standard";
}

Secure coding checklist

RiskSafer approach
SQL injectionPreparedStatement bind parameters
Path traversalResolve against trusted base, normalize, validate prefix, handle symlinks
Mutable internalsDefensive copies or unmodifiable views
Mutable record componentsCopy mutable inputs/accessors if invariants matter
Deserialization attacksAvoid untrusted deserialization; validate/filter when used
Sensitive data in stringsPrefer limited-lifetime structures where practical
Broad reflectionUse narrow opens ... to rather than open modules/packages
Overbroad exceptionsCatch what you can handle; preserve cause
Resource leaksTry-with-resources
Time zone bugsStore instants/offsets deliberately; format at boundaries

Common 1Z0-830-style traps checklist

Question patternFast check
“Which overload runs?”Use declared reference type and compile-time argument types
“Which override runs?”Use actual object type, unless method is static/private/final
Generic wildcard confusionextends read, super write
equals/hashCode with hash collectionsEqual objects must have equal hash codes
TreeSet removes “duplicates” unexpectedlyComparator/compareTo defines uniqueness
Stream result missing side effectsIntermediate operations are lazy until terminal op
Optional.orElse(expensive())Argument evaluated even when value present
switch with patternsCheck dominance, exhaustiveness, and null
Record immutabilityRecord is shallowly immutable only
List.of mutationThrows UnsupportedOperationException
Arrays.asList resizeadd/remove fail; set works
Date pattern typoMM month, mm minute; yyyy calendar year
JDBC parametersStart at 1, not 0
Try-with-resources exceptionClose exceptions may be suppressed
volatile count++Still not atomic
Module accesspublic is not enough without exported package
normalize() securityIt does not verify existence or symlinks
Preview syntaxNot exam-safe unless explicitly enabled

Exam-reading mindset

For code questions, classify the issue before calculating output.

First questionWhy it matters
Does it compile?Many distractors are compile-time errors caused by scope, generics, access, checked exceptions, pattern dominance, or illegal overrides.
If it compiles, what is initialized first?Static fields, instance fields, constructors, record constructors, and inheritance order often determine output.
Is the behavior deterministic?Streams, parallel code, threads, hash-based collections, and race conditions may not guarantee order.
Is the API mutable, immutable, fixed-size, or a view?List.of, Arrays.asList, Collections.unmodifiableList, reversed(), subList, and NIO streams behave differently.
Is a variable compile-time type or runtime type being used?Overloading is compile-time; overriding is runtime. Fields and static methods are not polymorphic.
Is a lambda or stream operation lazy?Intermediate stream operations do not run until a terminal operation.
Is the question asking for exact output or possible output?Concurrency, collection ordering, and parallel streams can make one “nice-looking” answer invalid.

High-yield Java SE 21 checklist

AreaMust-review pointsCommon traps
Java basicsprimitives, wrappers, String, StringBuilder, var, arrays, text blocksnumeric promotion, == vs equals, invalid var, array covariance
Control flowif, loops, labels, switch statements and expressionsyield, fall-through, exhaustiveness, case null, pattern dominance
OOPinheritance, overriding, overloading, interfaces, nested classesstatic hiding, private methods, covariant returns, checked exceptions
Records and sealed typesrecord constructors/accessors, sealed hierarchy rulesrecords are final; sealed subclasses must choose final, sealed, or non-sealed
Pattern matchinginstanceof, switch patterns, record patterns, guardspattern variable scope and dominated switch labels
Genericstype erasure, wildcards, bounds, raw typesinvariant generic types, List<?> add restrictions, heap pollution
CollectionsList, Set, Map, queues, deques, sequenced collectionsnull support, ordering, duplicate handling, immutable factories
Lambdas and streamsfunctional interfaces, method references, collectors, Optionalstream reuse, lazy execution, side effects, parallel ordering
Exceptionschecked/unchecked, try-with-resources, suppressed exceptionscatch order, close order, finally overriding results
Date/time/localizationjava.time, Period, Duration, formatters, resource bundlesimmutability, month numbering, time zone and DST assumptions
I/O and NIO.2Path, Files, streams, readers/writers, serialization conceptsrelative path resolution, resource leaks, lazy file streams
Concurrencythreads, executors, synchronization, atomics, virtual threadsraces, deadlocks, interruption, assuming virtual threads make CPU code faster
JDBCConnection, PreparedStatement, ResultSet, transactions1-based parameters/columns, next(), auto-commit, SQL injection
Modulesmodule-info.java, requires, exports, opens, servicesexported vs opened packages, class path vs module path

Object-oriented programming

Overloading vs overriding

TopicOverloadingOverriding
BindingCompile-timeRuntime polymorphism
Based onMethod name and parameter listSame signature after inheritance rules
Return typeNot enough by itselfSame or covariant return allowed
Static methodsCan be overloadedHidden, not overridden
Private methodsCan be redeclaredNot overridden
Checked exceptionsNot central to selectionCannot throw broader checked exceptions
Notes and examples

High-yield rule: the reference type selects overloaded methods; the runtime object selects overridden instance methods.

class A {
    void m(Object o) { System.out.print("A-Object"); }
    void n() { System.out.print("A"); }
}
class B extends A {
    void m(String s) { System.out.print("B-String"); } // overload
    @Override void n() { System.out.print("B"); }
}

A x = new B();
x.m("hi"); // A-Object
x.n();     // B

Constructors and initialization

Review order:

  1. Static fields and static initializers, superclass first.
  2. Instance fields and instance initializers, superclass first.
  3. Superclass constructor.
  4. Subclass instance fields/initializers and constructor body.

Constructor rules:

  • A constructor call to this(...) or super(...) must be the first statement when explicit.
  • If no constructor is declared, a default no-argument constructor is provided.
  • If any constructor is declared, no default constructor is automatically added.
  • Abstract classes can have constructors.
  • Interfaces do not have constructors.

Interfaces

Interface memberKey rule
FieldsImplicitly public static final.
Abstract methodsImplicitly public abstract unless default/static/private.
Default methodsInherited by implementing classes; conflicts must be resolved.
Static methodsCalled on the interface name, not inherited like instance methods.
Private methodsCan support default/static methods inside the interface.

Conflict rule: if a class inherits conflicting defaults, it must override and choose or provide behavior. A superclass instance method generally wins over an interface default.

Lambdas, method references, and functional interfaces

Core functional interfaces

InterfaceAbstract method shapeExample use
Predicate<T>T -> booleanfiltering
Function<T,R>T -> Rmapping
Consumer<T>T -> voidside effects
Supplier<T>() -> Tlazy creation
UnaryOperator<T>T -> Tsame-type transform
BinaryOperator<T>(T,T) -> Treductions
Comparator<T>(T,T) -> intsorting

Lambda rules:

  • Captured local variables must be final or effectively final.
  • The target type must be a functional interface.
  • Parameter types can be explicit, inferred, or all var; do not mix styles.
  • A block lambda with a non-void target must return a value on all paths.

Method reference forms:

FormExample
Static methodInteger::parseInt
Bound instance methodtext::toLowerCase
Unbound instance methodString::length
ConstructorArrayList::new

Streams and collectors

Stream pipeline structure

A stream pipeline has:

  1. Source: collection, array, file, generator, range.
  2. Intermediate operations: lazy transformations.
  3. Terminal operation: triggers processing and consumes the stream.
Operation typeExamples
Intermediatefilter, map, flatMap, sorted, distinct, limit, peek
TerminalforEach, collect, reduce, count, min, max, anyMatch, findFirst
Notes and examples
  • A stream cannot be reused after a terminal operation.
  • Intermediate operations do not run until a terminal operation.
  • peek is mainly for debugging; do not rely on it without a terminal operation.
  • findAny may return any matching element, especially with parallel streams.
  • forEach on a parallel stream does not preserve order; forEachOrdered attempts encounter order.

map vs flatMap

OperationResult shape
mapOne output element per input element.
flatMapEach input produces a stream that is flattened into one stream.

Example idea:

List<List<String>> groups = List.of(List.of("a", "b"), List.of("c"));

groups.stream()
      .flatMap(List::stream)
      .toList(); // ["a", "b", "c"]

Reduce and collect

TaskPrefer
Combine values into one valuereduce
Build a collection/map/string summarycollect
Group by classifierCollectors.groupingBy
Split into true/false groupsCollectors.partitioningBy
Count, sum, averageprimitive streams or summarizing collectors

Reduction trap: for parallel streams, accumulator and combiner must be associative and compatible with the identity. Side effects in reductions are a common source of wrong answers.

Optional

APIReview point
of(value)Throws if value is null.
ofNullable(value)Empty if value is null.
get()Throws if empty. Usually avoid unless presence is certain.
orElse(value)Evaluates the fallback eagerly.
orElseGet(supplier)Evaluates fallback lazily.
mapTransforms contained value.
flatMapAvoids nested Optional.

Secure and robust coding themes

Oracle Java SE 21 Developer Professional (1Z0-830) candidates should be comfortable recognizing safer coding choices in ordinary Java code.

ThemeExam-relevant habit
EncapsulationKeep fields private; expose controlled behavior.
ImmutabilityPrefer final fields and defensive copies for mutable inputs/outputs.
Input validationValidate boundaries before use.
SQL safetyUse bind parameters instead of string concatenation.
Serialization cautionDo not deserialize untrusted data casually.
Resource managementUse try-with-resources for closeable resources.
Concurrency safetyAvoid unsynchronized shared mutable state.
Error handlingDo not swallow exceptions without meaningful handling.

Common candidate mistakes

MistakeBetter exam habit
Reading code as intended instead of writtenTrace exact compile-time and runtime behavior.
Assuming all collections preserve insertion orderIdentify concrete collection type and contract.
Treating var as dynamicInfer the compile-time type immediately.
Forgetting stream lazinessMark the terminal operation before predicting side effects.
Reusing a streamA consumed stream cannot be reused.
Confusing overload and overrideResolve overload first by reference type and arguments.
Ignoring checked exceptionsAsk whether the method catches or declares them.
Assuming parallel stream orderLook for ordered terminal operations and source ordering.
Assuming virtual threads remove synchronization needsShared state still needs safe access.
Forgetting JDBC indexes are 1-basedParameters and result columns start at 1.
Confusing exports and opensCompile-time access and reflection are different.
Assuming records make deep immutable objectsComponent references can point to mutable objects.

Quick practice plan

Use this Cheat Sheet as a map for IT Mastery practice:

  1. Start with topic drills. Work small sets on language basics, OOP, records/sealed types, generics, streams, exceptions, modules, I/O, concurrency, and JDBC.
  2. Review every detailed explanation. For missed questions, identify whether the error was compilation, API behavior, output tracing, or concept confusion.
  3. Build a personal trap list. Include examples such as Arrays.asList, orElse eagerness, switch exhaustiveness, wildcard capture, and try-with-resources close order.
  4. Move to mixed sets. Once topic scores stabilize, use mixed original practice questions to simulate context switching.
  5. Finish with mock exams. Practice pacing and answer discipline. Do not change answers unless you find a specific code rule you missed.

Final review checklist before mock exams

You are ready for full-length practice when you can quickly answer:

  • Does this snippet compile?
  • Which overload is selected?
  • Which method is overridden at runtime?
  • Is the collection ordered, sorted, immutable, fixed-size, or a view?
  • Is a stream operation intermediate or terminal?
  • Can this lambda capture the variable?
  • Is the generic assignment safe, unsafe, or illegal?
  • What happens if this Optional is empty?
  • Which exception is caught, suppressed, or thrown?
  • Does the NIO operation normalize text or access the real file system?
  • Is this concurrency result deterministic?
  • Is this JDBC call using the right execution method and index?
  • Is this package exported, opened, both, or neither?

Next step: choose your weakest three topics from this page and work targeted question bank drills with original practice questions and detailed explanations before attempting another mixed mock exam.

Put the review into practice