The difference between a++ and ++a in java

1. When used as an independent statement, a++ and ++a are an effect, both are equivalent to a=a+1

public class test {
    public static void main(String[] args) {
        int a = 1;
        a++;
        ++a;
        System.out.println(a);
    }
}

2. Used as an expression: ++a is first self-incremented and then assigned; a++ is first assigned and then self-incremented

public class test {
    public static void main(String[] args) {
        int a = 1;
        int b = a++;
        int c = ++a;
        System.out.println(b);
        System.out.println(c);
    }
}

Above, there are two topics below:

What is the value of i output at this time?

Here is the post ++, the inside of the computer is actually such an execution step:

(1)temp=i (2)i=i+1 (3)i=temp

Obviously the output of i is still 1

Then, change the title as follows:

What is the i output at this time?

According to the above steps, let's analyze:

(1)i=i+1 (2)temp=i (3)i=temp 

Result output 2

 

Guess you like

Origin blog.csdn.net/Danelxiong/article/details/127822891