In Java, value passing and reference passing have been difficult to distinguish, and I'll take a few examples to distinguish what time is a value pass and what time is a reference pass
1: First of all say value delivery: the basic type (int, float, long,byte,short, double, Char,boolean) as a parameter pass, is a copy of the value, no matter how you change the copy, the original value will not change
Package com.test.list;
public class Test1 {public
static void Main (string[] args) {
int i = ten;
System.out.println ("Before Change" +i);
Change (i);
System.out.println ("After Change" +i);
}
public static void Change (int i) {
i=11
}
}
Output as: 10
2: The string type is also treated as a basic type in the pass process
This is because str = "PPP" is equivalent to the new String ("PPP");
public class Test2 {public
static void Main (string[] args) {
String str = "abc";
System.out.println ("Before Change" +str);
Change (str);
System.out.println ("After change" + str);
}
public static void Change (String str) {
str = ' PPP ';
}
}
Output is: ABC
3: The reference passing process is equivalent to copying the object's address in memory and passing it to the parameter
public class Test3 {public
static void Main (string[] args) {
StringBuffer sb = new StringBuffer ("abc");
System.out.println ("Before change" + SB);
Change (SB);
System.out.println ("After change" + SB);
}
public static void Change (StringBuffer str) {
str.append ("PPP");//Copy the object's address in memory and pass it to the parameter
}
}
See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/Java/
Output is: ABCPPP
Again for example:
public class Test5 {public
static void Main (string[] args) {
list<string> List = new Arraylist<string> ;();
List.add ("ABCD");
System.out.println ("Before Change" +list);
Change (list);
System.out.println ("After Change" +list);
}
public static void Change (List<string> List) {
list.add ("PPP");
}
The output is: ABCDPPP as shown in the following figure:
public class Test4 {public
static void Main (string[] args) {
StringBuffer sb = new StringBuffer ("abc");
System.out.println ("Before change" + SB);
Change (SB);
System.out.println ("After change" + SB);
}
public static void Change (StringBuffer str) {
str = new StringBuffer ();//This changes the reference and points to another address, so the output is
still unchanged. Str.append ("PPP");
}
The output is: ABC because it points to another memory space