This Java methods reference summarizes common operations on String, Math, ArrayList, HashMap, and Collections. A method name alone is not enough: note its return value, whether it changes an object, and its input assumptions. The worked examples combine related calls so you can see why a method is selected. All examples use Java 17 and keep their displayed output deterministic.
String methods return values without editing the string
| Method | Purpose and important contract |
|---|---|
| length() | Returns the number of UTF-16 code units |
| charAt(index) | Reads one code unit; index must be valid |
| substring(start, end) | Returns a slice with an exclusive end |
| contains(text) | Tests whether a character sequence appears |
| replace(old, new) | Returns text with literal replacements |
| strip() | Returns text without leading or trailing recognized whitespace |
| equals(other) | Compares string content |
Strings are immutable, so save the returned replacement or stripped value when needed. length is not universally a count of user-perceived characters. Use the dedicated string reference for more examples and the String API for overload details.
Math methods describe numeric operations
| Method | Result or caution |
|---|---|
| min(a, b), max(a, b) | Select an operand under the relevant overload |
| abs(value) | Absolute value; minimum integer values need overflow care |
| ceil(value) | Returns a double rounded upward |
| floor(value) | Returns a double rounded downward |
| round(double) | Returns the nearest long under its documented rule |
| sqrt(value), pow(base, exponent) | Return double results |
Choose numeric types before interpreting a result. Casting a rounded double is not the same operation as selecting Math.round, and floating-point results may require tolerance in tests. Math.abs(Integer.MIN_VALUE) remains negative because the positive counterpart cannot fit in int.
ArrayList methods separate queries from mutations
| Method | Purpose and contract |
|---|---|
| add(value) | Appends an element |
| get(index) | Reads an element at a valid position |
| set(index, value) | Replaces and returns the previous element |
| remove(index) | Removes by position and returns that element |
| remove(Object) | Removes a matching value and returns success |
| size(), contains(value) | Report count or equality-based presence |
The remove overload is especially important for lists of Integer. remove(2) selects the index form, while remove(Integer.valueOf(2)) removes a matching value. Adding or removing during an ordinary enhanced for loop can invalidate its iterator; use an appropriate supported operation.
HashMap methods express key-based behavior
| Method | Purpose and contract |
|---|---|
| put(key, value) | Stores a mapping and returns its previous value |
| get(key) | Returns its value or null for absence |
| containsKey(key) | Reports key presence independently of a null value |
| getOrDefault(key, fallback) | Supplies fallback for an absent key |
| merge(key, value, function) | Combines an incoming value with an existing mapping |
| remove(key), size() | Remove a mapping or report entry count |
HashMap allows null values, so get alone can be ambiguous. getOrDefault does not replace an explicitly mapped null. Ordinary HashMap merge is not a concurrency guarantee; use the right map and documented atomic operation for shared updates.
Collections utilities operate on suitable collections
| Method | Purpose and requirement |
|---|---|
| sort(list) | Orders a modifiable list by natural ordering |
| reverse(list) | Reverses a list in place |
| min(collection), max(collection) | Find extremes; empty input is invalid |
| frequency(collection, value) | Counts equal occurrences |
| binarySearch(list, key) | Searches a compatibly sorted list |
| unmodifiableList(list) | Returns a restricted view, not an independent copy |
The utility class is Collections with a plural name, while Collection is an interface. A restricted view can still reflect changes made through its backing collection. Use List.copyOf when an unmodifiable snapshot of element references is the intended contract.
Follow the receiver, result, and mutation boundary
Before using an unfamiliar call, ask which object receives it, what arguments it accepts, what it returns, and whether the receiver changes. String.replace returns another string, ArrayList.set changes an existing list, and Collections.reverse changes the list passed as an argument. Similar-looking expressions can therefore have different effects. Read overloads and failure conditions in the API rather than assuming all methods return a fresh collection or safely accept invalid indices.
Practice tasks and checks
For each table, choose one query and one operation returning or modifying data. Write the receiver type, argument type, and result before running a small test. Compare String.replace with ArrayList.set to explain their different mutation behavior. Test both remove overloads using a list whose values differ from their positions. Add a mapped null to HashMap and compare get, containsKey, and getOrDefault for that key and an absent key. Finally, wrap a mutable list with Collections.unmodifiableList, edit the backing list, and observe the view. Then compare List.copyOf so you can explain the distinction between a restricted view and a separate snapshot of references.
Java Summary
- Read return values, overloads, and mutation rules together.
- A restricted collection view is different from an independent snapshot.
- Validate indices, absence, and sorted-input preconditions.
- Continue with the focused String reference when these examples are clear.
Java Examples
Each example shows the code, the output it produces and what each part does.
Transform text using returned strings
Save this program as TextMethodsReference.java. Compile it with javac TextMethodsReference.java and run it with java TextMethodsReference.
Expected output:
strip removes the outer spaces and replace changes the literal East sequence in its returned string. The chained result is saved in cleaned. substring takes indices zero through three because its end four is exclusive. The original source remains spaced and says East, so equals returns false. No statement edits the contents of source; the variable still refers to the original immutable string.
public class TextMethodsReference {
public static void main(String[] args) {
String source = " East gate ";
String cleaned = source.strip().replace("East", "West");
System.out.println(cleaned);
System.out.println(cleaned.substring(0, 4));
System.out.println(source.equals(cleaned));
}
}West gate
West
falseDistinguish removing a value from removing an index
Save this program as ListMethodsReference.java. Compile it with javac ListMethodsReference.java and run it with java ListMethodsReference.
Expected output:
The Object overload removes the first equal two and reports true, leaving nine, two, five. The index overload then removes the element at index one, which is the remaining two, and returns that element. The final list is nine, five. Choosing an overload is part of the operation's meaning, so explicit Integer.valueOf is helpful when a value happens to resemble an intended position.
import java.util.ArrayList;
import java.util.List;
public class ListMethodsReference {
public static void main(String[] args) {
ArrayList<Integer> values = new ArrayList<>(List.of(2, 9, 2, 5));
System.out.println(values.remove(Integer.valueOf(2)));
System.out.println(values.remove(1));
System.out.println(values);
}
}true
2
[9, 5]Combine map accumulation with ordered utilities
Save this program as CollectionMethodsReference.java. Compile it with javac CollectionMethodsReference.java and run it with java CollectionMethodsReference.
Expected output:
merge accumulates two map occurrences and one pen occurrence. keySet is copied into a modifiable ArrayList so sorting can produce deterministic key order without relying on HashMap iteration. getOrDefault retrieves the stored map count, and Math.max selects the larger of the two present counts. A missing key passed through get and unboxed for Math.max would need an absence policy first.
import java.util.*;
public class CollectionMethodsReference {
public static void main(String[] args) {
Map<String, Integer> counts = new HashMap<>();
for (String label : List.of("map", "pen", "map")) counts.merge(label, 1, Integer::sum);
List<String> keys = new ArrayList<>(counts.keySet());
Collections.sort(keys);
System.out.println(keys);
System.out.println(counts.getOrDefault("map", 0));
System.out.println(Math.max(counts.get("map"), counts.get("pen")));
}
}[map, pen]
2
2Java FAQ
Is Collections the same as Collection?
No. Collection is an interface describing a group of elements. Collections is a utility class with static operations such as sort and frequency. The plural spelling matters when reading imports and method calls.
Does unmodifiableList make a deep copy?
No. It returns a restricted view of the supplied list. Changes through the backing list may remain visible, and mutable element objects are not deeply cloned.
How do I find out what an unfamiliar method does?
Read its Javadoc: in an IDE, hover over the method or press the documentation shortcut, or look it up in the official Java SE API documentation. Check the parameters, return value, exceptions and whether it changes the object. A quick experiment in jshell confirms the behaviour.
What does a return value of -1 usually mean?
Search methods such as indexOf, lastIndexOf and List.indexOf return -1 when nothing is found, because -1 can never be a valid index. Always check for it before using the result as a position, or substring and get will throw.
Why does Math.round return a long?
Math.round(double) returns a long, because a rounded double can be far larger than an int can hold. Math.round(float) returns an int. Cast the result, (int) Math.round(x), when you know the value fits.
Java Exercises
Answer each one and check it instantly. If you get stuck, open the hint before the answer.
What is the end convention of substring(start, end)?
How do you remove integer value two from ArrayList<Integer>?
Java Quiz
2 questions to check what you learned.
Which method distinguishes a missing HashMap key from a stored null?
- containsKey
- get alone
- size alone
What must be true before Collections.binarySearch?
- The list is sorted under the matching ordering
- The list has no duplicates
- The list is unmodifiable