1Z0-829 — Oracle Java SE 17 Developer Quick Reference

Compact independent Quick Reference for Oracle Java SE 17 Developer (1Z0-829): Java 17 language rules, APIs, modules, streams, concurrency, I/O, JDBC, and exam traps.

This Quick Reference is for candidates preparing for Oracle Java SE 17 Developer (1Z0-829). Use it as a compact review of Java 17 syntax, core APIs, and exam-style distinctions. It is independent exam-prep support and is not affiliated with Oracle.

High-Yield Java 17 Exam Map

AreaKnow coldCommon exam traps
Language basicsprimitives, wrappers, operators, control flow, var, text blocksnumeric promotion, compound assignment casts, == vs equals, var limitations
OOPinheritance, overriding, access, interfaces, enums, nested typesstatic hiding vs overriding, initialization order, covariant returns, default method conflicts
Java 17 featuresrecords, sealed classes, pattern matching for instanceof, switch expressionsrecord constructor rules, permits, final/sealed/non-sealed, pattern variable scope
Exceptionschecked vs unchecked, try-with-resources, suppressed exceptionsclose order, multi-catch rules, overriding with checked exceptions
Generics and collectionswildcards, List/Set/Map/Queue, comparatorstype erasure, raw types, immutable factories, TreeSet/TreeMap ordering
Lambdas and streamsfunctional interfaces, pipelines, collectors, Optionallazy intermediate ops, stream reuse, orElse eagerness, parallel stream side effects
Date/time/localizationjava.time, Locale, formatters, resource bundlesimmutable date/time types, Period vs Duration, bundle lookup order
I/O and NIO.2Path, Files, byte/char streams, serializationlexical vs real path operations, lazy file streams, transient/static serialization
Concurrencythreads, executors, futures, synchronization, atomicsstart() vs run(), visibility vs atomicity, deadlock, non-thread-safe collections
Modulesmodule-info.java, requires, exports, opens, servicesreadability vs accessibility, class path vs module path, automatic/unnamed modules
JDBCConnection, PreparedStatement, ResultSet, transactions1-based parameters, cursor position, auto-commit, resource closing

Core Language Rules

Declarations, Scope, and var

FeatureRuleExam reminder
Local variable scopeBegins at declaration and ends at enclosing blockA variable is not in scope before its declaration
Instance field defaultNumeric 0, boolean false, object refs nullLocal variables have no default; must be definitely assigned
varLocal variable type inference at compile timeNot dynamic typing
var requires initializervar x = 10; validvar x;, var x = null;, var a = {1,2}; invalid
var locationsLocal variables and lambda parametersNot fields, method return types, formal method parameters, catch parameters
Lambda varIf one lambda parameter uses var, all explicit parameters must use var(var a, var b) -> a + b valid; (var a, b) -> ... invalid
ShadowingInner declarations may shadow fieldsLocal variables cannot be redeclared in the same scope
Effectively finalRequired for captured local variablesVariable must not be reassigned after capture
var names = List.of("Ana", "Bo");       // inferred List<String>
var nums = new int[] {1, 2, 3};         // valid
// var bad = {1, 2, 3};                 // invalid
// var none = null;                     // invalid

int count = 0;
// Runnable r = () -> count++;          // invalid: count not effectively final

Primitive Types, Literals, and Numeric Promotion

TopicRule
Integer literal defaultint unless suffixed with L/l
Floating literal defaultdouble unless suffixed with F/f
Underscores in literalsAllowed between digits only
charUnsigned 16-bit UTF-16 code unit; participates in numeric promotion
Arithmetic promotionbyte, short, and char promote to int before arithmetic
Binary numeric promotionIf either operand is double, result double; else float; else long; else int
Compound assignmentIncludes implicit narrowing cast
Constant narrowingCompile-time constants in range may assign to byte, short, char
byte b = 10;
// b = b + 1;       // invalid: b + 1 is int
b += 1;             // valid: implicit cast to byte

short s = 1;
char c = 2;
int result = s + c; // promoted to int

long x = 10;        // int literal widened to long
float f = 10.0f;    // suffix required for float literal

Operators and Evaluation

