Java Cheat Sheet

Java reference with collections, streams, lambdas, records, and modern Java features. Copy-ready code for Java developers.

75 entries 7 sections

Variables

Syntax Description Example
Integer variable (32-bit) int count = 0;
Long integer (64-bit) long timestamp = System.currentTimeMillis();
Double-precision float double price = 19.99;
Boolean variable boolean isValid = true;
Character variable char grade = 'A';
String object String name = "Alice";
Local type inference (Java 10+) var list = new ArrayList<String>();
Immutable variable final int MAX_SIZE = 100;
Print with newline System.out.println("Hello " + name);
Formatted print System.out.printf("%.2f%n", price);

Strings

Syntax Description Example
String length "hello".length() // 5
Character at index "hello".charAt(0) // 'h'
Extract substring "hello".substring(1, 4) // "ell"
Check if contains substring "hello".contains("ell") // true
Check prefix/suffix "hello".startsWith("he") // true
Find position of substring "hello".indexOf("ll") // 2
Replace occurrences "hello".replace("l", "r") // "herro"
Split into array "a,b,c".split(",") // ["a","b","c"]
Remove whitespace " hi ".strip() // "hi"
Change case "hello".toUpperCase() // "HELLO"
Check empty / blank (11+) " ".isBlank() // true
Format string String.format("%s is %d", name, age)
String equality (not ==) "hi".equals(input) // correct comparison
Join strings String.join(", ", list) // "a, b, c"
Multi-line text block (13+) var json = """ {"key": "value"} """;

Collections

Syntax Description Example
Dynamic list List<String> names = new ArrayList<>();
Add element names.add("Alice");
Get / set by index String first = names.get(0);
Remove by index or value names.remove("Alice");
Size / check empty if (list.isEmpty()) { ... }
Check if list contains element names.contains("Alice") // true
Sort a list Collections.sort(names);
Immutable list (Java 9+) var nums = List.of(1, 2, 3);
Hash map Map<String, Integer> ages = new HashMap<>();
Set / get map entry ages.put("Alice", 30); ages.get("Alice");
Check if key exists ages.containsKey("Alice") // true
Get with fallback ages.getOrDefault("Bob", 0) // 0
Iterate map contents for (var e : map.entrySet()) { ... }
Immutable map (Java 9+) var m = Map.of("a", 1, "b", 2);
Hash set (unique values) Set<String> tags = new HashSet<>();

Control Flow

Syntax Description Example
Conditional branching if (x > 0) { ... } else { ... }
Switch statement switch (day) { case "Mon" -> ...; default -> ...; }
Switch with return value var result = switch(x) { case 1 -> "one"; default -> "other"; };
For loop for (int i = 0; i < 10; i++) { ... }
Enhanced for-each for (String name : names) { ... }
While loop while (count < 10) { count++; }
Exception handling try { ... } catch (IOException e) { ... } finally { ... }
Try-with-resources (auto-close) try (var reader = new FileReader(f)) { ... }
Throw exception throw new IllegalArgumentException("bad input");

Methods

Syntax Description Example
Method definition public int add(int a, int b) { return a + b; }
Static method (no instance) public static void main(String[] args) { ... }
Lambda expression (Java 8+) list.sort((a, b) -> a.compareTo(b));
Method reference list.forEach(System.out::println);
Varargs void log(String... messages) { ... }

Streams

Syntax Description Example
Create a stream from collection names.stream().filter(...).collect(...);
Filter elements .filter(s -> s.length() > 3)
Transform elements .map(String::toUpperCase)
Map and flatten .flatMap(Collection::stream)
Sort stream .sorted(Comparator.reverseOrder())
Collect to list var result = stream.collect(Collectors.toList());
Reduce to single value .reduce(0, Integer::sum)
Execute action for each element .forEach(System.out::println)
Find first/any matching element .filter(s -> s.startsWith("A")).findFirst()
Aggregate operations long count = names.stream().count();
Remove duplicates nums.stream().distinct().collect(...);
Group elements by key .collect(Collectors.groupingBy(String::length))

OOP

Syntax Description Example
Define a class public class User { private String name; }
Inheritance class Admin extends User { ... }
Implement interface class Dog implements Animal { ... }
Define an interface interface Drawable { void draw(); }
Abstract class abstract class Shape { abstract double area(); }
Data class (Java 16+) record Point(double x, double y) {}
Restrict subclasses sealed class Shape permits Circle, Square {}
Override annotation @Override public String toString() { ... }
Optional container Optional.ofNullable(value).orElse("default")

Frequently asked questions

Which Java version should I use?

Use the latest LTS (Long-Term Support) version: Java 21 (as of 2024). It includes records, sealed classes, pattern matching, virtual threads, and text blocks. Java 17 is the previous LTS. Avoid anything below Java 11 for new projects.

What's the difference between == and .equals()?

== compares references (are they the same object in memory). .equals() compares values (do they have the same content). For objects like String, always use .equals(). For primitives (int, double), use ==. This is Java's most common gotcha.

ArrayList vs LinkedList - which should I use?

ArrayList almost always. It has O(1) random access and better cache locality. LinkedList is theoretically better for frequent insertions in the middle, but in practice ArrayList wins due to CPU cache effects. Use ArrayDeque for stack/queue needs.

What are Java virtual threads?

Virtual threads (Java 21, Project Loom) are lightweight threads managed by the JVM. You can create millions of them. They make blocking I/O code scale like async code without the complexity. Use Thread.ofVirtual().start(() -> { ... }).

How does garbage collection work in Java?

Java automatically manages memory through garbage collection. Objects with no references are automatically cleaned up. Modern GCs (G1, ZGC, Shenandoah) have very low pause times. You rarely need to think about memory, but avoid creating unnecessary objects in hot loops.

What's the difference between interface and abstract class?

Interfaces define contracts with no state (pre-Java 8). Since Java 8, they can have default methods. Abstract classes can have state (fields) and constructors. A class can implement multiple interfaces but extend only one class. Prefer interfaces for flexibility.

Go from reference to real skills

Cheat sheets are great for quick lookups. Our in-depth courses take you from the fundamentals to professional-level mastery.

Browse all courses