String Immutability and StringBuilder
String is immutable. Operations such as concatenation produce a new string rather than changing the existing instance.
String name = "Java";
String upper = name.toUpperCase();
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 3; i++) {
builder.append(i).append(',');
}
String result = builder.toString();
Repeated concatenation in a large loop can create unnecessary temporary strings. StringBuilder is generally appropriate for incremental construction in one thread.
String equality
Use equals() for string content. == compares reference identity for objects.
Key Takeaways
- Strings are immutable.
- Use
StringBuilderfor repeated string construction. - String pooling is not a reason to use
==for value comparison.