Next: Running a program on
Up: 1 Programming Basics
Previous: Computer programs and java
Contents
We will start right away with a look at a Java program.
For most of this course all your programs will have the same basic
structure, which is reproduced below. This contains all the essential
parts of code that must be included in any program.
public class Simple
{
public static void main(String[] argv)
{
//some program code goes here
}
}
So what does this all mean?
- public class Simple
-
Java programs are made
up of classes, so the first line says that we are going to
define a a class and we have chosen to call it Simple, though
of course you could call it another name. (The convention is for
class names to start with a capital letter.) The class Simple is
everything contained within the outermost set of curly brackets {}.
The purpose of the word public is something we will come to
later; in the meantime you should always use it.
- public static void main(String[] argv)
-
Classes contain methods, and this line (3) is the start of the
method called main. When the computer runs any Java
program it starts by looking for the main method and carries out
whatever the instructions are within it. All programs must contain
one (and only one) main method.
- lines 4-6
-
Instructions for what the main
method should do are in the form of some Java code which goes
in the main method -- i.e. within the corresponding set of curly
brackets, {}
. The //some... part on line 5 is called a
comment, a note to yourself or others reading the file which
is ignored by the computer. There are other ways to write comments
which will be covered soon.
Also note how within the class all the other lines have been indented
by four spaces, and within the method everything is indented by a
further four spaces. The spaces don't have any effect in the program
-- they are just used to make the structure of the program clearer to
see at a glance. You may also use blank lines occasionally for
clarity as well.
Next: Running a program on
Up: 1 Programming Basics
Previous: Computer programs and java
Contents
RHUL Dept. of Physics