There was an error in this gadget

Sunday, July 6, 2008

Parens and Brackets and Braces, Oh My!

If you paid attention in English class when they were discussing the use of parentheses, curly braces, square brackets and so on I'm afraid it won't do you much good in Java. Java has a specific use for each of these, and it definitely pays to get then sorted out.

Knowing the names for each of the symbols is a good starting point:

{ } are curly braces.
( ) are parentheses (one is called a parenthesis.) Parens or paren for short.
[ ] are square brackets.
< > are called angle brackets. They're the same characters as the less than and greater than signs.

The first one of any pair is called the "opening" item; opening curly brace, opening parenthesis, etc. The second of a pair is called the "closing" item; closing square bracket, closing paren, and so on.

{ }
We discussed curly braces in Code Blocks, and mentioned briefly that they are a form of divider in Java in Those Pesky Semicolons. Curly braces mark the start and end of a code block.

Hold the phone! There's another use of curly braces. They can also be used to enclose a list that is used as an array initializer. For example:
int nums[] = {1, 2, 3};
This line declares an array named nums[] and initializes its first three elements to values 1, 2, and 3.

( )
Parentheses happen a lot in Java. They mark the start and end of the parameter list of a method. This includes both constructor methods and instance methods. The parameter list contains the information that is passed to the method to let the method do its job. If the method doesn't need any information, the parens are still there, there's just nothing between them: println(). A pair of parens at the end of a name is an easy way of identifying a method.

[ ]
Square brackets are used to enclose the "indexing expression" of an array. If you see square brackets, it's an array.

< >
When <> are not playing the part of "less than" and "greater than" they enclose the indexing expression of a collection. Collections are like arrays but considerably more flexible in the things they can do. Consider them as a sort of "super array."

There you are. Now you're prepared to punctuate your Java programs with the best of them, and hopefully you'll be able to read Java programs more easily. If you get into a dispute with your English teacher over these symbols, though, you're on your own!
StumbleUpon