What is the output of the following code?
public class Main { public static void main(String args[]) { StringBuilder s = new StringBuilder (10 + 2 + "SUN" + 4 + 5); s.append(s.delete(3, 6)); System.out.println(s); } }
a
This question tests your understanding of operators, String, and StringBuilder.
The following line of code returns 12SUN45:.
10 + 2 + "SUN" + 4 + 5
The + operator adds two numbers but concatenates the last two numbers.
When the + operator encounters a String object, it treats all the remaining operands as String objects.
Unlike the String objects, StringBuilder objects are mutable.
The append and delete methods defined in this class change its value.
s.delete(3, 6) modifies the existing value of the StringBuilder to 12S5.
It then appends the same value to itself when calling s.append()
, resulting in the value 12S512S5.