This is a classic interview question, it confuses Java novice. In this article, I'll use an example and some diagrams to prove that Java is passed by value.
Definition:
-Pass by value: Make a copy of the actual parameter value in memory to pass.
-Pass Reference: a copy of the address that passes the actual parameter.
Java is always a value pass. Both the original data type and the object reference are just values.
Pass the original type variable:
swap(Type arg1, Type arg2) { Type temp = arg1; arg1 = arg2; arg2 = temp;}
Passing objects:
Java refers to manipulating objects by reference, and all object variables are references. However, Java does not pass a parameter value by reference, but instead passes it by value.
The question is: why can the member values of an object be modified?
Code:
class Apple {public String color= "red" ;} public class main { Span class= "Hljs-keyword" >public static void main (string[] args) {Apple Apple = new A Pple (); System.out.println (Apple.color); Changeapple (Apple); System.out.println (Apple.color); } public static void changeapple (Apple apple) {Apple.color = "Gree n "; }}
Because the original and copied references point to the same object, the value of the member variable can be modified.
Results:
redgreen
http://www.programcreek.com/2011/08/so-java-passes-object-by-reference-or-by-value/
Java to pass a value or to pass a reference