# Chapter 4

# The Java Language: A Primer

### CONTENTS

- Creating Your First Stand-alone Java Application
  - The Basic Structure of a Stand-alone Application
  - Putting It All Together
  - Creating FirstApp
  - Compiling FirstApp
  - Running FirstApp
- Your First Java Applet
  - The Basic Structure of an Applet
  - Creating the Applet
  - Compiling FirstApplet
  - Creating an HTML File for Your Applet
  - Creating an Image for Your Applet
  - Creating a Sound File for Your Applet
  - Running FirstApplet
- Troubleshooting
  - Compiler Errors
  - Interpreter Errors
  - Viewer Errors
- Summary

After racing through cyberspace in Chapter 3, "The Java Browser and the World Wide Web: A Primer," you are probably ready for some hands-on experience with Java. Now you are going to dive right in to a primer for the Java programming language. The power of Java is that even the most basic Java programs can feature multimedia. This is primarily because the fundamentals of the Java programming language are easy to learn and use.

These fundamentals apply both to applets for use on the World Wide Web and to stand-alone applications. In this chapter, you create your first stand-alone application and your first applet. To show you how easy Java programming can be, one of these programs will use the built-in multimedia features of the language.

Don't worry-I'll stick to the basics. Even the most basic Java programs are useful in demonstrating the structure of Java programs. As you examine this structure, you will be able to see how classes, methods, and objects are used in Java programs.

## Creating Your First Stand-alone Java Application

As long as the Java developer's environment is installed on your computer as discussed in Chapter 2, "Getting Started with the JDK," you are ready to create your first stand-alone application. To follow the examples in this section, you will need the Java compiler and the Java interpreter.

### The Basic Structure of a Stand-alone Application

Your first Java program is a basic, stand-alone application called `FirstApp`. An important difference between Java applets and applications is the inclusion of a method called `main`. The `main` method is included in all Java applications.

Although all this simple application does is print the words "My first stand-alone application is a success," you will use this application as a stepping stone to more advanced programs and concepts. The great thing about Java is that all Java programs follow the same basic constructs. This is true no matter how complex or simple the program is.

The five-line application shown in Listing 4.1 is no different. It has all the features of more complex Java applications and all the features of an object-oriented program as well:

- It is an object
- It uses encapsulation and message passing
- It defines a class
- It uses inheritance
- It uses access modifiers

> Listing 4.1. Your first Java application.

> `class FirstApp {
> public static void main (String args[]) {
> ` System.out.println("My first stand-alone application is a success.");
> }
> }

To understand how this simple five-line application uses five of the key object-oriented programming concepts, you can look at how these concepts relate to this application.

#### The Object and Encapsulation in `FirstApp`

Objects are the fundamental unit in object-oriented programming. All objects have a state and a behavior. Everything the object knows about its variables and methods describes its state. The actions an object can perform describe its behavior. The `FirstApp` program defines a single object that has

> A state that is unchanging or static

> A behavior that is to print out a statement

You can use objects to send messages to other objects without having to know how those objects work. This object-oriented programming concept is called encapsulation. In Java, objects, classes, and packages are all encapsulated.

Encapsulation allows you to use a Java object as long as you know what values the object will accept. The `FirstApp` program uses the concept of encapsulation to access a method called `println`. To use the `println` method, you do not have to know how it works. All you have to know is that if you pass the method a line of text, it will print the line of text to the screen.

Another thing you need to know to access an object is where it is in the namespace. Java allows you to access public methods and variables as long as you know where the methods and variables are in the namespace. The `println` method is one of dozens of methods in the `System` class. The `System` class is a part of the core Java language package of the Application Programming Interface (API).

Java knows how to find the `println` method because the path to the method is specified. Although you do not have to specify the full path to methods, the full path for the `println` method is

> `java.lang.System.out.println`

You could translate this path into plain words. Here's how: `println` is a submethod of `out`, which is in the `System` class. The `System` class is a part of the `lang` package of the Java API.

#### Classes and Inheritance in `FirstApp`

In Java, classes encapsulate objects and serve to group a set of related methods and variables. Although most Java programs contain multiple class declarations, the `FirstApp` program has only one. This line of the `FirstApp` program declares it to be a class of objects called `FirstApp`:

> `class FirstApp {`

Usually you will declare classes in Java using one of two general forms. The first general form of a class declaration is

> `class name {
> //body of class declaration
> }`

The second general form of a class declaration is

