«Back to Home

Core Java

Topics

Substring In Java

Substring
 
In Java, substring is a part of string.
 
In other words, substring is a subset of another string.
 
Method substring() is used to get a substring of a particular string in Java.
 
In Java, we have two methods to get the substring from the given string object.
  • public String substring(int startIndex)

    It returns new string object, which contains the substring of the given string from the particular startIndex (inclusive).

  • public String substring(int startIndex, int endIndex)

    It returns new string object, which contains the substring of the given string from particular startIndex to endIndex.
Case of string in Java
  • startIndex: inclusive

  • endIndex: exclusive
Index starts from 0 always.
 
Let's see an example, given below.
 
Code
  1. public class SubstringExample {  
  2.     public static void main(String args[]) {  
  3.         String name = "James William";  
  4.         System.out.println(name.substring(9));  
  5.         System.out.println(name.substring(09));  
  6.     }  
  7. }  
28

Output

29

Let’s see another example, given below.
 
Code
  1. public class SubstringExample {  
  2.     public static void main(String args[]) {  
  3.         String s1 = new String("And hang a pearl in every cowslip's ear. ");  
  4.         System.out.println("Substring starting from index 10:");  
  5.         System.out.println(s1.substring(10));  
  6.         System.out.println("Substring starting from index 10 and ending at 20:");  
  7.         System.out.println(s1.substring(1020));  
  8.     }  
  9. }  
30

Output

31
 
Summary

Thus, we learnt that the substring is a subset of another string and also learnt their two methods, which are used to get a substring of a particular string in Java.