java.util Part 2: More Utility Classes

Simple, practical, book-style explanation of the remaining major java.util utilities.

Chapter idea: The previous chapter focused on the Collections Framework. This one continues java.util with utilities for text parsing, bits, optional values, dates, time zones, random numbers, scheduling, formatting, input, localization, identifiers, and functional interfaces.

1. What This Chapter Covers

Text
StringTokenizer, StringJoiner
Bits
BitSet
Optional values
Optional, OptionalInt, OptionalLong, OptionalDouble
Date & time
Date, Calendar, GregorianCalendar, TimeZone
Random & scheduling
Random, Timer, TimerTask
Formatting & input
Formatter, Scanner
Localization
Locale, Currency, ResourceBundle
Other utilities
Base64, UUID, Objects, HexFormat

2. StringTokenizer

StringTokenizer divides a string into tokens. A token is a discrete piece of text. It implements the legacy Enumeration interface.

String text = "Java is easy"; StringTokenizer st = new StringTokenizer(text); while (st.hasMoreTokens()) { System.out.println(st.nextToken()); }
MethodPurpose
hasMoreTokens()Checks whether another token exists.
nextToken()Returns the next token.
countTokens()Returns the number of remaining tokens.

3. BitSet

BitSet represents a collection of bits. Individual bits can be set, cleared, tested, or combined with another BitSet.

BitSet bits = new BitSet(16); bits.set(2); bits.set(5); System.out.println(bits);
{2, 5}
MethodPurpose
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.

4. Optional, OptionalInt, OptionalLong, OptionalDouble

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.

Optional<T>


   ↙ value present      empty

Creating Optional

Optional<String> a = Optional.of("Ravi"); Optional<String> b = Optional.empty(); Optional<String> c = Optional.ofNullable(null);
MethodPurpose
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.
String value = null; String result = Optional.ofNullable(value) .orElse("Unknown"); System.out.println(result);
Remember: Optional is a value-based class. Its main purpose is to make the possible absence of a value explicit.

5. Optional Primitive Types

The primitive-specialized classes avoid using a normal reference Optional for an optional primitive value.

OptionalInt result = OptionalInt.of(100); if (result.isPresent()) { System.out.println( result.getAsInt() ); }

Value access methods are getAsInt(), getAsLong(), and getAsDouble().

6. Date

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.

Date date = new Date(); System.out.println(date); long millis = date.getTime(); System.out.println(millis);
MethodPurpose
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.

7. Calendar

Calendar is an abstract class that exposes date/time components such as year, month, day, hour, minute, and second.

Calendar calendar = Calendar.getInstance(); int year = calendar.get(Calendar.YEAR); int month = calendar.get(Calendar.MONTH); int day = calendar.get(Calendar.DATE);
MethodPurpose
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.
Important: Calendar's traditional month field is zero-based; January is Calendar.JANUARY.

8. GregorianCalendar

GregorianCalendar is a concrete Calendar implementation using Gregorian calendar rules.

GregorianCalendar cal = new GregorianCalendar(); int year = cal.get(Calendar.YEAR); System.out.println( cal.isLeapYear(year) );

Constructors

GregorianCalendar() GregorianCalendar(year, month, day) GregorianCalendar(year, month, day, hour, minute) GregorianCalendar(year, month, day, hour, minute, second) GregorianCalendar(Locale locale) GregorianCalendar(TimeZone zone) GregorianCalendar(TimeZone zone, Locale locale)

isLeapYear(int) checks whether a year is a leap year. The chapter also describes conversion methods that connect this traditional API with java.time.

9. TimeZone

TimeZone represents time-zone information and can be used by Calendar.

TimeZone zone = TimeZone.getDefault(); System.out.println( zone.getID() );
MethodPurpose
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.

10. Random

Random generates pseudorandom values.

Random random = new Random(); int n = random.nextInt(100); double d = random.nextDouble(); System.out.println(n); System.out.println(d);
Example: nextInt(100) produces an integer from 0 through 99.
MethodPurpose
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.

