Standard Classes

Math

  • Math.min()
  • Math.max()
  • Math.abs()
  • Math.floor(): double
  • Math.ceil(): double
  • Exponential
    • Math.sqrt(): double
    • Math.cbrt(): double
    • Math.pow(): double
  • Math.random(): double
  • Constants:
    • Math.PI
    • Math.E

BigInteger

  • immutable
BigInteger x = new BigInteger("3456345353453453535353");
BigInteger y = BigInteger.valueOf(1_000_000_000);
x.add()
x.multiply()
x.divide()
x.subtract()
x.negate()
x.abs()

BigDecimal

  • immutable
  • alternative to float and double which causes incorrect results
System.out.println(0.1 + 0.2); // 0.30000000000000004
  • calculations are exactly correct in BigDecimal
    •  defined by an arbitrary precision integer and a 32-bit integer scale
BigDecimal x = new BigDecimal("10000000000000.5897654329");
 
BigDecimal first = new BigDecimal("0.2");
BigDecimal second = new BigDecimal("0.1");
BigDecimal result = first.add(second); // 0.3
  • Rounding
bigDecimal.setScale(newScale, RoundingMode)

Precision vs Scale

  • Precision: Number of digits in a number
  • Scale: Number of digits to the right of decimal
  • 123.45
    • precision: 5
    • scale: 2

Random

  • Used to generate pseudo random number
Random random = new Random(); // no seed
Random random2 = new Random(100000); // with seed
 
random.nextInt()
random.nextInt(n: int) // generates integer in range: [0...n)
random.nextDouble() // generate double between 0.0 and 1.0
random.nextBytes(bytes: byte[])
 
// generate integer in range: [lower...upper]
int next = random.nextInt(upper - lower + 1) + lower;
  • Similar classes
    • ThreadLocalRandom — to be used in multithreaded scenario
    • SecureRandom — cryptographically secure PRNG

Pseudo Random Numbers (PRN)

  • Every time we get a new pseudo random number, we actually get the next number in a predefined sequence
  • They are not completely unpredictable! We can calculate them all if we know the initial value and the algorithm of the sequence.
  • The initial value is called a seed

UUID

  • generates UUID (128-bit)
import java.util.UUID
 
// .....
 
String employeeId = UUID.randomUUID().toString();