Skip to main content

Learning Resources

Cheatsheet

A complete Java cheatsheet — every major concept in one page: syntax, strings, OOP, exceptions, generics, the Collections Framework, threads, streams, files, the JVM, coding templates, and interview traps. Ideal for last-minute revision.

Quick Reference

Java Programming Cheatsheet

Every major Java concept on one page — program structure, types, operators, control flow, arrays, strings, methods, OOP, exceptions, generics, collections, threads, lambdas and streams, files, math and dates, the JVM, version features, coding templates, and interview traps. Built for revision before interviews and for looking things up while you code.

20 sections 41 tables 56 code snippets

Program Structure, Output & Input

Minimal program

public class Hello {
    public static void main(String[] args) {
        System.out.println("Hello, Java!");
    }
}

Compile, run, package

javac Hello.java            # compile to Hello.class
java Hello                  # run (class name, no .class)
java Hello.java             # Java 11+: compile + run one file
javac -d out src/*.java     # put classes in out/
java -cp out com.app.Main   # run with a classpath
jar cfe app.jar Main *.class
java -jar app.jar

Output

System.out.print("no newline ");
System.out.println("with newline");
System.out.printf("%-8s|%5d|%8.2f%n", "Ravi", 42, 3.14159);
String s = String.format("%03d", 7);     // "007"
String t = "Total: %d".formatted(99);    // Java 15+
System.err.println("error stream");

Input with Scanner

import java.util.Scanner;

Scanner in = new Scanner(System.in);
int n = in.nextInt();
double d = in.nextDouble();
String word = in.next();       // up to whitespace
in.nextLine();                 // eat the leftover newline
String line = in.nextLine();   // whole line
while (in.hasNextInt()) { int x = in.nextInt(); }

Fast input (coding contests)

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine().trim());
StringTokenizer st = new StringTokenizer(br.readLine());
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());

Command-line arguments

// java Greet Ravi 21
public static void main(String[] args) {
    if (args.length < 2) return;
    String name = args[0];
    int age = Integer.parseInt(args[1]);
}

printf / String.format specifiers

SpecifierMeaningExampleOutput
%dIntegerprintf("%d", 42)42
%5d / %-5dWidth 5, right / left alignedprintf("[%5d]", 42)[ 42]
%05dZero paddedprintf("%05d", 42)00042
%,dThousands separatorprintf("%,d", 1000000)1,000,000
%f / %.2fDecimal (6 places default) / 2 placesprintf("%.2f", 3.14159)3.14
%eScientificprintf("%e", 1234.5)1.234500e+03
%sString (any object via toString)printf("%s", "hi")hi
%cCharacterprintf("%c", 'A')A
%bBooleanprintf("%b", true)true
%x / %X / %oHex lower / upper, octalprintf("%x", 255)ff
%nPlatform newlineprintf("a%nb")two lines
%%Literal percent signprintf("50%%")50%

Rules: the file name must match the public class (Hello.java holds public class Hello). At most one public top-level class per file. Java is case-sensitive, and every statement ends with ;.

Data Types, Variables, Casting & Wrappers

The 8 primitive types

TypeSizeRange / precisionDefaultLiteral
byte8 bits-128 to 1270(byte) 10
short16 bits-32,768 to 32,7670(short) 300
int32 bitsabout ±2.1 billion042, 1_000_000, 0x2A, 0b1010
long64 bitsabout ±9.2 × 10^180L42L
float32 bits6–7 significant digits0.0f3.14f
double64 bits15–16 significant digits0.03.14, 1e-9
char16 bits0 to 65,535 (UTF-16 unit)\u0000'A', '\n'
booleanJVM-specifictrue / falsefalsetrue

Variables, constants, var

int count = 0;                       // declare + initialise
final double GST = 0.18;             // constant
var names = new ArrayList<String>(); // Java 10+, local only
long big = 3_000_000_000L;           // L needed beyond int range
float f = 2.5f;                      // f needed: 2.5 is a double
char c = 'A';
int code = c;                        // 65 (char widens to int)
char next = (char) (c + 1);          // 'B'

Casting and conversion

// widening (automatic): byte → short → int → long → float → double
double d = 10;                  // 10.0
// narrowing (explicit, may lose data)
int i = (int) 9.99;             // 9   (truncates)
byte b = (byte) 130;            // -126 (wraps around)
long r = Math.round(9.5);       // 10
// String ↔ number
int n = Integer.parseInt("42");
double x = Double.parseDouble("3.5");
String s = String.valueOf(42);  // or "" + 42

Wrapper classes

PrimitiveWrapperParse from StringHandy members
intIntegerInteger.parseInt(s)MAX_VALUE, MIN_VALUE, toBinaryString(n), compare(a, b)
longLongLong.parseLong(s)MAX_VALUE, compare(a, b)
doubleDoubleDouble.parseDouble(s)isNaN(x), compare(a, b), MAX_VALUE
charCharacter—isDigit, isLetter, isWhitespace, toUpperCase
booleanBooleanBoolean.parseBoolean(s)TRUE, FALSE, logicalXor
byte / short / floatByte / Short / FloatparseByte / parseShort / parseFloatMAX_VALUE, MIN_VALUE

Autoboxing and enums

Integer boxed = 42;          // autoboxing
int raw = boxed;             // unboxing (NPE if boxed is null)
List<Integer> list = List.of(1, 2, 3);

enum Level { LOW, MEDIUM, HIGH }
Level l = Level.valueOf("HIGH");
l.ordinal();                 // 2
l.name();                    // "HIGH"
for (Level v : Level.values()) System.out.println(v);

Character helpers

CallResult
Character.isDigit('7')true
Character.isLetter('a')true
Character.isLetterOrDigit('_')false
Character.isUpperCase('Q')true
Character.toUpperCase('q')'Q'
'7' - '0'7 (digit value)
(char) ('a' + 2)'c'

Fields get default values; local variables do not and must be assigned before use. Integer overflow wraps silently: Integer.MAX_VALUE + 1 == Integer.MIN_VALUE. Use Math.addExact to get an exception instead, or long / BigInteger for big values.

Operators, Precedence & Bit Tricks

Operator kinds

KindOperators
Arithmetic+ - * / %
Relational== != < > <= >=
Logical&& || ! (short-circuit)
Bitwise& | ^ ~ << >> >>>
Assignment= += -= *= /= %= &= |= ^=
Increment / decrement++i i++ --i i--
Ternarycond ? a : b
Typeinstanceof, (type) cast
Lambda / reference->, ::

Precedence (high to low)

#OperatorsAssociativity
1a++ a--left to right
2++a --a +a -a ! ~ (type)right to left
3* / %left to right
4+ -left to right
5<< >> >>>left to right
6< > <= >= instanceofleft to right
7== !=left to right
8–10& then ^ then |left to right
11–12&& then ||left to right
13? :right to left
14= += -= ...right to left

Tricky expressions

int a = 5;
int b = a++ + ++a;          // 5 + 7 = 12, a is now 7
int q = 7 / 2;              // 3    integer division
int m = -7 % 3;             // -1   sign follows the dividend
double h = 7 / 2.0;         // 3.5
byte x = 10;
x += 5;                     // OK: compound assignment casts
// x = x + 5;               // error: int cannot go into byte
boolean ok = s != null && s.length() > 0;  // short-circuit guard
String t = "Sum: " + 1 + 2; // "Sum: 12"
String u = 1 + 2 + " sum";  // "3 sum"

Bit tricks

(n & 1) == 0          // n is even
n << 1                // n * 2
n >> 1                // n / 2 (rounds down for negatives)
n & (n - 1)           // clear the lowest set bit
n > 0 && (n & (n - 1)) == 0   // n is a power of two
Integer.bitCount(n)   // number of 1 bits
a ^ b ^ b             // == a  (find the unique element)
-8 >> 1               // -4          (sign kept)
-8 >>> 1              // 2147483644  (zero fill)

Control Flow & Pattern Matching

if / else-if / ternary

if (marks >= 90) grade = 'A';
else if (marks >= 75) grade = 'B';
else if (marks >= 60) grade = 'C';
else grade = 'D';

String label = age >= 18 ? "Adult" : "Minor";

Loops

for (int i = 0; i < n; i++) { }
for (int i = n - 1; i >= 0; i--) { }
for (int i = 0, j = n - 1; i < j; i++, j--) { }
while (cond) { }
do { } while (cond);           // runs at least once
for (String s : names) { }     // enhanced for
names.forEach(s -> System.out.println(s));

switch: classic vs arrow expression (Java 14+)

switch (day) {                  // classic: needs break
    case 1: name = "Mon"; break;
    case 2: name = "Tue"; break;
    default: name = "?";
}

String type = switch (day) {    // switch expression
    case 1, 7 -> "Weekend";
    case 2, 3, 4, 5, 6 -> "Weekday";
    default -> {
        System.out.println("bad day");
        yield "Unknown";
    }
};

break, continue, labels

outer:
for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 3; j++) {
        if (j == 1) continue;       // next j
        if (i == 2) break outer;    // leave both loops
        System.out.println(i + "," + j);
    }
}

Pattern matching (Java 16 instanceof, Java 21 switch)

if (obj instanceof String s && !s.isEmpty()) {
    System.out.println(s.length());       // s is already cast
}

String describe(Object o) {
    return switch (o) {
        case null -> "null";
        case Integer i when i > 0 -> "positive int";
        case Integer i -> "int " + i;
        case String s -> "string of length " + s.length();
        default -> "something else";
    };
}

Which loop?

SituationUse
Number of repetitions knownfor
Repeat until a condition changeswhile
Must run at least once (menus, input validation)do-while
Visit every element, index not neededenhanced for / forEach
Remove elements while loopingIterator.remove() or removeIf
Transform / filter a collectionStream pipeline

Arrays & java.util.Arrays

Create and access

int[] a = {5, 2, 9};
int[] b = new int[5];           // all 0
String[] s = new String[3];     // all null
int[][] grid = new int[3][4];   // 3 rows, 4 columns
int[][] jag = new int[3][];     // jagged: rows sized later
jag[0] = new int[2];
a.length;                       // a field, not a method
grid[1].length;                 // columns in row 1

Common patterns

int max = Integer.MIN_VALUE, sum = 0;
for (int x : a) { max = Math.max(max, x); sum += x; }

for (int i = 0, j = a.length - 1; i < j; i++, j--) {
    int t = a[i]; a[i] = a[j]; a[j] = t;      // reverse
}

for (int r = 0; r < grid.length; r++)
    for (int c = 0; c < grid[r].length; c++)
        grid[r][c] = r * c;

java.util.Arrays

MethodWhat it does
Arrays.sort(a)Sort ascending (in place)
Arrays.sort(a, from, to)Sort the range [from, to)
Arrays.sort(arr, Comparator.reverseOrder())Descending — object arrays such as Integer[] only
Arrays.binarySearch(a, key)Index of key in a sorted array; negative if absent
Arrays.fill(a, -1)Set every element
Arrays.copyOf(a, n)New array of length n (truncate or pad)
Arrays.copyOfRange(a, i, j)Copy of [i, j)
Arrays.equals(a, b)Element-by-element comparison
Arrays.toString(a)"[5, 2, 9]"
Arrays.deepToString(grid)Readable 2D array
Arrays.asList(arr)Fixed-size List view of an object array
Arrays.stream(a).sum()Stream operations on arrays

Array defaults: 0, 0.0, false, \u0000, null. a == b compares references — use Arrays.equals. An int[] cannot take a Comparator: box it to Integer[] or sort ascending and reverse.

Strings, StringBuilder & Text Blocks

String methods

MethodExampleResult
length()"java".length()4
charAt(i)"java".charAt(1)'a'
substring(b, e)"hello".substring(1, 3)"el" (end exclusive)
indexOf(x) / lastIndexOf(x)"banana".indexOf("an")1 (-1 if absent)
contains(x)"java".contains("av")true
startsWith(p) / endsWith(p)"file.txt".endsWith(".txt")true
equals(o) / equalsIgnoreCase(o)"A".equalsIgnoreCase("a")true
compareTo(o)"apple".compareTo("banana")negative (dictionary order)
toUpperCase() / toLowerCase()"Java".toUpperCase()"JAVA"
trim() / strip()" hi ".strip()"hi"
isEmpty() / isBlank()" ".isBlank()true (Java 11)
replace(a, b)"a-b-c".replace("-", "")"abc"
replaceAll(regex, r)"a1b2".replaceAll("[0-9]", "")"ab"
split(regex)"a,b,c".split(",")["a", "b", "c"]
String.join(d, items)String.join("-", "a", "b")"a-b"
repeat(n)"ab".repeat(3)"ababab" (Java 11)
toCharArray() / chars()"hi".toCharArray()['h', 'i']
String.valueOf(x)String.valueOf(3.5)"3.5"

StringBuilder methods

MethodEffect
append(x)Add to the end (chainable)
insert(i, x)Insert at index i
delete(b, e)Remove [b, e)
deleteCharAt(i)Remove one character
replace(b, e, s)Replace a range
setCharAt(i, c)Change one character
reverse()Reverse in place
length() / charAt(i)Size / read
toString()Convert to an immutable String

String vs StringBuilder vs StringBuffer

FeatureStringStringBuilderStringBuffer
MutableNoYesYes
Thread-safeYes (immutable)NoYes (synchronized)
Speed for many editsSlowFastestSlower
Use forFixed text, map keysBuilding text in one threadLegacy shared buffers

Common string tasks

String rev = new StringBuilder(s).reverse().toString();
boolean palindrome = s.equals(rev);

int[] freq = new int[26];
for (char ch : s.toCharArray()) freq[ch - 'a']++;   // lowercase letters

String[] words = line.trim().split("\\s+");          // split on any spaces
String csv = String.join(",", words);

char[] cs = s.toCharArray();
Arrays.sort(cs);
String key = new String(cs);                         // anagram key

String block = """
    Hello,
      this is a text block (Java 15+)
    """;

== compares references. Literals are pooled, so "a" == "a" is usually true, but new String("a") == "a" is false — always use equals. Strings work in switch (Java 7+). Use StringBuilder instead of + inside loops.

Methods, Overloading & Recursion

Method anatomy, overloading, varargs

// modifiers   return name  parameters
public static  int    add(int a, int b) {
    return a + b;
}

static int add(int a, int b, int c) { return a + b + c; }  // overload
static double add(double a, double b) { return a + b; }    // overload

static int sum(int... nums) {                              // varargs
    int t = 0;
    for (int n : nums) t += n;
    return t;
}
sum(); sum(1, 2); sum(1, 2, 3, 4);

Recursion templates

int fact(int n) {
    if (n <= 1) return 1;             // base case
    return n * fact(n - 1);           // smaller problem
}

long fib(int n, long[] memo) {        // memoised O(n)
    if (n <= 1) return n;
    if (memo[n] != 0) return memo[n];
    return memo[n] = fib(n - 1, memo) + fib(n - 2, memo);
}

long power(long b, int e) {           // fast power O(log e)
    if (e == 0) return 1;
    long half = power(b, e / 2);
    return e % 2 == 0 ? half * half : half * half * b;
}

static vs instance

Aspectstaticinstance
Belongs toThe classEach object
Call styleMath.max(a, b)list.size()
Uses this / instance fieldsNoYes
Copies in memoryOneOne per object
PolymorphismHidden, not overriddenOverridden at runtime

Overload resolution order

StepCompiler tries
1Exact type match
2Widening (int → long → double)
3Boxing (int → Integer)
4Varargs (int...)

Java is always pass-by-value. For objects the value is a copy of the reference, so a method can change an object’s fields but cannot make the caller’s variable point at a different object.

OOP — Classes, Objects, Constructors & Records

Complete class template

import java.util.Objects;

public class Student {
    private static int count = 0;            // shared by all objects
    private final int id;                    // assigned once
    private String name;
    private double marks;

    public Student(String name) {            // constructor chaining
        this(name, 0.0);
    }

    public Student(String name, double marks) {
        this.id = ++count;
        this.name = name;
        setMarks(marks);
    }

    public String getName() { return name; }
    public double getMarks() { return marks; }

    public void setMarks(double marks) {     // validation in the setter
        if (marks < 0 || marks > 100) throw new IllegalArgumentException("0-100 only");
        this.marks = marks;
    }

    public static int getCount() { return count; }

    @Override public String toString() { return id + ":" + name + " (" + marks + ")"; }

    @Override public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Student other)) return false;
        return id == other.id;
    }

    @Override public int hashCode() { return Objects.hash(id); }
}

Access modifiers

ModifierClassPackageSubclassWorld
public✓✓✓✓
protected✓✓✓✗
default (none)✓✓✗✗
private✓✗✗✗

this vs super

Usethissuper
Fieldthis.namesuper.name
Methodthis.show()super.show()
Constructor callthis(...)super(...)
RuleFirst line of a constructorFirst line of a constructor

Modifier keywords

KeywordOn a variableOn a methodOn a class
finalAssign once (constant)Cannot be overriddenCannot be extended
staticOne copy per classCall without an objectOnly for nested classes
abstract—No body; subclass must implementCannot be instantiated
synchronized—One thread at a time per lock—
transientSkipped by serialization——
volatileVisible across threads——

Initialisation order

class Demo {
    static { System.out.println("1 static block: once, at class load"); }
    { System.out.println("2 instance block: every new"); }
    Demo() { System.out.println("3 constructor"); }
}
// new Demo(); new Demo();
// prints 1, 2, 3, 2, 3

Records and enums with data

record Point(int x, int y) {               // Java 16+
    Point {                                // compact constructor
        if (x < 0 || y < 0) throw new IllegalArgumentException();
    }
    double dist() { return Math.sqrt(x * x + y * y); }
}
Point p = new Point(3, 4);
p.x(); p.dist();                           // 3, 5.0

enum Planet {
    EARTH(5.97e24), MARS(6.42e23);
    private final double mass;
    Planet(double mass) { this.mass = mass; }
    double mass() { return mass; }
}

Encapsulation = private fields + public methods. Java adds a no-argument constructor only if you write none. Records are final, their fields are final, and equals, hashCode, toString, and accessors are generated.

Inheritance, Abstraction, Interfaces & Polymorphism

Everything in one example

abstract class Shape {
    protected final String name;
    Shape(String name) { this.name = name; }
    abstract double area();                          // subclasses must implement
    void describe() { System.out.println(name + " area " + area()); }
}

interface Drawable {
    void draw();                                     // public abstract
    default void hint() { System.out.println("drawing..."); }
    static Drawable blank() { return () -> {}; }
}

class Circle extends Shape implements Drawable {
    private final double r;
    Circle(double r) { super("Circle"); this.r = r; }
    @Override double area() { return Math.PI * r * r; }
    @Override public void draw() { System.out.println("( )"); }
}

Shape s = new Circle(2);           // upcast: automatic
s.describe();                      // runtime dispatch → Circle.area()
if (s instanceof Circle c) c.draw();   // safe downcast

Abstract class vs interface

FeatureAbstract classInterface
Keywordextends (only one)implements (many)
ConstructorsYesNo
FieldsAny kindOnly public static final constants
MethodsAbstract + concreteAbstract, default, static, private
Instance stateYesNo
Best forRelated classes sharing code (IS-A)A capability shared by unrelated classes (CAN-DO)

Overloading vs overriding

PointOverloadingOverriding
WhereSame class (or subclass)Subclass
ParametersMust differMust be the same
Return typeAnySame or a subtype (covariant)
ResolvedCompile timeRuntime
AccessAnySame or wider
Checked exceptionsAnyNone new or broader
static / private / finalCan be overloadedCannot be overridden

Sealed types + pattern switch (Java 17 / 21)

sealed interface Shape permits Circle, Square {}
record Circle(double r) implements Shape {}
record Square(double side) implements Shape {}

double area(Shape s) {
    return switch (s) {               // exhaustive: no default needed
        case Circle c -> Math.PI * c.r() * c.r();
        case Square q -> q.side() * q.side();
    };
}

Methods inherited from Object

MethodOverride when
toString()You want readable printing / logging
equals(Object)Two objects with the same data should be equal
hashCode()Always together with equals
getClass()Final — read runtime type
clone()Rarely; prefer copy constructors

One superclass, many interfaces. Every constructor calls super() implicitly if you do not. Fields and static methods are not polymorphic — only instance methods are dispatched at runtime. Prefer composition (HAS-A) over inheritance when you only need to reuse code.

Exception Handling

Exception hierarchy

Throwable
├── Error                       # JVM problems: do not catch
│   ├── OutOfMemoryError
│   └── StackOverflowError
└── Exception                   # checked unless Runtime
    ├── IOException
    │   └── FileNotFoundException
    ├── SQLException
    ├── InterruptedException
    └── RuntimeException        # unchecked
        ├── NullPointerException
        ├── ArithmeticException
        ├── IllegalArgumentException
        │   └── NumberFormatException
        ├── IllegalStateException
        ├── IndexOutOfBoundsException
        ├── ClassCastException
        ├── ConcurrentModificationException
        └── UnsupportedOperationException

try / catch / finally / try-with-resources

try {
    int n = Integer.parseInt(input);
    System.out.println(100 / n);
} catch (NumberFormatException | ArithmeticException e) {  // multi-catch
    System.out.println("Bad input: " + e.getMessage());
} catch (Exception e) {                                    // general last
    e.printStackTrace();
} finally {
    System.out.println("always runs");
}

// resources close automatically, in reverse order
try (BufferedReader br = Files.newBufferedReader(Path.of("a.txt"))) {
    System.out.println(br.readLine());
} catch (IOException e) {
    System.out.println("Could not read: " + e.getMessage());
}

Custom exception, throw, throws

class InsufficientBalanceException extends Exception {        // checked
    InsufficientBalanceException(String msg) { super(msg); }
}

void withdraw(double amount) throws InsufficientBalanceException {
    if (amount <= 0) throw new IllegalArgumentException("amount must be positive"); // unchecked
    if (amount > balance)
        throw new InsufficientBalanceException("Short by " + (amount - balance));
    balance -= amount;
}

try {
    account.withdraw(5000);
} catch (InsufficientBalanceException e) {
    System.out.println(e.getMessage());
}

Common exceptions — cause and fix

ExceptionTypical causeFix
NullPointerExceptionCalling a method on nullNull checks, Optional, initialise fields
ArrayIndexOutOfBoundsExceptionIndex < 0 or >= lengthLoop with i < a.length
StringIndexOutOfBoundsExceptionBad charAt / substring indexCheck length() first
ArithmeticExceptionInteger division by zeroCheck the divisor
NumberFormatExceptionInteger.parseInt("abc")Validate input or catch it
InputMismatchExceptionScanner expected a numberUse hasNextInt() first
ClassCastExceptionWrong downcastUse instanceof first
ConcurrentModificationExceptionChanging a collection inside for-eachIterator.remove() or removeIf
UnsupportedOperationExceptionAdding to List.of(...) or Arrays.asList(...)Copy into new ArrayList<>(...)
IllegalArgumentExceptionInvalid argument passedValidate early with a clear message
IllegalStateExceptionMethod called at the wrong timeCheck the object state
StackOverflowErrorRecursion with no base caseFix the base case or use a loop
OutOfMemoryErrorToo many objects or a leakRelease references; tune -Xmx

Confusing pairs

TermMeaning
throwRaises one exception object
throwsDeclares exceptions a method may raise
finalConstant / no override / no subclass
finallyBlock that always runs after try
finalize()Deprecated GC hook — do not use

Checked vs unchecked

KindExamplesCompiler
CheckedIOException, SQLExceptionMust catch or declare throws
UncheckedNullPointerException, IllegalArgumentExceptionOptional
ErrorOutOfMemoryErrorDo not catch

Best practice: catch the most specific exception, never swallow it with an empty catch, include a useful message, and use try-with-resources for files, sockets, and connections. A return inside finally overrides the try block’s return — avoid it.

Generics & Wildcards

Generic classes and methods

class Box<T> {
    private T value;
    void set(T v) { value = v; }
    T get() { return value; }
}
Box<String> b = new Box<>();               // diamond operator

class Pair<K, V> {
    final K key; final V value;
    Pair(K key, V value) { this.key = key; this.value = value; }
}

static <T> void swap(T[] a, int i, int j) {
    T t = a[i]; a[i] = a[j]; a[j] = t;
}

static <T extends Comparable<T>> T max(List<T> list) {   // bounded
    T best = list.get(0);
    for (T x : list) if (x.compareTo(best) > 0) best = x;
    return best;
}

Wildcards

TypeAcceptsRead asCan add
List<Number>Exactly List<Number>NumberAny Number
List<?>A list of anythingObjectNothing (only null)
List<? extends Number>Number or a subtypeNumberNothing
List<? super Integer>Integer or a supertypeObjectInteger

PECS — Producer extends, Consumer super. List<Integer> is not a List<Number>. Generics are erased at runtime, so you cannot write new T(), new T[n], or instanceof List<String>. Primitives are not allowed: use List<Integer>, not List<int>.

Collections Framework

Hierarchy

Iterable
└── Collection
    ├── List    → ArrayList, LinkedList, (Vector, Stack: legacy)
    ├── Set     → HashSet, LinkedHashSet
    │   └── SortedSet → TreeSet
    └── Queue   → PriorityQueue
        └── Deque → ArrayDeque, LinkedList

Map  (not a Collection)
├── HashMap, LinkedHashMap, (Hashtable: legacy)
└── SortedMap → TreeMap

Immutable factories (Java 9+)

List<String> days = List.of("Mon", "Tue");
Set<Integer> primes = Set.of(2, 3, 5, 7);
Map<String, Integer> age = Map.of("Ravi", 21, "Asha", 22);
List<String> copy = List.copyOf(mutableList);

// need to modify? wrap in a mutable copy
List<String> editable = new ArrayList<>(days);

Choosing an implementation

ClassOrderDuplicatesnullLookupAdd / remove
ArrayListInsertion (indexed)YesYesget(i) O(1), contains O(n)End O(1)*, middle O(n)
LinkedListInsertionYesYesO(n)Ends O(1)
HashSetNoneNoOneO(1) averageO(1) average
LinkedHashSetInsertionNoOneO(1)O(1)
TreeSetSortedNoNoO(log n)O(log n)
HashMapNoneUnique keysOne null keyO(1) averageO(1) average
LinkedHashMapInsertion / accessUnique keysOne null keyO(1)O(1)
TreeMapSorted keysUnique keysNo null keyO(log n)O(log n)
ArrayDequeFIFO / LIFOYesNopeek O(1)Ends O(1)
PriorityQueueHeap (smallest first)YesNopeek O(1)offer / poll O(log n)

List

List<String> list = new ArrayList<>();
list.add("b"); list.add(0, "a");      // [a, b]
list.get(0); list.set(1, "c");        // a, [a, c]
list.remove("c"); list.remove(0);     // by value, by index
list.contains("a"); list.indexOf("a");
list.size(); list.isEmpty(); list.clear();
list.addAll(List.of("x", "y", "z"));
list.subList(0, 2);                   // view of [0, 2)
list.sort(Comparator.naturalOrder());
list.removeIf(String::isBlank);

List<Integer> nums = new ArrayList<>(List.of(3, 1, 2));
nums.remove(Integer.valueOf(1));      // removes value 1, not index 1

Map

Map<String, Integer> m = new HashMap<>();
m.put("apple", 3);
m.get("apple");                       // 3 (null if absent)
m.getOrDefault("kiwi", 0);            // 0
m.putIfAbsent("pear", 1);
m.merge("apple", 1, Integer::sum);    // apple → 4
m.containsKey("apple"); m.containsValue(4);
m.remove("pear");
for (Map.Entry<String, Integer> e : m.entrySet())
    System.out.println(e.getKey() + " = " + e.getValue());
m.forEach((k, v) -> System.out.println(k + v));

Map<String, List<String>> groups = new HashMap<>();
groups.computeIfAbsent("A", k -> new ArrayList<>()).add("Asha");

Set and TreeSet / TreeMap navigation

Set<Integer> a = new HashSet<>(List.of(1, 2, 3));
Set<Integer> b = new HashSet<>(List.of(2, 3, 4));
boolean added = a.add(3);                          // false: duplicate
Set<Integer> union = new HashSet<>(a); union.addAll(b);     // 1 2 3 4
Set<Integer> common = new HashSet<>(a); common.retainAll(b); // 2 3
Set<Integer> onlyA = new HashSet<>(a); onlyA.removeAll(b);   // 1

TreeSet<Integer> ts = new TreeSet<>(List.of(10, 20, 30));
ts.first(); ts.last();                 // 10, 30
ts.floor(25); ts.ceiling(25);          // 20, 30
ts.headSet(20); ts.tailSet(20);        // [10], [20, 30]

TreeMap<Integer, String> slabs = new TreeMap<>();
slabs.floorEntry(55);                  // nearest key <= 55

Stack, Queue, PriorityQueue

Deque<Integer> stack = new ArrayDeque<>();
stack.push(1); stack.push(2);
stack.peek(); stack.pop();             // 2, 2

Queue<Integer> queue = new ArrayDeque<>();
queue.offer(1); queue.offer(2);
queue.peek(); queue.poll();            // 1, 1

PriorityQueue<Integer> minHeap = new PriorityQueue<>();
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Comparator.reverseOrder());
PriorityQueue<int[]> byCost =
    new PriorityQueue<>((x, y) -> Integer.compare(x[1], y[1]));

Queue / Deque method pairs

OperationThrows exceptionReturns special value
Insert at tailadd(e)offer(e) → false
Remove headremove()poll() → null
Examine headelement()peek() → null
Stack push / poppush(e) / pop()peek() → null
Both ends (Deque)addFirst / removeLastofferFirst / pollLast

java.util.Collections utilities

MethodPurpose
sort(list) / sort(list, cmp)Sort in place
reverse(list) / shuffle(list)Reverse / randomise
max(coll) / min(coll)Largest / smallest
frequency(coll, x)Count occurrences
swap(list, i, j)Swap two positions
nCopies(n, x)Immutable list of n copies
unmodifiableList(list)Read-only view
synchronizedList(list)Thread-safe wrapper
binarySearch(list, key)Search a sorted list

Comparable and Comparator

class Book implements Comparable<Book> {      // natural order
    String title; int year;
    public int compareTo(Book o) { return Integer.compare(year, o.year); }
}
Collections.sort(books);

record Emp(String name, String dept, double salary) {}
emps.sort(Comparator.comparing(Emp::name));
emps.sort(Comparator.comparingDouble(Emp::salary).reversed());
emps.sort(Comparator.comparing(Emp::dept)
        .thenComparing(Emp::salary, Comparator.reverseOrder()));
names.sort(String.CASE_INSENSITIVE_ORDER);

Iterate and remove safely

Iterator<String> it = list.iterator();
while (it.hasNext()) {
    if (it.next().startsWith("x")) it.remove();   // safe
}
list.removeIf(s -> s.startsWith("x"));           // simpler (Java 8)

ListIterator<String> li = list.listIterator();
while (li.hasNext()) li.set(li.next().toUpperCase());

// for (String s : list) list.remove(s);   // ConcurrentModificationException

Arrays.asList is fixed-size and List.of is immutable (and rejects nulls). HashMap iteration order is not guaranteed — use LinkedHashMap or TreeMap when order matters. Never change a field used by equals / hashCode while the object is a key in a map or set. ArrayList add at the end is O(1) amortised (*).

Multithreading & Concurrency

Creating threads

class Worker extends Thread {
    @Override public void run() { System.out.println("worker"); }
}
new Worker().start();

Runnable task = () -> System.out.println(Thread.currentThread().getName());
Thread t = new Thread(task, "T1");
t.start();                     // new thread (run() would not)
t.join();                      // wait for it to finish

Thread v = Thread.ofVirtual().start(task);   // Java 21 virtual thread

Synchronisation tools

class Counter {
    private int count;
    public synchronized void inc() { count++; }        // locks this
    public void dec() { synchronized (this) { count--; } }
}

AtomicInteger hits = new AtomicInteger();
hits.incrementAndGet();                                // lock-free

ReentrantLock lock = new ReentrantLock();
lock.lock();
try { /* critical section */ } finally { lock.unlock(); }

