1
public void changeParams(int k, int[] A, String s){
    k++;
    A[0]++;
    s += "X";
}
public void print(){
    int k = 0;
    int[] A = {10, 20};
    String s = "aaa";
    changeParams(k, A, s);
    System.out.println(k + " " + A[0] + " " + s);
}

The question is asking "What is output when method print is called?" I think the answer is 0 10 aaa but the answer key says 0 11 aaa Could someone explain why? Thanks

Kirby
  • 15,127
  • 10
  • 89
  • 104

2 Answers2

3

It is 0 11 aaa.

The A[0]++ in changeParams() affects the value stored in the array because a pointer is passed into the method and so operations affect the shared data. Debug this and step through it...

public class SO {

    public void changeParams(int k, int[] A, String s){
        k++;
        A[0]++;
        s += "X";
    }
    public void print(){
        int k = 0;
        int[] A = {10, 20};
        String s = "aaa";
        changeParams(k, A, s);
        System.out.println(k + " " + A[0] + " " + s);
    }

    public static void main(String... args) throws Exception {
        new SO().print();
    }
}
Kirby
  • 15,127
  • 10
  • 89
  • 104
2

The answer is 0 11 aaa. The reason for it is that Java is pass by value.

Here's what that means.

In your changeParams method, you're affecting all three arguments to it - the int passed in, the array, and the String.

When you're passing something by value, you're giving them a copy (of sorts) of the value. What this means is, in general, you can't destroy or tamper with the original value passed in - with respect to primitives and immutable classes. String is immutable, so any operation done to it will produce a new String - and the operation done on it will only live inside of that method.

Arrays are not immutable. If you pass in an array, you have the ability to index into it and change any value you like, which may or may not be desirable to your program's intentions.

The same is also true if you pass in a mutable object - Calendar, for example; if you pass in a Calendar instance, you will be able to modify its state (day of week, hour, second, millisecond, etc), and potentially cause havoc when you're trying to use the same instance for something else later.

This is why the only thing that changes is 11. The value at A[0] has been incremented, and because arrays aren't immutable, you are effectively changing the value for the array at a given location.

Community
  • 1
  • 1
Makoto
  • 104,088
  • 27
  • 192
  • 230