The Java Math
library provides a wide range of mathematical functions and constants that are useful for performing mathematical operations. This library is part of the java.lang
package, so it’s automatically available and does not require an import statement. Here, we’ll explore various methods within the Math
library, accompanied by examples and explanations.
Constants in the Math Library
PI: The Math.PI
constant provides the value of π (pi).
1 |
System.out.println(Math.PI); // Output: 3.141592653589793 |
E: The Math.E
constant represents the base of natural logarithms, e.
1 |
System.out.println(Math.E); // Output: 2.718281828459045 |
Commonly Used Math Methods
Math.abs()
Returns the absolute value of a given number.
1 |
System.out.println(Math.abs(-4.7)); // Output: 4.7 |
Math.sqrt()
Calculates the square root of a number.
1 |
System.out.println(Math.sqrt(16)); // Output: 4.0 |
Math.pow()
Raises a number to the power of another number.
1 |
System.out.println(Math.pow(2, 3)); // Output: 8.0 |
Math.max()
and Math.min()
Determines the maximum or minimum of two numbers.
1 2 |
System.out.println(Math.max(5, 10)); // Output: 10 System.out.println(Math.min(5, 10)); // Output: 5 |
Math.round()
Rounds a floating-point number to the nearest integer
1 2 |
System.out.println(Math.round(4.3)); // Output: 4 System.out.println(Math.round(4.7)); // Output: 5 |
Math.ceil()
and Math.floor()
Math.ceil()
rounds a number upward to the nearest integer, while Math.floor()
rounds a number downward to the nearest integer.
1 2 |
System.out.println(Math.ceil(4.2)); // Output: 5.0 System.out.println(Math.floor(4.8)); // Output: 4.0 |
Math.random()
Generates a random double number greater than or equal to 0.0 and less than 1.0.
1 |
System.out.println(Math.random()); // Output varies |
To generate a random integer within a range, you can use Math.random()
like this:
1 2 3 4 |
int min = 1; int max = 10; int randomNum = (int)(Math.random() * (max - min + 1)) + min; System.out.println(randomNum); // Output varies between 1 and 10 |
Trigonometric Methods
The Math
library also includes methods for trigonometric operations, such as sin()
, cos()
, and tan()
, which expect an angle in radians.
1 2 3 |
System.out.println(Math.sin(Math.PI / 2)); // Output: 1.0 System.out.println(Math.cos(Math.PI)); // Output: -1.0 System.out.println(Math.tan(Math.PI / 4)); // Output: 1.0 |
To convert degrees to radians, you can use Math.toRadians()
, and to convert radians to degrees, use Math.toDegrees(
1 2 3 |
double degrees = 90; double radians = Math.toRadians(degrees); System.out.println(Math.sin(radians)); // Output: 1.0 |
The Java Math
library is an essential tool for dealing with mathematical computations, offering a robust set of functions and constants to handle a wide range of mathematical tasks efficiently.