Java Tutorial Java Advanced Java References

Java Methods - Strictly Pass By Value



When the argument or parameter of a function is passed by value, then the function takes only the value of parameter and any changes made to the parameter inside the function have no effect on the parameter. Java is strictly pass by value language which means that code within a function will not change the parameter used to pass in the function.

Example:

In the example below, the function called Square is created which returns square of the passed argument. The function modify the parameter as square of itself before returning it. In the main() method, when the passed argument is printed after calling the function Square, the value of the parameter remains unaffected because Java is a pass by value language.

public class MyClass {
  static int Square(int x) {
    x = x*x;
    return x;
  }

  public static void main(String[] args) {
    int x = 5;
    System.out.println("Initial value of x is "+ x);
    Square(x);
    System.out.println("Value of x after passed by value is "+ x); 
  }
}

The output of the above code will be:

Initial value of x is 5.
Value of x after passed by value is 5.

❮ Java - Methods