> `class name extends extendedclass {
> //body of class dec*
> l aration
> }`

In both general forms, the open bracket signifies the beginning of the class and the close bracket signifies the ending of the class. Within the brackets, you define the methods and instance variables associated with the class.

You can extend all classes in Java with another class either implicitly or explicitly. By doing so, you can create a class that inherits the functionality of an existing class. This object-oriented programming concept is called inheritance. Inheritance allows you to reuse code and to extend the functionality of existing classes.

Like other Java classes that do not explicitly extend another class, the `FirstApp` class extends the `Object` class. By inheriting the functionality of the `Object` class, your programs can do many things that they otherwise would not be able to do. To put this in perspective, you could rewrite the first general form of class declarations as follows:

> `class name extends Object {
> //body of class declaration
> }`

#### Access Modifiers in `FirstApp`

In Java, access to methods and variables is controlled through access modifiers. The Java programming language defines four levels for access controls for methods and variables:

Public | Accessible by any class without limitation
Protected | Accessible only by methods in the same class or subclass
Private | Accessible only by objects within the same class
Default | Unless declared otherwise, assumed to be friendly or accessible by any class in the same package

The main method in `FirstApp` is declared to be public. This means the method is completely accessible to other methods and variables. Another program could access `FirstApp`'s `main` method by specifying the path to the method in Java's namespace.

### Putting It All Together

Now that you have a basic understanding of how `FirstApp` uses object-oriented programming concepts, let's review the source code for `FirstApp` line by line.

The first line of the application declares the class as `FirstApp`. Because the declaration does not specify what class the application extends, by default `FirstApp` extends the `Object` class. The open bracket signifies the beginning of the `FirstApp` class:

> `class FirstApp {`

The next line declares many things about a method called `main`:

> `public static void main (String args[]) {`

You can break down the previous declarations item by item as follows:

`public` | The modifier `public` states that the method is accessible to other classes.
`static` | The modifier `static` states that the method is unchanging and implicitly final, meaning the method cannot be overridden.
`void` | The modifier `void` states that the method does not return a value.
`main()` | The word `main` specifies the `main` method for the application. Arguments for the method are placed between the open and close parentheses. The `main()` method is required in Java applications to tell the interpreter where to start. `main`, unlike `main()` in C/C++, does not return a value. Java handles its exceptions internally rather than sending them back to the system.
`(String args[])` | This specifies that the `main` method takes an argument that is an object of `String`.
`{` | The open bracket signifies the beginning of the method.

The next statement calls the `println` method of the `System` class and prints the sentence "My first stand-alone application is a success." As with other methods, the arguments to pass to the method are declared between open and close parentheses. Each statement in Java ends in a semicolon:

> `System.out.println("My first stand-alone application is a success.");`

The final two lines of the `FirstApp` program are close brackets. The first close bracket completes the block of code associated with the `main()` method. The second close bracket completes the block of code associated with the `FirstApp` class.

### Creating `FirstApp`

Now that you know what the `FirstApp` program looks like, you can create the program on your computer. Before you do this, there are two things you need to do:

1. Decide where on your file system you want to place your applications
2. Create an appropriately named file

#### Creating a File System Structure for Applications

When you installed the Java Developer's Kit on your system, you created a directory or folder to hold the files used by Java. Although you could store your personal Java applications in this directory, you might want to store them elsewhere so you can easily differentiate between the original programs and the ones you will create.

Peter's Principle
A good place to store your applications and all associated files might be in a directory called `java_apps`. You will find that the easier it is to get to the directory, the better-therefore, you should not place this directory too many levels deep in your directory structure. Depending on the complexity of your applications, you might want to create a separate subdirectory for each application. For complex or multipart applications, storing each application in a separate subdirectory makes sense. If you searched through the files and directories you created when you installed the JDK, you saw that the demo applets included with the JDK are stored in separate subdirectories. In the base subdirectory for each applet, you will find the source code, the compiled code, and an HTML document used in displaying the applet. Usually, you will find additional directories for sound and image files associated with the applet as well.

#### Naming the Source File for the Application

After you have decided where you want to place your application and have created directories if necessary, you can create the source code for the application. Whenever you create source code files for Java, you must remember three rules:

- Java requires you to create source code files with the `.java` extension.
- Java requires that the source code file use the name of the primary or first class declaration.
- Regardless of whether your computer's operating system is case sensitive, the Java compiler is case sensitive, and your filenames must match the primary class name exactly.

