gpt4 book ai didi

java - 将 boolean 值初始化为 false 还是 true 更有效?

转载 作者:行者123 更新时间:2023-12-01 08:01:19 27 4
gpt4 key购买 nike

在 java 中,如果你不初始化一个 boolean 值,它默认为 false。所以如果我说

boolean myFavoriteBoolean = true;

这比工作多吗

boolean myFavoriteBoolean = false;

我的想法是,在第一个示例中,它以 false 开头,并且必须设置为 true 或者事实并非如此?另外,我知道从性能角度来看这是一个没有实际意义的问题,但我之所以这么问,是因为我有兴趣了解 Java 的幕后工作原理。

最佳答案

假设您引用的是 boolean 类型的实例字段,那么答案就在 the JLS chapter regarding instance creation expressions. 中。

The new object contains new instances of all the fields declared in the specified class type and all its superclasses. As each new field instance is created, it is initialized to its default value (§4.12.5).

[...]

Next, the selected constructor of the specified class type is invoked. This results in invoking at least one constructor for each superclass of the class type. This process can be directed by explicit constructor invocation statements (§8.8) and is specified in detail in §12.5.

毕竟the super constructor calls

Execute the instance initializers and instance variable initializers for this class, assigning the values of instance variable initializers to the corresponding instance variables, in the left-to-right order in which they appear textually in the source code for the class. [...]

所以

boolean val = false;
//and
boolean val = true;

行为方式完全相同。

关于java - 将 boolean 值初始化为 false 还是 true 更有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25062789/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com