1. Saving in memory for basic types and reference types
(1) The basic type of the variable holds the original value , that is, the value it represents is the value itself;
The base type allocates space for a variable when it is declared;
The basic type is passed as a value during parameter passing, that is, copying a copy of the data into the parameter.
(2) A variable of the reference type holds the reference value ;
("reference value" points to the address of a memory space, which represents a reference to an object, not the object itself, where the object itself resides at the address represented by the reference value.) )
The reference type passes through the data reference during parameter passing, that is, the memory address passed in.
2. Reference passing and value passing
(1) Value transfer:
When a method is called, the actual parameter passes its value to the corresponding formal parameter, and the function receives a copy of the original value, at which time there are two equal basic types in memory, that is, the actual and formal parameters, the latter method
all of the actions in this form are value, without affecting the value of the actual parameter.
(2) Reference passing:
Also known as a pass-through address. When a method is called, the actual argument's reference (the address, not the value of the parameter) is passed to the corresponding formal parameter in the method, and the function receives the memory address of the original value;
In the execution of the method, the parameters and the arguments are the same, pointing to the same memory address, and the operation of the reference in the method execution will affect the actual object.
1 Public classTest {2 Public Static voidMain (string[] args) {3Test T =NewTest ();4 intScore = 59;//the arguments passed here score are passed by value.5 6Numbertest NT =Newnumbertest ();7Nt.num = 59;//the parameter num passed here is the reference pass8 9 T.addnum (score);TenSystem.out.println ("3:" +score); One A T.addnum (NT); -System.out.println ("4:" +nt.num); - the - } - - Public voidAddnum (intscore) { +score++;//1:60 - //score=score++; //1:59 + //score=score+1; ASystem.out.println ("1:" +score); at } - - Public voidAddnum (numbertest nt) { -nt.num++; -System.out.println ("2:" +nt.num); - } in - } to + - the Public classNumbertest { * $ Public intnum;Panax Notoginseng -}
Operation Result:
1:60
3:59
2:60
4:60
The result of this code run is one of the best examples;
There may be more influencing factors in the delivery, which will be discovered as the depth of study progresses.
java--value passing and reference passing