Your First Program

There comes a time in every programming course where you've got to stop talking in general about things and cut straight to the code. But before we do that, we've got to choose a particular programming language to use.

There are hundreds of programming languages to choose from (maybe more) - the more popular ones that you might have heard of are C, C++, Smalltalk, Squeak, Pascal, Delphi, Basic, Visual Basic, Eiffel, Ada, Cobol, Perl, Python, Fortran, Logo, Lisp, Scheme, Prolog and Haskell. The list goes on into ever more surreally chosen words and acronyms, each with different strengths and weaknesses and its own crowd of fanatical supporters.

The one we're going to use to illustrate the concepts in this course is called Java. It's caused quite a stir (no coffee-related pun intended) in the programming community recently because it has several very nice features that make it ideal for writing programs for the internet. However, we won't bore you with those, suffice it to say that it's:

  1. very popular,
  2. very powerful, and
  3. easier than C++.

Hello World

In a tradition that goes back many tens of years, your first program will be called "Hello World". Its requirements are simple - it must be simple. Its specification is simple - when run, it will display the words "Hello World!". Its design is simple - BEGIN, PRINT "Hello World!", END. And here's the code:

public class HelloWorld
  {
  public static void main( String[] args )
    {
    System.out.println( "Hello World!" );
    }
  }

Well it's almost simple...

You can think of the first line as telling the computer what you're going to call your program. In actual fact it does a little bit more than that - but again, we'll come back to that.

The second line is just a squiggly bracket, or brace to give it it's technical name. Braces always come in pairs: an open and a close brace; a brace of braces. They mark the beginning and end of a block of code of some sort. In this case the closing brace of this pair is the one on the last line of the code and they mark the beginning and end of the program.

The third line is rather more complicated to look at, but actually, it's simply a marker to tell the computer where to start from - the main entry point. They could have used something like 'Hey Computer, Start HERE!' instead, but that's programmers for you.

The fourth line is another brace that marks where to begin obeying the programs instructions. The computer will start at that brace and do everything you tell it to until it reaches the corresponding close brace (on the second to last line) and then it will stop. This set of instructions is referred to as the main method (or sometimes as main function or main procedure) because it's where everything happens.

The fifth line contains the meat of our program - it's a line that tells the computer 'System' to display a line of text 'out.println'. The bit in the round brackets (or parentheses) and the double quotation marks tells it what to display: 'Hello World!'. And then finally the semi-colon (;) tells the computer that that's the end of that instruction and that it should look for another. Java uses semi-colons like we use full-stops.

The next line though is the closing brace of the main method, and so the program will end.

The final line just ends the program definition.

You're now going to have a go at compiling and running it - bet hey, at least testing whether it works should be simple.


Compiling and Running

At this point I'm afraid I'm going to have to apologise in advance about not necessarily being able to give you accurate information about how to do this, as it will depend greatly on what sort of computer system you are using and who set it up. However, I'll give it a bash and if you get stuck ask somebody who looks like they know what they're doing to help you - but watch everything they do and take careful notes. Then next time, and every time afterwards, you'll be able to look like you know what you're doing too!

There are four stages to this process:

  1. Setting Up Your Java Environment
  2. Saving the Program in a Source File
  3. Compiling the Source File
  4. Running the Compiled Program

I'm going to give three different explanations, one for using the Java Development Kit on a Unix workstation in the Computer Science Department, one for using the Java Development Kit on a PC running Windows 95 or NT, and one very vague one about how to use a Java Development Environment like Java Workshop, Visual Cafe or Visual J++.

Setting Up Your Java Environment

The first thing you will need to do is set up your Java environment - this step basically involves telling your computer where it can find the Java compiler and other bits and bobs. You usually only have to do this once per programming session.

Unix

In an xterm window, at the prompt (which should look something like a greater than (>) or percent (%) sign) type:

setup Java

On other Unix systems you may have to type something like source /usr/scripts/JavaSetup or setenv PATH ${PATH}:/usr/java/bin

Windows 95/NT

Depending on how Java is installed on your computer, you may find that your Java environment is set up automatically (through the use of autoexec.bat or NT environment variables for those who need to know the details). However, if it's not you will need to get someone 'who knows PCs' to help you set things up.

In either case, you'll need to open a window that you can type commands into: use Start...->Programs to start either an MS-DOS Prompt (on Win95) or a Command Prompt (on WinNT). Type doskey and press RETURN - this will help you to correct mistakes in your typing more easily.

For the adventurous among you who don't have their environment set up automatically, you'll need to type something like set PATH=%PATH;C:\jdk\bin.

Development Environment

This one's easy - just start your development environment.

Saving the Program in a Source File

The second thing you need to do is to create a text file with your program in it. This is where you need to use a text processor - this is a bit like a word processor in that you can type and edit words in it, but it won't let you do things like use different fonts or centre stuff. For Java, you need to note that the source file needs to have the same name as your program, except with ".java" tagged on the end. So for our HelloWorld program, we need to save the file as "HelloWorld.java".

Unix

