ZMedia Purwodadi

Java String substring() method explained | technical-arbaab

Table of Contents

Java string substring() method explained


It is a predefined function which is present in the Java.lang.String package. It is used to find and return a specific part or substring(part of a string) from a string, It is of two types let us discuss each of them in detail-

 Types of substring() method

  •  public String substring(int beginIndex) {}
  •  public String substring(int beginIndex, int endIndex) {}

Imp.note: The method substring() takes the argument in this way substring(inclusive, exclusive) which means the starting index is taken while the last index isn't taken the index=endIndex-1 is actually taken to print the string (hope it is clear)

1. substring(int beginIndex): It will just take the string from starting index and returns the string from this index till the end, let's see how to implement it in the code-

Example 01 of substring(int beginIndex) function

 public class Substring {  
      public static void main(String[] args)  
      {  
           String s1 = "Sparrow";  
           System.out.println(s1.substring(2));//arrow printed  
      }  
 }  

output:
 arrow  

here, as you give the starting index 2 then at 2nd index of string the value which is there is taken for example here, "a" is there, so it takes the string from "a" till the end and return "arrow" simply.

2. substring(int beginIndex, int endIndex): It will just take the string from starting index till the endIndex as given by the user which is exclusive (endIndex-1 is actually taken) and returns the resulted stringlet's see how to implement it in the code-

Example 01 of substring(int beginIndex, int endIndex) function

 public class Substring {  
      public static void main(String[] args)  
      {  
           String s1 = "Sparrow";  
           System.out.println(s1.substring(2,5));//arr will be printed  
      }  
 }  
Output:
 arr

here, in this example as you see the index (2,5) matches with (inclusive index, exclusive index) so the string taken from index 2 till the index 4 as we discussed the second last index is actually taken to output the string because it is exclusive.



Arbaab khan
Arbaab khan FEAR has two meanings "forget everything and run" "Face everything and rise" The choice is yours Welcome u in our tech blog

Post a Comment