Issue
My logs show this exception: ArrayIndexOutOfBoundsException: length=0; index=0
triggered by the following piece of code:
public static String getInitialsFromFullName(String fullName)
{
String[] splitNames = fullName.split(" ");
String firstName = splitNames[0]; <-- Here
...
}
I am trying to figure out the condition for which String.split returns an empty array. My understanding is that if no match is found, an array of size 1 with the original string is returned.
This is Java compiled for the Android build SDK version 21. I am looking forward to hear what obvious detail I am missing.
Solution
split(regex)
returns result of split(regex,0)
where 0
is limit
. Now according to documentation (limit is represented by n
)
If
n
is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.
(emphasis mine)
It means that in case of code like
"ababaa".split("a")
at first you will get array ["", "b","b","",""]
but then trailing empty string swill be removed, so you will end up with array ["","b","b"]
BUT if your string contains text which can be matched by split
pattern entirely, like
"ababab".split("ab")
at first resulting array will contain ["","","",""]
(three splits), but then empty trailing strings will be removed. Since all of them are trailing empty strings all of them will be removed from array and empty array will be returned []
(array with size 0).
So to get empty array as result you need to split on string which is build from parts which can be matched by split
pattern. This means that in case of yourString.split(" ")
the yourString
must contain only spaces (at least one, see BTW for more info)
BTW if original string would be empty ""
and we call "".split("any-value")
then splitting won't happen (split nothing makes no sense). In such case array containing original string [""]
will be returned and that empty string will NOT be removed because it was not result of splitting.
In other words removing trailing empty strings makes sense only if these empty strings ware created as result of splitting, like "abaa".split("a")
initially creates ["","b", "",""]
. So when splitting didn't happen "cleanup" is not required. In such case result array will contain original string as explained in my earlier answer on this subject.
Answered By - Pshemo
Answer Checked By - Candace Johnson (JavaFixing Volunteer)