Java如何初始化String文字 [英] How does Java initialize String literal
问题描述
Javadoc表示:
Javadoc said that:
String类表示字符串. Java程序中的所有字符串文字(例如"abc")都实现为此类的实例.
The String class represents character strings. All string literals in Java programs, such as "abc", are implemented as instances of this class.
我们知道String
类具有两个属性,即:value[]
和hash
,并且String文字存储在String池中.
We know that String
class has two properties namely: value[]
and hash
, and String literal are stored in a String pool.
但是在放入该池之前,我无法弄清如何初始化String文字.好像稍后再调试字符串文字一样,我可以看到value[]
和hash
已填充.
But I am not able to figure out how that String literal is initialized before putting to that pool. As if I debug the string literal later, I can see the value[]
and hash
is somehow populated.
JVM是否调用特殊指令?
Does JVM invoke a special instruction?
推荐答案
JVM creates a new string literal object during constant pool resolution, if the same string has not been put to the string table before by String.intern
call.
未指定JVM如何创建和初始化此类字符串,因此JVM可以执行任何所需的操作,只要结果对象是可以从应用程序代码访问的常规java.lang.String
实例即可.
It is not specified how JVM creates and initializes such strings, so JVM may do whatever it wants as long as the result object is a regular java.lang.String
instance that can be accessed from application code.
对于HotSpot JVM,它不调用任何String
构造函数,它只是在Heap中分配一个新对象并填写C ++代码中的字段,请参见
As to HotSpot JVM, it does not call any of String
constructors, it just allocates a new object in Heap and fills in the fields in C++ code, see java_lang_String::basic_create
:
Handle java_lang_String::basic_create(int length, TRAPS) {
assert(initialized, "Must be initialized");
// Create the String object first, so there's a chance that the String
// and the char array it points to end up in the same cache line.
oop obj;
obj = InstanceKlass::cast(SystemDictionary::String_klass())->allocate_instance(CHECK_NH);
// Create the char array. The String object must be handlized here
// because GC can happen as a result of the allocation attempt.
Handle h_obj(THREAD, obj);
typeArrayOop buffer;
buffer = oopFactory::new_charArray(length, CHECK_NH);
// Point the String at the char array
obj = h_obj();
set_value(obj, buffer);
// No need to zero the offset, allocation zero'ed the entire String object
assert(offset(obj) == 0, "initial String offset should be zero");
//set_offset(obj, 0);
set_count(obj, length);
return h_obj;
}
这样的新对象的
hash
字段被初始化为零.正确的哈希码将在第一次调用String.hashCode
时计算出来.
hash
field of such new object is initialized to zero. The right hash code will be calculated on the first call to String.hashCode
.
这篇关于Java如何初始化String文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!