I found that prevent forgetting to initialize objects isn't fully covered in Java compiler and/or Sonar warning, I'm using latest Eclipse with latest Sonar plugin.
I'm missing error/warning about not initializing for example for Map
(similarly can be String
)
In the example Class Variable mapStatic
and Member Variable map
, both private and not final and can be declared without initialization and without any error/warning about the NullPointerException
to come.
Although for local variables as mapVar
I get compile error Compile The local variable mapVar may not have been initialized
Obviously Local variables are not assign with default value, but still why compiler/sonar doesn't warn about NullPointerException?
Local variables are slightly different; the compiler never assigns a default value to an uninitialized local variable.
private static Map<String, String> mapStatic; // Missing compile/warning
private Map<String, String> map; // Missing compile/warning
public void put() {
map.put("x", "1"); // NullPointerException
//Map<String, String> mapVar;
//mapVar.put("x", "1"); // Compile The local variable mapVar may not have been initialized
}
static {
mapStatic.put("x", "1"); // NullPointerException
}
Also if I add final
I'll get compile error Compile The local variable map may not have been initialized
.
I found an answer that it won't be in compile time, so how can avoid or found this issues beforehand?
Failing to initialise a value is a logic error on the part of the programmer, and should be caught as soon as possible. Java does this at compile time for locals, but only at runtime (or not at all) for fields.