1Z0-829 — Oracle Java SE 17 Developer Cheat Sheet

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

This Cheat Sheet 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.

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

Scope and study context

This page is IT Mastery review support. It is not affiliated with Oracle and does not replace Oracle’s official exam information.

  1. Scan the tables first. Mark anything you cannot explain without looking it up.
  2. Run topic drills immediately after each weak area. Java exam misses often come from small compile-time or runtime details.
  3. Practice with code mentally and in an IDE. The real challenge is usually not knowing an API exists; it is predicting exact behavior.
  4. Use detailed explanations to fix patterns. If you miss several questions on streams, generics, modules, or date/time, slow down and rebuild the rule set.

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
Notes and examples
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.

Source files, packages, imports, and main

TopicRule to rememberCommon trap
One public top-level typePublic top-level type name must match the file nameNon-public top-level classes can share a file
Package declarationIf present, it comes before imports and type declarationsComments can appear before it; imports cannot
Importsimport package.Type; or import package.*;Wildcard import does not import subpackages
Static importsImport static members by name or wildcardAmbiguous static imports can cause compile errors
main methodCommon form: public static void main(String[] args)String... args is equivalent; wrong return type is not an entry point
java.langImported automaticallyOther packages are not

Identifiers, var, and scope

FeatureValid useInvalid or risky use
var local variable inferenceLocal variables with an initializerFields, method parameters, return types
var initializervar n = 10;var x = null; because type cannot be inferred
Lambda parametersCan use var for all lambda parametersCannot mix var and explicit/implicit parameter styles
ScopeLocal variables live within their blockShadowing can hide fields or outer variables

Remember: var does not make Java dynamically typed. The type is inferred at compile time and then fixed.

Primitive types and numeric promotion

AreaRule
Integer literalsDefault type is int unless suffixed or context requires otherwise
Floating literalsDefault type is double; use f or F for float
byte, short, char arithmeticPromoted to int in most arithmetic expressions
Compound assignmentIncludes an implicit cast, so short s = 1; s += 1; can compile where s = s + 1; may not
DivisionInteger division truncates toward zero
OverflowInteger overflow wraps; it does not throw an exception
BooleanNot numeric; cannot be used as 0 or 1

High-yield example: char + char produces an int, not a char.

Equality and object identity

ExpressionMeaningTrap
a == b for primitivesNumeric or boolean value comparisonNumeric promotion may occur
a == b for referencesSame object referenceNot logical equality
a.equals(b)Type-specific equality if overriddenMay throw NullPointerException if a is null
Objects.equals(a, b)Null-safe equalityUseful for exam reasoning
RecordsGenerated equals compares record componentsComponent equality still depends on component types
StringsString literals may be internedDo not assume new String("x") == "x"

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
Notes and examples
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

if, loops, labels, break, and continue

ConstructReview point
if / elseelse binds to the nearest unmatched if
whileCondition checked before body
do whileBody executes at least once
Basic forInit, condition, update sections are optional
Enhanced forIterates arrays or Iterable objects
LabelsCan label loops and blocks, but most useful with nested loops
breakExits loop or switch; labeled break exits labeled statement
continueSkips to next loop iteration; labeled continue targets a loop

Enhanced for gives you the element value/reference, not an index. Reassigning the loop variable does not replace array or collection elements.

Switch statements and switch expressions

FeatureSwitch statementSwitch expression
PurposeControl flowProduces a value
Fall-throughPossible with colon labelsArrow labels do not fall through
Value requiredNoYes, every path must produce a value or throw
yieldNot used in classic statement styleUsed to return a value from block cases
ExhaustivenessLess strictMore strict

Common switch-compatible types include integral types and wrappers, String, enums, and certain other supported forms. Do not treat boolean, long, float, or double as normal switch selector types.

High-yield traps:

  • case labels must be compatible constants or valid case forms.
  • default is optional in some statements but often needed in expressions.
  • Arrow case syntax and colon case syntax behave differently.
  • Missing break in colon-style statements can cause fall-through.

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
Notes and examples
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};

String, StringBuilder, and text blocks

Type / featureKey propertiesExam trap
StringImmutableMethods return a new String; original unchanged
StringBuilderMutable, not synchronizedMethods usually mutate and return same builder
StringBufferMutable, synchronizedLess common in modern code
Text blocksMultiline string literals using triple quotesIncidental indentation and trailing newline behavior can matter
String comparisonUse .equals for content== checks reference identity

