Question 12
Back to Exercise
What is the output of the following Java program?
import java.util.Arrays;
import java.util.Comparator;
public class Main {
public static void main(String[] args) {
String[] w = {"banana", "Cherry", "apple", "date"};
Arrays.sort(w);
System.out.println(Arrays.toString(w));
Arrays.sort(w, Comparator.comparing(String::length).thenComparing(Comparator.naturalOrder()));
System.out.println(Arrays.toString(w));
}
}
- A [Cherry, apple, banana, date] [date, apple, Cherry, banana] Correct
- B [apple, banana, Cherry, date] [date, apple, banana, Cherry]
- C [Cherry, apple, banana, date] [date, apple, banana, Cherry]
- D [apple, banana, Cherry, date] [date, apple, Cherry, banana]
Correct Answer: Option A
Natural String order compares character codes, so uppercase 'C' comes before lowercase letters. The comparator sorts by length, then naturally: Cherry and banana both have 6 letters, and "Cherry" < "banana".
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!