Skip to main content

Learning Resources

Cheatsheet

A complete Java cheatsheet — every major concept in one page: basics, control flow, OOP, exceptions, and the Collections Framework. Ideal for last-minute revision.

Quick Reference

Java Programming Cheatsheet

Every major Java concept on one page — program structure, types, control flow, strings, OOP, exceptions, collections, threads, and Java 8+ — with tables and the smallest working snippets. Built for revision before interviews and for looking things up while you code.

Program Structure & I/O

Minimal program


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

Compile and run


javac Hello.java
java Hello
java -cp . Hello

Scanner / printf essentials


import java.util.Scanner;

Scanner in = new Scanner(System.in);
int n = in.nextInt();
double x = in.nextDouble();
in.nextLine();                      // consume leftover newline
String s = in.nextLine();
System.out.printf("%d %.2f%n", n, x);

Tip: File name must match the public class. Prefer try-with-resources for Scanner on files.

Data Types, Variables & Wrappers

Primitives (typical)

TypeBitsNotes
boolean—true / false
byte8Small signed integer
short16Signed integer
char16UTF-16 code unit
int32Default integer
long64Suffix L
float / double32 / 64Prefer double
var (Java 10+)—Local type inference

final / static / wrappers


final int MAX = 100;
Integer boxed = 42;               // autobox
int raw = boxed;                   // unbox — NPE if null
Integer.parseInt("42");
enum Color { RED, GREEN, BLUE }

Operators

KindExamples
Arithmetic+ - * / %
Relational== != < > <= >=
Logical&& || ! (short-circuit)
Bitwise& | ^ ~ << >> >>>
Assignment= += -= *= /=
Inc / Dec++i / i++
Ternarycond ? a : b
Otherinstanceof, () cast

== on objects is identity. Use equals for content. Integer division: 5/2 == 2.

Control Flow


if (x > 0) { ... }
else if (x == 0) { ... }
else { ... }

switch (k) {
  case 1: ...; break;
  default: ...;
}

for (int i = 0; i < n; i++) { ... }
while (cond) { ... }
do { ... } while (cond);
for (var x : list) { ... }
break; continue;

Arrays


int[] a = {1, 2, 3};
int[] b = new int[5];
int[][] m = new int[2][3];
a.length;                          // not a method
java.util.Arrays.sort(a);
java.util.Arrays.toString(a);

Arrays have a fixed length after creation. Prefer ArrayList when the size grows.

Strings (String / StringBuilder)


String s = "hi";
s.length(); s.isEmpty(); s.charAt(0);
s.substring(0, 2); s.contains("h");
s.equals(t);                       // not ==
StringBuilder sb = new StringBuilder();
sb.append("hi").append(42);
Integer.parseInt("42");

String is immutable and interned for literals. Use StringBuilder in loops. == on wrappers in the cache range can lie — always equals.

Methods, Recursion & Packages


package com.demo.util;

public static int add(int a, int b) {
    return a + b;
}

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

void log(String... parts) { }  // varargs

Overload = same name, different parameters. static methods have no this.

OOP — Classes & Objects


public class Account {
    private int balance;
    private static int count;

    public Account(int balance) {
        this.balance = balance;
        count++;
    }

    public int getBalance() { return balance; }
}
IdeaCheat note
Encapsulationprivate fields + public API
thisCurrent instance; this(...) chains ctors
Static membersShared by all instances
Accessprivate / default / protected / public
ConstructorsNo return type; same name as class
final classCannot be subclassed
equals / hashCodeOverride together for value types

Inheritance, Abstraction & Polymorphism


abstract class Shape {
    abstract double area();
}

interface Drawable {
    void draw();
    default void hint() { }
}

class Circle extends Shape implements Drawable {
    @Override public double area() { return 0; }
    @Override public void draw() { }
}

Shape s = new Circle();
s.area();                          // runtime dispatch

Keywords: extends, implements, abstract, @Override, super. One superclass; many interfaces. Overload = compile-time; override = runtime.

Exceptions & Files


try (var in = new java.io.FileReader("in.txt")) {
    throw new IllegalArgumentException("bad");
} catch (java.io.IOException e) {
    e.printStackTrace();
} finally {
    // cleanup if not using try-with-resources
}

void read() throws java.io.IOException { }
KindExamplesCompiler
CheckedIOException, SQLExceptionHandle or throws
UncheckedNPE, IllegalArgumentExceptionOptional
ErrorOutOfMemoryErrorDo not “fix”

Collections

TypeImplNotes
ListArrayListDynamic array — default
ListLinkedListDoubly linked; weak random access
SetHashSetUnique, unordered
SetTreeSetSorted unique
MapHashMapAverage O(1); one null key
MapTreeMapSorted keys, O(log n)
DequeArrayDequePrefer over legacy Stack
QueuePriorityQueueHeap; not FIFO

List<Integer> list = new ArrayList<>();
list.add(1);

Map<String, Integer> freq = new HashMap<>();
freq.merge("hi", 1, Integer::sum);

for (var it = list.iterator(); it.hasNext(); ) {
    it.next();
}

Threads & Synchronization


Runnable task = () -> System.out.println("hi");
Thread t = new Thread(task);
t.start();                         // not run()
t.join();

synchronized (this) { count++; }
volatile boolean ready;
APIMeaning
start()New call stack, then run()
sleepPause; keeps the monitor
wait / notifyMust hold the monitor
synchronizedMutual exclusion + visibility
volatileVisibility, not atomic i++
ExecutorServicePrefer pools over raw threads

Generics, Lambdas & Streams


class Box<T> { private T value; }

Predicate<String> ok = s -> !s.isBlank();
list.stream()
    .filter(ok)
    .map(String::toUpperCase)
    .toList();

Optional<String> maybe = Optional.ofNullable(name);

Generics erase at runtime. A functional interface has one abstract method. Streams are lazy until a terminal operation.

Gotchas & Interview Traps

TrapRemember
== on String / wrappersUse equals for content
Broken equals without hashCodeHashMap/HashSet lose entries
t.run() instead of start()No new thread
Unboxing a null IntegerNullPointerException
Integer cache -128..127== can be true by accident
Checked exception forgottenHandle or declare throws
Structural modify during for-eachfail-fast ConcurrentModificationException
String + in a loopUse StringBuilder
Overload vs overrideCompile-time vs runtime; static is hidden
Integer division5/2 == 2

How to use: skim jump chips → drill tables → type every snippet once. Pair with Interview Q&A for spoken answers.