【Java.Core】Create Java String Using ” ” or Constructor?
来源:互联网 发布:网络兼职广告语 编辑:程序博客网 时间:2024/06/05 03:36
转自: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:
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:
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:
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:
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. Here is a use case.
- 【Java.Core】Create Java String Using ” ” or Constructor?
- Create a string parser using java.util.StringTokenizer
- Java Constructor
- Java Constructor
- JAVA constructor
- Can I use Java to create or manage XML files?
- Constructor or not constructor?
- Java反射机制:Constructor!
- [Java] Constructor 构造方法
- Java中的constructor
- Java Private Constructor
- Java中的constructor
- Java中的constructor
- Java中的constructor
- Java: Snack from Constructor
- Java中的constructor
- java 中的constructor
- Java中的constructor
- Hadoop2.6源码编译
- No current when connecting Hive2 in HDP 2.1
- Serializable和Parcelable应该懂得的几个场景
- 判断一个框是否填写为double类型
- SignalR-Server开源项目
- 【Java.Core】Create Java String Using ” ” or Constructor?
- lnmp环境检测工具lnmpcheck
- div滚动效果
- JNI
- 菜单项MenuListener。。其实就是这种方法替换了OnOpetionsSelectedItem方法
- AppCan获得B轮1亿元融资并宣布移动引擎开源
- php输出格式化的那点事
- CSS 文字跳动
- python 学习笔记