Java String Predefined Functions: Methods and Examples

Formulas & functions · Updated November 22, 2026

Java’s predefined string operations are methods of the String class, not standalone functions. Common examples include length(), charAt(), substring(), equals(), contains(), and replace(); they let you inspect, compare, search, and create string values.

What “predefined string functions” means in Java

Programmers often use “function” informally to mean an operation they can call by name. In Java, an operation that belongs to an object or class is usually called a method. A string is an object of the built-in java.lang.String class, which Java makes available without an import statement. Its public methods form a standard API for working with text.

Most methods are called on a string value, such as name.length(). Some are static methods called on the class itself, such as String.join(...). The method’s return type varies: length() returns an integer, contains() returns a boolean, and toUpperCase() returns another string. A call does not usually change the original string; that follows from String’s immutability, explained below.

Here is a small example:

String language = "Java";
int size = language.length();
boolean hasAv = language.contains("av");
String upper = language.toUpperCase();

For this example, size is 4, hasAv is true, and upper is "JAVA". The examples in this article use standard Java syntax; a few methods are only available in newer Java releases, and those cases are identified.

Everyday methods for inspecting strings

These methods answer basic questions about a string or retrieve a character or section of it:

  • length() returns the string’s length as an int. An empty string has length zero.
  • isEmpty() returns true only when the length is zero. A string containing spaces is not empty.
  • isBlank(), available since Java 11, returns true if the string is empty or consists only of whitespace characters recognized by Java’s definition of whitespace.
  • charAt(index) returns the UTF-16 code unit at a zero-based index. The valid indices run from 0 through length() - 1.
  • substring(beginIndex) returns the part from the given index to the end. substring(beginIndex, endIndex) returns the part from the first index up to, but not including, the second.

For example, with String word = "planet";, word.charAt(1) is 'l' and word.substring(1, 4) is "lan". The end index being excluded makes it straightforward to calculate a slice length: the number of selected code units is endIndex - beginIndex. Passing a negative index, an index beyond the permitted range, or an end index smaller than the start causes StringIndexOutOfBoundsException.

Searching within a string

Use contains(sequence) for a simple yes-or-no check. It is case-sensitive: "Java".contains("java") is false. For a position, use indexOf(value); it returns the first matching index, or -1 if there is no match. An overload accepts a starting index. lastIndexOf(value) finds the last occurrence.

startsWith(prefix) and endsWith(suffix) are useful for checking prefixes and suffixes without manually extracting a substring. For example:

String file = "report.csv";
boolean isCsv = file.endsWith(".csv");
int comma = "red,green,blue".indexOf(",");

Here isCsv is true and comma is 3. These checks are case-sensitive too. If a search needs case-insensitive behavior, choose an explicit strategy—often normalizing both values with a suitable locale or using a regular expression—rather than assuming contains() ignores case.

Comparing strings correctly

For equality of text, use equals(), not the == operator. equals() compares the sequence of characters; == checks whether two references point to the same object. String literals may be interned, which can make some == comparisons appear to work, but that is not a reliable way to compare user input or strings created at runtime.

String first = new String("tea");
String second = new String("tea");
boolean sameText = first.equals(second);
boolean sameReference = first == second;

In this example, sameText is true and sameReference is false. If a value might be null, avoid calling a method on it directly. For instance, "tea".equals(input) safely returns false if input is null, whereas input.equals("tea") throws a NullPointerException.

equalsIgnoreCase() performs a case-insensitive comparison for many ordinary text uses, but it is not a full solution for every language’s case rules. compareTo() returns a negative number, zero, or a positive number according to lexicographic ordering; it does not promise to return exactly -1 or 1. Use compareToIgnoreCase() when that ordering should ignore case. For locale-sensitive sorting of human language, Java’s Collator is generally a more appropriate tool than raw string ordering.

Changing, trimming, and replacing text

Methods such as toLowerCase(), toUpperCase(), trim(), strip(), and replace() return strings with transformed content. They do not edit the original. Since Java 11, strip(), stripLeading(), and stripTrailing() are available for whitespace handling based on Unicode-aware whitespace rules. The older trim() removes characters at the ends whose code points are at most U+0020, so it is not interchangeable with strip() for all Unicode text.

Case conversion can depend on language rules. For predictable identifiers or protocol text, use the overload that accepts a locale, such as toLowerCase(Locale.ROOT), rather than relying on the machine’s default locale. For natural-language text, locale-specific behavior may be desirable. Import java.util.Locale if needed.

replace(target, replacement) replaces literal character sequences; it does not interpret the target as a regular expression. replaceAll(regex, replacement) does use a regular expression, as does replaceFirst(regex, replacement). For example, text.replace("cat", "dog") treats the letters literally. If you use replaceAll() to remove a pattern, remember that regular-expression metacharacters such as . and * have special meanings and may need escaping.

Splitting and joining strings