Following these naming rules, you must store the `FirstApp` program in a file called `FirstApp.java`. Although you can use your favorite text editor or word processor to create this file, you must save the file as standard ASCII text. For the sake of simplicity and ease of use, many programmers prefer to use basic text editors as opposed to word processors. On UNIX systems, you can use a command-line editor such as `vi` or `emacs`. On Windows 95/NT systems, you can use the MS-DOS editor or the Windows Notepad. On Macintosh systems, you can use BBEdit or Simple Text.

After you finish entering the source code, you should check it line by line for accuracy. When you are sure the source code is accurate, save it to the directory you have designated for your applications.

### Compiling `FirstApp`

To compile the application, you will use the Java compiler `javac`. When you compile the source, the Java compiler creates a separate file for each class in your program. If an application has more than one class file, you should always invoke the Java interpreter with the name of the class containing the `main` method. Because there is only one class declaration in `FirstApp`, the Java compiler will create only one class file.

Although compiling applications on the Macintosh is as easy as dragging the `FirstApp.java` file onto the compiler, other system owners should not be too envious. On other systems, `javac` is a
command-line program. Because the command line offers a simplified interface and streamlined design, the version of `javac` for UNIX, Windows 95/NT, and OS/2 is actually much more versatile.

Looking Ahead
If you like the ease of use associated with graphical tools and use a Windows based or UNIX system, don't worry. Graphical tools for Java on all systems is something that is already here. Several third party vendors have created compilers and interpreters that let you use graphical development environments. For more information on graphical development tools, see Chapter 5, "Java Tools and the JDK: A Primer."

#### Using a Graphical Compiler

Here are the steps you should use to compile `FirstApp` using a graphical compiler:

1. Drop the `FirstApp.java` file onto the compiler or select Open from the compiler's File menu.
2. The compiled output file, called `FirstApp.class`, is placed in the same directory as the source.
3. If an error window pops up, make sure you have typed the source correctly in the `FirstApp.java` file. If after correcting your mistakes you still cannot get the file to compile, refer to the section titled "Troubleshooting" at the end of this chapter.

#### Using a Command-Line Compiler

Here are the steps you should use to compile `FirstApp` using a command-line compiler:

1. Change to the directory containing the source code and type the following at the command prompt:
   `javac FirstApp.java
   `
2. The compiled output file, called `FirstApp.class`, is placed in the same directory as the source.
3. If you get an error stating that the system cannot find `javac`, your path is not set up correctly. You will have to set your path correctly or type the full path to the compiler. If errors pertaining to the source code are listed to the command area, make sure you have typed the source correctly in the `FirstApp.java` file. If after correcting your mistakes you still cannot get the file to compile, refer to the section "Troubleshooting" at the end of this chapter.

### Running `FirstApp`

When you compile an application, the compiler creates a separate file for each class declaration. Because the `FirstApp` program contains only one class declaration, only one class file is created. You run applications using the Java interpreter, `java`. On the Macintosh, using the Java interpreter is as easy as dragging the `FirstApp.class` file onto the interpreter. On other systems, the Java interpreter is a command-line program that is invoked with the name of the class you want to run.

#### Using a Graphical Interpreter

Here's what you should do to run `FirstApp` using a graphical interpreter: Drop the `FirstApp.class` file onto the interpreter icon or select Open from the interpreter's File menu.

You should see the sentence `My first stand-alone application is a success.` Congratulations-your first stand-alone application is a success. If the interpreter issues any errors, ensure that you tried to run the file with the `.class` extension. If you still have problems, refer to the section "Troubleshooting" at the end of this chapter.

#### Using a Command-Line Interpreter

Here's what you should to do run `FirstApp` using a command-line interpreter: Change to the directory containing the compiled file with the `.class` extension and type the following at the command prompt:

> `java FirstApp`

You should see the sentence `My first stand-alone application is a success.` Congratulations-your first stand-alone application is a success. If the interpreter issues errors, ensure that you typed `FirstApp` correctly and did not include the `.class` extension. If you still have problems, refer to the section "Troubleshooting" at the end of this chapter.

## Your First Java Applet

If the Java developer's environment is installed on your computer, as discussed in Chapter 2, you are ready to create your first applet. To follow the examples in this section, you will need the Java compiler and the Java applet viewer.

### The Basic Structure of an Applet

Your first Java applet is more complex than your first stand-alone application, yet still uses the same basic constructs and the same object-oriented programming concepts. This applet, called `FirstApplet`, uses Java's built-in multimedia features to display an image and play a sound file.

