Introduction
The subSequence()
method in Java's String
class is a handy tool for extracting a portion of a string without actually creating any new copies of the original characters. Think of it as slicing a string, but instead of getting a new String
object, you get a CharSequence
.
Syntax
public CharSequence subSequence(int beginIndex,
int endIndex)
Parameters
Parameter |
Description |
beginIndex |
The index (inclusive) of the first character in the subsequence. |
endIndex |
The index (exclusive) of the last character in the subsequence. |
Return Value
This method returns a CharSequence
object representing the specified portion of the original string.
Examples
Example 1: Basic Subsequence Extraction
Let's start with a simple example to illustrate how the subSequence()
method works. We'll extract a substring from an existing string, specifying the start and end indices.
String str = "Hello World";
CharSequence sub = str.subSequence(0, 5);
System.out.println(sub); // Output: Hello
Hello
In this example, we extract the characters from index 0 (inclusive) up to index 5 (exclusive). This results in the subsequence "Hello". Notice that it returns a CharSequence
which is implemented by String. So you can use it like a string.
Example 2: Extracting from the Middle
Here's an example demonstrating how to extract characters from the middle of a string.
String str = "Java Programming";
CharSequence sub = str.subSequence(5, 13);
System.out.println(sub); // Output: Program
Program
We're extracting characters from index 5 up to (but not including) index 13, giving us "Program". This highlights that the `endIndex` is exclusive.
Example 3: Extracting the Last Few Characters
This example shows how to extract the last few characters of a string using subSequence()
. This can be useful for things like extracting file extensions or processing the end of log messages.
String str = "example.txt";
CharSequence sub = str.subSequence(8, str.length());
System.out.println(sub); // Output: txt
txt
We're extracting from index 8 until the end of the string (using `str.length()`). This gives us "txt", which is the file extension in this case.
Example 4: Handling Edge Cases - Beginning to End
What happens when you want a copy of the entire string? This example demonstrates that scenario
String str = "Entire String";
CharSequence sub = str.subSequence(0, str.length());
System.out.println(sub); // Output: Entire String
Entire String
Extracting the entire string will return a CharSequence
containing all of it.
Important Considerations
- IndexOutOfBoundsException: If either
beginIndex
or endIndex
are out of bounds (negative, or greater than the length of the string), an IndexOutOfBoundsException
will be thrown.
- CharSequence vs. String: The method returns a
CharSequence
object, which is an interface that can be implemented by various classes, including String
. You can generally treat it as if it were a String
for most operations.
Comments
Loading comments...