EMZETT.
Login

Math Class

In short: Java’s built-in class java.lang.Math with static methods for mathematical operations — square root, power, rounding, random numbers, and more.

In more detail: All methods are static, so they’re called directly via the class name, with no object created: Math.sqrt(16), Math.pow(2, 10), Math.max(a, b), Math.random(). Since the class is part of java.lang, no explicit import is needed for it.

In Depth

double root = Math.sqrt(16);         // 4.0
double power = Math.pow(2, 10);       // 1024.0
int maximum = Math.max(5, 12);         // 12
int minimum = Math.min(5, 12);         // 5
int absolute = Math.abs(-7);            // 7
double random = Math.random();         // 0.0 to (exclusive) 1.0
 
// Rounding - three different meanings!
long rounded = Math.round(4.5);   // 5 - normal commercial rounding
double roundedUp = Math.ceil(4.1);  // 5.0 - always round up
double roundedDown = Math.floor(4.9);  // 4.0 - always round down
 
// Random number in a specific range (e.g. 1 to 6, like a die)
int die = (int) (Math.random() * 6) + 1;

Math.random() always returns a double between 0.0 (inclusive) and 1.0 (exclusive) — to generate an integer within a specific range from it, you have to multiply by the range size yourself, cast to int (cuts off the decimal places, so effectively always rounds down), and add the starting value. For more serious random-number use cases (e.g. several random numbers with a reproducible seed for tests), the java.util.Random class is more flexible, since it provides direct methods like nextInt(6) for a range and accepts an explicit starting value (seed). Math.round(double) returns a long for a double argument (an int for float) — a common casting trap when the result is meant to be assigned directly to an int variable.

See also: double, Type Casting