What is the result of the following code compilation and execution?

public class A {
    public static void main(String[] args) {
        for (int i = 0; ++i > 0;) {
            System.out.println(i);
        }
    }
}
Explanation

Values of int type require 32 bits (4 bytes) of memory. It means that there are 232 different possible values of int variable. Half of them are positive and half are negative. Numbers with a higher-order bit equal to one are considered to be negative:

00000000 00000000 00000000 000000002 = 010
00000000 00000000 00000000 000000012 = 110
. . .
01111111 11111111 11111111 111111112 = 214748364710 = 231–1
10000000 00000000 00000000 000000002 = –214748364810 = –231
. . .
11111111 11111111 11111111 111111112 = –110

Therefore, in the process of a loop execution a -2147483648 number will follow after a 2147483647 number. Since it does not satisfy the cycle continuation condition, program will exit the loop.

"22³²" must be correct to "2³²"

2015 Sep 1, 12:05:32 PM

Follow CodeGalaxy

Mobile Beta

Get it on Google Play
Send Feedback
Keep exploring
Java quizzes
Cosmo
Sign Up Now
or Subscribe for future quizzes