Start a text editor - you could use something like xemacs, textedit or axe. To start them, type their name at the xterm prompt. Create a new document, and type (or copy and paste using the middle mouse button) the program into it, save the document under the appropriate filename. Make sure you know where you've saved it to - which directory it's been saved into.

Windows 95/NT

Again, start a text editor like Accessories->Notepad or TextPad (which can be downloaded from the Internet). Again, type or copy and paste the program into a new document and save it with the appropriate name. Again make sure you note where you've saved it - which folder was it saved into.

Development Environment

This one's slightly more complicated. Most development environments like you to create a new project for each new program you wish to write, so try to find a menu item like that. Then when it asks you what to call the project, tell it the name of the program (without the ".java" bit).

Also, look closely at what type of project it's going to create for you - it'll probably give you a choice and it's most likely to default to something called an "applet". You want to change that type to a "Java Application" or something similar. You also don't want it to give you an Graphical User Interface (GUI) or use the Abstract Windowing Toolkit (AWT) yet - you're only going to be using simple console input and output for now.

Once you've done that and clicked okay, it'll save it and open up a barrage of windows - one of those should be the text editor (with the title "HelloWorld.java", and if you're lucky, it may already have written some of your program for you. Type, or copy and paste the rest into place and save it.

Compiling the Source File

This is the point at which you submit your program to the compiler to translate it into computer-ese for you. When the compiler has finished running it should create you a file with the same name as your program, except with ".class" on the end. If it finds any errors, the compiler will print them on the screen and expect you to change the code and run it again. If you're feeling brave, try deleting things like the semi-colon on the third line or one of the braces to see what it does. Don't forget to put them back afterwards though.

Unix

You will need to find your xterm prompt again and change directory to the place that you've saved your program. To do this you might need to type something like:

cd /home/something/username/myjava

Type ls to list the files in that directory to check that your ".java" file is there. To find out where you are - type pwd.

Once you're in the right place, simply type:

javac HelloWorld.java

If it complains with something like program "javac" not found or java.lang.Thread not found, things aren't setup properly - go back to stage one.

If you're using xemacs, you may be able to type CTRL-C CTRL-C at this point and it'll do everything for you.

Windows 95/NT

You will need to return to your MS-DOS/Command Prompt (use the old one - if you start a new one, you will need to set it up again). Once there, you will need to change directory to the folder that contains your program. To do that you will probably have to do something like:

cd C:\MyJava

Type dir to see a directory listing to check that your ".java" file is there. It should say where you are to the left of the > prompt.

Once you're in the right place, simply type:

javac HelloWorld.java

If it complains with something like bad command or file name or java.lang.Thread not found, things aren't setup properly - go back to stage one.

Development Environment

This one's easy - you should find a menu item or button labelled "Compile" - just choose that. There should be a window in which the results of the compilation (and any errors) are displayed.

Running the Compiled Program

You should now have a compiled program sitting in a ".class" file somewhere - you can try loading it into a text editor to see what it looks like if you're curious. Now what we need to do is tell the computer to run this code. With most programming languages, this would be simply a case of typing in the name of the program and the computer would load up the program, point its silicon chip at the main entry point and everything would just run.

Java, however, is a platform independent language - which means it is able to run on any sort of computer with any sort of chip in it - a kind of Esperanto for computers. To pull off this trick, Java programs actually run on a virtual machine - a pretend silicon chip which is the same everywhere. You can think of it as a program that hypnotises the real silicon chip so that it can speak a different, standard, language. So when you run a Java program, you have to point the real silicon chip at the Java virtual machine, and the Java virtual machine at your class file.

Unix

Again, find your xterm and make sure you're in the same directory as the ".class" file. Then type:

java HelloWorld

Windows 95/NT

Go back to your MS-DOS/Command Prompt and check that you're in the smae folder as the ".class" file. Then type:

java HelloWorld

Development Environment

You should find a menu item called "Run" or "Execute" - choose that!

  • Try removing semi-colon & braces.
  • Try getting it to print hello name
  • Try underlining your name with minus signs: -----
  • Try getting it to print hello to all of your friends

  • basic structure of a program [- data in -> do stuff with data -> data out] calculator
    What is Programming - telling a computer what to do - programming is like giving directions - why bother to learn how to program - the programming process [- problem -> design -> code as well as code -> compile -> debug] - basic structure of a program [- data in -> do stuff with data -> data out] - your first program - dissecting the code

    We are about to study the idea of a computational process. Computational processes are abstract beings that inhabit computers. As they evolve, processes manipulate other abstract things called data. The evolution of a process is directed by a pattern of rules called a program. People create programs to direct processes. In effect, we conjure the spirits of the computer with our spells.

    A computational process is indeed much like a sorcerer's idea of a spirit. It cannot be seen or touched. It is not composed of matter at all. However, it is very real. It can perform intellectual work. It can answer questions. It can affect the world by disbursing money at a bank or by controlling a robot arm in a factory. The programs we use to conjure processes are like a sorcerer's spells. They are carefully composed from symbolic expressions in arcane and esoteric programming languages that prescribe the tasks we want our processes to perform.