0

So im kinda new to java and i followed some tutorials, and he showed an example of how to use arrays in methods like this:

public static void main(String[] args){
    int myArray[] = new int[2];
    myArray[1] = 1;  //Setting the array to equal 1
    change(myArray);

    System.out.println(myArray[1]);  //Prints 2 instead of 1
}

public static void change(int a[]){
    a[1] = 2;

}

But when i change the array to an int it suddenly doesn't work anymore:

public static void main(String[] args){
    int myInt = 1;  //Setting the int to equal 1
    change(myInt);

    System.out.println(myInt);  //Still prints 1
}

public static void change(int a)
{
    a = 2;
}

So my question is: Why can i change the array with a method but not the int?

André Stannek
  • 7,773
  • 31
  • 52
Jelloboy
  • 3
  • 3

1 Answers1

2

An int is a value type, but an array (like String[]) is a reference type.

Since in Java, all function parameters are passed by value, a deep copy of the int is taken but only a shallow copy of the array is taken (i.e. the reference is copied by value but not the thing being referred to).

What you can't do inside the void change(int a[]) function is make the corresponding variable to a (myArray) in the caller refer to a different array.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483