-2

In the following code, why is arr2[0] still equal to 1.5 even though the original array is changed in method2? Ignore the other arrays and variables.

public class Problem3
{
    public static int method1(int[] array)
    {
        array[0] += 10;
        return array[0];
    }

    public static int method2(int aNum, String aStr,
        int[] array1, float[] array2, int[] array3)
    {
        float[] fNums = {1.5F, 2.5F};
        array2 = fNums;

        return 10 + method1(array3);
    }

    public static void main(String[] args)
    {
        int num = 1000;
        String aStr = "Hello!";
        int[] arr1 = {1, 2, 3};
        float[] arr2 = {0.5F, 1.5F};
        int[] arr3 = {5, 6, 7};
        int retNum = method2(num, aStr, arr1, arr2, arr3);

        System.out.println(arr2[0]);
    }
}
Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
Index Hacker
  • 2,004
  • 3
  • 17
  • 20

3 Answers3

2

because you changed the reference to the entire array and did not modify the array passed in.

When you call method2 the argument points to the array created outside. In the method2 you make the argument point to a new array. this does not alter the array which the variable in the calling method is pointing to, that is still pointing to the original array.

If you simply modified the existing array you were given in method2, then you would see those changes in the calling method.

Sam Holder
  • 32,535
  • 13
  • 101
  • 181
2

Basically, because array2 is not arr2, but they refer to the same array in memory on calling method2:

method2(num, aStr, arr1, arr2, arr3);
public static int method2(int aNum, String aStr, int[] array1, float[] array2, int[] array3)

Then, you make array2 refers to a new array which fNums is referring to, and you didn't change the array that arr2 referes to:

float[] fNums = {1.5F, 2.5F};
array2 = fNums;

See this answer for more details.

Community
  • 1
  • 1
Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
-1

I believe that Java uses pass-by-value paramter passing semantics. By declaring float[] arr2 within PSVM(), its scope is limited to there, and if you pass the array to another function, it gets passed by value.

If, on the other hand, you had declared float[] arr2 outside of PSVM() (but within the class definition), then its scope would be global within the class. However, I still don't think your code would work, because IIRC, you cannot assign the value of an entire array with a single assignment like your code does in method2().

pr1268
  • 1,176
  • 3
  • 9
  • 16