< Day Day Up > |
Creating an ApplicationAlthough 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.java1: 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:
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. |
< Day Day Up > |