When i passed an array as an argument to the function, the original array gets changed, but the array should not get changed right? please correct me if am wrong.
below i passed an int x=10 as an argument to change(int a) function. the value of the original int x got changed.
So how does the same code affects an array and 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. What you're passing in isn't the array - it's a reference to the array. Arrays are reference types in Java, so the value of a1
(for example) isn't an array object - it's a reference to an array object.
When you pass that reference into fix
, the parameter (a3
) has the same value as a1
... that value refers to the same array, so a modification to that array is visible after the method returns. At that point, a1
and a2
will be equal references - they both refer to the same array.
See more on this question at Stackoverflow