-2

I have just started learning programming, and as I was reading about strings, I found this piece of code:

System.out.print("Conversion from string to char array\n");
    char [] stringToarray = exampleString.toCharArray();
    for (char character : stringToarray) {
        System.out.print(character);
    }

Which I don't fully understand... what does "char character : stringToarray" do? Why can you use it inside a 'for', like that? I am confused because it is not the structure of 'for' I am used to see

Thank you very much for your attention !

  • 1
    Did you try searching for this? – Thiyagu Jul 11 '18 at 17:16
  • It's called `for-each` loop. Check the [documentation](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html) and these [docs](https://docs.oracle.com/javase/8/docs/technotes/guides/language/foreach.html) – jundev Jul 11 '18 at 17:17

1 Answers1

3

In this case it's equivalent to:

for (int i = 0; i < stringToArray.length; i ++){
     char character = stringToArray[i]; 
     System.out.println(character);
}

It's known as a for-each construct and is most commonly used for Collection classes

You can think of it like for( each <element> in <collection> ){ <code-block> }

Hongyu Wang
  • 378
  • 1
  • 10