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.
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.
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:
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.
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.
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
}
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:
| Accessible by any class without limitation |
| Accessible only by methods in the same class or subclass |
| Accessible only by objects within the same class |
| 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.
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.
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:
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. |
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:
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.
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." |
Here are the steps you should use to compile FirstApp using a graphical compiler:
Here are the steps you should use to compile FirstApp using a command-line compiler:
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.
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.
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.
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.
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.
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.
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:
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 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.
Here are the steps you should use to compile FirstApplet using a graphical compiler:
Here are the steps you should use to compile FirstApplet using a command-line compiler:
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. |
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:
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.*; |
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:
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. |
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.
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.
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 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 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:
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. |
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:
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.
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.
The three most common errors you will see are listed in this section. Each interpreter error report is followed by a solution.
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.
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.
The five most common errors you will see are listed in this section. Each viewer error report is followed by a solution:
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.
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
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.