split(regex) divides a string at matches of a regular expression and returns a String[]. A common trap is assuming its argument is always a literal separator. To split on a period, for example, use split("\\.") in Java source because a period is a regex metacharacter and the backslash itself must be escaped in a Java string literal. To split on commas, split(",") is sufficient.

The one-argument form of split() discards trailing empty strings. The overload split(regex, limit) gives control over that behavior; a negative limit preserves trailing empty fields. This matters when parsing simple delimited data. For complex or quoted CSV files, a dedicated CSV parser is safer than relying on split().

To combine values, use the static method String.join(delimiter, elements...) or its overload for an iterable. For example, String.join(" / ", "home", "projects", "app") returns "home / projects / app". Joining is clearer than manually adding delimiters in a loop and avoids having to handle the first element as a special case.

Creating and formatting strings

String literals are the simplest way to write fixed text. Java also provides String.valueOf(value) overloads to convert primitive values and objects to strings. For formatted output, String.format(format, arguments...) supports placeholders such as %s for a string representation and %d for an integer. For example, String.format("Item %s: %d", name, count) creates a formatted string. Formatting can be locale-sensitive; use an overload with an explicit Locale where consistent number formatting matters.

Java 15 added text blocks, a convenient syntax for multiline string literals. Java 11 added repeat(count), which returns a string repeated a specified number of times, and lines(), which returns a stream of lines. These are useful, but check the project’s Java version before using them: code must compile against a release that includes the method.

The concat() method joins one string to another, but the + operator is more commonly used for simple concatenation. For a small, fixed number of values, + is readable. If you build text repeatedly inside a loop, consider StringBuilder instead of repeatedly creating intermediate strings. A builder is mutable and can append efficiently; convert the finished result with toString().

Immutability, Unicode, and common mistakes

A Java String is immutable: once created, its content cannot be changed. A transformation returns a new value, so this code does not update message: message.toUpperCase();. To keep the transformed result, assign it: message = message.toUpperCase();. Immutability makes strings easier to share safely, but it also explains why repeated concatenation in a large loop can create unnecessary temporary objects.

Another important detail is Unicode. length() counts UTF-16 code units, not necessarily user-perceived characters. Many common letters take one code unit, but some symbols, including many emoji, use a surrogate pair and count as two. charAt() returns one code unit, so it may return only half of such a pair. When you need to process Unicode code points, methods such as codePointAt(), codePoints(), and offsetByCodePoints() are more suitable. Even a code point is not always a complete displayed character: combined accents and emoji sequences can contain multiple code points.

Common errors are easy to prevent:

  • Use equals() for text equality instead of ==.
  • Check an index before calling charAt() or substring() when input length is uncertain.
  • Remember that string searches and comparisons are case-sensitive unless the method says otherwise.
  • Distinguish literal replacement with replace() from regex-based replacement with replaceAll().
  • Use a locale deliberately for case conversion and formatting when results must be consistent across machines.

How to choose the right method

Start with the result you need rather than memorizing every method. For a yes-or-no test, use a boolean-returning method such as contains(), startsWith(), or equals(). For a position, use indexOf(). For a section, use substring(). For a literal edit, use replace(); for pattern-based work, use a regular expression method. For trimming user-entered whitespace, consider strip() when the project runs Java 11 or later.

Also check the method’s documentation for parameter rules, return values, exceptions, and the Java version where it became available. The official Java API documentation is the authoritative reference. A method name may sound obvious while details such as regex handling, trailing split fields, locale, or Unicode units affect the result. Small examples and boundary tests—empty input, missing search terms, and non-ASCII text—can reveal these issues early.

Frequently Asked Questions

What are the most commonly used Java String methods?
Start with length(), equals(), charAt(), substring(), contains(), indexOf(), replace(), and split(). The right set depends on whether you are inspecting, comparing, searching, or transforming text.

Is String a function or a data type in Java?
String is a class, and each string value is an object of that class. Operations such as length() are methods, not free-standing functions. Java does provide static methods on the String class, including join() and format().

How do I compare two strings in Java?
Use first.equals(second) to compare their text. Use equalsIgnoreCase() for a basic case-insensitive comparison. Avoid == unless you specifically intend to test whether two references point to the same object.

Does a String method change the original string?
No. Strings are immutable, so methods that appear to modify text return a new string. Assign the result or use it directly; otherwise, the original variable keeps its previous value.

What is the difference between replace() and replaceAll()?
replace() searches for a literal character sequence. replaceAll() treats its first argument as a regular expression, which is useful for patterns but requires escaping regex metacharacters when you mean them literally.

Bottom line

Java’s String class provides methods for nearly every routine text task, but understanding their distinctions matters more than learning a long list by rote. Use the method that matches the job, account for immutability and case sensitivity, and be alert to regex rules, Java-version requirements, and Unicode behavior. Those habits make string code more predictable and easier to maintain.

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.