Java Math Operations
In this page:
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
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
}
}
Login to try C/C++/Java/PHP code in the editor
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
public class Main {
public static void main(String[] args) {
System.out.println(Math.abs(-7));
System.out.println(Math.pow(2, 4));
}
}
Login to try C/C++/Java/PHP code in the editor
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
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
}
}
Login to try C/C++/Java/PHP code in the editor
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
public class Main {
public static void main(String[] args) {
System.out.println(Math.max(4, 9));
System.out.println(Math.min(4, 9));
}
}
Login to try C/C++/Java/PHP code in the editor
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
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);
}
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: