java方法形参的值传递与引用传递

借鉴文章:
https://blog.csdn.net/Start1234567/article/details/109373902

public static void main(String[] args) {

       /*基本数据类型,包装类和String类型的形参是值传递,
       值传递不会影响原对象的值;
       其他类型是引用传递
       * 引用传递在不改变对象的情况下(即new一个对象),更改对象属性会对原对象造成影响*/
        int a=0;
        test(a);
        System.out.println("原对象int:"+a);
        System.out.println("--------------------");
       Integer i=null;
       test(i);
        System.out.println("原对象Integer:"+i);
        System.out.println("--------------------");
        String str=null;
        test(str);
        System.out.println("原对象String:"+str);
        System.out.println("--------------------");
        String[] s = new String[2];
        test(s);
        for (String s1 : s) {
            System.out.println("原对象数组:"+s1);
        }
        System.out.println("--------------------");
        JSONObject jsonObject = new JSONObject();
        test(jsonObject);
        System.out.println("原对象JSONObject:"+jsonObject);

    }
    public static void   test(int  i){
        i=2;
        System.out.println("int类型更改后:"+i);
    }
    public static void   test(Integer  i){
        i=3;
        System.out.println("Integer类型更改后:"+i);
    }
    public static void   test(String  s){
        s ="test";
        System.out.println("String类型更改后:"+s);
    }
    public static void  test(JSONObject e){
        //没有改变原对象的
        e.put("test",11);
        System.out.println("JSONObject类型更改后:"+e);
    }
    public static void  test(String[]  s){
        //重新生成了一个对象,原对象不受影响
       s=new String[3];
       s[0]="111";
        for (String s1 : s) {
            System.out.println("数组类型更改后:"+s1);
        }
    }

运行结果:

int类型更改后:2
原对象int:0
--------------------
Integer类型更改后:3
原对象Integer:null
--------------------
String类型更改后:test
原对象String:null
--------------------
数组类型更改后:111
数组类型更改后:null
数组类型更改后:null
原对象数组:null
原对象数组:null
--------------------
JSONObject类型更改后:{"test":11}
原对象JSONObject:{"test":11}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值