Need to explain 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 result of the following code: 14. Why is it not 4?

And how could that be? Need some explanation

Thanks in advance...

+4
source share
4 answers
for (i = 0; i < 10; i++);

This loop does nothing but increment iby one, 10 times.

Then

System.out.println(i + 4);

estimated as

System.out.println(10 + 4);

// output
14 

If you let go half an hour at the end for (i = 0; i < 10; i++);, you get

4
5
6
7
8
9
10
11
12
13

as a way out.

+3
source

Simple

  • The loop increments iby 10without doing anything else (note the ;after loop definition for)
  • The operator System.outprints i + 4out of the loop (only once), i.e.14
+3

. :

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

System.out.println(i + 4); for (i = 0; i < 10; i++);.

The result for (i = 0; i < 10; i++);will be 10. The condition i < 10will be true before i=9, which is the 10th iteration, and in the 11th iteration it iwill be 10as it will i++, and here the condition i<10will fail. Now the final value iwill be 10. The following statement is calculated System.out.println(i + 4);, which is equal toi(=10)+4 = 14

0
source

Source: https://habr.com/ru/post/1623942/


All Articles