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.

public class ExampSubstring {
	public static void main(String[] args) {

		String val1 = "Hello World";
		System.out.println("Returns the substring - "+val1.substring(5)); // returns world
	}
}
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).

public class ExampSubstring {
	public static void main(String[] args) {

		String val1 = "Hello World";
		System.out.println("Returns the substring - "+val1.substring(3,8)); // returns world
	}
}
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

 

Avatar photo

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. This website is his window to the world. He believes that ,"Knowledge increases by sharing but not by saving".

You may also like...

1 Response

  1. August 7, 2015

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