The substring() method in Java is used to extract a portion of a string. It is part of the String class and returns a new string that is a subset of the original string.
Syntax
Java provides two overloaded versions of the substring() method:
public String substring(int beginIndex)
Returns a substring starting frombeginIndex(inclusive) to the end of the string.public String substring(int beginIndex, int endIndex)
Returns a substring frombeginIndex(inclusive) toendIndex(exclusive).
Key Points
Indexing starts at 0.
The
beginIndexis inclusive, while theendIndexis exclusive.The method always returns a new string; the original string remains unchanged because
Stringis immutable in Java.If indices are invalid, it throws a
StringIndexOutOfBoundsException.If the string is
null, it throws aNullPointerException.
Examples
String str = "Hello, World!";
// Extract from index 7 to end
String part1 = str.substring(7); // "World!"
// Extract from index 0 to 5 (exclusive of index 5)
String part2 = str.substring(0, 5); // "Hello"
// Extract domain from URL
String url = "https://www.digitalocean.com";
String domain = url.substring(8, url.indexOf("/", 8)); // "www.digitalocean.com"Common Use Cases
Extracting file extensions:
filename.substring(filename.lastIndexOf(".") + 1)Parsing dates:
date.substring(0, 4)for year.Extracting parts of URLs or email addresses.
Checking for palindromes or comparing string segments.
Best Practices
Always validate
beginIndexandendIndexto avoid exceptions.Check for
nullstrings before callingsubstring().Be mindful of memory usage: in older Java versions (pre-7), substrings shared the underlying character array, potentially causing memory leaks if large strings were retained.
For more details, refer to the Java documentation.
It's supposed to be an efficiency measure. i.e. when you're taking a substring you won't create a new char array, but merely create a window onto the existing char array.
Is this worthwhile ? Maybe. The downside is that it causes some confusion (e.g. see this SO question), plus each String object needs to carry the offset info into the array, even if it's not used.
EDIT: This behaviour has now changed as of Java 7. See the linked answer for more info
Answer from Brian Agnew on Stack OverflowVideos
It's supposed to be an efficiency measure. i.e. when you're taking a substring you won't create a new char array, but merely create a window onto the existing char array.
Is this worthwhile ? Maybe. The downside is that it causes some confusion (e.g. see this SO question), plus each String object needs to carry the offset info into the array, even if it's not used.
EDIT: This behaviour has now changed as of Java 7. See the linked answer for more info
Turning it around, why allocate a new char[] when it is not necessary? This is a valid implementation since String is immutable. It saves allocations and memory in the aggregate.