Utility classes in Java provide methods and constants for performing common operations. Here’s a quick overview of three key utility classes: Math, Date, and Calendar.

1. Math Class

The Math class contains methods for performing basic numeric operations such as exponential, logarithm, square root, and trigonometric functions. It’s a final class, so it cannot be subclassed.

Key Methods:

  • abs(x): Returns the absolute value of x.
  • sqrt(x): Returns the square root of x.
  • pow(x, y): Returns x raised to the power of y.
  • max(x, y): Returns the greater of x and y.
  • min(x, y): Returns the smaller of x and y.

Example:

  public class MathExample {
    public static void main(String[] args) {
        double value = -9.5;
        System.out.println("Absolute value: " + Math.abs(value));
        System.out.println("Square root: " + Math.sqrt(16));
        System.out.println("Power: " + Math.pow(2, 3));
        System.out.println("Max: " + Math.max(4, 7));
        System.out.println("Min: " + Math.min(4, 7));
    }
}
  

2. Date Class

The Date class represents a specific instant in time, with millisecond precision. It’s now considered somewhat outdated and has been largely replaced by the newer java.time package (introduced in Java 8).

Key Methods:

  • getTime(): Returns the number of milliseconds since January 1, 1970.
  • toString(): Returns a string representation of the date.
  • setYear(year): Sets the year of the date (deprecated).

Example:

  import java.util.Date;

public class DateExample {
    public static void main(String[] args) {
        Date now = new Date();
        System.out.println("Current date and time: " + now.toString());
        System.out.println("Milliseconds since epoch: " + now.getTime());
    }
}
  

3. Calendar Class

The Calendar class provides methods for working with dates and times in a more flexible way than Date. It allows you to manipulate and format dates.

Key Methods:

  • getInstance(): Returns a calendar object with the default time zone and locale.
  • get(int field): Gets the value of a specified calendar field (e.g., Calendar.YEAR).
  • set(int field, int value): Sets the value of a specified calendar field.
  • add(int field, int amount): Adds or subtracts a specified amount of time to the given calendar field.

Example:

  import java.util.Calendar;

public class CalendarExample {
    public static void main(String[] args) {
        Calendar calendar = Calendar.getInstance();
        System.out.println("Current year: " + calendar.get(Calendar.YEAR));
        System.out.println("Current month: " + (calendar.get(Calendar.MONTH) + 1)); // Months are 0-based
        System.out.println("Current day: " + calendar.get(Calendar.DAY_OF_MONTH));

        calendar.add(Calendar.YEAR, 1);
        System.out.println("Next year: " + calendar.get(Calendar.YEAR));
    }
}
  

Modern Alternatives

For new code, consider using the java.time package, which provides a more comprehensive and flexible API for handling dates and times, such as LocalDate, LocalTime, and LocalDateTime.

Objects Utility Class (Java 7+)

Objects provides null-safe helpers:

  import java.util.Objects;

String name = Objects.requireNonNull(input, "name must not be null");
boolean equal = Objects.equals(a, b);  // null-safe equals
int hash = Objects.hash(field1, field2, field3);
  

Random and SecureRandom

  import java.util.Random;
import java.security.SecureRandom;

Random rng = new Random();
int dice = rng.nextInt(6) + 1;

SecureRandom secure = new SecureRandom();
byte[] token = new byte[32];
secure.nextBytes(token);
  

Use SecureRandom for tokens, session IDs, and cryptographic operations.

java.time — Modern Date/Time API

  import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

LocalDate today = LocalDate.now();
LocalDateTime now = LocalDateTime.now();
String formatted = now.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);

LocalDate deadline = today.plusDays(30);
  

Prefer java.time over Date and Calendar in all new code.

Arrays Utility

  import java.util.Arrays;

int[] nums = {3, 1, 4, 1, 5};
Arrays.sort(nums);
System.out.println(Arrays.toString(nums));  // [1, 1, 3, 4, 5]

int index = Arrays.binarySearch(nums, 4);
  

Common Pitfalls

  • Using Date mutability — setYear() and similar methods modify in place.
  • Calendar.MONTH is 0-based (January = 0) — a frequent source of off-by-one bugs.
  • Math.random() returns [0.0, 1.0) — use Random.nextInt(bound) for integers.