0

How the String creation is working here? How s1 & s2 references to same object in String pool but the same is not working with s1 & s4

    String s1 = "tomcat10";
    String s2 = "tomcat" + 10;
    String s3 = "tomcat";
    String s4 = s3 + 10;

    System.out.println(s1==s2);//true
    System.out.println(s1==s4);//false
Suchit
  • 60
  • 2
  • 12
  • 3
    Possible duplicate of [What is Java String interning?](https://stackoverflow.com/questions/10578984/what-is-java-string-interning) – LppEdd Mar 10 '19 at 14:47
  • Try `final String s3 = "tomcat";` - and don't use `==` for comparing `Object`(s). – Elliott Frisch Mar 10 '19 at 14:48
  • I don't want to compare the content but basically looking out for the object creation and memory allocation.Content of s1,s2,s3 all are equal. s1 is a string literal and crated first so in goes in SCP memory, while creating s2 content is same as s1 so same object is referenced. but even s4 is having the same content as s1 and having same hashcode value but why == operation is returning false?? – Suchit Mar 10 '19 at 15:01
  • Because there are two unique `String` instances, if you mark `s3` as `final` (or explicitly `intern` `s3`) then it will search the constant pool and there won't be. But you shouldn't be relying on object reference(s) like this. – Elliott Frisch Mar 10 '19 at 15:02
  • 3
    in `String s2 = "tomcat" + 10;` the expression `"tomcat" + 10` is a compile time constant that the compiler replaces with `"tomcat10"`, so this assignment uses the same constant as `String s1 = "tomcat10";`. However in `String s4 = s3 + 10;` the expression `s3 + 10` is not a compile time constant, it is evaluated at runtime. And evaluation of string expressions at runtime never return constant pool entries, with the sole exception of `String.intern()` – Thomas Kläger Mar 10 '19 at 15:10
  • @ThomasKläger Thanks a lot for making it clear. Thanks everyone. – Suchit Mar 10 '19 at 15:14

0 Answers0