JAVA — Pass by Value

Anna Scott
4 min readOct 22, 2021

Java is a strictly pass by value language. What do we mean when we say that? We are talking about of how we are passing parameters to our methods. “Pass by value” means that the copy of parameters is passed into the method, and method does not affect the original parameters.

Please take a look at the following program:

public class Primitives {
static int x = 1, z;

public static void main(String... input) {
int y = 2;
changeZ(x,y,z);
System.out.println("x outside method" + x);
System.out.println("y outside method" + y);
System.out.println("z outside method: " + z);
}

static void changeZ(int x, int y, int z) {
x = 3;
y = 4;
z = x + y;
System.out.println("x inside method" + x);
System.out.println("y inside method" + y);
System.out.println("z inside method: " + z);
}
}

Its output is:

x inside method3
y inside method4
z inside method: 7
x outside method1
y outside method2
z outside method: 0

Our three variables x, y, and z are of type int, which is primitive type, their values are stored directly in stack memory.

After we call method changeZ(), copy of each of the variable created and put on stack in a different location:

Method changeZ only operates only on copies and does not affect the original values:

When we work with objects, object references are passed by value. Take a look at the following program:

public class NonPrimitives {
public static void main(String... input) {
Person person = new Person("Anna");
System.out.println("name of person " + person.name);
changeName(person);
System.out.println("name of person " + person.name);
}
static void changeName(Person somePerson) {
somePerson.name = "Wayne";
}
}

class Person{
String name;
Person (String name) {
this.name = name;
}
}

It produces the following result:

name of person Anna
name of person Wayne

Java object is stored on the heap, while its reference is stored on the heap:

The copy of the reference is created and placed on stack, when we pass object’s reference to changeMethod. It is still pointing to the same object:

Method changeName changes our original object:

Lets look at the JAVA String class:

public class StringPassByValue {
public static void main(String... input) {

String name = "Anna";
System.out.println("name before - " + name);
changeName(name);
System.out.println("name after - " + name);
}

static void changeName(String someName) {
someName = "Wayne";
}
}

String objects are immutable. The line:

someName = "wayne";

is equivalent to:

someName = new String("wayne");

The original reference “name” is still pointing to “Anna”:

In JAVA parameter passing is always pass by value. For primitives — parameter pass by value. For objects — reference pass by value.

Happy coding my friends!

All the code can be found here:

--

--