Search code examples
javaclassparametersintreturn

i am very confused how parameters and return


After I execute this code, the output is the output is 3 0 1 2 4 could you please explain the output? does the parameter in the mystery class sequence play a role in this?

public class MysteryReturn {
    public static void main(String[] args){
        int x = 1;
        int y=2;
        int z = 3;


           z = mystery(x,z,y);
           System.out.println(x + " "+y+" "+z);

    }
    public static int mystery(int z, int x, int y){
        z--;
        x =2*y +z;
        y=x-1;
        System.out.println(y + " "+ z);
        return x;
    }
}

Solution

  • It prints 1 2 3, and you aren't calling mystery function, so it can't affect.

    UPD. Question was updated, so lets look to your function

    public static int mystery(int z, int x, int y) {
        z--;
        x = 2 * y + z;
        y = x - 1;
        System.out.println(y + " " + z);
        return x;
    }
    

    it can be rewtiren to

    public static int mystery(int z, int x, int y) {
        return 2 * y + z-1;
    }
    

    and you calling it with arguments 1,3,2 - mystery(1,3,2) so answer becomes 2*2+1-1 which equals 4, so you have z=4, so

        System.out.println(x + " "+y+" "+z);
    

    will print 1 2 4