954,518 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Converting boolean to integer

Is there an easy way to convert a simple integer into a boolean type?

orcboyx
Newbie Poster
18 posts since Dec 2007
Reputation Points: 10
Solved Threads: 0
 
Acidburn
Posting Pro
511 posts since Dec 2004
Reputation Points: 12
Solved Threads: 5
 

(i != 0)

Ezzaral
Posting Genius
Moderator
15,986 posts since May 2007
Reputation Points: 3,250
Solved Threads: 847
 

use:

boolean b;
int iSomeValue;

b=true;
if(iSomeValue==0)b=false;

or use function

boolean intToBool(int iVal)
{
 boolean b=true;
 if(iVal==0)b=false;
 return b;
}
DangerDev
Posting Pro in Training
485 posts since Jan 2008
Reputation Points: 165
Solved Threads: 59
 

That is a lot more code than is needed. The conversion only needs the evaluation of intVal!=0, so the function reduces to

boolean intToBool(int value){
  return (value != 0);
}
Ezzaral
Posting Genius
Moderator
15,986 posts since May 2007
Reputation Points: 3,250
Solved Threads: 847
 

Thanks for the help, by th way i used ezzral's method it was quick and simple, i also found out i could've just started with a boolean by setting random generator class to boolean type.

orcboyx
Newbie Poster
18 posts since Dec 2007
Reputation Points: 10
Solved Threads: 0
 

Use

int intVal = (boolVal) ? 1 : 0;
Member 784921
Newbie Poster
1 post since Jul 2010
Reputation Points: 10
Solved Threads: 0
 

Why do you want to convert a boolean to an int.

It makes no sense. A boolean has 2 values, an int has billions.
Why would one of the billion values be true and another be false?
0 and NOT 0 are C concepts. Nothing in java corresponds.

NormR1
Posting Expert
Moderator
6,677 posts since Jun 2010
Reputation Points: 1,138
Solved Threads: 656
 

This thread has been solved but I would also like to add a small suggestion. If for some reason you want to use ints for boolean expressions, why don't you make a class for it. Call it: BoolInt. Have it have one int private attribute and with the help of public set methods make sure that the only valid values are 1 and 0 (or whatever you want)

class BoolInt {
  public static final int INT_TRUE = 1;
  public static final int INT_FALSE = 0;

  public BoolInt() {
  }

  private int i = INT_FALSE;

  public int getIntValue() {
     return i;
  }

  public boolean getBoolValue() {
     return i==INT_TRUE;
  }

  public void setIntValue(int i) throws Exception {
     // if the user doesn't enter 1 or 0 throw exception
     if (i!=INT_TRUE || i!=INT_FALSE) throw new Exception("your message");

     this.i=i;
  }

  public void setBoolValue(boolean b) {
     i = (b)?INT_TRUE:INT_FALSE
  }
}
javaAddict
Nearly a Senior Poster
Team Colleague
3,329 posts since Dec 2007
Reputation Points: 1,014
Solved Threads: 448
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You