Java’s built-in string operations are methods of the String class, rather than standalone functions. Common examples include length() for measuring a string, charAt() for reading a character, contains() for searching, substring() for extracting text, and replace() for making a changed copy.
What “built-in String functions” means in Java
Java programmers often say “String functions” when they mean methods provided by the standard java.lang.String class. A method is called on a string object, such as name.length(). The word “built-in” means these methods are part of Java’s standard library, so ordinary programs can use them without importing a package. The String class is automatically available.
Some useful operations are instance methods, called on a particular string, while others are static methods called on the class itself. For example, "Java".length() is an instance-method call, while String.valueOf(42) is a static-method call. The distinction matters when reading examples and choosing the right syntax.
There are many methods, and no short list covers every string task. The practical groups are measuring and inspecting text, comparing and searching it, creating modified strings, splitting or joining text, and converting between strings and other data. The examples below use Java syntax and focus on methods available in commonly used Java versions, noting newer methods where relevant.
Creating strings and checking their contents
A string literal is text enclosed in double quotation marks: String message = "Hello, Java";. You can also create strings from other values. String.valueOf(42), for example, produces the string "42". For most everyday code, literals and conversions are more common than explicitly calling a String constructor.
To check whether a string has any characters, use isEmpty(). It returns true only when the length is zero, so a string containing spaces is not empty. isBlank(), available since Java 11, returns true for an empty string or one containing only whitespace characters recognized by Java’s whitespace rules.
"".isEmpty()is true." ".isEmpty()is false, because the string contains a space." ".isBlank()is true on Java 11 and later.
These methods do not make a null reference safe. Calling text.isEmpty() throws a NullPointerException if text is null. Check for null first when a value may be absent, or use a design that avoids null strings.
Measuring strings and reading characters
length() returns the number of UTF-16 code units in a string. That is the quantity used by Java’s indexing methods; it is not always the same as the number of user-perceived characters. For ordinary English letters, the values usually match. Some Unicode symbols, including many emoji, are represented by a pair of code units, so a single visible symbol can contribute two to length().
charAt(index) returns the UTF-16 char at a zero-based position. The first position is 0, and the last valid position is length() - 1. An index outside that range causes a StringIndexOutOfBoundsException. For example, if word is "Java", word.charAt(0) returns 'J'.
When processing text where supplementary Unicode characters matter, a single charAt() call may give only half of a surrogate pair. The codePointAt(), codePoints(), and related code-point methods can be more appropriate for working with Unicode code points. Even code points do not necessarily equal what a person sees as one character: a displayed symbol can be made from several code points, such as a letter plus a combining accent.
Comparing strings correctly
Use equals() to test whether two strings contain the same sequence of characters. The == operator instead checks whether two references point to the same object. Because Java may reuse some string objects, == can appear to work in small examples and fail in others. For comparing text values, use equals().
equalsIgnoreCase() compares strings without distinguishing letter case under its documented case-insensitive rules. It is useful for simple labels or commands, but it is not a substitute for locale-aware language processing. For ordering, compareTo() returns a negative number, zero, or a positive number depending on the strings’ lexicographic order; it does not promise to return exactly -1 or 1. compareToIgnoreCase() performs a case-insensitive ordering comparison.
For example, "cat".equals("cat") is true, while "cat" == new String("cat") is false because the two expressions refer to different objects. A reliable conditional is "yes".equals(answer) if answer might be null: this form avoids calling a method on a null reference.
Searching for text and extracting part of a string
Several methods answer common search questions. contains(sequence) checks whether a character sequence occurs anywhere. startsWith(prefix) and endsWith(suffix) test the beginning and end. These checks are case-sensitive: "Java".contains("java") is false.
indexOf() returns the position of the first matching character or substring, and lastIndexOf() returns the position of the last match. Both return -1 when there is no match. They also accept a starting position in some overloads, which is useful when searching repeatedly. For example, "banana".indexOf("na") returns 2, while "banana".lastIndexOf("na") returns 4.
substring(beginIndex, endIndex) returns the portion from the beginning index up to, but not including, the end index. Thus, if word is "Java", word.substring(1, 3) returns "av". The one-argument form, substring(beginIndex), takes everything from that index to the end. Invalid bounds cause an index exception. The related subSequence() method returns a CharSequence, which is a more general text interface.
Changing text: replacement, case, and whitespace
Strings are immutable: a method does not alter the original string. It returns a result, and your program must store or use that result. For example, String clean = input.trim(); leaves input unchanged. Forgetting this is a common reason code seems not to work: calling input.toLowerCase(); and discarding the return value changes nothing.
replace(old, replacement) replaces literal character or character-sequence matches. By contrast, replaceAll(regex, replacement) and replaceFirst(regex, replacement) interpret the first argument as a regular expression. This difference matters when a search string contains regex characters such as a period or a plus sign. Use replace() for literal substitutions unless a regular expression is intended.
toUpperCase() and toLowerCase() change letter case in a returned string. Case conversion can depend on the default locale, which can produce surprising results in locale-sensitive situations. For predictable technical identifiers, such as protocol tokens, use an explicit locale, commonly toLowerCase(Locale.ROOT); import java.util.Locale if needed.
trim() removes leading and trailing characters at or below the traditional U+0020 space value. Java 11 added strip(), stripLeading(), and stripTrailing(), which use Java’s broader whitespace definition. Choose based on the input and Java version rather than assuming all invisible Unicode whitespace is treated identically.
Splitting, joining, and formatting text
split(regex) divides a string wherever a regular expression matches and returns a String[]. The argument is a regex, not necessarily a literal delimiter. A period, for instance, has a special meaning in regex syntax; to split on a literal period, escape it appropriately, such as split("\\.") in Java source. For a literal delimiter that could contain regex symbols, quoting it with Pattern.quote() can be clearer.
The one-argument split() form discards trailing empty strings. If those empty fields are significant, use the overload with a negative limit, such as line.split(",", -1). That distinction matters when parsing comma-separated data with an empty final field. For robust CSV files, however, a CSV parser is safer than splitting because quoted fields can contain commas and escaping rules add complexity.
String.join(delimiter, elements), available since Java 8, combines strings with a separator: String.join(", ", "red", "green", "blue") produces "red, green, blue". For placeholder-based formatting, String.format("Hello, %s", name) returns formatted text. Formatting syntax includes conversions such as %s for a string representation and %d for an integer; mismatched conversions can cause a formatting exception.
Converting strings to bytes and other values
When converting text to bytes for a file or network protocol, specify a character encoding rather than relying on a platform default. For example, text.getBytes(StandardCharsets.UTF_8) makes the intended encoding explicit; StandardCharsets is in java.nio.charset. The reverse conversion can use new String(bytes, StandardCharsets.UTF_8). Choosing the same agreed encoding at both ends prevents many text-corruption problems.
toCharArray() copies the string’s UTF-16 code units into a new character array. This can be useful for APIs that require a char[], though it does not turn the text into Unicode code points. For converting numbers or other objects to text, String.valueOf(value) handles primitive values and objects. For an object, it uses its string representation; if the reference is null, it returns the text "null", unlike calling toString() on that null reference, which throws an exception.
Choosing methods and avoiding common mistakes
Pick the method that expresses the task directly. Use equality methods for value comparisons, search methods for finding text, and literal replace() when regular expressions are unnecessary. Before using a method, consider whether the input can be null, whether indexes are valid, whether case sensitivity is intended, and whether the operation treats its argument as a regex.
- Use
equals(), not==, to compare string contents. - Remember that indexes start at zero and
substring()excludes its ending index. - Assign returned results: strings do not change in place.
- Use an explicit charset when converting text to or from bytes.
- Use
StringBuilderfor repeated concatenation in a loop, especially when building a large result.
The + operator is convenient for combining a few strings, and the compiler can optimize many simple concatenations. But because each String is immutable, repeatedly creating a longer result in a loop can produce unnecessary intermediate strings. A StringBuilder provides mutable accumulation; call toString() when the finished result is needed. This is a performance and allocation consideration, not a reason to avoid ordinary + expressions.
Frequently Asked Questions
Does Java have a String function called length?
Yes, but it is an instance method named length(), not a standalone function. Call it on a string, for example text.length(). It returns the number of UTF-16 code units.
What is the difference between isEmpty() and isBlank()?isEmpty() is true only when the string has length zero. isBlank(), introduced in Java 11, is also true when the string contains only whitespace recognized by Java. A string containing one space is empty only in neither sense: it is not empty, but it is blank.
How do I compare two strings in Java?
Use equals() for case-sensitive content equality, or equalsIgnoreCase() for a basic case-insensitive comparison. Do not use == to compare content; that operator checks whether references identify the same object.
Does replace() change the original string?
No. Java strings are immutable, so replace() returns a new string and leaves the original untouched. Store the result or pass it directly to another operation.
How can I split a string on a dot or another special character?split() accepts a regular expression. Escape special characters in the Java string and regex, or use Pattern.quote(delimiter) when treating a delimiter literally. Use a negative split limit if trailing empty fields must be retained.
Related
- Java split() Usage: Syntax, Examples, and Common Traps
- Databricks SQL CONTAINS: Find Text in a String
- Split Syntax in Java: Examples and Common Pitfalls
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- How to Calculate Age in Excel From a Date of BirthTo calculate age in completed years in Excel, put the date of birth in A2 and enter =DATEDIF(A2,TODAY(),"Y")…
- Excel Superscript Shortcut: Apply Superscript to TextExcel does not have a single dedicated keyboard shortcut that immediately turns selected text into superscript. In Excel…
- Excel Conditional Formatting for Expiry DatesTo highlight expiry dates in Excel, select the date cells, choose Home > Conditional Formatting > New Rule…
- Excel Flash Fill and Conditional Formatting ExplainedExcel Flash Fill and conditional formatting do different jobs: Flash Fill recognizes a pattern and writes values into…
- Excel: Remove Table Formatting Without Losing DataYes. In Excel for Microsoft 365 on Windows, choose Table Design > Table Styles > More > Clear…
- How to Enable AutoSave in Excel for Automatic SavingTo enable AutoSave in Excel for Microsoft 365 on Windows, save your workbook to OneDrive or SharePoint, then…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.