Skip to content
Tutorials Center
My learning

Topics

Lesson 195 of 201 ยท Practice and Review

Java Cheat Sheet

A one-page Java 25 cheat sheet with syntax, types, strings, control flow, OOP, records, exceptions, collections, lambdas, streams, dates, files and threads.

This page squeezes the whole Java course into one scrollable reference: the syntax, types and APIs you reach for every day, in compact snippets you can scan in seconds. Keep it open while you work on the practice exercises, while you write your own programs, or the night before an interview.

Every section links to the lesson that explains the topic properly, with the reasoning and pitfalls that a cheat sheet has no room for. The handful of rules that surprise people most often come with live editors, so you can run them and see the behavior for yourself. Everything here is modern Java 25; features added in recent versions name the version that introduced them.

Program structure

Two ways to write a program

Java
// Compact source file (Java 25): no class needed
void main() {
    IO.println("Hello, Java!");
}
Java
// Classic form: what most existing code and frameworks use
public class Main {
    public static void main(String[] args) {
        System.out.println("Hello, Java!");
    }
}

Compact files import all of java.base automatically (List, Map, Path, ...). Classic files need imports for anything outside java.lang. See Getting Started, Syntax and The main Method.

Compile and run

Terminal
java Main.java               # run a single source file directly (no javac step)
javac Main.java              # compile to Main.class (bytecode)
java Main                    # run the compiled class on the JVM
java -version                # which JDK is on the PATH
javac -d out src/app/*.java  # compile into an output folder

See How Java Works and Build Tools.

Comments and naming

Java
// line comment
/* block comment */
/** Javadoc: @param, @return, @throws */
/// Markdown doc comment (Java 23+)

class OrderService {}             // classes, records, enums: PascalCase
int itemCount;                    // variables and methods: camelCase
static final int MAX_RETRIES = 3; // constants: UPPER_SNAKE_CASE
package com.example.shop;         // packages: lowercase, reversed domain

See Comments and Javadoc and Keywords and Identifiers.

Output and input

Printing

Java
System.out.println("line");      // print + newline
System.out.print("no newline");
IO.println("Java 25 shortcut");  // also IO.print(...)
System.err.println("error stream");
System.out.printf("%s is %d%n", "Ada", 36);   // formatted (IO has no printf)
String s = "%.2f".formatted(3.14159);           // "3.14"
String t = String.format("%05d", 42);           // "00042"
Specifier Meaning Example โ†’ output
%d integer %d, 42 โ†’ 42
%,d grouped thousands %,d, 1234567 โ†’ 1,234,567
%05d zero-padded width 5 42 โ†’ 00042
%.2f 2 decimals (rounds) 3.14159 โ†’ 3.14
%8.2f width 8, right-aligned 3.5 โ†’ 3.50
%s / %-10s string / left-aligned in 10 "ab" โ†’ ab
%x / %X hexadecimal 255 โ†’ ff / FF
%e scientific 12345.0 โ†’ 1.234500e+04
%b %c %% %n boolean, char, a literal %, newline

See Printing Output and Formatting Strings.

Reading input

Java
Scanner in = new Scanner(System.in);
String line = in.nextLine();     // whole line
int n = in.nextInt();            // one token; leaves the newline behind!
while (in.hasNextInt()) { ... }  // read until input runs out

String name = IO.readln("Name: ");          // Java 25: prompt + read a line
int age = Integer.parseInt(IO.readln());

var reader = new BufferedReader(new InputStreamReader(System.in));
String first = reader.readLine();           // null at end of input

The classic trap: nextInt() followed by nextLine() returns an empty string, because nextInt() stops before the line break. Run this to see it, then the fix:

Java The nextInt plus nextLine trap

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Simplest fix in general: read whole lines and parse them with Integer.parseInt(line.trim()). See Reading User Input.

Variables and types

Primitive types

