value passing and reference passing
Recently learned the basis of time, the teacher told the value of the delivery and reference to pass, the problem has been not quite clear, the Internet to check a lot of information, according to their own understanding of the collation, found that before the place is not too clear to basically want to understand, if there is not the right place, welcome to correct, thank you.
The first thing to note is that there is no pointer in Java, there is only value passing in Java, there is only value passing!!! However, we often see that the passing of objects (arrays, classes, interfaces) seems a bit like reference passing, which can change the value of an attribute in an object. But don't be fooled by this illusion, the value of the incoming function is actually a copy of the object reference, that is, the value of the referenced address is passed, so it is passed by value .
Value passing
Example:
Public class TEST3 { publicstaticvoid change (int a) { a=50; } Public Static void Main (string[] args) { int a=10; System.out.println (a); Change (a); System.out.println (a); }}
It is clear that the output is 10, 10. It's worth a copy, and the copy doesn't have anything to do with the original value.
Memory Analysis:
Reference Delivery
Example:
Public class TEST3 { publicstaticvoid change (int []a) { a[0]=50 ; } Public Static void Main (string[] args) { int []a={10,20}; System.out.println (a[0]); Change (a); System.out.println (a[0]);} }
The output result is obviously 10 50. The value of the referenced address is actually passed.
Memory Analysis:
Example:
classEMP { Public intAge ;} Public classTest { Public Static voidChange (emp emp) {emp.age= 50; EMP=NewEMP ();//create an object againemp.age=100; } Public Static voidMain (string[] args) {emp emp=NewEmp (); Emp.age= 100; System.out.println (Emp.age); Change (EMP); System.out.println (Emp.age); System.out.println (Emp.age); }}
The output is: 100 50 50.
Memory Analysis:
For the String class:
Public class Test { publicstaticvoid change (String s) { s= "Zhangsan"; } Public Static void Main (string[] args) { string s=new String ("Lisi"); System.out.println (s); Change (s); System.out.println (s); }}
The output is: Lisi Lisi, because the string class is final decorated and immutable, it opens up a new space in memory.
Note: If there is an incorrect place, please correct me.
Value passing and reference passing issues in Java