Home > Articles

  • Print
  • + Share This
This chapter is from the book

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.

  4. Enter the package name com.java24hours.

  5. 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.1The Full Text of Root.java


 1: package com.java24hours;
 2:
 3: class Root {
 4:     public static void main(String[] arguments) {
 5:         int number = 225;
 6:         System.out.println("The square root of "
 7:             + number
 8:             + " is "
 9:             + Math.sqrt(number)
10:         );
11:     }
12: }

The Root application accomplishes the following tasks:

  • Line 1—The application is placed in the com.java24hours package.

  • Line 5—An integer value of 225 is stored in a variable named number.

  • Lines 6–10—This integer and its square root are displayed. The Math.sqrt(number) statement in Line 9 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

FIGURE 4.1 The output of the Root application.

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.

The statement Math.sqrt(number) in line 9 demonstrates a built-in capability of the Java language—the ability to determine the square root of a number. There is a Java program named Math that has a method called sqrt() to find a specified number’s square root.

The Math program is part of the Java Class Library, which you explore later this hour.

  • + Share This
  • 🔖 Save To Your Account