Common String methods to know: charAt, indexOf, substring, replace, trim, strip, isBlank, startsWith, endsWith, contains, split, join, format.

Important distinction:

MethodFocus
trim()Removes characters with code points less than or equal to U+0020
strip()Uses Unicode whitespace awareness
isEmpty()Length is zero
isBlank()Empty or only whitespace

Formatting numbers and text

Know the broad roles:

APIUse
String.formatFormat text using format specifiers
NumberFormatLocale-sensitive number, currency, and percent formatting
DecimalFormatCustom numeric patterns
DateTimeFormatterDate/time parsing and formatting

Pattern letters are case-sensitive. For date/time formatting, M and m are not interchangeable: month versus minute is a frequent trap.

Object-Oriented Java

Access Modifiers

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

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

Initialization order

For a new object, reason in this order:

  1. Load and initialize needed classes.
  2. Initialize superclass static fields and static blocks.
  3. Initialize subclass static fields and static blocks.
  4. Allocate object memory with default values.
  5. Run superclass instance fields, instance initializer blocks, and constructor.
  6. Run subclass instance fields, instance initializer blocks, and constructor.

Within a class, fields and initializer blocks execute in textual order.

High-yield trap: overridden methods called from constructors use dynamic dispatch, so subclass methods may run before subclass fields are fully initialized.

Access modifiers

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

protected is commonly misunderstood. A subclass in another package does not get unrestricted access to every protected member on every superclass reference.

Overloading, overriding, and hiding

ConceptDecided whenKey rule
OverloadingCompile timeSame method name, different parameter list
OverridingRuntime dispatchInstance method in subclass replaces superclass behavior
Static method hidingCompile time reference typeStatic methods are not polymorphic
Field hidingCompile time reference typeFields are not polymorphic
Covariant returnOverride may return subtypeMust still satisfy method contract
Checked exceptionsOverride cannot throw broader checked exceptionsRuntime exceptions are not restricted the same way

Overload resolution often chooses the most specific applicable method. Widening, boxing, varargs, and inheritance can interact; practice these with original practice questions until the selection order feels automatic.

Abstract classes, interfaces, enums, records, and sealed types

TypeHigh-yield facts
Abstract classCan have constructors, fields, concrete methods, abstract methods
InterfaceMethods are commonly public abstract; can also have default, static, and private methods
EnumConstants come first; constructors are implicitly private; can have fields and methods
RecordConcise immutable data carrier; final; generated constructor, accessors, equals, hashCode, toString
Sealed class/interfaceRestricts direct permitted subclasses/implementors
Non-sealed subtypeReopens inheritance below a sealed hierarchy
Final subtypeEnds inheritance branch

Records:

  • Components become private final fields plus public accessor methods.
  • Accessor names are component names, not JavaBean getX names by default.
  • A compact constructor cannot assign directly to component fields before the implicit assignment.
  • Records can implement interfaces.
  • Records cannot declare additional instance fields beyond record components, but they can declare static fields.

Sealed types:

  • Direct subclasses must be permitted.
  • Direct subclasses must declare final, sealed, or non-sealed.
  • Sealed hierarchies are a common source of compile-time questions.

Pattern matching for instanceof

Pattern matching reduces casting:

  • Traditional idea: check type, then cast.
  • Java 17 style: if (obj instanceof String s) { ... }.

Review points:

RuleTrap
Pattern variable is available only where definitely matchedNot visible outside invalid scope
Null does not match an instanceof patternnull instanceof Type is false
Pattern variable has the target typeNo separate cast needed

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
Notes and examples
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
Notes and examples

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

Checked, unchecked, and errors

CategoryExamplesCompile-time handling required?
Checked exceptionsIOException, SQLExceptionYes: catch or declare
Runtime exceptionsNullPointerException, IllegalArgumentExceptionNo
ErrorsOutOfMemoryError, StackOverflowErrorNo; usually not handled
  • Catch blocks must be ordered from more specific to more general.
  • A catch block that can never be reached causes a compile error.
  • Multi-catch alternatives cannot be related by subclassing.
  • The exception variable in a multi-catch is effectively final.
  • A finally block usually runs whether or not an exception is thrown.
  • A finally block can suppress or replace an earlier return/throw if it completes abruptly.

Try-with-resources

RuleWhy it matters
Resource must implement AutoCloseable or CloseableOtherwise it cannot be used as a resource
Resources close in reverse declaration orderFrequently tested
Close exceptions can be suppressedPrimary exception remains primary
Resource variables are effectively finalExisting effectively final variables can be used

