问题描述
只是想知道是否有与Java中的区别:
Just want to know if there is a difference in Java between:
private boolean someValue;
private boolean someValue = false;
第二行也许只是waisting时间?
The second line maybe is just a time waisting?
修改(摘要):
这是我发现有问题的答案几乎没有区别,但是:
From the answers I found that there is almost no difference, but:
的就凭这样的默认值,但通常被认为是不好的编程风格。的
但也有一些强有力的论据不这样做 - 见下面的接受的答案
But there are some strong arguments not to do so - see accepted answer below.
编辑2
我发现,在某些情况下,布尔
值必须初始化,否则code 将无法编译:
I found that in some cases boolean
value must be initialized, otherwise the code will not compile:
boolean someValue;
if (someValue) {//Error here
//Do something
}
在我的NetBeans IDE中我得到了错误 - 变量someValue中可能尚未初始化的
In my NetBeans IDE I got the error - "variable someValue might not have been initialized".
它变得有趣..:)
推荐答案
在Java中的所有实例和类变量被初始化了的:
All instance and class variables in Java are initialised with a default value:
有关键入布尔
,默认值为假
。
所以,你的两个语句在功能上等同 在单线程应用程序的
So your two statements are functionally equivalent in a single-threaded application.
然而要注意布尔B = FALSE;
将导致两个写操作: B
将首先被分配了默认值假
那么它将被赋予其初始值(这恰好是假
以及)。这可具有一个多线程的上下文中的重要性。请参见如何明确设置的默认值可以引入数据争这个例子。
Note however that boolean b = false;
will lead to two write operations: b
will first be assigned its default value false
then it will be assigned its initial value (which happens to be false
as well). This may have an importance in a multi-threaded context. See this example of how explicitly setting the default value can introduce a data race.
依靠这种默认值,但通常被认为是不好的编程风格。
我认为正好相反:明确设置的默认值是不好的做法:
I would argue the opposite: explicitly setting default values is bad practice:
- 它引入了不必要的混乱
- 可能引入微妙的并发问题
这篇关于默认在Java中的布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!