← Back to Core Java Course | Chapter 14: Advanced Topics | Lesson 3 of 6

Java Math Operations

Basic Arithmetic Operations

Java's basic arithmetic operators (+, -, *, /, %) work directly on numeric primitives, with % giving the remainder rather than a true modulo for negative operands. Mixing integer and floating-point operands in the same expression automatically promotes the result to a floating-point type.

Example: Basic Arithmetic Operations

java
public class Main {
	public static void main(String[] args) {
		System.out.println(10 + 3);
		System.out.println(10 % 3); // remainder
		System.out.println(-10 % 3); // not a true modulo for negatives
	}
}

Absolute and Power Functions

Math.abs() strips a value's sign to get its absolute magnitude, and Math.pow(base, exp) raises a number to a given power, both returning results appropriate to their input types.

Example: Absolute and Power Functions

java
public class Main {
	public static void main(String[] args) {
		System.out.println(Math.abs(-7));
		System.out.println(Math.pow(2, 4));
	}
}

Square Root and Rounding

Math.sqrt() computes a square root as a double, and combining it with Math.round() or casting lets you get a clean integer result when the exact square root isn't needed. Casting the double result of Math.sqrt() back to an int truncates any decimal portion rather than rounding it, which is a common source of off-by-one bugs.

Example: Square Root and Rounding

java
public class Main {
	public static void main(String[] args) {
		double root = Math.sqrt(20);
		System.out.println(root);
		System.out.println(Math.round(root)); // clean integer result
	}
}

Min and Max Helpers

Math.max() and Math.min() return the larger or smaller of two values respectively, avoiding a manual if-else comparison for this extremely common operation. Both methods are overloaded to accept int, long, float, and double arguments, so they work seamlessly across Java's numeric types.

Example: Min and Max Helpers

java
public class Main {
	public static void main(String[] args) {
		System.out.println(Math.max(4, 9));
		System.out.println(Math.min(4, 9));
	}
}

Generating Random Numbers

Generating a random number typically pairs Math.random() (which returns a double between 0.0 and 1.0) with scaling and casting to land within whatever integer range you actually need.

Example: Generating Random Numbers

java
public class Main {
	public static void main(String[] args) {
		int random = (int) (Math.random() * 10); // scaled and cast to an int range
		System.out.println(random >= 0 && random < 10);
	}
}
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

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.