Int division: Why is the result of 1/3 == 0?

Tofiq picture Tofiq · Jan 13, 2011 · Viewed 147.6k times · Source

I was writing this code:

public static void main(String[] args) {
    double g = 1 / 3;
    System.out.printf("%.2f", g);
}

The result is 0. Why is this, and how do I solve this problem?

Answer

Noldorin picture Noldorin · Jan 13, 2011

The two operands (1 and 3) are integers, therefore integer arithmetic (division here) is used. Declaring the result variable as double just causes an implicit conversion to occur after division.

Integer division of course returns the true result of division rounded towards zero. The result of 0.333... is thus rounded down to 0 here. (Note that the processor doesn't actually do any rounding, but you can think of it that way still.)

Also, note that if both operands (numbers) are given as floats; 3.0 and 1.0, or even just the first, then floating-point arithmetic is used, giving you 0.333....