If you leave the variable uninitialized, sometimes itβs good to let the compiler verify that it has been assigned in all possible code branches before using it. For example, if you have a complex condition that assigns a variable and should never be null :
String variable; if (conditionA) { if (conditionB) variable = "B"; else variable = "A"; } else { switch (conditionC) { case 1: variable = "C1"; break; case 2: variable = "C2"; break; default: variable = "CD"; break; } } System.out.println(variable.length());
If you forget to assign a variable in one of the branches, the compiler will complain. Since you know that you never assign null , you can safely use a variable without checking it for null . If you initialize the variable with null in the definition, and you forget to set the variable to a value that the compiler cannot check, and you can get a NullPointerException :
String variable = null; if (conditionA) variable = "A"; // NullPointerException if conditionA is false, not check by compiler System.out.println(variable.length());
A variable can also be final, in which case it can only be assigned once. If you initialize it with a default value, it would already be assigned and cannot be reassigned:
final int variable; if (condition) variable = 1; else variable = 2;
source share