Java Cheat Sheet
Last updated
Hello World & program structure
Every Java program runs from a main method inside a class.
| Element | Code |
|---|---|
| Class declaration | public class Main { ... } |
| Entry point | public static void main(String[] args) { ... } |
| Print a line | System.out.println("Hello, World!"); |
| Print without newline | System.out.print("text"); |
| Read input | Scanner sc = new Scanner(System.in); |
| Import a class | import java.util.ArrayList; |
| Comments | // line and /* block */ |
Data types
Primitives are lowercase; their wrapper classes are capitalized.
| Type | Description |
|---|---|
int | 32-bit signed integer |
long | 64-bit signed integer |
double / float | Floating point numbers |
boolean | true or false |
char | Single 16-bit Unicode character |
byte / short | 8-bit / 16-bit integers |
String | Immutable text (a class, not a primitive) |
Integer, Double, Boolean | Wrapper classes for primitives |
var | Inferred local type (Java 10+) |
Variables
| Operation | Syntax |
|---|---|
| Declare & initialize | int x = 5; |
| Type inference (local) | var name = "Ada"; |
| Constant | final double PI = 3.14159; |
| String concatenation | String s = "Hi " + name; |
| Convert string to int | int n = Integer.parseInt("42"); |
| Convert int to string | String s = String.valueOf(42); |
| Formatted string | String.format("%d items", n) |
Control flow
| Statement | Syntax |
|---|---|
| If / else | if (x > 0) { ... } else { ... } |
| Switch statement | switch (n) { case 1: ...; break; default: ...; } |
| Switch expression | var s = switch (n) { case 1 -> "one"; default -> "other"; }; |
| While loop | while (i < n) { ... } |
| Do-while loop | do { ... } while (i < n); |
| For loop | for (int i = 0; i < n; i++) { ... } |
| Enhanced for (for-each) | for (String item : list) { ... } |
| Break / continue | break; exits a loop, continue; skips to next iteration |
Methods
| Operation | Syntax |
|---|---|
| Define a method | int add(int a, int b) { return a + b; } |
| No return value | void greet() { ... } |
| Static method | static int square(int x) { return x * x; } |
| Public method | public String getName() { return name; } |
| Varargs | int sum(int... nums) { ... } |
| Call a method | int r = add(2, 3); |
| Call a static method | Math.max(a, b); |
| Method overloading | int max(int a, int b) and double max(double a, double b) |
Classes & OOP
| Operation | Syntax |
|---|---|
| Define a class | public class Dog { ... } |
| Field | private String name; |
| Constructor | public Dog(String name) { this.name = name; } |
| Create an object | Dog d = new Dog("Rex"); |
| Getter / setter | public String getName() { return name; } |
| Inheritance | class Puppy extends Dog { ... } |
| Interface | interface Runnable { void run(); } |
| Implement an interface | class Task implements Runnable { ... } |
| Override a method | @Override public void speak() { ... } |
Collections
Generic collections from java.util.
| Type | Use & example |
|---|---|
ArrayList<T> | Dynamic array: list.add(1); list.get(0); list.size(); |
HashMap<K, V> | Key-value: map.put("a", 1); map.get("a"); |
HashSet<T> | Unique values: set.add(5); set.contains(5); |
LinkedList<T> | Doubly linked list, good as a queue/deque |
ArrayDeque<T> | Stack/queue: dq.push(x); dq.pop(); |
| Array | int[] nums = {1, 2, 3}; |
| Iterate a list | for (T x : list) { ... } |
| Iterate a map | for (var e : map.entrySet()) { e.getKey(); e.getValue(); } |
Streams & lambdas
Functional-style pipelines over collections (Java 8+).
| Operation | Syntax |
|---|---|
| Lambda expression | x -> x * 2 |
| Create a stream | list.stream() |
| Filter | .filter(n -> n > 0) |
| Map / transform | .map(n -> n * 2) |
| Sort | .sorted() or .sorted(Comparator.reverseOrder()) |
| Reduce / sum | .reduce(0, Integer::sum) |
| Count / match | .count(), .anyMatch(n -> n > 5) |
| Collect to list | .collect(Collectors.toList()) |
| For each | .forEach(System.out::println) |
Common patterns (try/catch, generics)
| Pattern | Syntax |
|---|---|
| Try / catch | try { ... } catch (Exception e) { ... } |
| Catch specific exception | catch (IOException e) { ... } |
| Finally | finally { ... } always runs |
| Try-with-resources | try (Scanner sc = new Scanner(...)) { ... } |
| Throw an exception | throw new IllegalArgumentException("bad"); |
| Generic class | class Box<T> { T value; } |
| Generic method | <T> T first(List<T> list) { ... } |
| Bounded type | <T extends Number> |
The Java syntax, collections, and stream operations you reach for most, on one page. This Java cheat sheet is a quick reference for writing Java - the data types, control flow, classes, the ArrayList/HashMap collections, the Streams API, and the exception and generics patterns you use every day.
Everything here is standard Java (Java 8 and later) and compiles with javac. Copy what you need, or try any snippet live in the Java playground - no JDK to install.
Java cheat sheet FAQ
Is this Java cheat sheet free?
What is the difference between == and .equals() in Java?
== compares references - whether two variables point at the exact same object - while .equals() compares the contents. Two different String objects with the same text are .equals() but may not be ==. Always use .equals() to compare strings and other objects for value equality; use == only for primitives (int, boolean, etc.) or to check for null.What are streams used for in Java?
filter, map, sorted, reduce, collect - instead of manual loops. You start with list.stream(), chain intermediate operations, and finish with a terminal operation like collect(Collectors.toList()) or forEach. It keeps data-transformation code concise and expressive.