Type Size Range / values Default (fields) Literal
byte 8 bits -128 to 127 0 (byte) 10
short 16 bits -32,768 to 32,767 0 (short) 10
int 32 bits about ยฑ2.1 billion 0 42, 1_000_000, 0xFF, 0b1010, 017
long 64 bits about ยฑ9.2 ร— 10ยนโธ 0L 42L
float 32 bits about 7 significant digits 0.0f 3.14f
double 64 bits about 15โ€“16 significant digits 0.0 3.14, 1e-3
char 16 bits one UTF-16 code unit '\u0000' 'A', '\n'
boolean โ€“ true, false false true

Everything else is a reference type (String, arrays, objects), whose fields default to null. Local variables have no default: they must be assigned before use. See Primitive Data Types and Variables.

Declarations, var and final

Java
int count = 0;
double price = 9.99, tax = 0.2;
var names = new ArrayList<String>();   // type inferred: ArrayList<String>
final int limit = 10;                  // can't be reassigned
static final double VAT = 0.21;        // a constant (inside a class)

var works only for local variables with an initializer (not fields, parameters or var x = null;). See var and Constants and final.

Conversions

Java
long big = 42;                    // widening: automatic
int whole = (int) 3.99;           // narrowing: 3 (truncates toward zero)
byte wrapped = (byte) 200;        // -56 (keeps the low 8 bits)
int n = Integer.parseInt("123");  // NumberFormatException on "12a"
double d = Double.parseDouble("2.5");
String s = String.valueOf(42);    // or "" + 42, or Integer.toString(42)
int code = 'A';                   // 65
char next = (char) ('A' + 1);     // 'B'

See Type Casting and Conversion and Wrapper Classes.

Operators

Java
7 / 2          // 3      int division truncates
-7 / 2         // -3     toward zero
7 % 3          // 1
-7 % 3         // -1     sign follows the left operand
Math.floorMod(-7, 3)   // 2
7 / 2.0        // 3.5    one double makes it double division
1 + 2 + "3"    // "33"   left to right: 3, then "33"
"1" + 2 + 3    // "123"

x += 5;  x -= 1;  x *= 2;  x /= 3;  x %= 4;
i++  // use, then add 1      ++i  // add 1, then use

a == b, a != b, a < b, a >= b
a && b, a || b, !a     // short-circuit: b may not be evaluated
a & b, a | b, a ^ b    // on booleans: always evaluate both
int max = a > b ? a : b;           // ternary
obj instanceof String str          // type test + pattern variable

5 & 3 /* 1 */, 5 | 3 /* 7 */, 5 ^ 3 /* 6 */, ~5 /* -6 */
1 << 4 /* 16 */, -16 >> 2 /* -4 */, -16 >>> 28 /* 15 */

Precedence from high to low: postfix x++ โ†’ unary ++x -x ! ~ (cast) โ†’ * / % โ†’ + - โ†’ shifts โ†’ < > <= >= instanceof โ†’ == != โ†’ & โ†’ ^ โ†’ | โ†’ && โ†’ || โ†’ ?: โ†’ assignment. When in doubt, add parentheses. See Arithmetic Operators, Comparison and Logical Operators, Bitwise and Shift Operators and Operator Precedence.

Numeric surprises

Java Numeric surprises in one run

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

int and long overflow wraps around without warning; Math.addExact, multiplyExact and friends throw instead. Use BigDecimal for money. See Working with Numbers, Assignment Operators and BigInteger and BigDecimal.

The Math class

Java
Math.abs(-5)  Math.max(a, b)  Math.min(a, b)
Math.pow(2, 10)        // 1024.0 (a double)
Math.sqrt(16)  Math.cbrt(27)  Math.hypot(3, 4)   // 4.0 3.0 5.0
Math.round(2.4)        // 2 (a long for double arguments)
Math.floor(2.7)  Math.ceil(2.1)                  // 2.0 3.0
Math.floorDiv(-7, 2)   // -4
Math.clamp(150, 0, 100)                          // 100 (Java 21)
Math.random()          // 0.0 <= x < 1.0
RandomGenerator.getDefault().nextInt(1, 7)       // 1..6 (dice)

