0

I am practicing for the AP computer science A exam and I came across a question that I couldn't understand even after seeing the answer.

The Question is:

Consider the following two methods, which appear within a single class.

public static void changeIt (int[] arr, int val, String word)
{
   arr = new int[5];
   val = 0;
   word = word.substring(0, 5);
   
   for (int k = 0; k < arr.length; k++)
   {
       arr[k] = 0;
   }
}

public static void start()
{ 
  int[] nums = {1, 2, 3, 4, 5};
  int value = 6;
  String name = "blackboard";

  changeIt(nums, value, name);

  for (int k = 0; k < nums.length; k++)
{
    System.out.print(nums[k] + " ")
}
    System.out.print(value + " ");
    System.out.print(name);
}

The answer choices are:

A. 0 0 0 0 0 0 black

B. 0 0 0 0 0 0 blackboard

C. 1 2 3 4 5 6 black

D. 1 2 3 4 5 0 black

E. 1 2 3 4 5 6 blackboard

As you can see, the start() method called the changeIt method, and I thought this would update the array and "value" itself, making me choose A. However, the correct answer is E, and even after tracing the code few more times, I couldn't figure out why.

Does the void method have any function in this code? Why is the data not updated after going through the changeIt method? I have seen examples where the void method updates the variables and plays a central role in determining the final output, but why does that work while this one fails to do so? I am new to Java and any help would be really appreciated as I have to take my exam in a couple of days. Thanks!

  • 1
    "*Does the void method have any function in this code?*" - If by "function" we mean an "externally visible change in state" then no, it does not. --- Please read: [How to debug small programs (`https://ericlippert.com/`)](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) – Turing85 Apr 27 '22 at 18:54
  • You can modify the contents of objects passed into a method, but you cannot modify the object references themselves. – Louis Wasserman Apr 27 '22 at 18:55
  • The first three lines of your `changeIt` method reassign the parameter variables to something new. So the method effectively loses access to the values that were passed in. The `for` loop now can't change the original array. – Dawood ibn Kareem Apr 27 '22 at 19:26

0 Answers0