0

The value of int a remains same after calling function (testInPlaceInteger(a)) but for int[] arr changes after calling the function (squareArrayInPlace). Why is int a value not changing?
Following is my code:

public class Test {
  public static void main(String[] args) {
    int a = 5;
    int[] arr = new int[] {3, 4};

    Test test = new Test();

    test.testInPlaceInteger(a);
    test.squareArrayInPlace(arr);

    System.out.println(a);

    for (int i : arr) {
      System.out.println(i);
    }
  }

  public void testInPlaceInteger(int num) {
    num *= num;
  }

  public void squareArrayInPlace(int[] intArray) {
    for (int i = 0; i < intArray.length; i++) {
      intArray[i] *= intArray[i];
    }
  }
}

Output:

5
9
16
user2173372
  • 483
  • 7
  • 17

1 Answers1

0

Because int is a primitive type and is passed by value. However, intArray[i] is a memory location, so you can change the value within.

Héctor
  • 24,444
  • 35
  • 132
  • 243