LearnFrenzy
Sign in Take a free test

Strings and StringBuilder · Predict the Output · Question 6

Chaining StringBuilder operations Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 6 Back to Exercise

What is the output of the following Java program?

Main.java
public class Main {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("12345");
        sb.reverse().append('0').insert(2, '-').deleteCharAt(0);
        System.out.println(sb + " " + sb.length() + " " + sb.charAt(1));
    }
}
  • A 4-3210 6 - Correct
  • B 54-3210 7 4
  • C 4-321 5 -
  • D 5-43210 7 -
Correct Answer: Option A

54321 → 543210 → 54-3210 → 4-3210 (6 characters). Each method changes and returns the same builder.

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