Numbers in Java
Working with numbers in Java means choosing among several numeric primitives and knowing how the standard library rounds out what the primitives alone can't do. The Math class supplies static methods for anything beyond basic arithmetic — Math.pow, Math.sqrt, Math.abs, Math.max, Math.round, and dozens more — all callable without creating an object.
A quieter but important detail: dividing two integers always produces an integer result, discarding any remainder, even when the mathematical answer clearly has a fractional part. Getting a decimal result out of integer inputs means making at least one operand a double first, typically by casting or multiplying by 1.0.
Integer division truncates
7 / 2 evaluates to 3, not 3.5 — dividing two ints always produces an int, discarding the remainder entirely.
Getting a decimal result
Making at least one operand a double, such as by casting one side, forces the division itself to produce a fractional result instead of a truncated one.
The modulo operator
The percent sign returns the remainder of a division: 7 % 2 is 1, which is genuinely useful on its own, not just a side effect of division.
The Math class
Static methods like Math.pow, Math.sqrt, and Math.abs cover everything ordinary arithmetic operators don't, with no object to construct first.
Rounding
Math.round rounds to the nearest whole number, while a narrowing cast on a decimal always truncates toward zero instead — the two are not interchangeable.
public class NumberDemo { public static void main(String[] args) { int a = 7, b = 2; System.out.println("Integer division: " + (a / b)); System.out.println("Decimal division: " + (a / (double) b)); System.out.println("Remainder: " + (a % b)); System.out.println("Square root of 49: " + Math.sqrt(49)); }}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in Java yourself — building beats watching.