Increment and decrement operators in JAVA (the difference between i++ and ++i)

note:

The increment operator and decrement operator can only be used for variables, not for constants or expressions

Operator Calculation example result
++ Self-increment (front): first calculate and then take value a=2;b=++a; a=3;b=3;
++ Self-increment (after): first take the value and then calculate a=2;b=a++; a=3;b=2;
-- Decrement (front): first calculate and then take value a=2;b=--a; a=1;b=1;
-- Decrement (after): take the value first and then calculate a=2;b=a--; a=1;b=2;

Test code:

public class SignTest{
    
    
	public static void main(String[] args){
    
    
		int i1 = 10;
		int i2 = 20;
		int i = i1++;  
		System.out.print(“i=+i);  
		System.out.println(“i1=+i1);  
		i = ++i1;
		System.out.print(“i=+i);  
		System.out.println(“i1=+i1);   
		i = i2--;
		System.out.print(“i=+i);  
		System.out.println(“i2=+i2);   
		i = --i2;
		System.out.print(“i=+i);  
		System.out.println(“i2=+i2);
	}
}

operation result:

Insert picture description here

Extension exercises:

Code:

int n = 10;
n += (n++) + (++n);
System.out.print(n);

Output:
32
analysis:
n = n + (n++) + (++n); the first n on the right is 10, the second n is 10, n++ is the first value, so (n++) is 10, and then the operation, At this time, n is already 11, look at the third one, (++n), n is 11, first calculate and then take the value, (++n) becomes 12. 10 + 10 + 12=32.

Next stop: The difference between n+=1 and n=n+1 of JAVA foundation

Guess you like

Origin blog.csdn.net/m0_46278037/article/details/113721634