packagecom.yinyong;/**
* Time : 2023/3/18 20:04
* Author : 王摇摆
* FileName: ValueTrans.java
* Software: IntelliJ IDEA 2020.2.2
* Blog :https://blog.csdn.net/weixin_44943389?type=blog
*//**
* 本实例学习java中的经典值传递的思想
* 实验:交换两个数值
*/publicclassValueTrans{publicstaticvoidmain(String[] args){int a =10;int b =20;swap(a, b);System.out.println("the output of main function");System.out.println("The value of a is "+ a);System.out.println("The value of b is "+ b);}publicstaticvoidswap(int a,int b){int temp;
temp = a;
a = b;
b = temp;System.out.println("the output of swap function");System.out.println("The value of a is "+ a);System.out.println("The value of b is "+ b);}}
实验2:Java中的值传递(引用类型,传递对象引用)
packagecom.yinyong;/**
* Time : 2023/3/18 20:04
* Author : 王摇摆
* FileName: RefTrans.java
* Software: IntelliJ IDEA 2020.2.2
* Blog :https://blog.csdn.net/weixin_44943389?type=blog
*/importjavafx.scene.input.TouchEvent;/**
* 本实例实现引用传递交换两个值
* 使用类对象引用
*/publicclassRefTrans{publicstaticvoidmain(String[] args){Student s1 =newStudent("张三",23);Student s2 =newStudent("李四",24);// swap(s1, s2);//成功交换,Java中的是值传递,传递的是对象引用的副本,但是程序要写好这个东西swap1(s1,s2);//交换失败,记住,Java中只有值传递,传递的是对象引用的副本,所以形参的改变并不会影响实参System.out.println("The result of main function is :");System.out.println(s1.toString());System.out.println(s2.toString());}privatestaticvoidswap(Student a,Student b){Student temp =newStudent();
temp.age = a.age;
temp.name = a.name;
a.name = b.name;
a.age = b.age;
b.name = temp.name;
b.age = temp.age;System.out.println("The result of swap function is :");System.out.println(a.toString());System.out.println(b.toString());}privatestaticvoidswap1(Student a,Student b){Student temp =newStudent();
temp = a;
a = b;
b = temp;System.out.println("The result of swap1 function is :");System.out.println(a.toString());System.out.println(b.toString());}}classStudent{String name;int age;publicStudent(String name,int age){this.name = name;this.age = age;}publicStudent(){}@OverridepublicStringtoString(){return"Student{"+"name='"+ name +'\''+", age="+ age +'}';}}