// Quick Revision ยท 320+ Methods

๐Ÿ› ๏ธ Java Methods Reference

Every method you need to know โ€” from String to Stream, with behavioral notes and gotchas. Search across all 16 categories at once.

320+ Methods
16 Categories
Java 21 Up to Date
NEW Extras Added
No methods match your search.

01String Methods

Strings are immutable. Every method that "changes" a string returns a NEW string โ€” the original is unchanged unless you reassign.

MethodSyntaxDescriptionNotes
length()str.length()Number of chars (UTF-16 units)Counts code units, not code points. "๐Ÿ˜€".length() = 2.
charAt()str.charAt(2)Char at indexThrows StringIndexOutOfBoundsException if invalid.
indexOf()str.indexOf("a")First index of char/substringReturns -1 if not found. Overload: indexOf(s, from).
lastIndexOf()str.lastIndexOf("a")Last index of char/substringSearches from end. Returns -1 if not found.
substring()str.substring(2, 5)Extract [start, end)Returns NEW string. End is exclusive.
toLowerCase()str.toLowerCase()All chars to lowercaseUse Locale overload for locale-correct (e.g. Turkish 'I').
toUpperCase()str.toUpperCase()All chars to uppercaseReturns NEW string.
trim()str.trim()Remove leading/trailing whitespaceOnly strips ASCII โ‰ค . Prefer strip().
strip()str.strip()Unicode-aware trim (Java 11+)Preferred over trim() in modern code.
stripLeading()str.stripLeading()Remove leading whitespace only (11+)Trailing spaces kept.
stripTrailing()str.stripTrailing()Remove trailing whitespace only (11+)Leading spaces kept.
replace()str.replace("a", "b")Replace all literal occurrencesNo regex โ€” fast for literals.
replaceAll()str.replaceAll(regex, repl)Replace all regex matchesSpecial regex chars need escaping.
replaceFirst()str.replaceFirst(regex, repl)Replace first regex matchRegex-based.
contains()str.contains("hi")Substring presenceCase-sensitive. No regex.
startsWith()str.startsWith("Hi")Prefix checkOverload: startsWith(prefix, offset).
endsWith()str.endsWith("!")Suffix checkCase-sensitive.
equals()str.equals(other)Content equalityALWAYS use this, not ==.
equalsIgnoreCase()str.equalsIgnoreCase(other)Case-insensitive equalityNull arg throws NPE.
compareTo()str.compareTo(other)Lexicographic compare<0, 0, >0. Used by sort.
compareToIgnoreCase()str.compareToIgnoreCase(other)Case-insensitive compareFor alphabetic sort regardless of case.
isEmpty()str.isEmpty()Length is 0Doesn't catch whitespace-only.
isBlank()str.isBlank()Empty or whitespace-only (11+)Better than isEmpty() for input validation.
split()str.split(",")Split on regexTrailing empties dropped. Use split(r,-1) to keep.
toCharArray()str.toCharArray()Convert to char[]Returns NEW array โ€” modifying it doesn't change string.
valueOf()String.valueOf(42)Any value โ†’ String (static)valueOf(null) returns "null" โ€” no NPE.
format()String.format("%s %d", s, n)Printf-style format (static)Specifiers: %s, %d, %f, %n, %tF (date)โ€ฆ
concat()str.concat(" world")Append a stringPrefer + or StringBuilder for multiple concats.
intern()str.intern()Canonical from string poolMemory dedup. Use sparingly โ€” pool is global.
matches()str.matches(regex)Whole-string regex matchImplicitly anchored ^โ€ฆ$. For partial use find().
repeat()str.repeat(3)Repeat n times (Java 11+)repeat(0) = "". Negative throws.
chars()str.chars()IntStream of charsCast: .mapToObj(c -> (char)c).
codePoints() NEWstr.codePoints()IntStream of Unicode code pointsHandles surrogate pairs (emoji etc.) correctly.
codePointAt()str.codePointAt(0)Code point at indexUse over charAt() for non-BMP chars.
codePointCount() NEWstr.codePointCount(0, len)Count of code points in rangeDifferent from length() for emoji/CJK.
getBytes()str.getBytes(StandardCharsets.UTF_8)Encode to byte[]ALWAYS pass a charset for portability.
hashCode()str.hashCode()String hashEqual strings โ†’ equal hash. Cached after first call.
toString()str.toString()Returns itselfUseful via Object reference.
join()String.join("-", "a", "b")Join with delimiter (static)Also accepts Iterable: String.join(", ", list).
formatted() โ˜…"Hi %s".formatted(name)Instance format() (Java 15+)Cleaner than String.format().
lines()str.lines()Stream<String> of lines (11+)Splits on \n, \r, \r\n. No terminators in result.
indent() โ˜…str.indent(4)Add/remove indentation (12+)Negative removes spaces.
stripIndent() โ˜…str.stripIndent()Strip common indent (15+)For text blocks. Removes incidental whitespace.
translateEscapes() โ˜…str.translateEscapes()Translate \n etc. (15+)Processes escape sequences in literal text.
describeConstable() NEWstr.describeConstable()Optional constant desc (12+)For invokedynamic/CDS use; rarely needed.

