How do I use the RandomGenerator API introduced in JDK 17?

The RandomGenerator API, introduced in JDK 17, provides a simpler and more flexible way to work with random number generation by centralizing the different strategies for producing random numbers under a single interface (RandomGenerator). This allows developers to access multiple random number generation algorithms in a standardized manner. Additionally, it improves upon the legacy java.util.Random class.

Here’s how you can use the RandomGenerator API:

Key Classes/Interfaces in the RandomGenerator API

  • RandomGenerator (Interface): Defines methods for generating random values of different types (e.g., nextInt(), nextDouble(), etc.).
  • RandomGeneratorFactory (Class): Used to instantiate various implementations of the RandomGenerator interface.
  • SplittableRandom, ThreadLocalRandom, SecureRandom: Core implementations of RandomGenerator.
  • Random: Although part of the legacy API, it now implements RandomGenerator in JDK 17.

Code Example: Basic Usage with RandomGenerator

Here’s a basic example of how to use RandomGenerator:

package org.kodejava.util.random;

import java.util.random.RandomGenerator;

public class RandomGeneratorExample {
    public static void main(String[] args) {
        // Retrieve the default random generator
        RandomGenerator generator = RandomGenerator.getDefault();

        // Generate random numbers of various types
        int randomInt = generator.nextInt();          // Random integer
        double randomDouble = generator.nextDouble(); // Random double in [0.0, 1.0)
        long randomLong = generator.nextLong();       // Random long
        boolean randomBoolean = generator.nextBoolean(); // Random boolean

        // Print results
        System.out.println("Random integer: " + randomInt);
        System.out.println("Random double: " + randomDouble);
        System.out.println("Random long: " + randomLong);
        System.out.println("Random boolean: " + randomBoolean);

        // Generate a random integer within a range (0 to 100)
        int rangedInt = generator.nextInt(101);
        System.out.println("Random integer in range [0, 100]: " + rangedInt);
    }
}

Using RandomGeneratorFactory for Choosing a Specific Algorithm

The RandomGeneratorFactory class allows you to select specific implementations of RandomGenerator. This can help you use different algorithms tailored to your use case.

Example:

package org.kodejava.util.random;

import java.util.random.RandomGenerator;
import java.util.random.RandomGeneratorFactory;

public class CustomRandomGeneratorExample {
    public static void main(String[] args) {
        // List all available random generator algorithms
        System.out.println("Available Random Generators:");
        RandomGeneratorFactory.all().forEach(factory -> {
            System.out.println("- " + factory.name());
        });

        // Create a specific random generator (e.g., `L64X128MixRandom`)
        RandomGenerator generator = RandomGeneratorFactory.of("L64X128MixRandom").create();

        // Generate random values
        System.out.println("Random value: " + generator.nextDouble());
    }
}

Notes

  1. Default Generator: RandomGenerator.getDefault() provides a default random number generator.
  2. Thread-Safety: Consider java.util.concurrent.ThreadLocalRandom for generating random numbers in a multithreaded context.
  3. Secure Random Numbers: Use java.security.SecureRandom for cryptographically secure random numbers.
  4. Performance: If you need high-performance statistically random values, explore generators like L128X256MixRandom.

Benefits of Using the RandomGenerator API

  • Multiple Algorithms: No need to rely solely on java.util.Random.
  • Improved Extensibility: Selecting different implementations for specific use cases is easier.
  • Consistency: Unified method signatures across implementations enable flexible and consistent code.

How do I use record with generics?

Using records with generics in Java allows you to create immutable data structures while also providing the benefits of generics, such as type safety and flexibility. Since Java 16, the record feature was introduced, and it can be combined with generics like other classes. Here’s an example of how to use records with generics.

Syntax

To define a record with generics, you specify the type parameter(s) in the record declaration just like in a class declaration.

public record MyRecord<T>(T value) { }

Examples

1. Basic Generic Record