See The Math Class and Random Numbers.

Strings

Everyday String methods

Java
String s = "Hello, World";
s.length()                 // 12
s.charAt(0)                // 'H'
s.substring(7)             // "World"
s.substring(0, 5)          // "Hello" (end index excluded)
s.indexOf("o")             // 4      lastIndexOf("o") โ†’ 8, -1 if missing
s.contains("World")        // true
s.startsWith("He")  s.endsWith("!")
s.toUpperCase()  s.toLowerCase()
"  hi  ".strip()           // "hi"   (Unicode-aware; trim() is ASCII-only)
"".isEmpty()  "  ".isBlank()        // true true
s.replace('l', 'L')        // "HeLLo, WorLd"
"a1b22".replaceAll("\\d+", "#")      // "a#b#" (regex)
"a,b,,c,".split(",")       // [a, b, , c] (trailing empties dropped)
String.join("-", "a", "b") // "a-b"
"ab".repeat(3)             // "ababab"
"line1\nline2".lines()     // Stream<String>
s.toCharArray()            // char[]
s.chars()                  // IntStream of chars
s.equals(other)  s.equalsIgnoreCase(other)
s.compareTo("Help")        // negative: "Hello" sorts first

Strings are immutable: every method returns a new string, so write s = s.trim();. See Strings, String Methods and Comparing and Converting Strings.

== versus equals

Java Comparing strings and wrappers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

== compares references; equals compares contents. Any "true" you get from == on strings or boxed numbers is luck (pooling or caching), never something to rely on.

StringBuilder and text blocks

Java
var sb = new StringBuilder();
sb.append("Hi").append(' ').append(42);   // "Hi 42"
sb.insert(0, ">> ");  sb.reverse();  sb.setLength(0);
String csv = String.join(",", list);      // or Collectors.joining(",")

String json = """
    {
      "name": "Ada",
      "age": 36
    }
    """;   // indentation relative to the closing """ is removed

Use StringBuilder when building strings in loops. See StringBuilder, StringBuffer, StringJoiner and StringTokenizer and Text Blocks.

Control flow

if and switch

Java
if (score >= 90) {
    grade = 'A';
} else if (score >= 80) {
    grade = 'B';
} else {
    grade = 'C';
}

String type = switch (day) {              // switch expression
    case SATURDAY, SUNDAY -> "weekend";
    case MONDAY -> {
        log("start");
        yield "weekday";                  // yield returns from a block
    }
    default -> "weekday";
};

switch (command) {                        // classic statement: needs break
    case "start":
        start();
        break;
    case "stop":
    case "halt":                          // fall-through groups labels
        stop();
        break;
    default:
        help();
}

Switch works on int-like types, char, String, enums and (with patterns) any type. See if, else if and else and switch.

Loops

Java
for (int i = 0; i < 10; i++) { ... }
for (String name : names) { ... }          // arrays and any Iterable
while (condition) { ... }
do { ... } while (condition);              // body runs at least once

outer:
for (int r = 0; r < rows; r++) {
    for (int c = 0; c < cols; c++) {
        if (grid[r][c] == target) break outer;   // leaves both loops
        if (grid[r][c] < 0) continue;            // next c
    }
}

See while and do-while, for Loops and break, continue and Labels.

Arrays

Java
int[] nums = new int[5];                   // [0, 0, 0, 0, 0]
int[] primes = {2, 3, 5, 7};
String[] names = new String[3];            // [null, null, null]
nums.length                                // a field, not a method
int[][] grid = new int[3][4];              // 3 rows, 4 columns
int[][] jagged = {{1}, {2, 3}, {4, 5, 6}};

