Oracle Java Foundations cheat sheet
Oracle Java Foundations · Keep the key ideas within reach.
Java Basics
A source file's name must match its public top-level class name and end in .java; only one public top-level class is allowed per file.
javac compiles .java source into .class bytecode; the java launcher starts the JVM and runs a class whose bytecode already exists.
The JDK contains the compiler and the JRE; the JRE contains the JVM plus the core class libraries.
A package declaration, if present, is the first non-comment statement in the file; import statements follow it and a wildcard import (java.util.*) covers only that package's types.
Identifiers may contain letters, digits, underscore, and dollar sign, must not begin with a digit, and cannot be a reserved keyword; Java is case-sensitive.
The application entry point must be declared public static void main(String[] args) - static so it runs without an instance, void so it returns nothing.
Naming conventions: UpperCamelCase for classes and interfaces, lowerCamelCase for methods and variables, UPPER_SNAKE_CASE for constants, all-lowercase for packages.
Garbage collection reclaims unreachable objects automatically; no API forces collection - System.gc() is only a request.
Working with Java Data Types
Eight primitives: byte (8 bits), short (16), int (32), long (64), float (32), double (64), char (16 unsigned), boolean (not numeric).
Ranges: byte -128..127; short -32768..32767; int -2^31..2^31-1; char 0..65535; integer overflow wraps silently instead of throwing.
An integer literal is an int unless suffixed with L; a decimal literal is a double unless suffixed with f or F.
Widening conversion (byte→short→int→long→float→double) is implicit; narrowing requires an explicit cast and may lose magnitude or precision.
Binary numeric promotion widens byte, short, and char to int before arithmetic, so byte b = 1; b = b + 1; does not compile.
Local variables have no default value and must be assigned before use; instance and static fields default to 0, false, '\u0000', or null.
String is an immutable reference type; literals are interned in the string pool, while new String(...) always creates a distinct object.
Autoboxing converts primitives to wrapper objects and back; for objects == compares references while equals compares content.
Using Operators and Decision Constructs
Precedence high to low: postfix ++/--, unary and cast, * / %, + -, shifts, relational, == !=, & ^ |, && ||, ?:, assignment.
&& and || short-circuit (right operand may be skipped); & and | always evaluate both operands; all four require boolean operands.
== compares primitive values but object references; equals compares logical content for String and wrapper classes.
Compound assignments (+=, -=, *=, /=) apply an implicit cast back to the left-hand type, so byte b = 1; b += 2; compiles.
Ternary form: condition ? valueIfTrue : valueIfFalse - the condition must be boolean and both branches must be type-compatible.
if/else: conditions must be boolean (an int does not convert); else binds to the nearest unmatched if; braces are optional for single statements.
switch accepts byte, short, char, int, their boxed forms, String, and enum; case labels must be compile-time constants and must be unique.
Without break, switch falls through to subsequent cases; default is optional and may appear anywhere in the switch body.
Integer division truncates toward zero and throws ArithmeticException on a zero divisor; floating-point division by zero yields Infinity or NaN.
Creating and Using Arrays
An array is an object; its size is the final field length, written a.length - length() belongs to String and size() to collections.
After new, element defaults are 0 for numeric types, '\u0000' for char, false for boolean, and null for reference types.
Indexes are 0-based; valid values are 0 through length-1, and any other index throws ArrayIndexOutOfBoundsException at runtime.
Curly-brace initializers (int[] a = {1,2,3};) are legal only in a declaration; later assignment needs new int[]{1,2,3}.
Both int[] a; and int a[]; declare an array, because the brackets attach to the type rather than to every variable name.
Multidimensional arrays are arrays of arrays, so int[][] g = new int[3][]; creates three null rows whose lengths can differ.
Utility methods live in java.util.Arrays: sort, fill, copyOf, equals, binarySearch, and toString (deepToString for nested arrays).
Arrays.copyOf and System.arraycopy make shallow copies; a null array reference throws NullPointerException when length or an element is accessed.
Using Loop Constructs
while tests the condition before each iteration; do-while tests after the body, so a do-while body always runs at least once.
Basic for syntax is for(init; condition; update) - all three parts are optional, and for(;;) is a legal infinite loop.
The enhanced for loop works on arrays and Iterable; its variable receives a copy, so assigning to it does not alter the underlying element.
break exits the nearest enclosing loop or switch; continue skips the rest of the current iteration and re-tests the condition.
Labeled statements (outer:) allow break outer; and continue outer; to act on an enclosing loop instead of the innermost one.
Loop conditions must be boolean; an int expression such as while(1) is a compile-time error in Java.
A statement placed after an infinite loop with no reachable break (for example while(true){}) is an unreachable-statement compile error.
Working with Methods and Encapsulation
Declaration order: modifiers, return type, name, parenthesized parameter list, optional throws clause, body; constructors omit the return type.
Overloading requires a different parameter list (count, types, or order); return type and access modifier alone cannot create an overload.
Java is pass-by-value: primitives copy the value and object references copy the reference, so mutating the referenced object is visible to the caller.
Visibility: private (same class), default/package-private (same package), protected (package plus subclasses), public (everywhere).
Encapsulation means private fields reached through public getters and setters; boolean getters conventionally use the is prefix.
this refers to the current object; this(...) calls a sibling constructor and must be the first statement of the constructor body.
A varargs parameter (int... nums) must be last in the list and behaves as an array inside the method body.
A final variable may be assigned once; final methods cannot be overridden and final classes cannot be extended.
A class with no declared constructor receives a compiler-generated no-argument constructor that calls super().
Working with Inheritance
A class extends exactly one superclass but implements many interfaces; every class implicitly extends java.lang.Object.
A subclass constructor calls super() implicitly unless it starts with this(...) or super(...); any explicit call must be the first statement.
Overriding needs the same name and parameter list, allows a covariant (narrower) return type, cannot reduce visibility, and cannot throw broader checked exceptions.
Overloading is resolved at compile time (static binding); overriding is dispatched at runtime from the actual object type.
private, static, and final methods are not overridden - a static method with the same signature is hidden, not overridden.
Object supplies toString, equals, hashCode, and getClass, which subclasses commonly override.
A supertype reference may refer to a subtype object; a downcast requires an explicit cast and throws ClassCastException when the runtime type does not match.
abstract classes cannot be instantiated but may hold fields, constructors, and both abstract and concrete methods; interfaces declare constants plus abstract, default, and static methods.
super.method() invokes the parent version of an overridden method; super() in a constructor invokes the parent constructor.
Handling Exceptions
Throwable splits into Error and Exception; RuntimeException and its subclasses are unchecked, while all other Exception subclasses are checked.
Checked exceptions must be caught or declared with throws; unchecked exceptions and Errors need not be handled by the compiler.
try-catch-finally: catch blocks are tested in order, so a subclass catch must appear before a catch of its superclass.
finally runs whether the try completes normally, throws, or returns; only System.exit or a JVM crash skips it, and a return inside finally overrides the try's return.
Multi-catch syntax catch (IOException | SQLException e) is legal when the types are unrelated, and the parameter is implicitly final.
try-with-resources requires resources implementing AutoCloseable, closes them in reverse declaration order, and allows optional catch and finally blocks.
throw requires a Throwable object; a method declaring throws obliges callers to catch or propagate each checked type.
Typical unchecked exceptions: NullPointerException, ArrayIndexOutOfBoundsException, ArithmeticException, ClassCastException, NumberFormatException.
Catching a checked exception that the try block cannot throw is a compile-time error unless the caught type is Exception or Throwable.
Working with Selected Classes from the Java API
String is immutable: charAt, length(), substring(begin,end) with an exclusive end, indexOf, replace, trim, toUpperCase, split, equals, and equalsIgnoreCase.
StringBuilder is mutable and offers append, insert, reverse, delete, and toString; StringBuffer is the synchronized variant.
StringBuilder does not override equals, so two builders with identical content are equal only by reference.
Wrapper classes: Integer.parseInt returns an int, Integer.valueOf returns an Integer, and valueOf caches values from -128 to 127.
LocalDate, LocalTime, and LocalDateTime are immutable, created with of() or now(), and modified through plus/minus methods that return new instances.
ArrayList is a resizable, indexed collection allowing duplicates and null; size() gives its length versus length for arrays.
ArrayList.remove(int) removes by index and returns the element, while remove(Object) removes the first match and returns boolean.
Math utilities: Math.round, Math.abs, Math.max, Math.pow, and Math.random returning a double in the range 0.0 inclusive to 1.0 exclusive.
Period models date amounts (years, months, days) while Duration models time amounts (hours, minutes, seconds).