Sobes.tech
Middle

How are parameters passed to methods in Java — by reference or by value?

sobes.tech AI

Answer from AI

In Java, method parameters are passed by value only. This means that when a method is called, the value of the argument is copied and passed to the parameter.

  • For primitive types (int, double, etc.), the actual value is copied.
  • For reference types (objects), the value of the reference (the address of the object in memory) is copied.

Because of this, inside the method, you can change the state of the object that the parameter refers to, but you cannot change the reference itself to point to a different object outside the method.

Example:

void modify(StringBuilder sb) {
    sb.append(" world"); // modifies the object
    sb = new StringBuilder("new"); // modifies the local copy of the reference
}

StringBuilder s = new StringBuilder("hello");
modify(s);
System.out.println(s); // will output "hello world"

Here, the method changed the content of the object, but did not change the reference s outside the method.

How are parameters passed to methods in Java — by… - sobes.tech