Java Cheat Sheet: Syntax, Collections, Streams, and Records
Introduction
This Java cheat sheet targets modern Java, version 17 and newer, and notes where a feature needs a later release. Use it as a quick lookup alongside the Java lessons on this site.
Prerequisites
- JDK 17 or newer installed
Step-by-Step Guide
Step 1: Program structure and types
Every Java program starts from a class with a main method. Primitive types hold values, and wrapper types such as Integer are objects.
public class Main {
public static void main(String[] args) {
int age = 36;
long big = 10_000_000_000L;
double price = 9.99;
boolean ok = true;
char letter = 'A';
String name = "Ada";
var list = new java.util.ArrayList<String>(); // local type inference
System.out.println("Hello, " + name);
System.out.printf("%s is %d years old%n", name, age);
}
}
// javac Main.java then java Main
// or run a single file: java Main.javaStep 2: Strings
Strings are immutable. Use equals to compare content, never ==. Text blocks (Java 15 and newer) hold multi-line text.
String s = "Hello, World";
s.length(); s.toUpperCase(); s.trim(); s.strip();
s.substring(0, 5); // "Hello"
s.contains("World"); s.startsWith("He");
s.replace("World", "Java");
String[] parts = s.split(", ");
String.join("-", "a", "b"); // "a-b"
"abc".equals("abc"); // true
"abc".equalsIgnoreCase("ABC");
String text = """
Multi-line
text block
""";
String.format("%.2f", 3.14159);Step 3: Collections
Use List, Set, and Map interfaces and choose an implementation. The of factory methods create immutable collections.
import java.util.*;
List<Integer> nums = new ArrayList<>(List.of(3, 1, 2));
nums.add(4); nums.remove(Integer.valueOf(1)); nums.get(0);
Collections.sort(nums);
Set<String> tags = new HashSet<>(Set.of("a", "b"));
Map<String, Integer> ages = new HashMap<>();
ages.put("Ada", 36);
ages.getOrDefault("Bob", 0);
ages.computeIfAbsent("Eve", key -> 28);
for (Map.Entry<String, Integer> e : ages.entrySet()) {
System.out.println(e.getKey() + " " + e.getValue());
}
Deque<Integer> stack = new ArrayDeque<>();
stack.push(1); stack.pop();Step 4: Control flow
Switch expressions (Java 14 and newer) return a value and avoid fall-through. Pattern matching for instanceof removes casts.
for (int i = 0; i < 3; i++) { }
for (String item : list) { }
while (age < 40) { age++; }
String size = switch (day) {
case 1, 7 -> "weekend";
case 2, 3, 4, 5, 6 -> "weekday";
default -> "unknown";
};
if (obj instanceof String text && !text.isEmpty()) {
System.out.println(text.length());
}Step 5: Classes, interfaces, and records
Records (Java 16 and newer) are compact immutable data carriers. Sealed types (Java 17 and newer) limit which classes can extend them.
public class Account {
private final String owner;
private double balance;
public Account(String owner, double balance) {
this.owner = owner;
this.balance = balance;
}
public void deposit(double amount) { balance += amount; }
public double getBalance() { return balance; }
}
interface Shape { double area(); }
record Circle(double radius) implements Shape {
public double area() { return Math.PI * radius * radius; }
}
record Point(int x, int y) { } // equals, hashCode, toString included
var p = new Point(1, 2); p.x();Step 6: Streams and Optional
Streams process collections in a pipeline. Optional makes missing values explicit.
import java.util.stream.*;
List<Integer> evens = nums.stream()
.filter(n -> n % 2 == 0)
.map(n -> n * n)
.collect(Collectors.toList()); // or .toList() in Java 16+
int total = nums.stream().mapToInt(Integer::intValue).sum();
String joined = names.stream().sorted().collect(Collectors.joining(", "));
Map<Boolean, List<Integer>> split =
nums.stream().collect(Collectors.partitioningBy(n -> n > 2));
Optional<String> found = names.stream().filter(n -> n.startsWith("A")).findFirst();
found.ifPresent(System.out::println);
String value = found.orElse("none");Step 7: Exceptions and file handling
Use try-with-resources so resources close automatically. Checked exceptions must be caught or declared.
import java.nio.file.*;
import java.io.IOException;
try {
String content = Files.readString(Path.of("notes.txt"));
Files.writeString(Path.of("out.txt"), "hello");
} catch (IOException e) {
System.err.println("I/O problem: " + e.getMessage());
} finally {
System.out.println("cleanup");
}
throw new IllegalArgumentException("amount must be positive");FAQs
- Why does == fail for strings?
- == compares object references, not contents. Use equals, or equalsIgnoreCase, to compare string values.
Summary
Modern Java gives you var, text blocks, switch expressions, records, and streams. Compare strings with equals, use try-with-resources, and prefer immutable collections and records.
Related tutorials
- Linux Command Line Cheat Sheet: Files, Permissions, Processes, and Networking
- Docker and kubectl Cheat Sheet: Containers, Images, Compose, and Kubernetes
- SQL Cheat Sheet: SELECT, Joins, Aggregates, and Data Changes
- Git Cheat Sheet: Everyday Commands, Branching, and Undoing Mistakes
- Langflow Cheat Sheet: Install, Components, API Calls, and Custom Components
Comments
Log in or create a free account to join the discussion.