1.基本数据类型int
package test;
public class TestParamter {
/**
* @param args
*/
public static void main(String[] args) {
int x = 1;
System.out.println(x);
testInt(x);
System.out.println(x);
}
public static void testInt(int num){
num = 999;
}
}
输出结果
1
1
因此得出结论:简单数据类型为值传递
又因为对于每个简单数据类型有一个相关的封装类,例如int对应integer类,会产生什么样的结果
2.基本数据类型对应的类Integer
package test;
public class TestParamter {
/**
* @param args
*/
public static void main(String[] args) {
Integer integer = new Integer(111);
System.out.println(integer.intValue());
testInteger(integer);
System.out.println(integer.intValue());
}
public static void testInteger(Integer integer){
integer = new Integer(222);//或者integer +=222;
}
}
输出结果
111
111
结论:此时对象传递为值传递
原因:应该牵扯到int类型与integer类型转换时的拆箱与装箱
3.String类型
package test;
public class TestParamter {
/**
* @param args
*/
public static void main(String[] args) {
String param = "Hello World!";
System.out.println(param);
testString(param);
System.out.println(param);
}
public static void testString(String param){
param = "aaaa";
}
}
运行结果:
Hello World!
Hello World!
结论:String为值传递
4.StringBuffer类型
package test;
public class TestParamter {
/**
* @param args
*/
public static void main(String[] args) {
StringBuffer sb= new StringBuffer("Hello World!");
System.out.println(sb);
testStringBuffer(sb);
System.out.println(sb);
}
public static void testStringBuffer(StringBuffer param){
param.append("aaaaa");
}
}
运行结果:
Hello World!
Hello World!aaaaa
结论:StringBuffer为引用传递
5.类对象
package test;
public class TestParamter {
/**
* @param args
*/
public static void main(String[] args) {
A a = new A();
a.setA("old");
System.out.println(a.getA());
testObj(a);
System.out.println(a.getA());
}
public static void testObj(A a){
a.setA("change");
}
}
class A{
public String a;
public String getA() {
return a;
}
public void setA(String a) {
this.a = a;
}
}
运行结果:
old
change
结论:类对象为引用传递
6.数组int[]
package test;
public class TestParamter {
/**
* @param args
*/
public static void main(String[] args) {
int[] arr = {1,2,3};
System.out.println(arr[0]);
testArray(arr);
System.out.println(arr[0]);
}
public static void testArray(int[] arr){
arr[0] = 999;
}
}
运行结果:
1
999
结论:数组为引用传递