Wednesday, January 8, 2025
HomeProgrammingJava String substring() Method

Java String substring() Method

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

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x