My doubt is why do i get the length as 12 though the length of the string is 11,i see that there is no element at index 0
There are actually two things working here...
The first is... you are using "nothing" as the split string -- or to be more specific, "nothing OR nothing" as the split string. This means that you will get a match at the boundary of every character. This means that there is a split before the first character, and hence, your first element is a zero-length value.
Now the questions is... why are we seeing a length of 12? Instead of 13, as there should be a split at the end of the string too? Which leads to the second thing...
The default split() method, calls the regex version of split() that uses a value of zero to limit the number of matches. This has the effect of removing any trailing zero-length matches. This is why you don't see a empty string element at the end.
As you pointed out, the pipe (|) is a special character meaning "or". So when you split on "|", you are essentially splitting on "nothing or nothing." Note that splitting on an empty String ("") generates the same results. Also note that the length of an empty String is zero.
According to the API documentation for split, "The array returned by this method contains each substring of this string that is terminated by another substring that matches the given expression or is terminated by the end of the string."
In this case, the first match of "nothing" (with length zero) is at index 0. So the empty String returned as the first array element is the substring that's terminated at index 0.
"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer sscce.org
Raj Kumar Bindal
Joined: Apr 15, 2006
First of all i would like to tell you that the code you are writing has nothing to do with | character.Because the way you are using it reveals an OR operator. If you will write: String wow = m.split(""); then also this output will be same because once you have started splitting with OR operator then it has nothing to to with | operator.If you will give some other character in place of | in String m,then also,after splitting it will show length as 12.
Actually it is the only way split method is designed.