Java boolean default value

Just want to know if there is a difference between Java:

private boolean someValue; private boolean someValue = false; 

Perhaps the second line is just a pause in time?

EDIT (SUMMARY):

From the answers I found that there is almost no difference, but:

"However, relying on such defaults is generally considered a bad programming style."

But there are some good reasons not to do this - see the accepted answer below.

EDIT 2

I found that in some cases the 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 an error - "someValue variable may not have been initialized."

This is getting interesting .. :)

+7
java boolean
source share
5 answers

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

For the boolean type, the default value is false .

So, your two statements are functionally equivalent in a single-threaded application .

Note that boolean b = false; will lead to two write operations: b first its default value is false , then it will be assigned its initial value (which will also be false ). This can make a difference in a multi-threaded context. See this example for how explicitly setting a default value can lead to data race.

However, relying on such defaults is generally considered a bad programming style.

I would say the opposite: explicitly setting default values ​​is bad practice:

  • he introduces an unnecessary mess
  • it can introduce subtle concurrency problems
+19
source share

if you did not initialize it, it will be false . therefore there is no difference between the two.

+3
source share

The default value for the boolean type is false , so we can say that there is no difference.

+2
source share

There is no difference from:

http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

It is not always necessary to assign a value when declaring a field. Fields declared but not initialized will be set to a reasonable default compiler. Generally speaking, this default value will be zero or null, depending on the data type. Based on such default values, however, the style is usually considered poor programming.

+1
source share

If you declare as a primitive, i.e. boolean . The value will be false by default if it is an instance variable (or a class variable).

If it is a boolean instance variable, it will be null .

If it is declared as part of a method, you will have to initialize it, or there will be a compiler error.

0
source share

All Articles