Chapter 27:
Stepping Up to Straight Java

In This Chapter

JavaScript's Big Brother

If you've made it this far in the book, good for you! As you've seen, JavaScript is a very powerful language for extending the capabilities of your World Wide Web pages. No doubt, as you've surfed around checking out other authors' uses of JavaScript (okay, and peeked at their source code to get more ideas), you've encountered talk about a thing called Java. If you're the curious sort, you're probably wondering just what Java is and whether it's worth looking into. In this chapter, I’ll explain what Java is and how you can start to develop your own Java applets. Even if full-blown Java programming isn’t your “cup of tea,” as they say, you might want to use JavaScript to connect with and control Java applets, which you’ll see in the final section of this chapter.

Java is a full-blown programming language, designed for the purpose of providing "truly interactive" content through the World Wide Web; Java is the language on which JavaScript is based. Developed by Sun Microsystems, Java attempts to bridge the "multiple platform" gap that exists on the Internet by creating applications (called applets) that will run on any computer of any type—as long as a Java-enabled browser is handy. The same Java applet will run on Windows 95, Windows NT, UNIX, and Macintosh, eliminating the need for customizing the applet to the particular computer.

Java Relies on a "Virtual Computer"

In order to pull off the trick of being useable on a variety of platforms, Java applets actually run on what's
called the Java Virtual Machine. Look at it this way: Certain programs available today enable you to run 
Windows software on a Macintosh, or UNIX software on a Windows computer, and so on. They do this 
by emulating the behavior of a particular computer type (they "pretend" to be a Mac or Windows or 
UNIX machine so that the software thinks it's running on the correct computer). The Java Virtual Machine
is another type of emulator, but it doesn't emulate Mac, Windows, or UNIX. Rather, it pretends to be a 
totally different type of system. And by defining what the Java computer can and cannot do, Sun was able 
to create a program that—no matter what physical hardware it's run on—will always look like a Java 
computer to the applets.

Confounded Compiling 

Because Java is a programming language (like Pascal, BASIC, C, or C++), to work with it, you have to write a program. Java programs are similar to JavaScript scripts, except that they are much more extensive and require a lot of additional material in order to successfully complete the next phase of Java development: compiling. Compiling an applet means to take the program you've written and run a special program on it that converts it from "near-human-readable" format to "Java-machine-readable" format (called bytecode) so that a Java browser can run the applet.

Java is an "object-oriented" programming language most closely related to C++. "Object-oriented" is a difficult concept to explain clearly, but in essence, it means that the language revolves around manipulating end-results instead of designing the tools for manipulation. An object-oriented sculptor, for instance, would be more concerned with melding together various blocks of clay than with the tools that carve the clay initially. The popular construction toy Legos is a nice example of an object-oriented activity.

In this chapter, you're not going to dig deep into the bowels of Java. Like JavaScript, Java is still evolving, and by the time you're holding this book in your hands, there will no doubt be newer tools available for creating Java applets. Instead, you'll take a quick glance at what it takes put together an applet and how to link applets into your HTML pages.

To start, you'll need to do a little surfing and pick up a copy of the collection of utilities Sun puts out to aid Java programmers. It’s called the Java Developer's Kit.

Java Browsing

As with JavaScript, you need to use a Java-capable browser to run Java applets. At the time of this writing, the 32-bit versions of both browsers discussed in this book (Microsoft Internet Explorer 3.0 and Netscape Navigator 3.0) support Java. For Windows 3.1 users (16-bit) interested in Java, both Netscape and Microsoft are planning to release Java-capable versions of their browsers in 16-bit form within the year; they may have already done so by the time you read this.

The Java Developer's Kit

Before you dive into Java programming, you need to pick up a copy of the Java Developer's Kit (JDK for short). The JDK includes:

In a nutshell, the JDK has everything the budding Java programmer needs to start.

What? How much does it cost? Well, put your checkbook away! The JDK is available free off the Internet. Simply fire up your browser (any browser will do) and point it at the Sun Java Homesite at the address below. The following figure shows the Sun Java Homesite.

Links to download the Java Developer’s Kit.

Browse your way into the Download section, and you'll find the links for downloading the JDK for your machine. Note that, as pictured above, there are actually two JDK’s currently available: one for Java 1.02 and one for Java 1.1. If you want to create applets compatible with the current crop of Java-capable browsers, stick with 1.02. Java 1.1 is the newest release of Java and contains special features that the 3.0 browsers don’t support yet (presumably, the 4.0 versions of Internet Explorer and Netscape Navigator will support JDK 1.1 applets). The file you'll be downloading is rather large (4M or more), so start the download process and then go get a cup of coffee.

When the file has been downloaded completely, follow these steps:

  1. Move the file to the root of the drive where you want to install the JDK (C:\ for example). Make sure that you have at least 5 megabytes of free space on the disk before going to the next step (that's 5 megabytes after you copy the file to it).
  2.  Run the file (from a DOS window, or by selecting File, Run from Windows NT, or by the Run option on Windows 95's Start menu).
An .EXE File That Unpacks Itself? 
This is called a self-extracting archive, and all you have to do is "run" it. In Windows 3.x, you can choose File, Run from the Program Manager; in Windows 95, you choose Run from the Start menu on the taskbar. The file then decompresses and installs itself.

The file will automatically unpack itself, create a \java directory and a bunch of subdirectories, and copy a ton of files into these new directories. When all this is done, you can delete the original file (or store it in a safe place, if you like to keep a copy around just in case).

Where Are the Manuals?

One of the nice things about the JDK is the existence of very thorough documentation. What documentation, you ask? Well, if you fire up your browser and open the \java\progguide\index.htm file, you'll be introduced to one of the nicest documentation collections on Java and the JDK available (see the following figure).

JDK online documentation.

Now, scroll down a bit. As you can see in the next figure, below the Getting Started heading, you'll find Duke, the Java mascot (a cute little guy who looks amazingly like the Starfleet insignia). Look at that—he's waving at you! You guessed it. Duke's a Java applet!

Duke waves a friendly greeting. Resist the temptation to wave back.

All of the documentation that comes with the JDK is available in HTML format, so you might want to browse around a bit right now before going further in the book. One thing to note, though, is that not all the HTML files in the JDK are linked to the other files. The JDK contains a collection of document sets. You can simply list all of the JDK help files with the File Manager or the Windows Explorer and double-click any of the HTML files you like. They will then be opened into your browser.

Back from your local surfing? Good! Take a quick detour into HTML to see how Java applets connect to Web pages: the <APPLET> tag.

Introducing the <APPLET> Tag

Just as JavaScript scripts are identified by their own custom HTML tag (the <SCRIPT> tag you learned about back in Chapter 3), Java applets are included in Web pages through their own custom tag: the <APPLET> tag. As with other HTML tags, browsers that don't support Java will simply ignore the tag, so you can safely create Java-enabled pages that don't limit their viewing to Java-enabled users. (However, you will need to do a little more HTML to provide those who haven't caught up with the times something to look at).

The <APPLET> tag's structure is relatively simple. Actually, there are two tags that work together: APPLET and PARAMS. The <APPLET> tag looks like this:

<APPLET CODE="appletFile" WIDTH=pixels HEIGHT=pixels>
<!-- Alternate HTML code goes here -->
The CODE Attribute Must Be Relative
 Unlike most other HTML tags and attributes that use URLs, the CODE attribute cannot be an absolute URL; it must point to something relative to the current directory the HTML files are in.

The CODE attribute identifies the applet program and is a file with a ".class" extension located in the same directory as the HTML document. To make your page do something for those poor souls who don't have a Java-enabled browser, you can place any additional alternative HTML statements inside the <APPLET> tag. Java browsers will ignore these statements, and non-Java browsers will ignore the <APPLET> tag (which works out quite well, don't you think?).

The WIDTH and HEIGHT attributes define the size of the applet on the page. An applet's size is specified in pixels. In addition, there are several other optional attributes that you can add to the <APPLET> tag to modify its behavior.






Passing Applet Parameters

Those of you who remember the days of DOS (those glory days before Windows, X-Windows, and the Macintosh made pictures out of everything) might recall that you could run some programs by typing the name of the program and adding additional information on the command line before pressing the Enter key. Those additional pieces of information were called parameters.

You Can Spot Old (pre-JDK) Applets Easily
 As you surf the Web, if you come across an applet that's implemented in HTML using an <APP> tag instead of the JDK <APPLET> tag, you've found an old applet that was created prior to the standardization of Java. For it to function in today’s browsers, it may have to be upgraded via the utilities provided in the JDK.

It's possible to create applets that can take parameters. (In the case of applets, parameters are additional options that are unique to the applet and aren't covered by other <APPLET> attributes.) Passing parameter values to an applet is done with the <PARAM> tag. <PARAM> tags are placed after the <APPLET> tag and before any of the "alternate HTML" statements and the </APPLET> tag. The <PARAM> tag looks like this:

<PARAM NAME=appletAttribute VALUE=value>

In that expression, NAME identifies the particular attribute, and VALUE identifies its value. If you have more than one parameter, you use more than one <PARAM> tag. The parameters available depend on the particular applet in question and are defined by the applet’s programmer in the source code to the Java applet. For Java programmers, inside the applet code, you access the values passed in with <PARAM> with the getParameter() function.

For example, imagine an applet named ScrollText. As advertised, this applet can scroll a text message across the browser window. It’s stored in the file ScrollText.class and can take several parameters that customize its behavior:

<APPLET CODE=”ScrollText.class” NAME=”scroller” HEIGHT=100 WIDTH=300>
<PARAM NAME=text VALUE=”Welcome to my Home Page”>
<PARAM NAME=font VALUE=”Arial”>

In the above HTML example, you first specify the applet ScrollText.class, name it scroller, and set its dimensions. Then, having referred to the applet’s documentation, you set three parameters: text (with the message to scroll), font (with the font style to render the text), and speed (which controls the pace of the scroll). Remember that these parameters are individually programmed into each applet and are particular to an applet.

Java with Class

Java and JavaScript share many things, including the "objects" or things that give you access to different parts of a Web page. Java extends this by allowing you to create your own types of objects, as well as by offering up a larger collection of "canned" objects. Predefined objects in Java are bundled together in "classes" or collections of objects that share a common purpose.

Classes are at the heart of what makes Java an object-oriented language. A class is like a library of objects, all of which inherit certain characteristics from the class itself. "Class" is a hierarchical concept: One class could be a subset of a higher-level class. In Java, there is an "abstract class," which is a parental class containing many child classes. In this case, though, the abstract class is never directly used. Rather, it is defined solely to provide the "genes" for its children classes.

If any of this seems confusing, that's because it is. That is why entire books are written about object-oriented programming and Java in particular. Now, though, at least you have a taste for what object-orientedness is about: modules that are part of larger modules, which are part of even larger modules.

C++ is a very common object-oriented programming language that also revolves around these class concepts. One major difference between C++ and Java, in terms of how they deal with classes, is that Java programs can more easily withstand changes in class definitions without breaking any programs based on the previous definitions. In C++, on the other hand, if you change any class definitions, every program written using the previous definitions must be recompiled. For this reason, Sun calls Java "dynamic."

Hello World!

Let's close with a quick look at making your own Java applet. As it was in JavaScript, your first applet should be the traditional "Hello World" program. The Java program looks like this:

/* Hello World...Java Style */
public class HelloWorld
public static void main(String args[])
System.out.println("Hello World!");

Save this file as Then, after you type that, you need to compile the applet. Get yourself to a DOS prompt (you'll need to open a DOS window to do this) and type the following:


Finally, you can run your new applet right from DOS by typing this:

java HelloWorld

Congratulations! You've just taken another big step: Java programming!

Command Line? I'm Running a Mac!

If you're running a Macintosh (or a PowerPC), you're probably a bit confused by the reference to a 
"command line" because the Mac operating system doesn't have one. Does this mean that Mac users are
out of luck when it comes to creating Java applets? Sadly, at this moment, the answer is "Yes—unless you're 
willing to spend some money." There are no environments or library sets (source code) for Java compiling on
the Mac available for free off the Internet. Several companies (Symantec at and 
Metrowerks at to name two) have announced that they will be integrating Java
applet creation into their compilers, but their products aren't available yet.

Natural Intelligence, however, does market a package called Roaster that gives Mac users the ability to 
compile and develop Java applets on the Mac from inside the Mac OS. For more information, check out 
Natural's web page at

Mating Java and JavaScript

A significant new feature in JavaScript 1.1 is called “LiveConnect.” Actually a set of features, LiveConnect allows you, using JavaScript code, to poke into the core of an applet. By doing so, you can gain access to an applet’s variables, methods, and classes. You can exploit this to change the way an applet behaves on the page in response to other events.

LiveConnect supports a variety of interactions between JavaScript and Java, but several require a more detailed understanding of Java than I’ve presented in this book. Therefore, I’ll focus solely on controlling applets with JavaScript code.

Imagine, then, that your page contains one applet whose function is to scroll a text message. In JavaScript 1.1, you can refer to this applet in either of two familiar ways:

LiveConnect, for our purposes, allows you to call public methods within the Java applet. This is much like calling a function in your JavaScript code, except that the “function” resides within the Java applet (and is called a method instead of a function). To find out which public methods are available in an applet, you need to look at its source code (not the .class file, but the applet source file, which often ends in the extension .java). If you’re creating your own applets, this is easy because the author has the applet source code handy. However, if you’re trying to LiveConnect to other author’s applets, things may get trickier; even if the author makes the applet source code available, it may take a close reading of it to understand how it works.

Because we haven’t delved very deeply into authoring Java source code, let’s just consider a relevant snippet of the scroller applet source:

public void start() {
if(thread == null) {
thread = new Thread(this);

If you haven’t programmed Java and are familiar only with JavaScript, the snippet of code above may look a bit strange. Nonetheless, you can identify two important characteristics about the above:

The lesson in all this is that, using JavaScript, you can call the above Java method with a statement such as:


This statement will launch the start() method in the applet named scroller on the current page.

Similarly, this applet also contains a public method named stop(). As you can imagine, the statement document.scroller.stop() would stop the applet’s execution.

Depending upon the particular applet, the above principles can be used to modify all sorts of applet behavior. Suppose, for example, that the applet also had a public method named bgcolor().You could perhaps use the JavaScript statement document.scroller.bgcolor(“green”) to change the applet’s background color to green.

To repeat, though, the public methods available in an applet all depend on what the applet’s author chose to create. It can sometimes be difficult to understand other author’s programs, which is why LiveConnecting to any old applet isn’t always easy. If you program your own applets, you can create public methods that interface most successfully with JavaScript.

To close this chapter, take a look at a small sample page that pulls together the LiveConnect principles you’ve learned. This page contains a text-scrolling applet, as well as two form buttons. By exploiting LiveConnect in onClick event handlers, these form buttons can be used to start and stop the scrolling message.

<title>JavaScript Meets Java</title>
<body bgcolor="#FFFFFF">
<center><h2>Java Fun: See the pretty applet ...</h2></center><p>
<applet code="ScrollingText.class" name="scroller" width="350" height="128">
<param name="DIRECTION" value="RightLeft">
<param name="FONTSIZE" value="40"><param name="TEXT" value="This is a scrolling message ... wheee ...">
<center><h3>JavaScript Magic: Use the form buttons below to modify the applet</h3></center>
<input type=button value="Start" onClick="document.scroller.start()">
<input type=button value="Stop" onClick="document.scroller.stop()">

The Least You Need to Know

Previous Chapter Next Chapter

Beginning of ChapterTable of ContentsBook Home PageQue Home Page

For comments or technical support for our books and software, select Talk to Us.
To order books, call us at 800-716-0044 or 317-228-4366.

© 1997, QUE Corporation, an imprint of Macmillan Publishing USA, a Simon & Schuster Company.