private volatile boolean running = true;               // visibility flag

ExecutorService, Future, CompletableFuture

ExecutorService pool = Executors.newFixedThreadPool(4);
Future<Integer> f = pool.submit(() -> 6 * 7);     // Callable
System.out.println(f.get());                      // 42 (blocks)
pool.shutdown();
pool.awaitTermination(5, TimeUnit.SECONDS);

CompletableFuture.supplyAsync(() -> 100.0)
    .thenApply(price -> price * 1.18)
    .thenAccept(System.out::println);             // runs on a pool thread

Producer-consumer with BlockingQueue

BlockingQueue<String> q = new ArrayBlockingQueue<>(10);

Thread producer = new Thread(() -> {
    try { q.put("order-1"); }                 // waits if full
    catch (InterruptedException e) { Thread.currentThread().interrupt(); }
});
Thread consumer = new Thread(() -> {
    try { System.out.println(q.take()); }     // waits if empty
    catch (InterruptedException e) { Thread.currentThread().interrupt(); }
});
producer.start(); consumer.start();

Thread states

StateWhen
NEWCreated, start() not called yet
RUNNABLERunning or ready to run
BLOCKEDWaiting to enter a synchronized block
WAITINGwait(), join() with no timeout
TIMED_WAITINGsleep(ms), wait(ms), join(ms)
TERMINATEDrun() has finished

