0

In java for below code:-

s1="ab"
s2="a"
s1=="a"+"b" 
s1==s2+"b" 

The first comparison returs true and second comparison returns flase. Why so?

Note:- both results in "ab" string only

Yatin Garg
  • 141
  • 1
  • 8
  • 1
    Someone asked this just yesterday -- I guess you're also reading the Head First Java book (it's really popular, after all). – T.J. Crowder Jun 14 '15 at 08:57
  • Take a look here: [How do I compare strings in Java?](https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – tirz Jun 14 '15 at 09:28
  • I found below answer for the above question: "a"+"b" gets computed at compile time and gets stored as "ab". However s2+"b" gets computed at runtime and whike doing so jvm creates a new java string object in heap space.. I tried changing s2 as final s2.. This resulted in second comparison to true as s2 becomes compile time constant – Yatin Garg Jun 23 '15 at 13:29

0 Answers0