In Java, a string can be created in two ways:
What is the difference between using the double quotes and using the constructor?
1. Double Quotes vs. Constructor
This question can be answered by using two simple examples.
a==b is true because
b are referring to the same string literal in the method area. The memory references are the same.
When the same string literal is created more than once, only one copy of each distinct string value is stored. This is called "string interning". All compile-time constant strings in Java are automatically interned.
c==d is false because
d refer to two different objects in the heap. Different objects always have different memory references.
This diagram illustrate the two situations above:
2. Run-Time String Interning
Thanks to LukasEder (his comment below):
String interning can still be done at run-time, even if two strings are constructed with constructors:
3. When to Use Which
Because the literal "abcd" is already of type String, using constructor will create an extra unnecessary object. Therefore, double quotes should be used if you just need to create a String.
If you do need to create a new object in the heap, constructor should be used.
本文分享自微信公众号 - 彤哥读源码（gh_63d1b83b9e01）。
如有侵权，请联系 email@example.com 删除。