Listing 4.2 shows the `FirstApplet` program. Although the program is 17 lines long, four of these lines are used simply to make the program more readable.

> Listing 4.2. Your first Java applet.

> `import java.awt.*;
> import java.applet.*;
> public class FirstApplet extends Applet {
> Image NewImage;
> public void init() {
> resize(400,400);
> NewImage = getImage(getCodeBase(),"New.gif");
> }
> public void paint(Graphics g) {
> g.drawImage(NewImage,0,0,this);
> play(getCodeBase(),"New.au");
> }
> }`

Let's review the source code for `FirstApplet` line by line.

`import` statements allow the applet to use methods and classes from other packages:

> `import java.awt.*;
> import java.applet.*;`

By default, all Java programs import the `java.lang` package, which provides the core functionality of the Java language. The asterisk in the last element of the `import` statement allows Java to import classes dynamically. Here, the classes from the `java.awt` package and the `java.applet` package are imported dynamically.

This line declares a class called `FirstApplet` that extends the `Applet` class:

> `public class FirstApplet extends Applet {`

By extending the `Applet` class, `FirstApplet` inherits the functionality of that class. The open bracket signifies the beginning of the `FirstApplet` class.

This line initializes the variable `NewImage` and declares it to be of type `Image`. Here, `NewImage` is a placeholder for the image the applet will display:

> `Image NewImage;`

This line declares a method called `init` that overrides the `init` method of the `Applet` class:

> `public void init() {`

`Applet`'s `init` method is overridden so you can resize the window before you display the image. The modifier `public` states that the method is accessible to other classes. The modifier `void` states that the method does not return a value. Normally the arguments a method accepts are placed between the open and close parentheses. Because the `init` method accepts no arguments, nothing is placed between the parentheses.

Using the `resize` method, you can resize the display area for the applet. Here, the display area is resized to 400¥400 pixels:

> `resize(400,400);`

After you have declared a variable of a certain type, you can use it. This line of code sets a value for `NewImage`:

> `NewImage = getImage(getCodeBase(),"New.gif");`

The `getImage` method is used to do this. The first argument for `getImage` is actually a call to a method called `getCodeBase`, which returns the location of the base or current directory on your hard drive. The base directory is the directory containing the class file you are running. The second argument is the name of the image that can be found at the specified location.

This line declares a method called `paint` that overrides the `paint` method of the `AWT` package:

> `public void paint(Graphics g) {`

This method is overridden so the applet can draw the image to a specific location. The modifier `public` states that the method is accessible to other classes. The modifier `void` states that the method does not return a value. When the `paint` method is called, it needs to be sent an object of class `Graphics`. `Graphics` is the abstract base class for all graphic objects. The element `g` is the specified `Graphics` window.

This line invokes the `Graphics` object `g`, which displays the image called `NewImage`:

> `g.drawImage(NewImage,0,0,this);`

All the actual work is done by a method called `drawImage`. The `drawImage` method accepts arguments that tell it what image to display and where to display it. Here, `NewImage` will be displayed at the x,y coordinate 0,0. The final argument is called an observer. The purpose of the observer is to notify whether the image is completely displayed.

As the name implies, the method `play` is used to play audio files. The first argument for `play` is a call to the `getCodeBase` method, which returns the location of the base or current directory on your hard drive:

> `play(getCodeBase(),"New.au");`

The base directory is the directory containing the class file you are running. The second argument is the name of the sound file that can be found at the specified location.

### Creating the Applet

Now that you know what the `FirstApplet` program looks like, you can create the program on your computer. Before you do this, you need decide where on your file system you want to place your applets. Then you need to create an appropriately named file.

Tip

> A good place to store your applets and all associated files might be in a directory called `java_applets`. Depending on the complexity of your applets you may want to create a separate subdirectory for each applet. For complex or multipart applets storing each applet in a separate subdirectory makes sense.

When you have decided wher you want to place your applet and have created directories if necessary, you can create the source code for the applet. Whenever you create source code files for Java, you must remember three rules:

- Java requires you to create source code files with the `.java` extension.
- Java requires that the source code file use the name of the primary or first class declaration.
- Regardless of whether your computer's operating system is case sensitive, the Java compiler is case sensitive, and your filenames must match the primary class name exactly.

