I am fairly new to Java, and recently I was reading some material about Java being pass-by-value. I’ve read over this question, and this blog before running a test myself.
Now, based on my reading and my quick test, I found that there are two ways that I can alter the variables contained within an object reference. Which of the below approaches is the better or safer approach? Are there any obvious issues with either approach?
Both of these print out “iArr[0] = 45”.
Approach 1:
public static void main(String args[] ){
int[] iArr = {1};
method(iArr) ;
System.out.println( "iArr[0] = " + iArr [0] ) ;
}
public static void method(int[] n ) {
n [0] = 45 ;
}
Approach 2:
public static void main(String args[] )
{
int[] iArr = {1};
iArr = method(iArr) ;
System.out.println( "iArr[0] = " + iArr [0] ) ;
}
public static int[] method(int[] n ) {
n [0] = 45 ;
return n;
}
I find neither approach ideal as they both cause the same side-effects.
That is, they are the same but the 2nd approach also returns the modified object: the 2nd approach still modifies the array object passed in! The re-assignment to
iArrof the return value from #2 in the example code has no effect on the object modified! Remember that Java uses Call-By-Object-Sharing semantics (for reference types); the return value is unrelated to this behavior.I actually really dislike approach #2 because it “hides” this fact (I look at the signature and think “oh, I get a new array object!”), while approach #1 “does it’s dirty job”, but I can tell that quickly from the
voidreturn type. (In some advanced casing “chaining” can be useful; this is not one of them.)Here is a trivial version which does not cause side-effects: (I would suggest minimizing side-effects in general as it often makes code easier to reason about and debug.)