Menu

Java Cheat Sheet

Last updated

Hello World & program structure

Every Java program runs from a main method inside a class.

ElementCode
Class declarationpublic class Main { ... }
Entry pointpublic static void main(String[] args) { ... }
Print a lineSystem.out.println("Hello, World!");
Print without newlineSystem.out.print("text");
Read inputScanner sc = new Scanner(System.in);
Import a classimport java.util.ArrayList;
Comments// line and /* block */

Data types

Primitives are lowercase; their wrapper classes are capitalized.

TypeDescription
int32-bit signed integer
long64-bit signed integer
double / floatFloating point numbers
booleantrue or false
charSingle 16-bit Unicode character
byte / short8-bit / 16-bit integers
StringImmutable text (a class, not a primitive)
Integer, Double, BooleanWrapper classes for primitives
varInferred local type (Java 10+)

Variables

OperationSyntax
Declare & initializeint x = 5;
Type inference (local)var name = "Ada";
Constantfinal double PI = 3.14159;
String concatenationString s = "Hi " + name;
Convert string to intint n = Integer.parseInt("42");
Convert int to stringString s = String.valueOf(42);
Formatted stringString.format("%d items", n)

Control flow

StatementSyntax
If / elseif (x > 0) { ... } else { ... }
Switch statementswitch (n) { case 1: ...; break; default: ...; }
Switch expressionvar s = switch (n) { case 1 -> "one"; default -> "other"; };
While loopwhile (i < n) { ... }
Do-while loopdo { ... } while (i < n);
For loopfor (int i = 0; i < n; i++) { ... }
Enhanced for (for-each)for (String item : list) { ... }
Break / continuebreak; exits a loop, continue; skips to next iteration

Methods

OperationSyntax
Define a methodint add(int a, int b) { return a + b; }
No return valuevoid greet() { ... }
Static methodstatic int square(int x) { return x * x; }
Public methodpublic String getName() { return name; }
Varargsint sum(int... nums) { ... }
Call a methodint r = add(2, 3);
Call a static methodMath.max(a, b);
Method overloadingint max(int a, int b) and double max(double a, double b)

Classes & OOP

OperationSyntax
Define a classpublic class Dog { ... }
Fieldprivate String name;
Constructorpublic Dog(String name) { this.name = name; }
Create an objectDog d = new Dog("Rex");
Getter / setterpublic String getName() { return name; }
Inheritanceclass Puppy extends Dog { ... }
Interfaceinterface Runnable { void run(); }
Implement an interfaceclass Task implements Runnable { ... }
Override a method@Override public void speak() { ... }

Collections

Generic collections from java.util.

TypeUse & 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();
Arrayint[] nums = {1, 2, 3};
Iterate a listfor (T x : list) { ... }
Iterate a mapfor (var e : map.entrySet()) { e.getKey(); e.getValue(); }

Streams & lambdas

Functional-style pipelines over collections (Java 8+).

OperationSyntax
Lambda expressionx -> x * 2
Create a streamlist.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)

PatternSyntax
Try / catchtry { ... } catch (Exception e) { ... }
Catch specific exceptioncatch (IOException e) { ... }
Finallyfinally { ... } always runs
Try-with-resourcestry (Scanner sc = new Scanner(...)) { ... }
Throw an exceptionthrow new IllegalArgumentException("bad");
Generic classclass 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?
Yes. This Java cheat sheet is completely free, with no sign-up required. Bookmark it and come back whenever you need to look up syntax, a collection, or a stream operation.
What is the difference between == and .equals() in Java?
For objects, == 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?
The Streams API (Java 8+) lets you process collections with a readable pipeline of operations - 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?
Yes. Open the Java playground to compile and run any snippet from this cheat sheet in your browser - no JDK to install. When you want structure, Coddy's free interactive Java course takes you from variables and loops to classes, collections, and streams step by step.
Is this cheat sheet good for beginners?
Yes. It is organized from the most common building blocks (types, control flow, methods) down to advanced ones (streams, generics, exceptions), so you can use the top sections on day one and grow into the rest.
Coddy programming languages illustration

Learn Java with Coddy

GET STARTED