Java 值傳遞和引用傳遞詳解及實例代碼
Java 值傳遞和引用傳遞
前言:
當一個對象被當作參數(shù)傳遞到一個方法后,此方法可改變這個對象的屬性,并可返回變化后的結(jié)果,那么這里到底是值傳遞還是引用傳遞?
答:是值傳遞。Java 編程語言只有值傳遞參數(shù)。當一個對象實例作為一個參數(shù)被傳遞到方法中時,參數(shù)的值就是該對象的引用一個副本。指向同一個對象,對象的內(nèi)容可以在被調(diào)用的方法中改變,但對象的引用(不是引用的副本)是永遠不會改變的。
Java參數(shù),不管是原始類型還是引用類型,傳遞的都是副本(有另外一種說法是傳值,但是說傳副本更好理解吧,傳值通常是相對傳址而言)。
如果參數(shù)類型是原始類型,那么傳過來的就是這個參數(shù)的一個副本,也就是這個原始參數(shù)的值,這個跟之前所談的傳值是一樣的。如果在函數(shù)中改變了副本的 值不會改變原始的值.
如果參數(shù)類型是引用類型,那么傳過來的就是這個引用參數(shù)的副本,這個副本存放的是參數(shù)的地址。如果在函數(shù)中沒有改變這個副本的地址,而是改變了地址中的 值,那么在函數(shù)內(nèi)的改變會影響到傳入的參數(shù)。如果在函數(shù)中改變了副本的地址,如new一個,那么副本就指向了一個新的地址,此時傳入的參數(shù)還是指向原來的 地址,所以不會改變參數(shù)的值。
實例代碼:
public class ParamTest { public static void main(String[] args){ /** * Test 1: Methods can't modify numeric parameters */ System.out.println("Testing tripleValue:"); double percent = 10; System.out.println("Before: percent=" + percent); tripleValue(percent); System.out.println("After: percent=" + percent); /** * Test 2: Methods can change the state of object parameters */ System.out.println("\nTesting tripleSalary:"); Employee harry = new Employee("Harry", 50000); System.out.println("Before: salary=" + harry.getSalary()); tripleSalary(harry); System.out.println("After: salary=" + harry.getSalary()); /** * Test 3: Methods can't attach new objects to object parameters */ System.out.println("\nTesting swap:"); Employee a = new Employee("Alice", 70000); Employee b = new Employee("Bob", 60000); System.out.println("Before: a=" + a.getName()); System.out.println("Before: b=" + b.getName()); swap(a, b); System.out.println("After: a=" + a.getName()); System.out.println("After: b=" + b.getName()); } private static void swap(Employee x, Employee y) { Employee temp = x; x=y; y=temp; System.out.println("End of method: x=" + x.getName()); System.out.println("End of method: y=" + y.getName()); } private static void tripleSalary(Employee x) { x.raiseSalary(200); System.out.println("End of method: salary=" + x.getSalary()); } private static void tripleValue(double x) { x=3*x; System.out.println("End of Method X= "+x); } }
顯示結(jié)果:
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
感謝 閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關(guān)文章
Java Chassis3過載狀態(tài)下的快速失敗解決分析
本文解密了Java Chassis 3快速失敗相關(guān)的機制和背后故事,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2024-01-01mybatis 中 foreach collection的用法小結(jié)(三種)
這篇文章主要介紹了mybatis 中 foreach collection的用法小結(jié)(三種),需要的朋友可以參考下2017-10-10Java并發(fā)編程之詳解ConcurrentHashMap類
在之前的文章中已經(jīng)為大家介紹了java并發(fā)編程的工具:BlockingQueue接口、ArrayBlockingQueue、DelayQueue、LinkedBlockingQueue、PriorityBlockingQueue、SynchronousQueue、BlockingDeque接口,本文為系列文章第八篇.需要的朋友可以參考下2021-06-06