HOME HTML EDITOR C JAVA PHP

Java Math Methods

In Java, the Math class provides many built-in methods to perform mathematical operations such as square roots, powers, rounding, absolute values, and trigonometric calculations. The Math class belongs to java.lang package, so you do not need to import it explicitly.

All methods in the Math class are static, which means you can call them directly using Math.methodName().

1. Math.max() and Math.min()

These methods return the maximum or minimum value between two numbers.

System.out.println(Math.max(10, 20));
System.out.println(Math.min(10, 20));

2. Math.sqrt()

The sqrt() method returns the square root of a number.

System.out.println(Math.sqrt(64));

3. Math.pow()

The pow() method returns the value of a number raised to the power of another number.

System.out.println(Math.pow(2, 3));

4. Math.abs()

The abs() method returns the absolute (positive) value of a number.

System.out.println(Math.abs(-15));

5. Math.random()

The random() method generates a random number between 0.0 (inclusive) and 1.0 (exclusive).

System.out.println(Math.random());

To generate a random number within a range:

int number = (int)(Math.random() * 100);
System.out.println(number);

6. Math.round()

The round() method rounds a number to the nearest integer.

System.out.println(Math.round(4.6));
System.out.println(Math.round(4.4));

7. Math.ceil() and Math.floor()

ceil() rounds up to the nearest integer, while floor() rounds down.

System.out.println(Math.ceil(4.3));
System.out.println(Math.floor(4.7));

8. Math.cbrt()

The cbrt() method returns the cube root of a number.

System.out.println(Math.cbrt(27));

9. Trigonometric Methods

The Math class also provides trigonometric methods like sin(), cos(), and tan(). These methods use radians as input.

System.out.println(Math.sin(Math.toRadians(30)));
System.out.println(Math.cos(Math.toRadians(60)));

10. Math Constants

The Math class also provides important constants:

System.out.println(Math.PI);
System.out.println(Math.E);

Why Java Math Methods Are Important?

Helpful Tip: Always use built-in Math methods instead of writing complex mathematical logic manually. They are optimized and reliable.