在代码String s =" abc" +" xyz";中创建了多少个Java字符串对象? [英] How many Java string objects created in the code String s="abc"+"xyz";?

查看:109
本文介绍了在代码String s =" abc" +" xyz";中创建了多少个Java字符串对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下语句中将创建多少个Java字符串对象?

How many Java string objects will be created in the following statement?

String s = "abc" + "xyz"; 

我猜三个?

推荐答案

编译器为每个JVM启动创建1个String,因为编译器可以在编译时确定生成的String,它是 interned 并静态存储在JVM的字符串表

The compiler creates 1 String per JVM start, because the compiler can determine the resulting String at compile time, it is interned and statically stored in the JVM's String Table.

FYI,如果该语句连接变量(在运行时无法确定),将创建1个字符串,但它也会创建 StringBuilder 。代码将编译为:

FYI, if the statement were concatenating variables (not determinable at runtime), 1 String would be created, but it would create a StringBuilder too. The code would compile to:

new StringBuilder().append(abcVar).append(xyzVar).toString()

这篇关于在代码String s =" abc" +" xyz";中创建了多少个Java字符串对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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