-4

I need one help to understand String class, I wrote a program where i have created one string with new keyword and other one with literal, below is program. here my confusion is why string s (literal one) got changed , as string is immutable so only value have to change why hashcode got changed. is it because of intern() method, Please help me to understand this.

    String s = "xyz";
 String s1 = new String("abc"); 
System.out.println(s.hashCode()+"--> hashcode before literal string"); 

System.out.println(s1.hashCode()+"--> hashcode before new keyword string"); 

System.out.println(s+"--> before case S value "); 
s = s1; 
System.out.println(s+ "--> after case S value"); 

System.out.println(s.hashCode()+"--> hashcode after literal string"); 

System.out.println(s1.hashCode()+"--> hashcode after new keyword string");

the output of this is

119193--> hashcode, before literal string

96354--> hashcode, before new keyword string

xyz--> before case S value

abc--> after case S value

96354--> hashcode, after literal string

96354--> hashcode, after new keyword string

  • Please elaborate , i am looking for s = s1 the output is of s1 value this one is ok and the hashcode is s1 , how this is happening ? – Pragati Yadav Oct 14 '18 at 20:08
  • java only has primitive or reference variables. Your `String s` is a reference which can point to different objects at different times but the object it points too is immutable. – Peter Lawrey Oct 15 '18 at 06:41

1 Answers1

1

A String object's value is immutable and will always generate the same hashcode.

In your question s isn't one object with two different hashcodes: it's a variable that you set to two different objects.

khelwood
  • 55,782
  • 14
  • 81
  • 108