String is an immutable sequence of characters; operations return a result rather than editing the existing object.
Java strings and content equality
Working model
Use equals for content comparison. The == operator compares references. A constant on the left of equals handles a nullable candidate without dereferencing it.
Code
String paymentStatus = new String("PAID");
boolean dispatchAllowed = "PAID".equals(paymentStatus);
String receiptLabel = paymentStatus.toLowerCase(java.util.Locale.ROOT);
System.out.println(dispatchAllowed);
System.out.println(receiptLabel);The output is true and paid. paymentStatus remains PAID. Locale.ROOT makes this machine-facing transformation independent of a user locale.
Cost and design choices
Repeated concatenation inside a large loop can create many intermediate strings. Use StringBuilder for incremental construction. A StringBuilder is mutable, so do not share one between threads without a coordination policy.
Text length is not always character count
String.length counts UTF-16 code units. Some Unicode characters occupy two code units, and a user-perceived character can combine several code points. Indexing and substring boundaries therefore need a defined text model when the input is not restricted to a simple identifier alphabet.
String is immutable, but repeated concatenation in a loop can create intermediate strings and repeated copying. Use a StringBuilder for a growing report, and limit total output size. A small one-off concatenation is a different workload.
Connected lessons
Continue with Java classes and objects, Java Tutorial.
Common Mistakes
Strings are not passwords vaults; an immutable string cannot be wiped in place. Unicode characters can span more than one char. Do not assume length counts user-visible characters.
Define equality, positions and encoding separately
String.equals compares the represented character sequence; == compares whether two references point to the same object. Interning can make some reference comparisons appear to work until input comes from a parser or another allocation. Use the value contract directly.
String positions are UTF-16 code-unit positions. A supplementary code point can occupy two units, and several code points can form one displayed unit. A UI character limit and a protocol byte limit therefore need different measurements. Use an explicit charset when moving text across a byte boundary.
The String object does not change when concatenation returns another String. Repeated accumulation in a loop can create substantial copying and temporary objects; a builder makes the intended mutable assembly phase explicit. That optimization does not decide whether the final value needs normalization or a language-specific comparison rule.
