There is no "colon" operator, but the colon appears in two places:
1: In the ternary operator, e.g.:
int x = bigInt ? 10000 : 50;
In this case, the ternary operator acts as an 'if' for expressions. If bigInt is true, then x will get 10000 assigned to it. If not, 50. The colon here means "else".
2: In a for-each loop:
double[] vals = new double[100];
//fill x with values
for (double x : vals) {
//do something with x
}
This sets x to each of the values in 'vals' in turn. So if vals contains [10, 20.3, 30, ...], then x will be 10 on the first iteration, 20.3 on the second, etc.
Note: I say it's not an operator because it's just syntax. It can't appear in any given expression by itself, and it's just chance that both the for-each and the ternary operator use a colon.
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
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
class Person {
public static int compareByAge(Person a, Person b) {
return a.birthday.compareTo(b.birthday);
}}
}
Arrays.sort(persons, Person::compareByAge);
How would you write this for-each loop a different way so as to not incorporate the ":"?
Assuming that list is a Collection instance ...
public String toString() {
String cardString = "";
for (Iterator<PlayingCard> it = this.list.iterator(); it.hasNext(); /**/) {
PlayingCard c = it.next();
cardString = cardString + c + "\n";
}
}
I should add the pedantic point that : is not an operator in this context. An operator performs an operation in an expression, and the stuff inside the ( ... ) in a for statement is not an expression ... according to the JLS.
Since most for loops are very similar, Java provides a shortcut to reduce the
amount of code required to write the loop called the for each loop.
Here is an example of the concise for each loop:
for (Integer grade : quizGrades){
System.out.println(grade);
}
In the example above, the colon (:) can be read as "in". The for each loop
altogether can be read as "for each Integer element (called grade) in
quizGrades, print out the value of grade."