java中的递增运算符

Jac*_*son 2 java increment

刚开始学习java,所以抱歉问这么随意而愚蠢的事情......但是我不能把我的脑袋包裹在java中的增量运算符中.

为什么这样做:

int a = 5;
int a = ++a;
System.out.println(a);

>>6
Run Code Online (Sandbox Code Playgroud)

如果没有:

int a = ++5;
System.out.println(a);

>>Compilation error: Found value - Required variable.
Run Code Online (Sandbox Code Playgroud)

这个算子不应该像其他算术运算符一样工作吗?为什么这个特别需要一个变量?我的意思是a = 5+1;作品,为什么不a = ++5呢?

有没有办法++直接使用值?

sep*_*p2k 10

++x is not a shortcut for x + 1, it's a shortcut for x += 1. That is, in addition to evaluating to x+1, it also increments the value of x by one. This means two things:

  1. x = ++x; is redundant as ++x; by itself already accomplishes the same thing.
  2. ++1 makes no sense as you can't change the value of 1 - it is a constant.