Java字符串池对象创建

编程入门 行业动态 更新时间:2024-10-10 21:27:01
本文介绍了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字符串池对象创建

本文发布于:2023-08-04 21:43:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1299871.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   对象   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!