Arrays.toString(primes)                    // "[2, 3, 5, 7]"
Arrays.deepToString(grid)                  // nested arrays
Arrays.sort(nums);                         // ascending
Arrays.sort(words, Comparator.reverseOrder());   // objects only
Arrays.binarySearch(primes, 5)             // 2 (array must be sorted)
Arrays.fill(nums, -1);
int[] copy = Arrays.copyOf(nums, 10);      // pads with 0
int[] part = Arrays.copyOfRange(nums, 1, 3);
Arrays.equals(a, b)                        // contents; a.equals(b) is identity
List<String> view = Arrays.asList(names);  // fixed size: add() throws
int sum = Arrays.stream(primes).sum();     // 17

Indexes run from 0 to length - 1; anything else throws ArrayIndexOutOfBoundsException. See Arrays, Looping Through Arrays, Multidimensional Arrays and The Arrays Class.

Methods

Java
static int add(int a, int b) {             // static: call as add(1, 2)
    return a + b;
}
static double add(double a, double b) { ... }  // overload: different parameters
static int sum(int... values) { ... }      // varargs: sum(), sum(1, 2, 3)
record MinMax(int min, int max) {}         // return several values
static MinMax range(int[] a) { ... }

long factorial(int n) {                    // recursion needs a base case
    return n <= 1 ? 1 : n * factorial(n - 1);
}

