| Author |
I'm Confused : How does this work
|
Arun Giridharan
Ranch Hand
Joined: Sep 30, 2010
Posts: 290
|
|
I'm having a simple String code
the ouput i get is
[, h, e, l]
where does this empty comes from , beside i need to get Exception right ?!
|
 |
Jesper de Jong
Java Cowboy
Bartender
Joined: Aug 16, 2005
Posts: 12929
|
|
Did you expect to get an exception? Why?
The empty string is a valid regular expression, so you can pass it to the split() method without getting an error. When you split a string with the empty string as the delimiter, then Java will act as if there is an empty string between each two characters in the string, and also before the first character of the string. The API documentation of the split() method in class String also explains that trailing empty strings are not included, therefore your array doesn't end with an empty string.
Another point: Why are you creating strings by explicitly invoking new String("hel");? There is never a good reason to create a new String like this, passing a string literal to the constructor of class String. Just do this:
|
Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
|
 |
Arun Giridharan
Ranch Hand
Joined: Sep 30, 2010
Posts: 290
|
|
Jesper de Jong wrote:
Did you expect to get an exception? Why?
I thought ---> No way to split through "" either it has to give null as value or PatternSyntaxException .
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32708
|
|
Why on earth did you think you could get null out of ""? That is the empty String and has nothing whatsoever to do with null. It is (as, I think, Fred Rosenberger says) like the difference between an empty box and no box. The empty String "" is like an empty box, and null would be like not having a box at all
And there is no way you could get null from splitting a String. If you take a String "Campbell" and try to split it on the regular expression "[xyz]", the String will not split. But you will not get null returned. You will get something equal to this:That is, an array with one element, identical to the original String.
|
 |
Arun Giridharan
Ranch Hand
Joined: Sep 30, 2010
Posts: 290
|
|
Thank You.
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32708
|
|
You're welcome
|
 |
 |
|
|
subject: I'm Confused : How does this work
|
|
|