左自增与右自增的区别

左自增( ++a) 和 右自增 (a++ )的区别

++和--既可以出现操作数的左边,也可以出现在右边,但结果是不同的

左自增例子:

public class Demo {
    public static void main(String[] args) {
        int a = 5;
        int b = ++a;//让a先执行自增,然后再赋值给b
        System.out.println("a" + a);//输出结果6
        System.out.println("b" + b);//输出结果6
    }
}

右自增例子:

public class Demo {
    public static void main(String[] args) {
        int a = 5;
        int b = a++;//将a的值先赋值给变量b,然后再执行自增
        System.out.println("a" + a);//输出结果6
        System.out.println("b" + b);//输出结果5
    }
}

注意:

自增自减运算符只能用于操作变量,不能直接用于操作数值或者常量!

public class Demo {
public static void main(String[] args) {
int a = 5;
int b = ++a;//a先执行自增,然后再赋值给b
System.out.println("a" + a);//输出结果6
System.out.println("b" + b);//输出结果6
}
}

猜你喜欢

转载自www.cnblogs.com/libinhong/p/10988535.html