Simple, practical, book-style explanation of the remaining major java.util utilities.
StringTokenizer divides a string into tokens. A token is a discrete piece of text. It implements the legacy Enumeration interface.
| Method | Purpose |
|---|---|
| hasMoreTokens() | Checks whether another token exists. |
| nextToken() | Returns the next token. |
| countTokens() | Returns the number of remaining tokens. |
BitSet represents a collection of bits. Individual bits can be set, cleared, tested, or combined with another BitSet.
| Method | Purpose |
|---|---|
| set(int) | Sets a bit. |
| clear(int) | Clears a bit. |
| get(int) | Tests a bit. |
| flip(int) | Changes a bit's state. |
| and(BitSet) | Bitwise AND. |
| or(BitSet) | Bitwise OR. |
| xor(BitSet) | Bitwise XOR. |
| cardinality() | Number of set bits. |
Beginning with JDK 8, these classes represent a value that may or may not be present. They provide an explicit alternative to using null to represent absence.
| Method | Purpose |
|---|---|
| of(value) | Creates Optional containing a non-null value. |
| ofNullable(value) | Creates Optional containing value or empty for null. |
| empty() | Creates an empty Optional. |
| isPresent() | Tests whether a value exists. |
| isEmpty() | Tests whether no value exists. |
| get() | Returns the contained value when present. |
| orElse(value) | Returns value or a default. |
| orElseGet(Supplier) | Computes a default when empty. |
| orElseThrow() | Throws when empty. |
| ifPresent(Consumer) | Runs an action when present. |
| filter(Predicate) | Keeps the value only when a condition is true. |
| map(Function) | Transforms the contained value. |
| flatMap(Function) | Transforms using a function returning Optional. |
| or(Supplier) | Supplies another Optional when empty. |
The primitive-specialized classes avoid using a normal reference Optional for an optional primitive value.
Value access methods are getAsInt(), getAsLong(), and getAsDouble().
Date encapsulates date and time information. The chapter explains that many old Java 1.0 Date methods were moved to Calendar/date-formatting APIs and deprecated.
| Method | Purpose |
|---|---|
| after(Date) | Checks whether this date is later. |
| before(Date) | Checks whether this date is earlier. |
| compareTo(Date) | Compares two Date values. |
| getTime() | Returns milliseconds since January 1, 1970. |
| setTime(long) | Sets the date from milliseconds. |
| toInstant() | Converts to Instant. |
| toString() | Returns a string representation. |
Calendar is an abstract class that exposes date/time components such as year, month, day, hour, minute, and second.
| Method | Purpose |
|---|---|
| getInstance() | Creates Calendar for default locale/time zone. |
| get(int) | Gets a calendar field. |
| set(int,int) | Sets a calendar field. |
| add(int,int) | Adds or subtracts a field value. |
| before(Object) | Tests whether the date is earlier. |
| after(Object) | Tests whether the date is later. |
| getTime() | Returns an equivalent Date. |
| getTimeZone() | Returns the Calendar time zone. |
| clear() | Clears time fields. |
GregorianCalendar is a concrete Calendar implementation using Gregorian calendar rules.
isLeapYear(int) checks whether a year is a leap year. The chapter also describes conversion methods that connect this traditional API with java.time.
TimeZone represents time-zone information and can be used by Calendar.
| Method | Purpose |
|---|---|
| getDefault() | Gets the default time zone. |
| getTimeZone(String) | Gets a zone by ID. |
| getID() | Returns the zone ID. |
| getAvailableIDs() | Returns available zone IDs. |
| getRawOffset() | Returns the raw offset. |
Random generates pseudorandom values.
| Method | Purpose |
|---|---|
| nextInt() | Pseudorandom int. |
| nextInt(bound) | Int from 0 inclusive to bound exclusive. |
| nextLong() | Pseudorandom long. |
| nextDouble() | Double from 0.0 inclusive to 1.0 exclusive. |
| nextFloat() | Pseudorandom float. |
| nextBoolean() | Pseudorandom boolean. |
| nextBytes(byte[]) | Fills an array with pseudorandom bytes. |
JDK 8 also added doubles(), ints(), and longs() for streams of pseudorandom values.
Timer schedules a task. TimerTask contains the code that executes. TimerTask implements Runnable, so its run() method contains the task logic.
| Operation | Purpose |
|---|---|
| schedule(task, delay) | Runs after a delay. |
| schedule(task, date) | Runs at a specified date. |
| schedule(task, delay, period) | Repeats at a period. |
| scheduleAtFixedRate(...) | Repeating fixed-rate scheduling. |
| cancel() | Stops timer scheduling. |
Currency encapsulates currency information. It uses factory methods rather than public constructors.
| Method | Purpose |
|---|---|
| getInstance(Locale) | Gets currency for a locale. |
| getInstance(String) | Gets currency by code. |
| getCurrencyCode() | ISO 4217 currency code. |
| getSymbol() | Currency symbol. |
| getDisplayName() | Display name. |
| getDefaultFractionDigits() | Normal fractional digits. |
Formatter creates formatted output using format specifiers.
| Specifier | Meaning |
|---|---|
| %c | Character |
| %s | String |
| %d | Decimal integer |
| %f | Floating point |
| %e | Scientific notation |
| %g | General floating format |
| %o | Octal |
| %x | Hexadecimal |
| %a | Hexadecimal floating point |
| %n | Newline |
| %% | Percent sign |
A width such as %12f gives a minimum field width. A leading zero such as %012f requests zero padding. Precision such as %.2f controls decimal places for floating-point output.
The %t conversion uses suffixes for particular date/time components. Relative indexing such as %<tB can reuse the previous argument.
The chapter explains that printf() is a convenient console-oriented alternative to directly creating a Formatter. It uses Formatter-style formatting.
Scanner is the complement of Formatter. It reads formatted input and converts it into values. It can read from console input, files, strings, and other supported sources.
| Method | Purpose |
|---|---|
| hasNext() | Checks for another token. |
| next() | Reads the next token. |
| nextLine() | Reads a complete line. |
| hasNextInt() | Checks for an integer token. |
| nextInt() | Reads an int. |
| hasNextDouble() | Checks for a double token. |
| nextDouble() | Reads a double. |
| useDelimiter() | Changes the token delimiter. |
Locale represents language/cultural or regional settings and is used by utilities such as Calendar, Currency, Formatter, and ResourceBundle.
ResourceBundle supports localization by keeping resources such as user-visible strings separate from application logic.
| Method | Purpose |
|---|---|
| getBundle(name) | Loads a bundle. |
| getBundle(name, locale) | Loads a locale-specific bundle. |
| getString(key) | Gets a String resource. |
| getObject(key) | Gets an Object resource. |
| getStringArray(key) | Gets a String array. |
| getKeys() | Returns resource keys. |
| getLocale() | Returns the bundle locale. |
StringJoiner joins character sequences using a delimiter and can also add a prefix and suffix.
Important methods include add(), merge(), setEmptyValue(), length(), and toString().
UUID encapsulates and manages Universally Unique Identifiers.
Base64 supports Base64 encoding and decoding. It provides nested Encoder and Decoder classes.
IntSummaryStatistics and DoubleSummaryStatistics collect statistics such as count, sum, minimum, maximum, and average.
The java.util.function package defines predefined functional interfaces used heavily with lambda expressions and method references.
| Interface | Simple meaning |
|---|---|
| Consumer<T> | Accepts a value and performs an action. |
| Supplier<T> | Supplies a value. |
| Function<T,R> | Accepts a value and returns a result. |
| Predicate<T> | Tests a condition and returns boolean. |
| BiConsumer<T,U> | Consumes two values. |
| BiFunction<T,U,R> | Accepts two values and returns a result. |
| BiPredicate<T,U> | Tests two values. |
| UnaryOperator<T> | Input and result have the same type. |
| BinaryOperator<T> | Two same-type inputs produce the same type. |
| Class | Purpose |
|---|---|
| Objects | Utility methods that operate on objects. |
| HexFormat | Conversions to and from hexadecimal representation. |
| ServiceLoader | Finding service providers. |
| PropertyPermission | Property permissions. |
| EventObject | Superclass for event objects. |
| EventListenerProxy | Proxy support for event listeners. |
| FormattableFlags | Formatting flags for Formattable. |
| Subpackage | Purpose |
|---|---|
| java.util.concurrent | Concurrent programming and Fork/Join support. |
| java.util.concurrent.atomic | Atomic operations. |
| java.util.concurrent.locks | Explicit lock mechanisms. |
| java.util.function | Predefined functional interfaces. |
| java.util.jar | Read/write JAR files. |
| java.util.logging | Logging facilities. |
| java.util.prefs | Preferences. |
| java.util.random | Random-number APIs. |
| java.util.regex | Regular expressions. |
| java.util.spi | Service-provider interfaces. |
| java.util.stream | Stream APIs. |
| java.util.zip | Compression and ZIP utilities. |
| Problem | Think of |
|---|---|
| Break text into tokens | StringTokenizer |
| Read formatted input | Scanner |
| Create formatted output | Formatter |
| Represent possibly absent value | Optional |
| Optional primitive value | OptionalInt / Long / Double |
| Work with bits | BitSet |
| Traditional date/time | Date / Calendar |
| Gregorian rules | GregorianCalendar |
| Time-zone information | TimeZone |
| Pseudorandom values | Random |
| Schedule a task | Timer + TimerTask |
| Currency information | Currency |
| Localization | Locale + ResourceBundle |
| Join strings | StringJoiner |
| Unique identifier | UUID |
| Base64 representation | Base64 |