String Functions in Java: GeeksforGeeks Guide

Formulas & functions · Updated November 22, 2026

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() returns false.
  • 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() and s.toLowerCase().
  • Trimming: s.trim() removes leading/trailing spaces, returning "Hello, World!". Note: trim() only removes characters with code ≤ 32 (space). For Unicode whitespace, use strip() (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() or substring() with invalid indices. Remember indices start at 0, and substring end is exclusive.
  • Regex pitfalls: split() and replaceAll() take regex. If you want to split on a literal dot, use split("\\.") (escaped). Otherwise split(".") splits after every character.
  • Performance: Concatenating many strings with + in a loop creates many intermediate objects. Use StringBuilder instead. Example: StringBuilder sb = new StringBuilder(); for(...) { sb.append(i); }
  • Locale issues: toLowerCase() and toUpperCase() use the default locale, which can cause unexpected results in Turkish (e.g., ‘I’ becomes ‘ı’). Use toLowerCase(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

  1. Use equals() for content comparison, never ==.
  2. Prefer strip() over trim() for modern Java (11+) to handle Unicode whitespace.
  3. When splitting on regex special characters, escape them (e.g., "\\." for dot).
  4. For repeated concatenation, use StringBuilder.
  5. Always check for null before calling methods on strings received from external sources.
  6. Use String.valueOf() to convert primitives to strings safely (handles null gracefully).
  7. 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

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.