string java 初始化,Java如何初始化String文字

Javadoc said that:

The String class represents character strings. All string literals in Java programs, such as "abc", are implemented as instances of this class.

We know that String class has two properties namely: value[] and hash, and String literal are stored in a String pool.

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.

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.

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.

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 field of such new object is initialized to zero. The right hash code will be calculated on the first call to String.hashCode.

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值