Skip to content
Codewilds

Java cheat sheet

The essential Java syntax on one page. Every snippet comes from a lesson of our interactive Learn Java course — click "Practise" to write it yourself and get instant feedback.

Last updated on .

Fundamentals

Java Hello World: Your First Program

Write your first Java program: the Main class, the main method and System.out.println. Compile and run real Java in your browser — no JDK install.

public class Main {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}
Practise: Java Hello World: Your First Program

Java Variables and Primitive Data Types

Learn how to declare Java variables, the 8 primitive types (int, double, boolean, char…), String, var and final constants — then practise in your browser.

int level = 7;          // a whole number
String heroName = "Aria";
level = level + 1;      // assign a new value: level is now 8
Practise: Java Variables and Primitive Data Types

Java Operators: Integer vs Double Math

Master Java arithmetic: + - * / %, integer division, casting, compound assignment and the Math class. Practise with interactive exercises in your browser.

int a = 17;
int b = 5;
System.out.println(a + b);  // 22
System.out.println(a - b);  // 12
System.out.println(a * b);  // 85
System.out.println(a / b);  // 3   ← not 3.4!
System.out.println(a % b);  // 2   ← the remainder
Practise: Java Operators: Integer vs Double Math

Java Strings and String Methods

Learn Java Strings: concatenation, length, charAt, substring, indexOf, toUpperCase, trim and why you compare Strings with equals(), not ==.

String first = "Ada";
String last = "Lovelace";
String full = first + " " + last;       // "Ada Lovelace"
String label = "Level " + 3;            // "Level 3"
Practise: Java Strings and String Methods

Java if/else and switch Statements

Make decisions in Java with if, else if and else, logical operators, the ternary operator and modern switch expressions. Interactive exercises included.

int level = 12;
level == 12   // true  (equal — two equals signs!)
level != 12   // false (not equal)
level > 10    // true
level <= 9    // false
Practise: Java if/else and switch Statements

Java Loops: for, while and do-while

Repeat code with Java for, while and do-while loops, use break and continue, loop over the characters of a String and avoid off-by-one errors.

int stamina = 3;
while (stamina > 0) {
    System.out.println("Climbing... stamina " + stamina);
    stamina--;
}
System.out.println("Resting.");
Practise: Java Loops: for, while and do-while

Methods

Java Methods: Parameters and Return Values

Learn to write Java methods: static methods, parameters, return values, void, variable scope and pass-by-value. Practise with interactive exercises.

static int add(int a, int b) {
    return a + b;
}
Practise: Java Methods: Parameters and Return Values

Java Method Overloading and Varargs

Learn Java method overloading: one name, different parameter lists. See how the compiler picks an overload and write varargs methods in your browser.

static int max(int a, int b) {
    return a > b ? a : b;
}

static int max(int a, int b, int c) {
    return max(max(a, b), c);   // reuse the two-argument version
}

static double max(double a, double b) {
    return a > b ? a : b;
}
Practise: Java Method Overloading and Varargs

Java Recursion: Methods That Call Themselves

Learn recursion in Java: base cases, recursive cases and the call stack. Write recursive factorial, power, digit-sum and palindrome methods in your browser.

static int factorial(int n) {
    if (n <= 1) {
        return 1;                     // base case: answer known directly
    }
    return n * factorial(n - 1);      // recursive case: a smaller problem
}
Practise: Java Recursion: Methods That Call Themselves

Arrays & ArrayList

Java Arrays and the for-each Loop

Learn Java arrays: create them, read and write elements by index, use length, loop with for and for-each, and copy arrays safely. Practise in your browser.

int[] scores = {90, 72, 85};        // an array literal with 3 elements
double[] prices = new double[5];    // 5 elements, all 0.0
String[] names = new String[3];     // 3 elements, all null
Practise: Java Arrays and the for-each Loop

Java 2D Arrays: Grids, Nested Loops and Sorting

Learn Java 2D arrays: build grids, read rows and columns with nested loops, handle jagged arrays and sort with Arrays.sort. Practise in your browser.

int[][] grid = new int[3][4];   // 3 rows, 4 columns, all 0

int[][] board = {
    {1, 2, 3},
    {4, 5, 6}
};
System.out.println(board[1][2]);   // 6 → row 1, column 2
board[0][0] = 9;
Practise: Java 2D Arrays: Grids, Nested Loops and Sorting

Java ArrayList: Resizable Lists Explained

Learn Java ArrayList: add, get, set and remove elements, wrapper classes like Integer, List.of, sorting and the remove pitfall. Practise in your browser.

import java.util.ArrayList;

ArrayList<String> party = new ArrayList<>();
party.add("Aria");
party.add("Borin");
party.add("Cass");
System.out.println(party);          // [Aria, Borin, Cass]
System.out.println(party.size());   // 3
Practise: Java ArrayList: Resizable Lists Explained

Classes & Objects

Java Classes and Objects: Constructors and new

Learn Java classes and objects: fields, constructors, the new keyword, this and instance methods. Build a Hero class and test it in your browser.

class Hero {
    String name;
    int level;
    int hp;
}
Practise: Java Classes and Objects: Constructors and new

Java Encapsulation: private Fields, Getters and Setters

