1.重要声明:不管是传值还是传引用,都是将原来的值或引用复制一份传过去的,也就是说,传进函数里的是复制的值或者引用,下面将复制称为副本。
2.对于基本类型变量(int,long,double,float,byte,boolean,char),java是传 值的副本,
值的副本改变了,对值没有影响。
public
class
test{
public
static
void
test(
boolean
test
){//test的副本
test
=!
test
;
System.
out
.println(
test
);
}
public
static
void
main(String[]
args
){
boolean
test
=
true
;
System.
out
.println(
test
);//原test
test(
test
);//test将它的副本传到了test()
System.
out
.println(
test
);//原test
}
}
//输出结果:
true
false
true
对于一切的对象变量,java传 引用的副本(A a=new A(),a就是A的引用),引用指向的是对象的地址,把对象的地址比作仓库,引用就是仓库的钥匙,引用的副本就相当于复制的一把仓库的钥匙。
仓库只有一个,引用的副本打开了仓库拿走了东西,引用打开仓库就会发现东西被拿走了。
public
class
test{
public
static
void
test(StringBuffer
str
){
str
.append(
",World!"
);//引用的副本改变了仓库,仓库就变了
}
public
static
void
main(String[]
args
){
StringBuffer
string
=
new
StringBuffer(
"Hello"
);
test(
string
);
System.
out
.println(
string
);
}
}
//输出结果:
Hello,World!
特例:String
public
class
test{
public
static
void
test(String
str
){
str
=
"World"
;
//这句话实际上是:String str=new String("World");此时str已经指向了别的对象地址,它这把钥匙已经被改造去开别的仓库了。
}
public
static
void
main(String[]
args
){
String
string
=
"Hello"
;
test(
string
);
System.
out
.println(
string
);//所以原来的仓库并没有变。
}
}
//输出结果:
Hello