Creating an Application

The Saluton program you wrote during Hour 2, “Writing Your First Program,” is an example of a Java application. The next application you create calculates the square root of a number and displays the value.

With the Java24 project open in NetBeans, begin a new application:

1. Choose File, New File. The New File Wizard opens.

2. Choose the category Java and the file type Empty Java File, and then click Next.

3. Enter the class name Root and click Finish.

NetBeans creates Root.java and opens the empty file in the source editor so you can begin working on it. Enter everything from Listing 4.1, remembering not to enter the line numbers and colons along the left side of the listing. The numbers are used to make parts of programs easier to describe in the book. When you’re done, save the file by clicking the Save All button on the toolbar.

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:     }
10: }


The Root application accomplishes the following tasks:

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

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

If you have entered Listing 4.1 without any typos, including all punctuation and every word capitalized as shown, you can run the file in NetBeans by choosing Run, Run File. The output of the program appears in the output pane, as shown in Figure 4.1.

Figure 4.1. The output of the Root application.

Image

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

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.14.98