Keywords: current

Next: 1.4.6 Singleton Pattern Up: 1.4 The Union and Previous: 1.4.4 Conditional Statements

## 1.4.5 Blocks

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

    {
      s1;
      s2;
      ...
      sn;
    }

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?