A simple record that accepts a generic type parameter:

// Define record with a generic parameter T
public record Box<T>(T content) { }

Usage:

public class Main {
    public static void main(String[] args) {
        // Create a record with a String type
        Box<String> stringBox = new Box<>("Hello, generics!");
        System.out.println(stringBox.content()); // Output: Hello, generics!

        // Create a record with an Integer type
        Box<Integer> integerBox = new Box<>(123);
        System.out.println(integerBox.content()); // Output: 123
    }
}

2. Records with Multiple Generics

You can define records with multiple type parameters, just like generic classes:

// Define a record with two generic types
public record Pair<K, V>(K key, V value) { }

Usage:

public class Main {
    public static void main(String[] args) {
        // Create a Pair with String and Integer
        Pair<String, Integer> pair = new Pair<>("Age", 30);
        System.out.println(pair.key() + ": " + pair.value()); // Output: Age: 30

        // Create a Pair with two different types
        Pair<Double, String> anotherPair = new Pair<>(3.14, "Pi");
        System.out.println(anotherPair.key() + " -> " + anotherPair.value()); // Output: 3.14 -> Pi
    }
}

3. Generics with Constraints

Generic records can include bounded type parameters to restrict the types allowed:

// Generic type T is constrained to subclasses of Number
public record NumericBox<T extends Number>(T number) { }

Usage:

public class Main {
    public static void main(String[] args) {
        // Only Number or subclasses of Number are allowed
        NumericBox<Integer> intBox = new NumericBox<>(42);
        System.out.println(intBox.number()); // Output: 42

        NumericBox<Double> doubleBox = new NumericBox<>(3.14);
        System.out.println(doubleBox.number()); // Output: 3.14

        // Compiler error: String is not a subclass of Number
        // NumericBox<String> stringBox = new NumericBox<>("Not a number");
    }
}

4. Working with Wildcards

You can use wildcards in generic records when specifying their types:

public class Main {
    public static void main(String[] args) {
        // Using a wildcard
        Box<?> anyBox = new Box<>("Wildcard content");
        System.out.println(anyBox.content()); // Output: Wildcard content

        // Using bounded wildcards
        NumericBox<? extends Number> numBox = new NumericBox<>(42);
        System.out.println(numBox.number()); // Output: 42
    }
}

Benefits of Using Generics with Records

  1. Type Safety: With generics, the compiler ensures the record is used correctly for the intended type.
  2. Reusability: You can use the same record with different data types.
  3. Immutability: Records’ inherent immutability, coupled with generics, allows you to encapsulate type-safe, immutable data structures.

This approach works seamlessly with the other features of records, such as pattern matching and compact constructors. Let me know if you’d like more advanced scenarios!

How do I use String.strip(), isBlank() and lines() methods?

The String class in Java provides the methods strip(), isBlank(), and lines(), which were introduced in Java 11. These methods are useful for managing whitespaces, checking for blank strings, and processing multi-line strings.

1. strip()

The strip() method removes leading and trailing whitespaces from a string. Unlike trim(), it uses Unicode-aware whitespace handling, making it more robust for international characters.

Example:

public class StringStripExample {
    public static void main(String[] args) {
        String str = " \u2009Hello World  "; // Unicode whitespace
        System.out.println(str.strip());      // Outputs: "Hello World"
        System.out.println(str.stripLeading()); // Removes leading spaces: "Hello World  "
        System.out.println(str.stripTrailing()); // Removes trailing spaces: " \u2009Hello World"
    }
}

Key Point:

  • strip() differs from trim() in that it removes all Unicode whitespace, not just ASCII spaces.

2. isBlank()

The isBlank() method checks whether a string is empty or contains only whitespaces. This includes Unicode whitespace and helps to quickly validate string content.

Example:

