next up previous
Next: Singleton Pattern Up: The Union and Composite Previous: Conditional Statements

Blocks

In Java, braces are to aggregate sequences of statements into individual statements. A sequence of statements

{ 
  $s_1$;
  $s_2$;
  ...
  $s_n$;
}
enclosed in braces is called a block. A block is a form of Java statement. The other forms of statements that we have seen so far are variable definitions, assignment statements, conditional statements, and method calls.

Suppose that we wanted to print a message every time the findAddress method failed to match a name in a DeptDirectory. We need to add a statement to the else clause of our conditional statement in the body of findAddress in class Cons. We can accomplish this task by surrounding the return statement in the else clause with braces and inserting our print statement before the return statement as shown below:

String findAddress(String name) {
  if (name.equals(first.getName())) 
    return first.getAddress();
  else {
    System.out.println(first.getName() + " does not match");
    return rest.findAddress(name);
  }
}
Why not insert the print statement after the return statement instead of before?



Corky Cartwright 2004-02-05