简体   繁体   中英

Is this explanation correct for the output of the following postfix increment coding

I came across this coding...just want confirmation about what I understood how the output 121 is received.

System.out.print(i++ + obj1.operation(i));

In the above code i is zero , but i becomes one when it is passed as parameter to the operation method. In method operation the system.out.print prints out one and returns the post increment value 2 to above system.out.print . In above code the initial value of i and return value of method is added ie 0+2=2 , and it prints out 2. And the local variable i in the main method has increased to one in the above code so the next print statement prints 1. Is this the right explanation?

   public class CalculatorJava {
    public static void main(String[] args) {
        int i = 0;
        CalculatorJava obj1 = new CalculatorJava();
        System.out.print(i++ + obj1.operation(i));
        System.out.println(i);
    }

    public int operation(int i) {
        System.out.print(i++);
        return i;
    }
}

Not only the main method but also the operation method is using a local variable in this case. So we can consider them as two different variables. Let's call "i" in main as "mi" and "i" in operation as "oi". A simplified algorithm of the code above would be as follows:

1: assign 0 to mi
2: increase mi by one
4: assign the value of mi to oi
5: increase oi by one
6: print mi and oi
7: print mi

I assume you know that the plus sign inside the print method is not algebraic.

As you can see in the example code below, if we change the scope of i, that would let both methods use the same variable. And the output would be 122 instead of 121

public class CalculatorJava {
    static int i = 0;
    public static void main(String[] args) {
        CalculatorJava obj1 = new CalculatorJava();
        System.out.print(i++ + obj1.operation());
        System.out.println(i);
    }

    public int operation() {
        System.out.print(i++);
        return i;
    }
}

For further reading: Local Variables and Scope

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM