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!
Showing posts with label curly braces. Show all posts
Showing posts with label curly braces. Show all posts
Sunday, July 6, 2008
Monday, June 23, 2008
Those Pesky Semicolons
Sure, it sounds simple: "A semicolon ends a statement." The problem is that when you're new to the language, new to programming, and you sit down at the keyboard and start typing in your own programs from scratch for the first time, what seemed perfectly obvious when you were typing in code from someone else's examples turns weird and murky.
Let's take a look at a program and dink around with the semicolons in it and see what happens. Several versions of the program I'll give here won't compile, so be warned, this article contains non-working examples!
Here's our program, with no semicolons at all:
If you enter and try to compile this program with javac, you'll get the following error:
The place that Java has to have a semicolon is at the end of line 3. When it got to the curly brace on line 4, the compiler saw that it had gotten past the point where it expected a semicolon.
So let's add a semicolon at the end of line 3:
Let's try using a code block with if like this and see what happens. If the if is the statement that needs a semicolon, then we won't need a semicolon after the System.out.println("argl bargl") inside the code block:
I Know How to Spell Banana, I Just Don't Know When to Stop...
OK, so now we've got the minimum number of semicolons that it takes to make our short and simple program to compile. But what about all those other lines? Why don't we need semicolons for them?
Well, the comment (first line here) doesn't need a semicolon because technically it's not part of the program. The compiler ignores it. See Comments.
The second line isn't technically a statement, and neither is the line with main(). The curly braces are the same sort of thing to Java as the semicolon, they are all dividers. The curly braces at the end of the first two lines, and in the last two lines of the program define the code blocks associated with main() and the class Semicolon.
But what if we're programming away and this distinction eludes us? What happens if we just start throwing semicolons around like mad?
Believe it or not, this program compiles and runs just fine:
OK, where will extra semicolons do actual harm to your program? In the middle of a statement, that's where. Here's an example of a bad semicolon:
Then the compiler get to +c;, and by itself it doesn't make any sense:
OK, so a few extra semicolons don't matter. If you just want to get something working in your early days as a programmer and don't want to fuss with semicolons you can throw them in pretty much whenever you think they might be called for and call it a day. If you do that I recommend that once the program is working with too many semicolons in it, that you go back and start taking them out and recompiling to see which ones you didn't need until you get down to just the ones that were really necessary.
Otherwise, I recommend that you only do the ones that you know you need for sure, and when in doubt, leave them out. Then, when you compile, expect to go back into the program and add them where needed. This is a far better approach for learning where you need them than spamming your program with semicolons.
Most of all, have fun!
Let's take a look at a program and dink around with the semicolons in it and see what happens. Several versions of the program I'll give here won't compile, so be warned, this article contains non-working examples!
Here's our program, with no semicolons at all:
public class Semicolon{
public static void main(String arg[]){
System.out.println("argl bargl")
}
}
If you enter and try to compile this program with javac, you'll get the following error:
$ javac Semicolon.javaOK, the compiler is complaining that it got to line 4 and there was no semicolon. Does this mean it expected a semicolon here? No, the compiler tries to make as much sense of your program as it can, and when it gets to the point where it can't make any sense of things any more, it gives you an error message. That means that the place it is saying the error is at is after the place where the actual error lies.
Semicolon.java:4: ';' expected
}
^
1 error
The place that Java has to have a semicolon is at the end of line 3. When it got to the curly brace on line 4, the compiler saw that it had gotten past the point where it expected a semicolon.
So let's add a semicolon at the end of line 3:
public class Semicolon{This program will now compile and run. The statement here that needed a semicolon to end it was System.out.println("argl bargl"). So how can we know that it wasn't the if that needed the semicolon?
public static void main(String arg[]){
if (true) System.out.println("argl bargl");
}
}
Let's try using a code block with if like this and see what happens. If the if is the statement that needs a semicolon, then we won't need a semicolon after the System.out.println("argl bargl") inside the code block:
public class Semicolon{When we hand this to the compiler, it says:
public static void main(String arg[]){
if (true) {System.out.println("argl bargl")};
}
}
Semicolon.java:3: ';' expectedOK, so we know it's the System.out.println("argl bargl") that needs the semicolon, not the if part of the program.
if (true) { System.out.println("argl bargl") };
^
1 error
I Know How to Spell Banana, I Just Don't Know When to Stop...
OK, so now we've got the minimum number of semicolons that it takes to make our short and simple program to compile. But what about all those other lines? Why don't we need semicolons for them?
// The minimum number of semicolons:
public class Semicolon{
public static void main(String arg[]){
if (true) System.out.println("argl bargl");
}
}
Well, the comment (first line here) doesn't need a semicolon because technically it's not part of the program. The compiler ignores it. See Comments.
The second line isn't technically a statement, and neither is the line with main(). The curly braces are the same sort of thing to Java as the semicolon, they are all dividers. The curly braces at the end of the first two lines, and in the last two lines of the program define the code blocks associated with main() and the class Semicolon.
But what if we're programming away and this distinction eludes us? What happens if we just start throwing semicolons around like mad?
// Semicolons are cheap, so I use them everywhere! ;
public class Semicolon{;
public static void main(String arg[]){;
if (true){;
System.out.println("argl bargl");
}; // end of if;
};
};
Believe it or not, this program compiles and runs just fine:
$ javac Semicolon.javaNow, I'm gonna shake my finger at you and say "You really ought to know where the semicolons are supposed to be!", but the fact is that if you accidentally thrown in extras it doesn't hurt. Java sees the extra semicolon as an empty statement, so you can put an extra semicolon anywhere a full statement would have been legal. So, if you accidentally throw a semicolon in at the end of a line where it's not necessary it's not going to hurt anything.
$ java Semicolon
argl bargl
OK, where will extra semicolons do actual harm to your program? In the middle of a statement, that's where. Here's an example of a bad semicolon:
The semicolon that got put in between b and +c is going to hose the program. It's in the middle of an expression, breaking it up into two pieces. The first part, a=b;, makes sense to the compiler. It says "OK, take the value of b and stick it in a!" This isn't what you wanted it to do, but the compiler only knows what you tell it.public class BadSemicolon{
// This program has an error in it! It won't compile!
public static void main(String arg[]){
int a=4;
int b=5;
int c;
a=b; +c;
System.out.println(a, b, c);
}
}
Then the compiler get to +c;, and by itself it doesn't make any sense:
Because the semicolon is a separator, you've separated one statement into two by sticking one in the middle of things. +c is not a statement in Java, as the compiler tells you. So now you know why we don't just throw semicolons around everywhere, like every other character, just to make sure we get all the ones in that we need.BadSemicolon.java:6: not a statement
a=b; +c;
^
1 error
OK, so a few extra semicolons don't matter. If you just want to get something working in your early days as a programmer and don't want to fuss with semicolons you can throw them in pretty much whenever you think they might be called for and call it a day. If you do that I recommend that once the program is working with too many semicolons in it, that you go back and start taking them out and recompiling to see which ones you didn't need until you get down to just the ones that were really necessary.
Otherwise, I recommend that you only do the ones that you know you need for sure, and when in doubt, leave them out. Then, when you compile, expect to go back into the program and add them where needed. This is a far better approach for learning where you need them than spamming your program with semicolons.
Most of all, have fun!
Labels:
code blocks,
curly braces,
semicolons

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.
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.
Labels:
code blocks,
curly braces

