JavaJava Cheat Sheet

Java Cheat Sheet

A dense, scannable quick-reference for core Java syntax. Use it to jog your memory, not as a first introduction — follow the links in the sidebar for full explanations of any topic here.

Data Types

Primitives and common reference types

Java
byte    b  = 127;              // 8-bit
short   sh = 32_000;            // 16-bit
int     i  = 2_000_000_000;     // 32-bit
long    l  = 9_000_000_000L;    // 64-bit — note the L suffix
float   f  = 3.14f;             // 32-bit floating point — note the f suffix
double  d  = 3.14159;           // 64-bit floating point
char    c  = 'A';               // 16-bit Unicode character
boolean flag = true;

String  s  = "hello";           // reference type, immutable
Integer boxed = 42;             // wrapper type — autoboxes to/from int
var     inferred = "type inferred from the right-hand side";
Operators

Arithmetic, comparison, logical, ternary

Java
int sum = 5 + 3, diff = 5 - 3, prod = 5 * 3, quot = 5 / 3, rem = 5 % 3;
int inc = 5; inc++; inc--; inc += 2; inc -= 2; inc *= 2; inc /= 2;

boolean eq  = (5 == 5);
boolean neq = (5 != 3);
boolean and = (5 > 3) && (3 > 1);
boolean or  = (5 > 3) || (1 > 3);
boolean not = !(5 > 3);

String result = (5 > 3) ? "bigger" : "smaller"; // ternary operator

int bitAnd = 5 & 3, bitOr = 5 | 3, bitXor = 5 ^ 3, bitShift = 5 << 1;
Control Flow

if/else, switch, loops

Java
if (score >= 90) {
    grade = "A";
} else if (score >= 80) {
    grade = "B";
} else {
    grade = "F";
}

String day = switch (dayNumber) {
    case 1, 7 -> "Weekend";
    case 2, 3, 4, 5, 6 -> "Weekday";
    default -> "Invalid";
};

for (int i = 0; i < 10; i++) { /* ... */ }
for (String item : list) { /* enhanced for */ }
while (condition) { /* ... */ }
do { /* ... */ } while (condition);

for (int i = 0; i < 10; i++) {
    if (i == 3) continue;
    if (i == 7) break;
}
Arrays & Strings

Array and String essentials

Java
int[] nums = {1, 2, 3, 4, 5};
int[][] grid = new int[3][3];
int length = nums.length;
Arrays.sort(nums);
int idx = Arrays.binarySearch(nums, 3);
String asString = Arrays.toString(nums);

String s = "Hello, World!";
int len = s.length();
String upper = s.toUpperCase();
String sub = s.substring(0, 5);
boolean has = s.contains("World");
String[] parts = s.split(", ");
String joined = String.join("-", "a", "b", "c");
boolean same = s.equalsIgnoreCase("HELLO, WORLD!");
StringBuilder sb = new StringBuilder();
sb.append("a").append("b").insert(0, "z");
OOP Syntax

Class, interface, inheritance, record, enum

Java
public class Animal {
    protected String name;

    public Animal(String name) { this.name = name; }

    public String speak() { return name + " makes a sound"; }
}

public class Dog extends Animal {
    public Dog(String name) { super(name); }

    @Override
    public String speak() { return name + " barks"; }
}

public interface Shape {
    double area();
    default String describe() { return "Area: " + area(); }
}

public record Point(int x, int y) {}   // immutable data carrier

public enum Direction { NORTH, SOUTH, EAST, WEST }

abstract class Vehicle {
    abstract void move();
}
Collections

List, Set, Map essentials

Java
List<String> list = new ArrayList<>();
list.add("a"); list.get(0); list.remove("a"); list.size(); list.contains("a");

Set<String> set = new HashSet<>(List.of("a", "b", "c"));

Map<String, Integer> map = new HashMap<>();
map.put("a", 1);
map.get("a");
map.getOrDefault("z", 0);
map.containsKey("a");
for (Map.Entry<String, Integer> e : map.entrySet()) { /* ... */ }

Deque<Integer> stack = new ArrayDeque<>();
stack.push(1); stack.pop(); stack.peek();

Queue<Integer> queue = new LinkedList<>();
queue.offer(1); queue.poll(); queue.peek();
Streams

Stream pipeline essentials

Java
List<Integer> nums = List.of(1, 2, 3, 4, 5, 6);

List<Integer> evensSquared = nums.stream()
        .filter(n -> n % 2 == 0)
        .map(n -> n * n)
        .collect(Collectors.toList());

int sum = nums.stream().mapToInt(Integer::intValue).sum();
Optional<Integer> max = nums.stream().max(Integer::compareTo);
boolean anyMatch = nums.stream().anyMatch(n -> n > 5);
long count = nums.stream().filter(n -> n > 2).count();

Map<Boolean, List<Integer>> grouped = nums.stream()
        .collect(Collectors.partitioningBy(n -> n % 2 == 0));

String csv = nums.stream().map(String::valueOf).collect(Collectors.joining(","));
Exception Handling

try/catch/finally, try-with-resources, custom exceptions

Java
try {
    riskyOperation();
} catch (IOException e) {
    log(e);
} catch (RuntimeException e) {
    handle(e);
} finally {
    cleanup();
}

try (BufferedReader reader = new BufferedReader(new FileReader("data.txt"))) {
    String line = reader.readLine();
} catch (IOException e) {
    e.printStackTrace();
}

class InsufficientFundsException extends Exception {
    public InsufficientFundsException(String message) { super(message); }
}

void withdraw(double amount) throws InsufficientFundsException {
    if (amount > balance) {
        throw new InsufficientFundsException("Not enough funds");
    }
}