Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String#split behavior when splitting the empty string according the "\s+"

Tags:

java

arrays

split

I am a newbie in Java. Unfortunately, in Java there is a lot of stuff that is very hard to understand to a newbie.

For example,

String str = "";
String[] arr = str.split("\\s+");
System.out.println(Arrays.toString(arr));
System.out.println(arr.length);
System.exit(0);

The output is

[]
1

But why? I will appreciate if someone can explain me why the length of the array is 1.

like image 693
com Avatar asked Nov 30 '22 23:11

com


1 Answers

Even if the String instance is empty, it is still a String instance and the "nothing" must be put somewhere after split(). Thats the one element in the array.

If you printed str[0], you would get an empty string. The real "nothing" would be null but than you would get NullPointerException (you can't call split() on null value)

like image 139
Erveron Avatar answered Dec 04 '22 16:12

Erveron