Thread API

MethodMeaning
start()New call stack, then calls run()
join()Wait until that thread ends
Thread.sleep(ms)Pause; keeps any locks held
wait() / notify() / notifyAll()Must hold the object monitor; wait releases it
interrupt()Ask a thread to stop
setDaemon(true)JVM may exit while it runs
isAlive()Started and not finished

Thread-safe choices

NeedUse
Shared mapConcurrentHashMap
Read-heavy shared listCopyOnWriteArrayList
Producer-consumerArrayBlockingQueue, LinkedBlockingQueue
Shared counterAtomicInteger, LongAdder
Run many tasksExecutorService (fixed pool or virtual threads)
Run tasks on a scheduleScheduledExecutorService
Wait for N tasksCountDownLatch
Limit concurrent accessSemaphore

synchronized gives mutual exclusion and visibility; volatile gives visibility only (count++ is still unsafe). Avoid deadlock by always taking multiple locks in the same order. Always shutdown() an executor.

Lambdas, Functional Interfaces & Streams

Lambda forms

Runnable r = () -> System.out.println("no args");
Consumer<String> c = s -> System.out.println(s);
BinaryOperator<Integer> add = (a, b) -> a + b;
Comparator<String> byLen = (a, b) -> {
    int d = Integer.compare(a.length(), b.length());
    return d != 0 ? d : a.compareTo(b);
};

