1. Enhanced for loops (for-each loop)
2. Ternary expression
3. Labeling of the loops
4. Switch statements after case or default
Read Also: What does | mean in Java with examples
What does a colon mean in Java Programming
According to Oracle docs, When you see the colon(:) read it as "in". Let's dive deep into more detail:1. Enhanced for loops (for-each loop)
The enhanced for loop was introduced in Java 5. It was mainly introduced to traverse the collection of elements including arrays. The main advantage of using for each loop is that it makes the code more readable and eliminates the possibility of bugs.Syntax:
For-each loop syntax consists of datatype with the variable followed by a colon(:) then collection or array. for(dataType variable : collection | array)
{
// statements
}
Example:
1. Array
Suppose we have givenArray, then we can traverse it using conventional for loop or using new enhanced for loop(for-each loop) as shown below in the image: public class ColonJava {
public static void main(String args[]) {
// Declaring the Array
int[] givenArray = {11, 7, 45, 19};
// Traversing the array using for-each loop
for (int val : givenArray)
{
System.out.println(val);
}
}
}
Output:
11
7
45
19
One of the downsides of the for-each loop is that you can not traverse elements in reverse order. Also, you can not skip any number of elements.
2. Ternary expression
As the name suggests, the ternary operator takes three terms and its syntax is:Syntax:
BooleanExpression ? Expression1 : Expression2
The value of the BooleanExpression is determined. If it is true, then the value of the whole expression is Expression1, else, if it is false then the value of the whole expression is Expression2.
Example:
public class ColonJava2 {
public static void main(String args[]) {
boolean val = true;
int x = val ? 9 : 2;
System.out.println(x);
}
}
Output:
9
3. Labeling of the loops
In Java, a label is a valid variable name. The label denotes the name of the loop to where the control of execution should jump. It is simple to label a loop, place the label before the loop with a colon at the end as shown below in the example: public class ColonJava3 {
public static void main(String args[]) {
int i, j=0;
//outer label
outerloop:
for(i=0; i < 3; i++) {
System.out.print(i+" ");
// inner label
innerloop:
for(j=0; j < 4;j++) {
System.out.print(j + " ");
if (j==1)
break innerloop;
}
}
}
}
Output:
0 0 1 1 0 1 2 0 1
4. Switch statements after case or default
The simple syntax of the switch statement is given below: switch(expression){
case a:
// statements
break;
case b:
// statements
break;
default:
//statements
}
You can see that we have used colon(:) after the case and default keywords. You can find in detail the switch statements here.
That's all for today, please mention in the comments in case you have any questions related to what does a colon means in Java programming.