I am learning Java. One important concept to understand is whether function arguments are passed by copy or by reference.

Passing by copy means that when a variable is passed to a function, a copy of that variable is made. Passing by reference means that the code in the function operates on the original variable, not on a copy.

In Java, variables are always passed by copy. Let’s explore this through three scenarios:

Case 1: Passing Primitives

void incrementValue(int inFunction) {
  inFunction++;
  System.out.println("In function: " + inFunction);
}

int original = 10;
System.out.println("Original before: " + original);
incrementValue(original);
System.out.println("Original after: " + original);

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.println("In function: " + inFunction[0]);
}

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

The result is:

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

The original value did change! This happens 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 object or value.

int[] original = {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. When passed to a function, a new String is created, leaving the original String unaltered.