Saturday, 12 September 2015

Java String substring

Java String substring

The java string substring() method returns a part of the string.
We pass begin index and end index number position in the java substring method where start index is inclusive and end index is exclusive. In other words, start index starts from 0 whereas end index starts from 1.
There are two types of substring methods in java string.

Signature

  1. public String substring(int startIndex)  
  2. and  
  3. public String substring(int startIndex, int endIndex)  
If you don't specify endIndex, java substring() method will return all the characters from startIndex.

Parameters

startIndex : starting index is inclusive
endIndex : ending index is exclusive

Returns

specified string

Throws

StringIndexOutOfBoundsException if start index is negative value or end index is lower than starting index.

Java String substring() method example

  1. public class SubstringExample{  
  2. public static void main(String args[]){  
  3. String s1="javatpoint";  
  4. System.out.println(s1.substring(2,4));//returns va  
  5. System.out.println(s1.substring(2));//returns vatpoint  
  6. }}  
Output
va
vatpoint

No comments:

Post a Comment