Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why java is asking to initialize the variables when it is local

Please see the code below. The method printTest() is printing the default value of the uninitialized variables but when it's comes to main method java is asking for variable initialization. Can anybody explain why?

   public class Test1 {

    public static void main(String[] args) {   
      int j;
      String t;

      System.out.println(j);
      System.out.println(t);
    }
  }


  public class Test2 {

   int i;
   String test;

  public static void main(String[] args)   {   
    new Test().printTest();
  }

   void printTest()   {
     System.out.println(i);
     System.out.println(test);
  }

  }
like image 325
Ashok kumar Avatar asked Oct 18 '13 07:10

Ashok kumar


2 Answers

Local variables are used mostly for intermediate calculations whereas instance variables are supposed to carry data for calculations for future and intermediate as well. Java doesnt forces to initialize instance variable and allows default value but for local variables its the developers call to adssign the value. So to avoid mistakes you need to initialize local variables.

like image 59
Vineet Kasat Avatar answered Oct 19 '22 14:10

Vineet Kasat


This is a problem with what the compiler can know about.

In the case of the Main Method, the compiler knows for sure that the variables have not be initialized.

But in the case of the printTest method, the compiler does know that the could be some other method (or same package class) which initializes the class variables.

like image 40
Scary Wombat Avatar answered Oct 19 '22 15:10

Scary Wombat