Do not forget that close() itself may throw an exception depending on the resource type.

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>
Notes and examples
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.

Arrays

TopicRule
Lengtharray.length field, not method
IndexingZero-based
Default valuesNumeric zero, false, '\u0000', null references
CovarianceString[] is an Object[]
Runtime store checksWrong subtype assignment can throw ArrayStoreException
Multidimensional arraysArrays of arrays; inner lengths may differ

Array covariance is unlike generic invariance. String[] can be assigned to Object[], but List<String> cannot be assigned to List<Object>.

Collections quick map

Interface / classOrdered?Duplicates?High-yield note
ArrayListIndex orderYesFast random access
LinkedListIndex/insertion orderYesAlso implements Deque
HashSetNo guaranteed orderNoDepends on hashCode/equals
LinkedHashSetInsertion orderNoPredictable iteration order
TreeSetSortedNoRequires comparable elements or comparator
HashMapNo guaranteed orderKeys uniqueKey equality uses hashCode/equals
LinkedHashMapInsertion/access order optionsKeys uniquePredictable iteration order
TreeMapSorted keysKeys uniqueRequires comparable keys or comparator
ArrayDequeDeque orderYesOften preferred for stack/queue behavior
PriorityQueuePriority order for removalYesIteration order is not sorted order

Mutability and factory methods

Creation styleBehavior
List.of(...), Set.of(...), Map.of(...)Unmodifiable; reject nulls
Arrays.asList(array)Fixed-size list backed by the array
Collections.unmodifiableList(list)Unmodifiable view backed by original list
new ArrayList<>(list)Independent mutable copy

High-yield distinction: unmodifiable is not the same as immutable if the underlying data can still change through another reference.

Generics and wildcards

FormMeaningSafe mental model
List<T>Exact type parameterInvariant
List<?>Unknown typeRead as Object; cannot add specific elements except null
List<? extends Number>Some subtype of NumberProducer: read Number, do not add numbers
List<? super Integer>Some supertype of IntegerConsumer: can add Integer; reads as Object
Raw typeGeneric type without type argumentAllows unsafe operations and warnings

Use PECS: Producer Extends, Consumer Super.

Common traps:

  • Generic type parameters are erased at runtime.
  • You cannot create new T() directly.
  • You cannot create a normal array of a parameterized type such as new List<String>[10].
  • List<Integer> is not a subtype of List<Number>.

Sorting and comparison

APIPurpose
Comparable<T>Natural ordering using compareTo
Comparator<T>External ordering strategy
Comparator.comparingBuild comparator from key extractor
thenComparingTie-breaker
reversedReverse order
Collections.sort / List.sortSort lists
Arrays.sortSort arrays
binarySearchRequires sorted input according to same ordering

If input is not sorted correctly, binary search results are not reliable.

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
Notes and examples

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.

Functional interfaces

A functional interface has exactly one abstract method, though it may also have default, static, and private methods.

InterfaceAbstract method ideaExample use
Predicate<T>T -> booleanFiltering
Consumer<T>T -> voidPerforming side effects
Supplier<T>() -> TCreating/providing values
Function<T,R>T -> RMapping
UnaryOperator<T>T -> TSame-type transform
BinaryOperator<T>(T,T) -> TCombining
BiFunction<T,U,R>(T,U) -> RTwo-input mapping
  • Captured local variables must be final or effectively final.
  • Parameter types can be inferred, but syntax must be consistent.
  • A lambda body with braces needs explicit return for non-void results.
  • Method references must match the target functional interface signature.

Stream pipeline rules

StageExamplesKey point
SourceCollection, array, file lines, generated streamProvides elements
Intermediate operationsfilter, map, flatMap, sorted, distinct, limit, skip, peekLazy; return another stream
Terminal operationscollect, reduce, count, forEach, anyMatch, findFirstTrigger processing and close pipeline
ReuseNot allowed after terminal operationCauses IllegalStateException

Streams do not modify the source unless the operation itself causes side effects. Prefer side-effect-free lambdas, especially with parallel streams.

Intermediate operations

OperationPurposeTrap
filterKeep matching elementsPredicate returns boolean
mapOne element to one elementCan change element type
flatMapOne element to stream of elementsFlattens nested streams
distinctRemove duplicatesUses equality
sortedSort natural or comparator orderMay need comparable elements
peekObserve elementsLazy; mainly debugging
limitTruncate streamImportant for infinite streams
skipDiscard first n elementsOrder matters
takeWhileTake while predicate remains trueMost useful on ordered streams
dropWhileDrop while predicate remains trueBehavior differs for unordered streams

