(转载)Java String类型的参数传递问题

来源:互联网 发布:mac电脑的使用教程 编辑:程序博客网 时间:2024/06/10 14:47
1
2
3
4
5
6
7
8
9
10
11
12
13
public class Test
{
        public static void test(String str)
        {
            str = "world";
        }
        public static void main(String[] args)
        {
            String  str1 = new String("hello");
            test(str1);
            System.out.println(str1);
         }
}

  

1
2
3
4
5
6
7
8
9
10
11
12
13
public class Test
{
        public static void test(StringBuffer str)
        {
            str.append(" world");
        }
        public static void main(String[] args)
        {
            StringBuffer  str1 = new StringBuffer("hello");
            test(str1);
            System.out.println(str1);
        }
}

  理解这两个例子需要分清实参和形参的区别,引用和对象的区别
 第一个例子的内部执行过程:
 1.引用str1指向新对象new String("hello")。
 2.test( )刚刚开始调用时,形参(parameter)str复制了实参(argument)str1的值,这个值也就是对象new String("hello")的地址,所以这时候引用str和引用str1指向同一个对象"hello"。
 3.进入到test( )方法内部,“world”这个对象被分配给形参str,而这个操作对实参str1并没有影响,所以这时候,引用str指向"world",而引用str1仍然指向原来的对象"hello"。
 4.test( )方法结束后,形参str从栈内存中消失,他指向的对象"world"由于没有其他引用指向它,也可以被gc回收了。
 4.打印引用str1指向的对象,即"hello"。


 第二个例子的内部执行过程:
 1.引用str1指向新对象new StringBuffer("hello")。
 2.test( )刚刚开始调用时,形参(parameter)str复制了实参(argument)str1的值,这个值也就是对象new StringBuffer("hello")的地址,所以这时候引用str和引用str1指向同一个对象"hello"。
 3.进入到test( )方法内部,形参str调用append方法," world"附加到了引用str所指向的对象"hello"后面,由于形参str和实参str1指向的是同一个对象,所以这个操作同时也改变了引用str1指向的对象,因此这时候,引用str和str1指向同一个对象"hello world"。
 4.test( )方法结束后,形参str从栈内存中消失,他指向的对象"hello world"由于仍然有引用str1指向它,不满足被回收的条件。
 5.打印引用str1指向的对象,即"hello world"。

 理解这个例子后,回到原题,到底是传值还是传引用,一直是个有争议的问题,这个例子中,可以理解为值传递,这个值,就是引用所指向的对象的地址。

0 0
原创粉丝点击