02StringBuilder Methods

Mutable โ€” methods modify in-place and return this so they chain. Prefer over String + in loops.

MethodSyntaxDescriptionNotes
append()sb.append("x")Append to endOverloads for every type. Chains: sb.append("a").append("b").
insert()sb.insert(2, "Hi")Insert at indexShifts existing chars right.
delete()sb.delete(1, 4)Remove [start, end)In-place. End is exclusive.
deleteCharAt()sb.deleteCharAt(3)Remove single charIn-place.
replace()sb.replace(1, 4, "XY")Replace range with stringReplacement length can differ from range.
reverse()sb.reverse()Reverse in-placeHandles surrogate pairs correctly.
toString()sb.toString()Snapshot to immutable StringBuilder itself unchanged.
length()sb.length()Current content lengthDifferent from capacity().
charAt()sb.charAt(2)Char at indexThrows StringIndexOOB.
setCharAt()sb.setCharAt(2, 'Z')Set char at index (void)In-place. Returns nothing.
indexOf()sb.indexOf("ab")First index of substringReturns -1 if missing.
lastIndexOf()sb.lastIndexOf("ab")Last index of substringReturns -1 if missing.
substring()sb.substring(2)Substring as new StringBuilder unchanged.
capacity()sb.capacity()Current buffer sizeDefault 16. Grows as needed.
ensureCapacity()sb.ensureCapacity(50)Pre-grow bufferAvoids resize churn for known sizes.
trimToSize()sb.trimToSize()Shrink buffer to lengthFrees unused memory.
appendCodePoint() NEWsb.appendCodePoint(0x1F600)Append Unicode code pointCorrectly encodes surrogate pairs.
compareTo() NEWsb.compareTo(other)Lex compare (Java 11+)Returns <0, 0, >0.
chars() NEWsb.chars()IntStream of charsSame as String.chars().

03Array Methods (java.util.Arrays)

All static. sort(), fill(), setAll() mutate in-place; copyOf(), copyOfRange() return NEW arrays.

