String functions in Java, as covered on GeeksforGeeks, are built-in methods of the String class that let you manipulate, inspect, and transform text—like finding length, extracting substrings, replacing characters, or splitting strings. This article explains the most-used String methods, how they work under the hood, and common pitfalls, with code examples you can run.
Background: Why String Methods Matter
Java strings are objects, not primitive types. Every string literal like "hello" is an instance of the java.lang.String class, which provides over 60 methods. Because strings are used in virtually every Java program—from reading user input to building SQL queries—knowing these functions is essential for any developer. GeeksforGeeks (often abbreviated GfG) maintains a comprehensive list of these methods, but the official Java API documentation is the ultimate reference. The methods are immutable: they never change the original string; they return a new string instead.
Core String Methods You’ll Use Daily
Here are the most frequently used String functions, grouped by what they do. Each example assumes String s = " Hello, World! ";.
- Length and emptiness:
s.length()returns 17 (including spaces).s.isEmpty()returnsfalse. - Character access:
s.charAt(1)returns'H'(index 0 is space). - Substring:
s.substring(7)returns"World! ";s.substring(7, 12)returns"World"(end index exclusive). - Case conversion:
s.toUpperCase()ands.toLowerCase(). - Trimming:
s.trim()removes leading/trailing spaces, returning"Hello, World!". Note:trim()only removes characters with code ≤ 32 (space). For Unicode whitespace, usestrip()(Java 11+). - Replacement:
s.replace('l', 'L')replaces all occurrences;s.replaceAll("l", "L")uses regex. - Split:
s.split(",")returns[" Hello", " World! "]. - Index of:
s.indexOf('o')returns 5;s.lastIndexOf('o')returns 9. - Contains and starts/ends:
s.contains("World")→ true;s.startsWith(" ")→ true;s.endsWith("!")→ true.
How String Methods Work Internally
Java strings are stored as a byte[] array (since Java 9, using either LATIN-1 or UTF-16 encoding). When you call a method like substring(), the JVM creates a new String object that copies the relevant bytes—it does not share the original array (unlike older Java versions before 7). This ensures immutability, which makes strings thread-safe and allows them to be cached in the string pool. The equals() method compares character-by-character, while equalsIgnoreCase() does the same but ignores case. The hashCode() method uses the formula s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1], which is why "Aa" and "BB" have the same hash code (2112).
Comparing Strings: == vs equals()
A classic mistake is using == to compare strings. == compares object references, not content. For example:
String a = "hello";
String b = "hello";
System.out.println(a == b); // true (both point to same interned literal)
String c = new String("hello");
System.out.println(a == c); // false (c is a new object)
System.out.println(a.equals(c)); // true (content matches)
Always use .equals() for content comparison. For case-insensitive, use .equalsIgnoreCase(). To compare lexicographically (like dictionary order), use compareTo(), which returns a negative, zero, or positive integer.
Common Problems and How to Avoid Them
- NullPointerException: Calling methods on a null string. Check with
if (s != null)before calling. - IndexOutOfBounds: Using
charAt()orsubstring()with invalid indices. Remember indices start at 0, and substring end is exclusive. - Regex pitfalls:
split()andreplaceAll()take regex. If you want to split on a literal dot, usesplit("\\.")(escaped). Otherwisesplit(".")splits after every character. - Performance: Concatenating many strings with
+in a loop creates many intermediate objects. UseStringBuilderinstead. Example:StringBuilder sb = new StringBuilder(); for(...) { sb.append(i); } - Locale issues:
toLowerCase()andtoUpperCase()use the default locale, which can cause unexpected results in Turkish (e.g., ‘I’ becomes ‘ı’). UsetoLowerCase(Locale.ROOT)for consistent behavior.
Alternatives and Related Classes
While String methods are powerful, sometimes you need mutable sequences. StringBuilder (not thread-safe) and StringBuffer (thread-safe) allow in-place modification. For parsing, StringTokenizer is legacy—prefer split(). For formatted output, String.format() works like printf(). For joining multiple strings, String.join() (Java 8+) is handy: String.join(", ", "a", "b", "c") yields "a, b, c". The java.util.regex package provides full regex support via Pattern and Matcher if you need more than simple matching.
Best Practices for Using String Functions
- Use
equals()for content comparison, never==. - Prefer
strip()overtrim()for modern Java (11+) to handle Unicode whitespace. - When splitting on regex special characters, escape them (e.g.,
"\\."for dot). - For repeated concatenation, use
StringBuilder. - Always check for null before calling methods on strings received from external sources.
- Use
String.valueOf()to convert primitives to strings safely (handles null gracefully). - Remember that strings are immutable—each method returns a new string, so assign the result.
Frequently Asked Questions
What is the difference between replace and replaceAll?
replace(CharSequence target, CharSequence replacement) replaces all literal occurrences of the target. replaceAll(String regex, String replacement) treats the first argument as a regular expression. For example, "a.b".replace(".", "#") gives "a#b", but "a.b".replaceAll(".", "#") gives "###" because . matches any character. Use replace for literal text, replaceAll for regex.
How do I reverse a string in Java?
There is no built-in reverse() method for String. Use new StringBuilder(s).reverse().toString(). For example, new StringBuilder("hello").reverse().toString() returns "olleh".
Why does split() drop trailing empty strings?
By default, split() removes trailing empty strings. For example, "a,b,".split(",") returns ["a", "b"], not ["a", "b", ""]. To keep them, use the limit parameter: "a,b,".split(",", -1) returns all, including trailing empties.
Is String a primitive type?
No. String is a class in java.lang. It is not a primitive like int or boolean. However, it has special language support: string literals are interned, and the + operator is overloaded for concatenation.
What does intern() do?
intern() returns a canonical representation of the string from the string pool. If the pool already contains an equal string, it returns that reference; otherwise, it adds the current string to the pool. This can save memory when many strings are identical, but it’s rarely needed in modern applications.
Related
- Python join() Explained: Syntax, Examples, and Tips
- Snowflake SPLIT_PART: Syntax, Examples, and Edge Cases
- Java String Built-In Methods: Uses, Examples, and Tips
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- Excel Round to Nearest Quarter Dollar: 3 Easy WaysTo round a price to the nearest quarter dollar in Excel, use =MROUND(A1, 0.25) for standard rounding, =CEILING(A1,…
- How to Filter Not In Excel: Exclude Specific ValuesTo filter out one value in Excel, select a cell in your data, choose Data > Filter, open…
- Unique Excel Formula With Multiple Criteria: How It WorksTo return distinct values that meet multiple conditions in Excel for Microsoft 365, combine UNIQUE with FILTER. With…
- 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…
- Excel COUNTIF Range Contains Text: Formula GuideYes, you can use COUNTIF to count cells that contain text, but the exact formula depends on what…
- Excel Filter Not Grouping Dates by Month? Causes and FixesIf Excel’s filter dropdown is not grouping dates by month, first check that every value in the date…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.