Tuesday, March 4, 2014

Create Java String Using ” ” or Constructor?

In Java, a string can be created by using two methods:
String x = "abc";
String y = new String("abc");
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.
String a = "abcd";
String b = "abcd";
System.out.println(a == b);  // True
System.out.println(a.equals(b)); // True
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“.
String c = new String("abcd");
String d = new String("abcd");
System.out.println(c == d);  // False
System.out.println(c.equals(d)); // True
c==d is false because c and d refer to two different objects in the heap. Different objects always have different memory reference.
constructor vs double quotes Java String - New Page
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