Java String Functions: Methods, Examples, and Usage

Formulas & functions · Updated November 22, 2026

In Java, “string functions” usually means methods of the String class, which let a program inspect, compare, search, and create text. For example, text.length() returns a string’s length, text.toUpperCase() creates an uppercase version, and text.substring(0, 3) extracts part of it; because strings are immutable, these methods do not change the original string.

What “String functions” means in Java

Java does not generally call these operations string functions. They are instance methods on the built-in java.lang.String class, so they are called with dot notation on a string value. A method such as contains answers a question about the string, while a method such as replace returns a new string with a change applied. Java also provides static methods, including String.valueOf and String.join, which are called on the class itself.

A string literal is written between double quotation marks, as in "Java". A variable can refer to one:

String language = "Java";
int size = language.length();
System.out.println(size); // 4

String is part of java.lang, a package Java makes available without an import statement. These methods are useful for user input, file contents, messages, identifiers, and other text handled by a program.

Why String objects are immutable

Immutability means that once a String object has been created, its character contents cannot be changed. A method that appears to edit text instead returns another string. For example, language.toUpperCase() produces "JAVA", but language still refers to "Java".

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

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

The first call’s result is ignored, which is why the first print still shows the original value. Assigning the returned value makes the variable refer to the uppercase result. Immutability also explains why a string cannot be modified through a method like setCharAt; no such String method exists. When a program needs to build text through many edits, StringBuilder is usually a better tool.

Methods for measuring and extracting text

Several frequently used methods help determine what a string contains or retrieve a portion of it:

  • length() returns the number of UTF-16 code units in the string. It is not always the number of user-perceived characters: some Unicode characters use a pair of code units.
  • isEmpty() is true only when the length is zero. A string containing spaces, such as " ", is not empty.
  • charAt(index) returns the UTF-16 char at a zero-based index. An index must be at least zero and less than length(), or Java throws StringIndexOutOfBoundsException.
  • substring(beginIndex, endIndex) returns the portion from the starting index up to, but not including, the ending index. The one-argument form, substring(beginIndex), continues to the end.

For example, with String word = "program";, word.substring(0, 3) returns "pro". The end index is exclusive, so the returned text has three characters. A useful way to avoid mistakes is to remember that the length of a substring is endIndex - beginIndex. For Unicode work that must count full code points rather than UTF-16 units, methods such as codePointCount and codePointAt are available; visual grapheme clusters can still involve more than one code point.

Comparing strings correctly

Use equals to test whether two strings have the same character sequence. Do not use == when the goal is to compare text: == checks whether two references point to the same object, not whether their contents match. String literals may be pooled, which can make some == comparisons appear to work, but that is not a reliable content comparison.

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

Use equalsIgnoreCase when case differences should not matter for the comparison. For ordering, compareTo returns a negative number, zero, or a positive number depending on the lexicographic comparison; it does not promise to return exactly -1 or 1. These methods are case-sensitive unless otherwise specified. For user-facing language-sensitive sorting, a locale-aware Collator is more appropriate than assuming compareTo follows dictionary rules.

If a value might be null, calling a method on it throws NullPointerException. A null-safe check can put the known non-null literal first, as in "ready".equals(status), or explicitly check status != null before calling its methods.

Searching and checking content

Use contains to check whether a sequence of characters occurs somewhere in a string. It returns a boolean and treats the search text literally, not as a regular expression. startsWith and endsWith test prefixes and suffixes, useful for simple checks such as whether a file name ends in a particular extension.

indexOf returns the index of the first matching character or substring, and lastIndexOf searches from the end. Both return -1 when there is no match. A typical pattern is to test the result before using it as an index:

String file = "report.csv";
int dot = file.lastIndexOf('.');
if (dot >= 0) {
    String extension = file.substring(dot + 1);
    System.out.println(extension); // csv
}

This code also illustrates why a search result should not be assumed to exist. Taking a substring using an index calculated from a failed search can cause an exception or produce an unintended result.

Changing case, trimming, and replacing text

