The java.lang.Math class contains a comprehensive suite of static mathematical methods for performing basic numeric calculations, logarithms, square roots, and trigonometric calculations.
java.lang.Math Methodspublic class MathDemo {
public static void main(String[] args) {
// Mathematical Constants:
System.out.println("PI: " + Math.PI); // 3.141592653589793
System.out.println("E: " + Math.E); // 2.718281828459045
// Fundamental Functions:
System.out.println("Absolute: " + Math.abs(-45)); // 45
System.out.println("Max (10,20): " + Math.max(10, 20)); // 20
System.out.println("Min (10,20): " + Math.min(10, 20)); // 10
System.out.println("Power (2^8): " + Math.pow(2, 8)); // 256.0
System.out.println("Square Root: " + Math.sqrt(81)); // 9.0
// Rounding Functions:
System.out.println("Ceil (4.1): " + Math.ceil(4.1)); // 5.0 (Rounds UP)
System.out.println("Floor (4.9): " + Math.floor(4.9)); // 4.0 (Rounds DOWN)
System.out.println("Round (4.5): " + Math.round(4.5)); // 5 (Nearest int)
}
}
To generate an integer between min and max (inclusive) using Math.random():
// Formula: (int)(Math.random() * (max - min + 1)) + min
int min = 10;
int max = 50;
int randomNum = (int)(Math.random() * (max - min + 1)) + min;
System.out.println("Random Number between 10 and 50: " + randomNum);
Exam Question: "What is the difference between Math.random() and java.util.Random?"
Answer: Math.random() is a convenience method that internally delegates to a singleton java.util.Random instance, returning only a double. java.util.Random is a dedicated class that allows creating independent instances with seed values, producing typed random primitives (nextInt(), nextBoolean(), nextLong()).
Now let us step into robust error recovery: Exception Handling architecture. Proceed to: Java Exception Hierarchy →
Accelerate your Java mastery by studying these tightly connected core tutorials:
Numerical wrapper objects.
Basic arithmetic operations.
Handling ArithmeticException.
Mathematical methods cheat sheet.