MethodSyntaxDescriptionNotes
Arrays.sort()Arrays.sort(arr)Sort ascending in-placeDual-pivot quicksort (primitives), TimSort (objects).
Arrays.sort(range)Arrays.sort(arr, 2, 5)Sort sub-range [from, to)In-place.
Arrays.binarySearch()Arrays.binarySearch(arr, key)Binary search sorted arrayArray MUST be sorted. Negative if missing.
Arrays.fill()Arrays.fill(arr, 0)Fill with valueIn-place. Range overload available.
Arrays.copyOf()Arrays.copyOf(arr, 6)Copy with new lengthPads 0/null if larger.
Arrays.copyOfRange()Arrays.copyOfRange(arr, 1, 4)Copy sub-range[from, to). NEW array.
Arrays.equals()Arrays.equals(a, b)Element-wise equalityUse this โ€” arrays don't override equals().
Arrays.deepEquals()Arrays.deepEquals(a2d, b2d)Deep equality (nested)Use for 2D/nested arrays.
Arrays.toString()Arrays.toString(arr)Readable [a, b, c]arr.toString() gives [I@1b6dโ€ฆ.
Arrays.deepToString()Arrays.deepToString(a2d)Readable nested arraysFor 2D arrays.
Arrays.asList()Arrays.asList(1, 2, 3)Fixed-size list viewadd/remove throw UOE. Wrap in new ArrayList<>() to make resizable.
Arrays.stream()Arrays.stream(arr)Stream from arrayint[] โ†’ IntStream. Range overload exists.
Arrays.parallelSort()Arrays.parallelSort(arr)Parallel sort (large arrays)Useful only for >~1000 elements.
Arrays.mismatch()Arrays.mismatch(a, b)First differing index (Java 9+)Returns -1 if equal.
Arrays.compare()Arrays.compare(a, b)Lex compare (Java 9+)<0, 0, >0.
arr.lengtharr.lengthLength (FIELD, no parens)Fixed at creation.
arr.clone()arr.clone()Shallow copyFor 2D, inner arrays are still shared.
Arrays.setAll() NEWArrays.setAll(arr, i -> i*i)Fill via generator functionCleaner than a manual loop.
Arrays.parallelPrefix() NEWArrays.parallelPrefix(arr, Integer::sum)Cumulative reduction in-placeLike prefix sums; parallelized.
Arrays.hashCode() NEWArrays.hashCode(arr)Content-based hashUse in equals/hashCode of classes containing arrays.
Arrays.deepHashCode() NEWArrays.deepHashCode(a2d)Hash for nested arraysPairs with deepEquals().

04List & ArrayList Methods

ArrayList is mutable. List.of() creates IMMUTABLE lists. subList() returns a VIEW โ€” changes propagate.

MethodSyntaxDescriptionNotes
add()list.add("x")Append to endReturns boolean (always true for ArrayList).
add(i, v)list.add(2, "x")Insert at indexO(n) โ€” shifts right.
addAll()list.addAll(other)Append a collectionModifies in-place.
addAll(i, c) NEWlist.addAll(2, other)Insert collection at indexShifts existing elements.
get()list.get(0)Element at indexO(1) for ArrayList.
set()list.set(1, "y")Replace at indexReturns OLD value. Size unchanged.
remove(int)list.remove(2)Remove by indexReturns removed element. O(n) shift.
remove(Object)list.remove("abc")Remove first matchFor Integer values use remove(Integer.valueOf(n)).
clear()list.clear()Remove allCapacity retained.
size()list.size()Element countNot the same as capacity.
isEmpty()list.isEmpty()No elements?More readable than size()==0.
contains()list.contains("a")MembershipO(n). Uses equals().
containsAll()list.containsAll(other)All present?O(n*m). Use Set for speed.
indexOf()list.indexOf("a")First match index-1 if absent.
lastIndexOf()list.lastIndexOf("a")Last match index-1 if absent.
subList()list.subList(1, 4)VIEW of [from, to)Mutations reflect both ways. Wrap in new ArrayList for copy.
sort()list.sort(null)Sort with Comparator (or null = natural)In-place. Stable (TimSort).
toArray()list.toArray(new String[0])Convert to typed arrayPass new T[0] โ€” JVM optimizes.
iterator()list.iterator()Forward iteratorUse iterator.remove() to remove safely.
listIterator() NEWlist.listIterator()Bidirectional + indexSupports previous(), set(), add() during iteration.
forEach()list.forEach(System.out::println)Lambda iterationCannot resize during iteration.
removeIf()list.removeIf(x -> x > 5)Remove matching predicateSafe during iteration.
replaceAll()list.replaceAll(x -> x*2)Transform every elementSize unchanged.
retainAll() NEWlist.retainAll(other)Keep only common elementsSet intersection on lists.
stream()list.stream()Sequential streamDoesn't modify source.
parallelStream() NEWlist.parallelStream()Parallel streamUse only for CPU-bound, large lists.
List.of()List.of(1, 2, 3)Immutable list (Java 9+)Null elements throw NPE.
List.copyOf()List.copyOf(list)Immutable snapshot (10+)Defensive copy.

05Conversions: Array โ†” List โ†” Stream

Common gotcha: Arrays.asList() returns a fixed-size view. Wrap to make truly resizable.

DirectionSyntaxDescriptionNotes
Array โ†’ List (fixed)Arrays.asList(arr)Fixed-size list viewadd/remove throw UOE. set() works.
Array โ†’ ArrayListnew ArrayList<>(Arrays.asList(arr))Mutable resizable listStandard pattern.
Array โ†’ List (immut)List.of(arr)Immutable, no nullsJava 9+.
ArrayList โ†’ Arraylist.toArray(new String[0])Typed arrayPass zero-length โ€” JVM optimizes.
List โ†’ ArrayListnew ArrayList<>(list)Wrap any list as mutableDefensive copy.
Stream โ†’ Liststream.collect(Collectors.toList())Mutable listJava 16+: stream.toList() gives unmodifiable.
Stream โ†’ unmod Liststream.toList()Unmodifiable (Java 16+)Throws on add/remove.
int[] โ†’ List<Integer>Arrays.stream(arr).boxed().toList()Box primitivesCan't directly do Arrays.asList(int[]).
List<Integer> โ†’ int[]list.stream().mapToInt(x -> x).toArray()Unbox to int[]mapToInt unboxes.
List โ†’ Setnew HashSet<>(list)Dedupe + lookup O(1)Loses order. Use LinkedHashSet to preserve.
Map โ†’ List of entries NEWnew ArrayList<>(map.entrySet())Snapshot entriesFor sorting/streaming map data.

06Map & HashMap Methods

HashMap allows one null key + null values. ConcurrentHashMap forbids both. get()==null is ambiguous โ€” use containsKey() or getOrDefault().

MethodSyntaxDescriptionNotes
put()map.put("k", "v")Insert or updateReturns PREVIOUS value (or null).
get()map.get("k")Lookupnull if absent OR value is null.
getOrDefault()map.getOrDefault("k", 0)Lookup with fallbackDoesn't insert default.
remove()map.remove("k")Remove mappingReturns removed value.
remove(k, v) NEWmap.remove("k", expected)Conditional removeRemoves only if value matches.
containsKey()map.containsKey("k")Key present?O(1). Disambiguates null values.
containsValue()map.containsValue("v")Value present?O(n). Avoid in hot paths.
keySet()map.keySet()Set view of keysRemoving affects map.
values()map.values()Collection view of valuesNot a Set โ€” duplicates allowed.
entrySet()map.entrySet()Set of Map.EntryMost efficient iteration of both k+v.
size()map.size()Mapping countint.
isEmpty()map.isEmpty()No entries?size()==0.
clear()map.clear()Remove allIn-place.
putAll()map.putAll(other)Bulk insert/updateOverwrites existing keys.
putIfAbsent()map.putIfAbsent("k", "v")Insert if missingReturns existing value if present.
replace()map.replace("k", "v2")Update if presentDoesn't insert if missing.
replace(k, old, new) NEWmap.replace(k, old, new)CAS-style replaceOnly replaces if current value matches.
replaceAll() NEWmap.replaceAll((k, v) -> v.trim())Transform every valueLike List.replaceAll().
merge()map.merge("k", 1, Integer::sum)Combine or insertCounters / accumulators.
compute()map.compute("k", (k, v) -> v + 1)Recompute valuev may be null. Return null to remove.
computeIfAbsent()map.computeIfAbsent("k", k -> new ArrayList<>())Lazy init patternCommon for "map of lists".
computeIfPresent()map.computeIfPresent("k", (k, v) -> v + 1)Update if presentSkips missing keys.
forEach()map.forEach((k, v) -> โ€ฆ)BiConsumer iterationCleaner than entrySet loop.
Map.of()Map.of("a", 1, "b", 2)Immutable map (9+)Up to 10 pairs. No nulls.
Map.ofEntries() NEWMap.ofEntries(Map.entry("a", 1), โ€ฆ)Immutable, >10 entriesNo size limit.
Map.entry() NEWMap.entry("k", "v")Immutable Map.EntryFor ofEntries / collectors.
Map.copyOf()Map.copyOf(map)Immutable snapshot (10+)Defensive copy.
Map.Entry.comparingByKey() NEWMap.Entry.comparingByKey()Sort entries by keyUse with stream sorting.
Map.Entry.comparingByValue() NEWMap.Entry.comparingByValue()Sort entries by valuePair with reversed() for descending.

07Set, HashSet & TreeSet Methods

HashSet O(1), no order. LinkedHashSet preserves insertion order. TreeSet sorted, O(log n) โ€” implements NavigableSet.

MethodSyntaxDescriptionNotes
add()set.add("x")Add unique elementReturns false if duplicate.
addAll()set.addAll(coll)UnionReturns true if anything added.
remove()set.remove("x")Remove elementReturns boolean.
removeAll()set.removeAll(other)Set differenceA โˆ’ B.
retainAll()set.retainAll(other)Set intersectionKeep only A โˆฉ B.
contains()set.contains("x")MembershipO(1) HashSet vs O(n) List.
containsAll()set.containsAll(other)Subset checkA โЇ B?
size() / isEmpty() / clear()set.size()Standard collection opsAs elsewhere.
iterator()set.iterator()Iterate elementsOrder: HashSet undefined, LHS insertion, TreeSet sorted.
stream()set.stream()Stream of elementsSequential.
Set.of()Set.of(1, 2, 3)Immutable set (Java 9+)Duplicates throw IAE.
Set.copyOf() NEWSet.copyOf(set)Immutable snapshot (10+)Defensive copy.
first() [TreeSet]treeSet.first()Smallest elementNoSuchElement if empty.
last() [TreeSet]treeSet.last()Largest elementNoSuchElement if empty.
headSet() [TreeSet]treeSet.headSet("m")Strictly less than (view)Bidirectional propagation.
tailSet() [TreeSet]treeSet.tailSet("m")โ‰ฅ given value (view)Inclusive of "m".
subSet() [TreeSet] NEWtreeSet.subSet("a", "m")[from, to) range viewHalf-open range.
floor() [TreeSet] NEWtreeSet.floor("m")Greatest โ‰ค givennull if none.
ceiling() [TreeSet] NEWtreeSet.ceiling("m")Least โ‰ฅ givennull if none.
lower() [TreeSet] NEWtreeSet.lower("m")Greatest < givenStrict.
higher() [TreeSet] NEWtreeSet.higher("m")Least > givenStrict.
pollFirst() [TreeSet] NEWtreeSet.pollFirst()Remove and return smallestnull if empty.
pollLast() [TreeSet] NEWtreeSet.pollLast()Remove and return largestnull if empty.
descendingSet() [TreeSet] NEWtreeSet.descendingSet()Reverse-order viewIteration is largest-first.

08Queue & Deque Methods

Prefer offer/poll/peek (return null/false) over add/remove/element (throw). Use ArrayDeque instead of legacy Stack.

MethodSyntaxDescriptionNotes
offer()queue.offer("x")Insert at tailReturns false on capacity fail.
add()queue.add("x")Insert (throws)IllegalStateException if full.
poll()queue.poll()Remove + return headnull if empty โ€” preferred.
remove()queue.remove()Remove head (throws)NoSuchElement if empty.
peek()queue.peek()View head without removingnull if empty.
element()queue.element()View head (throws)NoSuchElement if empty.
offerFirst() [Deque]deque.offerFirst("x")Insert at frontStack push semantics.
offerLast() [Deque]deque.offerLast("x")Insert at endSame as offer() on a queue.
pollFirst() [Deque]deque.pollFirst()Remove from frontnull if empty.
pollLast() [Deque]deque.pollLast()Remove from endnull if empty.
peekFirst() [Deque]deque.peekFirst()View frontnull if empty.
peekLast() [Deque]deque.peekLast()View endnull if empty.
push() [Deque]deque.push("x")Stack push (= addFirst)Use ArrayDeque as a Stack.
pop() [Deque]deque.pop()Stack pop (= removeFirst)NoSuchElement if empty.
addFirst() / addLast() NEWdeque.addFirst(x)Insert (throws on capacity)Throwing variants of offerFirst/Last.
removeFirst() / removeLast() NEWdeque.removeFirst()Remove (throws)Use poll-variants if empty is OK.
getFirst() / getLast() NEWdeque.getFirst()View ends (throws)peek-variants are safer.
descendingIterator() NEWdeque.descendingIterator()End-to-front iterationUseful for stack traversal.
size() / isEmpty() / contains()queue.size()Standard opscontains() is O(n).

09Stack Methods (java.util.Stack)

Legacy class โ€” synchronizes unnecessarily. Prefer ArrayDeque for new code.

MethodSyntaxDescriptionNotes
push()stack.push("x")Push to topReturns the pushed element.
pop()stack.pop()Remove topEmptyStackException if empty.
peek()stack.peek()View topEmptyStackException if empty.
empty()stack.empty()Empty checkQuirk: empty() not isEmpty(). Inherits both.
search()stack.search("x")1-based distance from top-1 if not found. O(n).

10Collections Utility Methods

All static. sort/reverse/shuffle mutate in-place; unmodifiable* return read-only VIEWS.

MethodSyntaxDescriptionNotes
sort()Collections.sort(list)Natural order in-placeStable.
sort(Comp)Collections.sort(list, comp)Custom ComparatorPrefer list.sort(comp).
reverse()Collections.reverse(list)Flip order in-placeDoesn't sort.
shuffle()Collections.shuffle(list)Random in-placePass Random for reproducibility.
min() / max()Collections.min(list)Smallest / largestNoSuchElement if empty.
frequency()Collections.frequency(list, x)Count occurrencesO(n).
fill()Collections.fill(list, "X")Fill with valueSame reference for all positions.
copy()Collections.copy(dest, src)Copy src into destdest.size() must be โ‰ฅ src.size().
swap()Collections.swap(list, i, j)Swap two indicesIn-place.
binarySearch()Collections.binarySearch(list, key)Search sorted listList MUST be sorted.
disjoint()Collections.disjoint(c1, c2)No common elements?Returns boolean.
addAll()Collections.addAll(list, a, b, c)Varargs addCleaner than multiple add().
nCopies()Collections.nCopies(5, "X")Immutable list of n copiesSame reference reused.
singleton()Collections.singleton("x")Immutable 1-element SetNo mutation.
singletonList()Collections.singletonList("x")Immutable 1-element ListMore efficient than ArrayList.
emptyList() / emptySet() / emptyMap()Collections.emptyList()Shared empty constantsSame singleton each call.
unmodifiableList()Collections.unmodifiableList(list)Read-only VIEWOriginal mutations show through. Use List.copyOf() for true copy.
unmodifiableMap() / unmodifiableSet() NEWCollections.unmodifiableMap(m)Read-only VIEWSame caveats as List.
synchronizedList()Collections.synchronizedList(list)Thread-safe wrapperIteration still needs explicit sync. Consider CopyOnWriteArrayList.
reverseOrder()Collections.reverseOrder()Descending ComparatorFor natural-order types.
rotate()Collections.rotate(list, 2)Rotate elements+ right, โˆ’ left.

11Math Methods (java.lang.Math)

All static. PI/E are constant FIELDS (no parens). Most methods return double.

MethodSyntaxDescriptionNotes
abs()Math.abs(-5)Absolute valueโš ๏ธ Math.abs(Integer.MIN_VALUE) overflows.
max() / min()Math.max(3, 7)Larger / smaller of twoTwo-arg only โ€” chain for more.
pow()Math.pow(2, 8)Base ^ expFor 2^n use 1L << n โ€” much faster.
sqrt() / cbrt()Math.sqrt(16)Square / cube rootsqrt(-1) = NaN. cbrt handles negatives.
ceil() / floor()Math.ceil(4.2)Round up / down (returns double)Cast to int if needed. floor is toward โˆ’โˆž.
round()Math.round(4.5)Half-up roundReturns long for double, int for float.
random()Math.random()Pseudo-random [0, 1)For repeatability use java.util.Random.
log() / log10() / exp()Math.log(Math.E)ln / logโ‚โ‚€ / e^xlog(0) = โˆ’โˆž, log(neg) = NaN.
sin() / cos() / tan()Math.sin(Math.PI/2)Trig in radiansUse toRadians() first.
PI / EMath.PIConstants (FIELDS)No parentheses.
signum()Math.signum(-5.0)โˆ’1.0 / 0.0 / 1.0Direction normalization.
hypot()Math.hypot(3, 4)โˆš(xยฒ + yยฒ) without overflowMore accurate than manual sqrt.
toRadians() / toDegrees()Math.toRadians(180)Angle conversion180ยฐ = ฯ€ rad.
floorDiv() / floorMod()Math.floorDiv(7, 2)Floor-rounded div / mod-7 % 2 = -1 but floorMod(-7, 2) = 1.
addExact() / multiplyExact()Math.addExact(a, b)Throws on overflowUse when correctness matters.
subtractExact() NEWMath.subtractExact(a, b)Overflow-checked subtractThrows ArithmeticException.
negateExact() / decrementExact() / incrementExact() NEWMath.negateExact(x)Overflow-checked unary opsCatches MIN_VALUE pitfall.
divideExact() NEWMath.divideExact(a, b)Overflow-checked div (Java 18+)Catches MIN_VALUE / -1.
toIntExact() NEWMath.toIntExact(longValue)Long โ†’ int with checkThrows if doesn't fit.
log1p() โ˜…Math.log1p(x)ln(1 + x), accurate for small xAvoids precision loss vs log(1+x).
expm1() โ˜…Math.expm1(x)e^x โˆ’ 1, accurate for small xPairs with log1p().
fma() NEWMath.fma(a, b, c)Fused multiply-add (Java 9+)a*b+c with one rounding โ€” better precision.
copySign() NEWMath.copySign(magnitude, sign)Apply sign of one to anotherNumeric utility.
nextUp() / nextDown() NEWMath.nextUp(x)Next representable doubleFloating-point neighbor.
ulp() NEWMath.ulp(x)Unit in last placeTolerance for fp comparisons.
clamp() NEWMath.clamp(v, lo, hi)Bound between min/max (Java 21+)Replaces Math.max(lo, Math.min(hi, v)).

12Integer & Wrapper Methods

Wrapper classes bridge primitives and objects. Use Double.isNaN() not == Double.NaN (NaN โ‰  NaN).

MethodSyntaxDescriptionNotes
parseInt()Integer.parseInt("42")String โ†’ intNFE on bad input. Radix overload.
valueOf()Integer.valueOf("42")String/int โ†’ IntegerCaches [-128, 127] โ€” affects ==.
toString()Integer.toString(42)int โ†’ String (static)Radix overload available.
toBinaryString() / toHexString() / toOctalString()Integer.toHexString(255)int โ†’ string in baseNo prefix. For negatives: 2's complement.
MAX_VALUE / MIN_VALUEInteger.MAX_VALUEInt bounds (FIELDS)+1 wraps to MIN.
compare()Integer.compare(a, b)Safe lexicographic compareAvoid a-b (overflow).
sum() / max() / min()Integer.sum(3, 4)Method-reference helpersUseful with reduce / Collectors.
bitCount()Integer.bitCount(7)Population count of 1-bitsUseful for bitmask problems.
numberOfLeadingZeros() NEWInteger.numberOfLeadingZeros(n)Leading 0-bitsUseful for logโ‚‚ / size class calc.
numberOfTrailingZeros() NEWInteger.numberOfTrailingZeros(n)Trailing 0-bitsPosition of lowest set bit.
highestOneBit() / lowestOneBit() NEWInteger.highestOneBit(n)Isolate hi/lo set bitReturns power of two.
reverse() / reverseBytes() NEWInteger.reverse(n)Reverse bits / byte orderUseful in encoding/IO.
signum() NEWInteger.signum(n)โˆ’1 / 0 / 1Branchless sign.
parseUnsignedInt() / toUnsignedLong() NEWInteger.parseUnsignedInt("4294967295")Unsigned arithmetic helpersJava 8+ unsigned operations.
Double.parseDouble()Double.parseDouble("3.14")String โ†’ doubleAccepts NaN, Infinity strings.
Double.isNaN()Double.isNaN(x)NaN checkDon't use ==. NaN != NaN.
Double.isInfinite() / isFinite() NEWDouble.isFinite(x)ยฑโˆž / finite checkisFinite is Java 8+.
Boolean.parseBoolean()Boolean.parseBoolean("true")String โ†’ booleanOnly "true" (case-insens) โ†’ true.
Character.isLetter() / isDigit() / isLetterOrDigit() / isWhitespace()Character.isDigit('5')Char predicatesUnicode-aware.
Character.toUpperCase() / toLowerCase()Character.toUpperCase('a')Char case conversionFor Strings use String methods.
Character.getNumericValue()Character.getNumericValue('A')Numeric value (e.g. 'A' โ†’ 10)Useful for radix conversions.
Character.isAlphabetic() NEWCharacter.isAlphabetic(cp)Code-point alphabetic checkBroader than isLetter.

13Stream API Methods

Lazy: intermediate ops don't execute until a terminal op runs. A stream can only be consumed ONCE.

MethodSyntaxDescriptionNotes
filter()stream.filter(x -> x > 0)Keep matching elementsIntermediate.
map()stream.map(x -> x * 2)1:1 transformIntermediate.
mapToInt() / mapToLong() / mapToDouble()stream.mapToInt(String::length)To primitive streamAvoids boxing; enables sum() etc.
mapToObj() NEWintStream.mapToObj(Integer::toString)Primitive โ†’ object streamInverse of mapToInt.
boxed() NEWintStream.boxed()Box to Stream<Integer>Cleaner than mapToObj for plain boxing.
flatMap()stream.flatMap(Collection::stream)1:N โ†’ flattenIntermediate.
distinct()stream.distinct()Dedupe via equals/hashIntermediate. May be heavy.
sorted()stream.sorted()Natural / Comparator sortBuffers all elements.
limit() / skip()stream.limit(5)Truncate / drop prefixlimit short-circuits โ€” fine for infinite streams.
takeWhile() / dropWhile() NEWstream.takeWhile(x -> x < 10)Conditional prefix (Java 9+)Order-sensitive.
peek()stream.peek(System.out::println)Side-effect on each (debug)โš ๏ธ Don't rely on it in production.
collect()stream.collect(Collectors.toList())Reduce into containerTerminal.
toList() โ˜…stream.toList()Unmodifiable list (Java 16+)For mutable use Collectors.toList().
forEach()stream.forEach(System.out::println)Action per elementOrder undefined in parallel.
reduce()stream.reduce(0, Integer::sum)Fold to single valueIdentity arg โ†’ no Optional.
count()stream.count()Element countTerminal. Returns long.
findFirst() / findAny()stream.findFirst()Optional first / anyShort-circuit.
anyMatch() / allMatch() / noneMatch()stream.anyMatch(x -> x > 0)Quantifier predicatesShort-circuit.
min() / max()stream.min(Comparator.naturalOrder())Optional min / maxEmpty stream โ†’ empty Optional.
Stream.of()Stream.of(1, 2, 3)Stream from valuesFor arrays use Arrays.stream().
Stream.empty() / generate() / iterate() NEWStream.iterate(1, x -> x*2)Empty/infinite streamsCombine with limit().
Stream.concat() NEWStream.concat(s1, s2)Lazy concatenationUse flatMap for many streams.
IntStream.range() / rangeClosed()IntStream.range(0, 10)[from, to) / [from, to]Useful for index loops.
Collectors.toList() / toSet().collect(Collectors.toSet())Standard collectorsMutable result.
Collectors.toMap() NEW.collect(Collectors.toMap(k, v))Build a MapThrows on duplicate keys โ€” pass merge fn.
Collectors.groupingBy() โ˜….collect(Collectors.groupingBy(fn))Map<K, List<V>>Downstream collector overload available.
Collectors.partitioningBy() NEW.collect(Collectors.partitioningBy(p))Map<Boolean, List<V>>Two-bucket variant of groupingBy.
Collectors.counting() NEWgroupingBy(fn, Collectors.counting())Count per groupReturns Map<K, Long>.
Collectors.joining() โ˜….collect(Collectors.joining(", "))Concat stringsOverloads: joining(), (delim), (delim, prefix, suffix).
Collectors.summarizingInt() NEW.collect(Collectors.summarizingInt(fn))min/max/avg/sum/count at onceReturns IntSummaryStatistics.
Collectors.mapping() NEWgroupingBy(k, mapping(v, toList()))Adapt elements before downstreamCommon with groupingBy.
Collectors.reducing() NEW.collect(Collectors.reducing(0, Integer::sum))Fold collectorUse as a downstream collector too.
Stream.mapMulti() NEWstream.mapMulti((x, c) -> โ€ฆ)Push 0..N items (Java 16+)Often faster than flatMap for short fan-out.

14Optional Methods

A holder that may be empty. Don't call get() without checking โ€” use map/orElse/ifPresent.

MethodSyntaxDescriptionNotes
Optional.of()Optional.of(value)Non-null requiredNPE if null.
Optional.ofNullable()Optional.ofNullable(value)Null-safe wrapEmpty if null.
Optional.empty()Optional.empty()The empty OptionalSame singleton.
isPresent() / isEmpty()opt.isPresent()Presence checkisEmpty() is Java 11+.
get()opt.get()Unwrap (throws if empty)โš ๏ธ Defeats the point โ€” prefer orElse.
orElse()opt.orElse("default")Value or fallbackDefault ALWAYS evaluated.
orElseGet()opt.orElseGet(() -> compute())Value or lazy supplierUse for expensive defaults.
orElseThrow()opt.orElseThrow()Value or throwOverload for custom exception.
ifPresent()opt.ifPresent(System.out::println)Conditional actionCleaner than isPresent + get.
ifPresentOrElse() NEWopt.ifPresentOrElse(action, emptyAction)Two-branch action (Java 9+)Replaces if/else on isPresent.
map()opt.map(String::toUpperCase)Transform if presentEmpty stays empty.
flatMap()opt.flatMap(this::findUser)Unwrap nested OptionalWhen transform returns Optional.
filter()opt.filter(x -> x > 0)Empty if predicate failsLike Stream.filter for one element.
or() NEWopt.or(() -> otherOpt)Fallback Optional (Java 9+)Chain alternative sources.
stream() NEWopt.stream()0/1-element Stream (Java 9+)Useful in flatMap pipelines.

15Object & Objects Methods

Every class inherits from Object. Always override equals() and hashCode() together.

MethodSyntaxDescriptionNotes
toString()obj.toString()String representationDefault Class@hex. Override.
equals()obj.equals(other)Logical equalityDefault = reference equality.
hashCode()obj.hashCode()Hash for bucketsMust be consistent with equals().
getClass()obj.getClass()Runtime classOften instanceof is better.
clone()obj.clone()Shallow copyClass must implement Cloneable.
notify() / notifyAll() / wait()obj.wait()Intrinsic monitor signalingMust hold monitor. Use j.u.c.Condition for new code.
Objects.equals()Objects.equals(a, b)Null-safe equalityNo NPE if a is null.
Objects.hash()Objects.hash(a, b, c)Combine fieldsFor hashCode() overrides.
Objects.requireNonNull()Objects.requireNonNull(arg, "arg")Validate non-nullThrows NPE with message.
Objects.requireNonNullElse() NEWObjects.requireNonNullElse(x, def)Non-null or default (Java 9+)Like Optional.orElse.
Objects.requireNonNullElseGet() NEWrequireNonNullElseGet(x, ()->def)Lazy default (Java 9+)Like Optional.orElseGet.
Objects.isNull() / nonNull()Objects.nonNull(obj)Predicate referencesfilter(Objects::nonNull).
Objects.toString() NEWObjects.toString(obj, "?")Null-safe toStringReturns default if null.
Objects.compare() NEWObjects.compare(a, b, comp)Null-safe compareBoth null โ†’ 0.
Objects.checkIndex() NEWObjects.checkIndex(i, length)Bounds check (Java 9+)Throws IOOB if invalid.

16Comparable & Comparator

Comparable = natural order in the class. Comparator = external strategy. Chain with thenComparing().

MethodSyntaxDescriptionNotes
compareTo()a.compareTo(b)Natural order <0 / 0 / >0Used by sort and TreeSet.
Comparator.naturalOrder()Comparator.naturalOrder()Ascending naturalEquivalent to passing null to sort.
Comparator.reverseOrder()Comparator.reverseOrder()Descending naturalQuick negation.
Comparator.comparing()Comparator.comparing(Person::getName)By extracted keyMost common factory.
Comparator.comparingInt() / comparingLong() / comparingDouble() NEWComparator.comparingInt(String::length)Primitive-keyed compareNo boxing overhead.
thenComparing()comp.thenComparing(Person::getAge)Secondary keyChain N levels of tie-break.
thenComparingInt() NEWcomp.thenComparingInt(Person::getAge)Primitive secondaryAvoids boxing.
reversed()comp.reversed()Negate the comparatorPairs with comparing().
nullsFirst() / nullsLast()Comparator.nullsLast(naturalOrder())Null-handling wrapperWithout it, nulls cause NPE during sort.