Java中的"+ i"是什么意思?
我在查看同事的代码时遇到了这个问题.她无意中把它留了下来(它曾经是一个字符串连接),我以为它不会编译.原来我错了,所以我尝试看看那个操作员做了什么:
I ran across this while reviewing a colleague's code. She'd left it in by accident (it used to be a String concatenation), and I assumed that it wouldn't compile. Turns out I was wrong, so I tried seeing what that operator did:
public static void main(String[] args) {
int i = -1;
System.out.println(String.format("%s", +i));
System.out.println(String.format("%s", +i));
}
据我所知,它什么也没做,但是我很好奇是否允许它编译的原因.该操作员有一些隐藏的功能吗?它与 ++ i
类似,但是您会认为编译器会在 + i
上使用barf.
As far as I can tell, it does nothing, but I'm curious if there is a reason it's allowed to compile. Is there some hidden functionality to this operator? It's similar to ++i
, but you'd think the compiler would barf on +i
.
即数字升级,因此如果操作数的编译时类型为 byte
, short
或 char
,则将其提升为键入 int
".
That is the plus unary operator +
. It basicaly it does numeric promotion, so "if the operand is of compile-time type byte
, short
, or char
, it is promoted to a value of type int
".
另一个一元运算符是增量运算符 ++
,该运算符将值加1.可以在(后缀运算符).区别在于,前缀运算符( ++ i
)的值为增量值,而后缀运算符( i ++
)的值为原始值.
Another unary operator is the increment operator ++
, which increments a value by 1. The increment operator can be applied before (prefix operator) or after (postfix operator) the operand. The difference is that the prefix operator (++i
) evaluates to the incremented value, whereas the postfix operator (i++
) evaluates to the original value.
int i = -1;
System.out.println(+i); // prints -1
System.out.println(i++); // prints -1, then i is incremented to 0
System.out.println(++i); // i is incremented to 1, prints 1