Ratnajothy
Ratnajothy

Reputation: 128

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...

Upvotes: 4

Views: 113

Answers (4)

Mohammed Aouf Zouag
Mohammed Aouf Zouag

Reputation: 17132

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.

Upvotes: 3

Omkar Puttagunta
Omkar Puttagunta

Reputation: 4156

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

Upvotes: 0

e.doroskevic
e.doroskevic

Reputation: 2169

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);

Upvotes: 0

Mena
Mena

Reputation: 48404

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), i.e. 14

Upvotes: 3

Related Questions