java中传值与传引用

  1、一句话出自:think in Java,"When you're passing primitives into a method, you get a distinct copy of the primitive.

When you're passing a reference into a method, you get a copy of the reference.(如果java是传值,则传递的是值得副本;

如果java是传引用,则传递的是引用的副本。)

  2、对基本数据类型而言,就是把自己复制一份传递,即使副本变了,自己也不变。而对对象类型而言,它传的是引用

的副本。为什么不直接传对象?浪费内存且速度慢。

下面看个例子:

1、传值

 1 public class Test{
 2         public static void test(boolean test){
 3               tets = !test;
 4               system.out.println("In test (boolean) : test=" + test);
 5         }
 6          public static void main(String[] args){
 7                boolean test = true;
 8                system.out.println("before test(boolean) : test=" +test)
 9                test(test);
10                system.out.println("after test(boolean) : test=" +test)
11          }
12 }       
    运行结果:
         before test(boolean) : test=true
         In test (boolean) : test=false
before test(boolean) : test=true

2、传引用

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

另一种情况

public class Test{
         public static void test(String str){
                  str = "World";
         }  
         public static void main(String[] args){
                  String string = "Hello";
                  test(string);
                  system.out.println(string);
         }
}  
运行结果:
      Hello
原因:String类是final的,
str = "World";隐含重新生成一个对象。
 

总结:对于基本数据类型,java是传值的副本;对于一切对象型变量,java是传引用的副本。

猜你喜欢

转载自www.cnblogs.com/xingrui/p/9576820.html