Terminal operations

OperationReturnsReview point
countlongCounts elements
min / maxOptional<T>Need comparator
findFirstOptional<T>Encounter-order sensitive
findAnyOptional<T>Useful in parallel pipelines
anyMatchbooleanShort-circuiting
allMatchbooleanTrue for empty stream
noneMatchbooleanTrue for empty stream
forEachvoidOrder not guaranteed in parallel
forEachOrderedvoidPreserves encounter order where applicable
reduceValue or OptionalIdentity/accumulator/combiner rules matter
collectCollection, map, string, summaryUses collectors or custom collector

Collectors

CollectorUse
toList, toSet, toMapCollect elements into containers
joiningCombine strings
groupingByMap keys to grouped values
partitioningBySplit into true/false groups
mappingDownstream transformation
countingCount elements downstream
summingInt, averagingDouble, etc.Numeric aggregation
summarizingInt, etc.Count, sum, min, max, average
reducingDownstream reduction

toMap is a common trap: duplicate keys require a merge function unless the data guarantees uniqueness.

Primitive streams and Optional

TypePurpose
IntStream, LongStream, DoubleStreamAvoid boxing for primitive pipelines
Optional<T>Container for possibly absent reference value
OptionalInt, OptionalLong, OptionalDoublePrimitive optional variants

Know common Optional methods: isPresent, isEmpty, get, orElse, orElseGet, orElseThrow, ifPresent, map, flatMap, filter.

High-yield distinction:

MethodBehavior
orElse(value)Argument is evaluated before the call
orElseGet(supplier)Supplier runs only when optional is empty

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
Notes and examples
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
Notes and examples
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));
  • 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

Java date/time API

Most java.time types are immutable.

TypeRepresents
LocalDateDate without time zone
LocalTimeTime without date or zone
LocalDateTimeDate and time without zone
ZonedDateTimeDate and time with time zone
OffsetDateTimeDate and time with offset
InstantMachine timestamp
PeriodDate-based amount: years, months, days
DurationTime-based amount: seconds, nanoseconds
  • Period is for dates; Duration is for time-based amounts.
  • Date/time objects are immutable; date.plusDays(1) returns a new object.
  • Formatting patterns are case-sensitive.
  • Some operations may adjust invalid dates, such as month-end calculations.
  • Time zones and daylight saving transitions can affect ZonedDateTime.

Localization

APIUse
LocaleLanguage, country/region, variant information
ResourceBundleLocale-specific text/resources
NumberFormatLocale-sensitive numbers, currency, percentages
DateTimeFormatterDate/time formatting with locale support
MessageFormatParameterized localized messages

Resource bundle lookup can fall back through less-specific locales. Practice questions often test which bundle is selected or whether a key is found.

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
Notes and examples
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;
}

Path and Files

APIPurposeTrap
PathRepresents a pathPath object may refer to nonexistent file
Paths.get / Path.ofCreate pathsDoes not require file to exist
normalizeRemove redundant path elementsDoes not access filesystem
toAbsolutePathConvert to absolute pathDoes not necessarily verify existence
toRealPathResolve real filesystem pathAccesses filesystem and can throw
resolveCombine pathsAbsolute right-hand path may override
relativizePath from one path to anotherUsually requires compatible path types
Files.existsExistence checkCan be affected by permissions
Files.copy / move / deleteFile operationsOptions change behavior
Files.walk / find / listStream pathsClose streams

Byte streams, character streams, and buffering

CategoryExamplesUse
Byte streamsInputStream, OutputStreamBinary data
Character streamsReader, WriterText data
Buffered streams/readersBufferedInputStream, BufferedReaderEfficiency
Object streamsObjectInputStream, ObjectOutputStreamSerialization

Remember to close I/O resources. Try-with-resources is the standard exam-safe pattern.

Serialization review

RuleWhy it matters
Class must implement SerializableMarker interface enables standard serialization
transient fields are not serialized normallyThey receive default values on deserialization
Static fields are not part of object stateClass-level, not instance state
serialVersionUIDVersion compatibility identifier
ConstructorsDeserialization does not call the serializable class’s normal constructor

Serialization questions often combine inheritance, transient, static fields, and default values.

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
Notes and examples
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?

