Java String Functions: Methods, Examples, and Common Uses

Formulas & functions · Updated November 22, 2026

In Java, “string functions” usually means methods of the String class, such as length(), substring(), contains(), and replace(). These methods inspect, search, compare, or transform text; because strings are immutable, methods that change text return a new string rather than modifying the original.

What Java Means by String Functions

Java’s terminology is object-oriented: a string operation is generally an instance method called on a String object. For example, message.length() calls the length() method on the value stored in message. This differs from a standalone function that receives a string as an argument, though developers often use “function” informally when searching for Java string operations.

The String class belongs to java.lang, which Java makes available without an import statement. A string literal uses double quotes, while a single character uses the primitive char type and single quotes:

String message = "Hello, Java!";
int size = message.length();
char first = message.charAt(0);

Here, size is 12 and first is 'H'. The index of the first character is zero, a convention that also applies to many other Java collections and APIs.

How String Immutability Works

A String is immutable: once created, its character sequence cannot be changed. A method such as toUpperCase() returns a result, but it does not rewrite the object on which it was called. Assign that result if you need to keep it:

String name = "Mina";
name.toUpperCase();
System.out.println(name); // Mina

name = name.toUpperCase();
System.out.println(name); // MINA

This behavior helps make strings predictable and safe to share. It also explains a common beginner error: calling a transformation and expecting the original variable to change. A method call can produce the desired value while the program still holds the original string if the returned value is ignored.

Repeatedly joining text inside a large loop can create many temporary strings. For a small number of values, the + operator is clear and convenient. For frequent incremental building, use StringBuilder, which is designed for mutable text construction:

StringBuilder result = new StringBuilder();
for (String word : words) {
    result.append(word).append(' ');
}
String sentence = result.toString();

Use a String for text you want to pass around as a value; consider StringBuilder when appending many pieces in a loop. The builder’s toString() method produces the finished immutable string.

Methods for Measuring and Extracting Text

These commonly used methods help inspect a string or obtain a portion of it:

  • length() returns the number of UTF-16 code units in the string.
  • isEmpty() is true only when the string has zero length. A string containing spaces is not empty.
  • charAt(index) returns the character at a zero-based index. An invalid index causes an IndexOutOfBoundsException.
  • substring(beginIndex) returns text from the given index to the end.
  • substring(beginIndex, endIndex) includes the starting index and excludes the ending index.

For example, with String code = "JAVA-2026";, code.substring(0, 4) returns "JAVA", and code.substring(5) returns "2026". The endpoint rule makes the number of characters in a substring equal to endIndex - beginIndex, which is useful when calculating ranges.

Java 11 added isBlank(), which returns true when a string is empty or consists only of whitespace characters as recognized by Java’s whitespace rules. It is not interchangeable with isEmpty(): for example, " ".isEmpty() is false, while " ".isBlank() is true. If a project targets an older Java version, isBlank() is unavailable.

Searching and Comparing Strings

Use contains() to test whether a string includes a sequence of characters, and startsWith() or endsWith() to check its beginning or ending. These methods return booleans, so they fit naturally into conditions:

String file = "report.csv";
if (file.endsWith(".csv")) {
    System.out.println("CSV file");
}

For a position, use indexOf(). It returns the first matching index, or -1 when no match exists. Overloads let you search for a character or a string, and lastIndexOf() searches from the end. Check for -1 before using a returned position as a substring boundary.

To compare string contents, use equals(), not ==. The == operator checks whether two references point to the same object; it does not reliably ask whether their text is identical. For example, new String("cat").equals("cat") is true even though the objects can be distinct. Use equalsIgnoreCase() when case-insensitive comparison is appropriate.

Case conversion has a locale detail worth knowing: toLowerCase() and toUpperCase() can depend on the default locale. For identifiers or other text that should follow language-neutral rules, use toLowerCase(Locale.ROOT) or toUpperCase(Locale.ROOT) and import java.util.Locale. For user-facing language, locale-sensitive behavior may be desirable instead.

Replacing, Trimming, and Splitting Text

replace() can replace literal characters or character sequences. In contrast, replaceAll() treats its first argument as a regular expression. That distinction matters when searching for characters that have special meaning in regular expressions, such as a period or a dollar sign. Use replaceFirst() when only the first regex match should be replaced.