Protect your Java objects with encapsulation: private fields, getters, setters with validation and final fields. Build a safe BankAccount class.

class Thermostat {
    private double target = 20.0;
}

Thermostat t = new Thermostat();
t.target = 99;   // compile error: target has private access in Thermostat
Practise: Java Encapsulation: private Fields, Getters and Setters

Java static vs Instance Members

Understand the Java static keyword: shared static fields, static methods, static final constants and how they differ from instance fields and methods.

class Hero {
    static int created = 0;   // one counter, shared by the whole class
    String name;              // every hero has its own name

    Hero(String name) {
        this.name = name;
        created++;
    }
}

new Hero("Aria");
new Hero("Bram");
System.out.println(Hero.created);
Practise: Java static vs Instance Members

Java toString(), equals() and hashCode()

Override toString(), equals() and hashCode() in Java the right way, learn == vs equals, why HashSet needs hashCode and how records generate all three.

class Card {
    String rank;
    String suit;

    Card(String rank, String suit) {
        this.rank = rank;
        this.suit = suit;
    }

    @Override
    public String toString() {
        return rank + " of " + suit;
    }
}

System.out.println(new Card("Q", "hearts"));
Practise: Java toString(), equals() and hashCode()

Inheritance & Interfaces

Java Inheritance: extends and super

Learn Java inheritance: extends, super() constructor calls, protected fields and the Object class. Build a small class hierarchy and test it in your browser.

class Animal {
    protected String name;

    Animal(String name) {
        this.name = name;
    }

    String describe() {
        return name + " is an animal";
    }
}

class Dog extends Animal {
    Dog(String name) {
        super(name);
    }

    String fetch() {
        return name + " fetches the stick!";
    }
}
Practise: Java Inheritance: extends and super

Java Method Overriding and Polymorphism

Learn Java method overriding with @Override and polymorphism: dynamic dispatch, super calls, instanceof patterns and final. Practise in your browser.

class Animal {
    String sound() {
        return "...";
    }

    String speak() {
        return "It says " + sound();
    }
}

class Dog extends Animal {
    @Override
    String sound() {
        return "Woof";
    }
}

class Cat extends Animal {
    @Override
    String sound() {
        return "Meow";
    }
}
Practise: Java Method Overriding and Polymorphism

Java Abstract Classes and Abstract Methods

Learn Java abstract classes: abstract methods, constructors in abstract classes and the template method pattern. Write and test real Java in your browser.

abstract class Shape {
    abstract double area();   // no body: every subclass must provide one

    String describe() {       // ordinary methods are allowed too
        return "area " + area();
    }
}

class Circle extends Shape {
    private final double radius;

    Circle(double radius) {
        this.radius = radius;
    }

    @Override
    double area() {
        return Math.PI * radius * radius;
    }
}
Practise: Java Abstract Classes and Abstract Methods

Java Interfaces: implements, default Methods and Comparable

Learn Java interfaces: implements, multiple interfaces, default and static methods, and Comparable for sorting objects. Practise with real Java in your browser.

interface Greeter {
    String greet(String name);   // implicitly public and abstract
}

class FriendlyGreeter implements Greeter {
    @Override
    public String greet(String name) {
        return "Hello, " + name + "!";
    }
}

class PirateGreeter implements Greeter {
    @Override
    public String greet(String name) {
        return "Ahoy, " + name + "!";
    }
}
Practise: Java Interfaces: implements, default Methods and Comparable

Collections & Exceptions

Java HashMap: Key-Value Pairs

Learn the Java HashMap: put, get, getOrDefault, containsKey, looping over entries, counting with merge and grouping with computeIfAbsent.

Map<String, Integer> stock = new HashMap<>();
stock.put("potion", 12);
stock.put("arrow", 250);
stock.put("potion", 15);           // same key: replaces 12

System.out.println(stock.get("potion"));  // 15
System.out.println(stock.size());          // 2
Practise: Java HashMap: Key-Value Pairs

Java HashSet and the Set Interface

Learn Java sets: HashSet, TreeSet and LinkedHashSet, fast contains checks, removing duplicates, and union, intersection and difference.

Set<String> tags = new HashSet<>();
System.out.println(tags.add("rare"));     // true  – added
System.out.println(tags.add("magic"));    // true
System.out.println(tags.add("rare"));     // false – already there
System.out.println(tags.size());          // 2
System.out.println(tags.contains("magic")); // true
tags.remove("magic");
Practise: Java HashSet and the Set Interface

Java Exceptions: try, catch, finally and Custom Exceptions

Handle errors in Java with try, catch and finally, understand checked vs unchecked exceptions, use throw and throws, and write your own custom exceptions.

static void withdraw(int amount) {
    if (amount <= 0) {
        throw new IllegalArgumentException("amount must be positive");
    }
    // ...
}
Practise: Java Exceptions: try, catch, finally and Custom Exceptions

Java Lambdas and Streams Basics

Write modern Java with lambdas, method references and functional interfaces, then filter, map, sort and sum collections with the Stream API.

x -> x * 2                        // one parameter
(a, b) -> a + b                   // two parameters
name -> {                         // a block body needs return
    String trimmed = name.trim();
    return trimmed.toUpperCase();
}
Practise: Java Lambdas and Streams Basics