简体   繁体   中英

Need explanation for the output of the following java code

public class Test {  
  public static void main (String args[]) {
    int i = 0;
    for (i = 0; i < 10; i++);
    System.out.println(i + 4);
  }
}   

The output of the following code is 14.Why it is not 4?

And how can it be 14? Need some explanation

Thank you in advance...

Simple.

  • The loop increments i by 10 without doing anything else (notice the ; after the for loop definition)
  • The System.out statement prints i + 4 outside the loop (only once), ie 14
for (i = 0; i < 10; i++);

This loop does nothing but incrementing i by one, 10 times .

Then

System.out.println(i + 4);

evaluates to

System.out.println(10 + 4);

// output
14 

If you drop the semi colon at the end of for (i = 0; i < 10; i++); , you shall get

4
5
6
7
8
9
10
11
12
13

as an output.

See description in comments:

        // Declare variable 'i' of type int and initiate it to 0
        // 'i' value at this point 0;
        int i = 0;

        // Take variable 'i' and while it's less then 10 increment it by 1
        // 'i' value after this point 10;
        for (i = 0; i < 10; i++);

        // Output to console the result of the above computation
        // 'i' value after this point 14;
        System.out.println(i + 4);

System.out.println(i + 4); will get evaluated and executed after for (i = 0; i < 10; i++); statement is evaluated.

Result of for (i = 0; i < 10; i++); will be 10 . The condition i < 10 will be true till i=9 which is the 10th iteration and in the 11th iteration i will be 10 as i++ will be computed and here the i<10 condition fails. Now final value of i will be 10 . The next statement System.out.println(i + 4); is evaluated which is i(=10)+4 = 14

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM