Numbers, overflow and casts
Whole numbers in Java are fixed-width binary numbers, and a fractional number is IEEE 754. Both behave in ways that surprise a person and none that surprise the machine: a division of two integers discards the fraction, an int wraps around at its maximum, and 0.1 + 0.2 is not 0.3. This lesson reads each of them from a run.
Integer division and the remainder
The / operator between two integers gives an integer: the fraction is discarded, not rounded. The % operator gives what is left, and with a negative left operand it keeps the sign of that operand. A fractional operand makes the division a floating-point one.
public class Division {
public static void main(String[] args) {
int a = 7;
int b = 2;
System.out.println("7 / 2 = " + (a / b));
System.out.println("7 % 2 = " + (a % b));
System.out.println("-7 / 2 = " + (-a / b));
System.out.println("-7 % 2 = " + (-a % b));
System.out.println("7 / 2.0 = " + (a / 2.0));
System.out.println("7.0 / 0 = " + (7.0 / 0));
System.out.println("0.0 / 0 = " + (0.0 / 0));
}
}
javac -Xlint:all Division.java
java Division
7 / 2 = 3
7 % 2 = 1
-7 / 2 = -3
-7 % 2 = -1
7 / 2.0 = 3.5
7.0 / 0 = Infinity
0.0 / 0 = NaN
The division of two integers by zero throws an ArithmeticException, because there is no integer to return; the floating-point division returns Infinity or NaN instead of failing, and both are values a later comparison has to expect.
Overflow
An int has 32 bits, and the arithmetic does not check. Integer.MAX_VALUE + 1 wraps to the minimum, a negative number, and the program prints it without a warning. A long has room for the same value, and Math.addExact is the version of the addition that refuses to wrap.
public class Overflow {
public static void main(String[] args) {
int max = Integer.MAX_VALUE;
System.out.println("max: " + max);
System.out.println("max + 1: " + (max + 1));
long wide = max;
System.out.println("long: " + (wide + 1));
try {
System.out.println(Math.addExact(max, 1));
} catch (ArithmeticException error) {
System.out.println("addExact: " + error.getMessage());
}
long big = 3_000_000_000L;
System.out.println("big: " + big);
System.out.println("sum: " + (big + big));
}
}
javac -Xlint:all Overflow.java
java Overflow
max: 2147483647
max + 1: -2147483648
long: 2147483648
addExact: integer overflow
big: 3000000000
sum: 6000000000
The overflow happened before the value reached long: max + 1 is an int expression, and widening the result afterwards widens the wrong number. Write wide + 1 or (long) max + 1, and the sum is right. A long overflows in the same way at about nine quintillion, which is the point where a program reaches for BigInteger.
Floating point
A double stores a binary fraction, and most decimal fractions have no exact binary form. The sum of 0.1 and 0.2 is therefore the nearest double to 0.3, not 0.3, and the two are not equal. The difference is tiny and measurable, which is why money is never a double.
public class Floating {
public static void main(String[] args) {
double sum = 0.1 + 0.2;
System.out.println("0.1 + 0.2 = " + sum);
System.out.println("equals 0.3: " + (sum == 0.3));
System.out.println("difference: " + Math.abs(sum - 0.3));
System.out.println("close enough: " + (Math.abs(sum - 0.3) < 1e-9));
float f = 1.1f;
double d = 1.1;
System.out.println("float: " + f);
System.out.println("double: " + d);
double price = 19.99;
int cents = (int) Math.round(price * 100);
System.out.println("cents: " + cents);
}
}
javac -Xlint:all Floating.java
java Floating
0.1 + 0.2 = 0.30000000000000004
equals 0.3: false
difference: 5.551115123125783E-17
close enough: true
float: 1.1
double: 1.1
cents: 1999
Compare floating-point values with a tolerance, never with ==, and convert to cents or to BigDecimal before doing arithmetic that must add up. float has 24 bits of precision and a double has 53, which is why a float is enough for graphics and not for money.
Widening and narrowing casts
A conversion from a smaller type to a larger one is widening, and the compiler does it without a cast: int to long to double loses nothing. The other direction is narrowing, it may lose information, and the compiler requires the cast to say that you know.
public class Casts {
public static void main(String[] args) {
int i = 65;
long l = i;
double d = l;
System.out.println("widening: " + i + " " + l + " " + d);
long big = 3_000_000_000L;
int cut = (int) big;
System.out.println("narrowing: " + cut);
double fraction = 2.9;
int truncated = (int) fraction;
int rounded = (int) Math.round(fraction);
System.out.println("truncated: " + truncated);
System.out.println("rounded: " + rounded);
char letter = (char) 74;
System.out.println("char: " + letter);
System.out.println("back: " + (int) letter);
}
}
javac -Xlint:all Casts.java
java Casts
widening: 65 65 65.0
narrowing: -1294967296
truncated: 2
rounded: 3
char: J
back: 74
(int) 3_000_000_000L keeps the low 32 bits of the number, which is the negative value above: narrowing to a width that cannot hold the value is not a clamp. A cast from double to int truncates toward zero, so 2.9 becomes 2, and Math.round is the conversion that rounds instead.
Math
java.lang.Math holds the usual functions as static methods. They are imported by default because the package is java.lang, and each returns a double unless it is an integer operation.
public class MathDemo {
public static void main(String[] args) {
System.out.println("abs(-7): " + Math.abs(-7));
System.out.println("max(3, 9): " + Math.max(3, 9));
System.out.println("min(3, 9): " + Math.min(3, 9));
System.out.println("pow(2, 10): " + Math.pow(2, 10));
System.out.println("sqrt(144): " + Math.sqrt(144));
System.out.println("floor(2.9): " + Math.floor(2.9));
System.out.println("ceil(2.1): " + Math.ceil(2.1));
System.out.println("round(2.5): " + Math.round(2.5));
System.out.println("round(-2.5):" + Math.round(-2.5));
}
}
javac -Xlint:all MathDemo.java
java MathDemo
abs(-7): 7
max(3, 9): 9
min(3, 9): 3
pow(2, 10): 1024.0
sqrt(144): 12.0
floor(2.9): 2.0
ceil(2.1): 3.0
round(2.5): 3
round(-2.5):-2
pow and sqrt return double even for whole arguments, which is why 1024.0 has a decimal point. round returns a long for a double argument and rounds halves upward, so -2.5 becomes -2; the random page uses Math.random for a number between 0 and 1.
Exercises
- Compute the average of 7 and 2 as a whole number and as a fraction. Which expression gives 3.5?
- Add Integer.MAX_VALUE to itself in an int and in a long. Compare the two results.
- Print the difference between 0.1 + 0.2 and 0.3 in scientific notation. Which type is it?
- Convert 3000000000L to an int and back to a long. Is the value the same?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What is
7 / 2for two int variables?Answer
3
Integer division discards the fraction; 7 / 2.0 gives 3.5 because one operand is a double.
-
What is
7 % 3?Answer
1
The remainder is what is left after the largest multiple of 3 below 7, so it is 1.
-
What does
Integer.MAX_VALUE + 1give in an int?Answer
Integer.MIN_VALUE
The int wraps around: the maximum plus one is the minimum, -2147483648.
-
What does this program print?
public class Q1 { public static void main(String[] args) { int max = Integer.MAX_VALUE; System.out.println(max + 1); } }Answer
-2147483648
The addition is done in int, so it wraps to the minimum value.
-
What does this program print?
public class Q2 { public static void main(String[] args) { long big = 3_000_000_000L; System.out.println(big + big); } }Answer
6000000000
Both the value and the sum fit in a long, so no overflow happens.
-
What does
(int) 2.9give?Answer
2
A cast from double to int truncates toward zero, so 2.9 becomes 2.
-
What does this program print?
public class Q3 { public static void main(String[] args) { System.out.println((double) 1 / 2); } }Answer
0.5
The cast makes the numerator a double, so the division is a floating-point one.
-
What does this program print?
public class Q4 { public static void main(String[] args) { System.out.println(0.1 + 0.2 == 0.3); } }Answer
false
The sum is not the nearest double to 0.3, so the equality is false.
-
What does this program print?
public class Q5 { public static void main(String[] args) { System.out.println(Math.max(3, 9) + Math.min(3, 9)); } }Answer
12
The maximum is 9, the minimum is 3, and the sum is 12.
-
What is the first line of the compiler output for this program?
public class Q6 { public static void main(String[] args) { int price = 2.5; System.out.println(price); } }Answer
error: incompatible types: possible lossy conversion from double to int
A double does not fit in an int without a cast, and the compiler refuses the implicit narrowing.
The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.
Article author: Arthur Isaev