Failure to initialize a local variable will result in an error if the variable has not been initialized and you are in the process of querying it for a result.
Code:
// will produce a warning "variable might not have been initialized"
class T{
public static void main(String[] args){
int i;
System.out.println("The value of i is" + i);
}
}
If the member is declared static and is being accessed from a static context then the default value of the un-initialized member will be displayed. This is because static variables or "class members" are initialzed when the class is loaded by a hidden internal method. If one was to disassemble the byte codes in a java class file you would see the class initialization code in a method named <clinit>.
Code:
class T{
static int i;
public static void main(String[] args){
System.out.println("The value of i is" + i);
}
}
The following code would run fine even though our integer variable has not been initialized. This is because we have
already created an instance of the class X.
Code:
class T{
public static void main(String[] args){
new X().test();
}
}
class X{
int i;
public void test(){
System.out.println("The value of i is" + i);
}
}