Following these naming rules, you must store the `FirstApplet` program in a file called `FirstApplet.java`. You must also save the file as standard ASCII text. After you finish entering the source code, you should check it line by line for accuracy. When you are sure the source code is accurate, you should save it to the directory you have designated for your applets.

### Compiling `FirstApplet`

Compiling an applet is exactly the same as compiling an application. To compile the applet, you will use the Java compiler, `javac`. When you compile the source, the Java compiler creates a separate file for each class in your program. If an applet has more than one class file, you should always invoke the Java interpreter with the name of the class containing the primary method. Because there is only one class declaration in `FirstApplet`, the Java compiler will create only one class file.

#### Using a Graphical Compiler

Here are the steps you should use to compile `FirstApplet` using a graphical compiler:

1. Drop the `FirstApplet.java` file onto the compiler or select Open from the compiler's File menu.
2. The compiled output file called `FirstApplet.class` is placed in the same directory as the source.
3. If an error window pops up, make sure you have typed the source correctly in the `FirstApplet.java` file. If after correcting your mistakes you still cannot get the file to compile, refer to the section "Troubleshooting" at the end of this chapter.

#### Using a Command-Line Compiler

Here are the steps you should use to compile `FirstApplet` using a command-line compiler:

1. Change to the directory containing the source code and type the following at the command prompt:
   `javac FirstApplet.java`
2. The compiled output file called `FirstApplet.class` is placed in the same directory as the source.
3. If you get an error stating that the system cannot find `javac`, your path is not set up correctly. You will have to set your path correctly or type the full path to the compiler. If errors pertaining to the source code are listed to the command area, make sure you have typed the source correctly in the `FirstApplet.java` file. If after correcting your mistakes you still cannot get the file to compile, refer to the section "Troubleshooting" at the end of this chapter.

### Creating an HTML File for Your Applet

Because applets are made for viewing with hypertext viewers such as Web browsers, you must create an HTML document before you can use an applet. Within the HTML document, you use a markup tag called `APPLET` to load and run the specified applet. In the `<APPLET>` tag, you refer to Java classes and not to the files containing the class that ends in the `.class` extension. The example HTML document contains an `<APPLET>` tag that refers to the `FirstApplet` class and not to the file named `FirstApplet.class`.

Using your favorite word processor or text editor, create a plain ASCII text file with the following contents:

> `<HTML>
> <HEAD>
> <TITLE>First Java Applet</TITLE>
> </HEAD>
> <BODY>
> <APPLET CODE="FirstApplet" width=400 height=400></APPLET>
> </BODY>
> </HTML>`

After you create the file, save it in the same directory as the compiled code for the `FirstApplet` program. Most HTML documents use the `.html` extension; you should save your HTML document with an appropriate name, such as `example.html`.

Powered Web Presentations with Applets," for complete details on using the `<APPLET>` tag.

### Creating an Image for Your Applet

The Java API currently supports two image formats: GIF and JPEG, which are the most widely used image formats on the World Wide Web. The `FirstApplet` program displays a GIF image called `New.gif`, but you can create your own image to use instead. If you have published on the Web, you probably have a GIF image that `FirstApplet` can display. To use a GIF image you currently have on your computer, you will need to do the following:

1. Rename the image: `New.gif`.
2. Move the image to the directory containing the compiled code for the application.

If you do not have a GIF image you can use, don't worry. On the CD-ROM you will find a sample image in the directory for Chapter 4. You could also create an image using your favorite graphics program, such as CorelDRAW!. After you create the image, save the image to a file called `New.gif` and move it to the directory containing the source code for the application.

Note
If you do not have a graphics program that will create GIF images and you plan to create applets for use on the World Wide Web, you should probably purchase one or download a shareware graphics program from a reliable archive site on the Internet. Here's how you can rewrite the `FirstApplet` program so that it uses a text string instead of an image: `import java.awt.*; import java.applet.*; public class FirstApplet extends Applet { public void init() { resize(400,400); } public void paint(Graphics g) { g.drawString("My first Java applet.",50,50); play(getCodeBase(),"New.au"); } }`

### Creating a Sound File for Your Applet

In order for sound files to play on your system, your system must be properly configured to play sound. At this time, the Java API supports only the Sun AU format. Fortunately, the AU sound format is one of the widely used formats on the World Wide Web. The `FirstApplet` program plays an AU sound file called `New.au`, but you can create your own sound file to use instead. If you have published on the Web, you might have an AU sound file that `FirstApplet` can use.

To use an AU sound file you currently have on your computer, you will need to do the following:

1. Rename the sound file: `New.au`.
2. Move the sound file to the directory containing the compiled code for the application.

Note
If you do not have an AU sound file, don't worry. The `FirstApplet` program will still run-it just won't play a sound file for you. Also, you will find a sample AU sound file on the CD-ROM in the directory for Chapter 4.

### Running `FirstApplet`

After creating the necessary files for the `FirstApplet` program, you can run the applet using a hypertext viewer. The Java Developer's Kit includes a viewer called `appletviewer`. On the Macintosh, using `appletviewer` is as easy as dragging the HTML file that references the applet onto the AppletViewer icon. On other systems, `appletviewer` is a command-line program that is invoked with the name of the class you want to run.

#### Using a Graphical Applet Viewer

Here's what you should do to run `FirstApplet` using a graphical applet viewer: Drop your .`html` file onto the AppletViewer icon or select Open from `appletviewer`'s File menu.

You should now see a pop-up window for the applet viewer. Within a few seconds, you will see your GIF image and hear the audio file. If the viewer issues errors, ensure that you used the correct HTML document and that the document is in the same directory as your compiled code. If you still have problems, refer to the section "Troubleshooting" at the end of this chapter.

#### Using a Command-Line Applet Viewer

Here's what you should do to run `FirstApplet` using a command-line applet viewer: Change to the directory containing the compiled file with the `.class` extension and type the following at the command prompt:

> `appletviewer example.html`

You should now see a pop-up window for the applet viewer. Within a few seconds, you will see your GIF image and hear the audio file. If the viewer issues errors, ensure that you used the correct HTML document and that the document is in the same directory as your compiled code. If you still have problems, see the next section, "Troubleshooting."

## Troubleshooting

Troubleshooting is something of an art form. Some programmers can troubleshoot hundreds of lines of code in a few minutes. Others wade through the same code for hours. Thankfully, once the JDK is properly installed and tested on your system as outlined in Chapter 2, most of your errors at this stage should pertain to the code itself and your paths. Therefore, this is not an exhaustive list of all the errors that can occur during the running of Java programs. Rather, it is a list of pointers that should help you solve most problems and is divided into three parts:

- Compiler Errors
- Interpreter Errors
- Viewer Errors

### Compiler Errors

Compiler errors are normally output directly to the command window. Whenever the Java compiler displays an error, it will not create the `.class` file. Consequently, you must fix errors before you can successfully compile and run the code. The Java compiler does a fair job of telling you where the errors are in your file. However, a single error can be the source of multiple errors later in the compilation. With this in mind, you should generally look to the earliest errors for the source of your problems. After you fix such an error, you should recompile the code and look for other errors.

Most of the mistakes in your code at this stage should be typing mistakes. Typos are often hard to find; you might have to check your code character by character. There are three problem areas in particular you should look for:

Semicolons | Statements should end with a semicolon.
Brackets | Each class and method should have an open bracket and a close bracket. This means that for every class and method declaration, you should have one open bracket and one close bracket. The `FirstApp` program has one class declaration and one method declaration. Thus, there should be two open and two close brackets. The `FirstApplet` program has one class declaration and two method declarations. Thus, there should be three open and three close brackets. The brackets must be placed properly. The open bracket follows the class or method declaration. The close bracket is the final item in the class or method.
Parentheses | Every method name should be directly followed by its arguments enclosed in parentheses. Even if a method has no parameters, it should have an open and a close parenthesis.

#### Ten Most Common Compiler Errors

The following is a list of the 10 most common errors you will see if there are typos in `FirstApp`. Each compiler error report is followed by a solution. Although `FirstApp` is a very basic program, you can use the logic involved in solving these errors to help solve problems with larger programs, including the `FirstApplet` program:

1. Compiler error report 1:
   `FirstApp.java:1: '{' expected.
   class FirstApp
   ^
   1 error
   ` Solution: Add an open bracket to the class declaration on line 1 as follows:
   `class FirstApp {`
2. Compiler error report 2:
   `FirstApp.java:3: ';' expected.
   System.out.println("First stand-alone application.")
   &nbs p; ^
   1 error
   ` Solution: Add a semicolon to the end of the statement in line 4 as follows:
   `System.out.println("First stand-alone application.");`
3. Compiler error report 3:
   `FirstApp.java:2: ')' expected.
   public static void main (String args[] {
   ^
   1 error
   ` Solution: Add a close parenthesis to the method declaration in line 2 as follows:
   `public static void main (String args[]) {`