Methods such as toUpperCase and toLowerCase return strings with case transformed. For text intended for machine comparisons, such as a protocol token or a case-insensitive key, use the overload that takes a locale and pass Locale.ROOT when language-specific casing is not wanted. Case conversion can vary by locale, so it is not always safe to use the default locale for program identifiers.

trim() removes certain characters at or below the space character from the two ends of a string. In Java 11 and later, strip(), stripLeading(), and stripTrailing() handle Unicode whitespace more broadly. Also in Java 11 and later, isBlank() reports whether a string is empty or contains only whitespace as defined by Java’s whitespace test. These methods do not remove whitespace from the middle of text.

There is an important difference between replace and replaceAll. replace replaces literal characters or character sequences. replaceAll treats its first argument as a regular expression, so characters such as a period or a plus sign may have special meanings. If literal text is intended, prefer replace; if a regular expression is intended, read its syntax carefully. Both return a new string rather than changing the receiver.

Splitting and joining strings

split divides text according to a regular expression and returns a string array. A common surprise is that the separator is a regex: a dot must be escaped if it is meant to represent a literal period. For example, line.split(",") splits on commas, while line.split("\.") splits on literal periods. The default behavior discards trailing empty fields. To retain them, use a negative limit, such as line.split(",", -1).

When joining multiple pieces, String.join takes a delimiter and a sequence of elements. For instance, String.join(" - ", "red", "green", "blue") returns "red - green - blue". It is often clearer than repeatedly adding delimiters by hand. For formatted output, String.format supports format specifiers, while String.formatted is available starting in Java 15. Choose format placeholders to match the values supplied, and remember that formatting rules can be locale-sensitive.

Building text efficiently

For a few simple combinations, the + operator is readable and commonly used. The compiler can optimize many concatenations in a single expression. However, repeatedly concatenating inside a loop can create many intermediate string objects. For repeated appends, use StringBuilder, which is mutable and designed for constructing text:

StringBuilder result = new StringBuilder();
for (int i = 1; i <= 3; i++) {
    result.append(i);
    result.append(",");
}
String text = result.toString();
System.out.println(text); // 1,2,3,

This example deliberately appends a comma after every number; a real list may need logic to avoid a trailing delimiter, or may be better expressed with a join operation. StringBuffer offers synchronized methods and is a legacy alternative, but synchronization is not automatically needed for ordinary local text construction. Choose the simpler tool that fits the situation rather than replacing every use of + with a builder.

Common mistakes and practical choices

Many string bugs come from assumptions about what a method changes or what counts as a character. Keep these checks in mind when choosing a method:

  • Assign the result of a transformation if it needs to be used; strings are immutable.
  • Use equals for content equality, and handle possible null references deliberately.
  • Check indexes and search results before calling charAt or substring.
  • Remember that split and replaceAll use regular expressions, whereas contains and replace use literal text.
  • Do not treat length() as a guaranteed count of visible symbols in arbitrary Unicode text.

For basic validation, string methods can check simple patterns, prefixes, or lengths, but they do not replace a full parser when the input format is complex. For example, checking that an email-like string contains an at-sign is not enough to validate every address correctly. The right method depends on the job: search with contains or indexOf, compare with equals, extract with substring, and build repeated output with StringBuilder or join.

Frequently Asked Questions

What is the most commonly used String method in Java?
length(), equals(), and substring() are among the methods used frequently, but there is no single method that is most common for every program. Pick the method that matches the operation you need.

How do I find the length of a string?
Call length(), as in int count = text.length();. It returns the number of UTF-16 code units, which can differ from the number of visible characters in Unicode text.

Why does my Java string not change after calling replace?
replace returns a new string. Store the result, for example with text = text.replace("old", "new");, if the variable should refer to the changed text.

What is the difference between == and equals for strings?
== compares object references, while equals compares string contents. Use equals when deciding whether two strings contain the same text.

Is split a regular-expression method?
Yes. Its delimiter argument is a regular expression, so regex metacharacters may need escaping when you mean them literally. The method also drops trailing empty fields unless you supply a suitable limit, such as -1.

Should I use String or StringBuilder?
Use String for text values and straightforward concatenation. Use StringBuilder when constructing a string through many appends, particularly inside a loop.

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.