0

public class ExamPreparationDemo {

public static int[] arrayDivisionByD2(int[] numbers) {
    for(int i = 0; i < numbers.length; i++)
        numbers[i] = numbers[i]/2;
    return numbers;
}

public static void main(String[] args) {

    int[] numbers = {3,8,9,10};
    int[] numbers2 = arrayArrayDivisionBy2(numbers);
  
       
   System.out.println(Arrays.toString(numbers));
   System.out.println(Arrays.toString(numbers2));

// My Question: When I run my program, I see "1,4,4,5" "1,4,4,5". But why did my variable 'numbers' didn't stay the same? I.e "3,8,9,10"? They both changed while I only wanted "numbers2" to change. Please help.

  • Short answer: The code only ever creates *one* array. A reference to the array is passed to the method, which modifies the array's contents, and returns a reference which is stored in another variable. Both variables point to the same array. – David Aug 28 '20 at 13:56
  • Thanks for your comment, the link you sent me helped me a bit more at understanding things. Q : Is it correct to say that arrays and objects always point to an address? – Milan Van Hoestenberghe Aug 28 '20 at 14:43
  • It may be more accurate to say that they *are* an address, which points to a location in memory that contains data. That address can be passed around, copied, etc. but if only one object/array was actually created then only one exists. – David Aug 28 '20 at 15:06

1 Answers1

0

Array is passed by reference. Try creating a clone

        int[] numbers = {3,8,9,10};
        int[] numbers2 = numbers.clone(); //create a clone of array
        numbers2 = arrayDivisionByD2(numbers2); //passing new cloned array as param

Explanation

When you passed the "numbers" via method

concept "Call by reference" comes into picture

where the address of first block (address of memory block containing 3) is passed instead of values 3,8,9,10

numbers --> |3|8|9|10|

now whatever the changes you had performed, were actually carried over original array

and method "arrayDivisionByD2" is returning a reference to updated array not a different array containing updates

which means "numbers" and "numbers2" pointing to same array (This is the reason 1,4,4,5 printed twice) instead of two individual arrays

numbers and numbers2 --> |1|4|4|5|

which would have printed 3,8,9,10 and 1,4,4,5

and in the answer, clone of the original array was created and it was passed via method.Then, changes were carried over this cloned array

resulting having two individual array

numbers --> |3|8|9|10| 
numbers2 --> |1|4|4|5|
sachco
  • 274
  • 1
  • 9