next up previous
Next: 1.5.3 Unchecked Exceptions Up: 1.5 Loose Ends Previous: 1.5.1 Static members

1.5.2 Local variables

Method parameters play exactly the same role in Java as function parameters do in Scheme. They are simply local variables that are bound to the corresponding argument values. They are destroyed when the method returns. (In Scheme, this statement is false in general; local variables continue to exist as long as a ``closure'' referring to them exists.) Like Scheme, Java provides a mechanism for introducing local variables to perform a subcomputation without invoking a help method. In Java, local variables 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 sequence.

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

  public static void main(){
    Entry cork = new Entry("Corky","DH 3104","x6042");
    Entry matthias = new Entry("Matthias","DH 3106","x5732");
    Entry ian = new Entry("Ian","DH 3102","x3843");
    DeptDirectory dd = new Cons(ian, new Cons(cork, 
      new Cons(matthias, Empty.soleInstance)));
    System.out.println("ian " + dd.findOffice("ian") + " " + dd.findPhone("ian"));
    System.out.println("cork " + dd.findOffice("cork") + " " + dd.findPhone("cork"));
    System.out.println("matthias " + dd.findOffice("matthias") + " " + 
      dd.findPhone("matthias"));
  }



Robert Cartwright, Spring 1999