In Java, programmers are not allowed to choose value passing or address passing each parameter, and the base type is always passed by value. For an object, a reference to an object, that is, a copy, is passed to the method, in which only the object is modified to affect the value of the object, and the object is not affected by the reference of the manipulation object.
Now say the array: If you pass an element of an array of a single primitive type to a method and modify it in a method, then when the called method finishes executing, the element is not stored in the modified value, because the element is passed by value, and if the reference to the array is passed, subsequent modifications to the arrays of elements can reflected in the original array (because the array itself is an object, int[] A = new int[2];, the int in this is the type of the array element, and the modification of the array element is the manipulation object).
public class test{ string str = new String ("good"); char[] ch = {' A ', ' B ', ' C '}; int i = ten; public void Change (String str,char[] ch,int i) { str = "Test OK"; Ch[0] = ' g '; i++; } public static void Main (string[] args) { Test TT = new Test (); Tt.change (TT.STR,TT.CH,TT.I); System.out.println (TT.I); System.out.print (tt.str+ "and"); System.out.println (tt.ch); }
TR is a reference to a string type, I is a basic type variable, CH is an array name and is also a reference to an array object
In the Chang () method, str= "Test OK" is a new object that places the first address on the reference variable str;
and ch[0]= ' G ', because the reference to the array, and at this time ch[0]= ' G ', is an array of elements of the operation, can modify the contents of the source arrays;
I is the integer value, just copy the value to a method, the change in the method is not changing the source I.
So the result is:
10
Good and GBC
public class test{ string str = new String ("good"); char[] ch = {' A ', ' B ', ' C '}; int i = ten; public void Change (String str,char ch,int i) { str = "Test OK"; ch = ' g '; this.i = i+1; } public static void Main (string[] args) { Test TT = new Test (); Tt.change (TT.STR,TT.CH[0],TT.I); System.out.println (TT.I); System.out.print (tt.str+ "and"); System.out.println (tt.ch); } }
Look closely at the arguments and the changes in the parameters?
In the Change () method, the char[] ch becomes--------------Char ch;
This time pass is a char value of a single array element, according to the above parsing, at this time ch= ' 9 ', is not affecting the source array elements.
THIS.I = i+1; the left side of the equals sign is the attribute I, the I to the right of the equal sign is the local variable (i in the argument);
At this time i+1 to assign to the property of I, will naturally change the value of the attribute I, at the same time, 17 rows, TT.I is called the attribute I, this time the result is:
11
Good and ABC
http://blog.csdn.net/niuniu20008/article/details/2953785
Java value passing array passing