Table of Contents
Core String Methods for Daily Use
Java’s String
class provides dozens of methods for text processing. Let’s break down the most critical ones.
1. Getting Basic Information
length()
: Returns the number of characters.
String text = "Java";
System.out.println(text.length()); // 4
charAt(int index)
: Fetch a character at a specific position.
System.out.println("Hello".charAt(1)); // 'e' (indices start at 0)
2. Extracting Substrings
substring(int beginIndex)
: Get text frombeginIndex
to end.
String s = "Programming";
System.out.println(s.substring(3)); // "gramming"
substring(int beginIndex, int endIndex)
: Extract between indices (exclusive ofendIndex
).
System.out.println(s.substring(0, 4)); // "Prog"
Common Mistake:
// Causes StringIndexOutOfBoundsException if indices are invalid
String s = "Hi";
s.substring(0, 5); // ❌ Avoid!
3. Searching Strings
indexOf(String str)
: Find the first occurrence’s position.
String log = "Error: File not found";
System.out.println(log.indexOf("Error")); // 0
System.out.println(log.indexOf("Warn")); // -1 (not found)
contains(CharSequence s)
: Check if a substring exists.
System.out.println(log.contains("not")); // true
4. Concatenation: Combining Strings
- Using
+
Operator:
String name = "Alice";
String greeting = "Hello, " + name + "!"; // "Hello, Alice!"
concat(String str)
:
String s1 = "Java";
String s2 = s1.concat("Script"); // "JavaScript"
Key Difference:
+
handlesnull
gracefully ("null"
string).concat()
throwsNullPointerException
if argument isnull
.
5. Case Conversion
toUpperCase()
/toLowerCase()
:
String lang = "Java";
System.out.println(lang.toUpperCase()); // "JAVA"
System.out.println("HELLO".toLowerCase()); // "hello"
Pitfall: Forgetting to assign the result (Strings are immutable!):
String s = "text";
s.toUpperCase(); // ❌ Original 's' remains "text"
s = s.toUpperCase(); // ✅ Correct: s becomes "TEXT"
6. Trimming Whitespace
trim()
: Remove leading/trailing spaces (old method).
String input = " Java ";
System.out.println(input.trim()); // "Java"
strip()
(Java 11+): Handles Unicode whitespace (preferred).
String unicodeSpace = "\u2000Hello\u2000";
System.out.println(unicodeSpace.strip()); // "Hello"
Best Practices
- Prefer
isEmpty()
Overlength() == 0
:
if (str.isEmpty()) { ... } // Cleaner than checking length
- Use
strip()
for Modern Whitespace Handling (Java 11+). - Avoid Chaining
substring()
Calls: Creates unnecessary intermediate strings.
FAQ
What’s the difference between trim()
and strip()
?
trim()
removes only ASCII spaces (<= U+0020), while strip()
handles all Unicode whitespace (e.g., \u2000
).
Why is concat()
rarely used?
+
is more readable and flexible (e.g., "A" + null
vs. "A".concat(null)
).
Up Next: String Comparison: Learn to compare Strings safely with equals()
, compareTo()
, and more.