Java: Variables are Always Passed by Copy

March 14, 2015

I am learning Java. One of the important concepts to understand is whether arguments of a function is passing by copy or reference. Passing by copy means when a variable is passed to a function, a copy is made. Passing by reference means when a variable is passed to a function, the code in the function operates on the original variable.

In Java, variables are always passed by copy. Here are three scenarios:

Case 1: Passing Primitives

void incrementValue(int inFunction){ inFunction ++; System.out.printIn(“In function: ” + inFunction); }

int original = 10; System.out.printIn(“Original before: ” + original); incrementValue(original); System.out.printIn(“Original after: ” + original);

And the result is:

Original before: 10 In Function: 11 Original after: 10

The original value didn’t change.

Case 2: Passing primitives wrapped in objects

void incrementValue(int[] inFunction){ inFunction[0] ++; System.out.printIn(“In function: ” + inFunction[0]); }

int[] arOriginal = {10, 20, 30}; System.out.println(“Original before: ” + original[0]); incrementValue(original); System.out.println(“Original after: ” + original[0]);

And the result is:

Original before: 10 In function: 11 Original after: 11

The original value did change! This is because complex object variables are references. A reference variable points to a location in memory. When a variable is passed to a function, a new reference is always created. Both references point to the original objects or values.

int[] origial = {10, 20, 30}

original[0] —> | 10 | <— inFunction[0] | 20 | | 30 |

Both array elements point to the same memory location

Case 3: Passing Strings

void changeString(String inFunction){ inFunction = “New!”; System.out.println(“In function: ” + inFunction); }

String original = “Original!”; System.out.println(“Original before: ” + original); changeString(original); System.out.println(“Original after: ” + original);

The result is:

Original before: Original! In function: New! Original after: Original!

Remember, strings are immutable. A copy of the entire String is created when passed to a function.

Originally published at on March 9, 2015.

Written by Victor Leung who is a keen traveller to see every country in the world, passionate about cutting edge technologies. Follow me on Twitter