Short answer: Modern Java code uses var for local variables, List.of and Map.of for collections, records for data classes, switch expressions with pattern matching, and streams for filtering and grouping. Java 25 is the current long-term support release; it lets a small program start with just void main(), and java Main.java runs a source file without a separate compile step. The tables below cover the syntax you will use most, tested on Java 25 and 21.
The examples in this Java cheat sheet were run with OpenJDK 25.0.4.1 (Temurin) and OpenJDK 21.0.10 on 9 October 2026. Features marked Java 25 fail to compile on Java 21.
Table of Contents
Running Java: javac, java and compact source files
| Command | What it does |
|---|---|
java -version | Show the runtime version (Java 25 is the current LTS; Java 21 is the previous one) |
java Main.java | Compile in memory and run a single source file, no javac step |
javac -d out Main.java · java -cp out Main | Compile to classes · run them |
jar --create --file app.jar --main-class Main -C out . | Package classes into a runnable JAR |
java -jar app.jar | Run a JAR |
java -Xmx512m -jar app.jar | Cap the heap at 512 MB |
jcmd · jcmd <pid> GC.heap_info | List running JVMs · inspect one |
Java 25 lets a small program skip the class and the static boilerplate. A compact source file imports all of java.base automatically, and the new IO class handles console input and output:
// Hello.java, run with: java Hello.java (Java 25)
void main() {
List<String> hosts = List.of("web01", "db01");
for (var h : hosts) IO.println(h);
String name = IO.readln("Name? ");
IO.println("Hi " + name);
}
On Java 21, use the classic form: public class Main { public static void main(String[] args) { System.out.println("Hi"); } }.
Variables, types and strings
| Syntax | What it does |
|---|---|
int port = 443; · long big = 10_000_000_000L; | Primitive types; underscores aid readability |
double load = 0.75; · boolean up = true; · char c = 'A'; | Other common primitives |
var host = "web01"; | Local type inference (the type is still fixed: String) |
final int MAX = 3; | Cannot be reassigned |
7 / 2 · 7.0 / 2 · (int) 3.9 | 3 (integer division) · 3.5 · 3 (cast truncates) |
Integer.parseInt("42") · String.valueOf(10) | Parse and convert |
a.equals(b) | Compare string content. == compares references and can be false for equal text |
s.strip() · s.isBlank() · s.split(",") | Trim (Unicode-aware) · whitespace only? · split by regex |
String.join("-", list) · "Hi".repeat(2) | Join · repeat |
s.substring(1, 3) · s.contains("ell") · s.charAt(0) | Substring · contains · one character |
s.replaceAll("\\d", "#") | Regex replace; backslashes are doubled in Java strings |
String.format("%s:%d %.1f%%", host, port, pct) | printf-style formatting |
"%s:%d".formatted(host, port) | Same, called on the format string |
new StringBuilder().append(i).append(',') | Build strings in a loop efficiently |
String json = """
{
"host": "db01",
"port": 3306
}
"""; // text block: indentation is stripped to the closing quotes
Collections
| Syntax | What it does |
|---|---|
List.of("a", "b") · Map.of("ssh", 22) · Set.of(1, 2) | Immutable collections; add throws UnsupportedOperationException |
new ArrayList<>(List.of(...)) | A mutable copy |
list.add(x) · list.add(0, x) · list.remove(x) · list.get(0) | Add, insert, remove, read |
list.getFirst() · list.getLast() · list.reversed() | Sequenced collections (Java 21) |
map.put(k, v) · map.get(k) · map.getOrDefault(k, 25) | Write, read, read with default |
map.putIfAbsent(k, v) · map.containsKey(k) | Set only if missing · key test |
counts.merge(word, 1, Integer::sum) | Count occurrences in one line |
map.computeIfAbsent(k, x -> new ArrayList<>()).add(v) | Group values into lists |
for (var e : map.entrySet()) · map.forEach((k, v) -> ...) | Iterate a map |
new TreeMap<>() · new LinkedHashMap<>() | Sorted keys · insertion order (HashMap has no order) |
new ArrayDeque<>() with push · pop · peek | Stack or queue (prefer over Stack) |
Arrays.sort(arr) · Arrays.toString(arr) | Sort and print a primitive array |
list.sort(Comparator.comparing(String::length)) | Sort by a key; chain .thenComparing(...) |
Control flow, switch and pattern matching
int hours = switch (day) { // switch expression
case "SAT", "SUN" -> 0;
case "FRI" -> 6;
default -> { int h = 8; yield h; }
};
if (o instanceof String str && str.length() > 3) { // pattern: no cast needed
System.out.println(str.toUpperCase());
}
static String describe(Object o) {
return switch (o) { // pattern matching for switch (Java 21)
case null -> "null";
case Integer i when i > 1000 -> "big int " + i;
case Integer i -> "int " + i;
case String s -> "string of " + s.length();
case Server(var name, var ip, var port) -> "server " + name; // record pattern
default -> "other";
};
}
Loops are the familiar for (int i = 0; i < 3; i++), for (String h : hosts), while and do ... while. Java 22 and later accept _ for a variable you do not use, for example catch (NumberFormatException _).
Classes, records, enums and sealed types
record Server(String name, String ip, int port) {
Server { // compact constructor: validation
if (port < 1 || port > 65535) throw new IllegalArgumentException("bad port: " + port);
}
Server(String name, String ip) { this(name, ip, 22); }
String address() { return ip + ":" + port; }
}
// equals, hashCode, toString and accessors (srv.name()) are generated
enum Level { INFO, WARN, ERROR;
boolean serious() { return this != INFO; }
}
sealed interface Shape permits Circle, Square {}
record Circle(double r) implements Shape {}
record Square(double side) implements Shape {}
static double area(Shape s) {
return switch (s) { // no default: the compiler knows every case
case Circle c -> Math.PI * c.r() * c.r();
case Square(double side) -> side * side;
};
}
| Keyword | Meaning |
|---|---|
private · protected · public · (none) | Class only · package and subclasses · everywhere · package only |
static | Belongs to the class, not an instance |
abstract class · interface with default methods | Partial implementation · contract with optional shared code |
extends · implements · @Override | Inherit a class · implement interfaces · check you really override |
Java 25 also allows statements before super(...) in a constructor, so you can validate arguments before the parent constructor runs.
Lambdas and streams
| Syntax | What it does |
|---|---|
nums.stream().filter(x -> x > 2).map(x -> x * 10).toList() | Filter and transform; toList() returns an unmodifiable list |
.mapToInt(Integer::intValue).sum() | Sum (also average(), max()) |
.sorted() · .distinct() · .limit(10) | Sort, de-duplicate, take first N |
.anyMatch(fn) · .allMatch(fn) · .count() | Tests and counting |
.collect(Collectors.groupingBy(fn, Collectors.counting())) | Group and count |
.collect(Collectors.joining(", ")) | Join to one string |
IntStream.rangeClosed(1, 5) | Numbers 1 to 5 |
.findFirst().orElse("none") | Optional result with a default |
Function<T,R> · Supplier<T> · Predicate<T> · Consumer<T> | Common functional interfaces |
String::isEmpty · System.out::println | Method references |
.gather(Gatherers.windowFixed(2)) | Custom intermediate operations (Java 24+) |
Exceptions and try-with-resources
static int parsePort(String v) throws ConfigException { // checked exception must be declared
try {
return Integer.parseInt(v);
} catch (NumberFormatException e) {
throw new ConfigException("bad port: " + v, e); // keep the cause
}
}
try {
risky();
} catch (NullPointerException | IllegalStateException e) { // multi-catch
log(e);
} finally {
cleanup();
}
try (BufferedReader r = Files.newBufferedReader(path)) { // closed automatically
String line;
while ((line = r.readLine()) != null) { ... }
}
For server admins: files, processes and HTTP
| Syntax | What it does |
|---|---|
Path log = Path.of("/var/log/app.log") | A path; dir.resolve("x.log") joins |
Files.readString(log) · Files.readAllLines(log) | Whole file · list of lines (small files only) |
try (Stream<String> lines = Files.lines(log)) { ... } | Stream a large file line by line; close it with try |
Files.writeString(p, text, CREATE, APPEND) | Write or append (StandardOpenOption) |
Files.exists(p) · Files.size(p) · Files.createDirectories(p) | Test, size, mkdir -p |
try (Stream<Path> w = Files.walk(dir)) { ... } | Recursive listing |
new ProcessBuilder("df", "-h", "/").redirectErrorStream(true).start() | Run a command without a shell; read getInputStream(), then waitFor() for the exit code |
System.getenv("HOME") · System.getProperty("java.version") | Environment and JVM properties |
Runtime.getRuntime().availableProcessors() | CPU count the JVM sees (respects container limits) |
HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build();
HttpRequest req = HttpRequest.newBuilder(URI.create("https://example.com/"))
.timeout(Duration.ofSeconds(10)).GET().build();
HttpResponse<String> res = client.send(req, HttpResponse.BodyHandlers.ofString());
System.out.println(res.statusCode());
To parse an Apache or Nginx timestamp, use DateTimeFormatter.ofPattern("dd/MMM/yyyy:HH:mm:ss Z", Locale.ENGLISH) with ZonedDateTime.parse. Pass Locale.ENGLISH, or month names such as Oct fail to parse on servers with a different default locale.
Official documentation (checked 9 October 2026): JDK 25 Documentation · Java SE 25 API · JEP 512: Compact Source Files and Instance Main Methods · JEP 441: Pattern Matching for switch · JEP 440: Record Patterns · Dev.java: Learn Java
Java Cheat Sheet at a glance


Related guides: Kotlin Cheat Sheet: Syntax, Null Safety and Collections · C# Cheat Sheet: Syntax, LINQ and .NET 10 Essentials · SQL Cheat Sheet: MySQL, MariaDB and PostgreSQL Syntax.
Reading a lot of our guides? Go ad-free with srvScripts Pro for $6 a month. It also pays for new guides. Cancel any time.