11. Timer and TimerTask

Timer schedules a task. TimerTask contains the code that executes. TimerTask implements Runnable, so its run() method contains the task logic.

Timer
→ schedules →
TimerTask
run()
class MyTask extends TimerTask { @Override public void run() { System.out.println( "Task executed" ); } } Timer timer = new Timer(); timer.schedule( new MyTask(), 1000 );
OperationPurpose
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.

12. Currency

Currency encapsulates currency information. It uses factory methods rather than public constructors.

Currency c = Currency.getInstance(Locale.US); System.out.println( c.getCurrencyCode() ); System.out.println( c.getSymbol() );
MethodPurpose
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.

13. Formatter

Formatter creates formatted output using format specifiers.

Formatter fmt = new Formatter(); fmt.format( "Name: %s, Age: %d, Score: %f", "Ravi", 25, 98.5 ); System.out.println(fmt); fmt.close();
SpecifierMeaning
%cCharacter
%sString
%dDecimal integer
%fFloating point
%eScientific notation
%gGeneral floating format
%oOctal
%xHexadecimal
%aHexadecimal floating point
%nNewline
%%Percent sign

Field width and precision

fmt.format("|%f|%n|%12f|%n|%012f|", 10.12345, 10.12345, 10.12345); fmt.format("%.2f", 98.7654);

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.

Date/time formatting

Calendar cal = Calendar.getInstance(); Formatter fmt = new Formatter(); fmt.format( "Today is day %te of %tB, %tY", cal, cal, cal );

The %t conversion uses suffixes for particular date/time components. Relative indexing such as %<tB can reuse the previous argument.

14. printf() Connection

The chapter explains that printf() is a convenient console-oriented alternative to directly creating a Formatter. It uses Formatter-style formatting.

System.out.printf( "Name: %s, Age: %d%n", "Ravi", 25 );

15. Scanner

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.

Scanner scanner = new Scanner(System.in); System.out.print("Age: "); int age = scanner.nextInt(); System.out.println(age); scanner.close();
MethodPurpose
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.
Scanner scanner = new Scanner("10 99.88 Java"); int n = scanner.nextInt(); double d = scanner.nextDouble(); String s = scanner.next(); scanner.close();

16. Locale

Locale represents language/cultural or regional settings and is used by utilities such as Calendar, Currency, Formatter, and ResourceBundle.

Locale us = Locale.US; Locale germany = Locale.GERMANY; System.out.println(us); System.out.println(germany);

17. ResourceBundle

ResourceBundle supports localization by keeping resources such as user-visible strings separate from application logic.

ResourceBundle bundle = ResourceBundle.getBundle("SampleRB"); String title = bundle.getString("title"); System.out.println(title);
ResourceBundle german = ResourceBundle.getBundle( "SampleRB", Locale.GERMAN ); System.out.println( german.getString("title") );
MethodPurpose
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.

18. StringJoiner

StringJoiner joins character sequences using a delimiter and can also add a prefix and suffix.

StringJoiner joiner = new StringJoiner( ", ", "[", "]" ); joiner.add("Java"); joiner.add("Python"); joiner.add("C++"); System.out.println(joiner);
[Java, Python, C++]

Important methods include add(), merge(), setEmptyValue(), length(), and toString().

19. UUID

UUID encapsulates and manages Universally Unique Identifiers.

UUID id = UUID.randomUUID(); System.out.println(id);

20. Base64

Base64 supports Base64 encoding and decoding. It provides nested Encoder and Decoder classes.

String text = "Java"; String encoded = Base64.getEncoder() .encodeToString( text.getBytes() ); System.out.println(encoded);
Important: Base64 is an encoding representation; it is not encryption.

21. Summary Statistics

IntSummaryStatistics and DoubleSummaryStatistics collect statistics such as count, sum, minimum, maximum, and average.

