Java标签用法
在某个地方浏览java好文章,我发现这样的代码编译得很完美。
public int myMethod(){ http://www.google.com return 1; }
说明说http:
word将被视为标签, //www.google.com
将被视为评论
我不知道Java Label在循环外是如何有用的? 在什么情况下应该使用Java Label外部循环?
以下是在Java中使用标签的一个好处:
block: { // some code if(condition) break block; // rest of code that won't be executed if condition is true }
嵌套循环的另一种用法:
outterLoop: for(int i = 0; i < 10; i++) { while(condition) { // some code if(someConditon) break outterLoop; // break the for-loop if(anotherConditon) break; // break the while-loop // another code } // more code }
要么:
outterLoop: for(int i = 0; i < 10; i++) { while(condition) { // some code if(someConditon) continue outterLoop; // go to the next iteration of the for-loop if(anotherConditon) continue; // go to the next iteration of the while-loop // another code } // more code }
仅仅因为它编译并不意味着它是有用的…..
Java中经常忽略标签(使用带标记的break
,并continue
…?)。 但是,仅仅因为没有使用标签并不意味着它是非法的。