
Note: Java String index always starts with zero. Now that we understand the basics of substring() method, lets take an example to understand the usage. The String substring method returns a subset/portion of another string.There are two variations of this method, public String substring(int beginIndex) and. It throws IndexOutOfBoundsException If the beginIndex is less than zero OR beginIndex > endIndex OR endIndex is greater than the length of String. The method throws StringIndexOutOfBoundsException if the index values are. For example 'Chaitanya'.substring(2,5) would return 'ait'. And index of substring starts from 1 and not from 0. The substring begins with the character at the specified index and extends to the end of this string. We have taken an input String “Software Testing Help” and then extracted the substring from index 9. Java String substring() methods are used to create a substring from this string. String substring (): This method has two variants and returns a new string that is a substring of this string. Given below is the program in which we have demonstrated the extraction by using the first form of substring() method. So, whatever you mention in the starting index, it will return the entire String from that particular index. There are two variants for the substring() method. The first form returns the substring that starts at the given index and then runs through the entire String. The substring() method in Java returns a portion of a string and is used to get substrings in java. So, Ill show you how Substring functions in Java.
Java substring how to#
In this section, we will discuss the first form of the Java substring() method. A popular question asked in Java interviews is how to find the substring of a string. In the next section, we will look closely into each of these forms. String substring(int startingIndex, int endingIndex) Syntax: String substring(int startingIndex) String Concatenation Extraction Replace Trim Case Conversion String Conversion String.
Java substring full#
Extracting the last name from the full name.

For example, we can use it in the following scenarios: A. The syntax of each of these forms is given below. String Handling in Java String Length String Modification. We can use substring () in Java to extract any substring in a given string. Now, for the extraction from the main String, we need to specify the starting index and the ending index in the substring() method. This method is used to return or extract the substring from the main String.

As we all know, Java substring is nothing but a part of the main String.įor example, In a String “Software Testing”, the “Software” and “Testing” are the substrings.
