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.
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
import java.util.Scanner;
Scanner in = newScanner(System.in);
int n = in.nextInt();
double d = in.nextDouble();
String word = in.next(); // up to whitespace
in.nextLine(); // eat the leftover newlineString line = in.nextLine(); // whole linewhile (in.hasNextInt()) { int x = in.nextInt(); }
Fast input (coding contests)
BufferedReader br = newBufferedReader(newInputStreamReader(System.in));
int n = Integer.parseInt(br.readLine().trim());
StringTokenizer st = newStringTokenizer(br.readLine());
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
Command-line arguments
// java Greet Ravi 21publicstaticvoidmain(String[] args) {
if (args.length < 2) return;
String name = args[0];
int age = Integer.parseInt(args[1]);
}
printf / String.format specifiers
Specifier
Meaning
Example
Output
%d
Integer
printf("%d", 42)
42
%5d / %-5d
Width 5, right / left aligned
printf("[%5d]", 42)
[ 42]
%05d
Zero padded
printf("%05d", 42)
00042
%,d
Thousands separator
printf("%,d", 1000000)
1,000,000
%f / %.2f
Decimal (6 places default) / 2 places
printf("%.2f", 3.14159)
3.14
%e
Scientific
printf("%e", 1234.5)
1.234500e+03
%s
String (any object via toString)
printf("%s", "hi")
hi
%c
Character
printf("%c", 'A')
A
%b
Boolean
printf("%b", true)
true
%x / %X / %o
Hex lower / upper, octal
printf("%x", 255)
ff
%n
Platform newline
printf("a%nb")
two lines
%%
Literal percent sign
printf("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
Type
Size
Range / precision
Default
Literal
byte
8 bits
-128 to 127
0
(byte) 10
short
16 bits
-32,768 to 32,767
0
(short) 300
int
32 bits
about ±2.1 billion
0
42, 1_000_000, 0x2A, 0b1010
long
64 bits
about ±9.2 × 10^18
0L
42L
float
32 bits
6–7 significant digits
0.0f
3.14f
double
64 bits
15–16 significant digits
0.0
3.14, 1e-9
char
16 bits
0 to 65,535 (UTF-16 unit)
\u0000
'A', '\n'
boolean
JVM-specific
true / false
false
true
Variables, constants, var
int count = 0; // declare + initialisefinaldoubleGST = 0.18; // constantvar names = newArrayList<String>(); // Java 10+, local onlylong big = 3_000_000_000L; // L needed beyond int rangefloat f = 2.5f; // f needed: 2.5 is a doublechar 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 → doubledouble 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 ↔ numberint n = Integer.parseInt("42");
double x = Double.parseDouble("3.5");
String s = String.valueOf(42); // or "" + 42
Wrapper classes
Primitive
Wrapper
Parse from String
Handy members
int
Integer
Integer.parseInt(s)
MAX_VALUE, MIN_VALUE, toBinaryString(n), compare(a, b)
long
Long
Long.parseLong(s)
MAX_VALUE, compare(a, b)
double
Double
Double.parseDouble(s)
isNaN(x), compare(a, b), MAX_VALUE
char
Character
—
isDigit, isLetter, isWhitespace, toUpperCase
boolean
Boolean
Boolean.parseBoolean(s)
TRUE, FALSE, logicalXor
byte / short / float
Byte / Short / Float
parseByte / parseShort / parseFloat
MAX_VALUE, MIN_VALUE
Autoboxing and enums
Integer boxed = 42; // autoboxingint raw = boxed; // unboxing (NPE if boxed is null)List<Integer> list = List.of(1, 2, 3);
enumLevel { 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
Call
Result
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
Kind
Operators
Arithmetic
+ - * / %
Relational
== != < > <= >=
Logical
&& || ! (short-circuit)
Bitwise
& | ^ ~ << >> >>>
Assignment
= += -= *= /= %= &= |= ^=
Increment / decrement
++i i++ --i i--
Ternary
cond ? a : b
Type
instanceof, (type) cast
Lambda / reference
->, ::
Precedence (high to low)
#
Operators
Associativity
1
a++ 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
< > <= >= instanceof
left 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 7int q = 7 / 2; // 3 integer divisionint m = -7 % 3; // -1 sign follows the dividenddouble h = 7 / 2.0; // 3.5byte x = 10;
x += 5; // OK: compound assignment casts// x = x + 5; // error: int cannot go into byteboolean ok = s != null && s.length() > 0; // short-circuit guardString 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 twoInteger.bitCount(n) // number of 1 bits
a ^ b ^ b // == a (find the unique element)
-8 >> 1// -4 (sign kept)
-8 >>> 1// 2147483644 (zero fill)
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 oncefor (String s : names) { } // enhanced for
names.forEach(s -> System.out.println(s));
if (obj instanceofString s && !s.isEmpty()) {
System.out.println(s.length()); // s is already cast
}
Stringdescribe(Object o) {
returnswitch (o) {
casenull -> "null";
caseInteger i when i > 0 -> "positive int";
caseInteger i -> "int " + i;
caseString s -> "string of length " + s.length();
default -> "something else";
};
}
Which loop?
Situation
Use
Number of repetitions known
for
Repeat until a condition changes
while
Must run at least once (menus, input validation)
do-while
Visit every element, index not needed
enhanced for / forEach
Remove elements while looping
Iterator.remove() or removeIf
Transform / filter a collection
Stream pipeline
📑
Arrays & java.util.Arrays
Create and access
int[] a = {5, 2, 9};
int[] b = newint[5]; // all 0String[] s = newString[3]; // all nullint[][] grid = newint[3][4]; // 3 rows, 4 columnsint[][] jag = newint[3][]; // jagged: rows sized later
jag[0] = newint[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
Method
What 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
Method
Example
Result
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
Method
Effect
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
Feature
String
StringBuilder
StringBuffer
Mutable
No
Yes
Yes
Thread-safe
Yes (immutable)
No
Yes (synchronized)
Speed for many edits
Slow
Fastest
Slower
Use for
Fixed text, map keys
Building text in one thread
Legacy shared buffers
Common string tasks
String rev = newStringBuilder(s).reverse().toString();
boolean palindrome = s.equals(rev);
int[] freq = newint[26];
for (char ch : s.toCharArray()) freq[ch - 'a']++; // lowercase lettersString[] words = line.trim().split("\\s+"); // split on any spacesString csv = String.join(",", words);
char[] cs = s.toCharArray();
Arrays.sort(cs);
String key = newString(cs); // anagram keyString 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 parameterspublicstaticintadd(int a, int b) {
return a + b;
}
staticintadd(int a, int b, int c) { return a + b + c; } // overloadstaticdoubleadd(double a, double b) { return a + b; } // overloadstaticintsum(int... nums) { // varargsint t = 0;
for (int n : nums) t += n;
return t;
}
sum(); sum(1, 2); sum(1, 2, 3, 4);
Recursion templates
intfact(int n) {
if (n <= 1) return1; // base casereturn n * fact(n - 1); // smaller problem
}
longfib(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);
}
longpower(long b, int e) { // fast power O(log e)if (e == 0) return1;
long half = power(b, e / 2);
return e % 2 == 0 ? half * half : half * half * b;
}
static vs instance
Aspect
static
instance
Belongs to
The class
Each object
Call style
Math.max(a, b)
list.size()
Uses this / instance fields
No
Yes
Copies in memory
One
One per object
Polymorphism
Hidden, not overridden
Overridden at runtime
Overload resolution order
Step
Compiler tries
1
Exact type match
2
Widening (int → long → double)
3
Boxing (int → Integer)
4
Varargs (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.
classDemo {
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
recordPoint(int x, int y) { // Java 16+Point { // compact constructorif (x < 0 || y < 0) thrownewIllegalArgumentException();
}
doubledist() { returnMath.sqrt(x * x + y * y); }
}
Point p = newPoint(3, 4);
p.x(); p.dist(); // 3, 5.0enumPlanet {
EARTH(5.97e24), MARS(6.42e23);
privatefinaldouble mass;
Planet(double mass) { this.mass = mass; }
doublemass() { 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.
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.
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
classBox<T> {
privateT value;
voidset(T v) { value = v; }
Tget() { return value; }
}
Box<String> b = newBox<>(); // diamond operatorclassPair<K, V> {
finalK key; finalV value;
Pair(K key, V value) { this.key = key; this.value = value; }
}
static <T> voidswap(T[] a, int i, int j) {
T t = a[i]; a[i] = a[j]; a[j] = t;
}
static <TextendsComparable<T>> Tmax(List<T> list) { // boundedT best = list.get(0);
for (T x : list) if (x.compareTo(best) > 0) best = x;
return best;
}
Wildcards
Type
Accepts
Read as
Can add
List<Number>
Exactly List<Number>
Number
Any Number
List<?>
A list of anything
Object
Nothing (only null)
List<? extends Number>
Number or a subtype
Number
Nothing
List<? super Integer>
Integer or a supertype
Object
Integer
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>.
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
classWorkerextendsThread {
@Overridepublicvoidrun() { System.out.println("worker"); }
}
newWorker().start();
Runnable task = () -> System.out.println(Thread.currentThread().getName());
Thread t = newThread(task, "T1");
t.start(); // new thread (run() would not)
t.join(); // wait for it to finishThread v = Thread.ofVirtual().start(task); // Java 21 virtual thread
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);
};
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.
classUserimplementsSerializable {
privatestaticfinallong serialVersionUID = 1L;
String name;
transientString password; // not saved
}
try (var out = newObjectOutputStream(newFileOutputStream("u.ser"))) {
out.writeObject(user);
}
try (var in = newObjectInputStream(newFileInputStream("u.ser"))) {
User u = (User) in.readObject();
}
Which class should I use?
Need
Use
Read a small text file at once
Files.readString / Files.readAllLines
Read a large file line by line
Files.lines or BufferedReader.readLine
Write text
Files.writeString, BufferedWriter, PrintWriter
Append to a file
StandardOpenOption.APPEND or new FileWriter(f, true)
Binary data (images, PDFs)
Files.readAllBytes or buffered FileInputStream / FileOutputStream
Save / load objects
ObjectOutputStream / ObjectInputStream
List a folder
Files.list(dir), Files.walk(dir)
Simple CSV
BufferedReader + split(",") (a library for quoted fields)
🧮
Math, Big Numbers, Random & Date-Time
java.lang.Math
Call
Result
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 = newBigDecimal("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 equalsBigInteger f = BigInteger.ONE;
for (int i = 2; i <= 30; i++) f = f.multiply(BigInteger.valueOf(i)); // 30!Random rnd = newRandom();
int dice = rnd.nextInt(6) + 1; // 1..6int 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); // 30DayOfWeek dow = today.getDayOfWeek();
LocalDateTime now = LocalDateTime.now();
LocalTime alarm = LocalTime.of(6, 30);
Duration d = Duration.ofMinutes(90); // PT1H30MDateTimeFormatter f = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm");
String text = now.format(f);
LocalDate parsed = LocalDate.parse("2026-10-09"); // ISO formatZonedDateTime 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
Part
Contains
Needed by
JVM
Class loader, bytecode verifier, interpreter, JIT, GC
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.
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 = newHashMap<>();
for (char c : s.toCharArray()) freq.merge(c, 1, Integer::sum);
int[] count = newint[26]; // lowercase letters onlyfor (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) returnnewint[]{i, j};
if (sum < target) i++; else j--;
}
returnnewint[]{-1, -1};
Sliding window (longest unique substring)
Map<Character, Integer> last = newHashMap<>();
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 overflowif (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 = newboolean[rows][cols];
Deque<int[]> q = newArrayDeque<>();
q.offer(newint[]{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(newint[]{r, c});
}
}
Number helpers
booleanisPrime(int n) {
if (n < 2) returnfalse;
for (int i = 2; (long) i * i <= n; i++) if (n % i == 0) returnfalse;
returntrue;
}
intgcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); }
intlcm(int a, int b) { return a / gcd(a, b) * b; }
intdigitSum(int n) { int s = 0; while (n > 0) { s += n % 10; n /= 10; } return s; }
intreverse(int n) { int r = 0; while (n > 0) { r = r * 10 + n % 10; n /= 10; } return r; }
Big-O quick reference
Operation
Time
Array / ArrayList get by index
O(1)
ArrayList add at end
O(1) amortised
ArrayList insert / remove in the middle, contains
O(n)
LinkedList add / remove at either end
O(1)
HashMap / HashSet put, get, contains
O(1) average, O(log n) worst (Java 8+ tree bins)
TreeMap / TreeSet operations
O(log n)
PriorityQueue offer / poll — peek
O(log n) — O(1)
Arrays.sort / Collections.sort
O(n log n)
Binary search
O(log n)
String + in a loop vs StringBuilder
O(n²) vs O(n)
⚡
Gotchas & Interview Traps
Trap
What happens
Remember
== on String / wrappers
Compares references
Use equals
Integer cache -128..127
Integer a = 127, b = 127; a == b is true; with 128 it is false
Never compare wrappers with ==
equals overridden without hashCode
HashMap / HashSet cannot find the object
Override both together
t.run() instead of t.start()
Runs on the current thread
Always start()
Unboxing a null Integer
NullPointerException
Check for null first
list.remove(1) on List<Integer>
Removes index 1
remove(Integer.valueOf(1))
Arrays.asList(intArray)
A List<int[]> of size 1
Use Integer[] or IntStream.of(a).boxed()
List.of(...).add(x)
UnsupportedOperationException
Copy into new ArrayList<>(...)
Modifying a list inside for-each
ConcurrentModificationException
Iterator.remove() / removeIf
0.1 + 0.2 == 0.3
false
BigDecimal or compare with a tolerance
5 / 2
2
Use 5 / 2.0 for 2.5
'a' + 1
98 (an int)
(char) ('a' + 1) gives 'b'
"" + 1 + 2 vs 1 + 2 + ""
"12" vs "3"
Evaluated left to right
switch without break
Falls through to the next case
Use arrow case ->
return inside finally
Overrides the try / catch return
Never return from finally
Static method in a subclass
Hides, does not override
No runtime polymorphism for static
Math.abs(Integer.MIN_VALUE)
Still negative
Use long or Math.absExact
Comparator (a, b) -> a - b
Overflows for large values
Integer.compare(a, b)
"a.b".split(".")
Empty array — . is a regex
split("\\.") or Pattern.quote(".")
nextInt() then nextLine()
nextLine returns ""
Call an extra nextLine()
catch (Exception e) before a specific catch
Compile error: unreachable
Specific first, general last
Changing a HashMap key after insertion
Entry becomes unreachable
Use immutable keys
String + inside a loop
Creates 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.