Topic: 一道scjp-055的题目,关于String的,很奇怪他的答案

  Print this page

1.一道scjp-055的题目,关于String的,很奇怪他的答案 Copy to clipboard
Posted by: ycxct
Posted on: 2006-12-19 18:17

11. public String makinStrings() {
12. String s = “Fred”;
13. s = s + “47”;
14. s = s.substring(2, 5);
15. s = s.toUpperCase();
16. return s.toString();
17. }
How many String objects will be created when this method is invoked?
A. 1
B. 2
C. 3
D. 4
E. 5
F. 6
Answer: C

我认为应该是D,也就是4个String被创建
1:“Fred”;
2: s + “47”;
3: s.substring(2, 5);
4: s.toUpperCase();

可是答案是3个,奇怪ing,谁能帮我解惑

2.Re:一道scjp-055的题目,关于String的,很奇怪他的答案 [Re: ycxct] Copy to clipboard
Posted by: zerol
Posted on: 2006-12-19 19:17

i'v tried the following progie , and the output is :

C:\>java A
2198155
2112428622
100213
68469
68469


class A {
public static void main(String[] args) {
System.out.println((new A().makinStrings()).hashCode());
}

public String makinStrings() {
String s = "Fred";
System.out.println(s.hashCode());

s = s + "47";
System.out.println(s.hashCode());

s = s.substring(2, 5);
System.out.println(s.hashCode());

s = s.toUpperCase();
System.out.println(s.hashCode());

return s.toString();
}

}

3.Re:一道scjp-055的题目,关于String的,很奇怪他的答案 [Re: ycxct] Copy to clipboard
Posted by: ycxct
Posted on: 2006-12-19 21:44

呵呵,hashCode...,高人啊,不过看来题目是有问题了,明明就是4个嘛...

不过如果把 s = s.substring(2, 5) 改成 s = s.substring(4, 5),答案C就正确了,
因为这时s="25",无需变更大小写,"s.toUpperCase()"将返回原来的s地址
同时试验了一下,如果s里都为大写字母,返回的也是自己的地址..


   Powered by Jute Powerful Forum® Version Jute 1.5.6 Ent
Copyright © 2002-2021 Cjsdn Team. All Righits Reserved. 闽ICP备05005120号-1
客服电话 18559299278    客服信箱 714923@qq.com    客服QQ 714923