Java 8 String Functions: Common Methods and Examples

Formulas & functions · Updated November 22, 2026

In Java 8, “string functions” usually means methods on the String class, such as length(), substring(), contains(), and replace(). Java 8 also added useful ways to join strings and access their characters as streams; because strings are immutable, these methods return results rather than changing the original string.

What “string functions” means in Java

Java does not call these operations string functions in the same way some languages do. Most are instance methods of java.lang.String, which is available automatically without an import. You call a method on a string value, for example name.length(). A few related tools are separate APIs: String.format() is a static method, while StringBuilder and Java 8’s StringJoiner are different classes.

Many familiar methods existed before Java 8. The version matters because Java 8 does not have some methods added in later releases. In particular, isBlank(), strip(), lines(), and repeat() are not Java 8 String methods. Code that uses them will not compile against a Java 8 API. For Java 8, use alternatives such as trim() where appropriate, or a small helper for repeated text.

Strings are immutable

A Java String cannot be changed after it has been created. A call like text.toUpperCase() produces another string; it does not alter text. To keep the result, assign it to a variable:

String text = "java 8";
String upper = text.toUpperCase();
System.out.println(text);  // java 8
System.out.println(upper); // JAVA 8

This behavior is easy to overlook when cleaning input. Calling text.trim(); and then using text later leaves the original value unchanged. Write text = text.trim(); if the trimmed result should replace the variable’s value. The variable now refers to a different string, but the original string itself was never modified.

Immutability is useful when strings are shared: one part of a program cannot silently change text another part is using. It also means repeated concatenation in a loop can create many intermediate strings. For that case, use StringBuilder and convert the completed result with toString().

Length, characters, and substrings

length() returns the number of UTF-16 code units in a string, not necessarily the number of user-perceived characters. charAt(index) returns one UTF-16 code unit at a zero-based index. For ordinary English text, those details often match expectations. Some Unicode characters, including many emoji, need a pair of code units, so a single visible symbol can count as length two and cannot be represented by one char.

substring(beginIndex) returns text from the given index through the end. substring(beginIndex, endIndex) includes the beginning index but excludes the end index. Both indexes must be within range, or Java throws IndexOutOfBoundsException.

String word = "String";
System.out.println(word.length());        // 6
System.out.println(word.charAt(0));       // S
System.out.println(word.substring(1, 4)); // tri

For code that must handle supplementary Unicode characters as code points, Java 8 provides codePointCount(), codePointAt(), and offsetByCodePoints(). The chars() and codePoints() methods provide streams of character values, discussed below. Even with code points, visual cursor positions can be more complicated because some displayed symbols combine multiple code points.

Searching and checking text

Several methods answer whether or where text occurs. contains() checks for a literal character sequence and returns a boolean. indexOf() returns the first matching index or -1 when there is no match; lastIndexOf() searches from the end. Overloads allow searching for a character or a string, optionally starting at an index.

startsWith() and endsWith() check prefixes and suffixes. These checks are case-sensitive. For example, "report.csv".endsWith(".csv") is true, while checking against ".CSV" is false. If a file extension or identifier should be compared without regard to case, normalize both values using a deliberate locale choice, or use an API designed for the specific data format.

Use isEmpty() to test whether a string has length zero. It does not treat spaces as empty: " ".isEmpty() is false. Java 8 has no isBlank(); if whitespace-only input must count as blank, define that rule explicitly. For example, trimming and then checking emptiness is a common basic check, but Java 8’s trim() does not recognize every Unicode whitespace character.

Comparing strings correctly

Use equals() to compare string contents. The == operator checks whether two references point to the same object, not whether their text is equal. String literals may be interned, which can make == appear to work in a small example, but it is not a reliable content comparison.

String first = new String("oak");
String second = new String("oak");
System.out.println(first == second);      // false
System.out.println(first.equals(second)); // true

equalsIgnoreCase() performs a case-insensitive comparison, but it is not a general language-aware sorting or collation tool. compareTo() provides lexicographic ordering based on the string’s character values and returns a negative number, zero, or a positive number. Do not expect its exact nonzero result to be only -1 or 1. For human-language sorting, use a Collator configured for the relevant locale rather than assuming compareTo() follows dictionary rules.

Changing case, trimming, and replacing text

Java 8 provides toLowerCase() and toUpperCase(), each with overloads that accept a Locale. The no-argument versions use the JVM’s default locale, which can produce unexpected results for machine-oriented text such as protocol keys or identifiers. For locale-independent normalization, use Locale.ROOT:

import java.util.Locale;

String key = input.toLowerCase(Locale.ROOT);

