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

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

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

8条回答
  •  盖世英雄少女心
    2020-12-01 05:48

    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");
    }
    

提交回复
热议问题