JAVA basic variable

Increment and Decrement Operator

Insert picture description here

1. The increment (++) and decrement (–)
operator is a special arithmetic operator. In the arithmetic operator, two operands are needed to perform the operation, and the increment and decrement operator is an operand.

public class selfAddMinus{
    
    
    public static void main(String[] args){
    
    
        int i = 1;
        int y = 2;
        i++;
        ++y;
        System.out.println("单独进行自增运算后的值等于"+i);
        System.out.println("单独进行自增运算后的值等于"+y);
    }
}

The running result is:

The value after independent increment operation is equal to 2
The value after independent increment operation is equal to 3


++ and-can be placed after or before the variable.
When used alone, ++ and – whether placed before or after the variable, the result is the same.
When participating in the operation, if it is placed after the variable, first take the variable to participate in the operation, and then use the variable as ++ or -. When participating in the operation, if it is placed before the variable, first use the variable as ++ or -, and then use the variable to participate in the operation.

Examples:

public class selfAddMinus{
    
    
    public static void main(String[] args){
    
    
        int a = 3;//定义一个变量;
        int b = ++a;//自增运算
        int c = 3;
        int d = --c;//自减运算
        System.out.println("进行自增运算后的值等于"+b);
        System.out.println("进行自减运算后的值等于"+d);
    }
}

The running result is:

The value after the increment operation is equal to 4
The value after the decrement operation is equal to 2


Analysis:

int b = ++a; The splitting operation process is: a=a+1=4; b=a=4, the final result is b=4, a=4
int d = --c; The splitting operation process is: c=c-1=2; d=c=2, the final result is d=2,c=2

2. Prefix auto-increment and auto-subtraction (++a, –a): Perform auto-increment or auto-decrement first, and then perform expression operations.
3. Suffix auto-increment and auto-decrement method (a++, a–): Perform expression calculation first, and then auto-increment or auto-decrement operation
Example:


public class selfAddMinus{
    
    
    public static void main(String[] args){
    
    
        int a = 5;//定义一个变量;
        int b = 5;
        int x = 2*++a;
        int y = 2*b++;
        System.out.println("自增运算符前缀运算后a="+a+",x="+x);
        System.out.println("自增运算符后缀运算后b="+b+",y="+y);
    }
}

The running result is:

After the increment operator prefix operation a=6, x=12
After the increment operator suffix operation b=6, y=10

Guess you like

Origin blog.csdn.net/QQ1043051018/article/details/112911774