Lesson 6 / 38

Strings

See why Java Strings are immutable, why you compare them with equals() rather than ==, and how StringBuilder avoids O(n²) concatenation in loops.

Strings are immutable

Every method that seems to "change" a String (toUpperCase, replace, substring, trim) returns a new object; the original is untouched. This makes strings safe to share but wasteful in loops.

Compare with equals()

== tests whether two references point to the same object. To compare contents, use .equals() (or .equalsIgnoreCase()).

String a = "hi";
String b = new String("hi");
System.out.println(a == b);        // false
System.out.println(a.equals(b));   // true

StringBuilder for loops

Concatenating with + inside a loop creates a new string each iteration — O(n²). Use a StringBuilder and call toString() once at the end.

StringBuilder sb = new StringBuilder();
for (int i = 0; i < 5; i++) sb.append(i).append(',');
String csv = sb.toString();   // "0,1,2,3,4,"