由方法创建的字符串对象
我正在为我的 Oracle 认证 Java 程序员认证做一些模拟测试。我在测试中发现的问题之一是:
public String makinStrings() {
String s = “Fred”;
s = s + “47”;
s = s.substring(2, 5);
s = s.toUpperCase();
return s.toString();
}
“调用此方法时将创建多少个 String 对象?”。我数了 5 个:“Fred”、“47”、“Fred47”、子字符串“ed4”和大写字符串“ED4”,但问题答案是 3 个对象(并且测试所在的文档没有解释部分)。你能指出我的错误在哪里吗?
I'm doing a few mock test for my Oracle Certified Java Programmer certification. One of the question I found in a test is this one:
public String makinStrings() {
String s = “Fred”;
s = s + “47”;
s = s.substring(2, 5);
s = s.toUpperCase();
return s.toString();
}
And the question is "How many String objects will be created when this method is invoked?". I'm counting 5: "Fred", "47", "Fred47", the substring "ed4" and the uppercased string "ED4", but the question answer is 3 objects (and the document where the test is doesn't have an explanation section). Can you point where is my error?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
听起来错误在于“调用此方法时将创建多少个字符串对象”
您的说法是正确的,涉及五个字符串;但是,字符串是不可变的,其中两个是常量,它们被编译到包含
makinStrings()
方法的类中。因此,五个字符串中的两个预先存在该方法的调用,并且只创建了三个“新”字符串。这两个常量字符串存在于类的常量池中,并在类加载时构造。
Sounds like the error is in the interpretation of "how many strings objects will be created when this method is invoked"
You are correct in stating that five strings are involved; however, Strings are immutable, and two of those are constants that are compiled into the class containing the
makinStrings()
method. As such, two of your five pre-exist the call of the method, and only three "new" strings are created.The two constant strings exist in the class's constant pool, and were constructed at class load time.
字符串“Fred”和“47”是静态的,即它们是在加载类时创建的,而不是在调用方法时创建的。
The string "Fred" and "47" are static, ie they're created when the class is loaded, not when the method is invoked.
我能看到的最好的结果是:
“Fred”是在类加载时创建并添加到字符串池中的字符串文字。分配时不会创建对象;赋值只是传递对现有字符串的引用。
在这里,一个新的字符串被创建为 s 的先前值和文字“47”的组合。 (1)
substring() 并不对 String 本身进行操作(Java 中的 String 是不可变的),而是返回一个新的 String,即方法的返回值。 (2)
新字符串,原因与上一行相同。 (3)
String类中的toString()返回对String本身的引用。没有创建新对象。
所以 3 听起来像是正确答案。
Best I can see:
"Fred" is a string literal created and added to the String pool at class load time. No object is created when it is assigned; the assignment just passes a reference to an existing String.
Here, a new String is created as the combination of the previous value of s and the literal "47". (1)
substring() does not operate on the String itself (Strings are immutable in Java), rather, it returns a new String that is the method return value. (2)
New string, for the same reason as the previous line. (3)
toString() in the String class returns a reference to the String itself. No new object is created.
So 3 sounds like the correct answer.