The Java Course provides a general introduction to programming in Java. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details.

The First Program

Traditionally the first program people write in a new language is called "Hello, World." because all it does is print the words "Hello, World." In Java, this program looks like this:

class Hello {

  // main: generate some simple output

  public static void main (String[] args) {
    System.out.println ("Hello, world.");

Some people judge the quality of a programming language by the simplicity of the "Hello, World." program. By this standard, Java does not do very well. Even the simplest program contains a number of features that are hard to explain to beginning programmers. We are going to ignore a lot of them for now, but I will explain a few.

All programs are made up of class definitions, which have the form:


  public static void main (String[] args) {

Here CLASSNAME indicates an arbitrary name that you make up. The class name in the example is Hello.

In the second line, you should ignore the words public static void for now, but notice the word main. main is a special name that indicates the place in the program where execution begins. When the program runs, it starts by executing the first statement in main and it continues, in order, until it gets to the last statement, and then it quits.

There is no limit to the number of statements that can be in main, but the example contains only one. It is a print statement, meaning that it prints a message on the screen. It is a bit confusing that "print" sometimes means "display something on the screen," and sometimes means "send something to the printer." In this book I won't say much about sending things to the printer; we'll do all our printing on the screen.

The command that prints things on the screen is System.out.println, and the thing between the parentheses is the thing that will get printed. At the end of the statement there is a semi-colon (;), which is required at the end of every statement.

There are a few other things you should notice about the syntax of this program. First, Java uses squiggly-braces ({ and }) to group things together. The outermost squiggly-braces (lines 1 and 8) contain the class definition, and the inner braces contain the definition of main.

Also, notice that line 3 begins with //. This indicates that this line contains a comment, which is a bit of English text that you can put in the middle of a program, usually to explain what the program does. When the compiler sees a //, it ignores everything from there until the end of the line.

In the first lab you will compile and run this program, and also modify it in various ways in order to see what the syntax rules are, and to see what error messages the compiler generates when you violate one.

Last Update: 2011-01-24