Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

  }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
582 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...