Sunday 18 September 2016

String objects comparision

12.11 String objects comparision

String objects comparison
There are two ways to compare String objects:
  1. By .equals() method
  2. By = =  operator.
                                
1. By .equals() method
  • .equals() method will compare the content of the String objects.
  • .equals() method is available in Object class which is super class in Java, in Object class .equals() method compare the address comparison.
  • This method is overridden in String class for content comparison.
  • .equals() method will return the boolean type, means result will be either true or false.
-------------------------------------------------------------------
Program         :        Compare String objects by .equals() method
Program name  :        EqualsDemo1.java
Output             : 
                                true 
                                true
                                false

class EqualsDemo1
{
public static void main(String args[])
{
        String s1 = "Java";
        String s2 = "Java";

        String s3 = new String("Biriyani");
        String s4 = new String("Biriyani");

        System.out.println(s1.equals(s2));
        System.out.println(s3.equals(s4));
        System.out.println(s1.equals(s4));
}
}

Compile          :          javac EqualsDemo1.java
Run                :          java EqualsDemo1
Output            :
                                 true 
                                 true
                                 false
Note 
  • While comparing String objects by .equals() method, JVM never bother about the objects are created by literal or new operator.
  • .equals() method just compare the content of String objects where ever it is means either in heap or SCP
-------------------------------------------------------------------
2. By = = operator
  • == operator will compare the address of the String objects.
  • == operator will returns the boolean type, means result will be either true of false
-------------------------------------------------------------------
Program         :        Compare String objects by = = operator
Program name  :        EqualsDemo2.java
Output             : 
                                true 
                                false
                                false

class EqualsDemo2
{
public static void main(String args[])
{
        String s1 = "Java";
        String s2 = "Java";

        String s3 = new String("Biriyani");
        String s4 = new String("Biriyani");

        System.out.println(s1 == s2);
        System.out.println(s3 == s4);
        System.out.println(s1 == s4);
}
}

Compile          :          javac EqualsDemo2.java
Run                :          java EqualsDemo2
Output            :
                                 true 
                                 false
                                 false
-------------------------------------------------------------------
Thanks for your time.
Nireekshan