John
John

Reputation: 181

Using the ":" operator

I know this is a basic question, but all the documentation I read doesn't seem to answer my question: What does the ":" operator do?

I get the impression that if I do something like for(item : list), the for loop would go through every item of a list. Is this right?

Upvotes: 2

Views: 144

Answers (3)

brent777
brent777

Reputation: 3379

Yes, what you have there is a for each statement. The one you have is not quite correct, if you have a List<String> called list for example then you could do something like this:

for (String item: list) {
   System.out.println(item);
}

As an aside there is also another use for ":" as part of a ternary expression, e.g.

int i = y < 0 ? 10 : 100;

which is the same as:

int i;

if (y < 0) {
   i = 10;
} else {
   i = 100;
}

Upvotes: 6

mipadi
mipadi

Reputation: 410562

Yes. If you have an iterable object, you can do something like:

for (Object o : iterableObj) {
    o.doSomething();
}

which is equivalent (in functionality) to something like:

for (int i = 0; i < iterableObj.length(); i++) {
    Object o = iterableObj.get(i);
    o.doSomething();
}

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1499860

Yes, that's right. It's not really an operator as such - it's part of the syntax for the enhanced for loop which was introduced in Java 5.

Upvotes: 4

Related Questions