Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 201 ยท Variables and Types

Working with Numbers

Understand how Java numbers really behave - integer division and remainder, silent overflow and Math.addExact, floating-point precision, NaN, Infinity and when to use BigDecimal.

Numbers in Java look like the numbers you know from school, but they live inside fixed-size boxes of bits. That has consequences. An int can run out of room and wrap around to a negative value. Dividing two integers throws away the fraction. And 0.1 + 0.2 is not exactly 0.3.

None of this is a bug in Java: every mainstream language that uses the same hardware number formats behaves the same way. Professionals simply know the rules and the tools that tame them. This lesson walks through each surprise, shows you a runnable example, and gives you the safe pattern to use instead.

You already know the numeric types from Primitive Data Types. Here we focus on how they behave when you calculate with them.

Integer division drops the fraction

When both operands of / are integers, Java performs integer division: it computes the exact quotient and then truncates toward zero, throwing away everything after the decimal point. It does not round.

Java Integer division vs floating-point division

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The wrong line is one of the most common bugs in beginner and professional code alike. Storing the result in a double doesn't help, because total / count is evaluated as int arithmetic before the assignment happens: 17 / 4 is 4, which then becomes 4.0. Convert one operand first, either with a cast like (double) total or by multiplying by 1.0.

Integer division is often exactly what you want, though. Splitting a number into parts is a classic use:

Java
int totalSeconds = 3_725;
int hours = totalSeconds / 3600;          // 1
int minutes = totalSeconds % 3600 / 60;   // 2
int seconds = totalSeconds % 60;          // 5

The remainder operator %

The % operator gives the remainder left over after integer division. 17 % 5 is 2, because 17 = 3 ร— 5 + 2. It's called "modulo" informally, but strictly speaking Java's % is a remainder, and the difference shows up with negative numbers: the result takes the sign of the left operand.

Java Remainders, including negative ones

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

So never test oddness with n % 2 == 1: it fails for negative numbers. Use n % 2 != 0. When you need a "wrap-around" index that is never negative, such as a day of the week or a position in a circular buffer, use Math.floorMod. The Math class lesson covers it with floorDiv.

% also works on double: 7.5 % 2 is 1.5. That's handy occasionally, but most remainder work uses integers.

Dividing by zero

What happens when you divide by zero depends on the types:

  • Integer division or remainder by zero throws an ArithmeticException with the message / by zero, and the program stops unless you catch it.
  • Floating-point division by zero does not throw. It produces Infinity, -Infinity or NaN (more on these below).
Java
int a = 10 / 0;          // throws ArithmeticException: / by zero
double b = 10.0 / 0;     // Infinity
double c = 0.0 / 0;      // NaN

So guard integer divisions where the divisor could be zero (for example, an average of an empty list). Exceptions are explained fully in Exceptions and try-catch.

Overflow wraps around silently

Every integer type has a fixed range. When a calculation goes past the end of that range, Java does not stop or warn you: the value wraps around to the other end, like a car odometer rolling over. This is called overflow.

