📜  Java是严格按值传递的!

📅  最后修改于: 2022-05-13 01:55:34.883000             🧑  作者: Mango

Java是严格按值传递的!

考虑以下将原始类型传递给函数的Java程序。

public class Main
{
    public static void main(String[] args)
    {
        int x = 5;
        change(x);
        System.out.println(x);
    }
    public static void change(int x)
    {
        x = 10;
    }
}

输出:

5

我们将一个 int 传递给函数“change()”,因此该整数值的变化不会反映在 main 方法中。与 C/C++ 一样, Java创建在方法中传递的变量的副本,然后进行操作。因此,更改不会反映在 main 方法中。

对象或引用如何?

在Java中,所有原语如 int、char 等都类似于 C/C++,但所有非原语(或任何类的对象)始终是引用。所以当我们将对象引用传递给方法时会变得很棘手。 Java创建引用的副本并将其传递给方法,但它们仍然指向相同的内存引用。意味着如果将其他对象设置为在方法内部传递的引用,则来自调用方法的对象及其引用将不受影响。

如果我们更改对象本身以引用其他位置或对象,则更改不会反映回来
如果我们将引用分配给其他位置,则更改不会反映在 main() 中。

// A Java program to show that references are also passed
// by value.
class Test
{
    int x;
    Test(int i) { x = i; }
    Test()      { x = 0; }
}
  
class Main
{
    public static void main(String[] args)
    {
        // t is a reference
        Test t = new Test(5);
  
        // Reference is passed and a copy of reference
        // is created in change()
        change(t);
  
        // Old value of t.x is printed
        System.out.println(t.x);
    }
    public static void change(Test t)
    {
        // We changed reference to refer some other location
        // now any changes made to reference are not reflected
        // back in main
        t = new Test();
  
        t.x = 10;
    }
}

输出:

5

如果我们不分配对新位置或对象的引用,则更改会被反射回来:
如果我们不更改引用以引用其他对象(或内存位置),我们可以对成员进行更改,这些更改会被反射回来。

// A Java program to show that we can change members using using
// reference if we do not change the reference itself.
class Test
{
    int x;
    Test(int i) { x = i; }
    Test()      { x = 0; }
}
  
class Main
{
    public static void main(String[] args)
    {
        // t is a reference
        Test t = new Test(5);
  
        // Reference is passed and a copy of reference
        // is created in change()
        change(t);
  
        // New value of x is printed
        System.out.println(t.x);
    }
  
    // This change() doesn't change the reference, it only
    // changes member of object referred by reference
    public static void change(Test t)
    {
        t.x = 10;
    }
}

输出:

10

练习:预测以下Java程序的输出

//  Test.java
class Main {
   // swap() doesn't swap i and j
   public static void swap(Integer i, Integer j) 
   {
      Integer temp = new Integer(i);
      i = j;
      j = temp;
   }
   public static void main(String[] args) 
   {
      Integer i = new Integer(10);
      Integer j = new Integer(20);
      swap(i, j);
      System.out.println("i = " + i + ", j = " + j);
   }
}