java的传递与引用

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

     
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值