Java Cheat Sheet
Free Java cheat sheet: the most-used Java syntax and methods at a glance — searchable and beginner-friendly.
Basics
| Concept | Syntax | Example |
|---|---|---|
| Main method | public static void main(String[] args) | Entry point of every Java program |
System.out.println() | System.out.println("Hello"); | |
| Variable | type name = value; | int age = 25; |
| Array | type[] name = new type[size] | int[] nums = {1, 2, 3}; |
OOP
| Concept | Syntax | Example |
|---|---|---|
| Class | class Name { } | class Dog { String name; } |
| Constructor | ClassName(params) { } | Dog(String n) { name = n; } |
| Inheritance | class B extends A { } | class Puppy extends Dog { } |
| Interface | interface Name { method(); } | interface Runnable { void run(); } |
| Abstract class | abstract class Name { } | abstract class Shape { abstract double area(); } |
Collections
| Concept | Syntax | Example |
|---|---|---|
| ArrayList | List<T> list = new ArrayList<>() | List<String> names = new ArrayList<>(); |
| HashMap | Map<K,V> map = new HashMap<>() | Map<String,Integer> ages = new HashMap<>(); |
| HashSet | Set<T> set = new HashSet<>() | Set<String> unique = new HashSet<>(); |
| For-each | for (T item : collection) | for (String s : list) { ... } |
| Stream API | .stream().filter().map().collect() | list.stream().filter(x -> x > 5).toList(); |
Exception Handling
| Concept | Syntax | Example |
|---|---|---|
| Try-catch | try { } catch (Exception e) { } | try { int x = 1/0; } catch (ArithmeticException e) { ... } |
| Throw | throw new Exception(msg) | throw new IllegalArgumentException("Invalid"); |
| Finally | try { } finally { } | finally { connection.close(); } |
| Custom exception | class MyEx extends Exception { } | class NotFoundEx extends RuntimeException { } |
Strings
| Concept | Syntax | Example |
|---|---|---|
| Length | str.length() | "hello".length() // 5 |
| Substring | str.substring(start, end) | "hello".substring(0, 3) // "hel" |
| Split | str.split(regex) | "a,b,c".split(",") // ["a","b","c"] |
| Format | String.format("%s is %d", a, b) | String.format("Hi %s", name); |