For your first Java exercise you are going to design the most simple of programs, one which you are likely to encounter when you learn other programming languages. The purpose of the program is to print out some text to the console, more precisely the phrase “Hello World”, followed by a new line.
Note
Please note that this initial exercise intentionally avoids the use of a development environment. This is to help you understand what is going on under the hood and practice the use of the command line.
Create a folder (e.g., OOPExercises) inside your home directory on DICE to contain your exercises and then create a new file named HelloWorld.java, using your favourite text editor. If you’re not sure which editor to use, gedit is simple and provides nice highlighting for Java code. Since you will be using the terminal command line to compile and run your file, it’s a good idea to make sure you are working in the folder that you just created. Use the Linux cd (change directory) command for this:
: cd OOPExercises
(Note that we are using ':' to represent the terminal prompt; this is not something you are meant to type.)
HelloWorld.java is the class file for our program. This file will start with the class definition as shown below.
public class HelloWorld { ... }
The title of the class must be exactly the same as the filename without the .java extension on the end. So in this case the class file named HelloWorld.java has the class title HelloWorld. Everything to do with your class will be contained within the two curly brackets { and } , since these denote the start and end of a block of code.
So, we have our class, now we need somewhere within it where the program will start running from. We do this by adding a main() method.
Note
For the time being, you can think of a method as being similar to a function in Haskell. We’ll say more about methods in later weeks.
The code that we use to create main() looks horribly complicated at first, but it is something that stays the same for every program that we will write. By the end of this course you should understand what each of the keywords mean but for the time being you can treat it as magical incantation that you just have to repeat for every program that you write. As mentioned before, this section of code containing main() should be within the class definition block (i.e., the outermost two curly brackets).
public static void main( String[] args ) { ... }
Notice that main() comes along with its own set of curly brackets; these enclose the definition of the main() method. We will refer to this in future as the method’s definition block. When we add some statements which tell main() what to do, we’ll put them inside this definition block.
For completeness, we have listed below a quick description of what each of main()‘s keywords mean, but don’t worry if you don’t understand them just yet.
- public
- Denotes that the method is visible to every part of the program.
- static
- Denotes that there is only one of this method.
- void
- Specifies the return type of the method. As this is the method for our entry-point into the program, this must be void as it does not return anything.
- main
- This is the name of the method - the entry-point into our program.
- String[] args
- Inside the parentheses we get the parameter of the method; this indicates any arguments that are passed in from the command line. We’ll use these below.
Now we have our entry-point for the program. When you execute the program it will start at this block, and execute any instructions that you give it, line-by-line, from the start of this method’s block of code to the end of it. At the moment we haven’t added any instructions so our program won’t actually do anything! Let’s add something for it to do.
We want our program to print out the line of text “Hello World”, followed by a new line. There are several instructions in Java that print text out to the console, two of which are:
//Prints out whatever is between the brackets System.out.print( "Your text here" ); //As above except with a new line at the end of the text System.out.println( "Your text here" );
So, we need to add one of these inside the definition block for main() as described above.
Warning
You must use double quotes "..." to delimit strings in Java programs. Single quotes won’t work!
Pick the print method you think is most suitable and add it to your program.
Warning
Remember that you have to put a ; at the end of your print statement.
Once you have done so, you should have a file that looks something like this:
public class HelloWorld { public static void main( String[] args ) { System.out.println("Hello World"); } }
Notice that we have two blocks, one nested inside the other: the outermost one defines the class HelloWorld while the inner one defines the method main(). This structure is also represented in the way we’ve formatted the code: the text is indented every time a new block is started (i.e., with a { bracket), and then unindented every time a block is finished (i.e., with a } bracket). This is not mandatory, but it is good programming practise, as it makes the structure of your programs much easier to analyse and debug.
Finally, we need to test if our program has worked. As with any program, it is good to test it piece-by-piece as you write it. This makes debugging your code much simpler in the long run.
Unlike Haskell, Java does not have an interpreter that you can load your file into and run it directly. Instead, there is an edit-compile-execute cycle that must be followed. We’ve just performed the edit stage, so now we need to compile the program into something that the Java virtual machine (JVM) can understand.
This process converts your HelloWorld.java file into a HelloWorld.class file that humans cannot read but the JVM can. Compiling is fairly simple to do, but this is where a lot of error checking is performed. So if your code is syntactically incorrect, errors will show up at this point.
To compile your program, go to your terminal window and make sure you are in the directory that contains your HelloWorld.java file. Then execute the javac program as shown:
: javac HelloWorld.java :
(javac is the Java compiler.) If everything goes to plan, this will not show any errors, but will return silently to give you a new terminal line, allowing you to execute more commands. A HelloWorld.class file should also have been created in the same folder. In order to check that it has indeed been created, you can use the Linux ls command for listing the contents of the folder:
: ls HelloWorld.class Helloworld.java
If something has gone wrong then the compiler will list where it thinks the error has occurred and what it thinks is wrong with it. Take a moment to look at the error message; it can often be quite informative. However, the compiler can only guess as to where your code has gone wrong, so sometimes the error message is unhelpful and you will have to determine where the error in your code is yourself. Also, if one error exists, this can cause problems later in your program, hence creating a cascade of multiple error messages. So if you have several error messages it is worth starting from the top, fixing the first error, and then trying to recompile the program as this may have fixed the subsequent errors.
You cannot continue until you have no errors in your code, and the compiler has generated a HelloWorld.class file.
Finally, once everything has compiled fine, you want to actually run the program you have just created. To do this we use the java command to start the JVM, and provide it with the name of your class. The execution and output should look as follows:
: java HelloWorld Hello World :
Warning
You just provide the name of the class, not the full file name (i.e., HelloWorld, not HelloWorld.java, nor HelloWorld.class). Also, you must execute the java command from inside the same directory where your HelloWorld.class is located.
Notice that the terminal prompt : ends up on a new line beneath the output text. If your program does not format its output like this then you have done something wrong, and must return to the edit stage to correct your code, then recompile and finally execute the program again.
Warning
If your edited file looks OK and compilation seems to work OK, but you are still not getting the results you expected, check that you are saving your edited HelloWorld.java file to the correct folder.
An automated test has been created for this exercise: HelloWorldTest.java.
How to use this test with IntelliJ to check your program for correctness is described in the Introduction to Development Tools.