There are 6 places where we use a colon ( : ).
Using colon ( : ) as Jump-out label in java
This is the first use case of the colon ( : ) is to use it as a Jump-out label.
To understand this, imagine that you have a nested loop and you want to break out of the outer loop.
You’ll use a break, right!
Nope, this will move you out of the inner loop and not the outer loop.
To move out of the outer loop, you need to use the Jump-out label as shown in the code below.
Code
public static void main(String[] args) { | |
loop1: for (int i = 0; i <5 ; i++) { | |
loop2: for (int j = 0; j <5 ; j++) { | |
System.out.println(i+" "+j); | |
if (i==j) | |
break loop1; | |
} | |
} | |
} |
0 0
In the above example, loop1 and loop2 are jump-out labels. Using break loop1, we are breaking out of the outer loop or loop1.
Using colon ( : ) as Ternary condition in java
This is the second use case of the colon ( : ) is to use it as a Ternary operator.
The ternary operator is also known as shorthand if-else.
Let’s see it in action.
Code
public static void main(String[] args) { | |
int b = (7 > 2) ? 1 : 0; | |
System.out.println(b); | |
} |
1
In the above example, Line 3 means if 7 is greater than 2, then a will be given the value of 1 else the value of 0.
Using colon ( : ) in a for-each loop in java
This is another use case of the colon ( : ).
We use a colon ( : ) inside a for each loop which is used to traverse over a list or an array as shown in the code below.
Code
public static void main(String[] args) { | |
int[] arr= {1,2,3}; | |
for(int element : arr) | |
{ | |
System.out.println(element); | |
} | |
} |
1
2
3
In the above example, we are iterating over the array and printing each element.