Check out Manning's Countdown to 2014. Use discount code crdotd14 all month for 50% off every deal.
Big Moose Saloon
 Search | Java FAQ | Recent Topics Register / Login

# what's the integer value for boolean "true"?

Mindy Wu
Ranch Hand

Joined: Jan 12, 2001
Posts: 121
The following example seems to me that boolean value "true" has a value "0" and boolean value "false" has ? (I am not sure is 1 or -1).
public class test1 {
public static void main(String args[]) {
boolean x = true;
int a;
if(x) a = x ? 1: 2;
else a = x ? 3: 4;
System.out.println(a);
}
}
The result is 1, but if I change x=false, then the result is 4.
Can anyone clearify me for this?
Thanks!
Mindy
Manfred Leonhardt
Ranch Hand

Joined: Jan 09, 2001
Posts: 1492
Hi Mindy,
In java, boolean values represent truth values true and false. They are given no numeric values and the compiler will not let them be used as such ...
Let's walk through your example. You seem to be having problems understanding the conditional operator. The code below

can be written long hand as show below.

When we go through the code for x = true we get:
Line 1 --> true so run this section
Line 2 --> true so set a = 1;
When we go through the code for x = false we get:
Line 1 --> false so skip section
Line 4 --> true because Line 1 false
Line 6 --> true so set a = 4
The code doesn't show anything about the numeric value of boolean , it is just an exercise for conditional operators.
Regards,
Manfred.
Mindy Wu
Ranch Hand

Joined: Jan 12, 2001
Posts: 121
Thank so much for your clear explaination, Manfred Leonhardt!

Mindy

subject: what's the integer value for boolean "true"?