what is substring in java

what is substring in java

1 year ago 73
Nature

Substring in Java is a method that extracts a part of a string and returns it as a new string. A substring is a subset or part of another string, or it is a contiguous sequence of characters within a string. The Java String class provides the built-in substring() method that extracts a substring from the given string by using the index values passed as an argument. There are two variants of the substring() method:

  • substring(int startIndex): This variant requires a starting index and returns a new string that is a substring of the original string, starting from the specified index to the end of the string.

  • substring(int startIndex, int endIndex): This variant takes two parameters, a start index and an end index. It returns a new string containing the original strings characters from the startIndex (inclusive) up to the endIndex (exclusive).

Its important to note that the original string remains as it is, and the method returns a new string because strings are immutable in Java. The substring extraction finds its use in many applications including prefix and suffix extraction.

Heres an example of how to use the substring() method in Java:

String str = "Hello, World!";
String substr1 = str.substring(7); // returns "World!"
String substr2 = str.substring(0, 5); // returns "Hello"

In the above example, substr1 is a substring of str starting from index 7 to the end of the string, while substr2 is a substring of str starting from index 0 up to index 5.

Its important to note that if the startIndex or endIndex is negative or greater than the strings length, you will get an error.

Read Entire Article