-5

I am using the same string as str1 and str2 when I compare this it will give true output with same hashcode. but when I use new String it will give different output with same hash code. As per my information == keyword compare string according to hash code but still I get different output?

public class StringClass {
public static void main(String args[]){
    String str1="john";
    String str2="john";
    String str3=new String("john");
    String str4=new String("john");
    if(str1==str2){
        System.out.println("Both string have same hash code");
        System.out.println(str1.hashCode());
        System.out.println(str2.hashCode());
    }
    if(str3==str4){
        System.out.println("both have same hash code");
        System.out.println(str3.hashCode());
        System.out.println(str4.hashCode());
    }
}
}
RedLaser
  • 680
  • 1
  • 8
  • 20
nil
  • 1
  • 3
  • 3
    `==` does not compare `hashCode()`. It compares object references (to simplify at the cost of precision: it compares if two objects references point to the same physical object in memory) – Kon Mar 23 '15 at 16:44
  • 1
    possible duplicate of [Java String Pool](http://stackoverflow.com/questions/2486191/java-string-pool) – GhostCat Mar 23 '15 at 16:46
  • what is hash code how it is work – nil Mar 23 '15 at 16:49
  • 1
    [The documentation is very clear.](http://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#hashCode--) – Sotirios Delimanolis Mar 23 '15 at 16:52

3 Answers3

1

No. == compares the references. this means == compares where in the memory the object is saved. hashCode() creates an integer from the attributes of an Object (the algorithm for this operation may vary from class to class). Comparison of objects should be done via o1.equals(o2).

  • Two string always have same hash code if it is same string. And sometime in other case (almost randomly). – talex Mar 23 '15 at 16:58
  • might actually happen, though it's rather seldom. two objects have the same hashCode, if either equals is true, or if two objects create the same hashCode due to the implementation. –  Mar 23 '15 at 16:58
0

== does NOT use an object's hash to compare. Hash is just a tool for indexing and managing Objects. Two arbitrary objects may produce the same hash code.

Object.equals(Object) gives you the 'equality' as you may understand it, as "my string" is equals to "my string", without taking into account if it's actually the same object or not (both strings may be the same object, or two objects with the same data).

== compares the references, so it returns true only if the two variables contain the pointer to the same data.

Machavity
  • 30,841
  • 27
  • 92
  • 100
Dani
  • 161
  • 4
-1

You cannot use == when checking for String equality in Java. Use String.equals(otherString)!

Ron Thompson
  • 1,086
  • 6
  • 12