Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a boolean instance variable default value true or false

  1. if you create an instance variable in a class, is the default value true or false until otherwise changed?

  2. 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?

like image 648
Jessica M. Avatar asked Feb 22 '14 06:02

Jessica M.


People also ask

Is Boolean Default True or false?

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 .

What is the default value of instance boolean variable?

The default value of the bool type is false .

What is the correct value for Boolean variable True or 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.

Are Boolean variables initialized to TRUE?

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.


1 Answers

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.

like image 181
Stephen C Avatar answered Sep 22 '22 04:09

Stephen C