Java 的默认值是布尔值“真”吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6048313/
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
Is Java's default value for Boolean 'true'?
提问by camiloqp
Why does private Boolean shouldDropTables;
assign true
by default to the variable instead of NULL
, like when writing private Integer anInteger;
?
为什么在默认情况下private Boolean shouldDropTables;
分配给true
变量而不是NULL
像写入时一样private Integer anInteger;
?
I am asking because I came across some code where there was an evaluation on a shouldDropTables
Boolean variable being NULL
or not determining whether to execute a method.
我问是因为我遇到了一些代码,其中对shouldDropTables
布尔变量的评估正在NULL
确定是否执行一个方法。
回答by nicholas.hauschild
Boolean (with a uppercase 'B') is a Boolean object, which if not assigned a value, will default to null. boolean (with a lowercase 'b') is a boolean primitive, which if not assigned a value, will default to false.
Boolean(带有大写的“B”)是一个布尔对象,如果没有赋值,则默认为 null。boolean(带有小写的 'b')是一个布尔基元,如果没有赋值,默认为 false。
Boolean objectBoolean;
boolean primitiveBoolean;
System.out.println(objectBoolean); // will print 'null'
System.out.println(primitiveBoolean); // will print 'false'
回答by Jigar Joshi
No.
不。
Boolean is null
by default.
null
默认情况下为布尔值。
回答by sgokhales
It's NULL by default. Because it's a Boolean Object.
默认为 NULL。因为它是一个布尔对象。
Object 'Boolean' = NULL value // By default,
Primitive type 'boolean' = false value // By default.
回答by OscarRyz
Perhaps you're not seeing some initialization.
也许您没有看到一些初始化。
It has null by default. See this sample:
默认情况下它为空。请参阅此示例:
$ cat B.java
class B {
private Boolean shouldDrop;
public static void main( String ... args ) {
System.out.println( new B().shouldDrop );
}
}
$ javac B.java
$ java B
null
I hope that helps
我希望有帮助
回答by sakura
I just wanted to add one point (for beginners) regarding a primitive boolean
variable.
我只想就原始boolean
变量添加一点(对于初学者)。
As @99tm answered, the default value is "false". This is correct for instance or class variables.
正如@99tm 所回答的,默认值为“false”。这对于实例或类变量是正确的。
If you have a method local variable (i.e. local to a method) as a primitive boolean
, there is no default value and it is not an Object
so it also cannot be null.
如果您有一个方法局部变量(即方法的局部变量)作为原始boolean
值,则没有默认值并且它不是 an,Object
因此它也不能为 null。
You must initialize it before using it, otherwise it's a compilation error.
使用前必须初始化,否则编译错误。
回答by Roland
JLS 9, 4.12.5. Initial Values of Variables
For type boolean, the default value is false.
For all reference types (§4.3), the default value is null.
对于类型 boolean,默认值为 false。
对于所有引用类型(第 4.3 节),默认值为 null。
Boolean
is a reference type, therefore the default value is null
.
Boolean
是引用类型,因此默认值为null
。