I have read several previously asked questions and answers on this topic [or quite similar], but none of them have really addressed this point-blank. When declaring a new boolean varibale, is it redundant [e.g. unnecessary] to initialize it to false?
boolean selectedZone = false;
versus just declaring
boolean selectedZone;
The other posts I have looked at are Why is Java's default value for Boolean set to true? and Default value of Boolean in java
Notice that the boolean in the if-test (true or false) happens to be the same as the value we want to return. If the test value is true, we return true. If the test value is false, we return 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. Boolean values are not actually stored in Boolean variables as the words “true” or “false”.
The default value of any Object , such as Boolean , is null . The default value for a boolean is false.
A Boolean variable has only two possible values: true or false. It is common to use Booleans with control statements to determine the flow of a program.
It is redundant in most cases. The exception is if it's a local variable, in which case it needs to be initialized before being used. Examples:
class Example{
boolean value1;//valid, initialized to false
public void doStuff(){
boolean value2;//valid, but uninitialized
System.out.println(value1);//prints "false" (assuming value1 hasn't been changed)
System.out.println(value2);//invalid, because value2 isn't initialized. This line won't compile.
Some documentation on this: https://web.archive.org/web/20140814175549/https://docs.oracle.com/javase/specs/jls/se5.0/html/typesValues.html#96595
Even though variables are initialized, you still might want to explicitly declare their initial values. It can make the code more legible, and lets people reading your code know that it's a conscious decision to set it to that value.
Related
It is redundant, but I find it clearer.
The same goes for :
int var = 0;
vs.
int var;
I didn't make this up :
Default Values
It's not always necessary to assign a value when a field is declared. Fields that are declared but not initialized will be set to a reasonable default by the compiler. Generally speaking, this default will be zero or null, depending on the data type. Relying on such default values, however, is generally considered bad programming style.
The following chart summarizes the default values for the above data types.
Data Type Default Value (for fields)
byte 0
short 0
int 0
long 0L
float 0.0f
double 0.0d
char '\u0000'
String (or any object) null
boolean false
(Source)
However, as the comments suggest, if it's a local variable, it must be initialized.
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