There was an error in this gadget

Thursday, June 19, 2008

Code Blocks

A code block in Java is a chunk of code that's surrounded by a matched pair of curly braces: { }

Sometimes the curly braces put people off. They're odd-looking and it's hard to remember where you're supposed to use parentheses ( ), square brackets [ ], angle brackets < > (also known as the less-than and greater-than signs), and all the other odd little bits of punctuation that most folks only ever used for one semester of English class.

Curly braces { } are used to mark the start and end of a piece of code that all works as a piece. If you like, you can think of the opening curly brace { as standing for the word BEGIN to mark the beginning of a section of code. The closing curly brace } would then stand for the work END to mark the end of a section of code. (There are languages that actually use BEGIN and END instead of curly braces, like Pascal and Modula-2.)

In a Java program, there are usually several code blocks. Code blocks can be "nested" with one code block entirely inside another:

public class Hello{
  public static void main(String arg[]){
    System.out.println("Hello.");
  }
}

In this case, the first opening curly brace matches the last closing curly brace (the green ones.) The second opening curly brace, after main(), matches the second-to-last closing curly brace (the red ones.)

Here I've colored the contents of the inner code block red:

public class Hello{
  public static void main(String arg[]){
    System.out.println("Hello.");
  }
}

This would be called the main() code block, since this is the code associated with the main() method.

And here I've colored the contents of the outer code block green:

public class Hello{
  public static void main(String arg[]){
    System.out.println("Hello.");
  }
}

This would be called the Hello class code block, or simply Hello's code block.

Note how the main() code block is entirely within Hello's code block. Because of how Java matches up the curly braces, you can't have one code block "sticking out of" another code block. They always go one entirely inside the other, like nested boxes.

Here's the same program with the BEGIN and END words substituted for the curly braces. This isn't proper Java! It won't compile. It's just a mental exercise:

public class Hello BEGIN
  public static void main(String arg[])BEGIN
    System.out.println("Hello.");
  END
END

Matching pairs are again colored the same.

To make it easier to live with curly braces, there are a lot of editors that will match pairs of curly braces, parentheses, and square brackets for you. Usually you can put your cursor on one, and it will highlight the matching one. Some will "blink" over to the opening character as you type a closing one.
StumbleUpon