Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java For loop simple code - output clarification

Tags:

java

for-loop

Can somebody explain me how this code prints 8 2 as the result?

public class Check{

    public static void main(String args[]){

        int x=0;
        int y=0;

        for(int z=0;z<5;z++){
            if(++x>2||++y>2){
               x++;
            }
         }

         System.out.println(x+" "+y);

    }
}
like image 549
Achini Samuditha Avatar asked Dec 20 '12 15:12

Achini Samuditha


1 Answers

In iteration 0, 1, the condition is not true, so it ends with x=2, y=2.

From iteration 2 onward, the first condition ++x>2 is true, so the second one is not evaluated again. y remains fixed at 2. For each following loop, x is increased twice (once evaluating the ++x>2, once by the x++;). So x becomes 4, 6, and 8.

like image 120
SJuan76 Avatar answered Oct 01 '22 05:10

SJuan76