值传递和引用传递的区别

值传递: 只要是基本类型传递 都是值传递

引用传递:针对于基本类型进行封装,对封装进行传递,是引用传递

代码:值传递(int类型)

 public class Test {
    public static void main(String[] args) {

        int int1 = 10;

        int int2 = int1;
        System.out.println("int1==" + int1);
        System.out.println("int2==" + int2);

        int2 = 20;
        System.out.println("改变之后");
        System.out.println("int1==" + int1);
        System.out.println("int2==" + int2);
	}
}

运行代码:得到的当前的结果如下

int1==10
int2==10
改变之后
int1==10
int2==20

Process finished with exit code 0

根据结果会发现int类型的传递,当int2值改变的时候,int1的值是没有任何变化的,所以基本类型都是根据它的值去传递的,传递之后,int2的值得改变和int1的值已经没有任何关系了

String类型的传递

代码:

 	    String str1 = "str1";

        String str2 = str1;
        System.out.println("str1==" + str1);
        System.out.println("str2==" + str2);

        str2 = "str2";
        System.out.println("改变之后");
        System.out.println("str1==" + str1);
        System.out.println("str2==" + str2);

结果:

str1==str1
str2==str1
改变之后
str1==str1
str2==str2

Process finished with exit code 0

结果证明String的结果 和int的结果是一样的,但是表达的方式不一样, String的表达方式和Integer是一样的,都是重新new的方式去传递值的。
String str2 = str1; 这句话可以理解为 String str2 = new String(str1); 把str1当做参数传递过去,重新new了一个新的String,所以str2的值和str1的值 虽然是一样的,但是str2 和str1却不是同一个String

类传递(引用传递)

代码: 创建了一个TestDemo的类 ,里面有一个String类型的变量 txtProtected

 	 	TestDemo testDemo1 = new TestDemo();
        testDemo1.setTxtProtected("potected");

        TestDemo testDemo2 = testDemo1;

        TestDemo testDemo3 = new TestDemo();
        testDemo3.setTxtProtected(testDemo1.getTxtProtected());
        System.out.println("testDemo1==" + testDemo1.getTxtProtected());
        System.out.println("testDemo2==" + testDemo2.getTxtProtected());
        System.out.println("testDemo3==" + testDemo3.getTxtProtected());

        testDemo2.setTxtProtected("testDemo2");
        System.out.println("改变之后");
        System.out.println("testDemo1==" + testDemo1.getTxtProtected());
        System.out.println("testDemo2==" + testDemo2.getTxtProtected());
        System.out.println("testDemo3==" + testDemo3.getTxtProtected());

运行代码的结果:

testDemo1==potected
testDemo2==potected
testDemo3==potected
改变之后
testDemo1==testDemo2
testDemo2==testDemo2
testDemo3==potected

Process finished with exit code 0

从结果可看出 test2 和test1 是一样的结果,但是test3和 test1(test2)的结果并不是一样的
那么test2这个类的指针所指向的地方 是和test1 所指向的地方 是一个 ,所以test2的 txtProtected 会导致 test1
的txtProtected 的值发生改变。
test3和 test1的值却是不一样的,其实test3的方式 和上面String的方式 是一样的,都是通过new的方式创建出来的,所以就不叙述了。

  • 13
    点赞
  • 35
    收藏
    觉得还不错? 一键收藏
  • 11
    评论
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值