Lesson 42: Essential Utility Classes
Java provides many utility classes, often containing static methods, that simplify common tasks.
1. The Math Class
Contains methods for performing basic numeric operations, such as elementary exponential, logarithm, square root, and trigonometric functions.
- All methods and fields are
static. - Fields:
Math.PI,Math.E.
java // Square root double root = Math.sqrt(81.0); // 9.0
// Rounding long rounded = Math.round(3.7); // 4
// Max/Min int maxVal = Math.max(10, 20); // 20
// Power double power = Math.pow(2, 3); // 8.0
2. The Random Class
Used to generate pseudo-random numbers.
java import java.util.Random;
Random random = new Random();
// Generate a random integer int randInt = random.nextInt();
// Generate a random integer between 0 (inclusive) and 100 (exclusive) int diceRoll = random.nextInt(100);
// Generate a random double between 0.0 (inclusive) and 1.0 (exclusive) double randDouble = random.nextDouble();
3. The Modern Date/Time API (java.time)
Introduced in Java 8, this API fixes many flaws of the old Date and Calendar classes. It is much clearer, immutable, and thread-safe.
LocalDate: Date without time/timezone.LocalTime: Time without date/timezone.LocalDateTime: Date and time without timezone.
java import java.time.LocalDate; import java.time.LocalDateTime;
// Current date and time LocalDate today = LocalDate.now(); System.out.println(today);
// Specific date LocalDate birthday = LocalDate.of(1990, 10, 20);
// Manipulation (all these return new immutable objects) LocalDate nextWeek = today.plusWeeks(1);