/**
Generate a random color in HEX format (#RRGGBB).
This program demonstrates how numbers and bits are used
to produce a valid 24‑bit color value.
*/
import java.util.Random;
public class Main {
/**
* Create a 24‑bit random integer (0x000000–0xFFFFFF).
* Random.nextInt(bound) returns a value in [0, bound),
* so using 0x1000000 (2^24) gives exactly 24 bits.
*/
public static int randomColorInt(Random rng) {
// 24 bits → values from 0 to 16,777,215 (0xFFFFFF)
return rng.nextInt(0x1000000);
}
/**
* Convert a 24‑bit integer into a hex color string.
* String.format("%06X") ensures exactly 6 uppercase hex digits.
*/
public static String intToHexColor(int value) {
String hex = String.format("%06X", value); // Convert to 6‑digit hex
return "#" + hex;
}
/**
* Produce a random hex color by combining the two functions.
*/
public static ColorResult generateRandomHexColor(Random rng) {
int value = randomColorInt(rng); // 24‑bit random number
String hex = intToHexColor(value); // Convert to #RRGGBB
return new ColorResult(value, hex);
}
// Simple record-like container for the result
public static class ColorResult {
public final int value;
public final String hex;
public ColorResult(int value, String hex) {
this.value = value;
this.hex = hex;
}
}
public static void main(String[] args) {
Random rng = new Random();
ColorResult result = generateRandomHexColor(rng);
System.out.println("Random 24-bit value: " + result.value);
System.out.println("Hex color: " + result.hex);
}
}
/*
run:
Random 24-bit value: 8137980
Hex color: #7C2CFC
*/