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};

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(); }

Collections

ConceptSyntaxExample
ArrayListList<T> list = new ArrayList<>()List<String> names = new ArrayList<>();
HashMapMap<K,V> map = new HashMap<>()Map<String,Integer> ages = new HashMap<>();
HashSetSet<T> set = new HashSet<>()Set<String> unique = new HashSet<>();
For-eachfor (T item : collection)for (String s : list) { ... }
Stream API.stream().filter().map().collect()list.stream().filter(x -> x > 5).toList();

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 { }

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);