Hello World Application
The "Hello World!" applet we developed in the last section demonstrates the power of a Java applet. It will run on any Java capable browser. You simply insert a reference to the .class file in the HTML code, designate the size of the Window that the Applet will need to run in, and it will execute when the page is loaded. Unfortunately, this means that we need an HTML page to view an Applet's output. This can become very tedious and time consuming.
We can also develop Java Applications following the same procedure we used to generate the applet. First we use a text editor to write the code and save it with the .Java extension. Then we type JAVAC and the name of the source file to generate the .class file. But now we simply type JAVA and the name of the .class file (without the extension) and the application will run.
Copy the following code into a
text editor and
save it as helloworld.java.
| class helloworld { public static void main (String args[]){ System.out.println("Hello World !"); } } |
Line 1 Designates that we are defining a
new class- helloworld Notice that it does not extend the Applet class. So it will be an Application. Line 2 defines a method called main Line 3 sends the string Hello World ! to the system output device Notice the use of '{' and '}' to separate the program blocks. |
Follow these four steps:
Save the source code as helloworld.java .
Exit the text editor and return to a command prompt.
Type "javac
helloworld.java" at the command prompt.
If there are any errors, return to the editor and ensure
the source code is exactly the same as what you see
above. Remember that
Java is case sensitive.
Check your upper case letters carefully.
If there are no errors the compiler will work for a few
seconds and then save a file called helloworld.class in
the same directory.
To run the .class file type "java helloworld" at the command prompt.
After following these steps
Hello World !
Should appear on the screen.
Congratulations, you just ran your first Java Application.
Go to the next topic: Decision Structures