• Post Reply Bookmark Topic Watch Topic
  • New Topic

From JQ+  RSS feed

 
Ranch Hand
Posts: 356
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can anybody explain the output of this question I found at JQ+
Thanks
--Farooq
=======================================================
public class BreakTest
{

public static void main(String[] args)
{
int i = 0, j = 5;
lab1 : for( ; ; i++)
{
for( ; ; --j) if( i >j ) break lab1;
}
System.out.println(" i ="+i+" , j = "+j);
}
}
 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Farooq
Maybe I can explain it.
(By the way the output you get it "i=0 , j=-1" isn't it?)
The i loop (labeled Lab1) starts out with i=0, j=5.
The control passes into the j loop (inner loop) which loops (i=0, j=4, j=3, j=2, j=1, j=0, j=-1) when j=-1 it means i>j so the if-statement is true and the outer loop is broken: break Lab1 (control jumps to the statement after the end of the i loop). i is still 0 at this point.
Does that sound right? If you put a print statement in the loop, you can see j counting down and i staying at 0.
Cheers
David
 
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
good explanation...I ran the program and you have the right output
 
Muhammad Farooq
Ranch Hand
Posts: 356
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks David, You explain it very well.
--farooq
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!