Java is always pass-by-value: a method gets a copy of a primitive, or a copy of a reference (so it can change the object, but not which object the caller's variable points to). See Methods, Parameters and Return Values, Method Overloading, Recursion, Varargs and Variable Scope.

Classes and objects

A complete class

Java
public class Account {
    private static int created = 0;        // shared by all accounts
    private final String owner;            // set once
    private double balance;

    public Account(String owner) {
        this(owner, 0);                    // call another constructor
    }

    public Account(String owner, double balance) {
        if (balance < 0) throw new IllegalArgumentException("negative balance");
        this.owner = owner;                // this. disambiguates the field
        this.balance = balance;
        created++;
    }

    public double getBalance() { return balance; }
    public void deposit(double amount) { balance += amount; }
    public static int created() { return created; }

    @Override
    public String toString() { return owner + ": " + balance; }
}

Account acc = new Account("Ada", 100);
acc.deposit(50);

See Classes and Objects, Constructors, The this Keyword, Encapsulation and Static Members.

Access modifiers

Modifier Same class Same package Subclass (other package) Everywhere
public yes yes yes yes
protected yes yes yes no
(none) package-private yes yes no no
private yes no no no

See Access Modifiers.

Inheritance, abstract classes and interfaces

Java
abstract class Shape {
    abstract double area();                       // no body: subclasses must implement
    String describe() { return "Area " + area(); }
}

class Circle extends Shape {                      // one superclass only
    private final double r;
    Circle(double r) { super(); this.r = r; }     // super(...) calls the parent constructor
    @Override double area() { return Math.PI * r * r; }
}

interface Drawable {
    void draw();                                  // implicitly public abstract
    default void drawTwice() { draw(); draw(); }  // default method
    static Drawable noop() { return () -> {}; }
}

class Square extends Shape implements Drawable, Comparable<Square> { ... }

Shape s = new Circle(2);                          // upcast: always allowed
if (s instanceof Circle c) { ... }                // safe downcast with a pattern

See Inheritance, super, Polymorphism, Abstract Classes, Interfaces and Composition.

Records, enums and nested classes

Java
record Point(int x, int y) {                      // final fields, accessors x() and y(),
    Point {                                       // equals/hashCode/toString for free
        if (x < 0) throw new IllegalArgumentException("x < 0");  // compact constructor
    }
    Point withX(int nx) { return new Point(nx, y); }
}

enum Planet {
    MERCURY(3.303e23), EARTH(5.976e24);
    private final double mass;
    Planet(double mass) { this.mass = mass; }
    double mass() { return mass; }
}
Planet.values()  Planet.valueOf("EARTH")  Planet.EARTH.ordinal()  // 1

class Outer {
    static class Nested {}        // no link to an Outer instance
    class Inner {}                // needs one: outer.new Inner()
}
Runnable r = new Runnable() {     // anonymous class
    public void run() { IO.println("run"); }
};

See Records, Enums, Nested Classes and Immutable Classes.

Sealed types and pattern matching

Java Sealed interface, records and a pattern switch

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Because Shape is sealed, the compiler knows every subtype, so a switch that covers them all needs no default, and adding a new subtype turns every incomplete switch into a compile error. See Sealed Classes and Pattern Matching.

equals, hashCode and toString

Java
@Override
public boolean equals(Object o) {
    return o instanceof Isbn other && code.equals(other.code);
}
@Override
public int hashCode() { return Objects.hash(code); }   // equal objects โ†’ equal hashes
@Override
public String toString() { return "Isbn[" + code + "]"; }

Objects.equals(a, b)                     // null-safe
Objects.requireNonNull(name, "name")     // fail fast

Override equals and hashCode together, or hash-based collections break. See The Object Class and Copying Objects.

Exceptions

Java
try {
    int n = Integer.parseInt(text);
} catch (NumberFormatException e) {
    IO.println("Not a number: " + e.getMessage());
} catch (IllegalStateException | ArithmeticException e) {   // multi-catch
    throw new AppException("calculation failed", e);           // keep the cause
} finally {
    IO.println("always runs");
}

try (var reader = Files.newBufferedReader(path)) {   // closed automatically,
    return reader.readLine();                        // in reverse order
}

void load(Path p) throws IOException { ... }         // checked: declare or catch

class InsufficientFundsException extends RuntimeException {
    InsufficientFundsException(String message) { super(message); }
}
Kind Extends Must be caught or declared? Examples
Checked Exception yes IOException, SQLException, InterruptedException
Unchecked RuntimeException no NullPointerException, IllegalArgumentException, IndexOutOfBoundsException
Error Error no (don't catch) OutOfMemoryError, StackOverflowError

See Exceptions, Throwing Exceptions, Custom Exceptions, try-with-resources, Best Practices and Debugging.

Collections

Which one?

Need Use Notes
Ordered list, index access ArrayList the default list
Unique items, fast lookup HashSet no order
Unique items, insertion order LinkedHashSet
Unique items, sorted TreeSet first, floor, ceiling
Key โ†’ value HashMap one null key allowed
Key โ†’ value, insertion/access order LinkedHashMap LRU caches
Key โ†’ value, sorted keys TreeMap headMap, floorKey
Stack or queue ArrayDeque not Stack/LinkedList
Always take the smallest/largest PriorityQueue a binary heap
Shared between threads ConcurrentHashMap, CopyOnWriteArrayList, BlockingQueue
Operation ArrayList LinkedList HashMap/HashSet TreeMap/TreeSet
get by index / key O(1) O(n) O(1) average O(log n)
add at end / put O(1) amortized O(1) O(1) average O(log n)
insert/remove in middle O(n) O(n) to find, O(1) to unlink โ€“ โ€“
contains O(n) O(n) O(1) average O(log n)

See The Collections Framework and Choosing the Right Collection.

Lists, sets and maps in practice

Java
List<String> list = new ArrayList<>();
list.add("b");  list.add(0, "a");  list.get(0);  list.set(0, "z");
list.remove("z");  list.remove(0);  list.size();  list.contains("b");
list.removeIf(s -> s.isBlank());
list.sort(Comparator.naturalOrder());
list.getFirst();  list.getLast();  list.reversed();     // Java 21

Set<Integer> set = new HashSet<>(List.of(3, 1, 2));
set.add(1);                     // false: already there
set.retainAll(other);           // intersection (addAll = union, removeAll = difference)

Map<String, Integer> map = new HashMap<>();
map.put("apples", 3);
map.get("pears")                       // null when missing
map.getOrDefault("pears", 0)           // 0
map.putIfAbsent("pears", 1);
map.merge(word, 1, Integer::sum);      // counting in one line
map.computeIfAbsent(key, k -> new ArrayList<>()).add(value);   // grouping
for (Map.Entry<String, Integer> e : map.entrySet()) { e.getKey(); e.getValue(); }
map.forEach((k, v) -> IO.println(k + "=" + v));

Deque<Integer> stack = new ArrayDeque<>();
stack.push(1);  stack.pop();  stack.peek();
Queue<Integer> queue = new ArrayDeque<>();
queue.offer(1);  queue.poll();  queue.peek();         // null when empty
PriorityQueue<Task> pq = new PriorityQueue<>(Comparator.comparingInt(Task::priority));

List.of(1, 2, 3)  Set.of("a")  Map.of("k", 1)        // immutable, no nulls
List.copyOf(list)                                     // immutable copy
Collections.unmodifiableList(list)                    // read-only view
Collections.frequency(list, "b")  Collections.max(list)  Collections.shuffle(list)

Modifying a collection while looping over it with for-each throws ConcurrentModificationException; use removeIf or an Iterator's remove(). See ArrayList, HashMap, HashSet, TreeMap and TreeSet, Queues and Deques, Iterators and Immutable Collections.

Sorting

Java
record Person(String name, int age) {}
people.sort(Comparator.comparing(Person::name));
people.sort(Comparator.comparingInt(Person::age).reversed());
people.sort(Comparator.comparing(Person::age).thenComparing(Person::name));
names.sort(Comparator.nullsFirst(Comparator.naturalOrder()));

class Version implements Comparable<Version> {
    public int compareTo(Version o) { return Integer.compare(major, o.major); }
}

Never write return a - b; in a comparator: it overflows for large values. Use Integer.compare. See Comparable and Comparator.

Generics and functional programming

Generics

Java
class Box<T> {
    private final T value;
    Box(T value) { this.value = value; }
    T get() { return value; }
}
Box<String> box = new Box<>("hi");                     // diamond <>

static <T extends Comparable<T>> T max(List<T> items) { ... }   // bounded type
double sum(List<? extends Number> nums) { ... }        // read from a producer
void fill(List<? super Integer> out) { ... }           // write to a consumer

PECS: Producer extends, Consumer super. Generics are erased at run time: no new T(), no List<int> (use List<Integer>), no instanceof List<String>. See Generics, Bounded Types and Wildcards and Type Erasure.

Lambdas, functional interfaces and method references

Interface Method Shape Example
Function<T, R> apply T โ†’ R s -> s.length()
BiFunction<T, U, R> apply (T, U) โ†’ R (a, b) -> a + b
Predicate<T> test T โ†’ boolean n -> n > 0
Consumer<T> accept T โ†’ void IO::println
Supplier<T> get () โ†’ T ArrayList::new
UnaryOperator<T> apply T โ†’ T String::trim
BinaryOperator<T> apply (T, T) โ†’ T Integer::sum
Runnable / Callable<V> run / call () โ†’ void / V tasks for threads
Java
Function<Integer, Integer> twice = x -> x * 2;
Function<Integer, Integer> plusOne = x -> x + 1;
twice.andThen(plusOne).apply(5)     // 11
twice.compose(plusOne).apply(5)     // 12
Predicate<String> empty = String::isEmpty;
empty.negate().and(s -> s.length() < 5)

String::toUpperCase     // instance method of an arbitrary object: s -> s.toUpperCase()
System.out::println     // instance method of a particular object
Integer::parseInt       // static method
ArrayList::new          // constructor

Lambdas can use local variables only if they are effectively final. See Lambdas, Functional Interfaces, Method References and Functional Programming.

Streams

Java
List<String> result = names.stream()
    .filter(n -> n.length() > 3)          // intermediate: lazy
    .map(String::toUpperCase)
    .sorted()
    .distinct()
    .limit(10)
    .toList();                            // terminal: runs the pipeline (Java 16)

IntStream.range(0, 5)                     // 0..4  (rangeClosed(1, 5) โ†’ 1..5)
Stream.of("a", "b")  Arrays.stream(array)  list.stream()
stream.count()  .anyMatch(p)  .allMatch(p)  .noneMatch(p)
stream.findFirst()                        // Optional
stream.reduce(0, Integer::sum)
ints.mapToInt(Integer::intValue).sum()    // also average(), max(), summaryStatistics()
lists.stream().flatMap(List::stream)      // flatten
Java
Collectors.joining(", ", "[", "]")
Collectors.groupingBy(Person::city)                         // Map<City, List<Person>>
Collectors.groupingBy(Person::city, Collectors.counting())  // Map<City, Long>
Collectors.partitioningBy(p -> p.age() >= 18)               // Map<Boolean, List<...>>
Collectors.toMap(Person::name, Person::age, (a, b) -> a)    // merge on duplicate keys
Collectors.averagingInt(Person::age)
Java A stream pipeline with collectors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

A stream can be used only once, and it does nothing until a terminal operation runs. See Streams, Collecting Stream Results and Advanced Streams.

Optional

Java
Optional<User> found = repo.findById(id);
found.map(User::email).orElse("none");
found.orElseGet(() -> loadDefault());     // lazy fallback
found.orElseThrow();                      // NoSuchElementException if empty
found.ifPresentOrElse(u -> greet(u), () -> IO.println("not found"));
Optional.ofNullable(maybeNull)            // Optional.of(null) throws

Use Optional as a return type for "maybe no result", not for fields or parameters. See Optional.

Working with data

Dates and times (java.time)

Java
LocalDate today = LocalDate.now();
LocalDate due = LocalDate.of(2026, 3, 15).plusWeeks(2);
LocalDateTime meeting = LocalDateTime.of(2026, 5, 1, 9, 30);
ZonedDateTime tokyo = meeting.atZone(ZoneId.of("Asia/Tokyo"));
Instant now = Instant.now();                         // a point on the UTC timeline
Duration d = Duration.ofMinutes(90);                 // time-based: 1h30m
Period p = Period.between(birthday, today);          // date-based: years/months/days
long days = ChronoUnit.DAYS.between(start, end);
var fmt = DateTimeFormatter.ofPattern("dd.MM.yyyy");
fmt.format(today);  LocalDate.parse("01.02.2026", fmt);
today.with(TemporalAdjusters.lastDayOfMonth());
today.getDayOfWeek()                                 // e.g. MONDAY

All java.time types are immutable: plusDays returns a new value. Avoid the legacy Date and Calendar. See Dates and Times.

Regex, big numbers, UUIDs

Java
Pattern p = Pattern.compile("(?<year>\\d{4})-(\\d{2})");   // compile once, reuse
Matcher m = p.matcher("Due 2026-03");
if (m.find()) { m.group("year"); m.group(2); }              // "2026", "03"
"2026-03".matches("\\d{4}-\\d{2}")                          // whole string must match

new BigDecimal("0.10").add(new BigDecimal("0.20"))          // 0.30 exactly
amount.setScale(2, RoundingMode.HALF_EVEN)
a.compareTo(b) == 0                    // equals() also compares the scale: 2.0 โ‰  2.00
BigInteger.TWO.pow(100)

UUID.randomUUID()
HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes))
Base64.getEncoder().encodeToString(bytes)

See Regular Expressions, BigInteger and BigDecimal, UUIDs, Hashing and Base64 and Internationalization.

Files

Java
Path path = Path.of("data", "notes.txt");
Files.createDirectories(path.getParent());
Files.writeString(path, "first line\n");
Files.writeString(path, "more\n", StandardOpenOption.APPEND);
String text = Files.readString(path);
List<String> lines = Files.readAllLines(path);
try (Stream<String> stream = Files.lines(path)) { ... }   // large files: close it!
Files.exists(path)  Files.size(path)  Files.delete(path)
Files.copy(src, dst, StandardCopyOption.REPLACE_EXISTING);
try (Stream<Path> all = Files.walk(Path.of("."))) { ... }

Files APIs use UTF-8 by default. See Reading and Writing Files, Byte and Character Streams, Working with Directories, Serialization, Character Sets and Properties Files.

Concurrency

Java
Thread t = new Thread(() -> work());
t.start();                    // run() would execute on the current thread
t.join();                     // wait for it to finish

synchronized (lock) { count++; }          // one thread at a time
private volatile boolean running = true;  // visibility only, not atomicity
AtomicInteger hits = new AtomicInteger();
hits.incrementAndGet();
ConcurrentHashMap<String, Integer> counts = new ConcurrentHashMap<>();
counts.merge(key, 1, Integer::sum);       // atomic

