Standard libraries
libs4RandomAndUuid
- Path
- pkg13libs/libs4RandomAndUuid.java
- Package
- pkg13libs
- Study order
- 4
- Run
- Single-file source launch
- Command
- java pkg13libs/libs4RandomAndUuid.java
There is no in-browser runner. This is the file from the curriculum, unchanged.
1package pkg13libs;2 3import java.security.SecureRandom;4import java.util.Random;5import java.util.UUID;6import java.util.concurrent.ThreadLocalRandom;7import java.util.stream.Collectors;8 9/*10 * libs4RandomAndUuid.java11 * -----------------------12 * Randomness done right: Random, ThreadLocalRandom, SecureRandom, and UUIDs.13 *14 * DEFINITION:15 * Random is a fast pseudo-random generator (predictable from its seed).16 * SecureRandom is cryptographically strong (for tokens/keys). UUID is a17 * 128-bit unique identifier.18 *19 * KEY POINTS:20 * - Seed a Random to get reproducible sequences (great for tests).21 * - Use ThreadLocalRandom in concurrent code (no contention).22 * - Use SecureRandom for anything security-sensitive — never plain Random.23 * - UUID.randomUUID() (v4) is the go-to for distributed unique ids.24 */25public class libs4RandomAndUuid {26 27 public static void main(String[] args) {28 // Seeded Random is reproducible29 Random seeded = new Random(42);30 System.out.print("Seeded(42) ints : ");31 for (int i = 0; i < 5; i++) System.out.print(seeded.nextInt(100) + " ");32 System.out.println("(same every run)");33 34 // Ranges and other types35 Random r = new Random();36 System.out.println("\nrandom double : " + r.nextDouble());37 System.out.println("random boolean : " + r.nextBoolean());38 System.out.println("dice (1..6) : " + (r.nextInt(6) + 1));39 40 // Streams of random numbers (Java 8+)41 String nums = r.ints(5, 0, 10).mapToObj(Integer::toString).collect(Collectors.joining(", "));42 System.out.println("5 ints [0,10) : " + nums);43 44 // ThreadLocalRandom — preferred in multithreaded code45 System.out.println("\nThreadLocalRandom: " + ThreadLocalRandom.current().nextInt(1000));46 47 // SecureRandom — for tokens, salts, keys48 SecureRandom sr = new SecureRandom();49 byte[] token = new byte[8];50 sr.nextBytes(token);51 System.out.println("Secure token : " + java.util.HexFormat.of().formatHex(token));52 53 // UUIDs54 UUID id = UUID.randomUUID();55 System.out.println("\nUUID v4 : " + id);56 System.out.println("version : " + id.version() + ", variant: " + id.variant());57 }58}