Nearby lessons

52 of 125

Java - Math Class

📌 What You Will Learn
  • Use the Math class for common maths operations
  • Know the important Math methods
  • Generate random numbers with Math.random()

Learn the Java Math class — ready-made static methods for maximum, minimum, power, square root, absolute value, rounding and random numbers.

What is the Math Class?

The Math class lives in java.lang (so no import is needed) and gives you static methods for common maths operations. Call them with the class name: Math.max(...).

In simple words: Math is a free calculator built into Java — you call Math.something() and it does the maths for you.

Important Methods

MethodWhat it doesExample
Math.max(a, b)Larger of two valuesMath.max(4, 9) → 9
Math.min(a, b)Smaller of two valuesMath.min(4, 9) → 4
Math.pow(a, b)a raised to power bMath.pow(2, 3) → 8.0
Math.sqrt(x)Square rootMath.sqrt(25) → 5.0
Math.abs(x)Absolute valueMath.abs(-7) → 7
Math.round(x)Rounds to nearest longMath.round(3.6) → 4
Math.random()Random double in [0.0, 1.0)Math.random() → 0.47...

Math in Action

See the most-used methods working in one program:

Example03
JCode Cell
1public class MathDemo {
2 public static void main(String[] args) {
3 System.out.println("Max : " + Math.max(45, 78));
4 System.out.println("Min : " + Math.min(45, 78));
5 System.out.println("Pow : " + Math.pow(2, 10));
6 System.out.println("Sqrt : " + Math.sqrt(144));
7 System.out.println("Abs : " + Math.abs(-99));
8 System.out.println("Round : " + Math.round(3.6));
9 }
10}
Output
Max    : 78
Min    : 45
Pow    : 1024.0
Sqrt   : 12.0
Abs    : 99
Round  : 4

Random Numbers

Math.random() returns a double between 0.0 (inclusive) and 1.0 (exclusive). Multiply and cast to get a whole number in a range:

Example04
JCode Cell
1public class RandomDemo {
2 public static void main(String[] args) {
3 // random integer between 1 and 6 (like a dice)
4 int dice = (int) (Math.random() * 6) + 1;
5 System.out.println("Dice : " + dice);
6 }
7}
Output
Dice : 4
📝 Key Takeaways
  • Math is a final class in java.lang — no import needed
  • Methods like max, min, pow, sqrt, abs are all static
  • Math.random() gives a double between 0.0 and 1.0