• 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是传引用的副本。

  • 相关阅读:
    CTK 编译
    MITK 2021.2编译
    执行git add .报错LF will be replaced by CRLF in
    vscode标记“&&”不是此版本中的有效语句分隔符
    vscode prettier插件使用无效
    vscode使用技巧
    kafka及hdfs常用命令
    博客已迁移
    SVM
    逻辑回归
  • 原文地址:https://www.cnblogs.com/xingrui/p/9576820.html
Copyright © 2020-2023  润新知