将创建多少个String对象 [英] How many String objects will be created

查看:108
本文介绍了将创建多少个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对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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