String Methods in Java
Introduction
Strings in Java are heavily utilized, and to manipulate them efficiently, the String class provides a rich set of built-in methods. These methods abstract away the complexity of character array manipulation, ensuring safe and optimized string operations.
This guide covers the most commonly used String methods, categorized by their functionality, along with code examples and best practices.
1. Information and Inspection Methods
These methods are used to inspect the string's properties without modifying it.
length(): Returns the number of characters in the string.charAt(int index): Returns the character at the specified index. ThrowsStringIndexOutOfBoundsExceptionif the index is invalid.isEmpty(): Returnstrueif the string length is0.isBlank()(Java 11+): Returnstrueif the string is empty or contains only white space codepoints.
String text = " Java Programming ";
System.out.println(text.length()); // 18
System.out.println(text.charAt(2)); // 'a'
System.out.println(text.isEmpty()); // false
System.out.println(text.isBlank()); // false
2. Searching and Pattern Matching
These methods help locate substrings or characters within a string.
indexOf(String str): Returns the index of the first occurrence of the specified substring, or-1if not found.lastIndexOf(String str): Returns the index of the last occurrence of the specified substring.contains(CharSequence s): Returnstrueif the string contains the specified sequence of characters.startsWith(String prefix): Returnstrueif the string starts with the given prefix.endsWith(String suffix): Returnstrueif the string ends with the given suffix.
String sentence = "The quick brown fox jumps over the lazy dog";
System.out.println(sentence.indexOf("fox")); // 16
System.out.println(sentence.contains("brown")); // true
System.out.println(sentence.startsWith("The")); // true
System.out.println(sentence.endsWith("cat")); // false
3. String Comparison
Always use methods for string comparison rather than the == operator, which checks for reference equality.
equals(Object anObject): Compares this string to the specified object.equalsIgnoreCase(String anotherString): Compares strings, ignoring case considerations.compareTo(String anotherString): Compares two strings lexicographically. Returns0if equal, a negative integer if lexicographically less, and a positive integer if greater.
String s1 = "hello";
String s2 = "HELLO";
System.out.println(s1.equals(s2)); // false
System.out.println(s1.equalsIgnoreCase(s2)); // true
System.out.println(s1.compareTo("world")); // negative value
4. Manipulation and Extraction
Because Strings are immutable, these methods return a new String instance rather than modifying the original.
substring(int beginIndex, int endIndex): Extracts a portion of the string.endIndexis exclusive.toLowerCase()/toUpperCase(): Converts all characters to lower or upper case.trim(): Removes leading and trailing whitespace.strip()(Java 11+): "Unicode-aware" version oftrim(). Removes leading and trailing whitespace.replace(CharSequence target, CharSequence replacement): Replaces occurrences of the target sequence with the replacement.replaceAll(String regex, String replacement): Replaces substrings matching a regular expression.
String raw = " Hello World! ";
System.out.println(raw.trim()); // "Hello World!"
System.out.println(raw.toLowerCase()); // " hello world! "
System.out.println(raw.substring(3, 8)); // "Hello"
System.out.println(raw.replace("World", "Java"));// " Hello Java! "
5. Splitting and Joining
split(String regex): Splits the string around matches of the given regular expression, returning aString[].join(CharSequence delimiter, CharSequence... elements)(Java 8+): Joins multiple strings using a delimiter.
String csv = "apple,banana,orange";
String[] fruits = csv.split(","); // ["apple", "banana", "orange"]
String joined = String.join(" - ", fruits);
System.out.println(joined); // "apple - banana - orange"
Best Practices
- Null Checks: Calling a method on a
nullstring throws aNullPointerException. Consider usingObjects.requireNonNull()or checkingstr != nullbefore operating. - Immutability Awareness: Methods like
replaceorsubstringdo not alter the string they are called on. You must assign the result:str = str.trim();. - Prefer
isBlank()overisEmpty(): For validating user input,isBlank()is generally safer as it catches strings composed purely of spaces. - Use
StringBuilderfor Iterative Manipulation: If you need to repeatedly concatenate or modify strings in a loop, avoid using the+operator orconcat()method. UseStringBuilderinstead to prevent excessive memory allocation.