Learn AP Comp Sci

☰

Problem of the Day

Tuesday, September 29, 2026


Problem:

Consider the following method.

public static void triple(int n)
{
System.out.print(" " + n);
n = n * 3;
System.out.print(" " + n);
}

Which of the following is printed as a result of executing this code segment?

    int n = 2;
triple(n);
System.out.print(" " + n);
  1. 2 6 2
  2. 2 6 6
  3. 2 2 6
  4. 6 6 2

Show solution:

The correct answer is a. The variable n in the code segment has been assigned a value of 2. When the method triple is called, that value is passed as an argument to the method, also called n. This value is assigned to the parameter n in the method, which is a different variable that only has scope in the method. Working with that parameter in the method, we can print out its initial value 2, and assign it a new value (6, but this has no effect on the variable n that was in the calling code segment—they are two different variables, with two different scopes.

If we want to modify the value of the external n, we would need to include a return statement that would send that information back to the calling code.