Wednesday 8 February 2017

Java String equals() method




  This method compares one string with other and return true if the contents of both the strings being compared are equal. The general form is:

 boolean equals(Object stringObject)

For example

s1.equals(s2);

 Where s1 and s2 are two strings being compared. If they are equal the method returns true.
 Consider the following program:

EqualsTest.java


 class EqualsTest
 {
  public static void main(String arg[])
  {
   String s1="Java";
   String s2="Java";
   String s3="Coffee";
   String s4="JAVA";

   System.out.println(s1+" equals "+s2+" is: " +s1.equals(s2));
   System.out.println(s1+" equals "+s3+" is: "+s1.equals(s3));
   System.out.println(s1+" equals "+s4+" is: "+s1.equals(s4));
  }
 }

 The output generated by the above program ia:

  Java equals Java is:true
  Java equals Coffee is:false
  Java equals JAVA is:false

Note:

  equals() and ‘==’ are not same. Because while the equals() method compares two string objects, the == operator compares two objects to see if they have the same instance This is illustrated the next example:

CompreTest.java


 class CompareTest
 {
  public static void main(String arg[])
  {
   String s1="Java";
   String s2= new String(s1);
   System.out.println(s1+" equals "+s2+" is: "+s1.equals(s2));
   System.out.println(s1+"=="+s2+" is: "+(s1==s2));
  }
 }

 The output is:

  Java equals Java is: true
  Java==java is: false

  In the above program the variable s1 refers the String instance “Java” and the object referred to as s2 is created with s1 as an initialize. Thus the content of both the String objects are identical, but they are not the same objects.

 Next Topic Shahbaz

0 comments:

Post a Comment

Powered by Blogger.

Stats