Ewin Zuo
Ewin Zuo

Reputation: 45

Java println weird output

I'm getting a weird output from running this simple java program.

The output is: 0 4 2 -6

Why does the x++ print 0, it should be printing 4.

import java.util.*;
import java.io.*;

public class Java1 {

    public static void main(String[] args) throws IOException {

        int x = 4;
        int y = -5;

        System.out.println(x++ + " " + func(x++, y) + " " + --y);
    }

    public static int func(int work, int y) {

        int z = work + y;

        work++;

        y++;
        System.out.print(z + " ");
        return z + work + y;

    }
}

Upvotes: 1

Views: 83

Answers (5)

yathu
yathu

Reputation: 19

import java.util.*;
import java.io.IOException;

public class Java1 
{   
    public static void main(String args[])
    {
       int x = 4;
       int y = -5; 
       System.out.println("x = "+ (x++ ) +" func = "+ (func(x++, y) ) + " y = "+ --y);
    }

    public static int func(int work, int y) 
    {

        int z = work + y;// 5+-5 = 0
        work++; //6

        y++; //-4
        System.out.print("Z = " + z + " ");//0 
        return z + work + y;  //0 + 6+-4 = 2
    }
}

OUTPUT :

Z = 0 x = 4 func = 2 y = -6

Here the func() is executed first and hence the value of variable z is printed as 0 and then the x++ value is printed as 4.

Upvotes: 0

Devendra Lattu
Devendra Lattu

Reputation: 2812

I have mentioned the flow of points from 0 to 7 in the comments

    public static void main(String[] args) throws IOException {

        int x = 4;
        int y = -5;

        System.out.println(x++ + " " + func(x++, y) + " " + --y);
        // thus 0]4  6]2 (value returned as z) 7] localvalue of --y as -6 
    }

    //1] x++ makes x as 5 when it is passed to func()
    public static int func(int work, int y) {

        int z = work + y;
        //2] z = 5 + -5 = 0 
        work++;
        //3] work which was x as 5 is now 6
        y++;
        //4] y will be -4 now
        System.out.print(z + " ");
        return z + work + y;
        //5] z = 0 + 6 + -4 = 2 and is returned to func() caller
    }

Upvotes: 0

ram
ram

Reputation: 1169

System.out.print(z + " ");

is executed before

System.out.println(x++ + " " + func(x++, y) + " " + --y);

So the 0 comes from z, not x.

Upvotes: 0

Leon
Leon

Reputation: 3036

Okay, here is what's going on: First x++ is evaluated, returning 4 (which is later printed) and leaving x at 5. Then x++ is evaluated again, passing 5 to func. Then func is evaluated with 5 and -5 parameters. In here z is 0 (5 + (-5) = 0) which is then printed (BEFORE the println in the main method. func then returns 2 (0 + 6 + (-4)) which is also added to the string. Finally --y results in -6. Now the println in the main method prints its string (4 2 -6).

Upvotes: 1

Loris Securo
Loris Securo

Reputation: 7638

func(x++, y) is executed first, so 0 comes from System.out.print(z + " "); in func.

Upvotes: 0

Related Questions