Skip to content

Java Cheat Sheet

Java is a class-based, object-oriented programming language designed for portability and robustness. This Java cheatsheet is a structured, example-driven reference for core Java syntax, object-oriented features, collections, streams, exceptions, and commonly used APIs.


Minimal Program

public class Main {
    public static void main(String[] args) {
        System.out.println("Hello, Java");
    }
}

Compilation & Execution

javac Main.java
java Main

Primitive Types

byte    b = 1;
short   s = 2;
int     i = 3;
long    l = 4L;
float   f = 1.5f;
double  d = 3.14;
char    c = 'A';
boolean ok = true;
Integer.BYTES;
Double.BYTES;

Variables & Type Inference

int x = 10;
var y = 20;      // Java 10+

Operators

a + b;
a - b;
a * b;
a / b;
a % b;
a == b;
a != b;
a > b;
a < b;
a && b;
a || b;
!a;

Control Flow

if / else

if (x > 10) {
    result = 1;
} else {
    result = 0;
}

switch

switch (x) {
    case 1:
        break;
    case 2:
        break;
    default:
        break;
}
int r = switch (x) {
    case 1 -> 10;
    case 2 -> 20;
    default -> 0;
};

Loops

for (int n = 0; n < 5; n++) {
    System.out.println(n);
}
while (x > 0) {
    x--;
}
for (var item : list) {
    System.out.println(item);
}

Methods

static int add(int a, int b) {
    return a + b;
}
int r = add(2, 3);

Method Overloading

static int add(int a, int b);
static double add(double a, double b);

Classes

class Counter {
    private int value = 0;

    public void increment() {
        value++;
    }

    public int get() {
        return value;
    }
}

Constructors

class Point {
    int x;
    int y;

    Point(int x, int y) {
        this.x = x;
        this.y = y;
    }
}

Inheritance

class Animal {
    void speak() {}
}

class Dog extends Animal {
}

Polymorphism

Animal a = new Dog();
a.speak();

Abstract Classes

abstract class Shape {
    abstract double area();
}
class Square extends Shape {
    double size;
    Square(double s) { size = s; }
    double area() { return size * size; }
}

Interfaces

interface Logger {
    void log(String msg);
}
class ConsoleLogger implements Logger {
    public void log(String msg) {
        System.out.println(msg);
    }
}

Enums

enum Status {
    OK, ERROR, PENDING
}

Records (Java 16+)

record User(String name, int age) {}

Arrays

int[] arr = {1, 2, 3};
arr[0] = 10;

Collections

List

import java.util.List;
import java.util.ArrayList;

List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);

Map

import java.util.Map;
import java.util.HashMap;

Map<String, Integer> map = new HashMap<>();
map.put("a", 1);

Set

import java.util.Set;
import java.util.HashSet;

Set<Integer> set = new HashSet<>();

Iteration

for (var e : list) {
    System.out.println(e);
}
map.forEach((k, v) -> System.out.println(k + ":" + v));

Streams

import java.util.stream.Collectors;

var evens = list.stream()
    .filter(n -> n % 2 == 0)
    .collect(Collectors.toList());
int sum = list.stream().mapToInt(Integer::intValue).sum();

Optional

import java.util.Optional;

Optional<String> name = Optional.of("value");
name.ifPresent(System.out::println);
String v = name.orElse("default");

Exceptions

try {
    int v = Integer.parseInt("10");
} catch (NumberFormatException e) {
} finally {
}

Checked Exceptions

void read() throws IOException {
}

Try-with-Resources

try (var in = new FileInputStream("file.txt")) {
}

Generics

class Box<T> {
    T value;
    Box(T v) { value = v; }
}
Box<Integer> box = new Box<>(10);

Lambda Expressions

list.forEach(n -> System.out.println(n));

Functional Interfaces

import java.util.function.Function;

Function<Integer, Integer> square = x -> x * x;

Threads

new Thread(() -> {
    System.out.println("running");
}).start();

Executors

import java.util.concurrent.Executors;

var pool = Executors.newFixedThreadPool(2);
pool.submit(() -> System.out.println("task"));
pool.shutdown();

Synchronization

synchronized (this) {
}

File I/O

import java.nio.file.Files;
import java.nio.file.Path;

Files.writeString(Path.of("file.txt"), "text");
String text = Files.readString(Path.of("file.txt"));

Date & Time (java.time)

import java.time.LocalDate;
import java.time.LocalDateTime;

LocalDate today = LocalDate.now();
LocalDateTime now = LocalDateTime.now();