4. Compiler error report 4:
   `FirstApp.java:2: ')' expected.
   public static void main (String args]) {
   ^
   1 error
   ` Solution: In this case, the Java compiler gives a misleading error message. Line 2 is not missing a close parenthesis. It is missing an open square bracket. Although the error is misleading, it does help to pinpoint the source of the problem. Here the problem should be between the preceding open parenthesis and the next close parenthesis. The problem can be fixed as follows:
   `public static void main (String args[]) {`
5. Compiler error report 5:
   `FirstApp.java:2: Class tring not found in type declaration.
   public static void main (tring args[]) {
   ^
   1 error
   ` Solution: Java is looking for a class called `tring` instead of a class called `String`, which can be fixed as follows:
   `public static void main (String args[]) {`
6. Compiler error report 6:
   `FirstApp.java:2: Class vod not found in type declaration.
   public static vod main (String args[]) {
   ^
   FirstApp.java:2: Return required at end of vod main(java.lang.String[]).
   public static vod main (String args[]) {
   ^
   2 errors
   ` Solution: The word `void` is entered incorrectly as `vod`. This causes the Java compiler to give one good error message and one misleading error message. To fix this problem, you only need to correct the typo:
   `public static void main (String args[]) {`
7. Compiler error report 7:
   `FirstApp.java:2: Invalid method declaration; return type required.
   public static void (String args[]) {
   ^
   1 error
   ` Solution: The method declaration is invalid because it is missing the name of the method. To fix this problem, you need to add the word `main`:
   `public static void main (String args[]) {`
8. Compiler error report 8:
   `FirstApp.java:3: Method outprintln(java.lang.String) not found in
   ` Â `class java.lang.System.
   System.outprintln("First stand-alone application.");
   ^
   1 error
   ` Solution: The call to the `println` method has a typo that is causing the Java compiler to look for an invalid method called `outprintln`. Adding a period between the word `out` and the word `println` solves this problem:
   `System.out.println("First stand-alone application.");`
9. Compiler error report 9:
   `FirstApp.java:3: ')' expected.
   System.out.println(First stand-alone application.);
   ^
   1 error
   ` Solution: The Java compiler gives a misleading error message. Line 3 is not missing a close parenthesis. It is missing double quotation marks. Although the error is misleading, it does help to pinpoint the source of the problem. Here the problem should be between the preceding open parenthesis and the next close parenthesis. The problem can be fixed as follows:
   `System.out.println("First stand-alone application.");`
10. Compiler error report 10:
    `FirstApp.java:5: '}' expected.
    }
    ^
    FirstApp.java:5: '}' expected.
    }
    ^
    2 errors
    ` Solution: The compiler is a bit confused because there is a problem in the way your open and close brackets are placed. In particular, you probably have an open bracket where a close bracket should be. Review the code and see where the close bracket should be placed. The best place to start is at line 5. Work your way backward from there.

Other errors you may encounter are related to your paths. Your paths aren't set up correctly if you see an error that says

> `javac: Command not found`

To fix this problem, you need to update your path so that it includes the directory where the Java binary executables are stored. Chapter 2 includes a section on testing the installation for each major operating system. You should refer to the section appropriate for your operating system.

### Interpreter Errors

Sometimes a program will compile but still will not run with the Java interpreter. Unless redirected, interpreter errors are output directly to the command window. Most interpreter errors relate to either a missing `main` method or an incorrectly entered filename.

#### Three Most Common Interpreter Errors

The three most common errors you will see are listed in this section. Each interpreter error report is followed by a solution.

1. Interpreter error report 1:
   `In class FirstApp: void main(String argv[]) is undefined
   ` Solution: All Java applications must have a `main` method. The class file you are trying to run is missing the `main` method. If there is only one class file for this application, add a `main` method to the source code and recompile. If there are more than one class file for this application, invoke the interpreter with the name of the class file containing the `main` method.
2. Interpreter error report 2:
   `Can't find class Firstapp
   ` Solution: The Java interpreter cannot find the class file you have specified. This can be a result of an incorrectly typed class name or your path structure. First, check to make sure you have typed in the class name correctly. In this case, `FirstApp` was incorrectly entered as `Firstapp`. If you typed in the class name correctly, check your paths. You must either be in the directory containing the class file or have your paths set up correctly to look for the class file.
