Question 4
Back to Exercise
What is the output of the following Java program?
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
String line = ",a,,b,,";
System.out.println(Arrays.toString(line.split(",")) + " " + line.split(",").length);
System.out.println(line.split(",", -1).length + " " + "a b c".split(" ").length + " " + "a b c".split(" +").length);
}
}
- A [, a, , b] 4 6 4 3 Correct
- B [a, b] 2 6 3 3
- C [, a, , b, , ] 6 6 4 3
- D [a, , b] 3 5 4 3
Correct Answer: Option A
Leading empty strings are kept, trailing ones dropped (unless the limit is negative). Two spaces in a row produce an empty field unless the regex is " +".
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!