Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Boolean to Integer in Java without If-Statements

Tags:

I'm wondering if there's a way to convert a boolean to an int without using if statements (as not to break the pipeline). For example, I could write

int boolToInt( boolean b ){
  if ( b )
    return 1
  return 0

But I'm wondering if there's a way to do it without the if statement, like Python's

bool = True 
num = 1 * ( bool )

I also figure you could do

boolean bool = True;
int myint = Boolean.valueOf( bool ).compareTo( false );

This creates an extra object, though, so it's really wasteful and I found it to be even slower than the if-statement way (which isn't necessarily inefficient, just has the one weakness).

like image 720
en_Knight Avatar asked Jun 01 '13 01:06

en_Knight


People also ask

Can we convert boolean to int in Java?

To convert boolean to integer, let us first declare a variable of boolean primitive. boolean bool = true; Now, to convert it to integer, let us now take an integer variable and return a value “1” for “true” and “0” for “false”. int val = (bool) ?

How do you convert boolean to Java?

To convert String to Boolean, use the parseBoolean() method in Java. The parseBoolean() parses the string argument as a boolean. The boolean returned represents the value true if the string argument is not null and is equal, ignoring case, to the string "true".

How do you convert boolean to text?

JavaScript calls the toString() method automatically when a Boolean is to be represented as a text value or when a Boolean is referred to in a string concatenation. For Boolean objects and values, the built-in toString() method returns the string "true" or "false" depending on the value of the boolean object.


1 Answers

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.

like image 168
assylias Avatar answered Sep 19 '22 02:09

assylias