Method references

KindReferenceSame as
StaticInteger::parseInts -> Integer.parseInt(s)
Bound instanceSystem.out::printlnx -> System.out.println(x)
Unbound instanceString::toUpperCases -> s.toUpperCase()
ConstructorArrayList::new() -> new ArrayList<>()

Built-in functional interfaces (java.util.function)

InterfaceMethodShapeExample
Predicate<T>testT → booleans -> s.isEmpty()
Function<T, R>applyT → Rs -> s.length()
Consumer<T>acceptT → voidSystem.out::println
Supplier<T>get() → TArrayList::new
UnaryOperator<T>applyT → TString::trim
BinaryOperator<T>apply(T, T) → TInteger::sum
BiFunction<T, U, R>apply(T, U) → R(a, b) -> a * b
Runnablerun() → void() -> work()
Callable<V>call() → V, may throw() -> fetch()
Comparator<T>compare(T, T) → intComparator.comparing(Emp::name)

Stream operations

OperationKindExample
stream(), Stream.of, Arrays.stream, IntStream.rangeSourceIntStream.rangeClosed(1, 5)
filterIntermediate (lazy).filter(n -> n > 0)
map / mapToInt / mapToObjIntermediate.map(String::length)
flatMapIntermediate.flatMap(List::stream)
distinct / sorted / limit / skipIntermediate.sorted().limit(3)
peekIntermediate (debugging).peek(System.out::println)
forEachTerminal.forEach(System.out::println)
collect / toList()Terminal.toList() (Java 16, unmodifiable)
count / sum / average / min / maxTerminal.mapToInt(i -> i).sum()
reduceTerminal.reduce(0, Integer::sum)
anyMatch / allMatch / noneMatchTerminal (short-circuit).anyMatch(s -> s.isBlank())
findFirst / findAnyTerminal (short-circuit).findFirst().orElse("none")

