String Manipulation Functions in Java

Formulas & functions · Updated November 23, 2026

String manipulation functions in Java are methods provided by the String class (and related classes like StringBuilder, StringBuffer, and StringJoiner) that let you inspect, modify, combine, split, and transform strings. The most commonly used ones include length(), charAt(), substring(), indexOf(), replace(), split(), toLowerCase(), toUpperCase(), and trim().

Why String Manipulation Matters in Java

Strings are one of the most used data types in any programming language, and Java is no exception. Nearly every application processes text: user input, file contents, API responses, database records, or log messages. Java provides a rich set of built-in methods to handle these tasks efficiently and safely. Unlike some older languages where strings are just character arrays, Java treats strings as first-class objects with immutable behavior. This immutability is a core design decision—it makes strings thread-safe and allows them to be cached, but it also means that every modification creates a new string object, which can impact performance if done carelessly.

Core String Class Methods

The String class (in java.lang) contains dozens of methods. Here are the essential ones grouped by purpose:

  • Inspection: length() returns the number of characters; isEmpty() checks if length is zero; charAt(int index) returns the character at a given position.
  • Comparison: equals(Object) compares content; equalsIgnoreCase(String) does case-insensitive comparison; compareTo(String) returns a lexicographic difference; startsWith(String) and endsWith(String) check prefixes/suffixes.
  • Search: indexOf(String) returns the first index of a substring (-1 if not found); lastIndexOf(String) finds the last occurrence; contains(CharSequence) returns a boolean.
  • Extraction: substring(int beginIndex) or substring(int begin, int end) returns a new string; toCharArray() converts to a char array.
  • Transformation: toLowerCase(), toUpperCase(), trim() (removes leading/trailing whitespace), strip() (Unicode-aware, Java 11+), replace(char, char) or replace(CharSequence, CharSequence).
  • Split and Join: split(String regex) divides the string into an array based on a regular expression; String.join(CharSequence delimiter, CharSequence... elements) joins multiple strings.

Example: "Hello, World!".substring(7, 12) returns "World". "a-b-c".split("-") returns ["a", "b", "c"].

Immutability and Its Consequences

Every String object in Java is immutable: once created, its value cannot change. Any method that appears to modify a string actually returns a new string. For example, str.replace("a", "b") does not alter str; it creates a new string with the replacements. This design prevents accidental side effects and makes strings safe to share across threads. However, it also means that building a string through repeated concatenation (e.g., in a loop) creates many intermediate objects, which is inefficient. For such cases, use StringBuilder (non-thread-safe but fast) or StringBuffer (thread-safe but slower).

StringBuilder and StringBuffer

When you need to modify a string repeatedly, use StringBuilder or StringBuffer. Both provide methods like append(), insert(), delete(), reverse(), and toString() to produce a final string. The difference is that StringBuffer methods are synchronized, making it thread-safe but slower. In single-threaded code, StringBuilder is preferred.

Example: StringBuilder sb = new StringBuilder("Hello"); sb.append(" World"); sb.insert(5, ","); String result = sb.toString(); yields "Hello, World".

Regular Expressions and the split/replaceAll Methods

Java’s split() and replaceAll() methods use regular expressions, giving them enormous power but also requiring careful handling of special characters. For instance, to split on a literal dot, you must escape it: "a.b.c".split("\\.") because . matches any character. Similarly, replaceAll() treats the replacement string specially—dollar signs and backslashes have meaning. If you need a literal replacement, use replace() instead, which treats both arguments as plain strings. A common mistake is using replaceAll() when a simple replace() would suffice, leading to unexpected regex behavior.

Performance Considerations and Best Practices

String manipulation can become a performance bottleneck if not done thoughtfully. Key guidelines:

  • Avoid concatenation in loops: String s = ""; for (int i=0; i<1000; i++) s += i; creates 1000 intermediate strings. Use StringBuilder instead.
  • Use String.valueOf() for conversions: String.valueOf(123) is clearer than "" + 123.
  • Be mindful of split() with regex: It compiles the pattern each time; if you call it frequently, precompile with Pattern.compile().
  • Use strip() over trim() for Unicode whitespace: strip() (Java 11+) handles all Unicode whitespace, while trim() only removes characters with code points ≤ U+0020.
  • Consider StringJoiner for joining with prefixes/suffixes: It’s handy for building CSV-like strings.

Common Pitfalls and How to Avoid Them

Developers often trip over these issues:

  • Off-by-one errors with substring(): The end index is exclusive. "hello".substring(1, 3) returns "el", not "ell".
  • Null handling: Calling methods on a null string throws NullPointerException. Always check for null before calling methods, or use Objects.toString(str, "").
  • Locale-sensitive case changes: toLowerCase() uses the default locale, which can cause surprises (e.g., Turkish 'I'). Use toLowerCase(Locale.ROOT) for consistent behavior.
  • Misunderstanding replace() vs replaceAll(): replace(CharSequence, CharSequence) is literal; replaceAll(String, String) is regex.
  • Using == instead of equals(): == compares references, not content. Always use equals() for string content comparison.

Alternatives and Related Classes

Beyond the core classes, Java offers other tools:

  • StringTokenizer (legacy) can split strings but is discouraged in favor of split().
  • java.util.regex.Pattern and Matcher for complex regex operations like finding multiple matches.
  • java.text.MessageFormat for building strings with placeholders, e.g., MessageFormat.format("Hello {0}!", name).
  • String.format() (similar to C's printf) for formatted output: String.format("%,.2f", 1234.5) yields "1,234.50".
  • Text blocks (Java 15+) for multi-line strings with minimal escaping.

Frequently Asked Questions

How do I reverse a string in Java? Use new StringBuilder(str).reverse().toString(). There is no built-in reverse() in the String class.

What's the difference between trim() and strip()? trim() removes characters with code points up to U+0020 (space), while strip() (Java 11+) removes all Unicode whitespace, including non-breaking spaces. For most modern applications, strip() is preferred.

Why is String immutable in Java? Immutability provides security (strings are used in class loading and as keys), thread safety, and performance benefits like string pooling. It also simplifies caching and prevents accidental modification.

Can I modify a string in place? No, because strings are immutable. To modify, you must create a new string or use a mutable class like StringBuilder.

How do I split a string by multiple delimiters? Use a regex character class: "a,b;c".split("[,;]") splits on comma or semicolon.

Is StringBuilder thread-safe? No, it is not. Use StringBuffer if you need thread safety, but in practice, local variables are thread-safe, so StringBuilder is usually fine.

Related

Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.

More in Formulas & functions

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.