The substring()
method in Java is used to extract a part of a String. It takes two parameters, the starting index and the ending index (optional) of the substring to be extracted.
The syntax for using substring()
is as follows:
String str = "Hello World"; String sub = str.substring(6); // Returns "World" String sub2 = str.substring(0, 5); // Returns "Hello"
In the first example, the substring()
method starts at index 6 (which is the letter “W” in “World”) and extracts the rest of the String.
In the second example, the substring()
method starts at index 0 (which is the first letter “H” in “Hello”) and ends at index 5 (which is the last letter “o” in “Hello”), which extracts the substring “Hello”.
Note that the starting index is inclusive and the ending index is exclusive. So, the substring extracted by substring(startIndex, endIndex)
includes all characters starting from the startIndex
up to (but not including) the endIndex
.
If the ending index is not specified, then substring(startIndex)
returns the substring starting from the startIndex
to the end of the String.
Signature of Java String substring():
The signature of the substring()
method in Java is as follows:
public String substring(int beginIndex)
or
public String substring(int beginIndex, int endIndex)
The first version of the method takes only one parameter, which is the starting index of the substring to be extracted.
The second version of the method takes two parameters, the starting index and the ending index of the substring to be extracted.
Both versions return a new String that represents the substring extracted from the original String.
Parameters of Java String substring():
The substring()
method in Java takes one or two integer parameters, depending on which version of the method is used:
beginIndex
(mandatory): This parameter specifies the starting index of the substring to be extracted from the original String. The index of the first character in a String is 0, and the index of the last character islength() - 1
, wherelength()
is the length of the String. If thebeginIndex
is negative or greater than or equal to the length of the String, aStringIndexOutOfBoundsException
is thrown.endIndex
(optional): This parameter specifies the ending index of the substring to be extracted from the original String. TheendIndex
is exclusive, meaning that the character at theendIndex
is not included in the substring. If this parameter is not specified, the method extracts all characters from thebeginIndex
to the end of the String. If theendIndex
is negative or greater than the length of the String, it is set to the length of the String.
It’s important to note that both beginIndex
and endIndex
are zero-indexed. That means the first character in the String is at index 0, the second character is at index 1, and so on.
Returns of Java String substring():
The substring()
method in Java returns a new String object that represents the substring extracted from the original String. The specific return value depends on the version of the method used and the parameters passed to it:
substring(int beginIndex)
: This version of the method returns a new String that contains all characters from thebeginIndex
to the end of the original String.substring(int beginIndex, int endIndex)
: This version of the method returns a new String that contains all characters from thebeginIndex
up to (but not including) theendIndex
of the original String.
In both cases, the original String is not modified, and a new String object is created to represent the extracted substring. If the specified beginIndex
is equal to the length of the original String, an empty String is returned. If beginIndex
is greater than endIndex
, an empty String is also returned.
It’s important to note that the returned String object is a new object that is independent of the original String object. Any modifications made to the returned substring will not affect the original String, and vice versa.
Exception Throws:
The substring()
method in Java can throw a StringIndexOutOfBoundsException
if the specified indices are out of range. Specifically, the following scenarios can cause an exception to be thrown:
- If
beginIndex
is negative or greater than or equal to the length of the String. - If
endIndex
is negative or greater than the length of the String. - If
beginIndex
is greater thanendIndex
.
In any of these cases, a StringIndexOutOfBoundsException
is thrown.
Here is an example code snippet that demonstrates how the substring()
method can throw an exception:
String str = "Hello World"; // Throws an exception because endIndex is out of range String sub1 = str.substring(0, 20); // Throws an exception because beginIndex is greater than endIndex String sub2 = str.substring(7, 3); // Throws an exception because beginIndex is negative String sub3 = str.substring(-1);
In each of these cases, the substring()
method will throw a StringIndexOutOfBoundsException
with a message indicating the index that is out of range. It’s important to handle this exception appropriately in order to avoid program crashes or unexpected behavior.
Internal implementation substring(int beginIndex):
The substring(int beginIndex)
method in Java is implemented internally as follows:
public String substring(int beginIndex) { if (beginIndex < 0 || beginIndex > value.length) { throw new StringIndexOutOfBoundsException(beginIndex); } int subLen = value.length - beginIndex; return new String(value, beginIndex, subLen); }
The method first checks if the specified beginIndex
is out of range (i.e., less than zero or greater than the length of the String). If so, it throws a StringIndexOutOfBoundsException
.
If beginIndex
is within the valid range, the method computes the length of the substring by subtracting beginIndex
from the length of the original String. It then creates and returns a new String object that represents the substring by calling the constructor of the String class that takes a char[]
array, a starting index, and a length as arguments.
The value
field used in the constructor call represents the internal character array of the original String. By passing beginIndex
and subLen
as the starting index and length, respectively, the constructor creates a new String object that represents the specified substring.
It’s worth noting that this implementation creates a new character array to represent the substring, rather than reusing the internal character array of the original String. This means that the substring and the original String are completely independent of each other and modifications to one will not affect the other.
Internal implementation substring(int beginIndex, int endIndex):
The substring(int beginIndex, int endIndex)
method in Java is implemented internally as follows:
public String substring(int beginIndex, int endIndex) { if (beginIndex < 0) { throw new StringIndexOutOfBoundsException(beginIndex); } if (endIndex > value.length) { throw new StringIndexOutOfBoundsException(endIndex); } if (beginIndex > endIndex) { throw new StringIndexOutOfBoundsException(endIndex - beginIndex); } return ((beginIndex == 0) && (endIndex == value.length)) ? this : new String(value, beginIndex, endIndex - beginIndex); }
The method first checks if beginIndex
is negative or endIndex
is greater than the length of the String, and throws a StringIndexOutOfBoundsException
if either of these conditions is true. It also checks if beginIndex
is greater than endIndex
, and throws a StringIndexOutOfBoundsException
with the length of the substring as the detail message if this is the case.
If none of the above exceptions are thrown, the method then creates a new String object that represents the specified substring by calling the constructor of the String class that takes a char[]
array, a starting index, and a length as arguments.
The value
field used in the constructor call represents the internal character array of the original String. By passing beginIndex
and endIndex - beginIndex
as the starting index and length, respectively, the constructor creates a new String object that represents the specified substring.
Finally, if beginIndex
is zero and endIndex
is equal to the length of the original String, the method returns the original String object itself, since the specified substring is the same as the original String. This optimization avoids unnecessary object creation and copying of the internal character array.
It’s worth noting that this implementation also creates a new character array to represent the substring, rather than reusing the internal character array of the original String. This means that the substring and the original String are completely independent of each other and modifications to one will not affect the other.
Java String substring() method example:
Here is an example code snippet that demonstrates how to use the substring()
method in Java:
String str = "Hello World"; // Extracts a substring from the original string starting from index 0 String sub1 = str.substring(0); // sub1 is "Hello World" // Extracts a substring from the original string starting from index 6 String sub2 = str.substring(6); // sub2 is "World" // Extracts a substring from the original string starting from index 3 and ending at index 7 String sub3 = str.substring(3, 8); // sub3 is "lo Wo" // Extracts a substring from the original string starting from index 6 and ending at index 6 String sub4 = str.substring(6, 6); // sub4 is "" // Throws a StringIndexOutOfBoundsException because endIndex is greater than the length of the original string String sub5 = str.substring(0, 20);
In this example, the substring()
method is called on the str
String object to extract various substrings. The first call to substring()
extracts a substring that starts at index 0 and ends at the end of the original String, resulting in a substring that is identical to the original String. The second call to substring()
extracts a substring that starts at index 6, resulting in the substring “World”. The third call to substring()
extracts a substring that starts at index 3 and ends at index 7, resulting in the substring “lo Wo”. The fourth call to substring()
extracts a substring that starts and ends at index 6, resulting in an empty String. Finally, the fifth call to substring()
attempts to extract a substring that extends beyond the length of the original String, resulting in a StringIndexOutOfBoundsException
.
Applications of substring() Method:
The substring()
method in Java has a wide range of applications in various use cases. Here are some examples:
- Parsing strings:
substring()
can be used to extract substrings from larger strings based on certain patterns or delimiters. For example, you can usesubstring()
to extract the date portion of a timestamp string. - Manipulating strings:
substring()
can be used to replace or remove parts of a string. For example, you can usesubstring()
to remove the first few characters of a string, or to replace a portion of a string with another string. - Data validation:
substring()
can be used to validate data entered by users, such as checking if a substring contains only numerical digits. - Generating random strings:
substring()
can be used to generate random substrings from a larger string, such as when creating random passwords or access codes. - Searching for patterns:
substring()
can be used to search for patterns within a larger string, such as searching for a specific word or phrase within a paragraph of text. - Text processing:
substring()
can be used in various text processing tasks, such as tokenizing a string into individual words or sentences.
In summary, the substring()
method is a versatile tool for working with strings in Java, and can be used in a variety of applications ranging from data validation to text processing.