0

This is my first post here, so please be friendly! :)

Let's say I have this code:

public static void reassign (int[] nums) {
  int[] A = {10,11,22};
  A = nums;
}

public static void main(String[] args) {
  int[] nums = {0,2};

  reassign(nums);
  System.out.println(nums[1]);
}

Why is my answer 2, and not 11? Does it have something to do with the relative sizes of the arrays?

nreminder
  • 35
  • 6

2 Answers2

1

When you do this,

public static void reassign (int[] nums) {
    int[] A = {10,11,22};
    A = nums;
}

you make A as a refference of nums, and the nums you are refering to is the one from parameter, not the one from main method. its two different variable

This is how you suppose to do it:

static int[] nums = {0,2}; //initial value of nums

public static void reassign (int[] arr) {
    nums=arr;
}

public static void main(String[] args) {

    int[] A = {10,11,22};
    System.out.println("before reassign:"+nums[1]);
    reassign(A);
    System.out.println("after reassign:"+nums[1]);
}

Output:

    before reassign:2
    after reassign:11
Baby
  • 5,062
  • 3
  • 30
  • 52
0

Why is my answer 2, and not 11?

For one, you wanted to write

public static void reassign (int[] nums) {
  int[] A = {10,11,22};
  nums = A;
}

But than won't help you either: you cannot assign to one method's local variable from another method. The value of the variable (a reference to the array) is passed to reassign, not the address of the variable itself.

In reassign you merely create a new array and then assign its reference to the local variable nums (in my corrected code).

Does it have something to do with the relative sizes of the arrays?

No, the reason behind it is fully general and applies to all of Java.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436