ZMedia Purwodadi

Java String startsWith() method explained | technical-arbaab

Table of Contents

Java String startsWith() method 


It is a predefined function which is present in the Java.lang.String package. It is used to check whether your string starts with the specific sequence of characters or not which you will pass actually in the parameter of this method and returns boolean type true if it starts with the string passed or false if it is not starts with the string passed. lt is of two types, let us discuss each of them in detail:

Types of startsWith() method 

 public boolean startsWith(String prefix) {}  
 public boolean startsWith(String prefix, int toffset) {}  

Example 01 of startsWith(String prefix) method 

 public class StartsWith {  
      public static void main(String[] args) {  
           String s1="Neha is my love";  
           System.out.println(s2.startsWith("Ne"));
           System.out.println(s2.startsWith("Neha"));
           System.out.println(s2.startsWith("Neha is my")); 
      }  
 }  
Output:
 true  
 true  
 true  

here, we have first check that our string s1 starts with "Ne" then we check again that our string starts with "Neha" then again we check that our string starts with "Neha is my" and in all the three cases it is true hence it outputs true.

Example 01 of startsWith(String prefix, int toffset)

 public class StartsWith {  
      public static void main(String[] args) {  
      String s1="Neha is my love";   
      System.out.println(s2.startsWith("Neha",4));  
      }  
 }  
Output:
 false  

here, the method startsWith(String prefix, int toffset) works the same as the first one but there is one more option is given in this method that is to check from the specified index, whether your string starts with specified sequence of characters or not from the specified index number in your string for example here, in this above code our string starts with "Neha" but it has printed false because in the second parameter we have passed 4 which means to start the checking from index number 4 where is actually space is there after "Neha" so it has printed false (hope it is clear).

If you find this article helpful let us know in the comment section below and share it with your friends who are java lovers.

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

إرسال تعليق