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) |
Operators
Arithmetic, comparison, logical, and assignment operators.
| Operator | Meaning |
|---|---|
+ - * / % | Add, subtract, multiply, divide, modulo |
++ -- | Increment / decrement |
== != | Equal / not equal (references for objects) |
> < >= <= | Greater / less than comparisons |
&& || ! | Logical AND, OR, NOT (short-circuit) |
& | ^ ~ | Bitwise AND, OR, XOR, NOT |
<< >> >>> | Left, signed right, unsigned right shift |
+= -= *= /= | Compound assignment |
? : | Ternary: x > 0 ? "pos" : "neg" |
instanceof | Type check: if (o instanceof String s) |
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 |
String methods
String is immutable - every method returns a new string. Use StringBuilder when you concatenate in a loop.
| Method | What it does |
|---|---|
s.length() | Number of characters |
s.charAt(i) | Character at index i |
s.substring(a, b) | Slice from a (inclusive) to b (exclusive) |
s.indexOf("x") | First index of a substring, or -1 |
s.contains("x") | true if the substring is present |
s.replace("a", "b") | Replace all occurrences |
s.split(",") | Split into a String[] |
s.trim() / s.strip() | Remove leading/trailing whitespace |
s.toUpperCase() / toLowerCase() | Change case |
s.equals(t) / equalsIgnoreCase(t) | Value comparison (not ==) |
s.startsWith("x") / endsWith("x") | Prefix / suffix test |
String.join(",", list) | Join elements with a separator |
Math & common utilities
Static helpers from java.lang.Math and number wrappers.
| Call | Result |
|---|---|
Math.max(a, b) / Math.min(a, b) | Larger / smaller of two values |
Math.abs(x) | Absolute value |
Math.pow(x, y) | x to the power of y (returns double) |
Math.sqrt(x) | Square root |
Math.round(x) / floor / ceil | Round to nearest / down / up |
Math.random() | Random double in [0.0, 1.0) |
Integer.parseInt("42") | Parse a string to int |
Integer.MAX_VALUE / MIN_VALUE | Largest / smallest int |
Arrays.sort(arr) | Sort an array in place |
Arrays.toString(arr) | Readable array contents |
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() { ... } |
Records, enums & modern Java
Concise modern syntax (Java 14+) for data carriers and fixed value sets.
| Feature | Syntax |
|---|---|
| Record (immutable data) | record Point(int x, int y) {} |
| Use a record | var p = new Point(1, 2); p.x(); |
| Enum | enum Day { MON, TUE, WED } |
| Enum with values | enum Coin { PENNY(1), DIME(10); ... } |
| Text block | String s = """\n multi\n line\n """; |
Pattern matching instanceof | if (o instanceof String s) { s.length(); } |
| Switch pattern (Java 21) | case Integer i -> ...; case String s -> ...; |
| Sealed class | sealed interface Shape permits Circle, Square {} |
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. New to the language? Coddy's free interactive Java course builds the same concepts up step by step.
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.Can I practice Java online?
Is this cheat sheet good for beginners?
How do I convert a String to an int in Java?
Integer.parseInt("42") to get a primitive int, or Integer.valueOf("42") to get an Integer object. Both throw a NumberFormatException if the string is not a valid number, so wrap them in a try / catch when the input is untrusted. To go the other way, use String.valueOf(n) or Integer.toString(n).What is the difference between an ArrayList and an array in Java?
int[] a = new int[5]) has a fixed length set at creation and can hold primitives directly. An ArrayList<T> grows and shrinks dynamically with add() and remove(), but only stores objects, so primitives are auto-boxed (ArrayList<Integer>). Use an array when the size is known and fixed; use an ArrayList when the collection changes size.