Hour 4
Hour 4
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'll learn why that distinction is important, and the
following topics will be covered:
Organizing an application
Creating an Application
Although Java has become well-known because it can be used in conjunction with World Wide Web
pages, you can also use it to write any type of computer program. The Saluton program you wrote
during Hour 2, "Writing Your First Program," is an example of a Java application.
To try out another program, use your word processor to open up a new file and enter everything from
Listing 4.1. Remember not to enter the line numbers and colons along the left side of the listing; these
items are used to make parts of programs easier to describe in the book. When you're done, save the
file as Root.java, making sure to save it in text-only or plain ASCII text format.
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: }
Lines 4–7: This integer and its square root are displayed. The Math.sqrt(number) statement in
Line 7 displays the square root.
Before you can test out this application, you need to compile it using the Software Development Kit's
javac compiler or the compiler included with another Java development environment. If you're using
the SDK, go to a command line, open the folder that contains the Root.java file, then compile
Root.java by entering the following at a command line:
javac Root.java
If you have entered Listing 4.1 without any typos, including all punctuation and every word
capitalized exactly as shown, it should compile without any errors. The compiler responds to a
successful compilation by not responding with any message at all.
Java applications are compiled into a class file that can be run by a Java interpreter. If you're using the
SDK, you can run the compiled Root.class file by typing this command:
java Root
When you run a Java application, the interpreter looks for a main() block and starts handling Java
statements at that point. If your program does not have a main() block, the interpreter will respond
with an error.
Sending Arguments to Applications
Because Java applications are run from a command line, you can send information to applications at
the same time you run them. The following example uses the java interpreter to run an application
called DisplayTextFile.class, and it sends two extra items of information to the application, readme.txt
and /p:
Extra information you can send to a program is called an argument. The first argument, if there is one,
is provided one space after the name of the application. Each additional argument is also separated by
a space.
If you want to include a space inside an argument, you must put quotation marks around the
argument, as in the following:
This example runs the DisplayTextFile program with three arguments: readme.txt, /p, and Page Title.
The quote marks prevent Page and Title from being treated as separate arguments.
You can send as many arguments as you want to a Java application. In order to do something with
them, however, you have to write some statements in the application to handle them.
To see how arguments work in an application, create a new file in your word processor called
Blanks.java. Enter the text of Listing 4.2 into the file and save it when you're done. Compile the
program, correcting any errors that are caused by typos.
1: class Blanks
{
2: public static void main(String[] arguments)
{
3: System.out.println("The " + arguments[0] + " " + arguments[1] + " fox " + "jumped over
the " + arguments[2] + " dog.");
7: }
8: }
To try out the Blanks application, run it with a Java interpreter such as the SDK's java tool. Give it
three adjectives of your own choosing as arguments, as in the following example:
Try it with some of your own adjectives, making sure to always include at least three of them.
Arguments are a useful way to customize the performance of a program. They are often used to
configure a program so it runs a specific way. Java stores arguments in arrays, groups of related
variables that all hold the same information. You'll learn about arrays during Hour 9, "Storing
Information with Arrays."
Applet Basics
When the Java language was introduced in 1995, the language feature that got the most attention was
applets, Java programs that run on a World Wide Web page. Before Java, Web pages were a
combination of text, images, and forms that used gateway programs running on the computer that
hosted the pages. These gateway programs required special access to the Web server presenting the
page, so most Web users did not have the ability to use them. Writing them required even more
expertise.
In contrast, programmers of all skill levels can write Java applets, and you'll write several during the
span of these 24 hours. You can test them with any Web browser that handles Java programs, and put
one on a Web page without requiring any special access from a Web provider. The Java programs you
toured during the previous hour were all applets. Their structure differs from applications in several
important ways, and they are designed specifically for presentation on the World Wide Web.
Note
Because the applets you'll write in this book use Java 2, these applets must be run with a browser that
supports the most current version of the language. During Hour 17, "Creating Interactive Web
Programs," you'll learn how to set up a browser to use the Java Plug-in to run Java 2 applets. All
applets can also be tested with the appletviewer tool that is included with the Software Development
Kit.
Unlike applications, applets do not have a main() block. Instead, they have several different sections
that are handled depending on what is happening in the applet, as detailed fully during Hour 17. Two
of the sections are the init() block statement and the paint() block. init() is short for initialization, and
it is used to take care of anything that needs to be set up as an applet first runs. The paint() block is
used to display anything that should be displayed.
To see an applet version of the Root application, create a new file in your word processor and call it
RootApplet.java. Enter the code in Listing 4.3 and save it when you're done.
1: import java.awt.*;
2:
3: public class RootApplet extends javax.swing.JApplet {
4: int number;
5:
6: public void init() {
7: number = 225;
8: }
9:
10: public void paint(Graphics screen) {
11: Graphics2D screen2D = (Graphics2D) screen;
12: screen2D.drawString("The square root of " +
13: number +
14: " is " +
15: Math.sqrt(number), 5, 50);
16: }
17: }
Compile this file using your Java development software. If you are using the javac compiler tool in
the SDK, type the following at a command line:
javac RootApplet.java
This program contains a lot of the same statements as the Root application that did the same thing.
The main difference is in how it is organized—the main() block has been replaced with an init() block
and a paint() block.
Note
The sample programs in this hour are provided primarily to introduce you to the way Java programs
are structured. Some aspects of these programs will be introduced fully later, so don't feel like you're
falling behind. The main purpose of this hour is to get the programs to compile and see how they
function when you run them.
Unlike applications, compiled Java applets cannot be tested using a Java interpreter. You have to put
them on a Web page and view that page in one of two ways:
Use a Web browser that can handle Java 2 applets by using Sun's Java Plug-in, which requires
special configuration of the Web page.
Use the appletviewer tool that comes with the Software Development Kit.
To create a Web page that can display the RootApplet program, return to your word processor and
create a new file. Enter Listing 4.4 in that file and save it as RootApplet.html.
This Web page contains the bare minimum needed to display a Java applet on a Web page. The
<APPLET> tag is used to specify that a Java program is being put on the page, the code attribute
provides the name of the applet, and the height and width attributes describe the size of the applet's
display area. These items will be described in detail during Hour 17.
To see this applet using the appletviewer tool included with Software Development Kit, type the
following at a command line:
appletviewer RootApplet.html
To see it using your computer's default Web browser, type the following instead:
RootApplet.html
You can also load this page in your browser: Choose File, Open, then navigate to the folder that
contains RootApplet.html and select the file.
If you try to load this page with your Web browser and get an error, the most likely cause is that your
browser is not yet equipped with the Java Plug-in. To correct this, visit the Web page
http://java.sun.com/getjava to download and install the free Java Runtime Environment, which
includes the Java Plug-in.
Sending Parameters to Applets
Java applets are never run from the command line, so you can't specify arguments the way you can
with applications. Applets use a different way to receive information at the time the program is run.
This information is called parameters, and you can send parameters through the HTML page that runs
the applet. You have to use a special HTML tag for parameters called <PARAM>.
To see how the Blanks application would be rewritten as an applet, open your word processor, enter
the text of Listing 4.5, then save the file as BlanksApplet.java.
1: import java.awt.*;
2:
3: public class BlanksApplet extends javax.swing.JApplet {
4: String parameter1;
5: String parameter2;
6: String parameter3;
7:
8: public void init() {
9: parameter1 = getParameter("adjective1");
10: parameter2 = getParameter("adjective2");
11: parameter3 = getParameter("adjective3");
12: }
13:
14: public void paint(Graphics screen) {
15: screen.drawString("The " + parameter1
16: + " " + parameter2 + " fox "
17: + "jumped over the "
18: + parameter3 + " dog.", 5, 50);
19: }
20: }
Save the file and then compile it. Using the SDK, you can accomplish this by typing the following at
the command line:
javac BlanksApplet.java
Before you can try out this applet, you need to create a Web page that displays the BlanksApplet
applet after sending it three adjectives as parameters. Open your word processor and enter Listing 4.6,
saving it as BlanksApplet.html.
Save the file when you're done, and load the page using Internet Explorer, the SDK's appletviewer, or
another browser equipped with the Java Plug-in. The output should resemble Figure 4.2. Change the
values of the value attribute in Lines 2–4 of the BlanksApplet.html file, replacing "lachrymose",
"magenta", and "codependent" with your own adjectives, then save the file and run the program again.
Try this several times, and you'll see that your program is now flexible enough to handle any
adjectives, no matter how well or how poorly they describe the strange relationship between the fox
and the dog.
You can use as many parameters as needed to customize the operation of an applet, as long as each
has a different NAME attribute specified along with the <PARAM> tag.
As a short workshop to better familiarize yourself with the <APPLET> tag and how it can be used to
alter the performance of an applet, visit this book's World Wide Web site at
http://www.java24hours.com.
Load this site by using one of the Web browsers that can run Java applets, such as Microsoft Internet
Explorer, Netscape Navigator, or Mozilla. Go to the section of the site labeled "Hour 4 Showcase,"
and you'll be given a guided tour through several working examples of applets. These applets were
written with Java version 1.0, so they can be run with any browser that supports Java, even if it isn't
equipped with the Java Plug-in.
On each of the pages in the Hour 4 Showcase, you can use a pull-down menu command to view the
HTML tags that were used to create the page:
Appendix F, "This Book's Web Site," describes other things you can find on the book's site. The Web
site is intended as a complement to the material covered in this book, and a way to find out about
corrections, revisions, or other information that make these 24 hours more productive.
Summary
During this hour, you got a chance to create both a Java application and an applet. These two types of
programs have several important differences in the way they function and the way they are created.
Both kinds of Java programs can be easily customized at the time they are run. Applications use
arguments, which are specified on the command line at the time the program is run. Applets use
parameters, which are included on the Web page that displays the applet by using HTML tags.
The next several hours will continue to focus on applications as you become more experienced as a
Java programmer. Applications are quicker to test because they don't require you to create a Web
page to view them; they can be easier to create as well.