Is Java "pass-by-reference" or "pass-by-value"?

In Java, arguments are passed to methods by value. This means that when you pass an argument to a method, the method receives a copy of the argument rather than a reference to the original object.

For example, consider the following code:

public class Main {
   public static void main(String[] args) {
      int x = 10;
      foo(x);
      System.out.println(x);  // Outputs 10
   }
   
   public static void foo(int y) {
      y = 20;
   }
}

In this code, the foo method is called with the argument x, which has a value of 10. Inside the foo method, the value of y is changed to 20. However, this change does not affect the value of x in the main method, because y is just a copy of x and the main method and the foo method operate on separate copies of the data.

It's worth noting that while Java uses pass-by-value for primitive types like int and double, it uses pass-by-reference for objects. This means that when you pass an object to a method, the method receives a reference to the object, not a copy of the object. However, the reference itself is passed by value.

For example:

public class Main {
   public static void main(String[] args) {
      MyObject obj = new MyObject();
      obj.x = 10;
      foo(obj);
      System.out.println(obj.x);  // Outputs 20
   }
   
   public static void foo(MyObject y) {
      y.x = 20;
   }
}

class MyObject {
   int x;
}

In this code, the foo method is called with the argument obj, which is an instance of the MyObject class. Inside the foo method, the value of y.x is changed to 20. This change is reflected in the main method, because y is a reference to the same object as obj, and both references point to the same object in memory. However, the reference itself is passed by value, so the main method and the foo method do not share the same reference.