Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default Boolean value in Java [duplicate]

Tags:

java

boolean

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.. :)

like image 232
Ernestas Gruodis Avatar asked Feb 02 '14 09:02

Ernestas Gruodis


People also ask

What is default value for boolean in Java?

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).

What is the default value for a boolean?

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 .

Why default value of boolean is false in Java?

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.

Is 0 or 1 true or false Java?

The same section also says: "The Java Virtual Machine encodes boolean array components using 1 to represent true and 0 to represent false.


1 Answers

All instance and class variables in Java are initialised with a default value:

For type boolean, the default value is false.

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:

  • it introduces unnecessary clutter
  • it may introduce subtle concurrency issues
like image 196
assylias Avatar answered Nov 07 '22 12:11

assylias