Course contentsShow
← Java
Lesson 37 of 2,8702. Variables and Primitive TypesFree lesson

Common Pitfalls: Integer Division and Truncation

Recognize that dividing two integers always produces an integer result, discarding any fractional part without rounding.

Common Pitfalls: Integer Division and Truncation

What you'll learn: Why dividing two integers in Java can surprise you by "losing" the decimal part.

The Core Problem

When you divide one int by another int in Java, the result is always an int—never a decimal. Java doesn't round the answer; it simply chops off (truncates) everything after the decimal point.

Think of it like slicing a pizza: if you have 7 slices and divide them among 2 people using "integer math," each person gets 3 slices, and the leftover slice just disappears from the calculation. Java doesn't give anyone 3.5 slices—it can't, because integers are whole numbers only.

Why This Happens

Remember that int, long, short, and byte are all integer types—they store whole numbers without fractional parts. When Java evaluates an expression like 5 / 2, it sees two integers and produces an integer result: 2, not 2.5.

Example with Code

int a = 7;
int b = 2;
int result = a / b;  // result is 3, not 3.5
System.out.println(result);  // prints: 3

The mathematical answer is 3.5, but since both a and b are integers, Java performs integer division and truncates to 3.

Another Surprise

int x = 9;
int y = 10;
int fraction = x / y;  // fraction is 0, not 0.9

Even though 9 ÷ 10 = 0.9 mathematically, integer division gives you 0 because the fractional part vanishes.

Key Takeaway: Dividing two integers always produces an integer result by discarding (not rounding) any fractional part—plan accordingly when working with whole-number types.