Source: Introduction to Computer Science Concepts and Programming (Texas A&M University)
Tags: Java Math class, Math.abs, Math.pow, Math.sqrt, Math.random, Math.round, Math.min, Math.max, Math.floor, Math.ceil, random number generation Java, static methods Java, java.lang.Math
Difficulty: Beginner Prerequisites: Basic Java syntax, variables, data types, arithmetic operators.
Once you can read numbers from the user (via Scanner), you need tools to do something meaningful with them. The Math class is Java's built-in maths toolkit: absolute values, exponents, square roots, rounding, and random number generation. Unlike Scanner, you never need to import or instantiate it. It is always available, and every method is called directly on the class name. This topic appears in nearly every programming assignment that involves calculations, and it sets up later work on simulations, games, and algorithms.
Java's Math class lives in java.lang and is auto-imported into every program. All its methods are static, so you call them as Math.methodName() with no object creation. The key methods are abs(), pow(), sqrt(), random(), round(), min(), max(), floor(), and ceil(). The random() method is the basis for generating random integers within any range.
Math class
A final class in the java.lang package containing static methods for common mathematical operations. It is automatically imported, so no import statement is needed.
Think of it as a scientific calculator that is always in your pocket when you write Java.
Static method
A method that belongs to the class itself rather than to any particular object (instance) of the class. Called using the class name, e.g., Math.abs(-5).
In simple terms, you do not create a Math object. You just say Math. and then the method name.
Math.abs()
Returns the absolute value of the argument (its distance from zero, always non-negative).
Think of it as a "make it positive" function. Math.abs(-7) gives 7; Math.abs(5.67) gives 5.67.
Math.pow()
Takes two arguments (base, exponent) and returns the base raised to the power of the exponent, as a double.
In simple terms, Math.pow(4.5, 2) means 4.5 squared, which is 20.25.
Math.sqrt()
Returns the positive square root of the argument, as a double.
In simple terms, Math.sqrt(25) gives 5.0. This is the inverse of squaring a number.
Math.random()
Returns a pseudorandom double that is greater than or equal to 0.0 and strictly less than 1.0.
Think of it as rolling an infinitely-sided die that gives you a decimal between 0 and just-under-1. You then scale and shift it to get the range you need.
Math.round()
Rounds a floating-point number to the nearest integer. Returns a long when given a double, or an int when given a float.
In simple terms, 3.6 rounds to 4, and 3.4 rounds to 3.
Math.min() / Math.max()
min(a, b) returns whichever of the two arguments is smaller. max(a, b) returns whichever is larger.
Think of them as a quick comparison shortcut. No if-statement needed.
Math.floor() / Math.ceil()
floor(x) rounds x down to the nearest integer (towards negative infinity). ceil(x) rounds x up (towards positive infinity). Both return a double.
In simple terms, floor(3.9) is 3.0 and ceil(3.1) is 4.0.
The Math class is in the java.lang package, which Java imports automatically for every program.
You never write import java.lang.Math; (though it would not cause an error if you did).
You also never write Math m = new Math();. All methods are static, so you call them directly on the class name.
Accepts int, long, float, or double. Returns the same type.
Useful anywhere you need a non-negative result, e.g., computing the distance between two points on a number line.
Math.abs(-7); // returns 7
Math.abs(5.67); // returns 5.67
Signature: Math.pow(double base, double exponent) returns a double.
Java has no exponent operator (no ** or ^ for powers), so Math.pow() is the standard way.
Math.pow(4.5, 2); // returns 20.25
Math.pow(2, 10); // returns 1024.0
Returns a double.
Passing a negative number returns NaN (Not a Number), not an error.
Math.sqrt(25); // returns 5.0
Math.sqrt(2); // returns 1.4142135623730951
Math.round(x): standard rounding (0.5 rounds up).
Math.floor(x): always rounds down. Returns a double.
Math.ceil(x): always rounds up. Returns a double.
Math.round(3.6); // returns 4
Math.floor(3.9); // returns 3.0
Math.ceil(3.1); // returns 4.0
Math.min(a, b) and Math.max(a, b) each take exactly two arguments.
To find the min or max of three or more values, nest the calls: Math.min(a, Math.min(b, c)).
Math.random() returns a double in the range [0.0, 1.0) (inclusive of 0, exclusive of 1).
To produce random integers in a specific range, scale and shift:
// Random decimal between 0 and 10 (exclusive)
Math.random() * 10;
// Random integer between 0 and 9
(int)(Math.random() * 10);
// Random integer between 1 and 10
(int)(Math.random() * 10) + 1;
// Random integer between 8 and 107
(int)(Math.random() * 100) + 8;
General formula:
int randNumber = (int)(Math.random() * range) + startingValue;
Where range = total count of possible values = (end - start + 1), and startingValue = the lowest value in the desired range.
Two six-sided dice, each producing 1 through 6:
int firstDie = (int)(Math.random() * 6) + 1;
int secondDie = (int)(Math.random() * 6) + 1;
int sum = firstDie + secondDie;
The sum ranges from 2 to 12, but the probabilities are not uniform. A sum of 7 is far more likely than a sum of 2 or 12 because there are more combinations that produce 7. This mirrors real dice, which is exactly what you want. Do not generate a single random number from 2 to 12 directly, because that would give each sum equal probability, which is unrealistic.
Random integer in a range:
int result = (int)(Math.random() * (end - start + 1)) + start;
start = lowest desired value
end = highest desired value
(end - start + 1) = total number of possible values
Math.pow() and Math.sqrt() appear constantly in physics simulations (projectile motion, energy calculations) and financial formulas (compound interest). Math.random() is the engine behind any simulation, from shuffling a deck of cards to modelling traffic flow. Game developers use it for damage rolls, loot drops, and procedural content. Math.abs() is everywhere you compute distances.
Students sometimes try to create an instance of Math (Math m = new Math();). This is unnecessary and will not compile; Math's constructor is private. All methods are static.
Students often use ^ to mean "to the power of" in Java. In Java, ^ is the bitwise XOR operator, not exponentiation. Use Math.pow() instead.
Students forget that Math.random() never returns exactly 1.0. The range is [0.0, 1.0), so 1.0 is excluded. This matters when calculating range boundaries.
When simulating dice, students sometimes generate a single random number from 2 to 12 for the sum. This produces a uniform distribution, which is wrong. You must roll each die separately and add the results to preserve the correct probability distribution.
⚠️ The random integer formula (int)(Math.random() * range) + start is very commonly tested. Be able to determine the output range given specific values, and be able to write the expression given a desired range.
⚠️ Know that Math.pow() returns a double, even if both arguments look like integers. If you need an int result, you must cast.
⚠️ Distinguish between Math.round(), Math.floor(), and Math.ceil(). Exam questions often present a specific value (e.g., 3.5 or -2.3) and ask what each method returns.
⚠️ Remember that Math.sqrt() of a negative number returns NaN, not an exception.
⚠️ The dice simulation question (why you roll each die separately rather than generating one number from 2 to 12) has appeared in past exams and is a favourite conceptual question.
True or false: You must write import java.lang.Math; before using Math methods.
Fill in the blank: Math.pow(3, 4) returns ___________.
True or false: Math.random() can return exactly 1.0.
Fill in the blank: To generate a random integer between 5 and 15 (inclusive), write (int)(Math.random() * ___) + ___.
True or false: Math.floor(-2.3) returns -2.0.
Answers: 1. False (java.lang is auto-imported). 2. 81.0. 3. False (the upper bound is exclusive). 4. 11, 5. 5. False (it returns -3.0, because floor rounds towards negative infinity).
Q: What does Math.abs(-15) return?
A: 15.
Q: Write a Java expression that computes 2 to the power of 8.
A: Math.pow(2, 8) (returns 256.0 as a double).
Q: Why does Math.random() * 6 not produce values from 1 to 6?
A: Math.random() * 6 produces a double in [0.0, 6.0). Casting to int with (int) gives values 0 through 5. You need to add 1 to shift the range to 1 through 6.
Q: What is the difference between Math.round(3.5) and Math.floor(3.5)?
A: Math.round(3.5) returns 4 (rounds to nearest, with 0.5 rounding up). Math.floor(3.5) returns 3.0 (always rounds down).
Q: A student writes (int)(Math.random() * 12) + 2 to simulate the sum of two dice. Explain why this is incorrect.
A: This generates each value from 2 to 13 with equal probability (and 13 is too high). Real dice sums are not uniformly distributed: a sum of 7 is much more likely than a sum of 2. The correct approach is to roll each die independently ((int)(Math.random() * 6) + 1 for each) and add the results, which preserves the natural probability distribution.
This material connects to the Scanner class notes, since most programs will read user input and then apply Math methods to it (e.g., computing the hypotenuse from two side lengths the user provides). It also sets up later topics on loops and conditionals: once you can generate random numbers, you can build games and simulations that use loops to repeat random events. The concept of static methods introduced here will reappear when you write your own utility methods later in the course.
Java Math class, Math.abs, Math.pow, Math.sqrt, Math.random, Math.round, Math.floor, Math.ceil, Math.min, Math.max, static methods Java, random number generation Java, random integer range Java, dice simulation Java, java.lang.Math, exponentiation Java, square root Java, rounding Java, CSCE intro programming, Texas A&M CS