Skip to content
Preview · sample content · Explore all pages

Java strings and content equality

Last updated: 28 Sept 20263 min read
tutorial
By AITrove Editorial

String is an immutable sequence of characters; operations return a result rather than editing the existing object.

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

Java
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.

java
strings
Storage details