Java Cheat Sheet

Free Java cheat sheet: the most-used Java syntax and methods at a glance — searchable and beginner-friendly.

Basics

ConceptSyntaxExample
Main methodpublic static void main(String[] args)Entry point of every Java program
PrintSystem.out.println()System.out.println("Hello");
Variabletype name = value;int age = 25;
Arraytype[] name = new type[size]int[] nums = {1, 2, 3};

Learn it in a lesson: Introduction to Java · Variables and Data Types · Arrays

OOP

ConceptSyntaxExample
Classclass Name { }class Dog { String name; }
ConstructorClassName(params) { }Dog(String n) { name = n; }
Inheritanceclass B extends A { }class Puppy extends Dog { }
Interfaceinterface Name { method(); }interface Runnable { void run(); }
Abstract classabstract class Name { }abstract class Shape { abstract double area(); }

Learn it in a lesson: Object-Oriented Programming · Inheritance · Interfaces and Abstract Classes

Collections

ConceptSyntaxExample
ListList<T> l = new ArrayList<>()List<String> names = new ArrayList<>(); names.add("Ada");
MapMap<K,V> m = new HashMap<>()Map<String,Integer> ages = new HashMap<>(); ages.put("Ada", 36);
SetSet<T> s = new HashSet<>()new HashSet<>(list) // removes duplicates
For-eachfor (T item : collection)for (String s : list) { ... }
Default on miss
get() returns null for a missing key, which is where NullPointerExceptions come from.
map.getOrDefault(k, d)counts.getOrDefault(word, 0) + 1
Count into a map
The tidiest word-count line in Java.
map.merge(k, 1, Integer::sum)counts.merge(word, 1, Integer::sum);
Immutable literal
Java 9+. Throws if you try to add to it — that is the point.
List.of / Map.ofList.of("a", "b")

Learn it in a lesson: Collections Framework · ArrayList · HashMap · Immutability

Exception Handling

ConceptSyntaxExample
Try-catchtry { } catch (Exception e) { }try { int x = 1/0; } catch (ArithmeticException e) { ... }
Throwthrow new Exception(msg)throw new IllegalArgumentException("Invalid");
Finallytry { } finally { }finally { connection.close(); }
Custom exceptionclass MyEx extends Exception { }class NotFoundEx extends RuntimeException { }

Learn it in a lesson: Exception Handling

Strings

ConceptSyntaxExample
Lengthstr.length()"hello".length() // 5
Substringstr.substring(start, end)"hello".substring(0, 3) // "hel"
Splitstr.split(regex)"a,b,c".split(",") // ["a","b","c"]
FormatString.format("%s is %d", a, b)String.format("Hi %s", name);

Learn it in a lesson: Strings

Streams

ConceptSyntaxExample
Filter and collect
toList() is Java 16+; before that, .collect(Collectors.toList()).
.stream().filter().toList()names.stream().filter(n -> n.length() > 3).toList();
Map.map(fn)names.stream().map(String::toUpperCase).toList();
Sum.mapToInt().sum()orders.stream().mapToInt(Order::getQty).sum();
Sort.sorted(Comparator.comparing(fn))people.stream().sorted(Comparator.comparing(Person::age)).toList();
GroupCollectors.groupingBypeople.stream().collect(Collectors.groupingBy(Person::city));
Join to a stringCollectors.joining(", ")names.stream().collect(Collectors.joining(", "));

Learn it in a lesson: Streams API Advanced Operations & Pipelines · Comparable & Comparator · Collectors & Grouping

Null & Optional

ConceptSyntaxExample
Optional
Says "might not be there" in the signature instead of documenting it and hoping.
Optional<T>Optional<User> findById(long id);
Unwrap safely
Never call .get() without checking — it throws the same way null did.
.orElse(x) / .orElseThrow()user.orElseThrow(() -> new NotFoundException(id));
Chain.map().filter()user.map(User::email).filter(e -> e.contains("@"));
Guard a parameter
Fails at the boundary with a useful message rather than deep inside later.
Objects.requireNonNull(x, "name")this.name = Objects.requireNonNull(name, "name");

Learn it in a lesson: Working with Optionals the Right Way