<p>I'm looking at problem 36 in the 2009 MC exam (teacher bought it off of AP Central.)</p>
<p>
[quote]
Consider the following two methods that appear within a single class.</p>
<p>public void changeIt(int[] list, int num)
{
list = new int[5];
num = 0;</p>
<pre><code>for (int x = 0; x < list.length; x++)
list[x] = 0;
</code></pre>
<p>}</p>
<p>public void start()
{
int[] nums = {1,2,3,4,5};
int value = 6;</p>
<p>changeIt(nums, value);</p>
<p>for (int k = 0; k < nums.length; k++)
System.out.print(nums[k] + " ");</p>
<p>System.out.print(value);
}</p>
<p>What is printed as a result of the call start() ?</p>
<p>A) 0 0 0 0 0 0
B) 0 0 0 0 0 6
C) 1 2 3 4 5 6
D) 1 2 3 4 5 0
E) changeIt will throw an exception. </p>
<p>
[/quote]
</p>
<p>What is the solution, and why?</p>
<p>Well, the code won’t compile because of missing semicolons but I assume those are typos.
It’s B. Primitive data types are immutable, but arrays are not. So, value will stay the same while every number in nums is changed to zero.</p>
<p>Actually, it’s not, according to the answer key. </p>
<p>Thanks for pointing out the missing semicolons; I went ahead and fixed it.</p>
<p>Oh sorry I neglected the line:
list = new int[5];</p>
<p>This points list, which was originally a reference pointing at the same array as nums, to a new array, and any changes to this array do not affect nums since they are two different references. It is C then, I apologize.</p>
<p>The answer is C. With a little more detail than what bobtheboy provided:</p>
<p>When the array is passed into the changeIt() method, it is given a new pointer, “list”. So now, “nums” and “list” both point to the array that looks like {1,2,3,4,5}. Then we say “list = new int[5];”. So now “nums” still points to {1,2,3,4,5}, but “list” points to {0,0,0,0,0}. When the method changeIt() finishes its call, “list” is erased because it is a local variable. Therefore, when we come back to our original start() method, “nums” still points to {1,2,3,4,5}, and nothing has changed.</p>
<p>A good tip off that nothing will be affected is that if CollegeBoard is calling a method “changeIt”, chances are it ISN’T CHANGING, simply because we are dealing with the CollegeBoard.</p>
<p>So there you have it, an analytical explanation and a psychological explanation, both which point to the answer being C ^^.</p>