59

Is there any reason why Java booleans take only true or false why not 1 or 0 also?

Charles
  • 50,943
  • 13
  • 104
  • 142
GuruKulki
  • 25,776
  • 50
  • 140
  • 201

8 Answers8

62

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.

JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
  • 34
    At the JVM level, boolean, byte, short, char, and int are all treated as ints, and boolean is indeed represented as 0 and 1. So the "not implicitly convertible" is at the Java language level only. – C. K. Young Jan 06 '10 at 18:11
  • 6
    Plus, Java overtly attempts to learn from the past so that entire categories of bugs are removed. e.g. this ranges from the small features (no implicit boolean expressions) to the large (garbage collection) – Michael Easter Jan 06 '10 at 18:13
  • To continue on from Chris's point, it is legal to write char x = (char) 88945; or char y = (char) -489;. – Pops Jan 06 '10 at 18:16
  • 2
    C didn't originally have a bool type, so you had to use 0 or 1. – Powerlord Jan 06 '10 at 18:18
  • 11
    You didn't really answer the question. They asked *why*. – user359996 Oct 29 '10 at 22:37
33

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.

Community
  • 1
  • 1
Andrzej Doyle
  • 102,507
  • 33
  • 189
  • 228
  • 12
    +1: The same reason "x" is not a number, and 123 is not a date. – S.Lott Jan 06 '10 at 18:02
  • 1
    Being specific about this keeps you away from the whole TRUE in VB is -1 and in other langauges true is just NON ZERO. Keeping the boolean field as true or false keeps java outside of this argument. – Shaun Jan 06 '10 at 18:10
18

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.

Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276
  • The last paragraph is actually talking about how boolean converts to `int`, not the reverse. Yes, in C `int foo = (a!=b);` will be 0 or 1. But in C, any non-0 value is "true" in a boolean context. `if(foo)` doesn't check `foo==1`, it checks `foo!=0`. So if you write `if(foo)`, the compiler definitely does handle it. It's only if you do something like `_Bool equal = a & b` that you get in trouble, because `4 & 2 == 0` even though they're both true. I think that was the point you were trying to make. – Peter Cordes Jul 30 '17 at 03:18
16

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");
}
Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
3

Being specific about this keeps you away from the whole TRUE in VB is -1 and in other langauges true is just NON ZERO. Keeping the boolean field as true or false keeps java outside of this argument.

Shaun
  • 4,057
  • 7
  • 38
  • 48
3

On a related note: the java compiler uses int to represent boolean since JVM has a limited support for the boolean type.See Section 3.3.4 The boolean type.

In JVM, the integer zero represents false, and any non-zero integer represents true (Source : Inside Java Virtual Machine by Bill Venners)

sateesh
  • 27,947
  • 7
  • 36
  • 45
  • 4
    This is technically incorrect on three counts. 1) The Java compiler doesn't "represent" booleans. It generates bytecodes. 2) The things that the bytecodes deal with are object fields, abstract stack slots and slots in arrays. In some contexts, the slots that hold `boolean` values map to 32 bit words (on a typical JVM implementation), but that does not mean that the JVM thinks of them as being `ints`. 3) In a `boolean[]`, the slot used to hold one element is 8 bits, not 32. – Stephen C May 17 '12 at 11:44
  • 2
    I would also be wary of relying on a text book as a source on this. The definitive source is what the JVM specification says, not the "spin" that some author puts on it to make it understandable for his intended readers. (I haven't read the book, so don't take this as a criticism of it. It's just a caution ...) – Stephen C May 17 '12 at 11:49
  • @StephenC "expressions in the Java programming language that operate on boolean values are compiled to use values of the Java Virtual Machine int data type" http://docs.oracle.com/javase/specs/jvms/se8/html/jvms-2.html#jvms-2.3.4 – mdewit Dec 08 '16 at 08:16
  • The same section also says: *"The Java Virtual Machine encodes boolean array components using 1 to represent true and 0 to represent false. Where Java programming language boolean values are mapped by compilers to values of Java Virtual Machine type int, the compilers must use the same encoding."* - The first sentence directly contradicts the Bill Venners quote. And the second sentence has an interesting nuance .... – Stephen C Dec 08 '16 at 08:59
  • 1
    The nuance is that it is not saying that a Java compiler must use a the JVM `int` type to represent the Java `boolean` type. Furthermore @mdewit, the text that you have quoted 1) actually only applies to expressions and 2) is descriptive rather than prescriptive. (It doesn't say that a Java compiler **must** compile to the JVM int type.) – Stephen C Dec 08 '16 at 09:07
  • I agree the Bill Venners quote is definitely incorrect. So since the documentation only states that expressions gets compiled to use values of the int data type (I guess int is chosen as it would be the most efficient primitive to use), I would wonder what other methods would be reasonable to use rather than mapping the boolean values as an int. For a boolean array, mapping them as byte makes sense as less space would actually be used, but this concern does not apply to individual values. Anyway thanks for the explanation. – mdewit Dec 08 '16 at 10:37
1

Even though there is a bool (short for boolean) data type in C++. But in C++, any nonzero value is a true value including negative numbers. A 0 (zero) is treated as false. Where as in JAVA there is a separate data type boolean for true and false.

shubhcodegate
  • 123
  • 1
  • 6
-3

In C and C++ there is no data type called boolean. That's why it instead uses 1 and 0 as replacements for true and false values.

In Java, 1 and 0 are of the type int (integer), so it produces an error. Java also has its own boolean values (true and false), with their own boolean data type.

VLAZ
  • 26,331
  • 9
  • 49
  • 67
pratikpchpr
  • 419
  • 5
  • 4
  • C++ has a `bool` type, and `true` and `false` are keywords. C11 has `_Bool`, or you can `#include ` to get `bool`. The difference is that integers and pointer types are implicitly convertible to boolean, so you can write `bool condition = a` instead of `bool condition = (a!=0);`. Or `if(a){}` – Peter Cordes Jul 30 '17 at 03:22