心态
学习技术一定要一个知识点学的明明白白的,切勿浮躁--2017年3月20日
传值–基本类型变量
- 基本类型变量(int,long,double,float,byte,boolean,char)传其值的拷贝。
- 例子:最基础的
public class valueText {
public static void main(String[] args) {
int a=5;
int b=10;
System.out.println("a"+a+","+"b"+b); //a==5,b==10
send(a,b);
System.out.println("a"+a+","+"b"+b); // a==5,b==10
}
private static void send(int a,int b) {
System.out.println("a的值为:"+a+",b的值为"+b);// a==5,b==10
a=b;
b=b+a;
System.out.println("a值为"+a+"b值为"+b); // a==10,b==20
}
}
不难看出,虽然在send方法中传进来的值发生改变,但是对main方法中的a,b没有受到影响。综上:以参数形式传递简单类型的变量的时候,实际上是将参数的值copy一份副本传进方法中,不管在方法中如何改变其值,结果只是改变了副本的值,而不影响源值
传值–对象的引用
- 传引用的副本–这里特别注意string也是属于对象的引用。
- 实例
public class StringTest {
public static void test(StringBuffer string){
string.append(",world");
}
public static void main(String[] args) {
StringBuffer string=new StringBuffer("hello");
test(string);
System.out.println(string); //hello,world
}
}
总结:在调用test方法的时候,参数string其实是个引用的copy副本,它指向new StringBuffer(“hello”)这个对象。在test方法中修改内容,这就好比一个仓库要取货赠货,你有一把钥匙,别人拿着你钥匙复制了一把,他拿着复制的钥匙对仓库进行取货增货,你当然可以拿着你钥匙打开仓库.
- 实例
public class ObjectText {
private int a=7;
public static void main(String[] args) {
ObjectText obt=new ObjectText();
System.out.println(obt.a); // 7
ObjectText obt1=new ObjectText();
obt1.a=8;
System.out.println(obt1.a); // 8
ObjectText obt2=obt;
System.out.println(obt2.a); //7
obt2.a=10;
System.out.println(obt2.a);//10
System.out.println(obt.a);//10
}
}
}
总结:每次new ObjectText().a是恒等于7的。其实在内存栈中只有两个对象,obt2指向obt所指向的对象,在obt2.a=10的时候,其实是改变obt所指向对象的变量。
一个面试题
public class test03 {
public static void main(String[] args) {
test03 t=new test03();
t.first();
}
public void first(){
int i=5; // i=5;
Value v=new Value();
v.i=25;
Second(v,i);
System.out.println(v.i);
}
public void Second(Value v,int i){
i=0;
v.i=20;
Value val=new Value();
v=val;
System.out.println(v.i+""+i);
}
}
总结:输出结果:15,0,20