1.9.1 Local variables
Keywords: current

Next: 1.9.2 Casts and Static Up: 1.9 Loose Ends Previous: 1.9 Loose Ends

##
1.9.1 Local variables

In Java, method parameters are simply local variables that are intitialized to the corresponding argument values. They are destroyed when the method returns. Within a method, local variable definitions can be inserted as statements in any statement sequence (such as a function body or compound statement). Each such variable is accessible only in program text between its definition and the end of the statement sequence. The local variable is destroyed at the end of this statement sequence. In general, ordinary local variables in Java function exactly like they do in C++

For example, it is convenient in writing a test method for a class to introduce local variables to hold test data values. The following `test` method for the class `DeptDirectory` relies on this technique.

      public static void DDTest(){
        Entry cork = new Entry("Corky","DH 3104","x 6042");
        Entry matthias = new Entry("Matthias","DH 3106","x 5732");
        Entry ian = new Entry("Ian","DH 3102","x 3843");
        DeptDirectory dd = new Cons(ian, new Cons(cork,
          new Cons(matthias, Empty.ONLY)));

        System.out.println("ian " + dd.findAddress("ian") + " " +
          dd.findPhone("ian"));
        System.out.println("cork " + dd.findAddress("cork") + " " +
          dd.findPhone("cork"));
        System.out.println("matthias " + dd.findAddress("matthias")
          + " " + dd.findPhone("matthias"));
      }

Java imposes an important restriction on the use of local variables in anonymous classes. Any local variable mentioned in an anonymous class definition must be declared `final`. In practice, this is not a significant restriction. In fact, most attempted uses of non-`final` local variables in anonymous classes correspond to errors in program logic. In any case where you need to mention a non-final local variable in an anonymous class, you can simply introduce an extra `final` variable with the required value. Ironically, this transformation often converts a logically incorrect program in to a correct one! We will revisit this issue in later in the monograph in connection with programming graphical user interfaces.

Next: 1.9.2 Casts and Static Up: 1.9 Loose Ends Previous: 1.9 Loose Ends