Why java is asking to initialize the variables whe

2019-01-28 02:11发布

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);
  }

  }

7条回答
老娘就宠你
2楼-- · 2019-01-28 03:02

I THINK, local variables are not loaded to memory as part of JVM classloading, hence no default value assigned to those variables. Since there is no "null" concept for primitives, you should explicitly assign values for local variables.

open for discussion !!

查看更多
登录 后发表回答