📋 Cheat Sheets

Java Cheat Sheet — Syntax, Collections, and Common Patterns


Click any item to expand the explanation and examples.

📝 Basics

Variables and types basics
// Primitives
int count = 42;
long big = 9999999999L;
double price = 19.99;
float rate = 3.14f;
boolean active = true;
char letter = 'A';
byte b = 127;
short s = 32000;

// Strings (not a primitive — it’s an object) String name = “Alice”; String greeting = “Hello ” + name;

// var (Java 10+ — type inference) var list = new ArrayList<String>(); var count = 42;

// Constants final int MAX_SIZE = 100; static final String APP_NAME = “MyApp”;

// Arrays int[] nums = {1, 2, 3, 4, 5}; String[] names = new String[10]; int[][] matrix = {{1, 2}, {3, 4}};

String operations basics
String s = "Hello World";

s.length() // 11 s.charAt(0) // ‘H’ s.substring(0, 5) // “Hello” s.toLowerCase() // “hello world” s.toUpperCase() // “HELLO WORLD” s.trim() // Remove whitespace s.contains(“World”) // true s.startsWith(“Hello”) // true s.indexOf(“World”) // 6 s.replace(“World”, “Java”) // “Hello Java” s.split(” ”) // [“Hello”, “World”] s.isEmpty() // false s.isBlank() // false (Java 11+)

// String comparison (NEVER use ==) s.equals(“Hello World”) // true s.equalsIgnoreCase(“hello world”) // true

// String formatting String.format(“Hello %s, age %d”, name, age); “Hello %s”.formatted(name); // Java 15+

// Text blocks (Java 15+) String json = """ { “name”: “Alice”, “age”: 30 } """;

📦 Collections

List, Set, Map collections
// List (ordered, allows duplicates)
List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.get(0);           // "Alice"
names.size();           // 2
names.contains("Alice"); // true
names.remove("Bob");
names.isEmpty();

// Immutable list (Java 9+) var names = List.of(“Alice”, “Bob”, “Carol”);

// Set (unique, unordered) Set<String> tags = new HashSet<>(); tags.add(“java”); tags.add(“java”); // Ignored — already exists tags.size(); // 1

// Map (key-value) Map<String, Integer> ages = new HashMap<>(); ages.put(“Alice”, 30); ages.get(“Alice”); // 30 ages.getOrDefault(“Bob”, 0); // 0 ages.containsKey(“Alice”); // true ages.keySet(); // Set of keys ages.values(); // Collection of values ages.entrySet(); // Set of entries

// Immutable map (Java 9+) var ages = Map.of(“Alice”, 30, “Bob”, 25);

🔁 Control Flow

Loops and conditionals flow
// For loop
for (int i = 0; i < 10; i++) { }

// Enhanced for (foreach) for (String name : names) { }

// While while (condition) { }

// Switch (classic) switch (day) { case “MON”: System.out.println(“Monday”); break; case “FRI”: System.out.println(“Friday”); break; default: System.out.println(“Other”); }

// Switch expression (Java 14+) String result = switch (day) { case “MON”, “TUE”, “WED”, “THU”, “FRI” -> “Weekday”; case “SAT”, “SUN” -> “Weekend”; default -> “Unknown”; };

// Ternary String status = age >= 18 ? “adult” : “minor”;

⚡ Streams (Java 8+)

Stream operations streams
List<String> names = List.of("Alice", "Bob", "Carol", "Dave");

// Filter names.stream() .filter(n -> n.startsWith(“A”)) .toList(); // [“Alice”]

// Map (transform) names.stream() .map(String::toUpperCase) .toList(); // [“ALICE”, “BOB”, …]

// Find names.stream().findFirst(); // Optional<String> names.stream().anyMatch(n -> n.equals(“Bob”)); // true

// Reduce List<Integer> nums = List.of(1, 2, 3, 4, 5); int sum = nums.stream().reduce(0, Integer::sum); // 15

// Collect to map Map<String, Integer> nameLengths = names.stream() .collect(Collectors.toMap(n -> n, String::length));

// Sort names.stream().sorted().toList(); names.stream().sorted(Comparator.reverseOrder()).toList();

// Chain names.stream() .filter(n -> n.length() > 3) .map(String::toUpperCase) .sorted() .toList();

🏗️ OOP

Classes, interfaces, records oop
// Class
public class User {
    private String name;
    private int age;
public User(String name, int age) {
    this.name = name;
    this.age = age;
}

public String getName() { return name; }
public int getAge() { return age; }

}

// Record (Java 16+ — immutable data class) public record User(String name, int age) {} // Auto-generates constructor, getters, equals, hashCode, toString

// Interface public interface Printable { void print(); default void printUpperCase() { // Default method System.out.println(toString().toUpperCase()); } }

// Enum public enum Status { ACTIVE, INACTIVE, PENDING; }

// Sealed classes (Java 17+) public sealed interface Shape permits Circle, Rectangle {} public record Circle(double radius) implements Shape {} public record Rectangle(double w, double h) implements Shape {}

⚠️ Error Handling

try/catch, Optional errors
// Try-catch
try {
    int result = 10 / 0;
} catch (ArithmeticException e) {
    System.err.println("Error: " + e.getMessage());
} finally {
    // Always runs
}

// Try-with-resources (auto-closes) try (var reader = new BufferedReader(new FileReader(“file.txt”))) { String line = reader.readLine(); }

// Optional (avoid null) Optional<String> name = Optional.of(“Alice”); Optional<String> empty = Optional.empty();

name.isPresent(); // true name.get(); // “Alice” name.orElse(“Unknown”); // “Alice” empty.orElse(“Unknown”); // “Unknown” name.map(String::toUpperCase); // Optional[“ALICE”] name.ifPresent(System.out::println);