值传递和引用传递

来源:互联网 发布:知乎下载电脑版 编辑:程序博客网 时间:2024/06/16 16:07
下面程序的输出结果是?

<span style="font-family:Times New Roman;font-size:14px;"><span style="font-family:SimSun;font-size:14px;">public class Example {    String str = new String("good");    char[] ch = { 'a', 'b', 'c' };     public static void main(String args[]) {        Example ex = new Example();        ex.change(ex.str, ex.ch);        System.out.print(ex.str + " and ");        System.out.print(ex.ch);    }    public void change(String str, char ch[])         {        str = "test ok";        ch[0] = 'g';    }}</span></span>
输出结果为:good and gbc

考察值传递和引用传递。

对于值传递,拷贝的值用完之后就会被释放,对原值没有任何影响,但是对于引用传递,拷贝的是对象的引用,和原值指向的同一块地址,即操作的是同一个对象,所以操作之间会相互影响。

都是引用传递,只是因为String是个特殊的final类,所以每次对String的更改都会重新创建内存地址并存储(也可能是在字符串常量池中创建内存地址并存入对应的字符串内容),但是因为这里String是作为参数传递的,在方法体内会产生新的字符串而不会对方法体外的字符串产生影响。
0 0