In Java, the substring() method is used to extract a portion of a string. It is part of the String class and has two common forms:
- substring(int beginIndex): This version returns a new string starting from the specified index (beginIndex) to the end of the string.
Example:
java
String str = “Hello, World!”;
String subStr = str.substring(7); // Output: “World!” - substring(int beginIndex, int endIndex): This version returns a new string starting from the specified beginIndex and extending up to (but not including) the endIndex.
Example:
java
String str = “Hello, World!”;
String subStr = str.substring(0, 5); // Output: “Hello”
Key Points:
– The beginIndex is inclusive, while the endIndex is exclusive.
– If the beginIndex is greater than or equal to the string length, it throws a StringIndexOutOfBoundsException