Showing posts with label code blocks. Show all posts
Showing posts with label code blocks. Show all posts

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:
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.java
Semicolon.java:4: ';' expected
}
^
1 error
OK, 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.

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{
public static void main(String arg[]){
if (true) System.out.println("argl bargl");
}
}
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?

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{
public static void main(String arg[]){
if (true) {System.out.println("argl bargl")};
}
}
When we hand this to the compiler, it says:
Semicolon.java:3: ';' expected
if (true) { System.out.println("argl bargl") };
^
1 error
OK, so we know it's the System.out.println("argl bargl") that needs the semicolon, not the if part of the program.

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.java
$ java Semicolon
argl bargl
Now, 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.

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:

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);
}
}
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.

Then the compiler get to +c;, and by itself it doesn't make any sense:
BadSemicolon.java:6: not a statement
a=b; +c;
^
1 error

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.

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!
StumbleUpon

The Java Language Manual

The Java language itself, as opposed to the classes, interfaces, and so on, is defined in the Java language specification, which can be found online. You can either view the online HTML version, or download a copy to your own system in several formats from this location:

http://java.sun.com/docs/books/jls/

This describes how Java programs are put together. It's not an easy read, it's written for compiler implementors more than it's written for programmers.

Look for "API, Language, and Virtual Machine Documentation", the link to view or download this document is in that section, titled "The Java Language Specification."

There are a few items of clarity in the document, like the section on Blocks (code blocks.)

For most programmers, especially beginners, the time to refer to this document is when you have a specific question in mind about some code you're writing that doesn't seem to want to compile. If you take a look at it occasionally, however, looking up things that you do understand and feel like you've got a handle on, it'll start making sense. Then you'll be able to make more use of it as your Java programming ability grows.

StumbleUpon

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