Threads, tasks, and executors

ConceptReview point
ThreadRepresents an execution thread
RunnableTask with no return value and no checked exception from run
Callable<V>Task returning a value and allowed to throw checked exceptions
ExecutorServiceManages task execution
executeSubmits Runnable, no result
submitReturns Future
Future.getBlocks until result or exception
shutdownStops accepting new tasks; existing tasks continue
shutdownNowAttempts to stop running tasks and returns pending tasks

High-yield trap: creating a Thread object does not start execution. Calling run() directly is just a normal method call; start() starts a new thread.

Synchronization and shared state

ToolPurposeTrap
synchronized instance method/blockLock on an object instanceDifferent objects mean different locks
synchronized staticLock on class objectSeparate from instance lock
volatileVisibility guaranteeDoes not make compound actions atomic
Atomic classesAtomic updates like incrementKnow common classes such as AtomicInteger
Concurrent collectionsSafer concurrent accessIteration semantics may differ from fail-fast collections
LocksExplicit lock/unlock controlMust release in finally when used manually

Common concurrency errors:

  • Race condition: result depends on timing.
  • Deadlock: threads wait forever for each other’s locks.
  • Starvation: a thread cannot get needed resources.
  • Livelock: threads keep reacting but make no progress.
  • Unsafe publication: other threads see stale or partially initialized state.

Parallel streams

Parallel streams can improve throughput for suitable workloads, but exam questions often focus on correctness:

  • Avoid shared mutable state.
  • Do not assume forEach preserves order.
  • Use associative, stateless operations for reductions.
  • findAny may differ from findFirst.
  • Side effects become harder to reason about.

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
Notes and examples
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
Notes and examples

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

Core JDBC flow

StepAPI
Get connectionDriverManager or DataSource
Create statementStatement, PreparedStatement, or CallableStatement
Bind parametersPreparedStatement setters use 1-based parameter indexes
ExecuteexecuteQuery, executeUpdate, or execute
Read resultsResultSet cursor starts before first row; call next()
Clean upTry-with-resources
Manage transactionsetAutoCommit, commit, rollback

Statement selection

TypeUse
StatementSimple SQL without parameters
PreparedStatementParameterized SQL; helps avoid SQL injection
CallableStatementStored procedures

Execution method traps:

MethodBest fit
executeQuerySQL that returns a ResultSet
executeUpdateINSERT, UPDATE, DELETE, DDL; returns update count
executeGeneral method; returns boolean indicating result type

Always distinguish SQL parameter indexes from Java array indexes: JDBC parameters are commonly 1-based.

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 {}
Notes and examples

Built-in and meta-annotations

AnnotationPurpose
@OverrideCompiler verifies method override
@FunctionalInterfaceCompiler verifies single abstract method
@DeprecatedMarks obsolete API
@SuppressWarningsSuppresses selected compiler warnings
@SafeVarargsSuppresses heap pollution warnings for safe varargs use
@RetentionControls how long annotation is retained
@TargetControls where annotation can be used
@RepeatableAllows repeated annotation use
@InheritedAllows class annotation inheritance behavior
@DocumentedIncludes annotation in generated documentation
  • Element types are restricted to primitives, String, Class, enums, annotations, and arrays of those types.
  • Elements can have default values.
  • If the only required element is named value, shorthand syntax can be used.
  • Retention matters: reflection requires runtime retention.

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.
Notes and examples

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.

High-yield exam mindset

The Oracle Java SE 17 Developer (1Z0-829) exam rewards precision. Expect questions that test:

SkillWhat to watch
Compilation judgmentAccess rules, inheritance, generics, var, lambdas, modules, checked exceptions
Runtime behaviorInitialization order, polymorphism, exceptions, stream laziness, collection mutation
API fluencyString, StringBuilder, collections, streams, dates, NIO.2, JDBC, localization
Java 17 language featuresRecords, sealed classes, pattern matching for instanceof, switch expressions, text blocks
Edge casesNumeric promotion, overload resolution, wildcard bounds, resource closing order, immutability

A common mistake is reading code as if it were “normal application code.” Exam code is often designed to expose one exact rule.

Modules and deployment

Java Platform Module System essentials

DirectiveMeaning
requiresModule depends on another module
requires transitiveDependency is exposed to modules that require this module
requires staticNeeded at compile time but optional at runtime
exportsMakes package public to other modules at compile time and runtime
exports ... toQualified export to specific modules
opensAllows deep reflection at runtime
opens ... toQualified reflective access
usesDeclares service consumption
provides ... withDeclares service provider implementation
Notes and examples

