Reputation: 327
if I do
String a = ""
String b = a.split(" ")[0];
It is not giving ArrayIndexOutOfBoundException
but when I do
String a = " "
String b = a.split(" ")[0];
It is giving me ArrayIndexOutOfBoundException
again when I do
String a = " abc"
String b = a.split(" ")[0];
It is not giving me Exception WHY SO?
Upvotes: 11
Views: 231
Reputation: 148
String a = "";
String b = a.split(" ")[0];
When you do this, since there is no 'split' character present, therefore no split action is performed and an array is returned with first and only element as an empty string.
String a = " ";
String b = a.split(" ")[0];
while in this case it tries to split the string but get no values to be placed in either side, therefore no array is created. thus when you are trying to access its 0th element, it is giving ArrayOutOfBoundException.
String a = " abc";
String b = a.split(" ")[0];
In this case, splitting takes place and "abc" is placed at 0th place (I guess) and you are left with an array with a size greater that 0. Problem Solved!!..
Upvotes: 1
Reputation: 500357
Case #1
String a = ""
String b = a.split(" ")[0];
From the Javadoc:
If the expression does not match any part of the input then the resulting array has just one element, namely this string.
So split()
gives you a single-element array, consisting of the input string (""
). Therefore there's no exception.
Case #2
String a = " "
String b = a.split(" ")[0];
From the Javadoc:
Trailing empty strings are therefore not included in the resulting array.
You have two such trailing empty strings, and nothing else. Therefore you get back a zero-size array, resulting in the exception.
Case #3
String a = " abc"
String b = a.split(" ")[0];
It's not much of a corner case as it clearly has to return at least one element, hence no exception.
Upvotes: 2
Reputation: 29576
It's always a possibility that String.split()
will return an empty array if there is a complete match on the provided regex
Upvotes: 0
Reputation: 15990
It's kind of weird.
Thing is, in your first example, the empty String "" is a String, not null. So when you say: Split this "" with the token " ", the patterns doesn't match, and the array you get is the original String. Same as if you did
String a = "abc";
String b = a.split(" ")[0];
The pattern to split doesn't match, so you get one token, the original String.
You get an exception on the second case because the COMPLETE content of your String is exactly the delimiter you've passed to split, so you end up with an empty array.
Let me know if you want some further details, but this is pretty much it.
Upvotes: 3
Reputation: 1306
After:
String a = " "
String[] arr = a.split(" ");
arr
is an empty array. That's why it throws an ArrayIndexOutOfBoundsException
when you try to access its first (and non-existant) element. Now, after:
String a = " abc"
String[] arr = a.split(" ");
arr
has one element: "abc"
, which is why no exception is thrown when you try to access its first element.
Upvotes: 2