trim() returns a string with leading and trailing characters whose values are at most U+0020 removed. It does not remove whitespace inside the text, and its definition is narrower than the Unicode-aware strip() method added in a later Java release. That distinction matters when inputs may contain non-ASCII spaces.

replace() performs literal replacement of characters or character sequences. replaceAll() and replaceFirst(), by contrast, interpret the search argument as a regular expression. This is a frequent source of bugs: a dot in a regular expression matches any character, not just a period. To replace literal text, prefer replace(); if a regular expression is needed, escape special characters as appropriate.

Splitting and joining strings

split() divides text using a regular-expression delimiter and returns a String[]. A period, pipe, or other regex metacharacter may need escaping. The one-argument form behaves as though the limit were zero, so trailing empty fields are discarded. Pass a negative limit to keep them:

String csvLike = "red,blue,";
String[] withoutTrailingEmpty = csvLike.split(",");
String[] withTrailingEmpty = csvLike.split(",", -1);
System.out.println(withTrailingEmpty.length); // 3

For actual CSV files, splitting on commas is generally insufficient because quoted fields can contain commas and other CSV rules apply; use a CSV parser when the input follows that format.

Java 8 introduced String.join(). It accepts a delimiter followed by values, or a delimiter and an Iterable of character sequences. It is handy for simple lists:

String joined = String.join(" - ", "Mon", "Tue", "Wed");
System.out.println(joined); // Mon - Tue - Wed

For more control, Java 8 also introduced StringJoiner in java.util. It supports a delimiter and optional prefix and suffix, and can supply text for an empty joiner. Joining is clearer than building a result with manual delimiter checks, especially when the number of values is not known in advance.

Formatting, streams, and efficient construction

String.format() creates formatted text using format specifiers, much like printf. For example, String.format("%s: %d", "items", 3) produces items: 3. Formatting can depend on locale, especially for numbers, so use the overload that accepts a Locale when output must follow a specified convention. For simple concatenation of a few values, the + operator is usually easier to read.

Java 8 added chars() and codePoints(), which return IntStream values. The first emits UTF-16 code units as integers; the second combines valid surrogate pairs into Unicode code points. A basic example is "cat".codePoints().forEach(System.out::println). These methods are useful for stream operations, but they do not automatically solve every text-processing problem, such as grapheme-cluster counting or locale-sensitive case conversion.

For many appends, use StringBuilder rather than repeatedly combining immutable strings in a loop:

StringBuilder result = new StringBuilder();
for (String part : parts) {
    if (result.length() > 0) {
        result.append(", ");
    }
    result.append(part);
}
String text = result.toString();

For simple joining, String.join() or StringJoiner may be shorter. A StringBuilder is mutable and is not synchronized; it is commonly used as a local variable while constructing a result. StringBuffer is a synchronized alternative, but synchronization is not automatically needed for a builder confined to one thread.

Common mistakes and practical choices

  • Using == for text: use equals() for content equality.
  • Forgetting immutability: assign the result of trim(), case conversion, or replacement if you need to keep it.
  • Confusing literal search with regex: replaceAll() and split() use regular expressions; replace() is literal.
  • Assuming character indexes count visible symbols: Java indexes UTF-16 code units, so some Unicode symbols occupy two positions.
  • Using newer APIs on Java 8: methods such as strip() and isBlank() are unavailable in Java 8.

A useful rule of thumb is to select the simplest method matching the task: contains() for a literal presence check, equals() for content equality, replace() for literal substitution, split() for regex-based tokenization, and join() for combining values with a delimiter. Consider input size, encoding expectations, and whether the text is human language or a machine-defined format before choosing a more elaborate approach.

Frequently Asked Questions

Are strings mutable in Java 8?
No. A String is immutable. Methods that appear to change its case, spacing, or contents return a new string, so assign that return value if you want to use it.

Does Java 8 have isBlank() or strip()?
No. Those methods were added after Java 8. Java 8 provides trim(), but it has a narrower whitespace definition; choose a Unicode-aware alternative if that distinction matters.

What is the difference between equals() and ==?
equals() compares string contents. == compares object references. Use equals() for ordinary text comparisons.

Does String.length() count characters?
It counts UTF-16 code units. Many common characters occupy one unit, but some Unicode symbols use two. Use code-point methods when code-point counting is what the task requires.

Is split(",") safe for CSV data?
Not for general CSV. It applies a regular expression and does not handle quoted fields containing commas. Use a CSV parser for files that follow CSV rules.

Which Java 8 method joins strings?
Use String.join() for a delimiter-separated result, or StringJoiner when you also need a prefix, suffix, or custom empty value.

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.