Next: Pieces of a program. Up: Introduction. Previous: About Java.


A basic program

Textbook: Section 2.1

Consider the following program.

import csbsju.cs160.*;

public class Hello {
    public static void run() {
        IO.println("hello world!");
    }
}
This basic program illustrates the overall structure of a Java program.
class definition
    method definitions
        statements
For the moment, think of a class as a program and a method as a sequence of instructions saying what to do. (Over the next few weeks, we'll refine our understanding to be more accurate. But this one will work fine for now.)

(At this point, I want to get my terminology straight. A brace is either '{' or '}'. Some people redundantly call this a curly brace; I won't. A bracket is either '[' or ']'. Some people redundantly call this a square bracket; I won't. A parenthesis is either '(' or ')'.)

The first line of our example program is the following.

import csbsju.cs160.*;
This just says that we're going to use some stuff defined especially for this class. We'll include this line on every program we write throughout this course. Get used to it.

In our example program, we've defined the Hello class. Our definition of the class looks something like this.

public class Hello {
    method definitions
}
We could have named the program whatever we wanted, but the words public class and the set of braces are required. Within the braces, we place whatever method definitions we need.

In this case, we defined its run() method. The definition of the run() method looks like this:

    public static void run() {
        statements
    }
Again, we could have named the method whatever we wanted (we chose run(), but the words public static void and the set of braces are required.

Within the braces of the method, we list the statements that the computer should execute we tell the computer to execute run(). In this case, there's just one statement to execute:

        IO.println("hello world!");
This particular line prints the world ``hello world!'' into a window on the screen.

We could modify the program to do something slightly more interesting. Try modifying the body of the run() method:

    public static void run() {
        IO.println("hello world!");
        IO.println("good-bye");
    }
Now, when we run run(), two things happen: first it prints ``hello world!'' and then it prints ``good-bye''.

For the next several days, we'll be concentrating on what we can put within the body of that method. Don't worry about the rest of the program for now - we'll get to it when it's time.


Next: Pieces of a program. Up: Introduction. Previous: About Java.