Java string handling is mainly done with methods on String; use StringBuilder for repeated changes, regular-expression classes for pattern-based work, and charset APIs when converting text to bytes. Common tasks include checking length, searching, extracting parts, replacing text, comparing values, and formatting output.
Java does not generally call these operations “string functions”: they are methods, because they are called on objects or classes. Knowing which method fits the task—and what it returns—helps avoid common errors involving immutability, case, whitespace, and Unicode.
How Java strings work
A String represents text and is immutable: after a string is created, its contents cannot be changed. Methods such as replace and trim return a new string rather than modifying the original. If the result matters, assign it:
String name = " Mira ";name = name.trim();
In this example, trim returns a string with certain leading and trailing characters removed, and the assignment makes that result the new value of name. Calling name.trim(); alone does not update the variable.
Strings can be written as literals, created from other values, or read from input. A literal such as "Java" is an instance of String. Java also offers StringBuilder and StringBuffer for mutable character sequences. StringBuilder is the usual choice for building text through repeated operations in ordinary single-threaded code; StringBuffer synchronizes its methods for use cases that require that behavior.
Length, emptiness, and whitespace
length() returns the number of UTF-16 code units in a string, not necessarily the number of human-perceived characters. For ordinary English text, that distinction is easy to miss. Some Unicode characters, including many emoji, use two code units, so "🙂".length() is 2.
Use isEmpty() to test whether a string has length zero. It does not treat spaces as empty: " ".isEmpty() is false. In Java 11 and later, isBlank() returns true for an empty string or one containing only whitespace as recognized by the method. This is often the better check for user-entered text.
These methods do not accept a null reference. If a variable may be null, check that first or use a design that prevents null values:
if (value != null && !value.isBlank()) { ... }
The short-circuiting && ensures that isBlank() is called only when value is not null.
Searching and extracting text
Several methods help locate or take part of a string. Their index positions are zero-based, meaning the first code unit is at index 0. The end position used by substring(begin, end) is exclusive, so it is not included in the result.
charAt(index)returns the UTF-16 code unit at an index. It throwsIndexOutOfBoundsExceptionif the index is outside the string.substring(beginIndex)returns text from that index to the end;substring(beginIndex, endIndex)returns the range up to, but not including, the end index.indexOf(text)returns the first matching position, or-1if no match exists.lastIndexOf(text)searches from the end.contains(text)answers whether a sequence occurs, returning a boolean rather than an index.startsWith(prefix)andendsWith(suffix)test the beginning and end of a string.
For example, "report.csv".endsWith(".csv") is true. A search such as "banana".indexOf("na") returns 2. These basic methods are case-sensitive; contains("Java") does not match "java".
When working with Unicode beyond basic Latin text, remember that indexes and charAt operate on UTF-16 code units. The codePointAt and codePoints() methods can be more appropriate when iterating by Unicode code point. Even code points are not always the same as user-perceived characters: a visible symbol can be formed from multiple code points.
Changing and cleaning strings
Common transformation methods return new strings. toUpperCase() and toLowerCase() change letter case; replace(old, replacement) replaces literal character sequences; and replaceAll(regex, replacement) treats its first argument as a regular expression. replaceFirst(regex, replacement) changes only the first match.
Use trim() to remove leading and trailing characters whose values are no greater than the space character. Java 11 added strip(), stripLeading(), and stripTrailing(), which use Unicode-aware whitespace handling. For modern applications that need to handle a broader range of whitespace, strip() is often preferable to trim().
For example, " red ".strip() returns "red", while "red blue".replace(" ", "-") returns "red-blue". Neither call changes the original string. Also note that replacement text in replaceAll has special rules: dollar signs and backslashes can have meaning in a regular-expression replacement. For plain text replacement, replace is usually simpler.
Case conversion can depend on language rules. If a program is converting identifiers or protocol tokens that must follow a stable, language-independent convention, use overloads that accept a locale, commonly Locale.ROOT, rather than relying on the machine’s default locale.
Comparing strings correctly
Use equals to compare string contents. The == operator compares whether two references point to the same object, not whether their text is identical. String literals may be interned, which can make some == examples appear to work, but it is not a reliable content comparison.
equalsIgnoreCase compares text without considering case in its defined manner. 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 comparisons are not natural-language sorting. For locale-sensitive sorting, use a Collator.
Strings are immutable, so they are safe to share, but a variable holding a string can still be null. To avoid a null dereference in a comparison, either check the reference first or place a known non-null string on the left, as in "yes".equals(answer). That pattern is useful for simple checks, though clear null-handling logic is preferable when null has meaningful business semantics.
Joining, splitting, and formatting
String.join(delimiter, elements) combines character sequences with a delimiter and is available from Java 8. For example, String.join(", ", "tea", "coffee") returns "tea, coffee". It is convenient when the pieces are already available.
split(regex) divides a string using a regular-expression delimiter and returns a string array. A subtle point: the one-argument form discards trailing empty strings. To preserve them, supply a negative limit, as in line.split(",", -1). Since the delimiter is a regex, a literal period must be escaped—for example, text.split("\\.") in Java source. For CSV files with quoted fields and embedded commas, split is not a full CSV parser; use a CSV library.
For formatted output, String.format supports format specifiers such as %s for text, %d for integers, and %.2f for a floating-point value with two digits after the decimal point. Java 15 added the instance method formatted, which applies the same style of formatting to a format string. Formatting rules can be locale-sensitive; specify a locale when output must use consistent decimal or grouping conventions.
Building text efficiently
Using + is clear for a small number of values, and the compiler can optimize many concatenations within a single expression. But repeatedly appending inside a loop can create many intermediate strings. In that situation, use StringBuilder:
StringBuilder result = new StringBuilder();for (String item : items) { result.append(item).append(",");}String text = result.toString();
append adds values to the mutable builder, and toString() produces the final immutable string. If a delimiter is needed between items without an extra delimiter at the end, a loop can track whether it is adding the first item, or the program can use String.join when the input is already a collection of strings.
Do not assume a builder is always faster or clearer. For a short expression such as first + " " + last, concatenation is readable and appropriate. Choose a builder when a sequence of edits or loop-based construction makes the code simpler or avoids repeated intermediate results.
Regular expressions and text versus bytes
matches(regex) checks whether the entire string matches a regular expression, not merely whether some part matches. For finding matches within larger text, use Pattern and Matcher, particularly when the same pattern is reused. Regex syntax also applies to split, replaceAll, and replaceFirst, so a dot, bracket, or backslash may need escaping.
A Java String stores text; a byte array stores bytes. Converting between them requires a character encoding. Prefer an explicit charset, such as StandardCharsets.UTF_8, when turning text into bytes or decoding bytes into text. Relying on a platform default can produce different results on different systems. A charset is not a string-cleaning method: it defines how characters are represented as bytes.
Choosing the right approach
For everyday string work, start with the simplest method that expresses the intended operation. The following choices cover many common cases:
- Use
equalsfor exact content equality andcontains,startsWith, orendsWithfor straightforward searches. - Use
substringwhen the desired positions are known; useindexOffirst when they must be located. - Use
replacefor literal replacement and regex methods only when pattern matching is actually needed. - Use
stripfor Unicode-aware edge whitespace removal on Java 11 or later; use a compatible alternative if supporting older Java versions. - Use
StringBuilderfor repeated appends,String.joinfor joining existing pieces, and formatting methods when output needs a specific layout. - Use
PatternandMatcherfor reusable or more involved regular expressions, and a dedicated parser for structured formats such as CSV or JSON.
Frequently Asked Questions
Are Java string functions and methods the same thing?
People often say “string functions” informally, but Java’s built-in operations are generally methods of the String class or related classes. You call an instance method on a string, such as text.length(), or a static method such as String.join(...).
Does replace change the original Java string?
No. A String is immutable, so replace returns a new string. Store the result in a variable if you want to use it; the original object’s contents remain unchanged.
What is the difference between equals and == for strings?
equals tests whether the text contents are equal. == tests whether the two references identify the same object. For comparing words, names, or other string values, use equals or a suitable related method.
How do I remove spaces from a Java string?
Use trim() or, in Java 11 and later, strip() to remove whitespace at the beginning and end. To remove or replace spaces throughout the text, use an appropriate replace call or a regular expression, taking care to match only the characters intended.
When should I use StringBuilder instead of plus?
Use + for a small, readable concatenation. Consider StringBuilder when repeatedly appending inside a loop or making a sequence of changes, because it avoids constructing a separate immutable string for every intermediate step.
Related
- Accounting Trial Balance Worksheet: How It Works
- Google Sheets SPLIT Function: How to Separate Text
- Oracle Split String Example: SQL Methods That Work
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- Excel LEN Function: Count Text Characters in CellsIn Excel for Microsoft 365, use the LEN function to count the characters in a cell: with text…
- How to Filter Multiple Dates in Excel by Range or ListTo filter multiple dates in Excel, turn on the column filters, open the arrow on your date column,…
- XLOOKUP Practice Examples for Everyday Excel TasksFor an exact-match lookup, put the value to find in one cell, then use XLOOKUP to search a…
- Excel MID Function: Extract Text from a Cell’s MiddleTo extract characters from the middle of a cell in Excel, use the MID function, which takes a…
- LEFT in Excel: Extract Text from the StartIn Excel, use the LEFT function to return characters from the beginning of a text value: with text…
- Edit a Custom Sort List in ExcelTo edit a custom sort list in Excel for Microsoft 365 on Windows, open File > Options >…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.