Java字符串池对象创建 [英] Java String pool object creation

查看:96
本文介绍了Java字符串池对象创建的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怀疑我的概念在字符串池中是否清晰。请研究以下一组代码,并检查我的答案在以下一组陈述后创建的对象数量是否正确: -

I have doubts that whether my concepts are clear in stringpool. Please study the following set of code and check if my answers are correct in number of objects created after the following set of statements:-

1)

String s1 = "abc";
String s2 = "def";
s2 + "xyz";

2)

 String s1 = "abc";
 String s2 = "def";
 s2 = s2 + "xyz";

3)

String s1 = "abc";
String s2 = "def";
String s3 = s2 + "xyz";

4)

String s1 = "abc";
String s2 = "def";
s2 + "xyz";
String s3 = "defxyz";

根据我所知的概念,在上述所有4个案例中,将会创建4个对象每一行的执行。

As per what i know conceptually, in all the 4 cases above, there will be 4 objects created after the execution of each set of the lines.

推荐答案

你不能有像 s2 +xyz这样的表达式本身。编译器只评估常量,只有字符串常量自动添加到字符串文字池中。

You cannot have an expression like s2 + "xyz" on its own. Only constants are evaluated by the compiler and only string constants are automatically added to the String literal pool.

例如

final String s1 = "abc"; // string literal
String s2 = "abc"; // same string literal

String s3 = s1 + "xyz"; // constants evaluated by the compiler 
                        // and turned into "abcxyz"

String s4 = s2 + "xyz"; // s2 is not a constant and this will
                        // be evaluated at runtime. not in the literal pool.
assert s1 == s2;
assert s3 != s4; // different strings.

这篇关于Java字符串池对象创建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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