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.
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)
| Type | Bits | Notes |
|---|---|---|
boolean | — | true / false |
byte | 8 | Small signed integer |
short | 16 | Signed integer |
char | 16 | UTF-16 code unit |
int | 32 | Default integer |
long | 64 | Suffix L |
float / double | 32 / 64 | Prefer 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
| Kind | Examples |
|---|---|
| Arithmetic | + - * / % |
| Relational | == != < > <= >= |
| Logical | && || ! (short-circuit) |
| Bitwise | & | ^ ~ << >> >>> |
| Assignment | = += -= *= /= |
| Inc / Dec | ++i / i++ |
| Ternary | cond ? a : b |
| Other | instanceof, () 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; }
}
| Idea | Cheat note |
|---|---|
| Encapsulation | private fields + public API |
this | Current instance; this(...) chains ctors |
| Static members | Shared by all instances |
| Access | private / default / protected / public |
| Constructors | No return type; same name as class |
final class | Cannot be subclassed |
| equals / hashCode | Override 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 { }
| Kind | Examples | Compiler |
|---|---|---|
| Checked | IOException, SQLException | Handle or throws |
| Unchecked | NPE, IllegalArgumentException | Optional |
| Error | OutOfMemoryError | Do not “fix” |
Collections
| Type | Impl | Notes |
|---|---|---|
| List | ArrayList | Dynamic array — default |
| List | LinkedList | Doubly linked; weak random access |
| Set | HashSet | Unique, unordered |
| Set | TreeSet | Sorted unique |
| Map | HashMap | Average O(1); one null key |
| Map | TreeMap | Sorted keys, O(log n) |
| Deque | ArrayDeque | Prefer over legacy Stack |
| Queue | PriorityQueue | Heap; 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;
| API | Meaning |
|---|---|
start() | New call stack, then run() |
sleep | Pause; keeps the monitor |
wait / notify | Must hold the monitor |
synchronized | Mutual exclusion + visibility |
volatile | Visibility, not atomic i++ |
ExecutorService | Prefer 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
| Trap | Remember |
|---|---|
== on String / wrappers | Use equals for content |
Broken equals without hashCode | HashMap/HashSet lose entries |
t.run() instead of start() | No new thread |
Unboxing a null Integer | NullPointerException |
Integer cache -128..127 | == can be true by accident |
| Checked exception forgotten | Handle or declare throws |
| Structural modify during for-each | fail-fast ConcurrentModificationException |
String + in a loop | Use StringBuilder |
| Overload vs override | Compile-time vs runtime; static is hidden |
| Integer division | 5/2 == 2 |
How to use: skim jump chips → drill tables → type every snippet once. Pair with Interview Q&A for spoken answers.