What is the third boolean state in java?

谁说我不能喝 提交于 2020-01-01 23:13:05

问题


While I know that by definition a boolean consists of only two states, true or false. I was wondering what value does a boolean have before it is initialized with one of these states.


回答1:


It defaults to false.

Edit: By popular demand:

unless you're using the wrapped Boolean, which defaults to null. – sudhir.j




回答2:


If it is a local variable, it is a compiler error to reference it before it was initialized. If it is a field, it is initialized to false.




回答3:


public class NewMain {

    boolean foo;
    Boolean bar;

    public static void main(String[] args) {
        NewMain obj = new NewMain();

        obj.whatBoolean();
    }

    public void whatBoolean() {
        System.out.println(foo);
        System.out.println(bar);
    }
}

outputs

false
null

I know this was more philosophical of a question, but thanks to autoboxing you can use Java as a almost truly OO language (I hate having primitive types... now only if it would work in reverse too). It does, however, change the behavior when you use an object (for the better IMO).




回答4:


There is no third state. As @Yishai said, if you don't assign a value, boolean fields default to false. Local variables must be assigned before use:

Accessing an uninitialized local variable will result in a compile-time error

See the doc.




回答5:


In JAVA boolean types default to False.




回答6:


FYI, boolean defaults to false, primitive numbers default to 0, 0L, 0f or 0d as appropriate, char defaults to '\0', Object references (such as Boolean) default to null.

This also applies to the contents of arrays. (A common gotcha is that an array of Objects is initially full of null values)




回答7:


It is false




回答8:


If you had something like

boolean isTrue;

System.out.println(isTrue);

You should get a compile time error because the boolean wasn't initialized. By default when you try to initialize this it will be set to false;



来源:https://stackoverflow.com/questions/952169/what-is-the-third-boolean-state-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!