Stream recipes

List<Integer> evens = nums.stream().filter(n -> n % 2 == 0).toList();
int total = nums.stream().mapToInt(Integer::intValue).sum();
double avg = nums.stream().mapToInt(n -> n).average().orElse(0);
List<String> top3 = names.stream().sorted(Comparator.reverseOrder()).limit(3).toList();
String joined = names.stream().map(String::toUpperCase).collect(Collectors.joining(", "));

Map<String, List<Emp>> byDept = emps.stream().collect(Collectors.groupingBy(Emp::dept));
Map<String, Long> headcount = emps.stream()
    .collect(Collectors.groupingBy(Emp::dept, Collectors.counting()));
Map<String, Double> avgPay = emps.stream()
    .collect(Collectors.groupingBy(Emp::dept, Collectors.averagingDouble(Emp::salary)));
Map<Boolean, List<Integer>> passFail = marks.stream()
    .collect(Collectors.partitioningBy(m -> m >= 40));
Map<Character, Long> freq = word.chars().mapToObj(ch -> (char) ch)
    .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

Optional<Emp> richest = emps.stream().max(Comparator.comparingDouble(Emp::salary));
int product = nums.stream().reduce(1, (a, b) -> a * b);
List<String> flat = nested.stream().flatMap(List::stream).toList();