For example, text.replace(".", "!") replaces literal periods. With text.replaceAll(".", "!"), the dot is a regex wildcard that matches characters, so the result may be very different. Regular expressions are useful for patterns, but a literal replacement is simpler and safer when that is all the task requires.

trim() removes leading and trailing characters whose values are at most U+0020. Java 11’s strip(), stripLeading(), and stripTrailing() use Unicode-aware whitespace rules and are often a better choice for modern text. Neither approach removes spaces from the middle of a string.

split(regex) divides text using a regular expression and returns a string array. Since the separator is a regex, a pipe character, period, or other regex symbol may need escaping. The default one-argument form drops trailing empty fields. Pass a negative limit to keep them:

String row = "red,blue,";
String[] fields = row.split(",", -1);
// fields contains "red", "blue", and an empty final element

For fixed-format data, think about empty fields and escaping before relying on a split result. For complex CSV files, a dedicated CSV parser is generally more suitable than splitting on commas because quoted fields can themselves contain commas.

Formatting and Building Text

When you need to insert values into a template, String.format() uses format specifiers. For instance, String.format("Item: %s, count: %d", item, count) inserts a string for %s and an integer for %d. Format specifiers can also control width and decimal precision; %.2f displays a floating-point value to two digits after the decimal point.

Formatting is convenient for readable output, but it is not the only way to combine values. Concatenation is often clearer for a short message, while a builder suits repeated appends. Select the approach that makes the code easiest to understand, and avoid assuming formatting changes the original value: String.format() returns a new string.

Java text blocks, available as a standard feature starting in Java 15, provide a readable way to write multiline string literals. They are useful for embedded text such as templates or sample JSON, but they do not automatically validate or safely escape data for SQL, HTML, or another language. Use the appropriate parameterized API or encoder when inserting untrusted values into those contexts.

Unicode and Character Indexing

Java’s String stores text as UTF-16 code units. Consequently, length() does not always equal the number of user-perceived characters. Many familiar characters use one code unit, but some Unicode characters, including many emoji, use a pair of code units. A character represented by a pair can therefore contribute two to length().

For code that needs Unicode code points rather than UTF-16 units, codePointCount() can count code points in a range, and codePoints() provides an integer stream of them. For example, text.codePointCount(0, text.length()) counts code points across the full string. Even code points are not always the same as visible characters: some displayed symbols consist of multiple code points joined together. User-interface cursor movement and text selection may need higher-level Unicode handling.

Common Mistakes and Practical Choices

When choosing a method, first identify the actual operation: checking, finding, extracting, replacing, or assembling. A few safeguards prevent many everyday bugs:

  • Do not use == to compare text content; use equals() or an explicitly chosen comparison method.
  • Remember that string transformations return values. Save the result if you need to use it later.
  • Check bounds before calling charAt() or substring(), especially when indexes come from user input or a search result.
  • Distinguish an empty string from a blank string, and account for null separately.
  • Check whether an argument is a literal or a regular expression before using replaceAll() or split().
  • Choose a locale deliberately for case conversion used in comparisons or identifiers.

Most String methods cannot be called on a null reference. For example, value.isEmpty() throws a NullPointerException if value is null. If null is possible, check it first, require non-null input at an API boundary, or use a design that represents missing text explicitly. An empty string and null mean different things: one is a present string with no characters, and the other is no string reference.

Frequently Asked Questions

What is the difference between a Java function and a String method?
A String operation is usually an instance method, called on a string object such as text.length(). “String function” is a common informal phrase for these methods, even though Java terminology generally calls them methods.

How do I find the length of a string in Java?
Call length(), as in int count = text.length();. It returns the number of UTF-16 code units, so some Unicode characters represented by a surrogate pair count as two.

How do I compare two strings in Java?
Use equals() to compare their contents, or equalsIgnoreCase() when ignoring case is suitable. Do not rely on == for content comparison because it tests object identity.

Does replace() change the original string?
No. Strings are immutable, so replace() returns a new string. Assign the result, for example text = text.replace("old", "new"), if you want the variable to refer to the updated text.

What is the difference between isEmpty() and isBlank()?
isEmpty() checks whether the string has zero characters. isBlank(), available from Java 11, also returns true for strings consisting only of recognized whitespace characters.

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.