The Math class in Java is a utility class that provides several static methods for performing basic mathematical operations. It is part of the java.lang package, so you don’t need to import it explicitly. The methods in the Math class are designed to handle common mathematical tasks like rounding, exponentiation, logarithmic calculations, trigonometric functions, and random number generation.
Arithmetic Functions
There are many arithmetic functions like abs(double a), abs(int a), max(double a, double b), min(double a, double b), etc.
public class ArithmeticMathExample {
public static void main(String[] args) {
System.out.println("Absolute value of -15.4: " + Math.abs(-15.5)); // 15.4
System.out.println("Absolute value of -7: " + Math.abs(-7)); // 7
System.out.println("Max of 15.4 and 25.5: " + Math.max(15.4, 25.5)); // 25.5
System.out.println("Min of 15.4 and 25.5: " + Math.min(15.4, 25.5)); // 15.4
}
}
Rounding Functions
There are many round functions
round(float a), round(double a)
Rounds the argument to the nearest integer. If the argument is exactly halfway between two integers, it rounds up.
public class MathRoundExample {
public static void main(String[] args) {
System.out.println("Round of 4.7f: " + Math.round(4.7f)); // 4
System.out.println("Round of 5.3: " + Math.round(5.3)); // 5
System.out.println("Round of 5.5: " + Math.round(5.5)); // 6
}
}
ceil(double a)
Rounds the argument up to the nearest integer, even if it’s already an integer.
public class MathCeilExample {
public static void main(String[] args) {
System.out.println("Ceil of 5.4: " + Math.ceil(5.4)); // 6.0
System.out.println("Ceil of 5.9: " + Math.ceil(5.9)); // 6.0
}
}
floor(double a)
Rounds the argument down to the nearest integer.
public class MathFloorExample {
public static void main(String[] args) {
System.out.println("Floor of 5.4: " + Math.floor(5.4)); // 5.0
System.out.println("Floor of 5.9: " + Math.floor(5.9)); // 5.0
}
}
Random Number Generation
Returns a random number between 0.0 (inclusive) and 1.0 (exclusive)
public class MathRandomExample {
public static void main(String[] args) {
double randomValue = Math.random();
System.out.println("Random number between 0.0 and 1.0: " + randomValue);
}
}
Generate a random integer between min and max
Suppose, we have min value is 0 and max value is 100
public class MathRandomExample {
public static void main(String[] args) {
int min = 1;
int max = 100;
double randomValue = (int)(Math.random() * (max - min + 1)) + min;
System.out.println("Random number between 0 and 100: " + randomValue);
}
}
Mathematical Constants
The Math class defines a few useful constants:
- Math.PI: The value of π (approximately 3.14159).
- Math.E: The value of Euler’s number e (approximately 2.71828).
Example:
public class MathConstantsExample {
public static void main(String[] args) {
System.out.println("Value of Pi: " + Math.PI);
System.out.println("Value of Euler's number: " + Math.E);
}
}
Output:
Value of Euler’s number: 2.718281828459045