Java - Strings

Strings

Immutability

Strings are immutable. Any modification creates a new String object.

String s = "Hello";
s = s + " World"; // new String allocated

String Pool

Literals live in the string pool and may be reused. Use equals() for value equality.

String a = "hi";
String b = "hi";
boolean sameRef = (a == b); // often true (pool), but don't rely on it
boolean sameVal = a.equals(b); // true (correct check)

Common Operations

String s = "  Java,Streams  ";
s.trim();               // "Java,Streams"
s.toUpperCase();        // "  JAVA,STREAMS  "
s.contains("Stream");   // true
s.substring(2, 6);      // "Java"
"a:b:c".split(":");  // ["a", "b", "c"]
String.join(", ", java.util.List.of("a","b")); // "a, b"
String.format("%s %d", "count:", 3); // "count: 3"

StringBuilder vs StringBuffer

  • StringBuilder: not synchronized, faster; prefer in single-threaded code.
  • StringBuffer: synchronized; legacy. Use only when you truly need it.
StringBuilder sb = new StringBuilder();
sb.append("a").append("b");
String out = sb.toString();

Text Blocks (Java 15+)

String json = """
{
  "name": "Ada",
  "age": 36
}
""";

Unicode and Encoding

char is a UTF-16 code unit; some characters require surrogate pairs. Prefer String APIs that operate on code points when needed.

int count = (int) s.codePoints().count();
Never assume s.length() equals the number of user-perceived characters. Combine with normalization when comparing accented text.

Try it

  1. Build a CSV line using String.join and using StringBuilder; compare clarity.
  2. Count code points in a string that includes emoji and compare with length().
  3. Use a text block to format a JSON snippet.