0
public static void main(String[] args) {

    String s1="me";

    String s2="me".toUpperCase().toLowerCase();

    System.out.println(s1==s2);

    /*The line above prints false as output*/

}

String is immutable it means that if a string is created as "me" a object will be created and location will be assigned to variable and if another String is created with same data i.e. "me" instead of creating another object the JVM refers to the same location of first string. In given code "me" and "me" are created but have different location! I think both s1 and s2 should refer to same location as the final data stored is same case wise.

Please help me by telling me that why JVM is creating 2 objects even both have the same data.

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
  • 2
    `String s2="me".toUpperCase().toLowerCase().intern();` (keep it simple, don't compare objects with `==`). – Elliott Frisch Aug 27 '23 at 15:36
  • @ElliottFrisch I don't think this is a duplicate. OP is not asking how to compare strings, but why two String objects with the same content are in fact two different objects in the JVM. – Robert Aug 27 '23 at 15:38
  • 7
    @Robert, ...it certainly seems a duplicate to me. A full explanation of why `==` is the wrong operator covers the case at hand; and indeed, the accepted answer there _does_, in explaining the difference between reference equality and value equality, cover the necessary ground. – Charles Duffy Aug 27 '23 at 15:39
  • 1
    "instead of creating another object the JVM refers to the same location of first string." - citation needed. – Sören Aug 27 '23 at 15:41
  • 2
    @RaunakRanjan, "why JVM is creating 2 objects even [though] both have the same data" -- the amount of work that would be needed to detect "are there any preexisting objects identical to this new value?" is immense; it would significantly change the performance characteristics of language primitives. There's a reason interning is only done on request -- but [Stack Overflow is focused on "how" questions, not "why" ones](https://meta.stackexchange.com/questions/170394); we're narrowly focused on problems "you actually face", so once you know how to write correct code, our scope is fulfilled. – Charles Duffy Aug 27 '23 at 15:43
  • 6
    The point is not "why are the two objects different?" but "what makes you believe they are required to be the same?". "Immutable" means no such thing; it just means the object cannot be changed, it says nothing at all about object identity. – Arfur Narf Aug 27 '23 at 15:53
  • Your String objects are indeed equal: `"me".equals( "me".toUpperCase().toLowerCase() )` is true. https://ideone.com/qV93gs – Basil Bourque Aug 27 '23 at 17:01

0 Answers0