Java Uncovered: The Mind-Blowing Reality of Pass-by-Value vs Pass-by-Reference! ๐Ÿš€๐Ÿš€

Light
2 min readMar 9, 2024

--

public int abc() {
int[] diameter = new int[1];
def(diameter);
return diameter[0];
}

private int def(int[] diameter) {
int var = 5;
while (diameter[0] < 10) {
diameter[0]++;
}
return var;
}

The thing here is that arrays in Java are passed by reference. This means that when diameter is passed to the def(int[] diameter) method, any changes made to diameter inside def(int[] diameter) will affect the diameter in the abc() method. So, the while loop in def(int[] diameter) is actually incrementing the value of diameter[0] in the abc() method. As a result, abc() returns the incremented value of diameter[0], which will be 10.

Hereโ€™s the flow in a simpler way:

  1. abc() is called.
  2. diameter is initialized as an array with one element, 0.
  3. def(diameter) is called, passing the diameter array.
  4. Inside def(diameter), a while loop runs, incrementing diameter[0] until it is no longer less than 10.
  5. def(diameter) returns var, but this return value is not used.
  6. Back in abc(), diameter[0] (which is now 10) is returned.
public int abc() {
int diameter = 0;
def(diameter);
return diameter;
}

private int def(int diameter) {
int var = 5;
while (diameter < 10) {
diameter++;
}
return var;
}

In the previous code, diameter was an array, which is an object in Java. When objects are passed into methods in Java, they are passed by reference. This means that any changes to the object inside the method will affect the original object.

However, in this code, diameter is a primitive data type (an int). When primitive data types are passed into methods in Java, they are passed by value. This means that a copy of the variable is made, and the method receives that copy. Any changes to the copy inside the method do not affect the original variable.

So, in this code, when diameter is incremented inside the def(int diameter) method, it does not affect the diameter variable in the abc() method. As a result, abc() will always return 0, regardless of what happens in def(int diameter).

--

--

Light
Light

Written by Light

Upcoming CEO of "A" company

No responses yet