Previous |
Next |
The traditional way to start learning a programming language is by creating a small program that simply sends the string "Hello World" to the console (the command line, or DOS window in Windows XP or Vista). I will be assuming that you are using the naked JDK with a simple editor such as notepad.exe, that comes with Windows. If notepad is a little unexceptional you might like to consider notepad2 from www.flos-freeware.ch which is a “drop in replacement” for windows notepad but also includes some programmer specific features such as color syntax highlighting. The editor has a built in knowledge of the syntax of Java and colors the keywords accordingly. Whatever editor you use it must be able to save files with the extension .java.
If you are running a version of Windows and are not familiar with the console, chose the start menu, chose run and if you are on Windows 2000 or XP type cmd. (If you are running a version of Linux you need to run one of the shell interpreters, a popular one being bash). You will then see the black window of mystery that is the command prompt, or console. If you type in notepad (or notepad2 if it is in your path) you will see a real windows program start which is the minimal editor that ships with just about all versions of windows.
Create a file called HelloWorld.java. and enter the following code.
public class HelloWorld{
public static void main(String argv[]){
System.out.println("Hello World");
}
}

The screen shot shows how the notepad2 program colour codes the different parts of the program. The highlighting of the opening and closes of the curly braces can be very useful when a program gets more complex.
Note that the body of the main method is indented, i.e. It is set further to the right than the rest of the text. Indenting code makes no difference at all to the Java compiler or to the final program, but it can make code much easier for a programmer to understand. By indenting code it is possible to see where a block of code, a method or a loop begins and ends.
Now compile the code by typing
javac HelloWorld.java
If there are no problems you should return to the prompt without seeing any confirmation message. You may get an error message saying something like
public class Helloworld must be defined in a file called "Helloworld.java"
This indicates that the name of the class in the file does not exactly match the name of the file containing the code. This is because Java checks that the case of the letters in the file name matches the case of the letters in the class name. This can seem a little odd if (like me) you are used to the DOS/Windows platform where the case of a file name has almost no significance. Checking the case of letters is the first thing to examine when you have an error, particularly when you are first starting to work with Java. Make sure you have the semi colon at the end of the System.out... line.
If you get an error indicating that the system knows nothing about Javac then you may have to investigate the path setting in your system. This should be set to include the location of the Java binaries (the programs that actually make it go). On a Windows system these files are typically kept in a directory called something like
c:\jdk1.5\bin
If you have managed to compile up the program without error, do the DOS dir command to see what files have been produced.
You should see a new file has been created called
HelloWorld.class
The class file is what will actually be run. To run it you type
java HelloWorld
More information on creating your first program can be found at
http://java.sun.com/docs/books/tutorial/getStarted/cupojava/win32.html
|
|
Java is thoroughly case sensitive |
This program should now output the string "HelloWorld" to the console. Note that you only typed the name of the class file and did not give the .class extension, even though you had to give the .java extension when you compiled the program. If the code in your class says
public class HelloWorld
But you typed
java Helloworld
On the command line, you will get an error. I can't emphasise enough that Java is thoroughly case sensitive.
E:\data>java Helloworld
Exception in thread "main" java.lang.NoClassDefFoundError: Helloworld (wrong name: HelloWorld)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.access$100(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClassInternal(Unknown Source)
If you recall the code for the HelloWorld program was
public class HelloWorld{
public static void main(String argv[]){
System.out.println("Hello World");
}
}To take the first line of the program
public class HelloWorld{The keyword public indicates that this class will be visible from anywhere. This is known as an access modifier. Later you will learn about the modifiers private and protected. The keyword class indicates that this is the start of the most basic building block of Java. Classes are sometimes defined as
an aggregate of data and executable code
The executable code that in other languages might be called functions or subroutines are called methods in Java. The next line is an example of a method.
public static void main(String argv[]){There is a certain "magic" about the main method in Java in that it is the place where execution of any application starts. The main method must always have the same format or signature as in this example.
The keyword public has a similar meaning for a method as for a class. It indicates that the method can be called from anywhere. The keyword static indicates that this method can be called without creating an instance of the class. If that means nothing to you, don't worry about it as it will be explained later. The keyword void indicates that this method will return no value. The name of the method is main. A method can be given any name so long as it begins with a non-numeric character and does not contain spaces. You can start a method name with a dollar sign, but I wouldn't recommend it.
The parameters for the method are contained within the parenthesis, in this case
(String argv[])
This indicates that when the method is called it must be passed a String array. An array is a collection of elements all of the same data type. In this case we have an array of the type String. The Java Virtual Machine fills this array with any parameters passed to the program on the command line. This is often how programs are started in the world of Unix and older DOS programs but is not so common with GUI based programs. If you were to start the program with the command line
java HelloWorld one two three
The argv array would contain the Strings
"one" "two" "three"
which the program could then access, you could print out the first argument to the program (the first text after the program name) with a line as follows.
System.out.println(argv[0]);
See how the first element is zero and not one.
Note that the data type String begins with an upper case letter S. Note that the parameter name argv[] is just a convention, it would be just as correct to create a main method as
public static void main(String foo[])
However it is a good idea to stick to the convention of calling the parameter argv[] to make your code easily understandable.
System.out.println("Hello World");This is a call to the static method
System.out.println
Note the use of the dot notation. This means that println is a method of the class out that is a child of the class System. The System class is a low level class that any program can have access to at any time. The println method expects to receive a string for a parameter and in this case I have obliged by passing the "Hello World" string I want to send to the console. Note how the line is terminated by a semi colon as you would do in C/C++.
The next two lines simply consist of closing curly braces. The first one indicates the closure of the main method and the next indicates the end of the class. Note how the end of the class does not require a semi-colon.
Note that you can insert blank lines, tabs or space characters just about anywhere on a Java program, and it is a good idea to use them to make your code readable. Although the readability of your code may not seem important when you are first learning to program, it is a very good idea to get in the habit of creating readable code right from the start. Sooner or later every programmer reads code that makes them ask the question “what fool wrote this”. Sooner or later it will turn out that the answer is “oh dear I wrote it myself only six months ago, I wish I had made
You did not decide to learn Java so you could write strings to the console like some 1960's science fiction drama. Where are the web based graphics and GUI windows and menus you have come to expect?
From the very first release Java came with a standard set of libraries for creating graphical applications that have an appearance similar to modern GUI style programs that you would expect in an environment like the Macintosh or MS Windows.
This is a significant contrast to older programming languages where the "out of the box" experience was the text interface with various non standardised libraries available for creating graphical applications. Delightful though it is to create windows, buttons and components the things that make the programs actually go can be developed and tested in a purely text environment. It is also useful to keep the graphical interface and the "back end" functionality separate.
But to fast forward from an era of kipper ties and excess facial hair we need to get a demonstration of a better looking program than the text version of HelloWorld. The simplest way to demonstrate a graphical Java application is to create a simple Frame and then add a button to it.
|
|
Exercise: GoodbyeWorld |
|
|
|
Write a program in the same vein as HelloWorld, but where the class is called GoodbyeWorld and the output string is “Goodbye World”. Don't just copy HelloWorld and change it but create it “from scratch”.
Other Sources
Hello World according to Sun
http://java.sun.com/docs/books/tutorial/getStarted/application/index.html
Previous |
Next |