String Class Java With Substring
String Class Java With Substring
In Java, the String class is marked as final, meaning it cannot be subclassed. Below are some
commonly used methods of the String class, and an example of how to call them:
6. String substring(int beginIndex, int endIndex): Returns a substring starting from beginIndex and
ending at endIndex - 1.
7. int indexOf(String str): Returns the index of the first occurrence of the specified string.
8. boolean contains(CharSequence s): Returns true if the string contains the specified sequence.
14. String[] split(String regex): Splits the string using the given regular expression.
Example:
public class Main {
Java!"
}
String Class Methods in Java: substring()
In Java, the substring() method is part of the String class and is used to extract a portion of a string.
- This method returns a new string that starts from the specified beginIndex and goes to the end of
- Parameters:
- Returns: A new substring starting from the specified index to the end.
string.
Example:
- This method returns a new string that starts from the specified beginIndex and ends just before
- Parameters:
- Throws:
- IndexOutOfBoundsException if beginIndex or endIndex are negative, if beginIndex is greater
Example:
Important Notes:
- Zero-based Indexing: String indices in Java start at 0. For example, in "Hello", 'H' is at index 0, 'e'
is at 1, and so on.
- Immutability: Strings are immutable, so the substring() method creates a new string rather than
- Efficiency: Internally, for performance reasons, the substring shares the character array of the
original string until Java 6. From Java 7 onward, a new character array is created to avoid potential
memory leaks.
Example Program:
Summary:
- substring(int beginIndex): Returns a substring from the beginIndex to the end of the string.
- substring(int beginIndex, int endIndex): Returns a substring from the beginIndex to endIndex - 1.
Both methods are used to extract parts of a string based on the given indices.