Java 代码中有几个地方使用了冒号:
1) 跳出标签 (Tutorial http://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html):
label: for (int i = 0; i < x; i++) {
for (int j = 0; j < i; j++) {
if (something(i, j)) break label; // jumps out of the i loop
}
}
// i.e. jumps to here
2)三元条件(Tutorial http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html):
int a = (b < 4)? 7: 8; // if b < 4, set a to 7, else set a to 8
3)for-each循环(Tutorial http://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html):
String[] ss = {"hi", "there"}
for (String s: ss) {
print(s); // output "hi" , and "there" on the next iteration
}
4)断言(Guide http://docs.oracle.com/javase/8/docs/technotes/guides/language/assert.html):
int a = factorial(b);
assert a >= 0: "factorial may not be less than 0"; // throws an AssertionError with the message if the condition evaluates to false
5) switch 语句中的 case (Tutorial http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html):
switch (type) {
case WHITESPACE:
case RETURN:
break;
case NUMBER:
print("got number: " + value);
break;
default:
print("syntax error");
}
6)方法参考(Tutorial http://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html)
class Person {
public static int compareByAge(Person a, Person b) {
return a.birthday.compareTo(b.birthday);
}}
}
Arrays.sort(persons, Person::compareByAge);