
The extracted portion starts with the character at the index beginIndex till the end of the string. Otherwise the substring() method will simply throws IndexOutOfBoundsException. The beginIndex should be greater than zero and less than the length of the string.Īlso, endIndex should be greater than or equal to beginIndex and less than the length of the given string. When substring() Throws IndexOutOfBoundsException? Please bear in mind that both methods are susceptible to throw IndexOutOfBoundsException. Public String substring(int startIndex, int endIndex): this variant accepts two parametersīeginIndex: describes the starting index, it’s inclusive for both variantsĮndIndex: denotes the last index and it’s exclusive You have a String say, 1 GB, and if make a substring of it with 500 MB then it will return 500 MB character set with 1 GB value array object.

String's substring method uses old string's value array object to store substring. Public String substring(int startIndex): this version accepts only one parameter Also dig down into substring method which cause memory leak if we don't use it judiciously. String.substring() Syntax Variants in Javaīasically, there are two overloaded variants of the substring() method: So, let’s dig deep and take a close look at it.
#Substring java example how to
Now that we know what a substring is, let’s see how to create and manipulate it.įortunately, the String class provides a handy method called substring() especially to get a substring. In short, every subset or portion of an original string is called a substring.įor example, “devwithus” is composed of the following substrings: “dev”, “with”, “us”… What is a substring?Ī substring, as the name implies, is a contiguous sequence of characters within a particular string. So, this is where the substring() method comes to the rescue. We need just to manipulate some of them to solve one problem or another. However, sometimes we are not interested in all characters. String in Java is a class that represents a sequence of characters. In this article, we are going to shed light on Java String substring() method. In the second example, substr2 will contain the substring starting from the 0th index (i.e., the first character) of the string str till the 5th index (i.e., the character at the 5th index is not included) of the string. Important Key Points about the substring() Method.How substring() is Implemented Internally in Java?.substring(int beginIndex, int endIndex) Example.When substring() Throws IndexOutOfBoundsException?.

String.substring() Syntax Variants in Java.
