In Java, it is always pass by value. I have been refreshing Java concepts lately to become a better programmer by understanding the fundamentals and to write clean code. I am not a fan of writing one liner unless it is really required. My main intention is to make sure that my code is understandable for me after a few months. Lets dive in.
Table of Contents
Passing a primitive
Consider the below code block where x is being passed to two methods: one with return and another one with void.
As Java is always pass by value – the void method will print 20 inside the method. But the method which has the return of int will print 30.
modifyXWithReturn(x)? returns a new value (3 * 10 = 30), but the caller must explicitly use or assign it.
This shows primitives are passed by value
int x = 10;
System.out.println("X " + x);
modifyX(x);
System.out.println("X " + x);
System.out.println(modifyXWithReturn(x));
private static int modifyXWithReturn(int x) {
return 3 * x;
}
private static void modifyX(int x) {
x = 2 * x;
System.out.println(x);
}
Passing an Array (int[] arr1)
- Because arrays are objects, the reference value is copied into the method. Both caller and method point to the same array object.
- Mutations inside the method are visible outside:
int[] arr1 = {1, 2, 3};
System.out.println("Before arr1 in main " + Arrays.toString(arr1));
modifyArr1(arr1);
System.out.println("After arr1 in main " + Arrays.toString(arr1));
private static void modifyArr1(int[] arr1) {
for (int i = 0; i < arr1.length; ++i) {
arr1[i] = 2 * arr1[i];
}
System.out.println("Arr1 in modifyArr1 " + Arrays.toString(arr1));
}
Before arr1 in main [1, 2, 3]
Arr1 in modifyArr1 [2, 4, 6]
After arr1 in main [2, 4, 6]
This shows object references are passed by value (the reference itself is copied, but both copies point to the same object).
Passing an Array Element (arr2[0])
int[] arr2 = {7, 8, 9};
System.out.println("Before arr2 in main " + Arrays.toString(arr2));
int newArr2Element = modifyArr2Element(arr2[0]);
System.out.println("After arr2 in main " + Arrays.toString(arr2));
System.out.println(newArr2Element);
private static int modifyArr2Element(int n) {
System.out.println("Arr2 0th element is " + (n * 2));
return n * 2;
}
- Inside
modifyArr2Element, you print14and return it. - The original array remains unchanged:
Before arr2 in main [7, 8, 9]
Arr2 0th element is 14
After arr2 in main [7, 8, 9]
14
This shows passing a primitive extracted from an array does not mutate the array.
Key Takeaway
- Java is always pass by value.
- For primitives the actual value is copied.
- For objects the reference value is copied. Mutations are visible, but reassignment isn’t.