In Java, a string can be created by using two methods:
What is the difference between using double quotes and using constructor?
Double Quotes vs. Constructor
This question can be answered by using two simple code examples.
a==b
is true because a
and 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, JVM store only one copy of each distinct string value. This is called “string interning“.
c==d
is false because c
and d
refer to two different objects in the heap. Different objects always have different memory reference.
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.
No comments:
Post a Comment