Is java pass by reference or pass by value?

Java 8Object Oriented ProgrammingProgramming

Call by Value means calling a method with a parameter as value. Through this, the argument value is passed to the parameter.

While Call by Reference means calling a method with a parameter as reference. Through this, the argument reference is passed to the parameter.

In call by value, the modification done to the parameter passed does not reflect in the caller's scope while in call by reference, the the modification done to the parameter passed are persistent and changes are reflected in the caller's scope.

But Java uses only call by value. It creates a copy of references and pass them as value to the methods. If reference contains objects, then the value of object can be modified in the method but not the entire object. See the example −

Example

public class Tester {
   public static void main(String[] args) {
      Point point = new Point();
      System.out.println("X: " +point.x + ", Y: " + point.y);
      updatePoint(point);
      System.out.println("X: " +point.x + ", Y: " + point.y);
   }
   public static void updatePoint(Point point) {
      point.x = 100;
      point.y = 100;
   }
}
class Point {
   public int x, y;
}

Output

X: 0, Y: 0
X: 100, Y: 100
raja
Published on 06-Feb-2018 12:27:35
Advertisements