I just want to know if there is a difference in Java between:
private boolean someValue;
private boolean someValue = false;
The second line maybe is just a time wasting?
EDIT (SUMMARY):
From the answers I found that there is almost no difference, but:
"Relying on such default values, however, is generally considered bad programming style."
But there are some strong arguments not to do so - see accepted answer below.
EDIT 2
I found that in some cases boolean
value must be initialized, otherwise the code will not compile:
boolean someValue;
if (someValue) { // Error here
// Do something
}
In my NetBeans IDE I got the error - "variable someValue might not have been initialized".
It's getting interesting.. :)
The default value of boolean data type in Java is false, whereas in C++, it has no default value and contains garbage value (only in case of global variables, it will have default value as 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 .
If you declare as a primitive i.e. boolean. The value will be false by default if it's an instance variable (or class variable). If it's declared within a method you will still have to initialize it to either true or false, or there will be a compiler error.
The same section also says: "The Java Virtual Machine encodes boolean array components using 1 to represent true and 0 to represent false.
All instance and class variables in Java are initialised with a default value:
For type
boolean
, the default value isfalse
.
So your two statements are functionally equivalent in a single-threaded application.
Note however that boolean b = false;
will lead to two write operations: b
will first be assigned its default value false
then it will be assigned its initial value (which happens to be false
as well). This may have an importance in a multi-threaded context. See this example of how explicitly setting the default value can introduce a data race.
Relying on such default values, however, is generally considered bad programming style.
I would argue the opposite: explicitly setting default values is bad practice:
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