import java.util.Scanner; //值传递 (传递的是值的拷贝,也就是说传递后就互不相关了。) public class Main { void test1(int a) { a = 4; System.out.println("test1 a:" + a); } public static void main(String[] args) { Main ma = new Main(); int a = 2; ma.test1(a); System.out.println("main a: " + a); } } test1 a:4 main a: 2
void dfs(int num) { if (num == 0) return; num--; System.out.println(num); dfs(num); } public static void main(String[] args) { Main ma = new Main(); ma.dfs(3); }
2
1
0
import java.util.Scanner; //引用传递 (传递的引用的地址,也就是变量所对应的内存空间的地址。) //传递前和传递后都指向同一个引用(也就是同一个内存空间)。 class A { public int age = 0; } public class Main { void test1(A a) { a.age = 20; System.out.println("test1 age:" + a.age); } public static void main(String[] args) { Main ma = new Main(); A a = new A(); a.age = 10; ma.test1(a); System.out.println("main age: " + a.age); } } test1 age:20 main age: 20
import java.util.Scanner; class A { public int age = 0; } public class Main { void test1(A a) { a = new A(); a.age = 20; System.out.println("test1 age:" + a.age); } public static void main(String[] args) { Main ma = new Main(); A a = new A(); a.age = 10; ma.test1(a); System.out.println("main age: " + a.age); } } test1 age:20 main age: 10
内存分配示意图
test1 age:20
main age: 10
(1):“在Java里面参数传递都是按值传递”这句话的意思是:按值传递是传递的值的拷贝,按引用传递其实传递的是引用的地址值,所以统称按值传递。
(2):在Java里面只有基本类型和按照下面这种定义方式的String是按值传递,其它的都是按引用传递。就是直接使用双引号定义字符串方式:String str = “Java私塾”;
参考链接 :https://blog.csdn.net/p4885056000/article/details/79105922