Java Cheat Sheet
Program structure, operators, input, strings, formatting, switch, loops, collections, classes, enums, records, generics, exceptions, files, dates, streams and JUnit on one printable page.
Program structure
| Syntax | What it does | Lesson |
|---|---|---|
public class Main { } | A class; file must be Main.java | Introduction |
public static void main(String[] args) | Where the program starts | Introduction |
System.out.println(x); | Print and new line | Introduction |
javac Main.java then java Main | Compile and run | Introduction |
Variables & input
| Syntax | What it does | Lesson |
|---|---|---|
int double boolean char String | Common types | Variables |
final int MAX = 10; | Constant | Variables |
(int) 3.9 Integer.parseInt("7") | Cast / parse | Variables |
Scanner in = new Scanner(System.in); | Keyboard input | User input |
in.nextLine() in.nextInt() | Read a line / an int | User input |
System.out.printf("%s %.2f%n", s, d); | Formatted output | User input |
Strings
| Syntax | What it does | Lesson |
|---|---|---|
s.length() s.charAt(i) | Length, one character | Strings |
s.substring(a, b) s.indexOf("x") | Part of text, find text | Strings |
s.trim() s.toUpperCase() s.replace(a, b) | Transform (returns new String) | Strings |
s.split(",") String.join("-", arr) | Split / join | Strings |
a.equals(b) a.equalsIgnoreCase(b) | Compare text | Strings |
new StringBuilder().append(x) | Build text efficiently | Strings |
Conditions & loops
Arrays & methods
Classes & collections
| Syntax | What it does | Lesson |
|---|---|---|
class Dog { String name; Dog(String n) { name = n; } } | Class and constructor | Classes |
List<String> l = new ArrayList<>(); | Resizable list | ArrayList |
l.add(x) l.get(i) l.remove(i) l.size() | List methods | ArrayList |
Map<String, Integer> m = new HashMap<>(); | Key-value map | HashMap |
m.put(k, v) m.getOrDefault(k, 0) | Write / read safely | HashMap |
Set<String> s = new HashSet<>(); | Unique values | HashMap |
Inheritance & interfaces
| Syntax | What it does | Lesson |
|---|---|---|
class Car extends Vehicle | Inherit from a class | Inheritance |
super(args); super.method() | Call the parent | Inheritance |
@Override | Check an override | Inheritance |
interface Payable { void pay(); } | Define a contract | Interfaces |
class Card implements Payable | Keep the contract | Interfaces |
abstract class Shape { abstract double area(); } | Partial blueprint | Interfaces |
Exceptions & streams
| Syntax | What it does | Lesson |
|---|---|---|
try { } catch (Exception e) { } finally { } | Handle errors | Exceptions |
throw new IllegalArgumentException("msg"); | Report a problem | Exceptions |
void load() throws IOException | Declare a checked exception | Exceptions |
x -> x * 2 String::length | Lambda / method reference | Streams |
list.stream().filter(...).map(...).toList() | Stream pipeline | Streams |
Collectors.groupingBy(f, Collectors.counting()) | Group and count | Streams |
Operators, formatting & switch
| Syntax | What it does | Lesson |
|---|---|---|
7 / 2 7 % 2 (double) a / b | Integer division, remainder, decimal division | Operators & Math |
x++ x += 5 | Update a variable | Operators & Math |
Math.round(x) Math.max(a, b) Math.pow(a, b) | Common maths | Operators & Math |
System.out.printf("%-10s%6.2f%n", s, d) | Aligned, formatted output | Formatting & StringBuilder |
new StringBuilder().append(x).toString() | Build strings efficiently | Formatting & StringBuilder |
""" text block """ | Multi-line text | Formatting & StringBuilder |
case "A", "B" -> ... | Arrow case, no fall-through | switch |
int d = switch (m) { case 2 -> 28; default -> 31; }; | Switch expression | switch |
Collections, enums & records
| Syntax | What it does | Lesson |
|---|---|---|
new TreeSet<>() new LinkedHashSet<>() | Sorted / insertion-ordered set | Collections |
Deque<T> s = new ArrayDeque<>(); s.push(x); s.pop(); | Stack | Collections |
new PriorityQueue<>() | Smallest item first | Collections |
list.sort(Comparator.comparing(P::age).reversed()) | Sort objects | Collections |
enum Size { SMALL, LARGE } | Fixed set of constants | Enums |
Size.values() Size.valueOf("LARGE") | All constants / from text | Enums |
record Point(int x, int y) {} | Immutable data class | Records |
class Box<T> { } static <T> T f(T x) | Generic class and method | Generics |
List<? extends Number> | Read-only wildcard | Generics |
Files, dates & testing
| Syntax | What it does | Lesson |
|---|---|---|
Files.readAllLines(Path.of("f.txt")) | Read lines | Files & I/O |
Files.writeString(p, s, CREATE, APPEND) | Append to a file | Files & I/O |
try (Stream<String> l = Files.lines(p)) { } | Read a big file lazily | Files & I/O |
LocalDate.of(2024, 7, 5).plusDays(3) | Create and move a date | Dates & Times |
DateTimeFormatter.ofPattern("dd/MM/yyyy") | Format and parse dates | Dates & Times |
ChronoUnit.DAYS.between(a, b) | Days between dates | Dates & Times |
@Test void name() { assertEquals(exp, act); } | A JUnit test | Unit Testing (JUnit) |
assertThrows(X.class, () -> code()) | Expect an exception | Unit Testing (JUnit) |
@ParameterizedTest @CsvSource({...}) | One test, many inputs | Unit Testing (JUnit) |
Beginner companion reference
| Topic | Rule to remember | Lesson |
|---|---|---|
| Syntax and Statements | Expressions produce values; statements instruct the program | Open lesson |
| Output: print() vs. println() | println adds a line terminator | Open lesson |
| Comments and Code Structure | Comments explain intent without executing | Open lesson |
| Variables, Identifiers and Constants | final prevents reassignment of the variable | Open lesson |
| Primitive Data Types | Java has eight primitive types | Open lesson |
| Type Casting and var | var infers a fixed local type | Open lesson |
| Operators and Precedence | Multiplication binds before addition | Open lesson |
| Strings, Concatenation and Escapes | String objects are immutable | Open lesson |
| Boolean Expressions | && requires both operands to be true | Open lesson |
| switch Expressions and Statements | A switch expression produces a value | Open lesson |
| if, else if and Nested Conditions | An else-if chain takes the first matching branch | Open lesson |
| for, while and do-while Loops | do-while executes its body at least once | Open lesson |
| Nested and Enhanced for Loops | Enhanced for visits elements rather than indices | Open lesson |
| break and continue | break exits while continue skips one iteration | Open lesson |
| Methods and Parameters | Java passes arguments by value | Open lesson |
| Return Values and Method Overloading | Overloading requires different parameter lists | Open lesson |
| Variable Scope | A local variable belongs to its enclosing block | Open lesson |
| Recursion: Base Cases and Calls | Recursion needs a reachable base case | Open lesson |
| User Input with Scanner | nextLine reads the remainder of a line | Open lesson |
| Command-Line Arguments | Arguments arrive as strings in args | Open lesson |
Intermediate companion reference
| Topic | Rule to remember | Lesson |
|---|---|---|
| Classes and Objects Explained | An object is an instance of a class | Open lesson |
| Fields, Attributes and Methods | Instance fields hold each object state | Open lesson |
| Constructors and Constructor Overloading | Constructors initialize newly created objects | Open lesson |
| this Keyword | this refers to the current object | Open lesson |
| Access and Non-Access Modifiers | private restricts access to implementation details | Open lesson |
| Encapsulation and Validation | Encapsulation protects object invariants | Open lesson |
| Inheritance and the super Keyword | super can invoke a superclass constructor or method | Open lesson |
| Polymorphism and Method Overriding | Overridden instance methods dispatch using the actual object | Open lesson |
| Abstraction and Interfaces | Interfaces define a shared contract | Open lesson |
| Inner and Anonymous Classes | A non-static inner class has an enclosing instance | Open lesson |
| Enums and Enum Constructors | Enum constants are fixed named instances | Open lesson |
| Packages and Imports | An import allows a shorter type name | Open lesson |
| Single and Multidimensional Arrays | Java multidimensional arrays are arrays of arrays | Open lesson |
| Array Operations and Sorting | Binary search requires matching sorted order | Open lesson |
| String Methods Reference | String methods return new text when transforming | Open lesson |
| StringBuilder and StringBuffer | StringBuilder is a mutable character sequence | Open lesson |
| Wrapper Classes and Autoboxing | Autoboxing converts primitives to wrapper objects | Open lesson |
| Collections Framework Explained | List keeps positions while Set models uniqueness | Open lesson |
| List, ArrayList and LinkedList | ArrayList offers constant-time indexed access | Open lesson |
| HashSet, TreeSet and LinkedHashSet | LinkedHashSet preserves insertion order | Open lesson |
| HashMap, TreeMap and LinkedHashMap | A Map associates unique keys with values | Open lesson |
| Iterators and the Iterable Interface | Iterable provides an Iterator | Open lesson |
| Collections Sorting and Comparators | Comparator defines an external ordering | Open lesson |
| Generics and Generic Classes | Generics provide compile-time type checking | Open lesson |
Files and I/O companion reference
| Topic | Rule to remember | Lesson |
|---|---|---|
| Exception Types and Hierarchy | RuntimeException subclasses are unchecked | Open lesson |
| try, catch, finally, throw and throws | throw raises an exception while throws declares it | Open lesson |
| Custom Exceptions and Multi-Catch | Custom exceptions express domain-specific failures | Open lesson |
| Try-with-Resources | Try-with-resources closes AutoCloseable resources | Open lesson |
| File Handling: Create, Read, Write, Delete | File open options determine overwrite or append behavior | Open lesson |
| Path and Files APIs | Path models a path while Files performs operations | Open lesson |
| Byte Streams and Character Streams | Character streams decode or encode text | Open lesson |
| FileInputStream and FileOutputStream | InputStream.read returns minus one at end of stream | Open lesson |
| BufferedReader and BufferedWriter | readLine returns null at end of input | Open lesson |
| Serialization and Deserialization | Serializable marks types for native object serialization | Open lesson |
| JSON Processing with Jackson | A JSON library parses structured data rather than string splitting | Open lesson |
Advanced companion reference
| Topic | Rule to remember | Lesson |
|---|---|---|
| Lambda Expressions | A lambda implements a functional interface | Open lesson |
| Functional Interfaces | Function transforms while Predicate tests a value | Open lesson |
| Method References | A method reference adapts an existing method | Open lesson |
| Stream API: map, filter and reduce | Stream intermediate operations are lazy | Open lesson |
| Optional: Handling Missing Values | Optional models a present value or absence | Open lesson |
| Regular Expressions | matches validates the whole input | Open lesson |
| Date and Time API: java.time | LocalDate is a date without a time zone | Open lesson |
| Annotations Explained | Annotations provide metadata for tools or frameworks | Open lesson |
| Reflection API | Reflection inspects runtime type information | Open lesson |
| Multithreading and Thread Lifecycle | start begins execution on a new thread | Open lesson |
| Synchronization and Race Conditions | Synchronization coordinates access using a shared lock | Open lesson |
| ExecutorService and Thread Pools | ExecutorService manages submitted tasks | Open lesson |
| Concurrency Utilities | AtomicInteger provides atomic single-variable updates | Open lesson |
| Debugging and Logging Basics | A debugger pauses execution while logging records events | Open lesson |
Developer Tools companion reference
| Topic | Rule to remember | Lesson |
|---|---|---|
| JDK, JRE and JVM Explained | The JDK includes development tools and runtime capabilities | Open lesson |
| Installing Java and Setting Up the JDK | JAVA_HOME conventionally points to the JDK root | Open lesson |
| Compiling and Running Java Programs | javac compiles source and java launches bytecode | Open lesson |
| Classpath and Package Layout | Classpath entries are roots for locating classes | Open lesson |
| Maven and Gradle Basics | Build files declare dependencies and repeatable tasks | Open lesson |
| Unit Testing with JUnit | Unit tests compare observed behavior with explicit expectations | Open lesson |
| Debugging Java Applications Step by Step | Debugging tests a hypothesis with a reproducible case | Open lesson |
| Git Basics for Java Projects | A commit records a reviewed change in repository history | Open lesson |
| Modern Java: Records, Sealed Classes and Patterns | Records are data carriers with generated component accessors | Open lesson |
| Modules and module-info.java | exports exposes a package from a named module | Open lesson |
Java DSA companion reference
| Topic | Rule to remember | Lesson |
|---|---|---|
| Time and Space Complexity | Big O describes growth with input size | Open lesson |
| Linear Search and Binary Search | Binary search requires sorted input | Open lesson |
| Sorting Algorithms Explained | Insertion sort maintains a sorted prefix | Open lesson |
| Stacks and Queues with ArrayDeque | Stacks use LIFO and ordinary queues use FIFO | Open lesson |
| Linked Lists: Nodes and Links | A linked list connects nodes through references | Open lesson |
| Hashing and Hash Tables | Hash collisions still require equality checks | Open lesson |
| Trees and Binary Search Trees | In-order traversal sorts keys of a valid BST | Open lesson |
| Heaps and Priority Queues | PriorityQueue exposes the next item by priority | Open lesson |
| Graphs, BFS and DFS | BFS explores an unweighted graph by edge distance | Open lesson |
| Recursion and Backtracking | Backtracking explores and then undoes choices | Open lesson |
| Dynamic Programming Basics | Dynamic programming reuses overlapping subproblem results | Open lesson |
Practice and Projects companion reference
| Topic | Rule to remember | Lesson |
|---|---|---|
| Examples Library for Beginners | An example should expose one behavior and its result | Open lesson |
| Exercises by Topic | Exercises should state inputs and expected behavior | Open lesson |
| Quizzes by Chapter | Quizzes diagnose understanding rather than replace coding practice | Open lesson |
| Coding Challenges with Test Cases | Challenge constraints guide the algorithm choice | Open lesson |
| Keywords Reference and Glossary | Keywords have reserved language-defined roles | Open lesson |
| String, Math and Collections Methods | API references should include behavior and edge cases | Open lesson |
| Common Java Errors and Solutions | Compile errors, runtime failures and logic errors are different | Open lesson |
| Interview Questions and Answers | equals checks the equality contract while == checks reference identity | Open lesson |
| Beginner Java Projects with Practice Steps | A small project needs clear acceptance criteria | Open lesson |
| Intermediate Java Projects: Collections and Files | Domain operations should preserve state invariants | Open lesson |
| Advanced Java Projects: Testing and Concurrency | Advanced projects need explicit failure and shutdown policies | Open lesson |
| Learning Roadmap and Study Plan | A roadmap orders skills by prerequisites and practice | Open lesson |
How to use this Java cheat sheet
This Java cheat sheet collects the syntax beginners and intermediate programmers look up most often, in the same order as the course: program structure, variables and types, input and output, strings, conditions, loops and arrays, methods, classes, collections, inheritance and interfaces, enums, records, generics, exceptions, files, dates, streams and testing. Each row links to the lesson that explains it with examples and common mistakes.
Keep it beside you while you write programs in IntelliJ IDEA, VS Code or Eclipse. When you can't remember whether arrays use length or length(), how to read a whole line with Scanner, or the shape of a try-with-resources block, a quick glance answers it. Type a keyword into the filter box to jump straight to the right row, or print the page as a one-sheet reference.
Java gotchas worth remembering
- Compare strings with equals.
==checks whether two references point at the same object.name.equals("Ana")compares the text. - Integer division truncates.
7 / 2is3. Use adoubleon one side for3.5. - Arrays have length, strings have length(), lists have size(). Mixing them up is the most common compile error for beginners.
- Scanner leaves a newline behind. After
nextInt(), a followingnextLine()returns an empty string. CallnextLine()once to clear it, or read every line and parse it. - Don't remove items while looping with for-each. It throws ConcurrentModificationException. Use
removeIfor an Iterator instead. - Override equals and hashCode together. Otherwise your objects behave oddly as HashMap keys or in a HashSet. Records do both for you.
When a snippet surprises you, open the linked lesson for the full explanation, then test yourself with the Java quiz.
The Java lessons behind this cheat sheet
Beginner
- 1Java Introduction
- 2Java Syntax and Statements Explained
- 3Java Output with print, println and printf
- 4Java Comments and Code Structure
- 5Java Variables and Data Types
- 6Java Variables, Identifiers and Constants
- 7Java Primitive Data Types Explained
- 8Java Type Casting and the var Keyword
- 9Java Boolean Values and Expressions
- 10Java Operators and Math
- 11Java Operators and Operator Precedence
- 12Java User Input
- 13Java User Input with Scanner
- 14Java Command-Line Arguments Explained
- 15Java Strings
- 16Java Strings, Concatenation and Special Characters
- 17Java String Formatting and StringBuilder
- 18Java if, else if and else
- 19Java if, else if and Nested Conditions
- 20Java switch
- 21Java switch Statements and switch Expressions
- 22Java Loops
- 23Java for, while and do-while Loops
- 24Java Nested Loops and Enhanced for Loops
- 25Java break and continue Explained
- 26Java Methods
- 27Java Methods and Parameters Explained
- 28Java Return Values and Method Overloading
- 29Java Variable Scope Explained with Examples
- 30Java Recursion Explained for Beginners
Intermediate
- 31Java Arrays
- 32Java Single and Multidimensional Arrays
- 33Java Array Operations and Sorting
- 34Java Classes and Objects
- 35Java Classes and Objects Explained
- 36Java Fields, Attributes and Methods
- 37Java Constructors and Constructor Overloading
- 38Java this Keyword Explained with Examples
- 39Java Access and Non-Access Modifiers
- 40Java Encapsulation and Validation
- 41Java Inner and Anonymous Classes
- 42Java Packages and Imports
- 43Java String Methods Reference
- 44Java StringBuilder and StringBuffer
- 45Java Wrapper Classes and Autoboxing
- 46Java ArrayList
- 47Java List, ArrayList and LinkedList
- 48Java HashMap
- 49Java HashMap, TreeMap and LinkedHashMap
- 50Java Collections
- 51Java Collections Framework Explained
- 52Java HashSet, TreeSet and LinkedHashSet
- 53Java Iterators and the Iterable Interface
- 54Java Collections Sorting and Comparators
- 55Java Inheritance
- 56Java Inheritance and the super Keyword
- 57Java Polymorphism and Method Overriding
- 58Java Interfaces and Abstract Classes
- 59Java Abstraction and Interfaces
- 60Java Enums
- 61Java Enums and Enum Constructors
- 62Java Generics
- 63Java Generics and Generic Classes
Files and I/O
- 64Java Exceptions
- 65Java Exception Types and Hierarchy Explained with Examples
- 66Java try, catch, finally and throw Explained with Examples
- 67Java Custom and Multiple Exceptions Explained with Examples
- 68Java Try-with-Resources Explained with Examples
- 69Java File Handling Explained with Examples
- 70Java Path and Files APIs Explained with Examples
- 71Java Byte Streams and Character Streams Explained
- 72Java FileInputStream and FileOutputStream Examples
- 73Java BufferedReader and BufferedWriter with Examples
- 74Java Serialization and Deserialization Explained
- 75Java JSON Processing with Jackson Examples
- 76Java File Handling
Advanced
- 77Java Dates and Times
- 78Java Date and Time API Explained with Examples
- 79Java Lambdas and Streams
- 80Java Lambda Expressions Explained with Examples
- 81Java Functional Interfaces Explained with Examples
- 82Java Method References Explained with Examples
- 83Java Stream API and Collectors Explained with Examples
- 84Java Optional Explained with Examples
- 85Java Regular Expressions Explained with Examples
- 86Java Annotations Explained with Examples
- 87Java Reflection API Explained with Examples
- 88Java Threads and Lifecycle Explained with Examples
- 89Java Synchronization and Race Conditions Explained with Examples
- 90Java ExecutorService and Thread Pools Explained with Examples
- 91Java Concurrency Utilities Explained with Examples
- 92Java Debugging and Logging Explained with Examples
Developer Tools
- 93Java Records
- 94Unit Testing with JUnit
- 95Java JDK, JRE and JVM Explained with Examples
- 96Installing Java and the JDK Explained with Examples
- 97Compiling and Running Java Programs Explained with Examples
- 98Java Classpath and Packages Explained with Examples
- 99Java Maven and Gradle Basics Explained with Examples
- 100Java Unit Testing with JUnit Explained with Examples
- 101Debugging Java Applications Explained with Examples
- 102Git for Java Projects Explained with Examples
- 103Modern Java Features Explained with Examples
- 104Java Modules Explained with Examples
Java DSA
- 105Java Time and Space Complexity Explained with Examples
- 106Java Linear and Binary Search Explained with Examples
- 107Java Sorting Algorithms Explained with Examples
- 108Java Stacks and Queues Explained with Examples
- 109Java Linked List Data Structures Explained with Examples
- 110Java Hash Tables and Hashing Explained with Examples
- 111Java Trees and Binary Search Trees with Examples
- 112Java Heaps and Priority Queues with Examples
- 113Java Graphs, Breadth-First Search and Depth-First Search
- 114Java Recursion and Backtracking with Worked Examples
- 115Java Dynamic Programming Basics with Worked Examples
Practice and Projects
- 116Java Examples Library with Explained Programs
- 117Java Exercises by Topic with Solutions
- 118Java Quizzes by Chapter with Answers
- 119Java Coding Challenges with Explained Solutions
- 120Java Keywords Reference for Java 17
- 121Java String, Math and Collection Methods Reference
- 122Common Java Errors and How to Fix Them
- 123Java Interview Questions with Explained Answers
- 124Beginner Java Projects Explained with Examples
- 125Intermediate Java Projects Explained with Examples
- 126Advanced Java Projects Explained with Examples
- 127Java Learning Roadmap and Study Plan Explained with Examples