Operator areaKey rules
&&, `
&, `, ^`
== with primitivesCompares values after promotion
== with referencesCompares object identity
Mixed wrapper/primitiveWrapper is unboxed
Assignment expressionsReturn assigned value
Ternary ?:May trigger numeric promotion or boxing/unboxing
Pre/post incrementPrefix changes before value use; postfix changes after value use
Integer a = 1000;
Integer b = 1000;
System.out.println(a == b);      // false: different references likely
System.out.println(a.equals(b)); // true

Integer c = 10;
int d = 10;
System.out.println(c == d);      // true: c unboxed

Wrapper cache details can appear in questions, but the safer exam habit is: use equals() for value equality unless the question is specifically testing identity or unboxing.

Control Flow and Pattern Matching

if, Loops, Labels, and break/continue

ConstructRule
if conditionMust be boolean, not numeric
while / do whileCondition must be boolean
Enhanced forWorks with arrays and Iterable
break labelExits the labeled statement
continue labelContinues the labeled loop
Unreachable codeCompile-time error, except some special cases after non-constant conditions
outer:
for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 3; j++) {
        if (j == 1) continue outer;
    }
}

Switch Statements and Switch Expressions

FeatureSwitch statementSwitch expression
Produces valueNoYes
Fall-throughPossible with colon labelsNot with arrow labels
ExhaustivenessNot generally requiredRequired
yieldNot usedUsed to return a value from block cases
Case labelsCompatible constants, enum constants, strings, etc.Same core idea
defaultOptional for statementUsually needed unless exhaustive
int score = 2;

String grade = switch (score) {
    case 1 -> "low";
    case 2, 3 -> "mid";
    default -> {
        String label = "high";
        yield label;
    }
};

Pattern Matching for instanceof

PatternRule
obj instanceof String sIf true, s is a String pattern variable
ScopePattern variable is available where definitely matched
&&Pattern variable available on right side
`
Object obj = "java";

if (obj instanceof String s && s.length() > 2) {
    System.out.println(s.toUpperCase());
}

// if (obj instanceof String t || t.length() > 2) { } // invalid

Strings, Text Blocks, Arrays, and Formatting

String and StringBuilder