Subscribe to:
Posts (Atom)
Subjects:
- Android (3)
- angle brackets (1)
- API (15)
- applet (2)
- application (15)
- arguments (2)
- array (3)
- array initializer (1)
- assignment (3)
- asterisk (2)
- beginner (8)
- book review (4)
- C (1)
- C# (1)
- C++ (1)
- calculations (4)
- classes (8)
- code blocks (3)
- collection (6)
- collision detection (3)
- command line (7)
- Comments (1)
- comparison (3)
- constants (1)
- constructor (2)
- cross-platform (1)
- curly braces (3)
- dates (1)
- declaration (4)
- documentation (3)
- dot notation (1)
- embedded (1)
- environment (11)
- equals (2)
- events (3)
- example (2)
- expressions (2)
- file (3)
- file names (1)
- framework (3)
- generics (2)
- graphics (22)
- graphics Swing CSS (1)
- heavyweight component (1)
- humor (1)
- i/o (3)
- IDE (9)
- import (2)
- inheritance (2)
- initializer (1)
- inner class (5)
- input (5)
- interface (3)
- Java (27)
- Java version (7)
- Javascript (1)
- JDK (5)
- JFrame (6)
- JPanel (7)
- JVM (10)
- lightweight component (2)
- List (3)
- listeners (3)
- literal (1)
- local (1)
- loop (2)
- main() (4)
- Math (3)
- method (4)
- methods (2)
- modulo (1)
- mouse (1)
- name (2)
- numeric (2)
- object code (1)
- objects (3)
- operators (4)
- output (3)
- packages (5)
- paint() (3)
- paintComponent() (4)
- parentheses (1)
- percent sign (2)
- PHP (1)
- public (2)
- read (2)
- reference (8)
- regular expressions (1)
- Resources (5)
- restore (1)
- save (1)
- Scanner (1)
- semicolons (1)
- signature (4)
- source code (4)
- square brackets (1)
- star (1)
- static (2)
- Swift (1)
- System.out.println() (2)
- threads (2)
- trigonometry (1)
- type (8)
- variables (9)
- video game (8)
- virtual machine (2)
- void (2)
- web (2)
- why java (9)