LearnFrenzy
Sign in Take a free test

Strings and StringBuilder · Predict the Output · Question 11

Reversing the order of words Answer, explanation & discussion

  • Output
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 11 Back to Exercise

What is the output of the following Java program?

Main.java
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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links