public class StringIsBlankExample {
    public static void main(String[] args) {
        String empty = "   "; // Contains whitespaces
        System.out.println(empty.isBlank()); // Outputs: true

        String nonBlank = "Hello";
        System.out.println(nonBlank.isBlank()); // Outputs: false

        String unicodeSpace = "\u2009"; // Unicode whitespace
        System.out.println(unicodeSpace.isBlank()); // Outputs: true
    }
}

Key Point:

  • isBlank() is stronger than isEmpty() because it treats strings with only whitespace as blank, whereas isEmpty() considers only an empty string ("").

3. lines()

The lines() method breaks a multi-line string into a stream of lines, using the platform’s line terminator (e.g., \n or \r\n) to split the string.

Example:

public class StringLinesExample {
    public static void main(String[] args) {
        String multiLineString = "Hello\nWorld\nJava 11";

        // Use 'lines()' to split the multi-line string
        multiLineString.lines().forEach(System.out::println);

        // Output:
        // Hello
        // World
        // Java 11
    }
}

Key Points:

  • lines() splits the string into lines and returns a Stream<String>.
  • It can be combined with stream operations like filter(), map(), and forEach().

Combining Methods for Common Use Cases

Here’s how you can combine them:

Trim and Check Blank:

public class StringExample {
    public static void main(String[] args) {
        String input = "   ";
        if (input.strip().isBlank()) {
            System.out.println("Input is blank or empty!");
        } else {
            System.out.println("Input: " + input.strip());
        }
    }
}

Processing Multi-Line Strings:

public class MultiLineExample {
    public static void main(String[] args) {
        String text = "  Line 1  \n  Line 2  \n  Line 3  ";

        text.lines()
            .map(String::strip) // Clean up each line
            .forEach(System.out::println);

        // Output:
        // Line 1
        // Line 2
        // Line 3
    }
}

Summary of Functionalities:

  • strip(): Removes leading/trailing Unicode whitespace.
  • isBlank(): Checks if a string is empty or only whitespace.
  • lines(): Processes multi-line strings by splitting them into lines.

How do I use compact constructors in records?

Compact constructors in records are a concise way to initialize and validate fields of a record in Java. Unlike standard constructors, compact constructors omit the parameter list, as they operate directly on the record’s declared components.

Here’s how to use compact constructors in records:

1. Syntax:

A compact constructor is declared without parentheses after the constructor name. Inside the constructor body, you can initialize or validate fields of the record.

Example:

public record Person(String name, int age) {
    // Compact constructor
    public Person {
        if (name == null || name.isBlank()) {
            throw new IllegalArgumentException("Name cannot be null or blank");
        }
        if (age < 0) {
            throw new IllegalArgumentException("Age cannot be negative");
        }
    }
}

2. How It Works:

  • The compact constructor implicitly takes all the components of the record as parameters.
  • You can directly access these fields without explicitly specifying them as parameters since they are already “properties” of the record.
  • Unlike regular constructors, compact constructors aim to reduce boilerplate validations and/or additional initialization.

In the above example:

  • name and age are automatically initialized in the generated constructor, but the compact constructor validates them before allowing that to happen.
  • If the validations fail, the constructor throws exceptions.

3. Special Notes:

  • The Java compiler ensures that the compact constructor assigns values to all record components before the constructor completes execution.
  • You cannot directly modify the record components since they are implicitly final. What you can do is validate or make use of the incoming values.

4. Why Use Compact Constructors?

Compact constructors are helpful when:

  1. You need to validate fields during record initialization.
  2. You want to add extra logic (like logging) to the generated canonical constructor of the record.
  3. You want to reduce boilerplate by avoiding redundant parameter declarations.

5. Example with Additional Fields:

If the record has additional fields beyond what is declared in the record header, those can also be initialized in the compact constructor:

public record Rectangle(int length, int width) {
    private static final int MINIMUM_SIZE = 1;

    public Rectangle {
        // Validation
        if (length < MINIMUM_SIZE || width < MINIMUM_SIZE) {
            throw new IllegalArgumentException("Dimensions must be at least " + MINIMUM_SIZE);
        }
    }
}

