Java如何初始化String文字

Mạn*_*yễn 1 java string jvm

Javadoc说:

String类表示字符串。Java程序中的所有字符串文字(例如“ abc”)都实现为此类的实例。

我们知道String该类具有两个属性,分别为value[]和和hash,而String文字存储在String池中。

但是我无法弄清楚在放入该池之前如何初始化String文字。就像稍后调试字符串文字一样,我可以看到value[]hash以某种方式填充。

JVM是否调用特殊指令?

apa*_*gin 5

如果在调用之前未将相同的字符串放入字符串表,则JVM在常量池解析期间会创建一个新的字符串文字对象String.intern

没有指定JVM如何创建和初始化这样的字符串,因此JVM可以执行任何所需的操作,只要结果对象是java.lang.String可以从应用程序代码访问的常规实例即可。

至于HotSpot JVM,它不调用任何String构造函数,它只是在Heap中分配一个新对象并填写C ++代码中的字段,请参见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;
}
Run Code Online (Sandbox Code Playgroud)

hash这样的新对象的字段被初始化为零。正确的哈希码将在第一个调用时计算String.hashCode