Type/APIKey facts
StringImmutable; methods return new strings
String literalsInterned
StringBuilderMutable, not synchronized, does not override equals()
StringBufferMutable and synchronized
substringEnd index exclusive
replaceReplaces all matching chars or sequences
stripUnicode-aware whitespace removal
trimRemoves characters <= '\u0020'
String.formatUses format specifiers and optional locale
Text blocksMulti-line strings using """; incidental indentation handled
String s = "abc";
s.concat("d");
System.out.println(s);       // abc

StringBuilder sb = new StringBuilder("abc");
sb.append("d");
System.out.println(sb);      // abcd

String text = """
        line one
        line two
        """;

Arrays

TopicRule
Declarationint[] a preferred; int a[] valid
Initializationnew int[3] gives default values
Anonymous arraynew int[] {1, 2, 3}
LengthArray field length, not method
Multidimensional arraysArrays of arrays; rows may be different lengths
CovarianceString[] is an Object[], but unsafe stores fail at runtime
Sorting/searchingArrays.sort, Arrays.binarySearch
ComparisonArrays.compare, Arrays.mismatch, Arrays.equals
Object[] values = new String[2];
// values[0] = new Object(); // ArrayStoreException at runtime

int[][] grid = new int[2][];
grid[0] = new int[] {1, 2};
grid[1] = new int[] {3};

Object-Oriented Java

Access Modifiers

ModifierSame classSame packageSubclass different packageOther package
privateYesNoNoNo
package-privateYesYesNoNo
protectedYesYesYes, through inheritance rulesNo general access
publicYesYesYesYes

High-yield rules:

  • Top-level classes can be public or package-private only.
  • A source file may contain multiple top-level classes, but at most one public top-level class.
  • The public top-level class name must match the file name.
  • protected across packages is not the same as package access; access must be through the subclass relationship.

Initialization Order

OrderWhat runs
1Static fields and static initializers of superclass
2Static fields and static initializers of subclass
3Instance fields and instance initializers of superclass
4Superclass constructor
5Instance fields and instance initializers of subclass
6Subclass constructor
class Parent {
    static { System.out.print("A"); }
    { System.out.print("B"); }
    Parent() { System.out.print("C"); }
}
class Child extends Parent {
    static { System.out.print("D"); }
    { System.out.print("E"); }
    Child() { System.out.print("F"); }
}
// new Child() after class loading prints: A D B C E F

Inheritance, Overriding, and Hiding

ConceptRule
OverridingInstance method in subclass replaces inherited instance method
Static method hidingStatic methods are hidden, not overridden
Field hidingFields are hidden, not overridden
Access on overrideCannot reduce visibility
Return typeMay be covariant
Checked exceptionsOverride cannot throw broader checked exceptions
final methodCannot be overridden
final classCannot be extended
abstract classCannot be instantiated; may have constructors
ConstructorNot inherited; first statement is this(...) or super(...)
class A {
    static void s() { System.out.print("A.s "); }
    void m() { System.out.print("A.m "); }
}
class B extends A {
    static void s() { System.out.print("B.s "); }
    @Override void m() { System.out.print("B.m "); }
}

A ref = new B();
ref.s(); // A.s: static method chosen by reference type
ref.m(); // B.m: instance method chosen by object type

Interfaces

Interface memberImplicit modifiers / rules
Fieldpublic static final
Abstract methodpublic abstract
Default methodInstance method with body; inherited by implementers
Static methodCalled using interface name
Private methodHelper for default/static methods
Private static methodStatic helper
ConstructorInterfaces do not have constructors

Default method conflict rules:

  1. Class method wins over interface default.
  2. More specific interface wins over less specific interface.
  3. If unrelated defaults conflict, implementing class must override.
interface A {
    default String name() { return "A"; }
}
interface B {
    default String name() { return "B"; }
}
class C implements A, B {
    public String name() {
        return A.super.name();
    }
}

Java 17 Class Forms

Records

Record featureRule
PurposeTransparent, shallowly immutable data carrier
Declarationrecord Point(int x, int y) {}
SuperclassImplicitly extends java.lang.Record; cannot extend another class
FinalityRecords are implicitly final
ComponentsPrivate final fields plus public accessor methods named after components
Generated methodsConstructor, accessors, equals, hashCode, toString
InterfacesRecords may implement interfaces
Extra fieldsStatic fields allowed; additional instance fields not allowed
Compact constructorNo parameter list; validates or normalizes component parameters
Canonical constructorParameter list matches record components
record Range(int start, int end) {
    Range {
        if (end < start) throw new IllegalArgumentException();
    }

    int length() {
        return end - start;
    }
}

Record traps:

  • Accessor is x(), not getX(), unless manually added.
  • Compact constructors assign component fields automatically after the body.
  • You may reassign constructor parameters in a compact constructor to normalize values.
  • Records are shallowly immutable; mutable component objects can still mutate internally.

Sealed Classes and Interfaces

ModifierMeaning
sealedRestricts direct subclasses/implementers
permitsLists permitted direct subclasses, unless inferable in same source context
final subclassCannot be extended further
sealed subclassContinues restriction
non-sealed subclassReopens hierarchy for further extension
sealed interface Shape permits Circle, Rectangle {}

final class Circle implements Shape {}

non-sealed class Rectangle implements Shape {}

class Square extends Rectangle {} // allowed because Rectangle is non-sealed

Exam reminders:

  • Every direct subclass of a sealed type must declare exactly one of final, sealed, or non-sealed.
  • Sealing controls direct inheritance, not object creation by itself.
  • A sealed class can be abstract or concrete.

Enums

Enum ruleDetail
ConstantsListed first; semicolon needed if members follow
ConstructorImplicitly private
SuperclassExtends java.lang.Enum; cannot extend another class
InterfacesEnums may implement interfaces
MethodsMay define fields, constructors, methods, abstract methods
Per-constant bodyConstants can override methods
Common APIsvalues(), valueOf(String), name(), ordinal()
enum Level {
    LOW(1), HIGH(2);

    private final int code;

    Level(int code) {
        this.code = code;
    }

    int code() {
        return code;
    }
}

Exceptions and Resource Management

Exception Type Rules

TypeChecked?Must handle or declare?
Exception excluding RuntimeException subclassesYesYes
RuntimeException and subclassesNoNo
Error and subclassesNoNo
Custom checked exceptionExtends Exception but not RuntimeExceptionYes
Custom unchecked exceptionExtends RuntimeExceptionNo

Try, Catch, Finally, and Multi-Catch

FeatureRule
Catch orderMore specific before more general
Multi-catchAlternatives cannot be related by subclassing
Multi-catch variableEffectively final
finallyRuns after try/catch unless abnormal VM termination
Return in finallyCan override previous return or thrown exception; usually a trap
Override exceptionsCannot broaden checked exceptions
try {
    throw new java.io.IOException();
} catch (java.io.FileNotFoundException e) {
    // more specific first
} catch (java.io.IOException | RuntimeException e) {
    // e is effectively final
}

Try-With-Resources

RuleExam detail
Resource typeMust implement AutoCloseable or Closeable
Close orderReverse order of declaration
Suppressed exceptionsExceptions from close() are suppressed if try block already threw
Effectively final resourcesExisting effectively final variables can be used
catch/finallyOptional
try (var in = new FileInputStream("a.txt");
     var out = new FileOutputStream("b.txt")) {
    in.transferTo(out);
} // out closes first, then in

Generics and Collections

Generics Essentials

ConceptRule
Type erasureGeneric type parameters are mostly removed at runtime
InvarianceList<String> is not a subtype of List<Object>
Raw typeDisables generic checks; may cause heap pollution
Generic methodType parameter before return type
Diamond operatorInfers type arguments from context
Bounded type<T extends Number>
Multiple boundsClass bound first, then interfaces
Cannot createnew T(), new T[], new List<String>[]
Cannot testobj instanceof List<String>
static <T extends Comparable<T>> T max(T a, T b) {
    return a.compareTo(b) >= 0 ? a : b;
}

Wildcards: PECS

NeedUseExample
Read values produced by collection? extends TList<? extends Number>
Write values consumed by collection? super TList<? super Integer>
Exact read/write of TList<T>Generic method
Unknown type?List<?>
List<? extends Number> nums = List.of(1, 2, 3);
Number n = nums.get(0);
// nums.add(4); // invalid except null

List<? super Integer> sink = new ArrayList<Number>();
sink.add(10);
Object value = sink.get(0);

Collection Selection Matrix

NeedChooseNotes
Ordered sequence with duplicatesArrayListFast random access
Frequent insert/remove at endsArrayDequeOften preferred over Stack/LinkedList for stack/queue behavior
Unique elements, no guaranteed orderHashSetUses hashCode and equals
Unique sorted elementsTreeSetRequires natural ordering or comparator
Unique insertion orderLinkedHashSetPredictable iteration
Key-value lookupHashMapMap is not a Collection
Sorted key-value lookupTreeMapSorted by key
Insertion-order mapLinkedHashMapPredictable iteration
Thread-safe high-concurrency mapConcurrentHashMapDoes not allow null keys or null values
Read-heavy thread-safe listCopyOnWriteArrayListWrites copy underlying array

Factory and Wrapper Methods

APIResultTrap
List.of(...)Unmodifiable listRejects null
Set.of(...)Unmodifiable setRejects null and duplicates
Map.of(...)Unmodifiable mapRejects null and duplicate keys
List.copyOf(...)Unmodifiable copyRejects null
Arrays.asList(array)Fixed-size list backed by arrayset allowed; add/remove not allowed
Collections.unmodifiableList(list)Unmodifiable viewUnderlying list changes are visible
Collections.sort(list)Sorts mutable list in placeNeeds comparable elements or comparator

Comparator and Comparable

APIPurpose
Comparable<T>Natural ordering via compareTo
Comparator<T>External ordering via compare
Comparator.comparingBuild comparator from key extractor
thenComparingTie-breaker
reversedReverse order
nullsFirst / nullsLastHandle null values
record Person(String name, int age) {}

var people = new ArrayList<Person>();
people.sort(
    Comparator.comparing(Person::name)
              .thenComparingInt(Person::age)
);

equals, hashCode, and ordering traps:

  • If two objects are equal by equals, they must have the same hashCode.
  • HashSet uniqueness uses equals and hashCode.
  • TreeSet uniqueness is based on comparison result 0.
  • Natural ordering inconsistent with equals can produce surprising set/map behavior.

Lambdas and Functional Interfaces

Built-In Functional Interfaces

InterfaceAbstract methodInputOutput
Predicate<T>testTboolean
Consumer<T>acceptTvoid
Supplier<T>getnoneT
Function<T,R>applyTR
UnaryOperator<T>applyTT
BinaryOperator<T>applyT, TT
BiPredicate<T,U>testT, Uboolean
BiConsumer<T,U>acceptT, Uvoid
BiFunction<T,U,R>applyT, UR
Runnablerunnonevoid
Callable<V>callnoneV, may throw checked exception
Comparator<T>compareT, Tint

Lambda Syntax and Method References

FormExample
Inferred parameterx -> x.length()
Explicit parameter type(String x) -> x.length()
Multiple parameters(a, b) -> a + b
Block bodyx -> { return x.length(); }
Static method referenceInteger::parseInt
Bound instance referenceSystem.out::println
Unbound instance referenceString::length
Constructor referenceArrayList::new
Predicate<String> nonEmpty = s -> !s.isEmpty();
Function<String, Integer> parse = Integer::parseInt;
Supplier<List<String>> makeList = ArrayList::new;

Lambda traps:

  • A lambda targets a functional interface, not just any type.
  • Checked exceptions must match the functional interface method.
  • this inside a lambda refers to the enclosing instance.
  • Captured local variables must be final or effectively final.
  • Parameter names cannot redeclare local variables already in scope.

Streams and Optionals

Stream Pipeline Rules

Pipeline partExamplesNotes
Sourcecollection, array, generator, file linesCreates stream
Intermediate operationfilter, map, sorted, distinct, peek, limit, skipLazy; returns stream
Terminal operationforEach, collect, reduce, count, findFirst, anyMatchTriggers processing; stream consumed
Stateless operationfilter, mapIndependent per element
Stateful operationsorted, distinct, limit, skipMay need more elements/state
Short-circuitinglimit, findFirst, findAny, anyMatch, allMatch, noneMatchMay stop early
long count = List.of("a", "bb", "ccc").stream()
        .filter(s -> s.length() > 1)
        .map(String::toUpperCase)
        .count();

Stream traps:

  • A stream cannot be reused after a terminal operation.
  • Intermediate operations do not run until a terminal operation occurs.
  • Avoid modifying the stream source during pipeline execution.
  • peek is mainly for debugging; do not rely on it for required side effects.
  • Parallel stream operations should be stateless, non-interfering, and associative where reduction is involved.

Common Stream Operations

OperationTypePurpose
filter(Predicate)IntermediateKeep matching elements
map(Function)IntermediateTransform one-to-one
flatMap(Function)IntermediateTransform one-to-many and flatten
distinct()IntermediateRemove duplicates by equals
sorted()IntermediateNatural sort
sorted(Comparator)IntermediateCustom sort
limit(n)IntermediateFirst n elements
skip(n)IntermediateDrop first n elements
takeWhileIntermediateTake until predicate becomes false
dropWhileIntermediateDrop until predicate becomes false
forEachTerminalApply action, order not guaranteed in parallel
forEachOrderedTerminalPreserve encounter order where defined
collectTerminalMutable reduction
reduceTerminalImmutable reduction
toList()TerminalReturns an unmodifiable list in modern Java
countTerminalNumber of elements
min / maxTerminalOptional result
findFirstTerminalFirst by encounter order
findAnyTerminalAny element, useful in parallel

Primitive Streams

StreamCommon methods
IntStreamrange, rangeClosed, sum, average, mapToObj, boxed
LongStreamrange, rangeClosed, sum, average, boxed
DoubleStreamsum, average, boxed
int total = IntStream.rangeClosed(1, 5).sum(); // 15
List<Integer> boxed = IntStream.range(1, 4).boxed().toList();

Collectors

CollectorResult
Collectors.toList()Mutable list implementation not guaranteed
Collectors.toSet()Set implementation not guaranteed
Collectors.toMap(k, v)Map; duplicate keys throw unless merge function supplied
Collectors.groupingBy(classifier)Map<K, List<T>> by classifier
Collectors.partitioningBy(predicate)Map<Boolean, List<T>>
Collectors.joining(delimiter)Concatenated string
Collectors.counting()Count as Long
Collectors.mapping(...)Downstream mapping
Collectors.filtering(...)Downstream filtering
Collectors.reducing(...)Downstream reduction
Map<Integer, List<String>> byLength =
    Stream.of("a", "bb", "cc")
          .collect(Collectors.groupingBy(String::length));

Map<Character, String> merged =
    Stream.of("ant", "ape")
          .collect(Collectors.toMap(
              s -> s.charAt(0),
              s -> s,
              (left, right) -> left + "," + right
          ));

Optional

MethodBehavior
of(value)Throws if value is null
ofNullable(value)Empty if value is null
empty()Empty optional
get()Returns value or throws if empty
isPresent / isEmptyPresence tests
ifPresentRun consumer when value exists
orElse(value)Eagerly evaluates fallback argument
orElseGet(supplier)Lazily calls supplier only if empty
orElseThrow()Throws if empty
mapTransform contained value
flatMapTransform to another optional without nesting
filterKeep value only if predicate matches
String value = Optional.of("java")
        .filter(s -> s.length() > 2)
        .map(String::toUpperCase)
        .orElse("NONE");

Dates, Times, and Localization

java.time Selection Table

NeedType
Date without time or zoneLocalDate
Time without date or zoneLocalTime
Date and time without zoneLocalDateTime
Date and time with zoneZonedDateTime
Machine timestampInstant
Time zone identifierZoneId
Zone offsetZoneOffset
Date-based amountPeriod
Time-based amountDuration
Month/day recurring dateMonthDay
Year/month recurring dateYearMonth
LocalDate date = LocalDate.of(2026, Month.JUNE, 18);
LocalDate next = date.plus(Period.ofDays(3));

LocalTime time = LocalTime.of(9, 30);
LocalTime later = time.plus(Duration.ofMinutes(45));

High-yield traps:

  • java.time classes are immutable.
  • LocalDate does not contain time or zone information.
  • Use Period for date-based units; use Duration for time-based units.
  • Month numbers are 1-based in factory methods.
  • Many date/time methods throw runtime exceptions for invalid dates or unsupported units.

Formatting and Parsing

APIPurpose
DateTimeFormatter.ISO_LOCAL_DATEStandard ISO local date
DateTimeFormatter.ofPatternCustom pattern
formatTemporal object to text
parseText to temporal object
NumberFormat.getCurrencyInstance(locale)Localized currency
NumberFormat.getPercentInstance(locale)Localized percent
CompactNumberFormat via NumberFormat.getCompactNumberInstanceLocalized compact numbers
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd");
String text = LocalDate.of(2026, 6, 18).format(fmt);
LocalDate parsed = LocalDate.parse(text, fmt);

Locale and Resource Bundles

ConceptRule
LocaleLanguage, country/region, optional variant/extensions
Buildernew Locale.Builder().setLanguage("en").setRegion("US").build()
Resource bundleLoads localized resources by base name and locale
Properties bundleKey-value .properties files
Class bundleJava class extending ListResourceBundle
Missing keyThrows MissingResourceException

Resource bundle search conceptually moves from most specific to less specific, then may consider default locale, then base bundle. For example, for base messages and locale fr_CA, candidates should recognize names such as:

messages_fr_CA
messages_fr
messages

I/O, NIO.2, and Serialization

Stream and Reader/Writer Selection

NeedUse
Binary inputInputStream
Binary outputOutputStream
Character inputReader
Character outputWriter
Buffered binary inputBufferedInputStream
Buffered character inputBufferedReader
Object serializationObjectInputStream, ObjectOutputStream
Filesystem utilitiesFiles
Path abstractionPath
try (BufferedReader reader = Files.newBufferedReader(Path.of("data.txt"))) {
    reader.lines()
          .filter(s -> !s.isBlank())
          .forEach(System.out::println);
}

Path and Files

APIKey point
Path.of(...)Creates path object
getFileNameLast name element
getParentParent path or null
getRootRoot component or null
isAbsoluteWhether path is absolute
toAbsolutePathConverts to absolute path; does not require file to exist
normalizeRemoves redundant . and .. lexically
toRealPathRequires file to exist; resolves real path
resolveCombine paths
relativizePath from one path to another; paths must be compatible
Files.existsChecks existence; result may be affected by permissions
Files.isSameFileCompares actual files
Files.copyCopy file/stream
Files.moveMove or rename
Files.deleteThrows if deletion fails
Files.deleteIfExistsNo exception if missing
Files.walk / find / listReturn lazy streams; use try-with-resources
Path p = Path.of("logs", ".", "app.log").normalize();
Path absolute = p.toAbsolutePath();

try (Stream<Path> paths = Files.walk(Path.of("src"))) {
    paths.filter(Files::isRegularFile)
         .forEach(System.out::println);
}

NIO.2 traps:

  • Many Path methods are lexical and do not access the filesystem.
  • Files.walk, Files.find, and Files.list must be closed.
  • Path iteration skips the root and iterates name elements.
  • resolve with an absolute right-hand path returns the right-hand path.

Serialization

FeatureRule
Serializable classImplements java.io.Serializable marker interface
transient fieldNot serialized
Static fieldNot part of serialized object state
serialVersionUIDVersion identifier field
Serializable superclassIts object state is serialized
Non-serializable superclassNo-arg constructor runs during deserialization
Serializable class constructorDoes not run during deserialization
Custom hooksPrivate writeObject / readObject methods
class User implements Serializable {
    private static final long serialVersionUID = 1L;

    private String name;
    private transient String sessionToken;
}

Concurrency

Thread Basics

ConceptRule
Thread.start()Starts a new thread and calls run() asynchronously
Thread.run()Normal method call if invoked directly
Restarting threadCalling start() twice on same thread throws runtime exception
RunnableNo return value, no checked exception from run
Callable<V>Returns value and may throw checked exception
sleepStatic method; pauses current thread
interruptRequests interruption; blocking methods may throw InterruptedException
Daemon threadDoes not prevent JVM exit
Runnable task = () -> System.out.println(Thread.currentThread().getName());
Thread t = new Thread(task);
t.start();

Executors and Futures

APIPurpose
ExecutorExecutes Runnable
ExecutorServiceManages lifecycle and task submission
submitReturns Future
executeNo result returned
Future.getBlocks; wraps task exceptions
invokeAllRuns collection of tasks; returns futures
invokeAnyReturns one successful result
shutdownStops accepting new tasks; existing tasks continue
shutdownNowAttempts to stop running tasks and returns pending tasks
ScheduledExecutorServiceDelayed or periodic execution
ExecutorService service = Executors.newFixedThreadPool(2);
try {
    Future<Integer> future = service.submit(() -> 40 + 2);
    Integer answer = future.get();
} finally {
    service.shutdown();
}

Synchronization, Visibility, and Atomicity

ToolUseTrap
synchronized method/blockMutual exclusion using monitorMust use same lock object
wait / notify / notifyAllCoordination through monitorMust own monitor; usually in loop
volatileVisibility guarantee for reads/writesDoes not make compound actions atomic
AtomicInteger etc.Lock-free atomic operationsOperations are atomic per method call
ReentrantLockExplicit lock/unlockUse finally to unlock
Concurrent collectionsThread-safe collection operationsIteration semantics differ
Parallel streamsData parallelismAvoid shared mutable state
class Counter {
    private final AtomicInteger value = new AtomicInteger();

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

Deadlock checklist:

  • Are two locks acquired in different orders?
  • Is a lock held while waiting for another lock?
  • Is external code called while holding a lock?
  • Is wait() used without a condition loop?

Java Platform Module System

module-info.java Directives

DirectiveMeaning
requires module.name;Current module reads another module
requires transitive module.name;Dependents also read the required module
requires static module.name;Required at compile time, optional at runtime
exports package.name;Public types in package accessible to other modules
exports package.name to module.name;Qualified export
opens package.name;Allows deep reflection at runtime
opens package.name to module.name;Qualified open
open module name {}Opens all packages for deep reflection
uses service.Interface;Declares service consumption
provides service.Interface with impl.Class;Declares service provider
java.baseRequired implicitly by every module
module com.example.app {
    requires java.sql;
    requires transitive com.example.api;

    exports com.example.app.api;
    opens com.example.app.model;

    uses com.example.spi.Plugin;
    provides com.example.spi.Plugin with com.example.impl.DefaultPlugin;
}

Module Decision Points

QuestionExam answer pattern
Need compile-time and runtime access to public exported API?requires plus provider module must exports package
Need clients of your module to read your dependency automatically?requires transitive
Need reflection into non-public members at runtime?opens, not just exports
Need restrict export to selected modules?Qualified exports ... to ...
Need service loading?Consumer uses uses; provider uses provides ... with ...
Need all packages open for reflection?open module
On class path?Code is in unnamed module
Plain JAR on module path?Automatic module

Module traps:

  • Readability and accessibility are separate: requires grants readability; exports grants access to public types in a package.
  • Packages are not exported by default.
  • Reflection into non-public members requires openness.
  • Named modules cannot generally depend on classes from the unnamed module.
  • Automatic modules export all packages and read other resolved modules.
  • Avoid split packages across named modules.

Useful Module Commands

javac -d mods --module-source-path src $(find src -name "*.java")

java --module-path mods \
     --module com.example.app/com.example.app.Main

jar --create --file app.jar \
    --main-class com.example.app.Main \
    -C mods/com.example.app .

jdeps --module-path mods --module com.example.app

JDBC

Core JDBC Objects

ObjectPurpose
DriverManagerGets connections using JDBC URL
DataSourceConnection factory, often preferred in managed environments
ConnectionDatabase session; transactions
StatementExecutes static SQL
PreparedStatementPrecompiled SQL with parameters
CallableStatementStored procedures
ResultSetCursor over query results
SQLExceptionJDBC checked exception
SQLWarningNon-fatal database warning

Statement Execution

MethodUse
executeQuerySQL returning a ResultSet, typically SELECT
executeUpdateDML/DDL returning update count
executeUnknown or mixed result type
getResultSetRetrieve result set after execute
getUpdateCountRetrieve update count after execute
String sql = "select id, name from users where status = ?";

try (Connection conn = DriverManager.getConnection(url);
     PreparedStatement ps = conn.prepareStatement(sql)) {

    ps.setString(1, "ACTIVE"); // JDBC parameters are 1-based

    try (ResultSet rs = ps.executeQuery()) {
        while (rs.next()) {
            int id = rs.getInt("id");
            String name = rs.getString("name");
        }
    }
}

ResultSet and Transactions

TopicRule
Cursor positionInitially before first row
next()Moves cursor and returns whether row exists
Column indexes1-based
Column labelsOften clearer than indexes
getInt on SQL NULLReturns 0; call wasNull() to distinguish
Auto-commitUsually enabled by default
Manual transactionsetAutoCommit(false), then commit or rollback
SavepointPartial rollback marker
Closing resourcesClose ResultSet, Statement, Connection; try-with-resources preferred
try (Connection conn = DriverManager.getConnection(url)) {
    conn.setAutoCommit(false);
    try (PreparedStatement ps = conn.prepareStatement(
            "update account set balance = balance - ? where id = ?")) {
        ps.setBigDecimal(1, amount);
        ps.setLong(2, accountId);
        ps.executeUpdate();
        conn.commit();
    } catch (SQLException e) {
        conn.rollback();
        throw e;
    }
}

Annotations

AnnotationPurpose
@OverrideCompile-time check that a method overrides or implements
@DeprecatedMarks API as discouraged
@SuppressWarningsSuppresses compiler warnings
@FunctionalInterfaceConfirms interface has one abstract method
@SafeVarargsSuppresses heap pollution warnings for safe varargs usage
@RetentionControls annotation availability: SOURCE, CLASS, RUNTIME
@TargetControls legal annotation locations
@RepeatableAllows repeated annotation of same type
@InheritedClass-level annotation inheritance only
@DocumentedIncluded in generated documentation

Annotation element rules:

  • Element types may be primitives, String, Class, enum, annotation, or arrays of those.
  • Element defaults must be compile-time constants where applicable.
  • If the only required element is named value, the name may be omitted.
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@interface Reviewed {
    String value();
    int version() default 1;
}

@Reviewed("exam")
class Service {}

Final Exam-Prep Checklist

Compilation and Syntax Traps

  • Check whether code fails at compile time before reasoning about runtime output.
  • Verify imports, access modifiers, checked exceptions, and generic type compatibility.
  • Watch for local variables that are not definitely assigned.
  • Remember that var is compile-time inference, not runtime typing.
  • Distinguish overloaded method selection at compile time from overridden method dispatch at runtime.
  • Check whether a lambda target type permits checked exceptions.
  • Confirm whether a stream has a terminal operation and whether it is reused.

API Behavior Traps

  • String, LocalDate, LocalTime, LocalDateTime, and most java.time types are immutable.
  • StringBuilder.equals() uses object identity unless comparing same reference.
  • List.of, Set.of, and Map.of are unmodifiable and reject null.
  • Arrays.asList is fixed-size and backed by the array.
  • TreeSet and TreeMap need consistent ordering.
  • Optional.orElse evaluates its argument eagerly; orElseGet is lazy.
  • Files.walk, Files.find, and Files.list return streams that should be closed.
  • PreparedStatement parameters and ResultSet column indexes are 1-based.
  • volatile improves visibility, not compound atomicity.
  • exports is for API access; opens is for deep reflection.

Practical Next Step

Use this Quick Reference as a checklist while working timed Oracle Java SE 17 Developer (1Z0-829) practice questions. For every missed item, classify the miss as syntax, API behavior, inheritance/dispatch, generics, stream pipeline, concurrency, modules, or JDBC, then drill that category with small compilable code examples.

Browse Certification Practice Tests by Exam Family