Summary:

Compact constructors in records:

  • Automatically operate on the fields declared as record components.
  • Reduce boilerplate for constructor declarations.
  • Are ideal for validation and pre-processing logic.
  • Must initialize or ensure that all components are correctly set before completing.

How do I use sealed classes to control inheritance?

In Java, sealed classes are a feature introduced in Java 15 (as a preview and finalized in Java 17) that allows you to control inheritance by specifying which classes or interfaces can extend or implement a given class or interface. This makes your class hierarchy more predictable and easier to reason about.

Using sealed classes involves the following key concepts:

1. Declaration of a Sealed Class

A class can be declared as sealed, which means that only a specific set of classes (declared permits) can extend that class. Here’s the basic syntax:

public sealed class ParentClass permits ChildA, ChildB {
    // Class code
}

Here, only ChildA and ChildB (declared in permits) are allowed to extend ParentClass. This ensures complete control over the inheritance structure of your class.


2. The Role of Permitted Subclasses

Each subclass specified in the permits clause must do one of the following to complete the sealed hierarchy:

  • Declare itself as final (no further inheritance is allowed).
  • Declare itself as sealed (allowing further controlled inheritance).
  • Declare itself as non-sealed (allowing unrestricted inheritance).

Examples of each:

Final Subclass:

public final class ChildA extends ParentClass {
    // Class code
}

Sealed Subclass:

public sealed class ChildB extends ParentClass permits GrandChild {
    // Class code
}

public final class GrandChild extends ChildB {
    // Class code
}

Non-Sealed Subclass:

public non-sealed class ChildC extends ParentClass {
    // Class code
}

In the case of non-sealed, ChildC and its subclasses can be freely inherited, bypassing the restrictions of sealing.


3. Key Features and Benefits of Sealed Classes

  1. Ensure Complete Class Hierarchy Control:
    • By listing all allowed subclasses, you can restrict who can build upon your functionality.
    • Simplifies reasoning about the class hierarchy in complex systems.
  2. Improved Exhaustiveness Checking:
    • When used with instanceof or switch expressions, the compiler knows all the possible subclasses (because they’ve been explicitly listed).
    • For example, pattern matching with switch:
    public String process(ParentClass obj) {
         return switch (obj) {
             case ChildA a -> "ChildA";
             case ChildB b -> "ChildB";
             default -> throw new IllegalStateException("Unexpected value: " + obj);
         };
     }
    
  3. Enforces Encapsulation and API Design Consistency:
    • Encourages developers to think hard about which subclasses make sense.
  4. Useful for Modeling Closed Systems:
    • Great for scenarios where the possible subclasses represent a closed set of types, such as states in a state machine.

Example: Sealed Class for a Shape Hierarchy

Here is a practical example of using sealed classes in a geometric shape hierarchy:

public sealed class Shape permits Circle, Rectangle, Square {
    // Common shape fields and methods
}

public final class Circle extends Shape {
    // Circle-specific fields and methods
}

public final class Rectangle extends Shape {
    // Rectangle-specific fields and methods
}

public final class Square extends Shape {
    // Square-specific fields and methods
}

If someone tries to create a new subclass of Shape outside of those specified in permits, a compilation error will occur.


4. Rules and Restrictions

  • A sealed class must use the permits clause unless all permitted implementations are within the same file.
  • The permitted classes must extend the sealed class or implement the sealed interface.
  • Subclasses of sealed classes located in different packages must be public.
  • All permitted classes are resolved at compile time.

Summary

Java’s sealed classes provide you with a powerful tool to control inheritance in your programs by explicitly defining the classes that are allowed to extend or implement a particular class or interface. They make your code more robust, predictable, and maintainable by restricting which subclasses can exist in a hierarchy. Use them when you want tight control over a class hierarchy or when modeling scenarios with a limited set of possibilities.