如果在类中创建一个实例变量,除非另有更改,否则默认值为true还是false?
将实例变量设置为true,然后将其更改为false并在整个类中使用该变量是好的做法吗?或者从概念上讲,这是您应该避免使用实例变量的东西?
如果在类中创建一个实例变量,除非另有更改,否则默认值为true还是false?
将实例变量设置为true,然后将其更改为false并在整个类中使用该变量是好的做法吗?或者从概念上讲,这是您应该避免使用实例变量的东西?
false
。(JLS 4.12.5)It is good practice to define the instance variables so that they make sense to the reader of the code:
// Good (probably)
private boolean isValid = true;
// Bad (probably)
private boolean isNotValid; // so that I can rely on default init
(Now, it may make your code easier to understand if the variable is negated ... but the point is that you should decide based on what makes the code easy to understand ... not on based exploiting default initialization.)
It is bad practice to spend time worrying about performance issues at this level of granularity. The chances are that performance benefit of avoiding an explicit initialization is insignificant.
isInvalid
或idNotValid
而非isValid
的动机。 - Stephen C
每个类变量、实例变量或数组元素在创建时都会被初始化为默认值(§15.9,§15.10):
对于类型
byte
,默认值为零,即值为(byte)0
。对于类型
short
,默认值为零,即值为(short)0
。对于类型
int
,默认值为零,即值为0
。对于类型
long
,默认值为零,即值为0L
。对于类型
float
,默认值为正零,即值为0.0f
。对于类型
double
,默认值为正零,即值为0.0d
。对于类型
char
,默认值为 null 字符,即值为'\u0000'
。对于类型
boolean
,默认值为false
。对于所有引用类型 (§4.3),默认值为
null
。
when you crate a variable of boolean
public class check {
static boolean b;
public static void main(String args[]) {
System.out.print("The Default Value of Boolean is="+b);
}
}