Programming Tips - Java: Why is String.split() not giving me empty strings?

Date: 2012may11 Update: 2025oct15 Language: Java Q. Java: Why is String.split() not giving me empty strings?
String subject = ":"; String []a = subject.split(":");
Gives me an a.length == 0 but I expect 2. A. Regular split (helpfully) deletes trailing empty strings. So use the other form of split. Shown as a full example:
import java.util.Arrays; class Demo { public static final void main(String[] args) { String subject = ":"; String []a = subject.split(":", -1); // <-- Second parameter is -1 System.out.println("a.length=" + a.length); System.out.println("a=" + Arrays.toString(a)); } }
Output:
a.length=2 a=[, ]