In Java how can two different primitive data types such as int a = 3
and byte b = 3
be compared?
I note the size of int
is 4 bytes while byte
is only 1 byte. Is it a bitwise comparison?
It doesn't. It never will.
int a = 3;
byte b = 3;
if (a == b) {
...
}
This is not a comparison between an int
and a byte
. ==
can only compare primitives of the same type. So this is a comparison between an int
and an int
(since int
is the wider of the two). It is equivalent to the following more explicit code.
int a = 3;
byte b = 3;
if (a == (int)b) {
...
}
If you perform any math or bitwise operation on primitive data types that are smaller than int (that is, byte, short, or char), those values will be promoted to int before performing the operation.
Consider the following code snippet and the generated byte code:
int a = 1;
byte b = 1;
if (a == b) {
}
public static main([Ljava/lang/String;)V
L0
ICONST_1
ISTORE 1
L1
ICONST_1
ISTORE 2
L2
ILOAD 1
ILOAD 2
IF_ICMPNE L3
L3
RETURN
As can be seen from the example above, both constants (a, b) are pushed onto the operand stack with the ICONST
instruction as an int
constants.
With a couple of exceptions, conceptually at least, the smaller type is converted to the larger type prior to the comparison being made.
The actual comparison will be typically performed by a machine code instruction directly on the CPU. These days the comparison will not be bit by bit; all the bits will be compared simultaneously.
它通过一个不会丢失信息的扩展过程来执行。
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.