[英]How primitive long and int comparison happens in Java
long l = 1234;
int i = 1234;
if (l == i) {
System.out.println("equals");
} else {
System.out.println("not equals");
}
My question is are they compared as int
or long
? 我的问题是将它们比较为
int
还是long
?
I think both are int unless we specify 除非我们指定,否则我认为两者都是整数
long l = 1234L;
If someone has a deeper understanding then please explain. 如果有人有更深的理解,请解释。
Since one of the operands of the ==
operator is long
( l
) It compares two long
s after converting i
to long
. 由于
==
运算符的操作数之一是long
( l
),因此它将i
转换为long
后比较两个long
s。
Related JLS quotes: 相关JLS语录:
15.21.1. 15.21.1。 Numerical Equality Operators == and !=
数值相等运算符==和!=
If the operands of an equality operator are both of numeric type , or one is of numeric type and the other is convertible (§5.1.8) to numeric type, binary numeric promotion is performed on the operands (§5.6.2).
如果相等运算符的操作数都是数字类型的 ,或者一个是数字类型的,而另一个是可转换的(第5.1.8节)为数字类型, 则对操作数 (第5.6.2节) 执行二进制数字提升 。
If the promoted type of the operands is int or long, then an integer equality test is performed.
如果操作数的提升类型为int或long,则执行整数相等性测试。
5.6.2. 5.6.2。 Binary Numeric Promotion
二进制数值促销
Otherwise, if either operand is of type long, the other is converted to long .
否则, 如果一个操作数的类型为long,则另一个将转换为long 。
它必须是int
到long
,因为一些大的long值不能在不损失精度的情况下转换为int值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.