Java中的"+ i"是什么意思? [英] What does '+i' mean in Java?

查看:70
本文介绍了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.可以在(

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

这篇关于Java中的"+ i"是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