95
====
1. public class X {
2. public static void main (String[]args) {
3. String s = new String ("Hello");
4. modify(s);
5. System.out.println(s);
6. }
7.
8. public static void modify (String s) {
9. s += "world!";
10. }
11. }
What is the result?
A.The program runs and prints "Hello".
B.An error causes compilation to fail.
C.The program runs and prints "Hello world!".
D.The program runs but aborts with an exception.
为什么选A 而不选C?static不是引用地址,会改变的吗?
s += "world!";中的s引用了+= "world!";返回的新串,
String s = new String ("Hello");中的s引用的还是原来的对象
这个是关于变量传值的问题。
modify(s);
直接改变传进来变量的值,
对s是不会改变的
不仅是STRING,所有变量都一样。
如果传入数组,改变数组的值就可以。
一年前考过SCJP1。2
这些问题具体这么回答有点忘了。
相信许多资料对这个问题有说明
其实,本质上是因为,String对象从来不会改变的,如:
String str = "Hello World"; ----- 1
str = str +"!"; ------2
那么,我们可能认为str原来指向的句柄的内容为"Hello World!",
其实,1处和2处str的句柄被更改了,这与StringBuffer不一样,
StringBuffer对象是可以更改内容的,而String是不可以的,所以上面
modify(String s),参数s开始时是复制了一个1句柄,指向"Hello World",
后来,在modify中更改她的内容时,参数s的句柄被更改,所以你上面实参
str的句柄的内容是不变的。如果是StringBuffer,
实参和形参都指向同一个句柄,而该句柄指向的地址一样,所以你更改它的
值时,是可以改变外面的实参的。
上面是我的理解,如果有问题,我们再探讨探讨,互相学习
JAVA是传值调用 call by value,得到的是参数的拷贝
改变的只是
8. public static void modify (String s) {
9. s += "world!";
10. }
里的s的值,改变后的值没有传递出去
所以值仍然是hello