As it said in JVMS8
:
Although the Java Virtual Machine defines a boolean type, it only provides very limited support for it. There are no Java Virtual Machine instructions solely dedicated to operations on boolean values. Instead, expressions in the Java programming language that operate on boolean values are compiled to use values of the Java Virtual Machine int data type.
Indeed, these two methods:
boolean expr1(boolean a, boolean b) {
return a || b;
}
int expr2(int a, int b) {
return ((a != 0) || (b != 0)) ? 1 : 0;
}
will produce the same byte code (except the method signatures)
boolean expr1(boolean, boolean);
Signature: (ZZ)Z
Code:
0: iload_1
1: ifne 8
4: iload_2
5: ifeq 12
8: iconst_1
9: goto 13
12: iconst_0
13: ireturn
int expr2(int, int);
Signature: (II)I
Code:
0: iload_1
1: ifne 8
4: iload_2
5: ifeq 12
8: iconst_1
9: goto 13
12: iconst_0
13: ireturn
So, I do not understand why JVM
needs boolean
type. Is it just for the runtime check of method signatures?
As minimum it is needed to support methods overloading. Say, we have two methods in the same class
boolean a(boolean x) {...}
and
boolean a(int x) {...}
They can have different internal logic, so in the byte code they should be distinguished by their signatures.