Important Java Concept

Why do we use a colon in Java?

Welcome readers,
In this article, we will learn why do we use a colon in Java.
There are 6 places where we use a colon ( : ). 
Let’s go over each of these cases.
 

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;
}
}
}
view raw color_use1.java hosted with ❤ by GitHub

 

OUTPUT:
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);
}
view raw color_use2.java hosted with ❤ by GitHub

 

OUTPUT:
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);
}
}
view raw color_use3.java hosted with ❤ by GitHub

 

OUTPUT:
1
2
3

In the above example, we are iterating over the array and printing each element.

 

In this java tutorial, we learned why do we use a colon in Java.
I hope this article helped you.
 
In case the solution is not clear to you, I suggest you take a live 1:1 lesson on this subject from me. I am an Oracle-certified tutor who would love to teach this stuff to you.
Aniket Malik

Do you want

Java Tutor?

Aniket Malik

Aniket Malik

ORACLE CERTIFIED JAVA TUTOR

🟢 Oracle Certified Java Expert

🟢 300 + ⭐ ⭐ ⭐ ⭐ ⭐

🟢 B.tech & M.tech in CSE

🟢 6+ Years of Teaching Experience

🟢 Worked as SE in Virtusa and Digidez

Do you want

Java Tutor?