Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible that Java String.split can return a null String[]

Is it possible for split to return a null String[]? I am curious as I want to try to be as defensive as possible in my code without having unnecessary checks. The code is as follows:

String[] parts = myString.split("\\w");   

do I need to perform a null check before I use parts post splitting?

like image 520
Woot4Moo Avatar asked Aug 01 '11 17:08

Woot4Moo


People also ask

Can string split return empty array?

If the delimiter is an empty string, the split() method will return an array of elements, one element for each character of string. If you specify an empty string for string, the split() method will return an empty string and not an array of strings.

Does split return an array Java?

split() The method split() splits a String into multiple Strings given the delimiter that separates them. The returned object is an array which contains the split Strings.

How do you return a null string in Java?

In Java, a null value can be assigned to an object reference of any type to indicate that it points to nothing. The compiler assigns null to any uninitialized static and instance members of reference type. In the absence of a constructor, the getArticles() and getName() methods will return a null reference.

Does split return a string?

Using split() When the string is empty and no separator is specified, split() returns an array containing one empty string, rather than an empty array. If the string and separator are both empty strings, an empty array is returned.


Video Answer


1 Answers

It never returns null. You should always check the javadoc of the method if you are not sure. For example String#split(String) says

This method works as if by invoking the two-argument split method

...and String#split(String,int) says:

If the expression does not match any part of the input then the resulting array has just one element, namely this string.

From Javadoc you can also find out what kind of exceptions can happen and more importantly why were those exceptions thrown. Also one very important thing to check is if the classes are thread safe or not.

like image 69
palto Avatar answered Sep 19 '22 01:09

palto