Java Cheatsheet
Control Flow
Use this Java reference while you build software engineering projects, review code for technical interview prep, or polish examples for a software engineer resume.
if / else if / else
if (x > 0) { System.out.println("positive"); } else if (x < 0) { System.out.println("negative"); } else { System.out.println("zero"); } // Single-statement bodies (braces optional, but always recommended) if (flag) doSomething();
switch Statement (Classic)
int day = 3; switch (day) { case 1: System.out.println("Mon"); break; // break required to prevent fall-through case 2: System.out.println("Tue"); break; case 6: case 7: // fall-through grouping System.out.println("Weekend"); break; default: System.out.println("Other"); }
Supported types: byte, short, int, char, String (Java 7+), enums.
switch Expression (Java 14+)
Arrow form — no fall-through, no break, whole thing is an expression.
int numLetters = switch (day) { case "MON", "FRI", "SUN" -> 6; case "TUE" -> 7; case "THU", "SAT" -> 8; case "WED" -> 9; default -> throw new IllegalArgumentException("Unknown: " + day); }; // Yield for multi-statement arms String result = switch (code) { case 1 -> "one"; case 2 -> { System.out.println("computing..."); yield "two"; // yield returns a value from a block } default -> "other"; };
Pattern Matching switch (Java 21+)
static String describe(Object obj) { return switch (obj) { case Integer i when i < 0 -> "negative int: " + i; case Integer i -> "int: " + i; case String s -> "string of length " + s.length(); case null -> "null"; default -> "other: " + obj.getClass().getSimpleName(); }; }
for Loop
// Classic for (int i = 0; i < 10; i++) { System.out.println(i); } // Multiple variables for (int i = 0, j = 10; i < j; i++, j--) { ... } // Infinite for (;;) { ... } // Enhanced for-each (Iterable / array) int[] arr = {1, 2, 3, 4, 5}; for (int n : arr) { System.out.println(n); } List<String> names = List.of("Alice", "Bob"); for (String name : names) { System.out.println(name); }
while Loop
int i = 0; while (i < 10) { System.out.println(i); i++; } // Infinite with break while (true) { String input = sc.nextLine(); if (input.equals("quit")) break; }
do-while Loop
Executes the body at least once before checking the condition.
int n; do { System.out.print("Enter positive: "); n = sc.nextInt(); } while (n <= 0);
break, continue, and Labels
// break — exit current loop or switch for (int i = 0; i < 10; i++) { if (i == 5) break; // exits loop when i == 5 } // continue — skip to next iteration for (int i = 0; i < 10; i++) { if (i % 2 == 0) continue; // skip even numbers System.out.println(i); } // Labeled break — exit an outer loop outer: for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { if (i == 2 && j == 2) break outer; // exits both loops } } // Labeled continue outer: for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { if (j == 2) continue outer; // jumps to next i } }
Ternary Operator
int max = (a > b) ? a : b; String msg = (n == 1) ? "item" : "items"; // Nested ternary (discouraged, hard to read) String grade = score >= 90 ? "A" : score >= 80 ? "B" : "C";
try / catch / finally
try { int result = 10 / 0; } catch (ArithmeticException e) { System.out.println("Caught: " + e.getMessage()); } catch (NullPointerException | IllegalArgumentException e) { // multi-catch (Java 7+) e.printStackTrace(); } finally { System.out.println("Always runs"); // cleanup goes here }
See the Exceptions cheatsheet for full coverage of try-with-resources, custom exceptions, etc.
assert
assert x > 0; // throws AssertionError if false assert x > 0 : "x must be positive: " + x; // with message // Enable assertions at runtime: // java -ea MyClass // Disabled by default in production.
yield (switch expression)
int result = switch (x) { case 1 -> 10; default -> { int computed = x * x; yield computed; // exit the block with a value } };
Conditional (Short-Circuit) Evaluation
String s = null; // Safe: right side not evaluated if left is false if (s != null && s.length() > 0) { ... } // Safe: right side not evaluated if left is true if (s == null || s.isEmpty()) { ... } // Non-short-circuit (bitwise on booleans — both sides always evaluated) if (a() & b()) { ... } if (a() | b()) { ... }
Variable in Control Structures
// Variable declared in if condition (not valid in Java — unlike C/C++) // Must declare before: int val = getValue(); if (val > 0) { ... } // for-loop variable scoped to the loop for (int i = 0; i < 10; i++) { ... } // i not accessible here // try-with-resources — resource scoped to try block (Java 7+) try (BufferedReader br = new BufferedReader(new FileReader("f.txt"))) { String line = br.readLine(); } // br not accessible here, and auto-closed
Infinite Loop Patterns
// Common patterns for servers, event loops, retry logic while (true) { ... } for (;;) { ... } // With timeout / counter guard int attempts = 0; while (attempts < 3) { try { doSomething(); break; } catch (Exception e) { attempts++; } }