← Back to Core Java Course | Chapter 13: Advanced Topics & Reference | Lesson 1 of 10

Java Math Class

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

java
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));
	}
}

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

java
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
	}
}

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

java
public class Main {
	public static void main(String[] args) {
		System.out.println(Math.pow(2, 3));
		System.out.println(Math.sqrt(16));
	}
}

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

java
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
	}
}

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

java
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 run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.