Previous Section  < Day Day Up >  Next Section

Creating an Application

Although Java has become well-known because it can be used in conjunction with World Wide Web pages, you can also use it to write any type of computer program. The Saluton program you wrote during Hour 2, "Writing Your First Program," is an example of a Java application.

To try out another program, use your word processor to open up a new file and enter everything from Listing 4.1. Remember not to enter the line numbers and colons along the left side of the listing; these items are used to make parts of programs easier to describe in the book. When you're done, save the file as Root.java, making sure to save it in text-only or plain ASCII text format.

Listing 4.1. The Full Text of Root.java

1: class Root {

2:     public static void main(String[] arguments) {

3:         int number = 225;

4:         System.out.println("The square root of "

5:             + number

6:             + " is "

7:             + Math.sqrt(number) );

8:     }

9: }


The Root application accomplishes the following tasks:

  • Line 3: An integer value of 225 is stored in a variable named number.

  • Lines 4–7: This integer and its square root are displayed. The Math.sqrt (number) statement in Line 7 displays the square root.

Before you can test out this application, you need to compile it using the Java Development Kit's javac compiler or the compiler included with another Java development environment. If you're using the JDK, go to a command line, open the folder that contains the Root.java file, and then compile Root.java by entering the following at a command line:


javac Root.java


If you have entered Listing 4.1 without any typos, including all punctuation and every word capitalized exactly as shown, it should compile without any errors. The compiler responds to a successful compilation by not responding with any message at all.

Java applications are compiled into a class file that can be run by a Java interpreter. If you're using the JDK, you can run the compiled Root.class file by typing this command:


java Root


The output should be the following:


The square root of 225 is 15.0


When you run a Java application, the interpreter looks for a main() block and starts handling Java statements within that block. If your program does not have a main() block, the interpreter will respond with an error.

    Previous Section  < Day Day Up >  Next Section