Home > Mobile >  How does this break; syntax work in this code of Java
How does this break; syntax work in this code of Java

Time:07-04

public static void main(String[] args) {
int x = 0;
int y = 30;
for (int outer = 0; outer < 3; outer   ) {
   for (int inner = 4; inner > 1; inner --) {
      x = x   3;
      y = y - 2;
      if (x == 6) {
         break;
      }
      x = x   3;
   }
   y = y - 2;
 }
 System.out.println(x   " "   y);
}

what I did on this code: outer loop's first iteration starts when it is 0 after that inner for loop starts from 4, x = 0 3 will be save in x, then y = 30 - 2 will be saved, and x is not 6 so if statement will not be operating yet. and x will be added with another 3. So, now it's 6. What I am curious about at this point is will the program will start the if statement right away as soon as x reaches 6? or since if statement is already passed by the order of the lines on the program, is it not going to be executed? my possible output estimation is: 42 6 but the correct output is: 54 6

CodePudding user response:

What I am curious about at this point is will the program will start the if statement right away as soon as x reaches 6?

-> The program will then run for integer inner value 3 , then x becomes 9 and y becomes 26 . x != 6 , if condition wont be executed then x becomes 12

inner value 2 :

x = 15, y = 24 , x = 18 

inner value 1 : ( the for loop break ) 
x = 18 and y= 22

outer =1 : 

inner = 4, x = 24, y = 20 , 

inner = 3 , x = 30 , y =18 

inner = 2 , x = 36, y  = 16

inner = 1 ( won't executed ) 

 exits inner for loop 
x = 36, y = 14
outer= 2 ; 

inner = 4 : 
x = 42, y = 12
 
inner = 3 : 
x = 48 , y = 10 ; 

inner  =2 
x = 54, y = 8 
inner =1 : exits inner for loop 
x = 54 and y = 6 

thus the final values are x = 54, and y = 6 only 

:

CodePudding user response:

The if statement will never be true so we can ignore it, the inner loop runs a total of 9 times where you add 6 each time -> 9*6=54=x and substract 2 9 times = 18, outer loop runs 3 times total where you also substract 2 = 6. y=30-18-6=6. Not sure where your 42 comes from but for clarification just set some breakpoints and let it play through in the debugger

  • Related