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!