• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

labels

 
Stephanie Grasson
Ranch Hand
Posts: 347
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This segment is from Marcus Green's Java2 Certification Tutorial
(the section on flow control and exception handling).
public class Br
{
public static void main(String argv[])
{
Br b = new Br();
b.amethod();
}
public void amethod()
{
for(int i=0; i <3; i ++)
{
System.out.println("i"+i+"\n");
outer://<==Point of this example
if(i>2)
{
break outer;//<==Point of this example
}//End of if
for(int j=0; j <4 && i<3; j++)
{
System.out.println("j"+j);
}//End of for
}//End of for
}//end of Br method
}
I do not understand the point of the label "outer" or the statement "if(i>2)";
It seems to me that the outer for statement
"for(int i=0; i <3; i ++)"
will never allow execution to reach this point.
"i" will be set to 0, 1, and 2, then the conditional statement of the outer for loop will fail and execution should continue at the next line after the outer for loop (in this case, the end of the method).
Could someone please fill me in on what I am missing.
I do not understand Mr. Green's point with this example.
Thank you very much.
 
Carl Trusiak
Sheriff
Posts: 3340
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Stephanie Grasson:
This segment is from Marcus Green's Java2 Certification Tutorial
(the section on flow control and exception handling).
public class Br
{
public static void main(String argv[])
{
Br b = new Br();
b.amethod();
}
public void amethod()
{
for(int i=0; i <3; i ++)
{
System.out.println("i"+i+"\n");
outer://<==Point of this example
if(i>2)
{
break outer;//<==Point of this example
}//End of if
for(int j=0; j <4 && i<3; j++)
{
System.out.println("j"+j);
}//End of for
}//End of for
}//end of Br method
}
I do not understand the point of the label "outer" or the statement "if(i>2)";
It seems to me that the outer for statement
"for(int i=0; i <3; i ++)"
will never allow execution to reach this point.
"i" will be set to 0, 1, and 2, then the conditional statement of the outer for loop will fail and execution should continue at the next line after the outer for loop (in this case, the end of the method).
Could someone please fill me in on what I am missing.
I do not understand Mr. Green's point with this example.
Thank you very much.

I think he has a logic error try changing it to i<4 in both loops and running it. Then move the outer: to above the first for and run it. The point is to show how placement of a label affects the results.
 
Stephanie Grasson
Ranch Hand
Posts: 347
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks, Carl.
It makes a lot more sense that way.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic