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;
}