-2

According to the String.split() documentation the method returns array, so how come the following code compiles?

The retval variable inside the for loop is a String and not an array but there is no error?

public class String_Splitting_Example 
{
    public static void main(String args[])
    {
        String Str = new String("Welcome-to-Tutorialspoint.com");
        System.out.println("");
        System.out.println("Return Value :" );
        for (String retval: Str.split("-"))
        {
            System.out.println(retval);
        }
    }
}
dimo414
  • 44,897
  • 17
  • 143
  • 228
kittu
  • 6,112
  • 20
  • 81
  • 157

2 Answers2

4

String.split() returns an array. It isn't assigning the result of the call to retval (notice there's no = assignment operator). Instead, the : notation means it's using a for-each loop to iterate over the array, and assigning each element in turn to retval.

As @nobalG points out there are a number of good resources on StackOverflow as well. Check out some questions tagged java and foreach.

Community
  • 1
  • 1
dimo414
  • 44,897
  • 17
  • 143
  • 228
1

As Jared Burrows commented, by writing for (String retval: Str.split("-")) you are iterating through each part of the array where retval contains the current String in the array of Strings you got from doing Str.split

Moishe Lipsker
  • 2,954
  • 2
  • 23
  • 27