AP Computer Science CRAMMING

<p>The test is officially tomorrow!! and I need help on this question</p>

<p>Consider the following method:</p>

<p>public void reduce(int[] arr, int len)
{
for (int i = 0; i<len; i++)
{
arr*--;
}
len--;
}</p>

<p>What is the output of the following code segment?</p>

<p>int[] counts = {3, 2, 1, 0, 0, 0,};
int len = 3
reduce (counts, len);
for (int k : counts)</p>

<p>{
System.out.print(k + " ");
}
System.out.println (len);</p>

<p>Thanks!</p>

<p>error. There is no semicolon after
int len = 3
Also, if the second part of the code is inside a main method, it should be public static void reduce(int arr, int len). (I think)</p>

<p>Apart from that, the output is probably:
2 1 0 0 0 0 2</p>

<p>But I have a bad feeling that len is not going to be reduced.</p>

<p>I don’t think len is reduced…</p>

<p>how did you figure out the output is going to be 2 1 0 0 0 0 2</p>

<p>len is definitely NOT reduced; it has nothing to do with feelings. Primitives are passed by value, so the len in the reduce method is not the same as the len in the code snippet, and changing the len in the reduce method has no effect whatsoever on the len outside it. Arrays, on the other hand, are passed by reference, so changing the content WILL have an effect.</p>

<p>2 1 0 0 0 0 3</p>

<p>It’s actually 2 1 0 0 0 0 3 (at least, if the mistakes in the code were corrected)
To figure this out, just pretend to be a computer and go through the loops and stuff. len is not changed because primitives are passed by value- they can’t be changed within the method. Objects are passed by reference, which means that the fields of the object can be changed within the method, but the reference to the object remains the same. It’s better explained [url=<a href=“JDK 21 Documentation - Home”>Passing Information to a Method or a Constructor (The Java™ Tutorials > Learning the Java Language > Classes and Objects)]here[/url</a>].</p>