I am confused by the way arrays work. If I pass an array reference to some method, then that method is able to change the index values previously stored in array. However, if do the same with, say, a wrapper class object then that method is not able to change the value. Here is the code:
public class TestArray {
public static void main(String[] args) {
ChangeValues ch=new ChangeValues();
int intArr[]={1,2,3};
Integer iWrapper=new Integer(123);
ch.changeArray(intArr);
for(int i:intArr){
System.out.print(i);// o/p: 789
}
System.out.println("\n-----------------");
ch.changeWrapper(iWrapper);
System.out.println(iWrapper);// o/p: 123
}
}
class ChangeValues{
void changeArray(int i[]){
i[0]=7;
i[1]=8;
i[2]=9;
}
void changeWrapper(Integer i){
i=789;
}
}
output:
789
-----------------
123
Why is it that an array is able to change and not wrapper object. can any one clear away my doubts? thanks.
changeArray, but overwriting the reference to the Integer object inchangeWrapper-- two entirely different things.