Module review points:

  • java.base is required implicitly.
  • module-info.java declares module dependencies and exposed packages.
  • Packages are the unit of export, not individual classes.
  • Public class does not mean accessible outside the module unless its package is exported.
  • Reflection-heavy frameworks may require opens, not merely exports.
  • Named modules, unnamed modules, and automatic modules behave differently.
  • Split packages across modules can create problems.

JARs and command-line awareness

Know the purpose, not just syntax:

Tool / conceptPurpose
javacCompile source
javaRun application
jarPackage classes/resources
Module pathLocate modules
ClasspathLocate non-modular classes/resources
jdepsAnalyze dependencies
jlinkCreate custom runtime images

Practice command-line questions carefully; one misplaced module name or path option can change the answer.

Security and robustness mindset

The exam may combine API knowledge with safe coding judgment. Keep these habits in mind:

RiskSafer approach
SQL injectionUse PreparedStatement parameters
Exposed mutable internalsDefensive copies or immutable views
Resource leaksTry-with-resources
Unsafe deserializationValidate and minimize serialized surface
Shared mutable stateSynchronization, immutability, atomic classes, concurrent collections
Sensitive data in logsAvoid unnecessary exposure
Path traversalValidate and normalize paths carefully

For question-bank practice, treat “secure” answers as those that reduce trust in external input, avoid unnecessary mutability, and close resources predictably.

Common compile-time traps

Code patternLikely issue
Using var without initializerCannot infer type
Assigning int expression to shortNumeric promotion
Catching superclass exception before subclassUnreachable catch
Lambda captures modified local variableNot effectively final
Adding to List<? extends Number>Unsafe; compile error except null
Overriding with broader checked exceptionCompile error
Calling private method as if overriddenPrivate methods are not overridden
Accessing non-exported module packageNot accessible outside module
Mixing lambda parameter stylesCompile error
Creating generic arrayUsually illegal
Missing return in switch expression pathCompile error
Record with extra instance fieldCompile error
Sealed subclass lacking final, sealed, or non-sealedCompile error

Common runtime traps

Code patternPossible result
Downcast without valid object typeClassCastException
Store wrong subtype into covariant arrayArrayStoreException
Dereference nullNullPointerException
Access invalid array/list indexArrayIndexOutOfBoundsException or IndexOutOfBoundsException
Reuse consumed streamIllegalStateException
Modify collection during iterationConcurrentModificationException in many fail-fast cases
Parse invalid number/dateParsing exception
JDBC read before ResultSet.next()Invalid cursor position
Future task throws exceptionExecutionException from Future.get()
File operation without permissions or missing pathI/O exception or failed existence check

Fast topic drill map

Use this table to decide what to practice next in an IT Mastery question bank.

If you miss questions on…Drill these topics
“Does it compile?”Access modifiers, overload/override, checked exceptions, generics, var, records, sealed classes
Unexpected outputInitialization order, polymorphism, string immutability, numeric promotion, switch fall-through
CollectionsEquality, hashing, sorting, mutability, wildcards, factory methods
StreamsLaziness, terminal operations, collectors, optionals, primitive streams, parallel behavior
Date/timeImmutability, Period vs Duration, formatter patterns, locale behavior
I/OPath operations, Files methods, try-with-resources, serialization
ConcurrencyExecutors, Future, synchronization, volatile, atomics, race conditions
JDBCStatement type, execution method, transaction handling, cursor movement
Modulesrequires, exports, opens, service directives, module path vs classpath
LocalizationLocale, ResourceBundle fallback, number/date formatting

Final pre-practice checklist

Before starting a mock exam for Oracle Java SE 17 Developer (1Z0-829), confirm that you can:

  • Predict whether short Java snippets compile.
  • Explain overload resolution and override dispatch.
  • Trace object initialization order.
  • Distinguish identity, equality, and ordering.
  • Use generics wildcards without guessing.
  • Identify stream source, intermediate operations, terminal operation, and result type.
  • Choose correct collection implementations for ordering, uniqueness, and sorting.
  • Explain Period, Duration, and core java.time classes.
  • Know when I/O and JDBC resources are opened, used, and closed.
  • Recognize concurrency hazards in shared mutable state.
  • Read module-info.java directives accurately.
  • Spot when mutability, reflection, serialization, SQL, or file paths create safety issues.

Put the review into practice