为什么java在本地时要求初始化变量

2022-01-13 00:00:00 types scope type-conversion java

请看下面的代码.方法 printTest() 正在打印未初始化变量的默认值,但是当涉及到 main 方法时,java 要求进行变量初始化.谁能解释一下为什么?

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

  }

推荐答案

局部变量主要用于中间计算,而实例变量应该携带用于未来和中间计算的数据.Java 不强制初始化实例变量并允许默认值,但对于局部变量,开发人员调用它来分配值.所以为了避免错误,你需要初始化局部变量.

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.

相关文章