3. Interpreter error report 3:
   `Can't find class FirstApp/class
   ` Solution: You have invoked the interpreter with the filename instead of the class name for your application, and the Java interpreter replaced the period with the appropriate directory separator for your system. When you invoke the interpreter again, do not use the `.class` extension-use the class name.

Other errors you may encounter are related to your paths. Your paths aren't set up correctly if you see an error that says

> `java: Command not found`

To fix this problem, you need to update your path so that it includes the directory where the Java binary executables are stored. Chapter 2 includes a section on testing the installation for each major operating system. You should refer to the section appropriate for your operating system.

### Viewer Errors

Java's `appletviewer` introduces a new set of possible problems. This is primarily because to use `appletviewer` you need an HTML document with a correctly defined `<APPLET>` tag. Unless redirected, `appletviewer` errors are output directly to the command window.

#### Five Most Common Viewer Errors

The five most common errors you will see are listed in this section. Each viewer error report is followed by a solution:

1. Viewer error report 1:
   `I/O exception while reading: \C:\java_applets\new
   ` Make sure that `new` is a file and is readable.
   Solution: `appletviewer` does a good job of pinpointing the problem. You have entered the name of a file that either does not exist on your system or isn't at the location where Java expects to find it. If you typed in the name of the HTML document correctly, check your paths. You must either be in the directory containing the HTML document or have your paths set up correctly to look for the HTML document.
2. Viewer error report 2:
   `thread applet-FirstApplet.class find class FirstApplet
   Opening stream to: file:/C:/java_applets/FirstApplet.class to get FirstApplet
   load: class FirstApplet not found
   ` Solution: The `appletviewer` was able to load the HTML document, but it cannot find the Java class you specified in the `<APPLET>` tag. View the contents of the HTML document and make sure you have correctly entered the class name. If you typed in the class name correctly, check your paths. Your HTML document must either be in the directory containing the Java class file, or the `<APPLET>` tag must specify the relative or full path to the class file.
3. Viewer error report 3:
   `Warning: No Applets were started, make sure the input contains an <applet> tag.
   use: appletviewer [-debug] url|file ...
   ` Solution: `appletviewer` is trying to display the document, but the document does not contain an `<APPLET>` tag. Make sure you are invoking the `appletviewer` with the name of the HTML document and not the name of your Java class file. Then view the contents of the HTML document to make sure you have a fully qualified `<APPLET>` tag, such as
   `<APPLET CODE="FirstApplet" width=400 height=400></APPLET>`
4. Viewer error report 4:
   `Warning: <applet> tag requires width attribute.
   Warning: No Applets were started, make sure the input contains an <applet> tag.
   use: appletviewer [-debug] url|file ...
   ` Solution: `appletviewer` is trying to display the document, but the document does not contain a fully qualified `<APPLET>` tag. In this case, the `<APPLET>` tag is missing the `WIDTH` attribute.
5. Viewer error report 5:
   `Warning: <applet> tag requires height attribute.
   Warning: No Applets were started, make sure the input contains an <applet> tag.
   use: appletviewer -debug] url|file ...
   ` Solution: `appletviewer` is trying to display the document, but the document does not contain a fully qualified `<APPLET>` tag. In this case, the `<APPLET>` tag is missing the `HEIGHT` attribute.

Other errors you may encounter are related to your paths. Your paths aren't set up correctly if you see an error that says

> `appletviewer: Command not found`

To fix this problem, you need to update your path so that it includes the directory where the Java binary executables are stored. Chapter 2 includes a section on testing the installation for each major operating system. You should refer to the section appropriate for your operating system.

## Summary

You have learned the basics of creating Java applications and applets. Applications are stand-alone programs designed to be invoked with an interpreter. Applets are programs designed to be viewed with an external viewer. Although applications and applets are very similar in design, one key difference between them is that applications require a `main` method and applets do not.

Through a simple application called `FirstApp`, you saw that even the most basic Java programs use key object-oriented programming concepts. This is because

- All Java programs define objects that have a behavior and a state.
- All Java programs use encapsulation and message passing, which allow you to use a Java object as long as you know what values the object accepts.
- All Java programs define one or more classes that group sets of related methods and variables.
- All Java programs use inheritance, which enables you to create classes that inherit the functionality of existing classes.
- All Java programs use access modifiers that control access to methods and variables.

The five-line program called `FirstApp` and the 17-line program called `FirstApplet` used the similar constructs as well. These constructs form the basis of the Java programming language. More complex Java programs that may be hundreds of lines long will also follow these basic concepts and constructs.