next up previous
Next: Casts and Static Type Up: Loose Ends Previous: Loose Ends


Local variables

Method parameters in Java play exactly the same role as function parameters in Scheme. They are local variables bound to the corresponding argument values. They are destroyed when the method returns.1.8 Java also provides a mechanism, akin to Scheme's local construct, for introducing local variables to perform a subcomputation without invoking a helper method. In Java, 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.

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

class TestDeptDirectory {
  public static void testDeptDirectory(){
    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 up previous
Next: Casts and Static Type Up: Loose Ends Previous: Loose Ends
Corky Cartwright 2004-02-05