java - How does the values of an array changes when we passed it as an argument to other function? -
this question has answer here:
when passed array argument function, original array gets changed, array should not changed right? please correct me if wrong.
below passed int x=10 argument change(int a) function. value of original int x got changed.
so how same code affects array , int in different way?
public class runy { public static void main(string [] args) { runy p = new runy(); p.start(); } void start() { long [] a1 = {3,4,5}; long [] a2 = fix(a1); int x=10; int y= change(x); system.out.println(y); system.out.println(x); system.out.print(a1[0] + a1[1] + a1[2] + " "); system.out.println(a2[0] + a2[1] + a2[2]); } long [] fix(long [] a3) { a3[1] = 7; return a3; } int change(int a) { a=a+1; return a; }
}
you're wrong. you're passing in isn't array - it's reference array. arrays reference types in java, value of a1
(for example) isn't array object - it's reference array object.
when pass reference fix
, parameter (a3
) has same value a1
... value refers same array, modification array visible after method returns. @ point, a1
, a2
equal references - both refer same array.
Comments
Post a Comment