java中String对象作为参数传递问题

x33g5p2x  于2022-03-19 转载在 Java  
字(1.1k)|赞(0)|评价(0)|浏览(201)

问题

java中将对象作为参数传递究竟是值传递还是引用传递?
1、基本类型作为参数传递时,是传递值的拷贝,无论你怎么改变这个拷贝,原值是不会改变的。
2、对象作为参数传递时,是把对象在内存中的地址拷贝了一份传给了参数。

且看下面代码
首先我们有一个Student类,它有两个成员变量nameage

package test_code;
public class Student {
    String name;
    int age;
    public Student(String name,int age){
        this.name = name;
        this.age = age;
    }
}

Student对象进行参数传递,运行如下代码

package test_code;
public class method_test {
    public static void main(String[] args) {
        Student s = new Student("jack",16);
        test(stu);
        System.out.println(stu.age);
    }
    public static void test(Student s)
    {
        s.age = 22;
    }
}

请问输出是16还是22呢?
答案是22,因为对象进行参数传递时是将对象的地址拷贝了一份传给s,也就是说方法中的s和传入的stu指向的是同一个对象,通过s.age将值进行修改了那么stu.age的值也相应被修改了。这很容易理解。

那么当String类对象进行参数传递时,运行如下代码

package test_code;
public class method_test {
    public static void main(String[] args) {
        String str = "111";
        test(str);
        System.out.println(str);
    }
    public static void test(String s)
    {
        System.out.println(s);
        s = "222";
        System.out.println(s);
    }
}

请问输出是什么呢?
答案是222吗?不对。
那么为什么答案是111呢?
问题就在s = "222";这一行上。
这一行执行后,s和str所指向的对象就不是一个了。为什么呢?
由于Java中String对象不可改变的特性,这里其实是在常量池中新开辟了一块区域给222使用,s指向了222,但是并没有改变str的指向,那么str自然是111了。

本文较为简单,但希望能够大家带来一定的启发,大家在工作学习中一定要多多思考,欢迎关注,一起进步。

相关文章

微信公众号

最新文章

更多