Why boolean in Java takes only true or false? Why not 1 or 0 also?
One thing that other answers haven't pointed out is that one advantage of not treating integers as truth values is that it avoids this C / C++ bug syndrome:
int i = 0;
if (i = 1) {
print("the sky is falling!\n");
}
In C / C++, the mistaken use of =
rather than ==
causes the condition to unexpectedly evaluate to "true" and update i
as an accidental side-effect.
In Java, that is a compilation error, because the value of the assigment i = 1
has type int
and a boolean
is required at that point. The only case where you'd get into trouble in Java is if you write lame code like this:
boolean ok = false;
if (ok = true) { // bug and lame style
print("the sky is falling!\n");
}
... which anyone with an ounce of "good taste" would write as ...
boolean ok = false;
if (ok) {
print("the sky is falling!\n");
}
Java, unlike languages like C and C++, treats boolean
as a completely separate data type which has 2 distinct values: true and false. The values 1 and 0 are of type int and are not implicitly convertible to boolean
.
Because booleans have two values: true
or false
. Note that these are not strings, but actual boolean literals.
1 and 0 are integers, and there is no reason to confuse things by making them "alternative true" and "alternative false" (or the other way round for those used to Unix exit codes?). With strong typing in Java there should only ever be exactly two primitive boolean values.
EDIT: Note that you can easily write a conversion function if you want:
public static boolean intToBool(int input)
{
if (input < 0 || input > 1)
{
throw new IllegalArgumentException("input must be 0 or 1");
}
// Note we designate 1 as true and 0 as false though some may disagree
return input == 1;
}
Though I wouldn't recommend this. Note how you cannot guarantee that an int
variable really is 0 or 1; and there's no 100% obvious semantics of what one means true. On the other hand, a boolean
variable is always either true
or false
and it's obvious which one means true. :-)
So instead of the conversion function, get used to using boolean
variables for everything that represents a true/false concept. If you must use some kind of primitive text string (e.g. for storing in a flat file), "true" and "false" are much clearer in their meaning, and can be immediately turned into a boolean by the library method Boolean.valueOf.
Because the people who created Java wanted boolean to mean unambiguously true or false, not 1 or 0.
There's no consensus among languages about how 1 and 0 convert to booleans. C uses any nonzero value to mean true and 0 to mean false, but some UNIX shells do the opposite. Using ints weakens type-checking, because the compiler can't guard against cases where the int value passed in isn't something that should be used in a boolean context.