Unit 3 (Prog 1) : Test Initialization of Local and Instance Variables.

By | June 27, 2013

In this example, you will find the details and concept of Local and class variables, initialization and their scope.

/*
 * local variable must be initialized before attempt to use them.
 * Java will initialize instance variable for you !!!
 * Java does not give local variable a default value.
 */

public class TestInit {

   int i; // initialized with 0
   String str; // initialized with null
   float f; // initialized with 0.0f

   public void testMethod() {
      // initializing local variables.
      String localStr = null;
      int localInt = 0;
      float localFloat = 0.0f;
      System.out.println("instance variable String : " + str);
      System.out.println("instance int i : " + i);
      System.out.println("instance float : " + f);
   }

   public void anotherTestMethod() {
      String str;

      // following code, after removing comment, upsets the compiler. local 
      variable must be initialized.
      /*
      if (str != null) { // to the compiler, null is a value.
         System.out.println(str);
      }

      // what about this ?
      if(this.str != null) {
         System.out.println(str);
      }
      */
   }

   public static void main(String a[]) {

      TestInit test = new TestInit();
      test.testMethod();
      test.anotherTestMethod();
   }
}
email

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.