In some of our companys projects code I often read something like this:
boolean foo = Boolean.FALSE;
Besides the fact that AFAIK I only have to initialize local variables in Java at all (no random values like in Pascal) and besides the fact that especially for booleans I often WANT to have an initialization, what do I miss here? Why not:
boolean foo = false;
I don’t get it. And code analyzation tools like PMD and Findbugs mark it, too. But why?
Edit:
Without really knowing much about the bytecode except that it is there I created an example class and decompiled it. The Boolean.FALSE went to:
0: getstatic #15 // Field java/lang/Boolean.FALSE:Ljava/lang/Boolean;
3: invokevirtual #21 // Method java/lang/Boolean.booleanValue:()Z
6: istore_1
The ‘false’ variant went to:
0: iconst_1
1: istore_1
So without knowing too much about this, I’d guess that more statements means more time to execute so it’s not only wrong but also slower in the long run.
This is strange and unnecessarily complicated code, written by someone who likely didn’t know Java very well. You shouldn’t write code like this, and PMD and FindBugs are right to mark this.
Boolean.FALSEis ajava.lang.Booleanobject that gets auto-unboxed; the compiler essentially translates this to:Member variables do not need to be initialized explicitly; if you don’t, they’ll be initialized with a default value (which is
falsein the case ofboolean). Local variables do need to be explicitly initialized; if you try to use a local variable without initializing it, the compiler will give you an error.