Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Label (Continue)

 
Gaurav Pavan Kumar Jain
Ranch Hand
Posts: 168
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Folks

code:
---------------
public TestCont
{
public static void main(String args[])
{
outer:
for (int i=0; i<5; i++) {
for (int j=0; j<5; j++) {
System.out.println("Hello");
continue outer;
} // end of inner loop
System.out.println("outer"); // Never prints
}
System.out.println("Good-Bye");
}

Running this code produces
Hello
Hello
Hello
Hello
Hello
Good-Bye

My question is why it doesnot prints "Outer"

 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because you'll never reach the end of the inner loop.
 
Prasanna Choudhary
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The continue in the loop stops the execution of current iteration and goes to the next iteration.
When the iteration starts, it checks for the condition in the loop and if follows the execution of the loop if the condition is satisfied. If the condition is false, it won't enter into the loop and can't execute that statement.

Hope this is clear....
 
Chandra Bhatt
Ranch Hand
Posts: 1710
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Gaurav,



Here it goes:
Inside inner loop:
prints Hello, continue outer-> go to outer loop, i(1)<5 = true
prints Hello, continue outer-> go to outer loop, i(2)<5 = true
prints Hello, continue outer-> go to outer loop, i(3)<5 = true
prints Hello, continue outer-> go to outer loop, i(4)<5 = true
prints Hello, continue outer-> go to outer loop, i(5)<5 = false (exit from outer loop)

Question: Is statement "System.out.println("outer");" encounter anytime?
Answer: Never!
But compiler can't complaint about unreachable code, because continue is
inside the inner loop. If you make that in the outer loop, it will complaint, because of the unreachability of line.


Regards,
cmbhatt
 
Gaurav Pavan Kumar Jain
Ranch Hand
Posts: 168
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you folks now it's clear to me.



 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic