Random rng = new Random(); // unseededRandom seeded = new Random(42L);int dice = rng.nextInt(6) + 1; // 1..6double d = rng.nextDouble(); // [0,1)boolean b = rng.nextBoolean();rng.ints(10, 0, 100).forEach(System.out::println);
Method
Returns
nextInt()
Any int
nextInt(bound)
[0, bound)
nextLong/nextDouble/nextFloat/nextBoolean
Per-type
nextGaussian()
Normal distribution mean 0, sd 1
ints/longs/doubles
Stream of values
7. Using SecureRandom
Aspect
Detail
Class
java.security.SecureRandom
Use for
Tokens, passwords, crypto keys, salts
Algorithm
SecureRandom.getInstanceStrong()
API
Same as Random + nextBytes(byte[])
Warning: Never use Math.random() or Random for security-sensitive values.
8. Understanding Random Number Seeds
Behavior
Detail
Same seed
Same sequence (reproducible)
Default seed
System time + counter
Set after creation
rng.setSeed(s)
9. Working with BigInteger
Example: BigInteger
BigInteger a = new BigInteger("123456789012345678901234567890");BigInteger b = BigInteger.TEN.pow(50);BigInteger sum = a.add(b);BigInteger gcd = a.gcd(b);boolean prime = a.isProbablePrime(20);
Method
Description
add/subtract/multiply/divide/mod
Arithmetic (immutable)
pow(int)
Exponentiation
modPow(e, m)
Modular exponentiation
gcd(b)
Greatest common divisor
compareTo(b)
Order comparison
Constants
ZERO, ONE, TWO, TEN
10. Working with BigDecimal
Example: Money math
BigDecimal price = new BigDecimal("19.99");BigDecimal qty = BigDecimal.valueOf(3);BigDecimal total = price.multiply(qty) .setScale(2, RoundingMode.HALF_UP); // 59.97
Method
Description
new BigDecimal("0.1")
String constructor (exact)
BigDecimal.valueOf(d)
Use this for double — avoids float artifacts
add/subtract/multiply
Exact arithmetic
divide(b, scale, mode)
Specify rounding
setScale(s, RoundingMode)
Decimal places
RoundingMode
HALF_UP, HALF_EVEN, FLOOR, CEILING, UP, DOWN
Warning: Never construct via new BigDecimal(0.1) — uses inexact double. Use string or valueOf.