下面的语句会编译报错或者打印什么?

        System.out.print("baidu site :");
https://www.baidu.com;
System.out.println(" format");

很多人会说:会编译出错,中间那行是什么鬼?

Java 编程语言中很少被人了解的特性-statement label-LMLPHP

其实,不会报错,会打印出:

baidu site : format

如果改成这样的语句,是不是就不会觉得编译报错了?

        System.out.print("baidu site :");
https :
//www.baidu.com;
System.out.println(" format");

像不像switch语句中的case

int q = (n+7)/8;
switch (n%8) {
case 0: do { foo(); // Great C hack, Tom,
case 7: foo(); // but it's not valid here.
case 6: foo();
case 5: foo();
case 4: foo();
case 3: foo();
case 2: foo();
case 1: foo();
} while (--q > 0);
}

上面的语句,":" 是statement label 翻译成标号语句。

其语法如下:

LabeledStatement:
Identifier : Statement
LabeledStatementNoShortIf:
Identifier : StatementNoShortIf

与c和c++不同,java中没有goto语句;标号语句用于出现在标号语句内任何地方的break或者continue语句之上。

再来一个标句语句作为结尾的练习吧

class Test {
char[] value;
int offset, count;
int indexOf(TestString str, int fromIndex) {
char[] v1 = value, v2 = str.value;
int max = offset + (count - str.count);
int start = offset + ((fromIndex < 0) ? 0 : fromIndex);
i:
for (int i = start; i <= max; i++) {
int n = str.count, j = i, k = str.offset;
while (n-- != 0) {
if (v1[j++] != v2[k++])
continue i;
}
return i - offset;
}
return -1;
}
}

参考资料

【1】https://docs.oracle.com/javase/specs/jls/se12/html/jls-14.html#jls-14.7

05-11 14:45