try (ExecutorService pool = Executors.newFixedThreadPool(4)) {   // close() waits (Java 19+)
    Future<Integer> f = pool.submit(() -> compute());
    int value = f.get();
}

try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {  // Java 21
    for (int i = 0; i < 10_000; i++) executor.submit(() -> blockingCall());
}

CompletableFuture.supplyAsync(() -> fetch())
    .thenApply(String::length)
    .exceptionally(ex -> -1)
    .join();

See Threads, Synchronization, Locks, Atomic Variables, Executors, CompletableFuture, Concurrent Collections and Virtual Threads.

Version highlights

Version Headline features
8 (2014) lambdas, streams, Optional, java.time, default methods
9โ€“11 modules, List.of, var (10), HttpClient, String.strip/isBlank/repeat (11, LTS)
14โ€“17 switch expressions (14), text blocks (15), records (16), sealed classes (17, LTS)
21 (LTS) virtual threads, pattern matching for switch, record patterns, sequenced collections
22โ€“24 unnamed variables _ (22), Markdown doc comments (23), stream gatherers (24)
25 (LTS) compact source files and instance main, IO class, module imports, flexible constructor bodies, scoped values

See Java Versions and History, Best Practices and, for databases, web apps and Spring, the Advanced Java course.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does IO.println(1 + 2 + "3" + 4 + 5); print?

    Evaluation goes left to right. 1 + 2 is the int 3; adding "3" gives the string "33"; from then on every + is string concatenation, so you get "3345".
  2. 2. Which collection keeps keys in sorted order and can answer "the largest key smaller than 50"?

    TreeMap is a NavigableMap backed by a red-black tree, so lowerKey(50) or floorKey(50) answer that in O(log n). HashMap has no order, and LinkedHashMap only remembers insertion or access order.
  3. 3. int n = in.nextInt(); String s = in.nextLine(); with the input 5 then Ada on the next line. What is s?

    nextInt() reads the token 5 and stops before the line break, so nextLine() returns the rest of that line, which is empty. Call an extra nextLine() or read whole lines and parse them.
  4. 4. Why is Comparator<Integer> c = (a, b) -> a - b; a bad comparator?

    For example, Integer.MIN_VALUE - 1 overflows to a large positive number. Integer.compare(a, b) or Comparator.naturalOrder() always gets the sign right.

Summary

  • A Java 25 program can be a compact void main() file or a classic public class Main with public static void main(String[] args); print with IO.println or System.out.println, format with printf/formatted.
  • Know the eight primitives, integer division and overflow, the implicit cast in compound assignment, and why == on strings and boxed numbers is a bug.
  • Switch expressions, records, enums, sealed types and pattern matching make modern Java code short and safe; override equals and hashCode together.
  • Pick collections by need: ArrayList, HashMap, HashSet by default; Tree* for sorting, LinkedHash* for order, ArrayDeque for stacks and queues.
  • Lambdas, method references, streams and Optional cover most data processing; java.time, Files and java.util.concurrent cover dates, files and threads.

Next: Java Programs: 40 Classic Examples, where you'll practice these building blocks on short, runnable programs.