IntSummaryStatistics stats = new IntSummaryStatistics(); stats.accept(10); stats.accept(20); stats.accept(30); System.out.println(stats.getCount()); System.out.println(stats.getAverage()); System.out.println(stats.getSum());

22. java.util.function

The java.util.function package defines predefined functional interfaces used heavily with lambda expressions and method references.

InterfaceSimple 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.
Predicate<Integer> positive = n -> n > 0; System.out.println( positive.test(10) );

23. Other java.util Utilities

ClassPurpose
ObjectsUtility methods that operate on objects.
HexFormatConversions to and from hexadecimal representation.
ServiceLoaderFinding service providers.
PropertyPermissionProperty permissions.
EventObjectSuperclass for event objects.
EventListenerProxyProxy support for event listeners.
FormattableFlagsFormatting flags for Formattable.

24. java.util Subpackages

SubpackagePurpose
java.util.concurrentConcurrent programming and Fork/Join support.
java.util.concurrent.atomicAtomic operations.
java.util.concurrent.locksExplicit lock mechanisms.
java.util.functionPredefined functional interfaces.
java.util.jarRead/write JAR files.
java.util.loggingLogging facilities.
java.util.prefsPreferences.
java.util.randomRandom-number APIs.
java.util.regexRegular expressions.
java.util.spiService-provider interfaces.
java.util.streamStream APIs.
java.util.zipCompression and ZIP utilities.

25. Complete Mental Map

java.util | +-- Text | +-- StringTokenizer | +-- StringJoiner | +-- Optional values | +-- Optional<T> | +-- OptionalInt | +-- OptionalLong | +-- OptionalDouble | +-- Date / Time | +-- Date | +-- Calendar | +-- GregorianCalendar | +-- TimeZone | +-- Random / Scheduling | +-- Random | +-- Timer | +-- TimerTask | +-- Formatting / Input | +-- Formatter | +-- Scanner | +-- Localization | +-- Locale | +-- Currency | +-- ResourceBundle | +-- Other +-- BitSet +-- Base64 +-- UUID +-- Objects +-- HexFormat +-- SummaryStatistics

26. Which Utility Should I Choose?

ProblemThink of
Break text into tokensStringTokenizer
Read formatted inputScanner
Create formatted outputFormatter
Represent possibly absent valueOptional
Optional primitive valueOptionalInt / Long / Double
Work with bitsBitSet
Traditional date/timeDate / Calendar
Gregorian rulesGregorianCalendar
Time-zone informationTimeZone
Pseudorandom valuesRandom
Schedule a taskTimer + TimerTask
Currency informationCurrency
LocalizationLocale + ResourceBundle
Join stringsStringJoiner
Unique identifierUUID
Base64 representationBase64

27. Perspective

Do not memorize all of java.util.

Learn the requirement → utility relationship:

Missing value → Optional
Token input → Scanner / StringTokenizer
Formatted output → Formatter
Date components → Calendar
Time zone → TimeZone
Random values → Random
Scheduled task → Timer + TimerTask
Localization → Locale + ResourceBundle
Currency → Currency
Unique ID → UUID

28. Key Rules

  • Optional represents a value that may be absent or present.
  • Date represents date/time information using the traditional API.
  • Calendar exposes date/time components.
  • GregorianCalendar is a concrete Calendar implementation.
  • TimeZone represents time-zone information.
  • Random generates pseudorandom values.
  • Timer schedules; TimerTask executes.
  • Formatter creates formatted output; Scanner reads formatted input.
  • Locale, Currency, and ResourceBundle support internationalization/localization.
  • StringJoiner joins strings with delimiters.
  • UUID manages universally unique identifiers.
  • java.util.function supplies standard functional interfaces for lambdas.

29. Summary

This chapter completes the major utility-class portion of java.util. The most important skill is knowing which utility matches a programming requirement. Together with the Collections Framework chapter, these give you a strong foundation for Java's collection and general utility APIs.