[java] What does the colon (:) operator do?

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 :?

This question is related to java for-loop foreach operators colon

The answer is


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);             
 }

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.


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);
                   }
       }
}

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.


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;
          }
     }
}

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

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;

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.


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)

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


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


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to for-loop

List append() in for loop Prime numbers between 1 to 100 in C Programming Language Get current index from foreach loop how to loop through each row of dataFrame in pyspark TypeScript for ... of with index / key? Is there a way in Pandas to use previous row value in dataframe.apply when previous value is also calculated in the apply? Python for and if on one line R for loop skip to next iteration ifelse How to append rows in a pandas dataframe in a for loop? What is the difference between ( for... in ) and ( for... of ) statements?

Examples related to foreach

Angular ForEach in Angular4/Typescript? How to use forEach in vueJs? Python foreach equivalent Get current index from foreach loop TypeScript for ... of with index / key? JavaScript: Difference between .forEach() and .map() JSON forEach get Key and Value Laravel blade check empty foreach Go to "next" iteration in JavaScript forEach loop Why is "forEach not a function" for this object?

Examples related to operators

What is the difference between i = i + 1 and i += 1 in a 'for' loop? Using OR operator in a jquery if statement What is <=> (the 'Spaceship' Operator) in PHP 7? What does question mark and dot operator ?. mean in C# 6.0? Boolean operators ( &&, -a, ||, -o ) in Bash PowerShell and the -contains operator How do I print the percent sign(%) in c Using the && operator in an if statement What do these operators mean (** , ^ , %, //)? How to check if div element is empty

Examples related to colon

What does the colon (:) operator do?