Why boolean in Java takes only true or false? Why not 1 or 0 also?

后端 未结 8 1125
太阳男子
太阳男子 2020-12-01 05:28

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

8条回答
  •  -上瘾入骨i
    2020-12-01 05:28

    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.

提交回复
热议问题