Does a boolean set false false?

I read several previously asked questions and answers on this topic [or quite similar], but none of them really addressed this question. When declaring a new Boolean variation, is it redundant (for example, it is not necessary] to initialize it to false?

boolean selectedZone = false; 

against just an announcement

 boolean selectedZone; 

Other posts I've looked at are Why is the default value for Boolean set to true? and default value for boolean in java

+6
source share
4 answers

In most cases, it is redundant. The exception is a local variable, in which case it must be initialized before use. 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 documents on this subject: https://web.archive.org/web/20140814175549/https://docs.oracle.com/javase/specs/jls/se5.0/html/typesValues.html#96595

Although the variables are initialized, you can still explicitly declare your initial values. This can make the code more understandable and allows people reading your code to know that it is a conscious decision to set it for this value.

Related

+6
source

This is redundant, but I find it clearer.

The same goes for:

 int var = 0; 

vs.

 int var; 

I did not do it:

Default values

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.

The following table shows the default values ​​for the above 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 follows from the comments, if it is a local variable, it must be initialized.

+3
source

Yes, you can explicitly skip it to false , but just because you can doesn’t mean what you need.

Explicitly setting to false makes the code much clearer (and easier for developers coming from other languages ​​where this behavior is not the default).

+2
source

Fields and components of the array are initialized to zero, local variables are not. See JLS: http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.12.5

+1
source

Source: https://habr.com/ru/post/972712/


All Articles