-1

What does : operator mean in the for loop in the context of the code below?

Pond[] ponds = {new Ocean(), new Pond(), new Lake(), new Bay()};
for (Pond p : ponds) {
p.method1(); 
System.out.println(); 
p.method2(); 

On the web it says that : is a ternary operator, but I don't see how it would apply in this case.

CMSC
  • 157
  • 10

5 Answers5

0

In this case its similar to your for loop iteration. It iterates through every element in ponds

Pond[] ponds = {new Ocean(), new Pond(), new Lake(), new Bay()};
for (Pond p : ponds) {
   p.method1(); 
   System.out.println(); 
   p.method2();
}

Ternary operator basically comes with a ? and :

Syntax:

(condition)?(True statement):(False statement)

ganeshvjy
  • 399
  • 1
  • 12
0

The ternary operator is ? : which reads as if someBoolean then a, else b in someBoolean ? a : b.

The : in your case indicates a for-each loop, which reads as: for each pond in ponds.

Stephan Bijzitter
  • 4,425
  • 5
  • 24
  • 44
0

It's an enhanced for loop. In your example, it will iterate over all Pond objects in the ponds array.

Enhanced For Loop

Nick
  • 2,524
  • 17
  • 25
0

":" this is called ternary in conditional operation like : "(1>2)?10:20;"

Colon ":" is used in many places.

AnkeyNigam
  • 2,810
  • 4
  • 15
  • 23
Kulbhushan Singh
  • 627
  • 4
  • 20
  • 1
    Answers are not a place to mention duplicates. State it in the comments of the question. – deezy Jul 19 '15 at 17:06
0

ponds is an array of Pond objects. The loop is called an 'Enhanced for loop', essentially the same as a 'for each' loop in other languages, and it iterates thought the entire arrays length. For each pond in in the array it's assigning the value of the index in the array that it's current iterated to and assigning it to the variable p. So in this loop every time it it iterates to the next value it assigns that value to p and runs the code on p that is within the loop.

cbender
  • 2,231
  • 1
  • 14
  • 18