1

So I was doing a UIL practice test and this problem came up.

public void fun(int[] list){ list[2]++; list[1] = list[0]; list = new int[4]; list[2]++; } ////////////////////////// // client code int[] vals = {2, 7, 3}; fun(vals); out.print( Arrays.toString(vals) ); 

I tried it out and got [2, 2, 5] but the answer was [2, 2, 4]. Since it was just list[2]++, I figured that it would just add, but it didn't. Why was the last increment not included in the output?

3 Answers 3

3
list = new int[4]; 

The last line incremented an element in a different array.

Sign up to request clarification or add additional context in comments.

Comments

0

list = new int[4]; this changed the local reference list address. but, vals kept the old address. so, last increment done to a new array. and vals kept the old array with the operations did to it.

Comments

0

When you call fun(vals) the local variable list is pointing to the location of vals. After a new array is created, however, the local variable list now points to an entirely different block of memory (though the reference itself is still in the same location in memory).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.