Skip to content
AgileLogics

Java Cheat Sheet

Learn Java from the basics →

Variables & Types

int x = 5; double d = 3.14; boolean b = true; char c = 'A';
Primitive types
String name = "Ada";
String (an object, not a primitive)
final int MAX = 100;
Constant (cannot be reassigned)
var count = 10;
Local type inference (type still fixed at compile time)

Control Flow

if (x > 0) { } else if (x == 0) { } else { }
Conditional
for (int i = 0; i < 10; i++) { }
Counting loop
for (String s : list) { }
Enhanced for (for-each) loop
while (condition) { }
While loop
switch (day) { case 1 -> "Mon"; default -> "?"; }
Switch expression (Java 14+)

Arrays & Collections

int[] nums = {1, 2, 3};
Array literal
List<String> list = new ArrayList<>();
Resizable list
Map<String, Integer> map = new HashMap<>();
Key/value map
Set<String> set = new HashSet<>();
Unique-elements collection

OOP

public class Dog extends Animal implements Pet { }
Inheritance + interface implementation
private int age; public int getAge() { return age; }
Encapsulation with a getter
@Override public String toString() { return "..."; }
Overriding a parent method
public record Point(int x, int y) { }
Record — immutable data carrier (Java 16+)

Exceptions

try { risky(); } catch (IOException e) { } finally { }
Handle a checked exception
throw new IllegalArgumentException("bad input");
Throw an unchecked exception
try (var r = new FileReader(f)) { }
Try-with-resources — auto-closes r

Streams & Lambdas

list.stream().filter(x -> x > 0).map(x -> x * 2).toList();
Filter, transform, collect
list.forEach(System.out::println);
Method reference
Comparator.comparing(Person::getAge)
Comparator via method reference