Predict the output · Java
Numbers and arithmetic
Integer division, remainders, overflow, decimals and rounding.
Learn: Predicting what Java arithmetic prints7 minute read
Arithmetic questions in Java interviews are rarely about maths. They test how Java's number types behave: what type a calculation has, what happens when a value does not fit, and how decimals are stored. Testers meet these rules when they check totals, prices, counts and IDs, so interviewers use them to see whether you would spot a wrong number in a test. Here are the rules, basics first.
The number types you need
int holds whole numbers in 32 bits (a bit is one binary digit, 0 or 1), from -2147483648 to 2147483647. long holds whole numbers in 64 bits. byte holds -128 to 127. double holds numbers with a fraction, stored in binary. A whole number written in code, like 7, is an int; 7L is a long and 7.0 is a double.
Rule 1: the operands decide the type
The operands are the values on each side of an operator. When both sides of / are int, the result is an int and the fraction is cut off toward zero. So 9 / 4 is 2 and -9 / 4 is -2. Storing that result in a double does not bring the fraction back: the division already happened in int arithmetic. Make one operand a double, for example 9 / 4.0, and the fraction is kept. The remainder % takes the sign of the left operand.
public class Main {
public static void main(String[] args) {
System.out.println(9 / 4);
System.out.println(-9 / 4);
System.out.println(-9 % 4);
System.out.println(9 / 4.0);
double d = 9 / 4;
System.out.println(d);
}
}
2 -2 -1 2.25 2.0
Rule 2: overflow wraps around silently
If an int result does not fit, Java keeps the low 32 bits and carries on with no error. This is called overflow, and a large positive sum can come out negative. The same happens when a product of int values is later stored in a long: the overflow happens first, during the multiplication. Put an L on the first number, or cast before the operation, to work in long. A cast converts a value to another type, for example (long) big.
Casting to a smaller type also keeps only the low bits. For a byte that means subtracting 256 until the value fits, so (byte) 130 is -126.
Rule 3: doubles are binary approximations
Most decimal fractions, like 0.1, have no exact binary form, so they are stored as the nearest possible value. The tiny errors show up in sums: 0.1 + 0.2 prints 0.30000000000000004, so comparing doubles with == is unsafe. Compare with a tolerance (a small difference that you accept as equal), or use BigDecimal, a class that stores decimal digits exactly, for money.
Dividing a double by zero does not throw. It gives Infinity, -Infinity or NaN (not a number). Dividing an int by zero throws ArithmeticException, an error that stops the program. NaN is not equal to anything with ==, not even itself, so test for it with Double.isNaN.
public class Main {
public static void main(String[] args) {
int big = 2_000_000_000;
System.out.println(big + big);
System.out.println((long) big + big);
System.out.println((byte) 130);
System.out.println(0.1 + 0.2);
System.out.println(5.0 / 0);
}
}
-294967296 4000000000 -126 0.30000000000000004 Infinity
The underscores in 2_000_000_000 are only there to make the number easier to read. Java ignores them.
Rule 4: rounding and casting are different
A cast to int drops the fraction toward zero: 3.9 becomes 3 and -3.9 becomes -3. Math.round rounds to the nearest whole number, and a value exactly halfway goes up, toward the larger number. So Math.round(2.5) is 3 but Math.round(-2.5) is -2.
Rule 5: boxed numbers are objects
Integer is the object version of int. Java converts between them for you, which is called autoboxing and unboxing. Because an Integer is an object, == between two of them compares references. Autoboxing reuses cached objects for values from -128 to 127, which makes == look correct for small numbers and fail for larger ones. Use equals, or compare int values.
public class Main {
public static void main(String[] args) {
Integer a = 100, b = 100, c = 1000, d = 1000;
System.out.println(a == b);
System.out.println(c == d);
System.out.println(c.equals(d));
}
}
true false true
How to answer in an interview
Name the types before you calculate. "Both operands are int, so this is int division and the answer is 2." For overflow questions, say that Java gives no error and the value wraps, then say how you would avoid it: long, Math.addExact (it throws an error instead of wrapping), or BigDecimal for money. A short real example helps: a test that sums order totals in int can pass on small data and fail on large data.
Common mistakes
- Expecting
double d = 7 / 2;to store 3.5. - Expecting an exception when an
intoverflows. - Putting the
Lon the last number of a product instead of the first. - Treating a cast as rounding.
- Comparing two
Integerobjects with==.
Recap
Look at the operand types first: two ints give int division. Ints and smaller types wrap silently when a value does not fit. Doubles are close but not exact, and division by zero gives Infinity for doubles but throws for ints. A cast cuts the fraction off while Math.round rounds, and boxed numbers must be compared with equals.
10 questions0/10 solved
| Status | Question | Difficulty | Asked in |
|---|---|---|---|
| Not started | Integer division and remainder with negatives | Easy | |
| Not started | Integer division stored in a double | Easy | |
| Pro+ | 0.1 + 0.2 in Java | Easy-Medium | |
| Pro+ | Adding 1 to the largest int | Medium | Asked in: PayPal |
| Pro+ | A product that overflows before it reaches a long | Medium | |
| Pro+ | Integer caching: 127 versus 128 | Medium | |
| Pro+ | Dividing by zero: double versus int | Medium | |
| Pro+ | Math.round versus casting to int | Medium-Hard | |
| Pro+ | Casting 200 to byte and incrementing 127 | Medium-Hard | |
| Pro+ | NaN and negative zero with == and equals | Hard |
The first 2 questions of each topic are free. Pro+ opens every question.