0

The result you are suppose to get is 0, but I don't understand why? The array is changed when its passed through other method.

public class Tester {
  public static int function1 (int [] arr) {
    arr= function2(arr);
    return arr[0];
  }
  public static int[] function2 (int [] arr) {
    arr = new int[4];
    return arr;
  }
    public static void main(String[] args) {
      int arr[] = {1,2,3,4};
      System.out.print(Tester.function1(arr));
    }
}

I expected 4 from the printed answer.

1 Answers1

2

You are creating a completely new array in function2. That's why by default it is storing 0 at every index. When you are returning, the new array is returning only. For every index it will print 0 only. Why are you creating new array in function 2? If you have to print 4 then simply pass the existing array only and print the arr[3].

Here is the code :-

public class Tester {
  public static int function1 (int [] arr) {
    arr= function2(arr);
    //return arr[0];
    return arr[3];
  }
  public static int[] function2 (int [] arr) {
    //arr = new int[4];
    return arr;
  }
    public static void main(String[] args) {
      int arr[] = {1,2,3,4};
      System.out.print(Tester.function1(arr));
    }
}
Rockers
  • 163
  • 7