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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With