Java SE 8 Programmer I (OCAJP 8) cheat sheet
Java SE 8 Programmer I (OCAJP 8) · Keep the key ideas within reach.
Java Basics
A source file may contain at most one public top-level type, and its name must match the file name; non-public top-level classes may share a file.
Compilation (javac) produces .class bytecode; execution (java) starts at a public static void main(String[] args) method - also valid: String... args, or String[] with any parameter name.
Package declaration must be the first statement (after comments); import statements follow and apply to the whole compilation unit.
A wildcard import like java.util.* imports only types in that package, not subpackages such as java.util.concurrent.
java.lang is imported implicitly; java.util, java.io, and java.text are not.
Default package classes cannot be imported or used from named packages.
Access modifiers ranked narrowest to widest: private < default (package-private) < protected < public.
A class with no declared constructor gets a default no-arg constructor whose access modifier matches the class; declaring any constructor removes it.
main(String[] args) is not required for a class to compile; the JVM throws NoSuchMethodError at runtime if it is missing when the class is launched.
Working With Java Data Types
Eight primitives: byte(8), short(16), int(32), long(64), float(32), double(64), char(16 unsigned), boolean (size unspecified).
Widening conversions are implicit (byte→short→int→long→float→double); narrowing requires an explicit cast and may truncate or lose precision.
Integer literals are int by default; add L for long. Decimal literals are double by default; add F for float.
Underscores in numeric literals are allowed between digits (1_000_000) but not at the start/end, adjacent to a decimal point, or adjacent to L/F/D suffixes.
Binary 0b, octal 0, and hex 0x prefixes are valid; a leading zero makes a literal octal, so 08 fails to compile.
char accepts a single quoted character, an integer literal in range, or a unicode escape; "a" (String) does not assign to char.
Object reference variables hold references; passing them passes the reference by value, so reassigning the parameter does not affect the caller's variable.
String literals are interned; new String("x") creates a distinct object, so == may be false while equals is true.
Wrapper classes are immutable; autoboxing uses valueOf, so Integer caching applies to values -128 to 127 for == comparisons.
Using Operators and Decision Constructs
&& and || short-circuit (right operand may not evaluate); & and | on booleans always evaluate both sides.
Ternary condition ? a : b requires the condition to be boolean; the two branches must be assignable to a common type.
switch accepts byte, short, char, int, their wrappers, String, and enum - not long, float, double, or boolean.
switch case labels must be compile-time constants; fall-through continues until a break or the end of the switch block.
The default label may appear anywhere in a switch; it runs only when no case matches.
== on primitives compares values; on references compares identity; equals compares logical content when overridden.
Operator precedence: postfix > unary > cast > * / % > + - > relational > == != > & > ^ > | > && > || > ?: > assignment.
Compound assignment (+=, -=) performs an implicit narrowing cast, so byte b = 10; b += 5; compiles while b = b + 5; does not.
if/else without braces binds only the next single statement, which is the usual cause of dangling-else bugs.
Creating and Using Arrays
Array size is fixed at creation; length is a final field, not a method, so arr.length() does not compile.
Valid declarations: int[] a; int a[]; int[] a, b[]; - the brackets bind to the variable name in mixed declarations.
Array elements are default-initialized: 0 for numeric primitives, '\u0000' for char, false for boolean, null for references.
new int[3] creates three defaulted elements; new int[]{1,2,3} or {1,2,3} (only in a declaration) supplies initial values.
Array indexes are 0-based; accessing index < 0 or >= length throws ArrayIndexOutOfBoundsException at runtime.
Multidimensional arrays are arrays of arrays; int[][] a = new int[2][]; leaves a[0] and a[1] null.
Arrays.equals compares one-dimensional contents; for nested arrays use Arrays.deepEquals.
Arrays.sort on primitives uses dual-pivot quicksort; binarySearch requires a sorted array and returns a negative insertion point when not found.
A String[] is a subtype of Object[] (covariant), but storing a non-String element throws ArrayStoreException.
Using Loop Constructs
while checks the condition before the body (may run zero times); do-while checks after (runs at least once) and requires a trailing semicolon.
Classic for loop parts are all optional: for(;;) is an infinite loop; multiple initialization/update expressions are separated by commas.
The for-loop variable declared in the header is scoped to the loop and unavailable after it.
Enhanced for (for (Type x : arrayOrIterable)) cannot modify the underlying array elements through x for primitives.
break exits the innermost loop or switch; continue skips to the next iteration of the innermost loop.
Labeled break/continue (label: for(...) { break label; }) targets the named outer loop.
An unreachable statement after an unconditional break/return/throw is a compile error; an if(false) branch does not make code unreachable.
A for/while loop with a constant-true condition and no break makes following statements unreachable and fails compilation.
Working with Methods and Encapsulation
Method overloading is resolved at compile time by parameter list (type, order, number); return type and parameter names do not matter.
varargs (Type... name) must be the last parameter and is treated as an array inside the method; it can be called with zero arguments.
static methods cannot access instance fields or use this; they are invoked through the class name.
A static method can be hidden (not overridden) by a static method in a subclass with the same signature.
Encapsulation pattern: private fields with public getters/setters; a public getter on a private field exposes state read-only from outside.
Constructors have no return type, are not inherited, and can chain with this(...) or super(...), which must be the first statement.
A final method cannot be overridden; a final class cannot be extended; a final variable cannot be reassigned.
Instance initializer blocks run before constructor bodies, in textual order among themselves; static initializers run once at class initialization.
Pass-by-value: primitive arguments are copied; object references are copied, so mutating the referenced object is visible to the caller.
Working with Inheritance
A class extends exactly one class; it may implement multiple interfaces.
A subclass constructor implicitly calls super() if no explicit super(...) or this(...) is present; a missing no-arg super constructor causes a compile error.
Overriding rules: same signature, covariant return type allowed, access modifier cannot be more restrictive, checked exceptions cannot be broader.
private, static, and final methods are not overridden: private methods are not inherited, static methods are hidden, final methods cannot be replaced.
A reference of the supertype can point to a subtype object; only members visible on the reference type are accessible without a cast.
Casting a reference to an incompatible type compiles only for related types and throws ClassCastException at runtime if the object is not an instance.
Abstract classes cannot be instantiated and may contain abstract and concrete members; a concrete subclass must implement all abstract methods.
Interface members are implicitly public; Java 8 adds default methods and static methods, and default methods can be overridden by implementing classes.
An interface extending another interface inherits its abstract and default methods; a class implementing two interfaces with conflicting defaults must override.
Handling Exceptions
Throwable hierarchy: Throwable → Error and Exception; RuntimeException and its subclasses are unchecked, all other Exceptions are checked.
Checked exceptions must be caught or declared with throws; unchecked exceptions and Errors need not be.
Catch blocks are evaluated top-down; a broader supertype catch before a subtype makes the later block unreachable and fails compilation.
A try must have at least one catch or finally; try-with-resources (Java 7+) closes resources automatically in reverse order.
finally runs whether or not an exception is thrown, except when System.exit is called or the JVM crashes; a return in finally overrides the try's return.
Multi-catch uses | (catch (IOException | SQLException e)) and the parameter is implicitly final.
The exception parameter in catch is effectively final in Java 8; reassigning it is allowed only in single-catch blocks.
Overriding methods may throw fewer or narrower checked exceptions, but not new or broader ones.
A method that declares throws does not itself have to throw; callers must still handle the declared checked exception.
Working with Selected Classes from the Java API
String is immutable; concat, replace, substring, and trim return new objects, while StringBuilder/StringBuffer are mutable.
String indexOf returns -1 when absent; substring(begin, end) excludes end; charAt throws StringIndexOutOfBoundsException when out of range.
StringBuilder methods like append and insert return the same builder, enabling chaining; StringBuilder is not thread-safe, StringBuffer is.
String equality uses equals (case-sensitive) or equalsIgnoreCase; == compares references.
ArrayList is resizable and index-based; remove(int) removes by index while remove(Object) removes by value.
List and ArrayList equality is element-order-sensitive; Set implementations reject duplicates; HashSet has no defined iteration order.
Arrays.asList returns a fixed-size list backed by the array; add/remove throw UnsupportedOperationException, but set works.
java.time basics: LocalDate, LocalTime, LocalDateTime are immutable; plusDays/minusHours return new instances.
Period represents a date-based amount (years/months/days) and Duration a time-based amount (hours/minutes/seconds).