-1

I have a string handling related question

split() - The return type is String[]

In this for loop we are storing the split value in a String literal

for (String retval: Str.split("-"))

Why doesn't it give a type mismatch error like in the code below?

String Str1 = "abfg-hjddh-jdj";
String Str = Str1.split("-");
Stefan Podkowinski
  • 5,206
  • 1
  • 20
  • 25

1 Answers1

2
String Str = Str1.split("-");  

gives error because split returns an array, so the correct syntax is:

String[] Str = Str1.split("-");  

In a for-each loop

for (String retval : Str.split("-"))

For each loop : indicates you will be iterating an array, collection or list of Strings, so no error is trhown

Examples:

for (int retval : string.split("-"))   // error, 

ArrayList<Books> books;
for (Book book : books)  // correct

Set<Integer> integers;
for (Integer mInt : integers)  // correct
for (String mInt : integers)  // incorrect!!!

LAST BUT NOT LEAST: variables in Java should start with LOWERCASE, please check Code Conventions.

Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109