0

// Can someone please help explain how this code compiles. I know the output is:

//OUTPUT

foo : 48, a = 3, b = 6 
 main1 : 3, 9
foo : 24, a = 1, b = 3
 main2 : 1, 4
arr [0] = 12
arr [1] = 3
arr [2] = 36
arr [3] = 6
arr [4] = 60

// But I was confused how the code prints elements from the foo method and main method interchangeably, instead of in order of the main code. Thanks!

//CODE

public class ArrayTest {

    public static int foo (int a, int [] vals ) {

        int b = vals [a] % 7;

        System .out . println ("foo : " + vals [a] + ", a = " + a + ", b = " + b);
        vals [a] = b;
        return a + b;
    }

    public static void main ( String [] args ) {
        int a = 3;
        int b = 1;
        int [] arr = {12 , 24, 36, 48, 60};

        int x = foo(a, arr );
        System .out . println (" main1 : " + a + ", " + x);

        x = foo(b, arr );
        System .out . println (" main2 : " + b + ", " + x);

        for(int i = 0; i < arr. length ; i++) {
            System .out . println ("arr [" + i + "] = " + arr [i]);
        }
    }
}
  • What do you mean in order of the main? You call `foo()`, it is executed and prints, your print statement in the main prints, then you call `foo()` again and it prints, then you have one more print statement, and then in a loop print out the contents of `arr`. What is out of order? – GBlodgett Oct 08 '18 at 02:24
  • I got your question see this https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value – Ganesh Chowdhary Sadanala Oct 08 '18 at 02:53
  • Array is object type so it works as pass by reference that's why the updated value into the method reflects into main method also.. – Amit Oct 08 '18 at 03:11

0 Answers0