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.
Scan the tables first. Mark anything you cannot explain without looking it up.
Run topic drills immediately after each weak area. Java exam misses often come from small compile-time or runtime details.
Practice with code mentally and in an IDE. The real challenge is usually not knowing an API exists; it is predicting exact behavior.
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
Area
Know cold
Common exam traps
Language basics
primitives, wrappers, operators, control flow, var, text blocks
numeric promotion, compound assignment casts, == vs equals, var limitations
Local variables have no default; must be definitely assigned
var
Local variable type inference at compile time
Not dynamic typing
var requires initializer
var x = 10; valid
var x;, var x = null;, var a = {1,2}; invalid
var locations
Local variables and lambda parameters
Not fields, method return types, formal method parameters, catch parameters
Lambda var
If one lambda parameter uses var, all explicit parameters must use var
(var a, var b) -> a + b valid; (var a, b) -> ... invalid
Shadowing
Inner declarations may shadow fields
Local variables cannot be redeclared in the same scope
Effectively final
Required for captured local variables
Variable must not be reassigned after capture
Notes and examples
varnames=List.of("Ana","Bo");// inferred List<String>varnums=newint[]{1,2,3};// valid// var bad = {1, 2, 3}; // invalid// var none = null; // invalidintcount=0;// Runnable r = () -> count++; // invalid: count not effectively final
Primitive Types, Literals, and Numeric Promotion
Topic
Rule
Integer literal default
int unless suffixed with L/l
Floating literal default
double unless suffixed with F/f
Underscores in literals
Allowed between digits only
char
Unsigned 16-bit UTF-16 code unit; participates in numeric promotion
Arithmetic promotion
byte, short, and char promote to int before arithmetic
Binary numeric promotion
If either operand is double, result double; else float; else long; else int
Compound assignment
Includes implicit narrowing cast
Constant narrowing
Compile-time constants in range may assign to byte, short, char
byteb=10;// b = b + 1; // invalid: b + 1 is intb+=1;// valid: implicit cast to byteshorts=1;charc=2;intresult=s+c;// promoted to intlongx=10;// int literal widened to longfloatf=10.0f;// suffix required for float literal
Operators and Evaluation
Operator area
Key rules
&&, `
&, `
, ^`
== with primitives
Compares values after promotion
== with references
Compares object identity
Mixed wrapper/primitive
Wrapper is unboxed
Assignment expressions
Return assigned value
Ternary ?:
May trigger numeric promotion or boxing/unboxing
Pre/post increment
Prefix changes before value use; postfix changes after value use
Integera=1000;Integerb=1000;System.out.println(a==b);// false: different references likelySystem.out.println(a.equals(b));// trueIntegerc=10;intd=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
Topic
Rule to remember
Common trap
One public top-level type
Public top-level type name must match the file name
Non-public top-level classes can share a file
Package declaration
If present, it comes before imports and type declarations
Comments can appear before it; imports cannot
Imports
import package.Type; or import package.*;
Wildcard import does not import subpackages
Static imports
Import static members by name or wildcard
Ambiguous static imports can cause compile errors
main method
Common form: public static void main(String[] args)
String... args is equivalent; wrong return type is not an entry point
java.lang
Imported automatically
Other packages are not
Identifiers, var, and scope
Feature
Valid use
Invalid or risky use
var local variable inference
Local variables with an initializer
Fields, method parameters, return types
var initializer
var n = 10;
var x = null; because type cannot be inferred
Lambda parameters
Can use var for all lambda parameters
Cannot mix var and explicit/implicit parameter styles
Scope
Local variables live within their block
Shadowing 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
Area
Rule
Integer literals
Default type is int unless suffixed or context requires otherwise
Floating literals
Default type is double; use f or F for float
byte, short, char arithmetic
Promoted to int in most arithmetic expressions
Compound assignment
Includes an implicit cast, so short s = 1; s += 1; can compile where s = s + 1; may not
Division
Integer division truncates toward zero
Overflow
Integer overflow wraps; it does not throw an exception
Boolean
Not numeric; cannot be used as 0 or 1
High-yield example: char + char produces an int, not a char.
Equality and object identity
Expression
Meaning
Trap
a == b for primitives
Numeric or boolean value comparison
Numeric promotion may occur
a == b for references
Same object reference
Not logical equality
a.equals(b)
Type-specific equality if overridden
May throw NullPointerException if a is null
Objects.equals(a, b)
Null-safe equality
Useful for exam reasoning
Records
Generated equals compares record components
Component equality still depends on component types
Strings
String literals may be interned
Do not assume new String("x") == "x"
Control Flow and Pattern Matching
if, Loops, Labels, and break/continue
Construct
Rule
if condition
Must be boolean, not numeric
while / do while
Condition must be boolean
Enhanced for
Works with arrays and Iterable
break label
Exits the labeled statement
continue label
Continues the labeled loop
Unreachable code
Compile-time error, except some special cases after non-constant conditions
Pattern variable is available where definitely matched
&&
Pattern variable available on right side
`
Objectobj="java";if(objinstanceofStrings&&s.length()>2){System.out.println(s.toUpperCase());}// if (obj instanceof String t || t.length() > 2) { } // invalid
if, loops, labels, break, and continue
Construct
Review point
if / else
else binds to the nearest unmatched if
while
Condition checked before body
do while
Body executes at least once
Basic for
Init, condition, update sections are optional
Enhanced for
Iterates arrays or Iterable objects
Labels
Can label loops and blocks, but most useful with nested loops
break
Exits loop or switch; labeled break exits labeled statement
continue
Skips 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
Feature
Switch statement
Switch expression
Purpose
Control flow
Produces a value
Fall-through
Possible with colon labels
Arrow labels do not fall through
Value required
No
Yes, every path must produce a value or throw
yield
Not used in classic statement style
Used to return a value from block cases
Exhaustiveness
Less strict
More 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/API
Key facts
String
Immutable; methods return new strings
String literals
Interned
StringBuilder
Mutable, not synchronized, does not override equals()
StringBuffer
Mutable and synchronized
substring
End index exclusive
replace
Replaces all matching chars or sequences
strip
Unicode-aware whitespace removal
trim
Removes characters <= '\u0020'
String.format
Uses format specifiers and optional locale
Text blocks
Multi-line strings using """; incidental indentation handled
Notes and examples
Strings="abc";s.concat("d");System.out.println(s);// abcStringBuildersb=newStringBuilder("abc");sb.append("d");System.out.println(sb);// abcdStringtext="""
line one
line two
""";
Arrays
Topic
Rule
Declaration
int[] a preferred; int a[] valid
Initialization
new int[3] gives default values
Anonymous array
new int[] {1, 2, 3}
Length
Array field length, not method
Multidimensional arrays
Arrays of arrays; rows may be different lengths
Covariance
String[] is an Object[], but unsafe stores fail at runtime
Sorting/searching
Arrays.sort, Arrays.binarySearch
Comparison
Arrays.compare, Arrays.mismatch, Arrays.equals
Object[]values=newString[2];// values[0] = new Object(); // ArrayStoreException at runtimeint[][]grid=newint[2][];grid[0]=newint[]{1,2};grid[1]=newint[]{3};
String, StringBuilder, and text blocks
Type / feature
Key properties
Exam trap
String
Immutable
Methods return a new String; original unchanged
StringBuilder
Mutable, not synchronized
Methods usually mutate and return same builder
StringBuffer
Mutable, synchronized
Less common in modern code
Text blocks
Multiline string literals using triple quotes
Incidental indentation and trailing newline behavior can matter
String comparison
Use .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:
Method
Focus
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:
API
Use
String.format
Format text using format specifiers
NumberFormat
Locale-sensitive number, currency, and percent formatting
DecimalFormat
Custom numeric patterns
DateTimeFormatter
Date/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
Modifier
Same class
Same package
Subclass different package
Other package
private
Yes
No
No
No
package-private
Yes
Yes
No
No
protected
Yes
Yes
Yes, through inheritance rules
No general access
public
Yes
Yes
Yes
Yes
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
Order
What runs
1
Static fields and static initializers of superclass
2
Static fields and static initializers of subclass
3
Instance fields and instance initializers of superclass
4
Superclass constructor
5
Instance fields and instance initializers of subclass
6
Subclass constructor
classParent{static{System.out.print("A");}{System.out.print("B");}Parent(){System.out.print("C");}}classChildextendsParent{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
Concept
Rule
Overriding
Instance method in subclass replaces inherited instance method
Static method hiding
Static methods are hidden, not overridden
Field hiding
Fields are hidden, not overridden
Access on override
Cannot reduce visibility
Return type
May be covariant
Checked exceptions
Override cannot throw broader checked exceptions
final method
Cannot be overridden
final class
Cannot be extended
abstract class
Cannot be instantiated; may have constructors
Constructor
Not inherited; first statement is this(...) or super(...)
classA{staticvoids(){System.out.print("A.s ");}voidm(){System.out.print("A.m ");}}classBextendsA{staticvoids(){System.out.print("B.s ");}@Overridevoidm(){System.out.print("B.m ");}}Aref=newB();ref.s();// A.s: static method chosen by reference typeref.m();// B.m: instance method chosen by object type
Interfaces
Interface member
Implicit modifiers / rules
Field
public static final
Abstract method
public abstract
Default method
Instance method with body; inherited by implementers
Static method
Called using interface name
Private method
Helper for default/static methods
Private static method
Static helper
Constructor
Interfaces do not have constructors
Default method conflict rules:
Class method wins over interface default.
More specific interface wins over less specific interface.
If unrelated defaults conflict, implementing class must override.
Initialize superclass static fields and static blocks.
Initialize subclass static fields and static blocks.
Allocate object memory with default values.
Run superclass instance fields, instance initializer blocks, and constructor.
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
Modifier
Same class
Same package
Subclass in other package
Other package
private
Yes
No
No
No
package-private
Yes
Yes
No
No
protected
Yes
Yes
Yes, through inheritance rules
No general access
public
Yes
Yes
Yes
Yes
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
Concept
Decided when
Key rule
Overloading
Compile time
Same method name, different parameter list
Overriding
Runtime dispatch
Instance method in subclass replaces superclass behavior
Static method hiding
Compile time reference type
Static methods are not polymorphic
Field hiding
Compile time reference type
Fields are not polymorphic
Covariant return
Override may return subtype
Must still satisfy method contract
Checked exceptions
Override cannot throw broader checked exceptions
Runtime 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
Type
High-yield facts
Abstract class
Can have constructors, fields, concrete methods, abstract methods
Interface
Methods are commonly public abstract; can also have default, static, and private methods
Enum
Constants come first; constructors are implicitly private; can have fields and methods
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
Modifier
Meaning
sealed
Restricts direct subclasses/implementers
permits
Lists permitted direct subclasses, unless inferable in same source context
final subclass
Cannot be extended further
sealed subclass
Continues restriction
non-sealed subclass
Reopens hierarchy for further extension
sealedinterfaceShapepermitsCircle,Rectangle{}finalclassCircleimplementsShape{}non-sealedclassRectangleimplementsShape{}classSquareextendsRectangle{}// 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 rule
Detail
Constants
Listed first; semicolon needed if members follow
Constructor
Implicitly private
Superclass
Extends java.lang.Enum; cannot extend another class
Interfaces
Enums may implement interfaces
Methods
May define fields, constructors, methods, abstract methods
Runs after try/catch unless abnormal VM termination
Return in finally
Can override previous return or thrown exception; usually a trap
Override exceptions
Cannot broaden checked exceptions
try{thrownewjava.io.IOException();}catch(java.io.FileNotFoundExceptione){// more specific first}catch(java.io.IOException|RuntimeExceptione){// e is effectively final}
Try-With-Resources
Rule
Exam detail
Resource type
Must implement AutoCloseable or Closeable
Close order
Reverse order of declaration
Suppressed exceptions
Exceptions from close() are suppressed if try block already threw
Effectively final resources
Existing effectively final variables can be used
catch/finally
Optional
try(varin=newFileInputStream("a.txt");varout=newFileOutputStream("b.txt")){in.transferTo(out);}// out closes first, then in
Checked, unchecked, and errors
Category
Examples
Compile-time handling required?
Checked exceptions
IOException, SQLException
Yes: catch or declare
Runtime exceptions
NullPointerException, IllegalArgumentException
No
Errors
OutOfMemoryError, StackOverflowError
No; 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
Rule
Why it matters
Resource must implement AutoCloseable or Closeable
Otherwise it cannot be used as a resource
Resources close in reverse declaration order
Frequently tested
Close exceptions can be suppressed
Primary exception remains primary
Resource variables are effectively final
Existing 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
Concept
Rule
Type erasure
Generic type parameters are mostly removed at runtime
new Locale.Builder().setLanguage("en").setRegion("US").build()
Resource bundle
Loads localized resources by base name and locale
Properties bundle
Key-value .properties files
Class bundle
Java class extending ListResourceBundle
Missing key
Throws 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.
Type
Represents
LocalDate
Date without time zone
LocalTime
Time without date or zone
LocalDateTime
Date and time without zone
ZonedDateTime
Date and time with time zone
OffsetDateTime
Date and time with offset
Instant
Machine timestamp
Period
Date-based amount: years, months, days
Duration
Time-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
API
Use
Locale
Language, country/region, variant information
ResourceBundle
Locale-specific text/resources
NumberFormat
Locale-sensitive numbers, currency, percentages
DateTimeFormatter
Date/time formatting with locale support
MessageFormat
Parameterized 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.
Connection factory, often preferred in managed environments
Connection
Database session; transactions
Statement
Executes static SQL
PreparedStatement
Precompiled SQL with parameters
CallableStatement
Stored procedures
ResultSet
Cursor over query results
SQLException
JDBC checked exception
SQLWarning
Non-fatal database warning
Notes and examples
Statement Execution
Method
Use
executeQuery
SQL returning a ResultSet, typically SELECT
executeUpdate
DML/DDL returning update count
execute
Unknown or mixed result type
getResultSet
Retrieve result set after execute
getUpdateCount
Retrieve update count after execute
Stringsql="select id, name from users where status = ?";try(Connectionconn=DriverManager.getConnection(url);PreparedStatementps=conn.prepareStatement(sql)){ps.setString(1,"ACTIVE");// JDBC parameters are 1-basedtry(ResultSetrs=ps.executeQuery()){while(rs.next()){intid=rs.getInt("id");Stringname=rs.getString("name");}}}
ResultSet and Transactions
Topic
Rule
Cursor position
Initially before first row
next()
Moves cursor and returns whether row exists
Column indexes
1-based
Column labels
Often clearer than indexes
getInt on SQL NULL
Returns 0; call wasNull() to distinguish
Auto-commit
Usually enabled by default
Manual transaction
setAutoCommit(false), then commit or rollback
Savepoint
Partial rollback marker
Closing resources
Close ResultSet, Statement, Connection; try-with-resources preferred
try(Connectionconn=DriverManager.getConnection(url)){conn.setAutoCommit(false);try(PreparedStatementps=conn.prepareStatement("update account set balance = balance - ? where id = ?")){ps.setBigDecimal(1,amount);ps.setLong(2,accountId);ps.executeUpdate();conn.commit();}catch(SQLExceptione){conn.rollback();throwe;}}
Core JDBC flow
Step
API
Get connection
DriverManager or DataSource
Create statement
Statement, PreparedStatement, or CallableStatement
Bind parameters
PreparedStatement setters use 1-based parameter indexes
Execute
executeQuery, executeUpdate, or execute
Read results
ResultSet cursor starts before first row; call next()
Clean up
Try-with-resources
Manage transaction
setAutoCommit, commit, rollback
Statement selection
Type
Use
Statement
Simple SQL without parameters
PreparedStatement
Parameterized SQL; helps avoid SQL injection
CallableStatement
Stored procedures
Execution method traps:
Method
Best fit
executeQuery
SQL that returns a ResultSet
executeUpdate
INSERT, UPDATE, DELETE, DDL; returns update count
execute
General method; returns boolean indicating result type
Always distinguish SQL parameter indexes from Java array indexes: JDBC parameters are commonly 1-based.
Annotations
Annotation
Purpose
@Override
Compile-time check that a method overrides or implements
@Deprecated
Marks API as discouraged
@SuppressWarnings
Suppresses compiler warnings
@FunctionalInterface
Confirms interface has one abstract method
@SafeVarargs
Suppresses heap pollution warnings for safe varargs usage
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 pattern
Likely issue
Using var without initializer
Cannot infer type
Assigning int expression to short
Numeric promotion
Catching superclass exception before subclass
Unreachable catch
Lambda captures modified local variable
Not effectively final
Adding to List<? extends Number>
Unsafe; compile error except null
Overriding with broader checked exception
Compile error
Calling private method as if overridden
Private methods are not overridden
Accessing non-exported module package
Not accessible outside module
Mixing lambda parameter styles
Compile error
Creating generic array
Usually illegal
Missing return in switch expression path
Compile error
Record with extra instance field
Compile error
Sealed subclass lacking final, sealed, or non-sealed
Compile error
Common runtime traps
Code pattern
Possible result
Downcast without valid object type
ClassCastException
Store wrong subtype into covariant array
ArrayStoreException
Dereference null
NullPointerException
Access invalid array/list index
ArrayIndexOutOfBoundsException or IndexOutOfBoundsException
Reuse consumed stream
IllegalStateException
Modify collection during iteration
ConcurrentModificationException in many fail-fast cases
Parse invalid number/date
Parsing exception
JDBC read before ResultSet.next()
Invalid cursor position
Future task throws exception
ExecutionException from Future.get()
File operation without permissions or missing path
I/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