Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Flow Control

 
Arun Pai
Ranch Hand
Posts: 143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class TestClass
{
public static void main(String[] args)
{
String: for(int i = 0; i< 10; i++)
{
for (int j = 0; j< 10; j++)
{
if ( i+ j > 10 ) break String;
}
System.out.println( "hello");
}
}
}
I have 2 questions for this code from JQ+?
1. Why should this code compile if a keyword String is used a label identifier in break.
2. Why the output should print hello twice.


-Arun
 
Jon Huhtala
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
String is a class name and not a keyword. It is OK, but poor coding technique, to use it as a label.
Note that the inner loop does no printing. In fact it prevents the outer loop from printing when i+j is greater than 10 because it breaks to the next iteration of the outer loop. Printing only happens when i is 0 or 1 because j takes on values as high as 9 and forces the break.
 
Arun Pai
Ranch Hand
Posts: 143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks, Jon
oops... used String as keyword.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic