Java’s String class provides methods for inspecting, comparing, searching, extracting, and transforming text. Commonly used methods include length(), charAt(), equals(), contains(), substring(), replace(), split(), and toUpperCase(); because strings are immutable, methods that appear to change text return a new string rather than modifying the original.
What the String class represents
String is a class in the java.lang package, which Java makes available without an import statement. A string represents a sequence of characters, such as a name, a sentence, or text read from a file. You can create one with a string literal, such as String language = "Java";, or with a constructor, though literals and factory methods are usually more convenient than calling new String(...).
A central feature of String is immutability: after a string object is created, its contents cannot be changed. For example, language.toUpperCase() produces a string containing "JAVA", but it does not alter the object referenced by language. To keep the result, assign it: language = language.toUpperCase();. Immutability makes strings easier to share safely, but it also explains why code that repeatedly builds text in a loop may be inefficient.
People often search for “String functions” when they mean Java String methods. The methods below are instance methods unless noted otherwise; Java also provides static methods such as String.valueOf() and String.join().
Checking length and reading characters
length() returns the number of UTF-16 code units in the string. For ordinary English text, this is usually the number of characters people expect. Some Unicode symbols, including many emoji, use two UTF-16 code units, so length() is not always the same as the number of visible symbols.
isEmpty() checks whether the string has length zero. It returns true for "", but not for a string containing spaces. Since Java 11, isBlank() checks whether a string is empty or contains only whitespace characters recognized by Java. For example, " ".isBlank() is true, while " ".isEmpty() is false.
Use charAt(index) to read one UTF-16 code unit at a zero-based index. The first position is index 0; requesting an index less than zero or greater than or equal to length() throws StringIndexOutOfBoundsException. For text where supplementary Unicode characters matter, use code-point methods such as codePointAt() or codePointCount() rather than assuming each visible symbol occupies one position.
String word = "Java";
int size = word.length(); // 4
char first = word.charAt(0); // 'J'
boolean empty = word.isEmpty(); // false
Comparing strings correctly
Use equals() to test whether two strings contain the same sequence of characters. Use equalsIgnoreCase() when a case-insensitive comparison is appropriate. By contrast, == checks whether two references point to the same object, not whether their text is equal. String literals may be pooled by Java, which can make some == comparisons appear to work, but it is not a reliable text comparison.
String first = new String("cat");
String second = "cat";
boolean sameText = first.equals(second); // true
boolean sameObject = first == second; // false
compareTo() provides an ordering comparison: it returns zero when the strings are equal, a negative value when the receiver sorts before the argument, and a positive value when it sorts after. The exact nonzero number is not a promise of “minus one” or “plus one”; test its sign. compareToIgnoreCase() offers a case-insensitive ordering. These methods are useful for sorting, but language-aware sorting rules may require a Collator rather than simple string ordering.
String comparisons are case-sensitive by default. For identifiers or protocol values that should be matched without regard to case, equalsIgnoreCase() may be suitable. For language-sensitive transformations, avoid assuming the computer’s default locale is appropriate: use toLowerCase(Locale.ROOT) for locale-independent normalization of many identifiers, importing java.util.Locale as needed. Lowercasing is not a substitute for a complete Unicode normalization or security policy.
Searching within text
contains() answers whether a string includes a given character sequence. It returns a boolean and is convenient for simple searches. indexOf() returns the index of the first matching character or substring, while lastIndexOf() finds the last occurrence. Both return -1 when there is no match. Overloads let you search for a character or string and optionally begin at a specified index.
Use startsWith() and endsWith() to check prefixes and suffixes. These are often clearer than extracting a substring just to compare it. For example, a file-name check can use name.endsWith(".csv"), although real file-type handling may need to account for case, paths, and content rather than relying only on the suffix.
String message = "Java String methods";
boolean hasString = message.contains("String"); // true
int position = message.indexOf("methods"); // 12
boolean startsWithJava = message.startsWith("Java"); // true
The returned positions are UTF-16 indexes, consistent with charAt() and substring(). If a search result will be used to cut text, check for -1 first; passing an unsuccessful search result into an index-based method can cause an exception or produce unintended results.
Extracting and combining parts
substring(beginIndex) returns the portion from the given index to the end. substring(beginIndex, endIndex) returns the range beginning at beginIndex and ending just before endIndex. In other words, the beginning is included and the ending is excluded. This convention makes the result length equal to endIndex - beginIndex, but both indexes must be within valid bounds and the beginning cannot exceed the ending.
For example, "program".substring(0, 3) returns "pro". Calling substring(3) on the same value returns "gram". These methods do not edit the original string. When the task is to divide text by a delimiter, split() may be more suitable; when the task is to join values, consider String.join().
concat() appends another string and returns the combined result. The + operator is more commonly used for straightforward concatenation and can also convert other values to text. For combining a collection of strings with a delimiter, String.join(", ", values) is clearer than manually inserting separators. If the number of pieces is not known until runtime, a StringBuilder is often the better tool.
Changing, trimming, and replacing text
Methods such as toUpperCase() and toLowerCase() return strings with changed letter case. They do not modify the receiver. Their no-argument versions use the default locale, which can produce unexpected results for some languages when handling machine-oriented text. Use a specified locale where consistent locale-independent behavior is required.
trim() removes leading and trailing characters whose values are at most U+0020. Since Java 11, strip(), stripLeading(), and stripTrailing() provide whitespace handling based on Unicode whitespace rules and can be a better fit for modern text. Neither trimming approach removes whitespace from the middle of a string. Choose based on the kind of input and Java version your project supports.
replace() performs literal replacement when given character or character-sequence arguments. In contrast, replaceAll() and replaceFirst() interpret their first argument as a regular expression. This distinction matters when the search text contains regex metacharacters such as a period or a plus sign. Regex replacement text also gives special meaning to characters such as $ and backslash, so literal replacement is simpler when patterns are not needed.
String raw = " Java ";
String clean = raw.strip(); // "Java"
String updated = "one one".replace("one", "two"); // "two two"
String digits = "room 42".replaceAll("\\d+", "number"); // "room number"
Splitting text and working with regular expressions
split(regex) separates a string wherever a regular-expression pattern matches and returns a String[]. A frequent mistake is treating its argument as an ordinary delimiter. For example, a period means “any character” in a regular expression, so splitting on a literal period requires escaping it, such as split("\\."). In Java source code, the backslash itself must be escaped in the string literal.
The two-argument form, split(regex, limit), controls how many pieces are produced and how trailing empty strings are handled. With the default one-argument form, trailing empty results are discarded. A negative limit preserves trailing empty pieces, which can matter when parsing records where the final field is empty. Splitting is convenient for simple, well-defined formats, but it is not a full parser for quoted CSV fields or other grammars with escaping rules.
For pattern matching beyond simple substring searches, Java’s regular-expression API includes Pattern and Matcher in java.util.regex. This can make a reusable pattern and its matching behavior more explicit than calling matches() or replaceAll() repeatedly. Note that String.matches(regex) tests whether the entire string matches the pattern, not whether the pattern appears anywhere inside it.
Formatting and converting values
String.valueOf(value) converts supported primitive values and objects into strings. For an object, it uses that object’s string representation; for a null object reference, String.valueOf((Object) null) returns "null". This differs from calling toString() directly on a null reference, which throws NullPointerException. That difference can help avoid an exception, but the text "null" may not be appropriate for the application’s output.
String.format() creates formatted text from a format string and arguments. It supports conversion markers for values such as integers, floating-point numbers, and strings, and can be useful for fixed-width output or readable messages. Formatting conventions can depend on locale, so specify a locale when output must be consistent across environments. For repeated high-volume formatting, consider the overhead and readability of the chosen approach rather than using formatting automatically for every concatenation.
Java also offers text blocks for multi-line string literals in modern Java, which can make embedded text easier to read. Text blocks are a language feature, not a separate family of String methods. Regardless of how a string is created, the usual String methods can be applied to it.
Immutability, performance, and safer alternatives
Because String objects are immutable, a sequence such as result = result + part inside a large loop can create many intermediate strings. A compiler can optimize some concatenation expressions, but for repeated incremental construction, StringBuilder is usually the direct choice. Append pieces with append(), then call toString() when the completed result is needed.
Use StringBuffer when its synchronized methods are specifically useful for shared mutable text; for the common case of building a string within one thread, StringBuilder is generally preferred. Neither class replaces String for ordinary text values: mutable builders are tools for construction, while the finished result is commonly a String.
- Choose String methods for clear, one-off text operations such as checking a prefix or extracting a short section.
- Choose
StringBuilderfor repeated appends in loops or incremental construction. - Choose regular-expression APIs when the matching rule is genuinely a pattern, not just a literal substring.
- Choose a parser or format-specific library for structured data with quoting, nesting, or escaping rules.
Do not rely on intern() as a general performance fix. It returns a canonical representation from the string pool, which may help in specialized cases but introduces memory and design trade-offs. Likewise, avoid assuming every user-perceived character is one Java char; Unicode text can require code-point-aware processing, and complex grapheme clusters may contain multiple code points.
Frequently Asked Questions
Are Java String functions and methods the same thing?
In everyday searches, “String functions” usually means the methods supplied by Java’s String class. Java documentation generally calls these methods. Some, such as length(), operate on a particular string object, while others, such as String.valueOf(), are static methods called on the class.
How do I compare two strings in Java?
Use equals() to check whether their contents match, or equalsIgnoreCase() when ignoring case is suitable. Do not use == to compare text contents; it compares object references.
Does a String method change the original string?
No. String is immutable. Methods such as replace(), strip(), and toUpperCase() return a result; assign that result to a variable if you need to keep it.
What is the difference between replace() and replaceAll()?
replace() searches for literal characters or character sequences. replaceAll() treats its search argument as a regular expression, so regex symbols can affect the match. Use the literal form unless a regular-expression pattern is needed.
Why does String.length() give a surprising result for emoji?
length() counts UTF-16 code units, not necessarily visible symbols. Many emoji occupy two code units, and some displayed symbols combine multiple code points. Use code-point methods when code-point counts matter, and a grapheme-aware library or approach when the requirement is to count user-perceived characters.
Related
- SOLIDWORKS Split Line: How It Works and When to Use It
- C++ String Count: How to Count Characters
- Oracle String to Value: Converting Text in SQL
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- Dynamic Range Formula in Excel: Methods and ExamplesA dynamic range in Excel expands or contracts as data is added or removed. For a contiguous list…
- How to Show Formulas in Excel for MacTo show formulas in Excel for Mac, open the worksheet and choose Formulas > Show Formulas. You can…
- Excel COUNTIF by Text Color: Options and WorkaroundsExcel’s COUNTIF function cannot count cells by font or text color: its criteria test cell values, not formatting.…
- Excel COUNTIF for Text: Exact Match FormulaTo count cells in Excel that equal a specific text exactly, use =COUNTIF(range,"text"). For example, =COUNTIF(A2:A10,"Apple") counts every…
- How to Merge Names in Excel: Formulas and Flash FillTo combine first and last names in Excel, put the first names in column A and last names…
- Excel SUMIFS Between Two Dates: Formula and ExamplesTo sum values in Excel between two dates, use SUMIFS with the date range as a criteria range…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.