The problem of passing and referencing in Java functions has always been a "scary" problem, in fact, the parameters in Java functions are passed values, the difference is that the basic data type is passed a copy of the parameter, for the class type is passed the reference copy of the class parameter, when modifying the parameter value in the function body, Whether a parameter of a primitive type or a parameter of a reference type modifies only the copy of the parameter, does not affect the value of the function argument, and if the member value of the reference type is modified, the member value referenced by that argument can be changed, as in the example below.
The first is to define the change parameters
Public Static voidChangeint (inti) {//function to change int type variablei = 100; } Public Static voidChangestring (String s) {//functions that change string variabless = "Changestring"; } Public Static voidChangemodel (model model) {//function to change the model type variableModel =NewModel (); Model.i= 1; Model.s= "Changemodel"; } Public Static voidCHANGEMODEL2 (model model) {//functions that change the members of a model variableModel.i = 1; Model.s= "Changemodel"; } //class Model classModel { Public inti = 0; PublicString s = "No value"; } //Test Program Public Static voidMain (string[] args) {inti = 0; String s= "Hello"; Model Model=NewModel (); Model Model2=NewModel (); Changeint (i); System.out.println ("I=" +i); Changestring (s); System.out.println ("S=" +s); Changemodel (model); System.out.println ("Model:" +model.s); ChangeModel2 (MODEL2); System.out.println ("Model2:" +model2.s); }
Test Result: i=0 S=hello model:no value Model2:changemodel can see that I has not changed, S has not changed, mode has not changed, Model2 s changed. Summary: The formal parameter in Java is a copy of the copied argument (the copy of the reference is copied) (the copy referenced in the stack), so changing the parameter in the function cannot change the value of the argument, and changing the reference simply points the reference to the other new object, and the reference to the argument also points to the original object. Changing the members of a parameter reference will of course affect the value of the argument reference member, because their references point to the same object. Original address: http://blog.sina.com.cn/s/blog_5198c7370100dut4.html
Passing values and references in Java