Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the ":" operator

Tags:

java

operators

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?

like image 277
John Avatar asked Apr 25 '26 09:04

John


1 Answers

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;
}
like image 160
brent777 Avatar answered Apr 26 '26 22:04

brent777



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!