Will Java's split override the length of array even if it is pre initialized?

String [] arr = {" "," "," "," "};  // String arr = new String[4];
String splitThis = "Hello, World, There";
arr = splitThis.split(","); 
arr[3] = "YAY"; 

The fourth line throws an Array Index Out of bounds Exception. Even though the array is of length 4. How to progress in this case?

Jon Skeet
people
quotationmark

No, the array isn't length 4. The array is of length 3, because it's the result of the split operation.

Your code is effectively just:

String splitThis = "Hello, World, There";
String[] arr = splitThis.split(","); 
arr[3] = "YAY";

Once you've done an assignment to a variable, its previous value doesn't matter at all. The split method returns a reference to an array, and you're assigning that reference to arr. The split method is unaware of the previous value of the variable - it operates entirely independently of what you happen to do with the value afterwards - so it's not just filling in part of an existing array.

If you want that sort of behaviour, you could use something like this:

String[] array = { " ", " ", " ", " " }; // Or fill however you want
String splitThis = "Hello, World, There";
String[] splitResults = splitThis.split(",");
System.arraycopy(splitResults, 0, array, 0,
                 Math.min(array.length, splitResults.length));

Or perhaps you want a List<String> so you can add items later:

String splitThis = "Hello, World, There";
List<String> list = new ArrayList<>(Arrays.asList(splitThis.split(","));
list.add(...);

people

See more on this question at Stackoverflow