-1

I'm a Java beginner and have problems understanding what this means:

 for( String string : myWord){

Is there another way to write this? Even if it is probably more complicated, it might help me understand!

Thanks for any help.

nurders04
  • 9
  • 2
  • What specifically don't you understand about it? What it does? Or how it works internally? Or what the parts within the for-loop are? – Ivar Jun 11 '20 at 07:19
  • I dont specifically understand what the colon is aiming to do – nurders04 Jun 11 '20 at 07:23
  • The colon itself is just part of the syntax of the enhanced for loop. It separates the element that is currently iterated over from the collection it gets these elements from. – Ivar Jun 11 '20 at 07:30

2 Answers2

1

Well, assuming that myWord is some sort of collection, such as List, you could use a stream. Assuming your original code:

List<String> myWord = new ArrayList<>();
myWord.add("Hello");
myWord.add("World");
for (String string : myWord) {
    System.out.println(string);
}

Using streams, the above becomes:

myWord.stream().foreach(System.out::println);
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

From the oracle foreach documentation:

When you see the colon (:) read it as "in."

More details and scenarios are available at the oracle link I provided.

dariosicily
  • 4,239
  • 2
  • 11
  • 17