if you create an instance variable in a class, is the default value true or false until otherwise changed?
Is it good practice to have an instance variable as ex. true then change the value to false and use that variable throughout your class? Or is that something you should conceptually avoid in terms of using instance variables?
The default value of Boolean is False . Boolean values are not stored as numbers, and the stored values are not intended to be equivalent to numbers. You should never write code that relies on equivalent numeric values for True and False .
The default value of the bool type is false .
Boolean variables are displayed as either True or False. Like C, when other numeric data types are converted to Boolean values then a 0 becomes False and any other values become True. When Boolean values are converted to other data types, False becomes 0 while True becomes –1.
Boolean variables are variables that can have only two possible values: true, and false. To declare a Boolean variable, we use the keyword bool. To initialize or assign a true or false value to a Boolean variable, we use the keywords true and false.
If you create an instance variable in a class, is the default value true or false until otherwise changed?
The default value is false
. (JLS 4.12.5)
Is it good practice to have an instance variable as ex. true then change the value to false and use that variable throughout your class?
I assume you mean, is it good practice to define your boolean instance variables so that you can rely on default initialization.
The answer is: No. It is not good practice:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With