Java cheatsheet – syntax overview
80 key commands and patterns for quick reference.
Basics Types & operators Control flow Strings Arrays & lists Maps & sets Classes, records & enums Errors & files Lambdas & streams Optional & concurrency
Basics
System.out.println("Text " + x); | Output with a line break |
System.out.printf("%d %s %.2f%n", 1, "a", 2.5); | Formatted output |
Scanner sc = new Scanner(System.in);
String s = sc.nextLine(); | Read input from the console |
// Comment /* Block */ /** Javadoc */ | Comments |
var x = 42; | Local type inference (Java 10+) |
final int MAX = 10; | Constant (cannot be changed) |
java File.java javac File.java | Run directly / compile |
Types & operators
int long double float boolean char byte short | The eight primitive types |
Integer.parseInt("5") Double.parseDouble("2.5") | Convert text to a number |
String.valueOf(5) Integer.toString(5) | Convert a number to text |
(int) 3.9 (double) 7 / 2 | Cast (explicit conversion) |
+ - * / % | Arithmetic (with int, / is integer division) |
== != < > <= >= && || ! | Comparisons and logic |
Math.max(a, b) Math.abs(x) Math.pow(2, 10) Math.sqrt(x) | Common math functions |
Integer.MAX_VALUE Long.MIN_VALUE | Limits of the types |
Control flow
if (x > 0) { ... } else if (x == 0) { ... } else { ... } | Branching |
String s = x > 0 ? "pos" : "not pos"; | Ternary operator |
switch (x) { case 1, 2 -> "a"; default -> "b"; } | switch expression with an arrow |
for (int i = 0; i < n; i++) { } | Counting loop |
for (String s : liste) { } | for-each over a collection |
while (bed) { } do { } while (bed); | Loops with a condition |
break; continue; yield wert; | Abort / continue / value in a switch block |
Strings
s.length() s.charAt(0) s.isEmpty() s.isBlank() | Length, character, check for empty |
s.toUpperCase() s.toLowerCase() s.strip() | Convert and trim |
s.substring(1, 4) s.indexOf("x") s.contains("x") | Substring and searching |
s.split(",") String.join("-", liste) | Split and join |
s.replace("a", "b") s.repeat(3) | Replace and repeat |
a.equals(b) a.equalsIgnoreCase(b) | Compare content (never with ==) |
"Hello %s".formatted(name) | String formatting (Java 15+) |
String t = """
Multi-line
"""; | Text block |
Arrays & lists
int[] a = new int[5]; int[] b = {1, 2, 3}; | Create an array |
a.length Arrays.toString(a) Arrays.sort(a) | Length, print, sort |
List<String> l = new ArrayList<>(); | Mutable list |
List.of(1, 2, 3) List.copyOf(l) | Immutable list |
l.add(x) l.get(i) l.set(i, x) l.remove(i) | Basic operations |
l.size() l.isEmpty() l.contains(x) l.indexOf(x) | Queries |
l.sort(Comparator.naturalOrder()) Collections.reverse(l) | Sort / reverse |
l.getFirst() l.getLast() l.reversed() | First, last, reversed view (Java 21) |
Maps & sets
Map<String, Integer> m = new HashMap<>(); | Create a map (unordered) |
m.put("a", 1) m.get("a") m.getOrDefault("b", 0) | Set and read |
m.containsKey("a") m.remove("a") m.size() | Check, remove, size |
for (var e : m.entrySet()) { e.getKey(); e.getValue(); } | Iterate over pairs |
m.merge(k, 1, Integer::sum) | Increment a counter |
m.computeIfAbsent(k, x -> new ArrayList<>()).add(v) | Create a list per key |
new LinkedHashMap<>() new TreeMap<>() | Insertion order / sorted |
Set<Integer> s = new HashSet<>(List.of(1, 2, 2)); | Set: unique values only |
Classes, records & enums
class A extends B implements C { } | Inheritance and interfaces |
record P(int x, int y) {} | Record: immutable data class |
enum Farbe { ROT, GRUEN } | Enum: fixed set of values |
interface I { default void f() { } } | Interface with a default method |
abstract class A { abstract void f(); } | Abstract class |
sealed interface S permits A, B {} | Closed type hierarchy (Java 17) |
@Override @FunctionalInterface @Deprecated | Common annotations |
this.x = x; super(x); static int zaehler; | this, super and static fields |
Errors & files
try { } catch (IOException | RuntimeException e) { } finally { } | Error handling with multi-catch |
throw new IllegalArgumentException("Text"); | Throw an error |
void f() throws IOException { } | Pass on a checked exception |
try (var in = Files.newBufferedReader(p)) { } | try-with-resources |
Path p = Path.of("daten", "a.txt"); | Platform-independent path |
Files.readString(p) Files.readAllLines(p) | Read a file |
Files.writeString(p, "text") Files.exists(p) | Write / check a file |
Files.lines(p) Files.list(ordner) | Lines / folder contents as a stream (close it!) |
Lambdas & streams
(a, b) -> a + b String::length | Lambda and method reference |
liste.stream().filter(x -> x > 1).map(x -> x * 2).toList() | Filter and transform |
.sorted() .sorted(Comparator.comparing(P::name)) | Sort |
.distinct() .limit(5) .skip(2) | Duplicates, limit, skip |
.mapToInt(Integer::intValue).sum() | Sum (also average, max, min) |
.collect(Collectors.groupingBy(P::stadt)) | Group like GROUP BY |
.collect(Collectors.joining(", ")) | Join strings |
.anyMatch(p) .allMatch(p) .findFirst() .count() | Queries and terminal operations |
IntStream.rangeClosed(1, 5) | Number sequence 1..5 |
Optional & concurrency
Optional.ofNullable(x) Optional.empty() | Create an Optional |
o.map(f).orElse("standard") | Transform with a fallback value |
o.ifPresent(v -> ...) o.orElseThrow() | Use the value or throw an error |
Executors.newFixedThreadPool(4) | Thread pool |
Executors.newVirtualThreadPerTaskExecutor() | Virtual threads (Java 21) |
CompletableFuture.supplyAsync(() -> x).thenApply(f).join() | Asynchronous chaining |
AtomicInteger n = new AtomicInteger(); n.incrementAndGet(); | Thread-safe counter |
synchronized (lock) { } | Critical section |
ConcurrentHashMap<K, V> | Thread-safe map |