In: Computer Science
created a new StringBuilder sb using the following index:
StringBuilder sb = new StringBuilder ("Welcome To ");
What would be sb after each of the following statements? Explain the methods used and how they change the content
sb.append("Java");
sb.insert(11, "HTML and ");
StringBuilder is a predefined class used to create as StringBuffer but the basic difference between both of them is String created by StringBuilder is not synchronized as in StringBuffer it is. The difference between StringBuilder and StringBuffer and common String is that StringBuilder and StringBuffer create mutable String.
As in our question, we created an object of StringBuilder(sb) and passing the value "Welcome To". So when that line is compiled then, a new StringBuilder object will be created initialized with "Welcome To".
Now String will be created containing "Welcome To"
In the second-line, the user called the append function and pass value Java. This function appends the given string at the end of the string stored at StringBuilder.
After calling this function passing "Java" String. After compiling this line, the string will be "Welcome To Java".
And, insert function adds the given string at the given index. That line will add "HTML and " at the 11th index of the string. As we can see in the image, At the 11th index "J" is stored, so "HTML and " will be placed starting from the 11th index.
So Final String Will be
Welcome To HTML and Java