简体   繁体   中英

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 ?

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 .

Related JLS quotes:

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).

If the promoted type of the operands is int or long, then an integer equality test is performed.

5.6.2. Binary Numeric Promotion

Otherwise, if either operand is of type long, the other is converted to long .

它必须是intlong ,因为一些大的long值不能在不损失精度的情况下转换为int值。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM