Home > Articles > Programming > Java

Understanding How Java Programs Work

  • Print
  • + Share This
This chapter explains the operation and organization of Java applications and applets.
This chapter is from the book

An important distinction to make in Java programming is where your program is supposed to be running. Some programs are intended to work on your computer. Other programs are intended to run as part of a web page.

Java programs that run locally on your own computer are called applications. Programs that run on web pages are called applets. During this hour, you learn why that distinction is important.

Creating an Application

The Saluton program you wrote during Hour 2, "Writing Your First Program," is an example of a Java application.

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

  • Choose File, New File. The New File wizard opens.
  • Choose the category Java and the file type Empty Java File, and then click Next.
  • 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[] args) {
 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

Figure 4.1 The output of the application.

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 responds with an error.

  • + Share This
  • 🔖 Save To Your Account