1

As of i know any changes on String a new Object will create,and for some run time activity if there is a content change then a new object will create in Heap are, but i am confusing on below cases, please give idea...

String s8="abcd";
String s9=s8.toUpperCase();
String s11=s8.toUpperCase();
System.out.println("S9 "+s9.hashCode() +"  s10 "+s11.hashCode());//S9 -- 2001986  s10 -- 2001986
System.out.println(s9==s11);//false

In the above scenario the address is printing same but the == operator shaowing false.

please tell why address is same and comparision is false.

Kunu
  • 35
  • 1
  • 6
  • 1
    `s9.hashCode()` is not an address. `String` class overrides `hashCode`. The value depends on the contents of the `String`. – Eran May 08 '18 at 05:23
  • Sorry please more elaborate why s9==s11 is false – Kunu May 08 '18 at 05:31
  • @Goutam Each call to `.toUpperCase()` returns a new String. – Eran May 08 '18 at 05:33
  • But the content will same means the same object will reuse right but when calling String s11=s9.toUpperCase() then the result is true... String s6=new String("goutamgiri"); String s7=s6.toString(); System.out.println(s6==s7);// true because the content is same and the same object will resue..... because of this only i am confusing – Kunu May 08 '18 at 05:37
  • Use of `==` with objects compares identity (is it the exact same object), you need to use `.equals()` to check if they are equal (same value, but possibly different object). – Mark Rotteveel May 10 '18 at 12:03

2 Answers2

1
String s8="abcd"; : Memory will be allocated from constant pool.

String s9=s8.toUpperCase(); New object will be created on heap

String s11=s8.toUpperCase(); Another  New object will be created on heap

If you look at the implementation of toUpperCase

public String toUpperCase(Locale locale) {

..

return new String(result, 0, len + resultOffset);

Hence it creates a new object on heap each time. therefore s9 != s11

Note: If two objects are equal then their hashcodes are equal but vice versa is not true

UPDATE:

String s11=s9.toUpperCase();
s11==s9 // returns true 

Because there are not chars which can be modified and therefore s11 and s9 both points to the same object. I strongly recommend to you to read the implementation

Yati Sawhney
  • 1,372
  • 1
  • 12
  • 19
0

== operator is used for reference comperison. Basically when you create s9 and s11 then only 1 object is created in heap. That's why those 2 hashcode is same and 2 different references are pointing same object. That's why s9==s11 has retured false.

emon
  • 1,629
  • 1
  • 17
  • 18