ZMedia Purwodadi

Java String contains() method explained | technical-arbaab

Table of Contents

 Java String contains() method explained


It is a predefined function which is present in the Java.lang.String package. It is used to check the occurrence of specific sequence of characters in a string and returns boolean type true or false let's see it in the code-

Syntax of contains() method

  public boolean contains(CharSequence s) {}  

Example 01 of contains() method

 public class Contains {  
      public static void main(String[] args)  
      {  
           String s1 = "mountains";  
           System.out.println(s1.contains("mou"));  
      }  
 }  

Output:

 true  

Example 02 of contains() method

program 01: "To check the occurrence of specific sequence of characters in a string using contains method".

Problem Statement: "Take a string input from the user as a password variable and check whether the specific sequence of strings exists in that password or not if yes, print valid if not print incorrect and give another chance to the user to enter password repeatedly, till the user enters right password which actually contains specific sequence of strings and when the user enters right password print password is valid and terminate the program".

Source code:

 import java.io.*;  
 public class Contains {  
      public static void main(String[] args) throws IOException  
      {  
           System.out.println("enter a password");  
           checkPassword();  
      }  
           public static void checkPassword() throws IOException  
           {  
                BufferedReader b = new BufferedReader(new InputStreamReader(System.in));  
                String pas = b.readLine();  
                if(pas.contains("#$@!"))  
                {  
                     System.out.println("password is valid");  
                }  
                else  
                {  
                     System.out.println("enter password again");  
                     checkPassword();  
                }  
           }  
 }  
Output:
 enter a password  
 Arbaab123  
 password is incorect  
 enter password again  
 zack&54  
 password is incorect  
 enter password again  
 Arbaab#$@!  
 password is valid  
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

إرسال تعليق