The Hello Examples

These are some very simple examples of Java code to get you going. Please note all examples used in these notes will be distributed through the directory

/import/teaching/BSc/1st/ItP 

If you look there you will see a number of files. Copy them over as you are asked in these notes.

Hello World

By tradition, the first examples shown in any new language is one which prints "Hello World". In other words, how to print a simple message to the screen. We will keep to this tradition, even though it is a rather outdated one. These days, computer users tend to interact with their programs through graphical user interfaces (GUIs) and not by typing commands into a console window, and then typing further information diretly into that window. However, the examples used in this course will tend to keep to this old-fashioned approach in order to avoid the complexities involved in programming GUIs.

Here is "Hello World" in Java:

1  class HelloWorld
2  {
3  //  A program that prints the phrase "Hello World"
4
5    public static void main(String[] args)
6    {
7     System.out.println("Hello World");
8    }
9  }
The numbers on the left-hand side are added for reference here, they are not part of Java. The program can be found in the file

/import/teaching/BSc/1st/ItP/HelloWorld.java

You can copy it into your directory by issuing the Linux command from there:

% cp /import/teaching/BSc/1st/ItP/HelloWorld.java HelloWorld.java

A shorter version of this is:

% cp /import/teaching/BSc/1st/ItP/HelloWorld.java .

In Linux, the dot at the end (make sure there is a space between java and the final dot, but no spaces in HelloWorld.java) is a short way of saying the name of the file being copied into is the same as the name of the file being copied to, though in a different directory.

Java programs consist of a set of classes each containing a set of methods. This program has just one class called HelloWorld which has just one method called main in it. The method main has just one command in it, on line 7. So System.out.println(" text") is the Java command for printing the text between the two quotes. In Java (like C) all commands are followed by a semi-colon. The commands which make up a method are enclosed between an opening and closing curly bracket (on lines 6 and 8 here), and the methods which make up a class are also enclosed between an opening and closing curly bracket (on lines 2 and 9 here). In Java the exact layout of the text that makes up a program doesn't matter to the computer, but it is generally recommended that it is done in a way that makes the structure clear to human readers of the code. For example, it is a good idea to line up matching brackets so they the closing bracket is directly below the opening bracket it matches. It is also a good idea to have a human explanation of the code. Here that is done on line 3. Any line which begins with // is a "comment" i.e. it is ignored by the computer, but contains explanatory information for the human reader. The blank line 4 means nothing at all, but inserting blank lines where appropriate is another way of making the program look clearer to human readers.

Java has two sorts of programs. This program is an application. The other sort of program is known as an applet. In this course we shall concentrate on applications, which are programs that are run on their own. A Java applet is a program that is intended to be run in conjunction with a Web page. Although Java has become famous for its connection to the Web, we shall concentrate on using it as a standard programming language. All Java applications must have a method in a class somewhere which has a header of the form

public static void main(String[] args)
just like line 5 above. You will see later exactly what this means, but for now just treat it is a set of words that are needed in the makeup of an application.

Computers do not understand Java programs directly. To run a Java program it has to be converted to another form called Java byte code. The Linux command

% javac HelloWorld.java
will convert the Java program in the file HelloWorld.java to Java byte code. In general each class in a Java program has its own file which has the same name as the class with the addition of .java. Running javac causes a new file of the equivalent Java byte codes to be created with the same name as the class with the addition of the ending .class. So the above command will cause a new file called HelloWorld.class to appear in your directory. The Linux command
% java HelloWorld
will then cause the converted program to run and the words Hello World will be printed on the screen. In general, entering the command java SomeClass causes the system to look for the file SomeClass.class, look for the code representing the method main in that file, and run the commands in that method. These commands may call other methods which may be in other classes. If no file SomeClass exists, or no method main exists within it, an error message is printed.

The word compile is generally used to refer to the conversion of a program written in a "high-level" (i.e. designed for human programmers) language to a "low-level" one (i.e. one which directly controls the computer). Java byte code, however, is not really machine-level code, so it could be argued the translation is not true compilation. The idea behind Java is that another program (an "interpreter"), written in the real language of whatever machine is being used, actually obeys the Java byte-code. This is what happens when the java command is called. The advantage of this is that so long as the appropriate interpreter is available, a Java byte code program can be run on any machine and have exactly the same effect. Compare this to a language like C where there are subtle "machine dependencies" which means a program that runs on one machine may not run correctly on another.

Hello You

The next program does a bit more than HelloWorld. It can be found in the file HelloYou.java in the same directory as HelloWorld i.e. /import/teaching/BSc/1st/ItP/. You can copy it into your own directory and run it in a similar way. Here is the program (with added line numbers):
 1  import java.io.*;
 2
 3  class HelloYou
 4  {
 5  //  A program that prompts for your name then says hello to you personally
 6
 7  public static void main(String[] args) throws IOException
 8  {
 9   String name;
10   BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
11   System.out.print("Please type your name: ");
12   name=in.readLine();
13   System.out.println("Hello "+name);
14   }
15 }
This program shows you how to output text to the screen as well as input it. As you can see, this introduces more complexity.

