# Cheat Sheet

Course: [Java](https://www.devtutorials.ai/learn/java) · Section: Reference
Source: https://www.devtutorials.ai/learn/java/reference/cheat-sheet

> Every topic in the Java course on one page: syntax, the methods used most, and the mistakes that cost the most time.

This page is a quick reference for everything covered in the course. It is written to be scanned, not read through.

Each section gives the syntax, the parts you reach for most, and the one thing people get wrong.

## Program Structure

Every Java program lives in a class. Execution starts at `main`.

```java runnable title="A whole program"
public class Main {
    public static void main(String[] args) {
        System.out.println("Hello");
        System.out.println(add(4, 6));
    }

    static int add(int first, int second) {
        return first + second;
    }
}
```

Expected output:

```text
Hello
10
```

| Piece | Purpose |
|---|---|
| `public class Main` | The class; a public class must match its file name, `Main.java` |
| `public static void main(String[] args)` | Where the program starts |
| `System.out.println(x)` | Prints a line |
| `System.out.print(x)` | Prints without a new line |
| `//` and `/* */` | Comments |
| `;` | Ends every statement |
| `javac Main.java` then `java Main` | Compile, then run |

Every runnable cell on this page is self-contained. Change the values and run it again to check what you remember.

## Variables and Data Types

| Type | Holds | Default | Example |
|---|---|---|---|
| `byte` | -128 to 127 | `0` | `byte b = 12;` |
| `short` | -32,768 to 32,767 | `0` | `short s = 2026;` |
| `int` | Whole numbers (default choice) | `0` | `int count = 10;` |
| `long` | Large whole numbers | `0` | `long views = 8000000000L;` |
| `float` | Decimals, about 7 digits | `0.0` | `float r = 4.5f;` |
| `double` | Decimals (default choice) | `0.0` | `double price = 199.99;` |
| `char` | One character | `'\u0000'` | `char grade = 'A';` |
| `boolean` | `true` or `false` | `false` | `boolean ok = true;` |
| `String` | Text (a class) | `null` | `String name = "Asha";` |

```java runnable title="Declaring, constants, var and conversions"
public class Main {
    public static void main(String[] args) {
        int count = 10;
        double average = 82.5;
        final int MAX_USERS = 100;
        var city = "Pune";

        double widened = count;
        int narrowed = (int) 9.99;
        int parsed = Integer.parseInt("42");
        String text = String.valueOf(3.5);

        System.out.println(count + " " + average + " " + MAX_USERS + " " + city);
        System.out.println(widened + " " + narrowed + " " + parsed + " " + text);
    }
}
```

Expected output:

```text
10 82.5 100 Pune
10.0 9 42 3.5
```

- **Widening** (small → big type) is automatic. **Narrowing** needs a cast and can lose data.
- `(int) 9.99` cuts off the decimal part. It does **not** round.
- Parse text: `Integer.parseInt`, `Double.parseDouble`, `Boolean.parseBoolean`. Turn values into text: `String.valueOf`.

## Input With Scanner

```text
import java.util.Scanner;

Scanner sc = new Scanner(System.in);
String name = sc.nextLine();   // a whole line
int age = sc.nextInt();        // a whole number
sc.nextLine();                 // clear the rest of the line after nextInt
```

## Operators

| Group | Operators |
|---|---|
| Arithmetic | `+` `-` `*` `/` `%` |
| Increment / decrement | `++` `--` |
| Comparison | `==` `!=` `>` `<` `>=` `<=` |
| Logical | `&&` `\|\|` `!` |
| Assignment | `=` `+=` `-=` `*=` `/=` `%=` |
| Ternary | `condition ? a : b` |
| Bitwise / shift | `&` `\|` `^` `~` `<<` `>>` `>>>` |

```java runnable title="The ones that surprise people"
public class Main {
    public static void main(String[] args) {
        System.out.println(7 / 2);
        System.out.println(7 / 2.0);
        System.out.println(17 % 5);
        System.out.println("Sum: " + 2 + 3);
        System.out.println("Sum: " + (2 + 3));

        int x = 5;
        int y = x++;
        System.out.println("x=" + x + ", y=" + y);
    }
}
```

Expected output:

```text
3
3.5
2
Sum: 23
Sum: 5
x=6, y=5
```

## Conditional Statements

```java runnable title="if, else if, ternary and switch"
public class Main {
    public static void main(String[] args) {
        int marks = 76;

        if (marks >= 90) {
            System.out.println("A");
        } else if (marks >= 75) {
            System.out.println("B");
        } else {
            System.out.println("C");
        }

        String result = marks >= 40 ? "Pass" : "Fail";
        System.out.println(result);

        int day = 3;
        switch (day) {
            case 1:
                System.out.println("Monday");
                break;
            case 3:
                System.out.println("Wednesday");
                break;
            default:
                System.out.println("Other day");
        }

        String size = "M";
        int price = switch (size) {
            case "S" -> 199;
            case "M" -> 249;
            default -> 299;
        };
        System.out.println(price);
    }
}
```

Expected output:

```text
B
Pass
Wednesday
249
```

- Compare text with `.equals()`, never `==`.
- A classic `switch` case needs `break`, or it falls through to the next case. The arrow form `->` never falls through.

## Loops

```java runnable title="for, while, do-while, for-each, break and continue"
public class Main {
    public static void main(String[] args) {
        for (int i = 1; i <= 3; i++) {
            System.out.print(i + " ");
        }
        System.out.println();

        int n = 3;
        while (n > 0) {
            System.out.print(n + " ");
            n--;
        }
        System.out.println();

        int tries = 0;
        do {
            tries++;
        } while (tries < 0);
        System.out.println("do-while ran " + tries + " time");

        int[] marks = {72, 35, 88};
        for (int m : marks) {
            if (m < 40) continue;
            System.out.print(m + " ");
        }
        System.out.println();

        for (int i = 1; i <= 10; i++) {
            if (i == 4) break;
            System.out.print(i + " ");
        }
        System.out.println();
    }
}
```

Expected output:

```text
1 2 3
3 2 1
do-while ran 1 time
72 88
1 2 3
```

| Loop | Use when |
|---|---|
| `for` | You know the count |
| `while` | You wait for a condition (may run 0 times) |
| `do-while` | The body must run at least once |
| for-each | You read every item in an array or collection |

## Methods

```java runnable title="Parameters, returns, overloads, varargs and recursion"
public class Main {
    public static void main(String[] args) {
        System.out.println(area(4, 6));
        System.out.println(area(5));
        System.out.println(sum(1, 2, 3, 4));
        System.out.println(factorial(5));
        greet("Ravi");
    }

    static int area(int w, int h) { return w * h; }
    static int area(int side) { return side * side; }

    static int sum(int... values) {
        int total = 0;
        for (int v : values) total += v;
        return total;
    }

    static int factorial(int n) {
        return n <= 1 ? 1 : n * factorial(n - 1);
    }

    static void greet(String name) {
        System.out.println("Hello, " + name);
    }
}
```

Expected output:

```text
24
25
10
120
Hello, Ravi
```

- Java is **pass by value**. A method gets a copy; for objects, a copy of the reference.
- `void` methods return nothing. Every path of a non-void method must `return`.

## Arrays

```java runnable title="1D, 2D and the Arrays class"
import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] scores = {72, 95, 58};
        String[] names = new String[2];
        names[0] = "Asha";

        int[][] grid = {{1, 2, 3}, {4, 5, 6}};

        Arrays.sort(scores);
        System.out.println(Arrays.toString(scores));
        System.out.println("Length: " + scores.length);
        System.out.println("Second name: " + names[1]);
        System.out.println("grid[1][2]: " + grid[1][2]);
        System.out.println("Index of 95: " + Arrays.binarySearch(scores, 95));
        System.out.println(Arrays.toString(Arrays.copyOf(scores, 5)));
    }
}
```

Expected output:

```text
[58, 72, 95]
Length: 3
Second name: null
grid[1][2]: 6
Index of 95: 2
[58, 72, 95, 0, 0]
```

- Indexes run from `0` to `length - 1`. Arrays use `length`, with no brackets.

## Strings

```java runnable title="The methods used most"
public class Main {
    public static void main(String[] args) {
        String s = "  Hello, Java  ";
        String t = s.trim();

        System.out.println(t.length());
        System.out.println(t.toUpperCase());
        System.out.println(t.charAt(0));
        System.out.println(t.indexOf("Java"));
        System.out.println(t.substring(0, 5));
        System.out.println(t.replace("Java", "World"));
        System.out.println(t.contains("Java"));
        System.out.println("a,b,c".split(",").length);
        System.out.println("java".equals("JAVA") + " " + "java".equalsIgnoreCase("JAVA"));

        StringBuilder sb = new StringBuilder("ab");
        sb.append("cd").reverse();
        System.out.println(sb);
    }
}
```

Expected output:

```text
11
HELLO, JAVA
H
7
Hello
Hello, World
true
3
false true
dcba
```

- Strings are **immutable**: methods return new strings, so store the result.
- Build text in a loop with `StringBuilder`.

## DateTime

```java runnable title="LocalDate, formatting, arithmetic and periods"
import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;

public class Main {
    public static void main(String[] args) {
        LocalDate start = LocalDate.of(2026, 1, 31);
        DateTimeFormatter indian = DateTimeFormatter.ofPattern("dd/MM/yyyy");

        System.out.println(start.plusDays(10));
        System.out.println(start.plusMonths(1));
        System.out.println(start.format(indian));
        System.out.println(LocalDate.parse("15/08/2026", indian));
        System.out.println(start.isBefore(LocalDate.of(2026, 2, 1)));
        System.out.println(Period.between(LocalDate.of(2008, 3, 14), LocalDate.of(2026, 10, 7)));
    }
}
```

Expected output:

```text
2026-02-10
2026-02-28
31/01/2026
2026-08-15
true
P18Y6M23D
```

| Class | Holds |
|---|---|
| `LocalDate` | A date |
| `LocalTime` | A time |
| `LocalDateTime` | A date and a time |
| `ZonedDateTime` | A date and time in a time zone |
| `Duration` / `Period` | A gap in time / in calendar days |

- `MM` is months, `mm` is minutes.

## Classes and Objects

```java runnable title="Fields, constructors, this, getters and static"
public class Main {
    public static void main(String[] args) {
        Account a = new Account("Asha", 500);
        a.deposit(200);
        a.deposit(-50);
        System.out.println(a.getOwner() + ": " + a.getBalance());
        System.out.println("Accounts created: " + Account.count);
    }
}

class Account {
    static int count = 0;
    private final String owner;
    private int balance;

    Account(String owner, int balance) {
        this.owner = owner;
        this.balance = balance;
        count++;
    }

    public String getOwner() { return owner; }
    public int getBalance() { return balance; }

    public void deposit(int amount) {
        if (amount > 0) {
            balance += amount;
        }
    }
}
```

Expected output:

```text
Asha: 700
Accounts created: 1
```

| Modifier | Visible to |
|---|---|
| `private` | This class only |
| default (none) | This package |
| `protected` | This package and child classes |
| `public` | Everyone |

## Inheritance, Polymorphism and Abstraction

```java runnable title="extends, super, @Override and abstract"
public class Main {
    public static void main(String[] args) {
        Shape[] shapes = { new Circle(2), new Square(3) };
        for (Shape s : shapes) {
            s.describe();
        }

        Shape s = shapes[1];
        if (s instanceof Square sq) {
            System.out.println("Side: " + sq.side);
        }
    }
}

abstract class Shape {
    String name;

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

    abstract double area();

    void describe() {
        System.out.println(name + " area: " + area());
    }
}

class Circle extends Shape {
    double r;
    Circle(double r) { super("Circle"); this.r = r; }
    @Override double area() { return 3.0 * r * r; }
}

class Square extends Shape {
    double side;
    Square(double side) { super("Square"); this.side = side; }
    @Override double area() { return side * side; }
}
```

Expected output:

```text
Circle area: 12.0
Square area: 9.0
Side: 3.0
```

- `extends` one class; `implements` many interfaces.
- The object's real type decides which overridden method runs.
- Always mark overrides with `@Override`.

## Interfaces, Enums and Records

```java runnable title="The other type kinds"
public class Main {
    public static void main(String[] args) {
        Greeter g = name -> "Hello, " + name;
        System.out.println(g.greet("Meena"));

        Size s = Size.M;
        System.out.println(s + " costs " + s.price());

        Point p = new Point(3, 4);
        System.out.println(p + " x=" + p.x());
        System.out.println(p.equals(new Point(3, 4)));
    }
}

interface Greeter {
    String greet(String name);
}

enum Size {
    S(199), M(249), L(299);

    private final int price;
    Size(int price) { this.price = price; }
    int price() { return price; }
}

record Point(int x, int y) { }
```

Expected output:

```text
Hello, Meena
M costs 249
Point[x=3, y=4] x=3
true
```

| Kind | Use for |
|---|---|
| `interface` | An ability many classes share |
| `abstract class` | A half-built parent with shared code |
| `enum` | A fixed list of choices |
| `record` | Small data that never changes |
| `sealed` | A type with a fixed list of children |

## Exception Handling

```java runnable title="try, catch, finally, throw and a custom exception"
public class Main {
    public static void main(String[] args) {
        try {
            int n = Integer.parseInt("abc");
        } catch (NumberFormatException e) {
            System.out.println("Not a number");
        } finally {
            System.out.println("finally always runs");
        }

        try {
            withdraw(100, 500);
        } catch (LowBalanceException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }

    static void withdraw(int balance, int amount) throws LowBalanceException {
        if (amount > balance) {
            throw new LowBalanceException("Need " + (amount - balance) + " more");
        }
    }
}

class LowBalanceException extends Exception {
    LowBalanceException(String message) {
        super(message);
    }
}
```

Expected output:

```text
Not a number
finally always runs
Error: Need 400 more
```

| Kind | Extends | Must catch or declare? |
|---|---|---|
| Checked | `Exception` | Yes |
| Unchecked | `RuntimeException` | No |
| Error | `Error` | No, do not catch |

- Catch specific exceptions before general ones. `throw` raises; `throws` declares.

## Packages

```text
package com.syncshop.billing;          // first line of the file

import java.util.List;                 // one class
import java.util.*;                    // a whole package
import static java.lang.Math.PI;       // a static member
```

- Package names are lowercase, starting with your domain reversed: `com.company.project`.
- `java.lang` is imported automatically.

## Generics

```java runnable title="A generic class, a generic method and a bound"
import java.util.List;

public class Main {
    public static void main(String[] args) {
        Box<String> box = new Box<>("Asha");
        System.out.println(box.get());

        System.out.println(first(List.of(7, 3, 9)));
        System.out.println(total(List.of(1.5, 2.5)));
    }

    static <T> T first(List<T> items) {
        return items.get(0);
    }

    static double total(List<? extends Number> nums) {
        double sum = 0;
        for (Number n : nums) sum += n.doubleValue();
        return sum;
    }
}

class Box<T> {
    private final T item;
    Box(T item) { this.item = item; }
    T get() { return item; }
}
```

Expected output:

```text
Asha
7
4.0
```

- Use wrapper types: `List<Integer>`, never `List<int>`.
- **PECS**: read with `? extends`, write with `? super`.

## Collections

```java runnable title="List, Set, Map, Stack and Queue"
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;

public class Main {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>(List.of("Pen", "Bag", "Pen"));
        list.add("Cap");
        System.out.println(list + " size " + list.size());

        Set<String> set = new TreeSet<>(list);
        System.out.println(set);

        Map<String, Integer> prices = new TreeMap<>();
        prices.put("Pen", 20);
        prices.put("Bag", 499);
        System.out.println(prices.get("Bag") + " " + prices.getOrDefault("Hat", 0));

        Deque<String> stack = new ArrayDeque<>();
        stack.push("a");
        stack.push("b");
        System.out.println("Stack pops: " + stack.pop());

        Queue<String> queue = new ArrayDeque<>();
        queue.offer("first");
        queue.offer("second");
        System.out.println("Queue polls: " + queue.poll());
    }
}
```

Expected output:

```text
[Pen, Bag, Pen, Cap] size 4
[Bag, Cap, Pen]
499 0
Stack pops: b
Queue polls: first
```

| Need | Use |
|---|---|
| Items in order, duplicates allowed | `ArrayList` |
| Unique items, fast checks | `HashSet` (`TreeSet` for sorted) |
| Look up a value by key | `HashMap` (`TreeMap` for sorted keys) |
| Last in, first out | `ArrayDeque` as a stack |
| First in, first out | `ArrayDeque` or `LinkedList` as a queue |
| Smallest first | `PriorityQueue` |

- Remove while looping with `removeIf` or an `Iterator`, never `list.remove` inside for-each.

## Lambdas and Streams

```java runnable title="Lambdas, method references and a stream pipeline"
import java.util.List;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        Predicate<Integer> isEven = n -> n % 2 == 0;
        Function<String, Integer> length = String::length;
        System.out.println(isEven.test(4) + " " + length.apply("Java"));

        List<Integer> marks = List.of(72, 35, 88, 28, 64, 91);

        List<Integer> passed = marks.stream()
                .filter(m -> m >= 40)
                .sorted()
                .toList();
        System.out.println(passed);

        int total = marks.stream().reduce(0, Integer::sum);
        long high = marks.stream().filter(m -> m > 80).count();
        String joined = List.of("a", "b", "c").stream().collect(Collectors.joining("-"));
        System.out.println(total + " " + high + " " + joined);
    }
}
```

Expected output:

```text
true 4
[64, 72, 88, 91]
378 2 a-b-c
```

| Interface | Takes | Returns |
|---|---|---|
| `Predicate<T>` | One value | `boolean` |
| `Function<T, R>` | One value | A value |
| `Consumer<T>` | One value | Nothing |
| `Supplier<T>` | Nothing | A value |

- Intermediate: `filter`, `map`, `sorted`, `distinct`, `limit`, `skip`. Terminal: `collect`, `toList`, `forEach`, `reduce`, `count`, `findFirst`, `anyMatch`, `allMatch`.
- A stream can only be used once.

## File Handling

```text
Path file = Path.of("notes.txt");
Files.writeString(file, "Hello\n");                                       // replace
Files.writeString(file, "More\n", StandardOpenOption.CREATE,
        StandardOpenOption.APPEND);                                       // append
String all = Files.readString(file);
List<String> lines = Files.readAllLines(file);

try (BufferedReader r = new BufferedReader(new FileReader("notes.txt"))) {
    String line;
    while ((line = r.readLine()) != null) { ... }
}
```

- Put every file, reader and writer in try-with-resources so it is closed.
- File methods throw `IOException`, a checked exception.

## Multithreading

```java runnable title="Threads, join and synchronized"
public class Main {
    static int count = 0;

    static synchronized void increment() {
        count++;
    }

    public static void main(String[] args) throws InterruptedException {
        Runnable job = () -> {
            for (int i = 0; i < 1000; i++) increment();
        };

        Thread a = new Thread(job, "worker-a");
        Thread b = new Thread(job, "worker-b");
        a.start();
        b.start();
        a.join();
        b.join();

        System.out.println("Count: " + count);
        System.out.println("State of a: " + a.getState());
    }
}
```

Expected output:

```text
Count: 2000
State of a: TERMINATED
```

- `start()` creates a thread; calling `run()` does not.
- `join()` waits for a thread to finish.
- Guard shared, changing data with `synchronized`. Take several locks in the same order to avoid deadlocks.

## Optional and Pattern Matching

```java runnable title="Optional and switch patterns"
import java.util.Optional;

public class Main {
    public static void main(String[] args) {
        Optional<String> found = Optional.of("Ravi");
        Optional<String> missing = Optional.empty();

        System.out.println(found.orElse("nobody") + " " + missing.orElse("nobody"));
        found.ifPresent(name -> System.out.println("Hi, " + name));

        Object[] values = {250, -5, "hello"};
        for (Object v : values) {
            String label = switch (v) {
                case Integer i when i > 100 -> "big number";
                case Integer i -> "number";
                case String s -> "text of length " + s.length();
                default -> "other";
            };
            System.out.println(label);
        }
    }
}
```

Expected output:

```text
Ravi nobody
Hi, Ravi
big number
number
text of length 5
```

- Create with `Optional.of`, `Optional.ofNullable` or `Optional.empty()`. Avoid `get()` without a check.
- `orElse` always builds its fallback; `orElseGet` builds it only when empty.
- `obj instanceof String s` checks and casts in one step.

## Check What You Remember

This page is a reminder, not a replacement for the lessons. If a line here does not make sense, go back to that chapter and work through its examples.

## The Mistakes That Cost the Most Time

| Symptom | Cause | Fix |
|---|---|---|
| `';' expected` | A statement has no semicolon | Add `;` |
| `cannot find symbol` | A typo, a wrong capital letter, or a missing import | Check spelling, case and imports |
| `incompatible types: possible lossy conversion` | A bigger type was stored in a smaller one | Use the right type, or cast |
| An average comes out as a whole number | Both operands are `int` | Make one a `double` |
| Text that looks the same does not match | `==` was used on strings | Use `.equals()` |
| `NullPointerException` | A method was called on `null` | Check for `null`, or use `Optional` |
| `ArrayIndexOutOfBoundsException` | `<=` used with `length` | Loop with `i < array.length` |
| `ConcurrentModificationException` | A collection changed during a for-each loop | Use `removeIf` or an `Iterator` |
| `unreported exception ... must be caught or declared` | A checked exception was ignored | Catch it, or add `throws` |
| A written file is empty | The writer was never closed | Use try-with-resources |
| A total changes every run with threads | A race condition | Use `synchronized` |
| The program freezes with threads | A deadlock | Take locks in the same order |
