Mastering Java String Methods: Commonly Used Operations with Examples

Illustration for Mastering Java String Methods: Commonly Used Operations with Examples
By Last updated:

Strings are at the heart of Java programming — from logging messages and parsing inputs to constructing SQL queries or APIs. Java provides a powerful String class packed with dozens of utility methods that simplify text processing.

This tutorial walks you through the most commonly used string methods, offering insights into their behavior, use cases, pitfalls, and performance tips — ideal for both beginners and seasoned developers.


📘 What Is the Java String Class?

The String class in Java represents immutable sequences of characters. It is part of java.lang, so no import is needed.

String name = "Java";

🔍 Most Commonly Used String Methods

length()

Returns the number of characters in the string.

String s = "Hello";
System.out.println(s.length()); // 5

charAt(int index)

Returns the character at a specific index.

System.out.println("Java".charAt(2)); // 'v'

substring(int beginIndex, int endIndex)

Extracts a portion of the string.

String text = "Programming";
System.out.println(text.substring(0, 6)); // "Progra"

equals(String anotherString)

Compares two strings by value (case-sensitive).

"Java".equals("java"); // false

equalsIgnoreCase(String anotherString)

Case-insensitive comparison.

"Java".equalsIgnoreCase("java"); // true

contains(CharSequence s)

Checks if a string contains another sequence.

"Java Developer".contains("Dev"); // true

replace(CharSequence old, CharSequence new)

Replaces characters or substrings.

"banana".replace('a', 'o'); // "bonono"

toLowerCase() / toUpperCase()

Changes case of all characters.

"Java".toLowerCase(); // "java"
"Java".toUpperCase(); // "JAVA"

trim()

Removes leading and trailing whitespace.

"  hello  ".trim(); // "hello"

split(String regex)

Splits the string into an array using regex.

String[] words = "apple,banana,grape".split(",");

startsWith(String prefix) / endsWith(String suffix)

Checks beginning or end of a string.

"developer".startsWith("dev"); // true
"developer".endsWith("per");   // true

indexOf(String str) / lastIndexOf(String str)

Returns position of first/last occurrence.

"hello".indexOf('l'); // 2
"hello".lastIndexOf('l'); // 3

isEmpty()

Checks if string is empty.

"".isEmpty(); // true

🆕 Java 11+ Enhancements

isBlank()

Returns true if string is empty or contains only whitespace.

"  ".isBlank(); // true

strip(), stripLeading(), stripTrailing()

Unicode-aware trimming (better than trim()).

"  hello  ".strip(); // "hello"

lines()

Splits multi-line strings into a stream of lines.

String multiline = "line1\nline2";
multiline.lines().forEach(System.out::println);

📈 Performance and Use Case Tips

Method Use Case Performance Consideration
concat() Simple appending Avoid in loops
StringBuilder Multiple appends in loops ✅ Preferred
split() Parsing CSV or structured text Regex-based; can be slower
replace() Replacing substrings Creates new string (immutable)
equals() String comparison Use constant first to avoid NPE

🔄 Refactoring Examples

❌ Repetitive Concatenation

String result = "";
for (int i = 0; i < 100; i++) {
  result += i;
}

✅ Use StringBuilder

StringBuilder sb = new StringBuilder();
for (int i = 0; i < 100; i++) {
  sb.append(i);
}
String result = sb.toString();

📌 What's New in Java Strings?

Java 8

  • String.join(), String.chars()

Java 11

  • isBlank(), strip(), lines()

Java 13+

  • Text Blocks (""") for multi-line strings

Java 21

  • String Templates (Preview)
String name = "Java";
String msg = STR."Hello, \{name}!";

✅ Best Practices

  • Always null-check before calling methods like .equals()
  • Prefer .equalsIgnoreCase() for case-insensitive comparisons
  • Use StringBuilder in loops or bulk string manipulation
  • Use isBlank() (Java 11+) instead of trim().isEmpty()

🔚 Conclusion and Key Takeaways

  • The Java String class offers powerful, built-in methods for every text processing need.
  • Understanding these methods helps write cleaner, more efficient code.
  • Keep performance in mind — especially with string concatenation.

❓ FAQ

1. Is trim() the same as strip()?

No. strip() is Unicode-aware and more reliable (Java 11+).

2. Can I compare strings with ==?

No. Use .equals() for content comparison.

3. When should I use split()?

When parsing delimited data (CSV, log entries, etc.)

4. What’s the difference between isEmpty() and isBlank()?

isEmpty() checks for length 0. isBlank() also checks whitespace (Java 11+).

5. Is replace() destructive?

No. It returns a new string (strings are immutable).

6. What’s faster: + or StringBuilder?

StringBuilder is faster in loops or frequent concatenation.

7. How to convert a string to a char array?

Use toCharArray().

8. How to join strings from an array?

Use String.join().

9. Are string methods thread-safe?

Yes, because strings are immutable.

10. Do methods like toLowerCase() modify the original?

No. They return a new string.