Converting Boolean to Integer in Java without If-Statements

You can't use a boolean other than in a if. However it does not mean that there will be a branch at the assembly level.

If you check the compiled code of that method (by the way, using return b ? 1 : 0; compiles to the exact same instructions), you will see that it does not use a jump:

0x0000000002672580: sub    $0x18,%rsp
0x0000000002672587: mov    %rbp,0x10(%rsp)    ;*synchronization entry
0x000000000267258c: mov    %edx,%eax
0x000000000267258e: add    $0x10,%rsp
0x0000000002672592: pop    %rbp
0x0000000002672593: test   %eax,-0x2542599(%rip)        # 0x0000000000130000
                                                ;   {poll_return}
0x00000000025b2599: retq  

Note: this is on hotspot server 7 - you might get different results on a different VM.


Use the ?: operator: ( b ? 1 : 0 )