将创建多少个String对象

编程入门 行业动态 更新时间:2024-10-15 20:16:33
本文介绍了将创建多少个String对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有以下Java代码:

I have the following Java code:

public String makinStrings() { String s = "Fred"; s = s + "47"; s = s.substring(2, 5); s = s.toUpperCase(); return s.toString(); }

这个问题有点简单:多少 String 调用此方法时会创建对象吗?

The question is somehow simple: how many String objects will be created when this method is invoked?

一开始我回答说创建了5个String对象,但我书中的答案说只创建了3个对象并且没有给出解释(这是一个SCJP问题)。

At the beginning I answered that 5 String objects are created, but the answer from my book says that only 3 objects are created and no explanation was given (this is a SCJP question).

从我的观点来看,有5个对象:Fred ,47,Fred47,ed4,ED4。

From my point of view there are 5 objects: "Fred", "47", "Fred47", "ed4", "ED4".

我也在SCJP模拟考试中找到了这个问题,答案相同3。

I also found this question on a SCJP simulation exam, with the same answer 3.

推荐答案

Fred和47将来自字符串文字池。因此,在调用方法时,将不会创建。相反,它们将在加载类时放在那里(或者更早,如果其他类使用具有相同值的常量)。

"Fred" and "47" will come from the string literal pool. As such they won't be created when the method is invoked. Instead they will be put there when the class is loaded (or earlier, if other classes use constants with the same value).

Fred47,ed4和 ED4是将在每次方法调用时创建的3 String 对象。

"Fred47", "ed4" and "ED4" are the 3 String objects that will be created on each method invocation.

更多推荐

将创建多少个String对象

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

发布评论

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

>www.elefans.com

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