Java
Core Java language reference - syntax, OOP, generics, collections, streams, and modern Java 25 features.
Getting Started
Your first program, compiling, and running Java.
The classic entry point, plus the simplified launch form finalized in Java 25.
// Quick Reference
public class Main {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}Compile to bytecode, run, or launch a single file directly.
// Quick Reference
javac Main.java // compile -> Main.class
java Main // run the class (no .class extension)
java Main.java // compile + run a single file in one stepVariables & Data Types
Primitives, type inference, constants, and wrappers.
Java's eight built-in value types.
// Quick Reference
int i = 42;
long l = 42L;
double d = 3.14;
float f = 3.14f;
boolean b = true;
char c = 'A';Local type inference, constants, casting, and boxed types.
// Quick Reference
var name = "Sam"; // inferred as String
final int MAX = 100; // constant, cannot reassign
Integer boxed = 42; // wrapper object (nullable)Operators
Arithmetic, comparison, logical, and type checks.
Everyday operators plus the ternary and instanceof pattern.
// Quick Reference
+ - * / % // arithmetic
== != < > <= >= // comparison
&& || ! // logical
condition ? a : b // ternaryMath & Numbers
The Math class, parsing, exact decimals, and randomness.
Common numeric operations and gotchas.
// Quick Reference
Math.max(3, 7); Math.abs(-5); Math.pow(2, 10);
Math.sqrt(16); Math.round(3.6);
int n = Integer.parseInt("42");Strings & Text Blocks
Working with text, builders, and multi-line strings.
Common operations on immutable strings.
// Quick Reference
s.length() s.charAt(0)
s.toUpperCase() s.trim() s.strip()
s.substring(1, 4) s.split(",")
s.contains("x") s.replace("a", "b")Efficient concatenation, multi-line text, and formatting.
// Quick Reference
var sb = new StringBuilder();
sb.append("a").append("b");
String out = sb.toString();
String json = """
{ "name": "Sam" }
"""; // text blockRegular Expressions
Matching, capturing groups, and replacing with regex.
Java regex via String helpers and the Pattern/Matcher API.
// Quick Reference
"abc123".matches("[a-z]+\\d+"); // true (whole string)
"a1b2".replaceAll("\\d", "#"); // "a#b#"
"a,b;c".split("[,;]"); // ["a", "b", "c"]Control Flow
Branching, modern switch, and loops.
if/else and switch expressions with pattern matching.
// Quick Reference
if (x > 0) { ... } else if (x < 0) { ... } else { ... }
String r = switch (day) {
case 6, 7 -> "weekend";
default -> "weekday";
};for, enhanced for, while, and do-while.
// Quick Reference
for (int i = 0; i < 5; i++) { ... }
for (String s : list) { ... } // enhanced for
while (cond) { ... }
do { ... } while (cond);Methods
Defining behavior, overloading, and varargs.
Parameters, return types, overloading, and varargs.
// Quick Reference
returnType name(params) { ... return value; }
void greet(String n) { ... } // no return value
int add(int... nums) { ... } // varargsClasses & Records
Objects, constructors, encapsulation, and records.
Fields, constructors, this, and access modifiers.
// Quick Reference
class Person {
private String name;
Person(String name) { this.name = name; }
String getName() { return name; }
}
var p = new Person("Sam");Class-level members and concise immutable data carriers.
// Quick Reference
static int count = 0; // shared across all instances
static final double PI = 3.14; // constant
record Point(int x, int y) {} // immutable data classInheritance & Interfaces
Reuse, polymorphism, contracts, and sealed hierarchies.
extends, super, overriding, and abstract base classes.
// Quick Reference
class Dog extends Animal {
@Override
void speak() { System.out.println("Woof"); }
}
abstract class Animal { abstract void speak(); }Contracts with default methods and restricted hierarchies.
// Quick Reference
interface Shape {
double area(); // abstract
default String label() { return "shape"; } // default method
}
sealed interface Expr permits Num, Add {}Enums
Type-safe sets of named constants.
Simple constants and enums with fields and methods.
// Quick Reference
enum Day { MON, TUE, WED }
Day d = Day.MON;
switch (d) { case MON -> ...; }Annotations
Built-in markers and defining your own.
The common annotations plus a custom one read via reflection.
// Quick Reference
@Override // method overrides a supertype method
@Deprecated // API is obsolete
@FunctionalInterface // exactly one abstract method
@SuppressWarnings("unchecked")Generics
Type-safe, reusable classes and methods.
Generic classes, methods, bounds, and wildcards.
// Quick Reference
class Box<T> { T value; }
<T> T first(List<T> list) { return list.get(0); }
List<? extends Number> nums; // wildcardArrays & Collections
Fixed arrays plus the core List, Map, and Set types.
Fixed-size sequences and the Arrays utility class.
// Quick Reference
int[] nums = {1, 2, 3};
int[] zeros = new int[5];
nums.length; // 3
Arrays.sort(nums);The most-used resizable, ordered collection.
// Quick Reference
List<String> list = new ArrayList<>();
list.add("a"); list.get(0);
list.remove("a"); list.size();
var fixed = List.of("x", "y"); // immutableKey-value pairs and unique collections.
// Quick Reference
Map<String, Integer> m = new HashMap<>();
m.put("a", 1); m.get("a");
Set<String> set = new HashSet<>();
set.add("x"); set.contains("x");Exception Handling
Catching, throwing, and cleaning up resources.
try/catch/finally, resources, and custom exceptions.
// Quick Reference
try {
risky();
} catch (IOException e) {
e.printStackTrace();
} finally {
cleanup();
}Lambdas & Functional Interfaces
First-class behavior with lambdas and method references.
Concise functions and the built-in functional interfaces.
// Quick Reference
Runnable r = () -> System.out.println("hi");
Function<Integer, Integer> sq = x -> x * x;
list.forEach(System.out::println); // method referenceStreams & Optional
Declarative data pipelines and null-safe containers.
Transform and aggregate collections functionally.
// Quick Reference
list.stream()
.filter(x -> x > 2)
.map(x -> x * 10)
.toList();Grouping, joining, and null-safe results.
// Quick Reference
stream.collect(Collectors.groupingBy(fn));
stream.collect(Collectors.joining(", "));
Optional<T> o = ...; o.orElse(fallback);Concurrency
Threads, synchronization, executors, and virtual threads.
Creating threads and guarding shared state.
// Quick Reference
Thread t = new Thread(() -> System.out.println("run"));
t.start();
t.join(); // wait for it to finish
synchronized void inc() { count++; }Thread pools, futures, and lightweight virtual threads (21+).
// Quick Reference
try (var ex = Executors.newVirtualThreadPerTaskExecutor()) {
ex.submit(() -> handle());
}
Thread.startVirtualThread(() -> work()); // Java 21+Date & Time
The modern immutable java.time API.
Dates, times, instants, durations, and formatting.
// Quick Reference
LocalDate today = LocalDate.now();
LocalDateTime dt = LocalDateTime.now();
today.plusDays(7);
today.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));File I/O
Reading and writing files with the NIO API.
Modern file reading and writing with java.nio.
// Quick Reference
Path p = Path.of("data.txt");
String text = Files.readString(p);
Files.writeString(p, "hello");
List<String> lines = Files.readAllLines(p);Modern Java (25)
Language features finalized in and around today's LTS.
Deconstruct records and match by shape.
// Quick Reference
record Point(int x, int y) {}
String s = switch (obj) {
case Point(int x, int y) -> x + "," + y; // record pattern
default -> "other";
};Finalized features that simplify everyday code.
// Quick Reference
void main() { // compact source file (JEP 512)
IO.println("Hi!");
}
import module java.base; // module import (JEP 511)