The String Class
Master Java's String class: immutability, concatenation, interning, and key methods like substring, split, and format for text processing.
Master Java's String class: immutability, concatenation, interning, and key methods like substring, split, and format for text processing.
The String Class
The String class is one of the most fundamental and frequently used types in Java. Representing sequences of Unicode characters, Strings are immutable objects that provide rich functionality for text manipulation, searching, and formatting.
Introduction
The String class is one of Java’s most frequently used reference types. Strings are immutable: once created, their contents cannot change. That makes them safe to share and useful as map keys. Repeated concatenation in a loop can also create intermediate strings and copy data, though the cost depends on the code and the Java runtime.
String interning lets equal strings share a reference through the String Pool. StringBuilder is often a practical choice when a loop appends many pieces, but benchmark the real workload before treating it as a performance fix. The built-in methods (indexOf, substring, split, replace, format) cover most text manipulation needs without external libraries.
This post covers String immutability, the String Pool and intern(), common methods, and security considerations such as using char[] buffers for passwords. It also explains UTF-16 indexing and common split() and substring() pitfalls.
When to Use / When Not to Use
Use String when:
- Working with text data of any kind
- You need immutable text storage (keys, constants, etc.)
- Building up strings through concatenation in non-critical paths
- Pattern matching with split() or regex
Consider alternatives when:
- Appending many pieces in a loop (consider StringBuilder)
- Frequent string modification (StringBuilder or StringBuffer)
- Case-insensitive comparisons (use Locale-aware comparison)
- Large text manipulation (consider CharSequence or specialized libraries)
String Memory Architecture
graph TD
A["String Pool<br>(interned references)"] --> B["hello<br/>Ref: s1"]
A --> C["hello<br/>Ref: s2<br/>Same as s1"]
D["Heap Memory"] --> E["new String<br>New object"]
F["Reference Variables"] --> A
F --> D
This diagram shows how interning lets references share a string; it is not a map of JVM memory regions. The Java API treats a String as UTF-16 code units, but its internal storage is an implementation detail. OpenJDK changed its representation in JDK 9: compact strings use a byte[] with a coder flag, storing Latin-1 text compactly when possible and UTF-16 otherwise (JEP 254). Other Java implementations can choose a different representation.
Production Failure Scenarios
| Scenario | Cause | Mitigation |
|---|---|---|
| Repeated concatenation in loops | Can copy growing results and create intermediate strings | Try StringBuilder, then benchmark the workload |
Unmeasured use of intern() |
Pool lookups add work and may not help for high-cardinality text | Use interning only when repeated values justify it; measure first |
| Case-sensitive comparison bugs | “ABC”.equals(“abc”) returns false | Use equalsIgnoreCase() or Locale |
| Split creating empty tokens | split(“X”) creates empty strings | Use limit parameter or trim |
| Substring memory leak | Older JDKs could retain the source backing array | Avoid retaining small substrings of large strings on those JDKs |
// Repeated concatenation may copy growing results and create intermediate strings
String result = "";
for (String item : items) {
result += item + ",";
}
// A StringBuilder is often a better fit for many appends; benchmark the real workload.
StringBuilder sb = new StringBuilder();
for (String item : items) {
sb.append(item).append(",");
}
String result = sb.toString();
// Split gotcha: trailing empty strings
String input = "a,b,c,";
String[] parts = input.split(","); // [a, b, c] - no trailing empty
// But with regex
String[] parts2 = input.split(","); // Still [a, b, c]
// For controlled splitting with limit
String[] limited = input.split(",", -1); // [a, b, c, ""] - keeps trailing empty
// Before Java 7u6, a substring could keep the whole source string's backing array alive.
String big = "large string...";
String small = big.substring(0, 5); // In old JDKs, this could retain the source backing array.
// Later JDKs copy the requested content into a separate String representation.
Trade-off Table
| Operation | Method | Performance | Notes |
|---|---|---|---|
| Concatenation | + |
Depends on expression and runtime | Clear for a few values; benchmark repeated concatenation in loops |
| Building | StringBuilder.append() |
Usually suitable for repeated appends | Explicit mutable buffer; benchmark if performance matters |
| Thread-safe building | StringBuffer |
Depends on workload | Methods are synchronized; use when shared mutable text is needed |
| Search | indexOf() |
O(n) | Linear scan |
| Immutable key | String in HashMap | O(1) average | Good for caching |
| Tokenizing | split() or StringTokenizer |
Depends on the operation | split() takes a regex; StringTokenizer is a legacy delimiter-set API |
Implementation Snippets
String Creation and Interning
String literals are interned, so equal literals can share a reference. new String() creates a distinct String object, while intern() returns the canonical pool reference for equal content. Interning can save memory when many values repeat, but measure before using it broadly.
public class StringCreation {
public static void main(String[] args) {
// String literals go to the pool (interned)
String a = "hello";
String b = "hello";
System.out.println(a == b); // true - same pool reference
// new creates heap object
String c = new String("hello");
System.out.println(a == c); // false - different objects
// Explicit interning
String d = c.intern(); // Returns pool reference
System.out.println(a == d); // true
// Constant expressions are combined at compile time
String e = "hel" + "lo"; // "hello"
System.out.println(a == e); // true
}
}
UTF-16 Indexes and Unicode Code Points
The Java String API exposes UTF-16 code units. length(), charAt(), and substring() use code-unit indexes, so a supplementary code point such as 😀 occupies two positions. An arbitrary index can split its surrogate pair. Use codePointCount() to count code points and offsetByCodePoints() to find code-unit indexes for code-point boundaries; codePointAt() reads a code point at a code-unit index. Code points are not always user-perceived characters: a visible character can contain multiple code points, such as a base letter and a combining mark.
public class UnicodeStringIndexing {
public static void main(String[] args) {
String text = "A\uD83D\uDE00B"; // A😀B
int emojiStart = text.offsetByCodePoints(0, 1);
int emojiEnd = text.offsetByCodePoints(emojiStart, 1);
String emoji = text.substring(emojiStart, emojiEnd);
String splitPair = text.substring(1, 2);
System.out.println("length: " + text.length());
System.out.println("code points: " + text.codePointCount(0, text.length()));
System.out.println("substring(1, 2) is a high surrogate: "
+ Character.isHighSurrogate(splitPair.charAt(0)));
System.out.println("safe code-point slice: " + emoji);
}
}
Expected output:
length: 4
code points: 3
substring(1, 2) is a high surrogate: true
safe code-point slice: 😀
Essential String Methods
The String class provides methods for searching (indexOf, contains), extraction (substring, charAt), transformation (toUpperCase, replace, trim), and formatting (String.format). Watch for edge cases: split() drops trailing empty strings by default, trim() has limited whitespace rules, and format() needs the right specifiers. The examples below cover common patterns.
public class StringMethods {
public static void main(String[] args) {
String text = "Hello, World!";
// Searching
int idx = text.indexOf("World"); // 7
int last = text.lastIndexOf("o"); // 8
boolean has = text.contains("ell"); // true
boolean starts = text.startsWith("Hell"); // true
boolean ends = text.endsWith("!"); // true
// Extraction
String sub = text.substring(7); // "World!"
String sub2 = text.substring(7, 12); // "World"
char ch = text.charAt(0); // 'H'
String trimmed = text.trim(); // Removes leading/trailing whitespace
// Transformation
String upper = text.toUpperCase(); // "HELLO, WORLD!"
String lower = text.toLowerCase(); // "hello, world!"
String replaced = text.replace("World", "Java"); // "Hello, Java!"
String[] words = text.split(", "); // ["Hello", "World!"]
// Formatting
String formatted = String.format("Name: %s, Age: %d", "Alice", 30);
// Null-safe operations
String nullStr = null;
String safe = String.valueOf(nullStr); // "null" not NPE
// Or use Objects.toString()
}
}
StringBuilder Patterns
For many appends, StringBuilder is often a practical choice: it keeps a resizable buffer and lets you add content without repeatedly assigning a new String. The actual performance difference depends on the workload and runtime, so benchmark hot paths. StringBuffer has synchronized methods for shared mutable use. The examples below cover CSV building, reversal, palindrome checking, and capacity hints.
public class StringBuilderDemo {
// Efficient string building
public static String buildCsv(List<String> values) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < values.size(); i++) {
if (i > 0) sb.append(",");
sb.append(escapeCsv(values.get(i)));
}
return sb.toString();
}
// Reverse string
public static String reverse(String input) {
return new StringBuilder(input).reverse().toString();
}
// Check palindrome
public static boolean isPalindrome(String s) {
String clean = s.replaceAll("[^a-zA-Z0-9]", "").toLowerCase();
return clean.equals(new StringBuilder(clean).reverse().toString());
}
private static String escapeCsv(String value) {
if (value.contains(",") || value.contains("\"") || value.contains("\n")) {
return "\"" + value.replace("\"", "\"\"") + "\"";
}
return value;
}
}
Observability Checklist
- Monitor string memory usage (String pool size in heap)
- Track StringBuilder usage vs concatenation in performance profiling
- Alert on excessive String.split() operations in hot paths
- Log when interning is called (can indicate memory pressure)
- Measure substring creation overhead in old JVM versions
// Observability for string operations
public class StringMetrics {
public static void trackBuildTime(StringBuilder sb, String context) {
if (sb.length() > 10000) {
Logger.info("Large StringBuilder [{}]: {} chars", context, sb.length());
}
}
public static void trackSplit(String input, String delimiter) {
String[] parts = input.split(delimiter);
if (parts.length > 100) {
Logger.warn("Large split result [{}]: {} parts", input, parts.length);
}
}
}
Common Pitfalls / Anti-Patterns
- Password handling: Strings are immutable, passwords stay in memory until GC. Use
char[]for sensitive data. - Log injection: User input in logs can be exploited; sanitize newlines and special chars
- String comparison timing attacks: Constant-time comparison not native to String (use
MessageDigest.isEqual()) - Encoding issues: Always specify charset when converting bytes to String
// Security: avoid storing passwords in Strings
public class SecurePassword {
public boolean verify(char[] input, char[] stored) {
if (input.length != stored.length) return false;
// Constant-time comparison
boolean match = true;
for (int i = 0; i < input.length; i++) {
match &= (input[i] == stored[i]);
}
// Clear arrays when done
Arrays.fill(input, '0');
Arrays.fill(stored, '0');
return match;
}
}
// Security: specify charset to avoid garbling
byte[] bytes = getData();
String safe = new String(bytes, StandardCharsets.UTF_8); // Always specify
String unsafe = new String(bytes); // Platform default - unpredictable
-
Using == to compare string values
// BAD - compares references, not content String a = new String("hello"); String b = new String("hello"); if (a == b) { } // false // GOOD - compares values if (a.equals(b)) { } // true -
Concatenating in loops
// BAD - creates many intermediate String objects String result = ""; for (String s : list) { result += s; } // GOOD - StringBuilder StringBuilder sb = new StringBuilder(); for (String s : list) { sb.append(s); } String result = sb.toString(); -
Ignoring empty string vs null
// BAD - NPE if str is null boolean empty = str.isEmpty(); // GOOD - handles null boolean empty = (str == null) || str.isEmpty(); // or use Apache Commons StringUtils.isEmpty() -
Case-insensitive comparison without Locale
// BAD - uses system default locale, may not be correct if (str.equalsIgnoreCase("yes")) { } // GOOD - explicitly use US locale for ASCII comparison if (str.equalsIgnoreCase("yes")) { } // Actually fine for ASCII, but for Turkish: str.toUpperCase(Locale.US).equals("YES") // Correct
Quick Recap Checklist
- String is immutable — creating a new String modifies nothing, returns new object
- String literals are interned (stored in String pool for reuse)
- Use new String() only when you need a distinct heap object
- intern() adds a string to the pool and returns the pooled reference
- Use StringBuilder for building strings in loops or multiple operations
- split() with no limit can create empty trailing tokens
- Use char[] instead of String for passwords (immutability prevents clearing)
- Always specify charset when creating strings from bytes
Interview Questions
intern() returns a canonical string from the string pool: equal strings share the same result by reference. Use it only when canonicalization helps the application; do not use `==` as a shortcut for content comparison. The pool's storage and garbage-collection behavior are implementation details, so measure before interning large or high-cardinality inputs.String.split() with no limit (or limit > 0) discards trailing empty strings. For example, "a,b,c,".split(",") returns ["a", "b", "c"] — the trailing empty string is dropped. To preserve trailing empties, use a negative limit: "a,b,c,".split(",", -1) returns ["a", "b", "c", ""]. This behavior mirrors the Unix tool awk and prevents empty tokens at the end of lines from being silently lost.substring() created a new String that could share the source string's backing array. Keeping a short substring could therefore keep a much larger source array alive. JDK 7u6 changed this behavior so a substring no longer shares that array. The API does not promise a particular internal representation for current strings. Use substring() when its code-unit indexes match the text operation you need.indexOf() searches from the beginning of the string toward the end, returning the first index where the substring is found, or -1 if not found. lastIndexOf() searches from the end toward the beginning, returning the last (rightmost) index of the substring. Both support an optional start position parameter. Use indexOf() when you want the first occurrence; use lastIndexOf() when you want the last occurrence, such as finding the final path separator in a file path (path.lastIndexOf('/')). Both perform linear O(n) searching through the string's character array.replace(char, char) replaces all occurrences of a character — returns a new String. replace(CharSequence, CharSequence) replaces all occurrences of a substring. replaceFirst(String regex) replaces only the first match of a regex pattern. replaceAll(String regex, String replacement) replaces all matches of a regex. All return a new String (String is immutable) and perform linear-time scanning for simple character/substring replacements. For regex-based replacements, compilation happens on each call — consider using Pattern.compile() once and reusing the matcher for better performance in loops.length() returns the number of code units, and charAt() can return just one half of a supplementary character's surrogate pair. A supplementary code point therefore takes two code units. Use codePointCount(0, length()) to count code points, codePointAt() to read one, and offsetByCodePoints() to find a code-unit index at a code-point boundary. substring() also takes code-unit indexes, so an arbitrary index can split a surrogate pair.trim() removes leading and trailing ASCII whitespace (code points <= U+0020). It returns a new String with these characters removed. Limitations: it does not remove non-ASCII whitespace (e.g., NBSP U+00A0, BOM U+FEFF), it only looks at char values <= 32, and it cannot distinguish between intentional zero-width space and unwanted whitespace. For Unicode-aware trimming, use strip() (Java 11+) which uses Character.isWhitespace() and handles Unicode properly. stripLeading() and stripTrailing() remove from one side only. For HTML/entity whitespace, use a regex or a library like Apache Commons Text.toLowerCase(Locale.getDefault()) or toUpperCase(Locale.US) to specify locale. The default locale-sensitive versions can produce unexpected results in Turkish locale — for example, 'i'.toUpperCase() in Turkish locale produces 'İ' (dotted I), not 'I'. For ASCII-only strings, explicitly use Locale.ROOT or Locale.US: str.toUpperCase(Locale.US). The toLowerCase() and toUpperCase() without locale use the JVM's default locale, which can change between environments and cause subtle bugs in internationalized applications.String.split() treats its argument as a regular expression and follows its documented rules for trailing empty results. StringTokenizer treats the delimiter argument as a set of delimiter characters and does not produce empty tokens. Choose based on those semantics and readability; do not assume one is faster. If tokenization is a measured bottleneck, benchmark the same input and delimiter behavior on the target JDK.s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1], using `int` arithmetic and UTF-16 `char` values. Immutability means the result stays the same for that string. Whether an implementation caches the computed value is not part of the API contract, so code should not depend on caching for speed.if (str != null) { ... }. 2) Use String.valueOf(obj) which returns "null" for null rather than throwing NPE. 3) Use Objects.requireNonNull() to fail fast on null input. 4) Use Objects.toString() with a default: Objects.toString(str, "default"). 5) In equals comparisons, put the literal first: "literal".equals(str) — this is null-safe (won't throw NPE) and also guards against the literal being mistakenly null. 6) Apache Commons Lang StringUtils.defaultString() and related utilities handle null gracefully.String.format() uses a format string with printf-style specifiers (%s, %d, %.2f) and returns a formatted string. Use it for complex formatted output, aligned columns, or messages that need formatting rules. For simple cases like "Hello " + name, concatenation is clearer. The String API notes that a compiler may implement concatenation with StringBuilder, StringBuffer, or StringConcatFactory, depending on the JDK. Benchmark before changing a hot path.String(byte[], charset) constructor decodes the byte array using the specified charset, throwing UnsupportedEncodingException if the charset is not supported. Always specify a charset explicitly: new String(bytes, StandardCharsets.UTF_8). Without a charset, new String(bytes) uses the JVM's default charset, which varies by platform and locale — a common source of encoding bugs. Similarly, getBytes(charset) should be used instead of getBytes() for consistent encoding. For binary data in strings (Base64, etc.), use proper encoding utilities rather than this constructor.equals() checks string contents; == checks whether both references identify the same object. Interned strings may share a reference, but that does not make `==` a content comparison. For value comparisons, use equals().+ is usually the clearest choice. For many appends, especially inside a loop, try StringBuilder: StringBuilder sb = new StringBuilder(); for (String s : strings) { sb.append(s); } return sb.toString();. Repeated concatenation can copy growing results and create intermediate strings, but the cost depends on the code and runtime. Java compilers may use different strategies for concatenation, so benchmark the actual workload. For streams, Collectors.joining() is another option.isEmpty() (Java 6+) returns true only if length() == 0 — it does not check for whitespace. isBlank() (Java 11+) returns true if the string is empty OR contains only whitespace characters (according to Character.isWhitespace()). Example: " ".isEmpty() is false, but " ".isBlank() is true. "".isBlank() is true (empty is blank by definition). For input validation, isBlank() is usually what you want — it treats spaces, tabs, and other whitespace as empty. For checking if a string has actual content (non-whitespace characters), use isBlank() or trim + isEmpty depending on your requirements.compareTo() compares strings lexicographically by the Unicode value of each character in sequence. Java `String` indexes refer to UTF-16 code units, so this is not locale-aware or a language-sensitive dictionary sort. For locale-sensitive ordering, use `Collator`; for case-insensitive ordering, use an appropriate `String` comparator.Further Reading
- Java Wrapper Classes - Immutable wrappers bridging primitives and objects
- String (Java SE 27) - UTF-16 indexing and concatenation API notes
- JEP 254: Compact Strings - OpenJDK’s compact string representation change
- String Implementation - OpenJDK - Source code for String class
- String Performance - Baeldung - Performance characteristics of String operations
- String Interning Deep Dive - Understanding String pool and intern() method
- Unicode and Java Strings - Oracle tutorial on Unicode handling
Conclusion
The String class is immutable and exposes a sequence of UTF-16 code units through its API. OpenJDK’s internal representation changed with compact strings in JDK 9, but that layout is an implementation detail. Interning lets equal strings share a reference, and the class provides methods for searching, extracting, transforming, and formatting text.
Immutability makes String safe to share and useful as a map key. Repeated concatenation in a loop can copy growing results and create intermediate strings; StringBuilder is a practical option for many appends, and benchmarking can show whether it helps your workload. String literals are interned, while new String() creates a distinct object. split() discards trailing empty strings unless you use a negative limit parameter.
Strings are the most common reference type in Java and appear in virtually every program. For understanding how wrapper classes like Integer and Double handle the boundary between primitives and objects, see Java Wrapper Classes.
Category
Related Posts
Abstract Classes in Java: Interfaces and Composition
Compare Java interfaces, abstract classes, and composition, then see when shared state, default methods, or sealed types change the design choice.
Arithmetic Operators in Java: Division, Overflow, Promotion
Compare Java arithmetic with runnable examples of division, negative remainders, overflow, type promotion, and BigDecimal for decimal money.
Java Array Basics: Length, Bounds, Copies, and Resizing
Learn Java arrays through runtime-sized allocation, bounds checks, aliasing, copying, and the fixed length that distinguishes them from ArrayList.