String methods – substring

As its name says, it is used to get the substring from the any String.

It has 2 types of implementations.

  1. String substring(int beginIndex)
  2. String substring(int beginIndex, int endIndex)

Let’s look at them one by on with examples.

String substring(int beginIndex):

It is used to return the substring starting from the specified index(beginIndex) till the end of the string.

e.g. Suppose, we have a string “”Hello World”. If we want to return a substring “world” then we have to do the following shown in the example below.

Output: Returns the substring – World
Note : Method throws IndexOutOfBoundsException If the beginIndex is less than zero or greater than the length of String.

 

String substring(int beginIndex, int endIndex):

Returns the substring starting from the given index(beginIndex) till the specified index(endIndex).

Output: Returns the substring – lo Wo
Note : Method throws IndexOutOfBoundsException, If the beginIndex is less than zero OR beginIndex > endIndex OR endIndex is greater than the length of String.
Ask Question
Have any question or suggestion for us?Please feel free to post in Q&A Forum

 

Print Friendly, PDF & Email
String methods - trim() and length()
String methods - charAt() and compareTo()
Shekhar Sharma

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. He is an automation engineer having more than 8 years of experience who loves troubleshooting in automation and finding innovative ways to solve the problems. His other leisurely activities includes playing harmonica, paintings, sketching portrait, watching movies and travelling etc.

You may also like...

1 Response

  1. August 7, 2015

    […] String substring(int beginIndex) […]