Program to demonstrate initialization of local variables and usage in Java
public class LocalFields { public static void main(String[] args) { int local; //uninitialized local variable int field = 10; if(field > 10){ local = 10; } if(field < 10){ local = 11; } if(field == 10){ local = 12; } // below lines throws compile time error because //compiler doesn't computes that which if will execute //it sees that local is been used without being initialized System.out.println("The value of local is : " + local); } }The correct implementation of the program :
public class LocalFields { public static void main(String[] args) { int local= 0; // always initialize local variables // before use int field = 10; if(field > 10){ local = 10; } if(field < 10){ local = 11; } if(field == 10){ local = 12; } System.out.println("The value of local is : " + local); } }Output of the program :