Java String Methods: From Common to Uncommon
(With Examples)
This guide covers a range of useful Java String methods, categorized from most commonly used to less
frequently encountered. Each method includes an example for practical reference.
🔹 Most Common Methods
1. length()
Returns the number of characters in the string.
String str = "Hello";
int len = str.length(); // 5
2. charAt(int index)
Returns the character at the specified index.
char ch = str.charAt(1); // 'e'
3. substring(int beginIndex, int endIndex)
Extracts a substring from a string.
String sub = str.substring(1, 4); // "ell"
4. equals(String anotherString)
Compares strings for exact content equality.
boolean isEqual = str.equals("Hello"); // true
5. toLowerCase() / toUpperCase()
Converts to lower/uppercase.
1
str.toLowerCase(); // "hello"
str.toUpperCase(); // "HELLO"
6. contains(CharSequence seq)
Checks if a string contains a sequence.
boolean hasEl = str.contains("el"); // true
7. replace(char oldChar, char newChar)
Replaces all instances of a char with another.
String updated = str.replace('l', 'x'); // "Hexxo"
🔸 Intermediate Methods
8. indexOf(String str) / lastIndexOf(String str)
Finds the position of a substring.
int index = str.indexOf("l"); // 2
int lastIndex = str.lastIndexOf("l"); // 3
9. startsWith(String prefix) / endsWith(String suffix)
Checks beginning or ending of a string.
str.startsWith("He"); // true
str.endsWith("lo"); // true
10. trim()
Removes leading and trailing whitespace.
String dirty = " Hello ";
String clean = dirty.trim(); // "Hello"
2
11. split(String regex)
Splits the string based on a delimiter.
String sentence = "Java is fun";
String[] words = sentence.split(" "); // ["Java", "is", "fun"]
12. equalsIgnoreCase(String anotherString)
Case-insensitive comparison.
str.equalsIgnoreCase("HELLO"); // true
🔹 Less Common Methods
13. isEmpty() / isBlank() (Java 11+)
Checks if the string is empty or blank (empty or whitespace).
"".isEmpty(); // true
" ".isBlank(); // true
14. join(CharSequence delimiter, CharSequence... elements) (Java 8+)
Joins multiple strings with a delimiter.
String joined = String.join("-", "Java", "Python", "C++"); // "Java-Python-C++"
15. repeat(int count) (Java 11+)
Repeats the string count times.
"Ha".repeat(3); // "HaHaHa"
16. intern()
Returns a canonical representation for the string object.
3
String s1 = new String("test").intern();
String s2 = "test";
System.out.println(s1 == s2); // true
17. format(String format, Object... args)
Formats strings similarly to printf .
String result = String.format("%s scored %d%%", "Alice", 95);
// "Alice scored 95%"
🧠 Conclusion
Java provides a powerful String class with methods ranging from simple character access to advanced
formatting and manipulation. Understanding and practicing these will significantly improve your Java
programming fluency.