What is the output of the following Java code?
public class Test { public static void main(String[] args) { String s = ""; for (int i = 0; i < 3; i++) { s += i; } System.out.println(s); } }
Remember that String concatenation with += creates new String objects each time.
The loop appends the numbers 0, 1, and 2 to the empty string. So the output is "012".
What is the output of this Java code using StringBuilder?
public class Test { public static void main(String[] args) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < 3; i++) { sb.append(i); } System.out.println(sb.toString()); } }
StringBuilder appends efficiently without creating new objects each time.
The StringBuilder appends 0, 1, and 2, resulting in "012".
Consider these two code snippets. Which one is faster for large loops and why?
1) Using String with += in a loop
2) Using StringBuilder with append in a loop
Think about how many objects are created in each approach.
StringBuilder is faster because it changes the same object, avoiding many temporary String creations that happen with +=.
What is the output of this Java code?
public class Test { public static void main(String[] args) { StringBuilder sb = new StringBuilder("hello"); sb.reverse(); System.out.println(sb.toString()); } }
StringBuilder has a method to reverse the characters in the string.
The reverse() method reverses the characters, so "hello" becomes "olleh".
Which statement correctly describes the difference between String and StringBuilder in Java regarding immutability and thread safety?
Think about which class can be changed after creation and which can be safely used by multiple threads.
String objects cannot be changed after creation, making them thread-safe. StringBuilder objects can be changed but are not thread-safe.