The basic structure remains the same - a single class containing a single main method. The addition of an import statement on line 1 introduces one of the most important aspects of Java programming: the use of the extensive collection of ready provided classes that go along with the Java system. The statement import java.io.* occurring outside any class enables all classes in the file to make use of the classes in the Java package java.io. This package contains a number of classes dealing with input/output. Here it is needed so we can make use of the BufferedReader class for input.

Becoming an expert Java programmer involves knowing a lot about the classes provided by the Java system. There are many Java reference books which provide information on them. One that is particularly recommended as concise and complete is Java in a Nutshell by David Flanagan, published by O'Reilly. However, the philosophy of this course is that it is important to become a good general programmer first before moving on to the special intricacies of Java or any other programming language. We will therefore introduce system classes only as and when necessary, and try to minimise the number we use. The important thing is that the course is about understanding how to program and not on memorising large amounts of information about Java classes.

On line 7 of HelloYou you will see the header for the main method is as before but with the addition of throws IOException. Exceptions are a way of dealing with unexpected occurrences when a program is run. They can occur in input, for example, if there is a command to read a number but the next character read is not numerical. There are two sorts of exceptions: run-time exceptions and checked exceptions. If a command can cause a checked exception the program has to indicate how to deal with it. The words throw IOException in a method header indicate that if the exception IOException (essentially something going wrong in reading or writing) occurs anywhere when the method is being run, it is "thrown" to be dealt with by whatever called the method. We will deal with exceptions in more detail later in the course, so for now you can just consider this as yet another thing you just have to put in to make your Java program convert properly to Java byte code.

Line 9 is a variable declaration. It declares a variable called name of type String. A variable is a named piece of computer store that holds information and must be of a specific type, so, for example, name can store Strings but not integers or any other type. A String is a list of characters; again more details will come later in the course.

Line 10 is actually also a variable declaration, although a complicated one. It declares variable in of type BufferedReader. The bit following the equals sign in an initialisation. However, for now, you can just think of this as something necessary to get input working. It means that in links to what is actually typed in on the computer screen in the window where HelloYou is being run.

Line 11 is very like line 7 in HelloWorld, except that it prints something different, and has print in the place of println. This means that the cursor on the screen won't move to a new line after Please type your name: is printed.

Line 12 does the actual input. Having declared in to be a BufferedReader, in.readLine() is a call to the system method readLine attached to in which returns as a value the whole of the next line in in, that is everything typed onto the screen up to the carriage return. The name= bit means this is then put into the variable name.

Line 13 is a println call like line 7 in HelloWorld. You will notice, however, that between the brackets is "Hello "+name rather than "Hello World". In Java, the plus symbol may be used to join two strings together. "Hello " is one string, and name is a variable containing another string. So "Hello "+name is the string storing Hello plus the contents of name. Because name doesn't have quotes around it, it refers to the contents of variable name rather than the word name. If the command had been System.out.println(Hello+"name") it would print the contents of the variable Hello (assuming there was one) joined to the actual word name.

As in all standard programming languages, the commands in lines 9 to 13 are executed in the order they are written (you can think of a variable declaration as a command which reserves a piece of computer store). You may think this is so obvious that it was unnecessary to mention it, but computer scientists should always be precise and not take things for granted! As it happens, there are programming languages designed for parallel processors where you wouldn't necessarily have a sequence of commands executed in turn one after the other.

Hello You 1

The program in the file HelloYou1.java works very similarly to that in HelloYou.java. However, if you copy it to your directory, and attempt to use javac to convert it to Java byte code, you will get an error message. The reason for this is that it is meant to illustrate another aspect of Java, use of non-system classes. This program makes use of a class Text which is not part of the Java system, but was written by someone else (in fact Judy Bishop, author of the textbook "Java Gently", for use in conjunction with that book). You can use someone else's Java program without knowing much about the program and how it works, in fact to illustrate this you will find that only the version of Text already converted to Java byte code, in file Text.class is available in directory /import/teaching/BSc/1st/ItP/Bishop. If you copy this to your own directory, javac will work without complaint on HelloYou1.java.

