Today, we go back to the basics and we’re going to understand to a simple but sometimes hard to answer for some developers. Are Java parameters passed by value or by reference ?

Before to answer, it seems important to define what is the difference between these two kinds of methods to pass arguments in methods.

From Wikipedia, we get the following definitions :

1. Pass by Reference

“In call-by-reference evaluation (also referred to as pass-by-reference), a function receives an implicit reference to a variable used as argument, rather than a copy of its value. This typically means that the function can modify (i.e. assign to) the variable used as argument—something that will be seen by its caller.”

2. Pass by Value

“In call-by-value, the argument expression is evaluated, and the resulting value is bound to the corresponding variable in the function […]. If the function or procedure is able to assign values to its parameters, only its local copy is assigned […].”
To better how it works in Java, you can make a simple example. Considering the following object :


private static class MyObject {

  private String str;

  public MyObject(String str) {
    this.str = str;
  }

  public String getStr() {
    return str;
  }

}

Now, we’re going to create a MyObject instance with a defined str value. Then, pass the instance in a method an create a new instance of MyObject and check after the method’s execution what is the value of str field :


public class Main {

  public void testChange(MyObject myObj) {
    myObj = new MyObject("New Value");
  }

  public static void main(String[] args) {
    Main m = new Main();
    MyObject myObj = new MyObject("Old Value");
    m.testChange(myObj);

    if ("Old Value".equals(myObj.getStr())) {
      System.out.println("Passed by value");
    } else {
      System.out.println("Passed by reference");
    }
  }

}

It produces the following result :

Is Java Passed by ref or value
So, you can conclude that Java passes arguments by value to methods. To be more precise, JVM passes objects as references and those references are passed by value. Confusion can come from this.

To keep clear idea about this, nothing’s better than read again JVM Specifications from Oracle here : http://docs.oracle.com/javase/specs/jvms/se8/html/jvms-2.html#jvms-2.4 .