There are a lot of questions concerning String immutability, but yet I haven't found an answer for why the following happens:
1) "TEST".equals("TEST") // TRUE obviously
2) "TEST" == "TEST" // Also TRUE since String's are immutable
3) "TEST" == "T" + "E" + "S" + "T" // TRUE, but why? Due to compiler optimalization?
4) "TEST" == new String("TEST"); // FALSE, because you explicitly request a new String?
Can anyone correct me if necessary and explain in further detail 3 and 4? Many thanks!
The concatenation happens at compile time, so the String goes to the pool, that's why you get true
.
Regarding the last one, a new object is created because your'e using new
keyword and comparing the references by ==
, so you're getting false
.
And this has nothing to do with immutability.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.