This question already has answers here:
What is the purpose of Java's unary plus operator?

(7个答案)


6年前关闭。




我在查看同事的代码时遇到了这个问题。她无意中把它留了下来(它曾经是一个字符串连接),我以为它不会编译。原来我错了,所以我尝试看看那个运算符(operator)做了什么:
public static void main(String[] args) {
    int i = -1;
    System.out.println(String.format("%s", +i));
    System.out.println(String.format("%s", +i));
}

据我所知,它什么也没做,但是我很好奇它是否有理由被编译。该运算符(operator)有一些隐藏的功能吗?它类似于++i,但是您会认为编译器会否定+i

最佳答案

那就是plus unary operator + 。它基本上执行numeric promotion,因此“如果操作数是编译时类型byteshortchar,则将其提升为int类型的值”。

另一个一元运算符是增量运算符++,它将值增加1。可以在操作数(prefix operator)之前或之后(postfix operator)应用增量运算符。区别在于前缀运算符(++i)评估为增加的值,而后缀运算符(i++)评估为原始值。

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

09-30 18:00
查看更多