< Prev
Next >

substring() method

As the name of the method hints, substring() method of String class is used to extract a substring out of an invoked String object, starting at a particular index. There are two forms of substring() method, let's discuss each of those with example one by one.

Signature of the first form of substring() method

public String substring(int startIndex)

Note :

The startIndex int value is a zero-based index, hence the first index is counted as 0.

substring(int startIndex) example

Here in program below, we have a String object and we are extracting a substring out of it by calling the second form of substring(int startIndex) method.
// Program to find a substring of a String. Starting and ending at specified indexes.

class StringSubstring
public static void main(String[] ar)
String str1= new String("0123456789");

String substring  = str1.substring(2);

System.out.println("Original String is "+ str1);
System.out.println("Substring from index 2 to the end :"+ substring );

Output is :

Original String is 0123456789
Substring from index 2 to the end :23456789

Program Analysis

This substring starts at startIndex(2) and ends at at the last index of invoked String object, hence the extracted substring has the value 23456789 , because startIndex is an zero-based index int value i.e.. the first index in a string is counted as 0, hence, the character at the startIndex(2), is 2.


Signature of the second form of substring() method

 public String substring(int startIndex, int endIndex)

Please Subscribe

Please subscribe to our social media channels for daily updates.

Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page



Please check our latest addition