java 值传递和引用传递。
2016-05-10 18:50
399 查看
java不同于C++,没有灵活但是复杂的指针。
显示结果:
转载自http://www.cnblogs.com/clara/archive/2011/09/17/2179493.html
不管是原始类型还是引用类型,传递的都是副本(有另外一种说法是传值,但是说传副本更好理解吧,传值通常是相对传址而言)。 如果参数类型是原始类型,那么传过来的就是这个参数的一个副本,也就是这个原始参数的值,这个跟之前所谈的传值是一样的。如果在函数中改变了副本的值不会改变原始的值. 如果参数类型是引用类型(java中非原始数据都需要使用new操作创建对象的引用),那么传过来的就是这个引用参数的副本,这个副本存放的是参数的地址。如果在函数中没有改变这个副本的地址,而是改变了地址中的 值,那么在函数内的改变会影响到传入的参数。如果在函数中改变了副本的地址,如new一个,那么副本就指向了一个新的地址,此时传入的参数还是指向原来的地址,所以不会改变参数的值。
1 public class ParamTest { 2 public static void main(String[] args){ 3 /** 4 * Test 1: Methods can't modify numeric parameters 5 */ 6 System.out.println("Testing tripleValue:"); 7 double percent = 10; 8 System.out.println("Before: percent=" + percent); 9 tripleValue(percent); 10 System.out.println("After: percent=" + percent); 11 12 /** 13 * Test 2: Methods can change the state of object parameters 14 */ 15 System.out.println("\nTesting tripleSalary:"); 16 Employee harry = new Employee("Harry", 50000); 17 System.out.println("Before: salary=" + harry.getSalary()); 18 tripleSalary(harry); 19 System.out.println("After: salary=" + harry.getSalary()); 20 21 /** 22 * Test 3: Methods can't attach new objects to object parameters 23 */ 24 System.out.println("\nTesting swap:"); 25 Employee a = new Employee("Alice", 70000); 26 Employee b = new Employee("Bob", 60000); 27 System.out.println("Before: a=" + a.getName()); 28 System.out.println("Before: b=" + b.getName()); 29 swap(a, b); 30 System.out.println("After: a=" + a.getName()); 31 System.out.println("After: b=" + b.getName()); 32 } 33 34 private static void swap(Employee x, Employee y) { 35 Employee temp = x; 36 x=y; 37 y=temp; 38 System.out.println("End of method: x=" + x.getName()); 39 System.out.println("End of method: y=" + y.getName()); 40 } 41 42 private static void tripleSalary(Employee x) { 43 x.raiseSalary(200); 44 System.out.println("End of method: salary=" + x.getSalary()); 45 } 46 47 private static void tripleValue(double x) { 48 x=3*x; 49 System.out.println("End of Method X= "+x); 50 } 51 }
显示结果:
Testing tripleValue: Before: percent=10.0 End of Method X= 30.0 After: percent=10.0 Testing tripleSalary: Before: salary=50000.0 End of method: salary=150000.0 After: salary=150000.0 Testing swap: Before: a=Alice Before: b=Bob End of method: x=Bob //可见引用的副本进行了交换 End of method: y=Alice After: a=Alice //引用本身没有交换 After: b=Bob
转载自http://www.cnblogs.com/clara/archive/2011/09/17/2179493.html
相关文章推荐
- java对世界各个时区(TimeZone)的通用转换处理方法(转载)
- java-注解annotation
- java-模拟tomcat服务器
- java-用HttpURLConnection发送Http请求.
- java-WEB中的监听器Lisener
- Android IPC进程间通讯机制
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- 介绍一款信息管理系统的开源框架---jeecg
- 聚类算法之kmeans算法java版本
- java实现 PageRank算法
- PropertyChangeListener简单理解
- c++11 + SDL2 + ffmpeg +OpenAL + java = Android播放器
- 插入排序
- 冒泡排序
- 堆排序
- 快速排序
- 二叉查找树