Java Math Class
In this page:
Basic Math Operations
The Math class provides static methods for basic operations, like Math.abs() for absolute value and Math.max()/Math.min() for comparisons, without needing to instantiate anything.
Example: Basic Math Operations
public class Main {
public static void main(String[] args) {
System.out.println(Math.abs(-5));
System.out.println(Math.max(3, 7));
System.out.println(Math.min(3, 7));
}
}
Login to try C/C++/Java/PHP code in the editor
Rounding Operations
Math.round(), Math.floor(), and Math.ceil() each round differently — nearest, down, and up respectively — and choosing the wrong one is a common source of off-by-one bugs in numeric code.
Example: Rounding Operations
public class Main {
public static void main(String[] args) {
System.out.println(Math.round(4.5)); // nearest
System.out.println(Math.floor(4.9)); // down
System.out.println(Math.ceil(4.1)); // up
}
}
Login to try C/C++/Java/PHP code in the editor
Exponents and Roots
Math.pow(base, exponent) computes exponents and Math.sqrt() computes square roots, both returning a double even when the inputs are integers. Note that Math.pow is generally slower than direct multiplication for small fixed integer powers, so 'x * x' often beats Math.pow(x, 2).
Example: Exponents and Roots
public class Main {
public static void main(String[] args) {
System.out.println(Math.pow(2, 3));
System.out.println(Math.sqrt(16));
}
}
Login to try C/C++/Java/PHP code in the editor
Trigonometry and Constants
Math.sin(), Math.cos(), and constants like Math.PI support trigonometric and geometric calculations, all working in radians rather than degrees by default. Converting between degrees and radians with Math.toRadians() and Math.toDegrees() is a common companion step when working with real-world angle values.
Example: Trigonometry and Constants
public class Main {
public static void main(String[] args) {
System.out.println(Math.PI);
System.out.println(Math.sin(Math.PI / 2)); // radians, not degrees
}
}
Login to try C/C++/Java/PHP code in the editor
Exact Arithmetic
Methods like Math.addExact() throw an ArithmeticException on overflow instead of silently wrapping around, which is valuable when exact correctness matters more than raw speed.
Example: Exact Arithmetic
public class Main {
public static void main(String[] args) {
try {
Math.addExact(Integer.MAX_VALUE, 1); // throws instead of silently wrapping
} catch (ArithmeticException e) {
System.out.println("Overflow detected: " + e.getMessage());
}
}
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: