A Java String is immutable: once created it never changes. Methods like toUpperCase return a new String.
public class Strings {
public static void main(String[] args) {
String a = "uni"; String b = "uni"; String c = new String("uni");
System.out.println((a == b) + " " + (a == c) + " " + a.equals(c));
String s = "hello";
s.toUpperCase();
System.out.println(s);
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 5; i++) sb.append(i).append(i < 5 ? "," : "");
System.out.println(sb.reverse());
}
}true false true
hello
5,4,3,2,1What the output shows
- a == b is true because identical string literals share one object from the string pool.
- a == c is false because new String always creates a separate object. == compares references; equals compares the characters. Always use equals (or equalsIgnoreCase) for String content.
- s is still "hello" because the result of toUpperCase was thrown away. Write s = s.toUpperCase().
When to use StringBuilder
Joining Strings with + inside a loop creates a new String each time, copying everything built so far, which is O(n²) for n pieces. StringBuilder appends into one growing buffer, which is O(n) overall. Use it whenever you build a string in a loop. It also offers reverse, insert and deleteCharAt, which are handy in coding rounds. StringBuffer is the older, synchronised version; prefer StringBuilder unless several threads share it.
#java#strings#stringbuilder#immutability
Sources and further reading
Practise this as an interview question
Written by the UniCircle team, checked by an editor on 22 Oct 2026. It is not official policy of any university. Exam patterns and rules change; confirm dates and rules on the official website.
