-8

I have below code

    String s1=new String("hello");  

    String s2="hello";  

    System.out.println(s1.hashCode());

    System.out.println(s2.hashCode());

    System.out.println(s1==s2); //returns false

Why do we get last statement as false ,the hashcode of s1 and s2 is same can someone please explain?

and after i do String s3=s1.intern();, System.out.println(s2==s3); returns true.

MD5
  • 1,356
  • 15
  • 14

1 Answers1

1

== compares references.

.equals compares values.

When you are comparing values of objects, for example, Strings, you should always use s1.equals(s2)

When you are comparing references to objects to compare if two references are pointing to the same object. Then you should use ==.


In your code, System.out.println(s1==s2); //returns false this statement compares two references s1 and s2 which are pointing to different objects though their values are same (value is "Hello", but they are two different objects in memory). Thus, your get a false in your output.


Hope this helps!

anacron
  • 6,443
  • 2
  • 26
  • 31
  • but S1.hashcode and S2.hashcode is same.. – MD5 Mar 14 '17 at 06:43
  • if you look at the code for `String.hashcode()` method, you'll find that the hashcode is computed by using the value contained in the string. So, if two strings have the same value, their hashcodes will be same. – anacron Mar 14 '17 at 06:46
  • What my assumption was If the string already exists in the pool, a reference to the pooled instance is returned. If string doesn't exist in the pool, a new string instance is created and placed in the pool. For example: String s1="Welcome"; String s2="Welcome";//will not create new instance – MD5 Mar 14 '17 at 06:51
  • That assumption is correct. The only difference in your post is that your are invoking the `new String("hello")` constructor for `s1`. – anacron Mar 14 '17 at 07:03
  • When you call `String.intern()`, it returns the reference to the object from the Stirng pool. – anacron Mar 14 '17 at 07:05