-1

Please help me with this one guys! why are there arguments given to a method that is void??

public class C {   
    public static void main(String[] argv) {     
        int k = 1;     
        int[] x = {0, 1, 2, 3};     
        int[] y = x;     
        lurig(x, y, k);     
        System.out.println(x[0] + k + y[0]);   
    } 

    public static void lurig(int[] p, int[] q, int r) {     
        p[0] = 1;     
        q[0] = 2;     
        r = 3;   
    } 
} 
azro
  • 53,056
  • 7
  • 34
  • 70
Mr Miyagi
  • 31
  • 6

2 Answers2

0

Your x and y array actually refer to the same location in memory. This means that after calling lurig(x, y, k) both x[0] and y[0] are 2.

If you want x and y to refer to seperate memory locations, you need to do it like this

int[] x = {0, 1, 2, 3};     
int[] y = new int[4];
System.arraycopy(x, 0, y, 0, x.length);
Delphi1024
  • 183
  • 1
  • 4
0

x[0] is 0 k is 1 y[0] is 0

-> lurig() changes x[0] to 1 and y[0] to 2 but since y has the same reference as x it also changes x[0] to 2 k is a primitive type so it remains as 1 (completely unaffected)

-> 2 + 1 + 2 gives 5

5 is NOT returned it's being written out to the console. You don't have a return statement you have a System.out out stands for output.

InsertKnowledge
  • 1,012
  • 1
  • 11
  • 17