Question 11
Back to Exercise
What is the output of the following Java program?
public class Main {
public static void main(String[] args) {
String sentence = "Java is fun";
String[] words = sentence.split("\\s+");
StringBuilder sb = new StringBuilder();
for (int i = words.length - 1; i >= 0; i--) {
sb.append(words[i]);
if (i > 0) sb.append(' ');
}
System.out.println(sb + "|" + new StringBuilder(sentence).reverse());
}
}
- A fun is Java|nuf si avaJ Correct
- B nuf si avaJ|fun is Java
- C fun is Java|nuf si avaJ
- D fun is Java|fun is Java
Correct Answer: Option A
Splitting on \s+ collapses the double spaces; reversing the whole builder reverses every character, spaces included.
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!