What does the colon (:) operator do?

JavaFor LoopForeachOperatorsColon

Java Problem Overview


Apparently a colon is used in multiple ways in Java. Would anyone mind explaining what it does?

For instance here:

String cardString = "";
for (PlayingCard c : this.list)  // <--
{
	cardString += c + "\n";
}

How would you write this for-each loop a different way so as to not incorporate the :?

Java Solutions


Solution 1 - Java

There are several places colon is used in Java code:

  1. Jump-out label (Tutorial):

    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. Ternary condition (Tutorial):

    int a = (b < 4)? 7: 8; // if b < 4, set a to 7, else set a to 8

  3. For-each loop (Tutorial):

    String[] ss = {"hi", "there"} for (String s: ss) { print(s); // output "hi" , and "there" on the next iteration }

  4. Assertion (Guide):

    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. Case in switch statement (Tutorial):

    switch (type) { case WHITESPACE: case RETURN: break; case NUMBER: print("got number: " + value); break; default: print("syntax error"); }

  6. Method references (Tutorial)

    class Person { public static int compareByAge(Person a, Person b) { return a.birthday.compareTo(b.birthday); }} }

    Arrays.sort(persons, Person::compareByAge);

Solution 2 - Java

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.

Solution 3 - Java

Just to add, when used in a for-each loop, the ":" can basically be read as "in".

So

for (String name : names) {
    // remainder omitted
}

should be read "For each name IN names do ..."

Solution 4 - Java

> 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.

Solution 5 - Java

It's used in for loops to iterate over a list of objects.

for (Object o: list)
{
    // o is an element of list here
}

Think of it as a for <item> in <list> in Python.

Solution 6 - Java

You usually see it in the ternary assignment operator;

Syntax

variable =  `condition ? result 1 : result 2;`

example:

boolean isNegative = number > 0 ? false : true;

which is "equivalent" in nature to the if else

if(number > 0){
    isNegative = false;
}
else{
    isNegative = true;
}

Other than examples given by different posters,

you can also use : to signify a label for a block which you can use in conjunction with continue and break..

for example:

public void someFunction(){
     //an infinite loop
     goBackHere: { //label
          for(int i = 0; i < 10 ;i++){
               if(i == 9 ) continue goBackHere;
          }
     }
}

Solution 7 - Java

In your specific case,

String cardString = "";
for (PlayingCard c : this.list)  // <--
{
    cardString = cardString + c + "\n";
}

this.list is a collection (list, set, or array), and that code assigns c to each element of the collection.

So, if this.list were a collection {"2S", "3H", "4S"} then the cardString on the end would be this string:

2S
3H
4S

Solution 8 - Java

It is used in the new short hand for/loop

final List<String> list = new ArrayList<String>();
for (final String s : list)
{
   System.out.println(s);
}

and the ternary operator

list.isEmpty() ? true : false;

Solution 9 - Java

The colon actually exists in conjunction with ?

int minVal = (a < b) ? a : b;

is equivalent to:

int minval;
if(a < b){ minval = a;} 
else{ minval = b; }

Also in the for each loop:

for(Node n : List l){ ... }

literally:

for(Node n = l.head; n.next != null; n = n.next)

Solution 10 - Java

It will prints the string"something" three times.

JLabel[] labels = {new JLabel(), new JLabel(), new JLabel()};                   

for ( JLabel label : labels )                  
 {              
   label.setText("something");  
  
 panel.add(label);             
 }

Solution 11 - Java

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."

Solution 12 - Java

colon is using in for-each loop, Try this example,

import java.util.*;

class ForEachLoop
{
       public static void main(String args[])
	   {`enter code here`
	   Integer[] iray={1,2,3,4,5};
	   String[] sray={"ENRIQUE IGLESIAS"};
	   printME(iray);
	   printME(sray);
	   
	   }
	   public static void printME(Integer[] i)
	   {           
	              for(Integer x:i)
	              {
	                System.out.println(x);
	              }
	   }
	   public static void printME(String[] i)
	   {
	               for(String x:i)
				   {
	               System.out.println(x);
				   }
	   }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondukevinView Question on Stackoverflow
Solution 1 - JavaRandy Sugianto 'Yuku'View Answer on Stackoverflow
Solution 2 - JavaClaudiuView Answer on Stackoverflow
Solution 3 - JavahelpermethodView Answer on Stackoverflow
Solution 4 - JavaStephen CView Answer on Stackoverflow
Solution 5 - JavaMike CialowiczView Answer on Stackoverflow
Solution 6 - JavaultrajohnView Answer on Stackoverflow
Solution 7 - JavaRandy Sugianto 'Yuku'View Answer on Stackoverflow
Solution 8 - Javauser177800View Answer on Stackoverflow
Solution 9 - JavaRitwik BoseView Answer on Stackoverflow
Solution 10 - Javauser3756229View Answer on Stackoverflow
Solution 11 - JavaSoft developerView Answer on Stackoverflow
Solution 12 - Javauser6940848View Answer on Stackoverflow