使用String文字创建String对象时调用哪个String类构造函数 [英] which String class constructor get called when String object created by using String literal

查看:47
本文介绍了使用String文字创建String对象时调用哪个String类构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我们使用String文字创建字符串对象时,将调用字符串类的哪个构造函数.

which constructor of string class get called when we create string object by using String literal .

示例:

String str = "hello";

在这种情况下,哪个字符串类的构造函数得到了?

In this case which constructor of string class get?

推荐答案

当JVM加载包含String文字的类

When JVM loads a class containing a String literal

String str = "hello";

它以UTF-8编码从类文件中读取字符串文字,并从中创建一个char数组

it reads string literal from class file in UTF-8 encoding and creates a char array from it

char[] a = {'h', 'e', 'l', 'l', 'o'};

然后使用String(char [])构造函数从此char数组中创建一个String对象

then it creates a String object from this char array using String(char[]) constructor

new String(a)

然后,JVM将String对象放置在String池中,并将对此String对象的引用分配给 str 变量.

then JVM places the String object in String pool and assigns the reference to this String object to str variable.

这篇关于使用String文字创建String对象时调用哪个String类构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