【Java.Core】Create Java String Using ” ” or Constructor?

转自http://www.programcreek.com/2014/03/create-java-string-by-double-quotes-vs-by-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?

1. Double Quotes vs. Constructor

This question can be answered by using two simple code examples.

Example 1:

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, 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.

Example 2:

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 references.

This diagram illustrate the two situations above:
constructor vs double quotes Java String - New Page

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:

String c = new String("abcd").intern();
String d = new String("abcd").intern();
System.out.println(c == d);  // Now true
System.out.println(c.equals(d)); // True

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. Here is a use case.


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值