Sunday, June 2, 2019

Java String equals()

 

Introduction:-

The Java string equals() method compares the two given strings based on the content of the string. If any character is not matched, it returns false. If all characters are matched, it returns true.

 

Example:

public class EqualsExample{
public static void main(String args[]){
String s1="automationworld";
String s2="automationworld";
String s3="AUTOMATIONWORLD";
String s4="manualworld";
System.out.println(s1.equals(s2));      //true because content and case is same
System.out.println(s1.equals(s3));     //false because case is not same
System.out.println(s1.equals(s4));    //false because content is not same
}}

 

  • The equals() method compares two strings and can be used in the if-else control structure.
  • public class EqualsExample {
        public static void main(String[] args) {
            String s1 = "automation"
            String s2 = "automation"
            String s3 = "Automation";
            System.out.println(s1.equals(s2)); // True because content is same  
            if (s1.equals(s3)) {
                System.out.println("both strings are equal");
            }else System.out.println("both strings are unequal");  
        }

     

 

 

 Test the equality of string present in the list.

import java.util.ArrayList;
public class EqualsExample3 {
    public static void main(String[] args) {
        String str1 = "Mukesh";
        ArrayList<String> list = new ArrayList<>();
        list.add("Ravi");
        list.add("Mukesh");
        list.add("Ramesh");
        list.add("Ajay");
        for (String str : list) {
            if (str.equals(str1)) {
                System.out.println("Mukesh is present");
            }
        }
    }
}


o/p
Mukesh is present
 
 
  • Difference between == and .equals() method in Java

     
 public class equalMethod {
 public static void main(String[] args) {
  
  
  String s = "Hello";
  String s1 = "Hello";
  String s2 = "hello";
   System.out.println(s==s1);    //true : literal String are equals
   System.out.println(s.equals(s1));       //true
   System.out.println(s1.equals(s2));   //false
   System.out.println(s1.equalsIgnoreCase(s2));  //true
   System.out.println(s.equalsIgnoreCase(s2));  //true
   
   
   String s3 = new String("Hello");
   String s4 = new String("Hello");
   
   System.out.println(s3==s4);    //false  // String with new keyword are not equals
   System.out.println(s3.equals(s4));   //true 
   
   
         System.out.println('a' == 97.0);   //true it will compare unicode value of 'a' that is 97 
   
         System.out.println('a' == 'a');
         System.out.println('a' == 'A');
   
   

 


No comments:

Post a Comment