0
public class SomeClass {
    public static void f(int x, int [] y, int[] z){
        x=2;
        y[0]=x;
        z= new int[5];
        z[0]=555;
    }

        public static void main(String[] args){
        int x= 111;
        int[] y={222,333,444,555};
        int[] z={666,777,888,999};
        f(x,y,z);
        System.out.println(x);
        System.out.println(y[0]);
        System.out.println(z[0]);

    }

    }

The output of this code is 111-2-666, what does f(x,y,z); exactly do? and why after execution it prints x as 111, while y[0] gets the value of the other x and prints 2 and z remains the same although it says that z[0] is 555? Everything remains unchanged except y[0] and i don't understand why.

  • 4
    Debug your code, that's the best explanation you can get. – Maroun Sep 02 '14 at 14:48
  • Marked as duplicate does not really answers my question, if i understood what the other post said i would not post here. I need someone to give me a clear explanation if possible and not to copy paste links. Not all the people have the same experience here – Charis Patsalidis Sep 02 '14 at 14:57
  • The obfuscation in this code is the fact that the same names (`x`, `y` and `z`) have been used for two completely separate sets of local variables, namely the ones inside `main` and the ones inside `f`. Try renaming the two sets of variables to something like `fx`, `fy`, `fz` and `mx`, `my`, `mz` instead and see if that makes things any clearer. – Ian Roberts Sep 02 '14 at 15:02
  • if i rename them as you say the program does not work.... – Charis Patsalidis Sep 02 '14 at 15:09
  • The other link explains what pass by value is and how that works in Java. Your misunderstanding is with that concept. – Sotirios Delimanolis Sep 02 '14 at 15:12
  • So how can i know when a value is passed by reference or by value? – Charis Patsalidis Sep 02 '14 at 15:36
  • Please read the other link. Java only passes by value. – Sotirios Delimanolis Sep 02 '14 at 15:43
  • This assignment `z= new int[5];` is not visible from the caller because of the fact that java is pass by value. – Sotirios Delimanolis Sep 02 '14 at 15:45

0 Answers0