0
0
Javaprogramming~15 mins

String vs StringBuilder in Java - Practice Questions

Choose your learning style8 modes available
trophyChallenge - 5 Problems
🎖️
String Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
💻 code output
intermediate
2:00remaining
Output of String concatenation in loop

What is the output of the following Java code?

Java
public class Test {
    public static void main(String[] args) {
        String s = "";
        for (int i = 0; i < 3; i++) {
            s += i;
        }
        System.out.println(s);
    }
}
Anull012
B0 1 2
C0123
D012
Attempts:
2 left
💻 code output
intermediate
2:00remaining
Output of StringBuilder append in loop

What is the output of this Java code using StringBuilder?

Java
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());
    }
}
A0 1 2
B012
Cnull012
D0123
Attempts:
2 left
💻 code output
advanced
2:00remaining
Performance difference in string concatenation

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

AStringBuilder is faster because it modifies the same object without creating new ones.
BString with += is faster because it is simpler to write.
CBoth have the same speed because Java optimizes string concatenation automatically.
DString with += is faster because it uses less memory.
Attempts:
2 left
💻 code output
advanced
2:00remaining
Output of StringBuilder reverse method

What is the output of this Java code?

Java
public class Test {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("hello");
        sb.reverse();
        System.out.println(sb.toString());
    }
}
Aolleh
Bhello
Cnull
DHELLO
Attempts:
2 left
🧠 conceptual
expert
2:00remaining
Immutability and thread safety of String vs StringBuilder

Which statement correctly describes the difference between String and StringBuilder in Java regarding immutability and thread safety?

ABoth String and StringBuilder are immutable and thread-safe.
BString is mutable and thread-safe; StringBuilder is immutable and not thread-safe.
CString is immutable and thread-safe; StringBuilder is mutable and not thread-safe.
DBoth String and StringBuilder are mutable and not thread-safe.
Attempts:
2 left