1Z0-830 — Oracle Java SE 21 Developer Professional Quick Reference

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

Exam identity and use

This independent Quick Reference supports preparation for Oracle Java SE 21 Developer Professional (1Z0-830). Use it as a compact checklist for language rules, core APIs, Java 21 features, common traps, and decision points that are easy to miss under exam timing.

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.

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
## 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

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

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;
};

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
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";
    };
}

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

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

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

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

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

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
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

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
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.

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

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

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

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;
    }
}

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
@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

Practical next step

Use this Quick Reference as an error-log checklist: after each Oracle Java SE 21 Developer Professional (1Z0-830) practice set, mark every missed question by rule category, then write and run a minimal Java 21 snippet that proves the correct behavior.

Browse Certification Practice Tests by Exam Family