aspose file tools*
The moose likes Beginning Java and the fly likes I'm Confused : How does this work Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "I Watch "I New topic
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
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14338
    
  22


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 8 API documentation
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: 39791
    
  28
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: 39791
    
  28
You're welcome
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: I'm Confused : How does this work