Reading history

Java Math Class and Random Numbers

7 min read 0 views

Use Java's Math class for powers, roots and rounding, avoid integer division traps, and make random numbers with Random, seeds, shuffle and SecureRandom.

Most programs need a little maths: a square root for a distance, rounding for a price, or a random number for a dice game or a one-time code. Java keeps these tools in two places. The Math class has ready-made functions such as sqrt, pow and round. The Random class makes random numbers. This lesson shows the methods you will use most, and the traps that catch beginners, such as integer division and rounding of negative numbers.

In this lesson you will learn

  • Common Math methods: abs, pow, sqrt, hypot, max
  • The four ways to round: round, floor, ceil and rint
  • Integer division, floorDiv and floorMod
  • Safe arithmetic with addExact
  • Random numbers in a range, seeds, shuffling and OTP codes

You should know Java data types and Java operators.

The Math Class

All Math methods are static, so you call them on the class name, like Math.sqrt(144). You never write new Math().

public class Main {
    public static void main(String[] args) {
        System.out.println("abs(-7)        = " + Math.abs(-7));
        System.out.println("max(4, 9)      = " + Math.max(4, 9));
        System.out.println("pow(2, 10)     = " + Math.pow(2, 10));
        System.out.println("sqrt(144)      = " + Math.sqrt(144));
        System.out.println("cbrt(27)       = " + Math.cbrt(27));
        System.out.println("hypot(3, 4)    = " + Math.hypot(3, 4));

        double x = 2.5, y = -2.5;
        System.out.println();
        System.out.println("value  round  floor  ceil  rint");
        for (double v : new double[]{x, y, 2.4, 3.5}) {
            System.out.printf("%5.1f  %5d  %5.1f  %4.1f  %4.1f%n",
                v, Math.round(v), Math.floor(v), Math.ceil(v), Math.rint(v));
        }

        System.out.println();
        System.out.println("7 / 2          = " + (7 / 2));
        System.out.println("-7 / 2         = " + (-7 / 2));
        System.out.println("floorDiv(-7,2) = " + Math.floorDiv(-7, 2));
        System.out.println("-7 % 3         = " + (-7 % 3));
        System.out.println("floorMod(-7,3) = " + Math.floorMod(-7, 3));

        System.out.println();
        System.out.printf("sin(30 deg)    = %.4f%n", Math.sin(Math.toRadians(30)));
        System.out.printf("PI             = %.6f%n", Math.PI);
        System.out.println("0.1 + 0.2      = " + (0.1 + 0.2));
        System.out.printf("rounded        = %.2f%n", 0.1 + 0.2);

        try {
            Math.addExact(Integer.MAX_VALUE, 1);
        } catch (ArithmeticException e) {
            System.out.println("addExact       : " + e.getMessage());
        }
    }
}

Output

abs(-7)        = 7
max(4, 9)      = 9
pow(2, 10)     = 1024.0
sqrt(144)      = 12.0
cbrt(27)       = 3.0
hypot(3, 4)    = 5.0

value  round  floor  ceil  rint
  2.5      3    2.0   3.0   2.0
 -2.5     -2   -3.0  -2.0  -2.0
  2.4      2    2.0   3.0   2.0
  3.5      4    3.0   4.0   4.0

7 / 2          = 3
-7 / 2         = -3
floorDiv(-7,2) = -4
-7 % 3         = -1
floorMod(-7,3) = 2

sin(30 deg)    = 0.5000
PI             = 3.141593
0.1 + 0.2      = 0.30000000000000004
rounded        = 0.30
addExact       : integer overflow
  • Math.pow and Math.sqrt always return a double, so you see 1024.0, not 1024. Cast to int if you need a whole number.
  • Math.hypot(3, 4) gives the long side of a right triangle, √(3² + 4²) = 5, without overflow problems.
  • round goes to the nearest whole number. A value exactly halfway goes up, so 2.5 becomes 3 but −2.5 becomes −2.
  • floor always goes down and ceil always goes up. rint sends halfway values to the nearest even number, so 2.5 becomes 2.0 and 3.5 becomes 4.0.
  • With two int values, / drops the fraction: 7 / 2 is 3, and −7 / 2 is −3. Math.floorDiv rounds down instead, giving −4.
  • % keeps the sign of the left number, so −7 % 3 is −1. Math.floorMod always gives a result from 0 up to the divisor, which is what you want for clock times and circular lists.
  • The trig functions use radians. Convert degrees first with Math.toRadians.
  • 0.1 + 0.2 is not exactly 0.3, because a double stores most decimals approximately. Format the output with %.2f, or use BigDecimal for money.
  • Math.addExact throws an exception on overflow instead of silently wrapping to a negative number.
Valueroundfloorceilrint
2.422.03.02.0
2.532.03.02.0
3.543.04.04.0
−2.5−2−3.0−2.0−2.0

Random Numbers

A Random object makes a stream of numbers that look random. If you give it a seed, such as new Random(42), it makes the same numbers every run. That is very useful for testing and for this lesson, because your output will match ours. Without a seed, you get different numbers each time.

import java.util.*;
import java.util.stream.*;

public class Main {
    public static void main(String[] args) {
        Random r = new Random(42);          // fixed seed: same numbers every run
        System.out.print("Dice rolls : ");
        for (int i = 0; i < 10; i++) System.out.print((r.nextInt(6) + 1) + " ");
        System.out.println();

        System.out.println("Between 50 and 100 : " + r.nextInt(50, 101));
        System.out.printf("Random double      : %.4f%n", r.nextDouble());

        // Count 60,000 rolls: each face should appear about 10,000 times
        int[] count = new int[7];
        Random big = new Random(7);
        for (int i = 0; i < 60_000; i++) count[big.nextInt(6) + 1]++;
        System.out.println("Counts of 1..6     : " + Arrays.toString(Arrays.copyOfRange(count, 1, 7)));

        // Shuffle a list of names to pick a random order
        List<String> team = new ArrayList<>(List.of("Rafi", "Nusrat", "Imran", "Mim", "Sabbir"));
        Collections.shuffle(team, new Random(3));
        System.out.println("Speaking order     : " + team);

        // 6-digit one-time code, always 6 digits (leading zeros kept)
        int code = new Random(99).nextInt(1_000_000);
        System.out.println("OTP                : " + String.format("%06d", code));

        // Stream of random ints
        List<Integer> lottery = new Random(5).ints(1, 50).distinct().limit(6)
            .sorted().boxed().collect(Collectors.toList());
        System.out.println("Lottery numbers    : " + lottery);
    }
}

Output

Dice rolls : 3 4 1 3 1 2 6 3 2 6 
Between 50 and 100 : 64
Random double      : 0.4513
Counts of 1..6     : [10018, 9900, 9996, 9938, 10109, 10039]
Speaking order     : [Mim, Nusrat, Rafi, Imran, Sabbir]
OTP                : 465787
Lottery numbers    : [1, 5, 33, 36, 40, 45]
  • nextInt(6) gives 0 to 5. Adding 1 gives a dice roll from 1 to 6.
  • nextInt(50, 101) gives 50 to 100. The first number is included and the second is not.
  • In 60,000 rolls each face came up close to 10,000 times. That is a quick check that the numbers are spread evenly.
  • Collections.shuffle puts a list in random order, which is a fair way to choose who speaks first.
  • String.format("%06d", code) pads with zeros, so a code like 4521 is shown as 004521 and is always six digits.
  • ints(1, 50).distinct().limit(6) makes a stream of six different numbers from 1 to 49, like a lottery draw.
NeedUse
Quick random numbernew Random().nextInt(n)
Same numbers every run (tests)new Random(seed)
Many threads at onceThreadLocalRandom.current().nextInt(a, b)
Passwords, OTPs, tokensjava.security.SecureRandom
A double from 0.0 up to 1.0Math.random()

For anything secret, such as a real login code, use SecureRandom. A normal Random can be predicted by someone who sees a few of its numbers. We used a seeded Random above only so the output stays the same.

Common Mistakes

  1. Dividing two ints and expecting a fraction. 5 / 2 is 2. Write 5 / 2.0 or cast one side to double.
  2. Off-by-one ranges. nextInt(6) never returns 6. Add 1 for a dice roll.
  3. Creating a new Random inside a loop. Make one object and reuse it.
  4. Comparing doubles with ==. Check that the difference is tiny instead, for example Math.abs(a - b) < 1e-9.
  5. Using % for wrap-around with negative numbers. Use Math.floorMod.

Practice Exercises

Exercise 1. A shop rounds every bill up to the next 10 Taka. Write an expression that turns 437 into 440 and 430 into 430.

Show answer
int bill = 437;
int rounded = (int) Math.ceil(bill / 10.0) * 10;   // 440
// Integer-only version: ((bill + 9) / 10) * 10

Dividing by 10.0 keeps the fraction (43.7), ceil moves it up to 44.0, and multiplying by 10 gives 440. For 430 the division gives exactly 43.0, so it stays 430.

Exercise 2. Today is day 5 of the week (Friday, if Sunday is 0). Which day is it 10 days ago?

Show answer
int day = Math.floorMod(5 - 10, 7);   // 2, Tuesday
// (5 - 10) % 7 would give -5, which is not a valid day

Frequently Asked Questions

Why does Math.round(2.5) give 3 but Math.round(-2.5) give -2?

Math.round adds 0.5 and then rounds down. For 2.5 that gives 3. For -2.5 it gives -2.0, which rounds down to -2. So halfway values always move towards positive infinity.

Is Math.random() good enough for passwords?

No. Math.random and java.util.Random are fine for games and tests, but their numbers can be predicted. Use java.security.SecureRandom for passwords, one-time codes and security tokens.

Summary

  • Math methods are static; pow and sqrt return double.
  • round goes to the nearest number, floor down, ceil up, and rint to the nearest even number at halfway.
  • Integer / drops the fraction; use floorDiv and floorMod for negatives.
  • Random with a seed repeats its numbers; nextInt(a, b) includes a but not b.
  • Use SecureRandom for anything secret.

Next: Java Character Class and Unicode.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *