摘自http://blog.csdn.net/zhaoyue007101/article/details/7870560
(一)基本数据类型:传值,方法不会改变实参的值。
如int,string
(二)对象类型参数:传引用,<"方法体内改变形参引用,不会改变实参的引用">,<"但有可能改变实参对象的属性值">
String[]数组
(1)方法体内改变形参引用,但不会改变实参引用 ,实参值不变。
(2)方法体内,通过引用改变了实际参数对象的内容,注意是“内容”,引用还是不变的。
package com.fortest.code;
public class ParameterTest {
static void forChange(String a, String b){
a = a+","+b;
b = a ;
}
static void forChange(String[] a){
String tmp = a[0];
a[0] = a[1];
a[1] = tmp;
}
static void forChange(Person p){
p.age = p.age+10;
}
static void forChangePoint(Person p){
p = new Person(50);
}
public static void main(String[] args){
String a = "a";
String b = "b";
System.out.println("before change, a="+a+",b="+b);
forChange(a, b);
System.out.println("after change, a="+a+",b="+b+"\n");
String[] c = {"m","n"};
System.out.println("before change, c[0]="+c[0]+",c[1]="+c[1]);
forChange(c);
System.out.println("after change, c[0]="+c[0]+",c[1]="+c[1]+"\n");
Person p = new Person(20);
System.out.println("before change, p.age="+p.age);
forChange(p);
System.out.println("after change, p.age="+p.age);
forChangePoint(p);
System.out.println("after change point, p.age="+p.age);
}
static class Person{
public int age;
public Person(){
}
public Person(int age){
this.age = age;
}
}
}
输出结果
before change, a=a,b=b
after change, a=a,b=b
before change, c[0]=m,c[1]=n
after change, c[0]=n,c[1]=m
before change, p.age=20
after change, p.age=30
after change point, p.age=30