Menu
Coddy logo textTech

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)

Operators

Arithmetic, comparison, logical, and assignment operators.

OperatorMeaning
+ - * / %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"
instanceofType check: if (o instanceof String s)

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

String methods

String is immutable - every method returns a new string. Use StringBuilder when you concatenate in a loop.

MethodWhat 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.

CallResult
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 / ceilRound 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_VALUELargest / smallest int
Arrays.sort(arr)Sort an array in place
Arrays.toString(arr)Readable array contents

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() { ... }

Records, enums & modern Java

Concise modern syntax (Java 14+) for data carriers and fixed value sets.

FeatureSyntax
Record (immutable data)record Point(int x, int y) {}
Use a recordvar p = new Point(1, 2); p.x();
Enumenum Day { MON, TUE, WED }
Enum with valuesenum Coin { PENNY(1), DIME(10); ... }
Text blockString s = """\n multi\n line\n """;
Pattern matching instanceofif (o instanceof String s) { s.length(); }
Switch pattern (Java 21)case Integer i -> ...; case String s -> ...;
Sealed classsealed interface Shape permits Circle, Square {}

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. 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?
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.
How do I convert a String to an int in Java?
Use 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?
An array (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.
Coddy programming languages illustration

Learn Java with Coddy

GET STARTED