0

In below code HashCode of s1 and s3 are equal but s1==s3 returns false why?.Please clarify it. Here s1 ,s2 and s3 contains same content and HashCode . When run below code then out is

108274800

108274800

108274800

s1==s2

s1.equals(s2)

s1.equals(s3)

Code is given as follows...

public class StringTest {

/**
 * @param args
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub

String s1="rahul";
String s2="rahul";
String s3=new String("rahul");
System.out.println(s1.hashCode());
System.out.println(s2.hashCode());
System.out.println(s3.hashCode());

if(s1==s2){

    System.out.println("s1==s2");
}

if(s1==s3){

    System.out.println("s1==s3");
}

if(s1.equals(s2)){

    System.out.println("s1.equals(s2)");
}

if(s1.equals(s3)){

    System.out.println("s1.equals(s3)");
}

}

}

Rahul Tripathi
  • 545
  • 2
  • 7
  • 17

1 Answers1

1

== Compares only the reference type, to compare objects or string, you should must use s1.equals(s2)

Tarek
  • 771
  • 7
  • 18
  • I read this line on SO, about 1000 times ;) – Suresh Atta Oct 17 '14 at 12:12
  • 2
    And you may also want, he will read that minimum 1 time. – Tarek Oct 17 '14 at 12:14
  • what is relation between hashcode and ==.This is my question ?Please suggest on this basis. – Rahul Tripathi Oct 17 '14 at 12:18
  • 1
    If strings are equal then their hash codes must also be equal. The reverse is not true. Different strings may have identical hash codes. The number of possible strings is vastly greater than the number of possible hash codes, so duplicate hash codes are inevitable. – rossum Oct 17 '14 at 12:23