java中的第三个布尔状态是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/952169/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the third boolean state in java?
提问by soldier.moth
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.
虽然我知道根据定义,布尔值只包含两种状态,真或假。我想知道布尔值在用这些状态之一初始化之前有什么值。
采纳答案by Adam Paynter
Edit:By popular demand:
编辑:根据大众需求:
unless you're using the wrapped Boolean, which defaults to null. – sudhir.j
除非您使用包装好的 Boolean,它默认为 null。– sudhir.j
回答by Yishai
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.
如果它是一个局部变量,在它被初始化之前引用它是一个编译器错误。如果是字段,则初始化为false。
回答by Matthew Vines
In JAVA boolean types default to False.
在 JAVA 中布尔类型默认为 False。
回答by JeffH
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:
没有第三种状态。正如@Yishai 所说,如果你不赋值,布尔字段默认为 false。局部变量必须在使用前赋值:
Accessing an uninitialized local variable will result in a compile-time error
访问未初始化的局部变量将导致编译时错误
See the doc.
请参阅文档。
回答by NinethSense
It is false
这是假的
回答by ist_lion
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;
您应该收到编译时错误,因为布尔值未初始化。默认情况下,当您尝试初始化它时,它将被设置为 false;
回答by Trey
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).
我知道这是一个更哲学的问题,但是由于自动装箱,您可以将 Java 用作几乎真正的 OO 语言(我讨厌原始类型......现在只有它也可以反向工作)。但是,它确实会在您使用对象时更改行为(为了更好的 IMO)。
回答by Peter Lawrey
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.
仅供参考,boolean 默认为 false,原始数字默认为 0、0L、0f 或 0d(视情况而定),char 默认为 '\0',对象引用(例如 Boolean)默认为 null。
This also applies to the contents of arrays. (A common gotcha is that an array of Objects is initially full of null values)
这也适用于数组的内容。(一个常见的问题是对象数组最初充满空值)