• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

I'm Confused : How does this work

 
Arun Giridharan
Ranch Hand
Posts: 290
Debian Fedora Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Saloon Keeper
Posts: 15480
43
Android IntelliJ IDE Java Scala Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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:

 
Arun Giridharan
Ranch Hand
Posts: 290
Debian Fedora Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 50171
79
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 290
Debian Fedora Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank You.
 
Campbell Ritchie
Sheriff
Pie
Posts: 50171
79
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're welcome
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic