且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Java中,为什么String是非原始数据类型?

更新时间:2023-01-01 08:59:58

字符串str =这是字符串文字";

这是字符串文字.像这样声明字符串时,实际上是在String上调用intern()方法.此方法引用内部字符串对象池.如果已经存在一个字符串值"This is stringliteral",则str将引用该字符串,并且不会创建新的String对象.

String str = "This is string literal";

This is string literal. When you declare string like this, you are actually calling intern() method on String. This method references internal pool of string objects. If there already exists a string value "This is string literal", then str will reference of that string and no new String object will be created.

这是字符串对象.在这种方法中,即使引用池中有这是由新操作员创建的字符串",JVM也***创建新的字符串引用.

This is string object. In this method JVM is forced to create a new string reference, even if "this is string created by new operator" is in the reference pool.