The substring Method: Extracting Substrings
What you'll learn: How to extract portions of a String using Java's substring() methods.
The Core Idea
Think of a String as a row of numbered seats in a theater, where each character occupies one seat starting from position 0. The substring() method lets you "rope off" a section of those seats and create a new String containing just those characters.
Java provides two versions of substring():
1. substring(int beginIndex)
This extracts from beginIndex to the end of the String. The character at beginIndex is included.
String message = "Hello World";
String result = message.substring(6); // "World"
2. substring(int beginIndex, int endIndex)
This extracts characters from beginIndex up to (but not including) endIndex. Think of it as a half-open range: [beginIndex, endIndex).
String message = "Hello World";
String result = message.substring(0, 5); // "Hello"
String mid = message.substring(3, 8); // "lo Wo"
Index Mechanics
Remember that String indexing is zero-based. In "Hello":
- Index 0 = 'H'
- Index 4 = 'o'
- Length = 5
The endIndex parameter marks where extraction stops (exclusive), not the last character you want.
String word = "Java";
String first = word.substring(0, 1); // "J" (not "Ja")
String last = word.substring(3, 4); // "a"
Important: substring() creates a new String object; it doesn't modify the original (remember immutability!).
Key Takeaway: Use substring(beginIndex) to extract from a position to the end, or substring(beginIndex, endIndex) to extract a specific range—where beginIndex is inclusive and endIndex is exclusive.