Here is the program in HelloYou1.java:

 1  import java.io.*;
 2
 3  class HelloYou1
 4  {
 5  /*
 6     A program that prompts for your name then says hello to you personally.
 7     Uses the Text input/output class (from Judy Bishop's "Java Gently")
 8  */
 9
10   public static void main(String[] args) throws IOException
11   {
12    String name;
13    BufferedReader in = Text.open(System.in);
14    System.out.print("Please type your name: ");
15    name=Text.readString(in);
16    System.out.println("Hello "+name);
17   }
18  }
Just for variety and illustration, a different form of comment is used. Whereas previously we saw // to start a comment which finished at the end of the line, here in line 5 we see /* used to start a comment, with the difference that comments started in this way go on until a */ occurs, in this case on line 8. The comment mentions the use of the class Text - information like this is important, otherwise someone who tried to use this program might wonder why it wouldn't work.

Line 12 uses the open method provided in Text. Note it is shown this method comes from Text by actually writing it Text.open. In general static methods are attached where necessary to class names like this, while other methods are attached to variables as readLine is attached to in in line 12 of HelloYou.java above. This will be explained further later in the course. Line 12 in HelloYou1.java does exactly the the same as line 10 in HelloYou.java. However, it looks a lot cleaner because the details of how a BufferedReader is provided are confined to the Text class. This illustrates an important point for good programming - complicated detail can often be avoided to make the intention of a programmer clearer by making use of supplementary classes and methods to hide the details.

The Java language is designed for modern computer systems where input and output will generally be through a graphical user interface rather than text in a single window. However, this means that its extensive input/output facilities can be very complicated for the novice user. For this reason, classes like Text are often used by authors of introductory textbooks which use Java in order to provide simple text-based input/output. In this course we shall take this approach, as the aim is to get across basic understanding of algorithms and data structures, and we do not wish to cause distraction by having to deal with the intricacies of graphical user interfaces.

Line 15 in HelloYou1.java performs a similar task to line 12 in HelloYou.java. Again, the method call is attached to the class name Text rather than to the variable name in, but as in is needed to say where the reading is done from, it is passed as an argument to the method. There is a subtle difference between the readString method in Text and readLine, a standard method for BufferedReaders. While readLine reads a whole line up to the carriage return character, Text.readString only reads up to the first space. You will notice this is you run the programs and type in your full name (first names and surname) in response to the prompt: because HelloYou1 uses Text.readString the program will ignore all but your first name.

The program Hello1a.java makes use of the class introduced by David Barnes for his text book for simple text input:

 1  import java.io.*;
 2
 3  class HelloYou1a
 4  {
 5   /*
 6   A program that prompts for your name then says hello to you personally.
 7   Uses the SimpleInput class (from David Barnes' book)
 8   */
 9
10  public static void main(String[] args) throws IOException
11  {
12   String name;
13   SimpleInput in = new SimpleInput();
14   System.out.print("Please type your name: ");
16   name=in.nextLine();
17   System.out.println("Hello "+name);
18  }
19 }
As you can see, input is handled rather differently using Barnes' SimpleInput class rather than Bishop's Text class. You can find the file SimpleInput.class in the directory /import/teaching/BSc/1st/ItP/Barnes/utilities.

As yet another example of a simple input class introduced to accompany a textbook, below is a program to do the same thing but using the ConsoleReader class from Cay Horstmann's textbook. You can find the file ConsoleReader.java in the directory /import/teaching/BSc/1st/ItP/Horstmann/ch3.

 1  import java.io.*;
 2
 3  class HelloYou1b
 4  {
 5   /*
 6   A program that prompts for your name then says hello to you personally.
 7   Uses the SimpleInput class (from David Barnes' book)
 8   */
 9
10  public static void main(String[] args) throws IOException
11  {
12   String name;
13   ConsoleReader in = new ConsoleReader(System.in);
14   System.out.print("Please type your name: ");
16   name=in.readLine();
17   System.out.println("Hello "+name);
18  }
19 }

Hello You 2 and Hello You 3

There are two more "Hello" programs which you can copy to your directory, compile, and run. The first, HelloYou2.java is very similar to HelloYou1.java, it just prints an extra message. If you have not already tried changing the programs to experiment with what you already know about Java, you could alter this one to print a different message. The second program, HelloYou3.java is completely different to the ones you have seen. Just try compiling it, running it, and seeing what it does. It is given as a demonstration of a simple graphical user interface program. It is not necessary to know how it works to run it, and we shall not explain how it works or what the various parts of it mean. If you are interested and want to study yourself how these things work then do so, but it will not be examinable. Note that as the file HelloYou3.java has a separate class HelloWindowCloser in it, as well as class HelloYou3, when you compile it you will get a separate file HelloWindowCloser.class as well as HelloYou3. That was done to illustrate a point, but in general, to avoid unexpected things like that, we will keep to the rule that each class has its own separate file.
Matthew Huntbach

These notes were produced as part of the course Introduction to Programming as it was given in the Department of Computer Science at Queen Mary, University of London during the academic years 1998-2001.

Last modified: 2 Oct 2000