Wednesday, February 6, 2013

== vs equals in Strings in Java

The equals( ) method compares the characters inside a String object. The == operator compares two object references to see whether they refer to the same instance. The following program shows how two different String objects can contain the same characters, but references to these objects will not compare as equal:

package
blogspot.sbollam.com
 public class Sample {
 public Sample()
 {
  System.out.println("Sample.Sample()");
 }

 /**
  * @param args
  */
 public static void main(String[] args)
 {


  String s1= new String("abc");
  String s2= new String("abc");
  String s3 ="abc";
  String s4 ="abc";
  System.out.println(s1==s3);
  System.out.println(s1==s2);
  System.out.println(s1.equals(s2));
  System.out.println(s1.equals(s3));
  System.out.println(s3.equals(s4));
  System.out.println(s3==s4);
  /*OUTPPUT:
   *
   * false false true true true true
   * */
 }

}


No comments:

Post a Comment