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.

5
  • 1
    s9.hashCode() is not an address. String class overrides hashCode. The value depends on the contents of the String. Commented May 8, 2018 at 5:23
  • Sorry please more elaborate why s9==s11 is false Commented May 8, 2018 at 5:31
  • @Goutam Each call to .toUpperCase() returns a new String. Commented May 8, 2018 at 5: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 Commented May 8, 2018 at 5: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). Commented May 10, 2018 at 12:03

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

String s11=s9.toUpperCase()//is it will create a new object in Heap? then s9==s11//true why?
Updated my answer. Please check
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.