-6

I have what may be a simple question but I can't seem to find an answer. Can variables be assigned with : (colon) in java. Like in this code below:

 for(String token: tokens) {
  System.out.println(token);

I saw this on one of the question boards for a different topic.

Thanks for responding.

CSchulz
  • 10,882
  • 11
  • 60
  • 114
chokkie
  • 25
  • 2

6 Answers6

4

In this case the operator : is not an assignment; it represents the enhanced for loop added in Java 5. It basically means "for every String in the String array or String Iterable, use the String.

Random42
  • 8,989
  • 6
  • 55
  • 86
3

This is called an enhanced for loop. From The Java Tutorials:

class EnhancedForDemo {
    public static void main(String[] args){
         int[] numbers = 
             {1,2,3,4,5,6,7,8,9,10};
         for (int item : numbers) {
             System.out.println("Count is: " + item);
         }
    }
}

The output from this program:

Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10
philipvr
  • 5,738
  • 4
  • 32
  • 44
  • Nit: Although this comment *shouldn't* apply to anyone, enhanced for-loops were added in [Java 5](http://en.wikipedia.org/wiki/Java_version_history) (~ 2004). So for *old* versions of javac it could result in a syntax error .. – user2864740 Feb 26 '14 at 19:40
  • Cheers again guys, also read this up on docs.oracle. Thank you. – chokkie Mar 01 '14 at 16:44
0

Yes, this is valid, assuming there is a collection of strings named tokens. Although, you're missing the closing }

Tips48
  • 745
  • 2
  • 11
  • 26
0

That's a "for-each" in Java. It reads like "for each token in tokens". The tokens variable is an Iterable collection. The code inside the loop repeats for each element from the collection.

helderdarocha
  • 23,209
  • 4
  • 50
  • 65
0

This is a special for loop in Java called for-each. What the statement for(String token: tokens) means is that iterate over the collection tokens & assign the values to the String variable token as you iterate.

The assignment via ':' works only in for each loop and not in any other constructs

Kakarot
  • 4,252
  • 2
  • 16
  • 18
0

This is also known as a foreach loop which iterates through a collection.

There's a better example here

Community
  • 1
  • 1
Mike
  • 3,186
  • 3
  • 26
  • 32