java中方法传参形式

成员方法传参形式:

1.基本数据类型:传递的是值

public class Object03 {
    public static void main(String[] args) {
        AA aa = new AA();
        int a = 10,b= 20;
        System.out.println("main中a:"+a+",b:"+b);
        aa.swap(a, b);
        System.out.println("main中调用swap后a:"+a+",b:"+b);
        
    }

}
class AA {
    public void swap(int a,int b) {
        System.out.println("swap中a:"+a+",b:"+b);
        int tmp = a;
        a = b;
        b = tmp;
        System.out.println("swap中交换后:"+a+",b:"+b);
    }
}

jvm内存图,如下图所示:

vip

运行结果:

2.引用数据类型:传递的是地址

public class Obejct04 {
    public static void main(String[] args) {
        BB bb = new BB();
        int[] arr = {0,2,3};
        bb.AlertArr(arr);
        
        for(int i=0;i<arr.length;i++) {
            System.out.print(arr[i]+" ");
        }
        System.out.println();
    }
}

class BB {
    public void AlertArr(int[] arr) {
        arr[0] = 200;
        
        for(int i = 0;i<arr.length;i++) {
            System.out.print(arr[i]+" ");
        }
        System.out.println();
    }
}

jvm内存如下图所示:

vip

 运行结果:

3.对象传递:与2类似

public class Object05 {
    public static void main(String[] args) {
        Person p = new Person();
        B bb = new B();
        p.name = "jack";
        p.age = 20;
        bb.PersonTest(p);
        System.out.println("Person的age:"+ p.age+",name:"+p.name);
    }

}
class Person {
    String name;
    int age;
}
class B {
    
    public void PersonTest(Person p) {
        p.age = 200;
    }
}

jvm内存图如图所示:

vip

运行结果如下:

 

posted @ 2022-12-08 15:49  zwGitOne  阅读(105)  评论(0编辑  收藏  举报