Java – set Boolean value to false redundancy?

I have read several previous questions and answers [or very similar] on this topic, but none of them really solve this When declaring a new boolean variable, it is redundant [for example, unnecessary] to initialize it to false?

boolean selectedZone = false;

Instead of announcing

boolean selectedZone;

Why is Java's default value for Boolean set to true? And default value of Boolean in Java

Solution

In most cases, it is redundant The exception is that it is a local variable, in which case it needs to be initialized before use example:

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 about this: https://web.archive.org/web/20140814175549/https://docs.oracle.com/javase/specs/jls/se5.0/html/typesValues.html#96595

Even if a variable is initialized, you may want to declare its initial value explicitly It can make the code clearer and let people know that setting it to this value is a conscious decision when reading the code

Related

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>