Collectors

CollectorResult
toList() / toSet()List / Set
toMap(k, v)Map (throws on duplicate keys)
toMap(k, v, (a, b) -> a)Map, merge duplicates
groupingBy(f)Map<K, List<T>>
groupingBy(f, counting())Map<K, Long>
partitioningBy(pred)Map<Boolean, List<T>>
joining(", ")Single String
summingInt / averagingDoubleNumber
mapping(f, toList())Transform inside a group

Optional

MethodUse
Optional.of(x) / ofNullable(x) / empty()Create
isPresent() / isEmpty()Check
ifPresent(c) / ifPresentOrElse(c, r)Act on the value
orElse(d)Value or default (default always evaluated)
orElseGet(() -> d)Default computed lazily
orElseThrow()Value or NoSuchElementException
map(f) / filter(p)Transform safely

Streams are lazy (nothing runs until a terminal operation) and single-use. Keep lambdas free of side effects. A lambda can use local variables only if they are effectively final.

File Handling & I/O

Modern NIO: Path and Files

import java.nio.file.*;

Path p = Path.of("data", "notes.txt");                 // data/notes.txt
Files.createDirectories(p.getParent());
Files.writeString(p, "Hello\n");                        // create / overwrite
Files.writeString(p, "More\n", StandardOpenOption.APPEND);
String all = Files.readString(p);
List<String> lines = Files.readAllLines(p);
try (Stream<String> s = Files.lines(p)) {               // lazy: large files
    long errors = s.filter(l -> l.contains("ERROR")).count();
}
Files.exists(p); Files.size(p);
Files.copy(p, Path.of("backup.txt"), StandardCopyOption.REPLACE_EXISTING);
Files.delete(p);

