1. The use of the increment and decrement operators is different in the two scenarios
(1) When used alone, the result of the operation is the same no matter where the "++" symbol is;
The following two examples are used for comparison
eg1 :
public static void main(String[] args){
int i =10;
System.out.println("i:"+i);
//输出结果为: i:10
i++;
System.out.println("i:"+i);
//输出结果为: i:11
}
eg2:
public static void main(String[] args) {
int i =10;
System.out.println("i:"+i);
//输出结果为 i:10
++i;
System.out.println("i:"+i);
//输出结果为 i:11
(2) When participating in the operation, if it is placed behind the variable, first use the variable to participate in the operation, and then use the variable as ++ or --;
When participating in the operation, if it is placed in front of the variable, first use the variable as ++ or --, and then use the variable to participate in the operation;
Here are two examples for a deeper understanding:
eg1:
public static void main(String[] args) {
int i=10;
int j=i++;
System.out.println(i);
//输出结果为 11
System.out.println(j);
//输出结果为10
}
eg2:
public static void main(String[] args) {
int i=10;
int j=++i;
System.out.println(i);
//结果为11
System.out.println(j);
//结果为11
}
2. To summarize
Apply the rules
symbol | effect | illustrate |
++ | auto increment | The value of the variable is incremented by 1 |
-- | Decrement | Decrement the value of the variable by 1 |