Java Integer overflow

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Three lessons hide in this output:

  1. Integer.MAX_VALUE + 1 becomes -2147483648. In binary, adding one to the largest positive value flips the sign bit. (The Bitwise and Shift Operators lesson explains this two's-complement layout.)
  2. The year-in-milliseconds bug is subtle. Every number on the right is an int, so the multiplication runs in int and overflows to 1471228928 before the result is widened to long. Making the first factor a long (365L) makes the whole chain long arithmetic.
  3. Math.abs(Integer.MIN_VALUE) is still negative, because +2,147,483,648 doesn't fit in an int. There's one more negative value than positive values.

Catching overflow with Math.*Exact

When a wrong result would be dangerous (money, quantities, array sizes), ask Java to check for you. The Math methods addExact, subtractExact, multiplyExact, incrementExact, negateExact and toIntExact behave like the normal operators but throw an ArithmeticException instead of wrapping:

Java Overflow-checked arithmetic

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The last line ends the program on purpose with java.lang.ArithmeticException: integer overflow and a stack trace. That's the point: a loud failure is far better than a silently wrong number. Note that overloads exist for both int and long; with 100_000_000L the long version is chosen.

A quick rule of thumb: if a value can come from users, files or multiplication of other values, think about its maximum size. Use long when in doubt, Math.*Exact when overflow must never go unnoticed, and BigInteger when numbers can grow without limit (see BigInteger and BigDecimal).

Floating-point precision

double and float store numbers in binary scientific notation. Just as 1/3 can't be written exactly in decimal (0.3333โ€ฆ), many simple decimal fractions like 0.1 can't be written exactly in binary. Java stores the nearest representable value, and tiny errors appear when you combine them:

Java Floating-point rounding errors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Practical rules for floating point:

  • Never compare doubles with == after calculations. Check whether the difference is smaller than a tolerance you choose for your problem (1e-9 is common for values near 1).
  • Round for display, not for storage. Keep full precision while calculating and format at the end with String.format("%.2f", x) or printf. Formatting Strings covers the options.
  • Integers are exact. A double stores every whole number up to 2โตยณ (about 9 ร— 10ยนโต) exactly, but past that it can't even represent every integer.
  • Money needs exact decimals. Use BigDecimal or count whole cents in a long.

Here's what BigDecimal looks like, just as a preview:

Java
import java.math.BigDecimal;

BigDecimal price = new BigDecimal("0.10");   // pass a String, not a double
BigDecimal total = price.add(new BigDecimal("0.20"));
IO.println(total);   // 0.30, exactly

Infinity, NaN and negative zero

Floating-point types have a few special values that integers don't:

  • Infinity and -Infinity result from overflow or from dividing a nonzero number by zero. Double.POSITIVE_INFINITY and Double.NEGATIVE_INFINITY name them.
  • NaN ("not a number") results from undefined operations such as 0.0 / 0, Math.sqrt(-1) or Infinity - Infinity.
  • -0.0 exists too. It equals 0.0 with ==, but 1 / -0.0 is -Infinity.

NaN has a famous quirk: it isn't equal to anything, not even itself. So x == Double.NaN is always false. Use Double.isNaN(x) instead.

Java Special floating-point values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Because NaN spreads quietly through every later calculation, a single bad division can turn an entire report into NaN. Check inputs early with Double.isFinite(x), which is false for NaN and both infinities.

Useful constants and helpers

The wrapper classes hold constants and helper methods you'll use often:

Expression Meaning
Integer.MAX_VALUE, Integer.MIN_VALUE the int range: 2147483647 and -2147483648
Long.MAX_VALUE, Long.MIN_VALUE the long range
Double.MAX_VALUE the largest finite double, about 1.8 ร— 10ยณโฐโธ
Double.MIN_VALUE the smallest positive double, about 4.9 ร— 10โปยณยฒโด (not the most negative!)
Double.isNaN(x), Double.isFinite(x) test for special values
Integer.compare(a, b), Double.compare(a, b) negative, zero or positive, without overflow
Integer.sum(a, b), Integer.max(a, b) method versions of operators, handy with streams

Double.MIN_VALUE misleads many developers: the most negative double is -Double.MAX_VALUE.

Comparing with Integer.compare(a, b) instead of returning a - b matters too. The subtraction can overflow (Integer.MIN_VALUE - 1 is positive!), giving a wrong order. You'll see why this matters in Sorting with Comparable and Comparator.

Java Safe comparisons and the constants

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The last line shows the limit of double for integers: 2โตยณ + 1 = 9007199254740993 can't be stored exactly, so it prints 9.007199254740992E15.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does double avg = 9 / 2; store in avg?

    Both operands are int, so 9 / 2 is integer division and gives 4. Only then is 4 widened to the double 4.0.
  2. 2. What is -10 % 3 in Java?

    Java's remainder takes the sign of the left operand. 10 % 3 is 1, so -10 % 3 is -1. Math.floorMod(-10, 3) would give 2.
  3. 3. What does Integer.MAX_VALUE + 1 evaluate to?

    Normal int arithmetic overflows silently and wraps to Integer.MIN_VALUE. Only Math.addExact would throw.
  4. 4. Given double x = 0.0 / 0;, which test is true?

    0.0 / 0 is NaN, and NaN is never equal to anything, including itself, so the == checks are false. Double.isNaN is the correct test.
  5. 5. Why does long ms = 1000 * 60 * 60 * 24 * 30; give a wrong value?

    All literals are int, so the product is computed in int and overflows. Writing 1000L makes the whole chain long arithmetic.

Summary

  • / on two integers truncates toward zero. Convert an operand to double before dividing when you want a fraction.
  • % gives the remainder, with the sign of the left operand. Test oddness with n % 2 != 0; use Math.floorMod for non-negative wrap-around.
  • Integer division by zero throws ArithmeticException; floating-point division by zero gives Infinity or NaN.
  • Integer overflow wraps around silently. Use long literals (365L), Math.addExact and friends, or BigInteger.
  • Floating-point values are approximations: never compare them with ==, round only for display, and use BigDecimal for money.
  • NaN is not equal to itself; test it with Double.isNaN, and check inputs with Double.isFinite.
  • Double.MIN_VALUE is the smallest positive double, and Integer.compare is safer than subtracting.

Next: Characters and Booleans, where you'll explore char as a Unicode code unit, character arithmetic and boolean logic.