Classic buffered I/O

try (BufferedReader br = new BufferedReader(new FileReader("in.txt"));
     BufferedWriter bw = new BufferedWriter(new FileWriter("out.txt", true))) {
    String line;
    while ((line = br.readLine()) != null) {     // null = end of file
        bw.write(line.toUpperCase());
        bw.newLine();
    }
} catch (IOException e) {
    System.out.println("I/O failed: " + e.getMessage());
}

Serialization

class User implements Serializable {
    private static final long serialVersionUID = 1L;
    String name;
    transient String password;            // not saved
}

try (var out = new ObjectOutputStream(new FileOutputStream("u.ser"))) {
    out.writeObject(user);
}
try (var in = new ObjectInputStream(new FileInputStream("u.ser"))) {
    User u = (User) in.readObject();
}

Which class should I use?

NeedUse
Read a small text file at onceFiles.readString / Files.readAllLines
Read a large file line by lineFiles.lines or BufferedReader.readLine
Write textFiles.writeString, BufferedWriter, PrintWriter
Append to a fileStandardOpenOption.APPEND or new FileWriter(f, true)
Binary data (images, PDFs)Files.readAllBytes or buffered FileInputStream / FileOutputStream
Save / load objectsObjectOutputStream / ObjectInputStream
List a folderFiles.list(dir), Files.walk(dir)
Simple CSVBufferedReader + split(",") (a library for quoted fields)

Math, Big Numbers, Random & Date-Time

java.lang.Math

CallResult
Math.abs(-5)5
Math.max(3, 7) / Math.min(3, 7)7 / 3
Math.pow(2, 10)1024.0 (double)
Math.sqrt(16) / Math.cbrt(27)4.0 / 3.0
Math.ceil(4.1) / Math.floor(4.9)5.0 / 4.0
Math.round(4.5) / Math.round(-4.5)5 / -4
Math.floorMod(-7, 3)2 (always non-negative for positive divisor)
Math.hypot(3, 4)5.0
Math.log(Math.E) / Math.log10(1000)1.0 / 3.0
Math.random()0.0 ≤ x < 1.0
Math.addExact(a, b)Throws on overflow

BigDecimal, BigInteger, Random

BigDecimal price = new BigDecimal("19.99");            // String constructor!
BigDecimal total = price.multiply(BigDecimal.valueOf(3))
                        .setScale(2, RoundingMode.HALF_UP);   // 59.97
price.compareTo(BigDecimal.TEN) > 0;                   // compare, not equals

BigInteger f = BigInteger.ONE;
for (int i = 2; i <= 30; i++) f = f.multiply(BigInteger.valueOf(i));  // 30!

Random rnd = new Random();
int dice = rnd.nextInt(6) + 1;                         // 1..6
int r = ThreadLocalRandom.current().nextInt(10, 21);   // 10..20

java.time (Java 8+)

LocalDate today = LocalDate.now();
LocalDate due = today.plusDays(30);
LocalDate dob = LocalDate.of(2000, 5, 15);
int age = Period.between(dob, today).getYears();
long days = ChronoUnit.DAYS.between(today, due);        // 30
DayOfWeek dow = today.getDayOfWeek();

LocalDateTime now = LocalDateTime.now();
LocalTime alarm = LocalTime.of(6, 30);
Duration d = Duration.ofMinutes(90);                    // PT1H30M

DateTimeFormatter f = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm");
String text = now.format(f);
LocalDate parsed = LocalDate.parse("2026-10-09");       // ISO format
ZonedDateTime ist = ZonedDateTime.now(ZoneId.of("Asia/Kolkata"));

Use BigDecimal (built from a String) for money, never double. java.time classes are immutable — plusDays returns a new object. Prefer java.time over the old Date and Calendar.

JVM, Memory & Tools

JDK vs JRE vs JVM

PartContainsNeeded by
JVMClass loader, bytecode verifier, interpreter, JIT, GCEvery running program
JREJVM + core librariesRunning apps
JDKJRE + javac, jar, jshell, debugger, toolsDevelopers

Stack vs heap

AspectStackHeap
StoresMethod frames, local primitives, referencesObjects, arrays, instance fields
Shared?One per threadShared by all threads
FreedWhen the method returnsBy GC when unreachable
When fullStackOverflowErrorOutOfMemoryError
Size flag-Xss-Xms / -Xmx

Useful commands

java -version
java -Xms256m -Xmx1g -jar app.jar     # initial / maximum heap
java -XX:+UseG1GC -jar app.jar        # choose a garbage collector
jshell                                # interactive Java (Java 9+)
javap -c Hello                        # view bytecode
jps                                   # list running JVMs
jstack <pid>                          # thread dump: find deadlocks
jcmd <pid> GC.heap_info               # heap summary

Class loading: Bootstrap → Platform → Application class loader (parent first). The String pool lives on the heap (since Java 7). An object becomes eligible for GC when no live reference reaches it; System.gc() is only a request.

Modern Java — Features by Version

VersionYearKey features
8 (LTS)2014Lambdas, streams, Optional, default methods, java.time
92017Modules (JPMS), JShell, List.of / Set.of / Map.of, private interface methods
102018var for local variables
11 (LTS)2018isBlank, strip, repeat, lines; HttpClient; run a single file with java File.java
142020Switch expressions (->, yield)
152020Text blocks ("""), helpful NullPointerException messages on by default
162021Records, pattern matching for instanceof, Stream.toList()
17 (LTS)2021Sealed classes and interfaces
21 (LTS)2023Virtual threads, pattern matching for switch, record patterns, sequenced collections
25 (LTS)2025Compact source files with instance main, flexible constructor bodies, module imports, scoped values

Learn on the latest LTS release. Interviews still ask about Java 8 features (lambdas, streams, Optional) most often, then records, var, and switch expressions.

Interview Coding Templates

Frequency count

Map<Character, Integer> freq = new HashMap<>();
for (char c : s.toCharArray()) freq.merge(c, 1, Integer::sum);

int[] count = new int[26];              // lowercase letters only
for (char c : s.toCharArray()) count[c - 'a']++;

Two pointers (sorted array, target sum)

int i = 0, j = a.length - 1;
while (i < j) {
    int sum = a[i] + a[j];
    if (sum == target) return new int[]{i, j};
    if (sum < target) i++; else j--;
}
return new int[]{-1, -1};

Sliding window (longest unique substring)

Map<Character, Integer> last = new HashMap<>();
int best = 0, left = 0;
for (int right = 0; right < s.length(); right++) {
    char c = s.charAt(right);
    if (last.containsKey(c) && last.get(c) >= left) left = last.get(c) + 1;
    last.put(c, right);
    best = Math.max(best, right - left + 1);
}

Binary search

int lo = 0, hi = a.length - 1;
while (lo <= hi) {
    int mid = lo + (hi - lo) / 2;       // avoids int overflow
    if (a[mid] == key) return mid;
    if (a[mid] < key) lo = mid + 1;
    else hi = mid - 1;
}
return -1;

BFS on a grid

int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
boolean[][] seen = new boolean[rows][cols];
Deque<int[]> q = new ArrayDeque<>();
q.offer(new int[]{0, 0});
seen[0][0] = true;
while (!q.isEmpty()) {
    int[] cur = q.poll();
    for (int[] d : dirs) {
        int r = cur[0] + d[0], c = cur[1] + d[1];
        if (r < 0 || r >= rows || c < 0 || c >= cols) continue;
        if (seen[r][c] || grid[r][c] == 1) continue;
        seen[r][c] = true;
        q.offer(new int[]{r, c});
    }
}

Number helpers

boolean isPrime(int n) {
    if (n < 2) return false;
    for (int i = 2; (long) i * i <= n; i++) if (n % i == 0) return false;
    return true;
}
int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); }
int lcm(int a, int b) { return a / gcd(a, b) * b; }
int digitSum(int n) { int s = 0; while (n > 0) { s += n % 10; n /= 10; } return s; }
int reverse(int n) { int r = 0; while (n > 0) { r = r * 10 + n % 10; n /= 10; } return r; }

Big-O quick reference

OperationTime
Array / ArrayList get by indexO(1)
ArrayList add at endO(1) amortised
ArrayList insert / remove in the middle, containsO(n)
LinkedList add / remove at either endO(1)
HashMap / HashSet put, get, containsO(1) average, O(log n) worst (Java 8+ tree bins)
TreeMap / TreeSet operationsO(log n)
PriorityQueue offer / poll — peekO(log n) — O(1)
Arrays.sort / Collections.sortO(n log n)
Binary searchO(log n)
String + in a loop vs StringBuilderO(n²) vs O(n)

Gotchas & Interview Traps

TrapWhat happensRemember
== on String / wrappersCompares referencesUse equals
Integer cache -128..127Integer a = 127, b = 127; a == b is true; with 128 it is falseNever compare wrappers with ==
equals overridden without hashCodeHashMap / HashSet cannot find the objectOverride both together
t.run() instead of t.start()Runs on the current threadAlways start()
Unboxing a null IntegerNullPointerExceptionCheck for null first
list.remove(1) on List<Integer>Removes index 1remove(Integer.valueOf(1))
Arrays.asList(intArray)A List<int[]> of size 1Use Integer[] or IntStream.of(a).boxed()
List.of(...).add(x)UnsupportedOperationExceptionCopy into new ArrayList<>(...)
Modifying a list inside for-eachConcurrentModificationExceptionIterator.remove() / removeIf
0.1 + 0.2 == 0.3falseBigDecimal or compare with a tolerance
5 / 22Use 5 / 2.0 for 2.5
'a' + 198 (an int)(char) ('a' + 1) gives 'b'
"" + 1 + 2 vs 1 + 2 + """12" vs "3"Evaluated left to right
switch without breakFalls through to the next caseUse arrow case ->
return inside finallyOverrides the try / catch returnNever return from finally
Static method in a subclassHides, does not overrideNo runtime polymorphism for static
Math.abs(Integer.MIN_VALUE)Still negativeUse long or Math.absExact
Comparator (a, b) -> a - bOverflows for large valuesInteger.compare(a, b)
"a.b".split(".")Empty array — . is a regexsplit("\\.") or Pattern.quote(".")
nextInt() then nextLine()nextLine returns ""Call an extra nextLine()
catch (Exception e) before a specific catchCompile error: unreachableSpecific first, general last
Changing a HashMap key after insertionEntry becomes unreachableUse immutable keys
String + inside a loopCreates many objects, O(n²)Use StringBuilder

How to use this page: skim the jump chips, drill the tables, then type every snippet once in an IDE or JShell. Pair it with the Interview Q&A page for spoken answers and the Real-life Examples page for simple explanations.