Wednesday, April 06, 2005

How to Write, Compile and Run an Application

How to Write an Application

Now that you know what a program should look like, it's time to add code that does something "useful", like writing "Hello World!". You may use a simple editor to write the program below. Make sure that you save the file as HelloWorld.java. See Getting Started for a few editors you could use.

How to Compile an Application

The Java compiler is called javac.

Open a Linux terminal window or MS-DOS window and compile the HelloWorld.java file with the javac compiler:

[user]$ javac HelloWorld.java

The program still doesn't produce output, because it must run first.

How to Run an Application

Finally, you may run the HelloWorld.class file with the Java interpreter called java. Type the following commands (and do not use the .java file extension):

[user]$ java HelloWorld
Hello World!

Watch the terminal window, and observe that your program just wrote Hello World!

Discussion

When you tell the Java Virtual Machine to run your application, you must specify the class where execution should start, HelloWorld, and you may also pass some parameters to the application. (No parameters are passed in this example.)

Think of HelloWorld as the title of the program. The program must be saved in a file named HelloWorld.java, because HelloWorld is the name of the class containing the main method and because the file extension .java must be used for all Java programs.

Conclusion

Now, you know how to write a program that prints something to the screen. You also know how to compile and run it. This is about all you need to know in order to follow the rest of the tutorial. In addition you should read about Swing applications when needed.

Exercise: Write a Java application that writes your name to the screen.

No comments: