在内存中创建了多少个字符串? [英] How many Strings are created in memory?

查看:87
本文介绍了在内存中创建了多少个字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有这个 String 表达式

String hi = "Tom" + "Brady" + "Goat"

我知道字符串池允许运行时通过在池中保留不可变的字符串来节省内存 字符串池

I know that the String pool "allows a runtime to save memory by preserving immutable strings in a pool" String Pool

将在字符串池中创建多少个字符串?

How many strings will be created in the string pool?

我最初的猜测是5-汤姆 Brady 山羊 TomBrady TomBradyGoat ,因为 String 串联的操作顺序(从左到右?)还是存储在字符串池中的最终结果 TomBradyGoat?

My initial guess was 5 - "Tom", "Brady", "Goat", "TomBrady","TomBradyGoat", because of the order of operations of String concatenation (left to right?) or is it only the final result, "TomBradyGoat", that is stored in the String pool?

推荐答案

在运行时,该片段代码将转换为单个 String 对象。编译器将在编译时进行串联,并在常量池中添加一个值。

At runtime, that piece of code will translate into a single String object. The compiler will take care of concatenation at compile time and add a single value in the constants pool.

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

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