Day 1

An Introduction to Java Programming

by Laura Lemay


CONTENTS

Hello and welcome to Teach Yourself Java in 21 Days! Starting today and for the next few weeks you'll learn all about the Java language and how to use it to create programs that run inside Web pages (called applets) and programs that can run on their own (called applications).

That's the overall goal for the next couple weeks. Today, the goals are somewhat more modest, and you'll learn about the following:

What Is Java?

Based on the enormous amount of press Java is getting and the amount of excitement it has generated, you may get the impression that Java will save the world-or at least solve all the problems of the Internet. Not so. Java's hype has run far ahead of its capabilities, and while Java is indeed new and interesting, it really is another programming language with which you write programs that run on the Internet. In this respect, Java is closer to popular programming languages such as C, C++, Visual Basic, or Pascal, than it is to a page description language such as HTML, or a very simple scripting language such as JavaScript.

More specifically, Java is an object-oriented programming language developed by Sun Microsystems, a company best known for its high-end UNIX workstations. Modeled after C++, the Java language was designed to be small, simple, and portable across platforms and operating systems, both at the source and at the binary level, which means that Java programs (applets and applications) can run on any machine that has the Java virtual machine installed (you'll learn more about this later).

Java is usually mentioned in the context of the World Wide Web, where browsers such as Netscape's Navigator and Microsoft's Internet Explorer claim to be "Java enabled." Java enabled means that the browser in question can download and play Java programs, called applets, on the reader's system. Applets appear in a Web page much the same way as images do, but unlike images, applets are dynamic and interactive. Applets can be used to create animation, figures, forms that immediately respond to input from the reader, games, or other interactive effects on the same Web pages among the text and graphics. Figure 1.1 shows an applet running in Netscape 3.0. (This applet, at http://prominence.com/java/poetry/, is an electronic version of the refrigerator magnets that you can move around to create poetry or messages.)

Figure 1.1 : Netscape running a Java applet.

New Term
Applets are programs that are downloaded from the World Wide Web by a Web browser and run inside an HTML Web page. You'll need a Java-enabled browser such as Netscape Navigator or Microsoft's Internet Explorer to run applets.

To create an applet, you write it in the Java language, compile it using a Java compiler, and refer to that applet in your HTML Web pages. You put the resulting HTML and Java files on a Web site in the same way that you make ordinary HTML and image files available. Then, when someone using a Java-enabled browser views your page with the embedded applet, that browser downloads the applet to the local system and executes it, allowing your reader to view and interact with your applet in all its glory. (Readers using other browsers may see text, a static graphic, or nothing.) You'll learn more about how applets, browsers, and the World Wide Web work together later in this book.

While applets are probably the most popular use of Java, the important thing to understand about Java is that you can do so much more with it than create and use applets. Java was written as a full-fledged general-purpose programming language in which you can accomplish the same sorts of tasks and solve the same sorts of problems that you can in other programming languages, such as C or C++.

Java's Past, Present, and Future

The Java language was developed at Sun Microsystems in 1991 as part of a research project to develop software for consumer electronics devices-television sets, VCRs, toasters, and the other sorts of machines you can buy at any department store. Java's goals at that time were to be small, fast, efficient, and easily portable to a wide range of hardware devices. Those same goals made Java an ideal language for distributing executable programs via the World Wide Web and also a general-purpose programming language for developing programs that are easily usable and portable across different platforms.

The Java language was used in several projects within Sun (under the name Oak), but did not get very much commercial attention until it was paired with HotJava. HotJava, an experimental World Wide Web browser, was written in 1994 in a matter of months, both as a vehicle for downloading and running applets and also as an example of the sort of complex application that can be written in Java. Although HotJava got a lot of attention in the Web community, it wasn't until Netscape incorporated HotJava's ability to play applets into its own browser that Java really took off and started to generate the excitement that it has both on and off the World Wide Web. Java has generated so much excitement, in fact, that inside Sun the Java group spun off into its own subsidiary called JavaSoft.

Versions of Java itself, or, as it's most commonly called, the Java API, correspond to versions of Sun's Java Developer's Kit, or JDK. As of this writing, the current version of the JDK is 1.0.2. Previously released versions of the JDK (alphas and betas) did not have all the features or had a number of security-related bugs. Most Java tools and browsers conform to the features in the 1.0.2 JDK, and all the examples in this book run on that version as well.

The next major release of the JDK and therefore of the Java API will be 1.1, with a prerelease version available sometime in the later part of 1996. This release will have few changes to the language, but a number of additional capabilities and features added to the class library. Throughout this book, if a feature will change or will be enhanced in 1.1, we'll let you know, and in the last two days of this book you'll find out more about new Java features for 1.1 and for the future.

Currently, to program in Java, you'll need a Java development environment of some sort for your platform. Sun's JDK works just fine for this purpose and includes tools for compiling and testing Java applets and applications. In addition, a wide variety of excellent Java development environments have been developed, including Sun's own Java Workshop, Symantec's Café, Microsoft's Visual J++ (which is indeed a Java tool, despite its name), and Natural Intelligence's Roaster, with more development tools appearing all the time.

To run and view Java applets, you'll need a Java-enabled browser or other tool. As mentioned before, recent versions of Netscape Navigator (2.0 and higher) and Internet Explorer (3.0) can both run Java applets. (Note that for Windows you'll need the 32-bit version of Netscape, and for Macintosh you'll need Netscape 3.0.) You can also use Sun's own HotJava browser to view applets, as long as you have the 1.0 prebeta version (older versions are not compatible with newer applets, and vice versa). Even if you don't have a Java-enabled browser, many development tools provide simple viewers with which you can run your applets. The JDK comes with one of these; it's called the appletviewer.

Note
If you're running Windows 3.x as your main system, very few tools exist for you to be able to work with Java. As I write this, the only Java tool available for writing and running Java applets is a version of the JDK from IBM called the ADK. You can write applets using this tool, and view them using the applet viewer that comes with that package (neither Netscape nor Internet Explorer will run Java applets on Windows 3.1). See http://www.alphaWorks.ibm.com/ for more information.

What's in store for Java in the future? A number of new developments have been brewing (pardon the pun):

Why Learn Java?

At the moment, probably the most compelling reason to learn Java-and probably the reason you bought this book-is that applets are written in Java. Even if that were not the case, Java as a programming language has significant advantages over other languages and other environments that make it suitable for just about any programming task. This section describes some of those advantages.

Java Is Platform Independent

Platform independence-that is, the ability of a program to move easily from one computer system to another-is one of the most significant advantages that Java has over other programming languages, particularly if your software needs to run on many different platforms. If you're writing software for the World Wide Web, being able to run the same program on many different systems is crucial to that program's success. Java is platform independent at both the source and the binary level.

New Term
Platform independence means that a program can run on any computer system. Java programs can run on any system for which a Java virtual machine has been installed.

At the source level, Java's primitive data types have consistent sizes across all development platforms. Java's foundation class libraries make it easy to write code that can be moved from platform to platform without the need to rewrite it to work with that platform. When you write a program in Java, you don't need to rely on features of that particular operating system to accomplish basic tasks. Platform independence at the source level means that you can move Java source files from system to system and have them compile and run cleanly on any system.

Platform independence in Java doesn't stop at the source level, however. Java compiled binary files are also platform independent and can run on multiple platforms (if they have a Java virtual machine available) without the need to recompile the source.

Normally, when you compile a program written in C or in most other languages, the compiler translates your program into machine code or processor instructions. Those instructions are specific to the processor your computer is running-so, for example, if you compile your code on an Intel-based system, the resulting program will run only on other Intel-based systems. If you want to use the same program on another system, you have to go back to your original source code, get a compiler for that system, and recompile your code so that you have a program specific to that system. Figure 1.2 shows the result of this system: multiple executable programs for multiple systems.

Figure 1.2 : Traditional compiled programs.

Things are different when you write code in Java. The Java development environment actually has two parts: a Java compiler and a Java interpreter. The Java compiler takes your Java program and, instead of generating machine codes from your source files, it generates bytecodes. Bytecodes are instructions that look a lot like machine code, but are not specific to any one processor.

To execute a Java program, you run a program called a bytecode interpreter, which in turn reads the bytecodes and executes your Java program (see Figure 1.3). The Java bytecode interpreter is often also called the Java virtual machine or the Java runtime.

Figure 1.3 : Java programs.

New Term
Java bytecodes are a special set of machine instructions that are not specific to any one processor or computer system. A platform-specific bytecode interpreter executes the Java bytecodes. The bytecode interpreter is also called the Java virtual machine or the Java runtime interpreter.

Where do you get the bytecode interpreter? For applets, the bytecode interpreter is built into every Java-enabled browser, so you don't have to worry about it-Java applets just automatically run. For more general Java applications, you'll need to have the interpreter installed on your system in order to run that Java program. Right now, you can get the Java interpreter as part of your development environment, or if you buy a Java program, you'll get it with that package. In the future, however, the Java bytecode interpreter will most likely come with every new operating system-buy a Windows machine, and you'll get Java for free.

Why go through all the trouble of adding this extra layer of the bytecode interpreter? Having your Java programs in bytecode form means that instead of being specific to any one system, your programs can be run on any platform and any operating or window system as long as the Java interpreter is available. This capability of a single binary file to be executable across platforms is crucial to what makes applets work because the World Wide Web itself is also platform independent. Just as HTML files can be read on any platform, so can applets be executed on any platform that has a Java-enabled browser.

The disadvantage of using bytecodes is in execution speed. Because system-specific programs run directly on the hardware for which they are compiled, they run significantly faster than Java bytecodes, which must be processed by the interpreter. For many basic Java programs, speed may not be an issue. If you write programs that require more execution speed than the Java interpreter can provide, you have several solutions available to you, including being able to link native code into your Java program or using special tools (called just-in-time compilers) to convert your Java bytecodes into native code and speed up their execution. Note that by using any of these solutions, you lose the portability that Java bytecodes provide. You'll learn about each of these mechanisms on Day 20, "Using Native Methods and Libraries."

Java Is Object Oriented

To some, the object-oriented programming (OOP) technique is merely a way of organizing programs, and it can be accomplished using any language. Working with a real object-oriented language and programming environment, however, enables you to take full advantage of object-oriented methodology and its capabilities for creating flexible, modular programs and reusing code.

Many of Java's object-oriented concepts are inherited from C++, the language on which it is based, but it borrows many concepts from other object-oriented languages as well. Like most object-oriented programming languages, Java includes a set of class libraries that provide basic data types, system input and output capabilities, and other utility functions. These basic libraries are part of the standard Java environment, which also includes simple libraries, form networking, common Internet protocols, and user interface toolkit functions. Because these class libraries are written in Java, they are portable across platforms as all Java applications are.

You'll learn more about object-oriented programming and Java tomorrow.

Java Is Easy to Learn

In addition to its portability and object orientation, one of Java's initial design goals was to be small and simple, and therefore easier to write, easier to compile, easier to debug, and, best of all, easy to learn. Keeping the language small also makes it more robust because there are fewer chances for programmers to make mistakes that are difficult to fix. Despite its size and simple design, however, Java still has a great deal of power and flexibility.

Java is modeled after C and C++, and much of the syntax and object-oriented structure is borrowed from the latter. If you are familiar with C++, learning Java will be particularly easy for you because you have most of the foundation already. (In fact, you may find yourself skipping through the first week of this book fairly rapidly. Go ahead; I won't mind.)

Although Java looks similar to C and C++, most of the more complex parts of those languages have been excluded from Java, making the language simpler without sacrificing much of its power. There are no pointers in Java, nor is there pointer arithmetic. Strings and arrays are real objects in Java. Memory management is automatic. To an experienced programmer, these omissions may be difficult to get used to, but to beginners or programmers who have worked in other languages, they make the Java language far easier to learn.

However, while Java's design makes it easier to learn than other programming languages, working with a programming language is still a great deal more complicated than, say, working in HTML. If you have no programming language background at all, you may find Java difficult to understand and to grasp. But don't be discouraged! Learning programming is a valuable skill for the Web and for computers in general, and Java is a terrific language to start out with.

Getting Started Programming in Java

Enough background! For the second half of this day let's actually dive into simple Java programming and create two Java programs: a standalone Java application and an applet that you can view in a Java-enabled browser. Although both these programs are extremely simple, they will give you an idea of what a Java program looks like and how to compile and run it.

Getting a Java Development Environment

In order to write Java programs, you will, of course, need a Java development environment. (Although browsers such as Netscape allow you to play Java applets, they don't let you write them. For that you'll need a separate tool.) Sun's JDK, which is available for downloading at the JavaSoft Web site (http://www.javasoft.com/) and included on the CD for this book, will do just fine. It runs on Solaris, Windows 95 and NT, and Macintosh. However, despite the JDK's popularity, it is not the easiest development tool to use. If you're used to using a graphical user interface-based development tool with an integrated editor and debugger, you'll most likely find the JDK's command-line interfaces rather primitive. Fortunately, the JDK is not the only tool in town.

As mentioned earlier, a number of third-party development environments (called integrated development environments, or IDEs) are also available for developing in Java. These include Sun's Java Workshop for Solaris, Windows NT and Windows 95 (you can get more information about it at http://www.sun.com/developer-products/java/); Symantec's Café for Windows 95, Windows NT, and Macintosh (http://cafe.symantec.com/); Microsoft's Visual J++ for Windows 95 and Windows NT (http://www.microsoft.com/visualj/); and Natural Intelligence's Roaster (http://www.natural.com/pages/products/roaster/index.html). All three are commercial programs, but you might be able to download trial or limited versions of these programs to try them out. You'll learn more about the features and capabilities of the various Java IDEs on Day 22, "Java Programming Tools."

Note
I find the graphical development environments far easier to use than the standard JDK. If you have the money and the time to invest in one of these tools, I highly recommend you do so. It'll make your Java development experience much more pleasant.

Installing the JDK and Sample Files

Sun's JDK for Solaris, Windows, and Macintosh is included as part of the CD-ROM that comes with this book. Also on the CD-ROM are all of the code examples from this book-a great help if you don't want to type them all in again. To install either the JDK or the sample files (or both), use one of the following procedures:

Note
If you don't have access to a CD-ROM drive, you can also get access to these files over the World Wide Web. You can download the JDK itself from http://java.sun.com/products/JDK/1.0.2/ and install it per the instructions on those pages. The sample files from this book are available on the Web site for this book: http://www.lne.com/Web/JavaProf/.
If you download the JDK and source files, as opposed to getting them off the CD-ROM, make sure you read the section "Configuring the JDK" to make sure everything is set up right.


Windows
Sun's JDK runs on Windows 95 and Windows NT. It does not run on Windows 3.x.

To install the JDK or the sample files on Windows, run the Setup program on the CD-ROM (double-clicking the CD icon will do this automatically). By default, the package will be installed into C:\Java; you can install it anywhere on your hard disk that you'd like. You'll be given options to install the JDK, the sample files, and various other extra files; choose the options you want and those files will be installed.

If you've installed the JDK, note that in the directory JDK\lib there is a file called classes.zip. Do not unzip this file; it needs to remain in zip form for it to work correctly. The file JDK\src.zip contains the source code for many of the JDK libraries; you can unzip this one if you like. Make sure if you do that you have a zip program that supports long filenames, or it will not work correctly!

Macintosh
Sun's JDK for Macintosh runs on System 7 (MacOS) for 68KB or Power Mac.

To install the JDK or the sample files on the Macintosh, double-click the installation program on the CD-ROM. By default, the package will be installed into the folder Java on your hard disk; you can install it anywhere on your disk that you'd like. You'll be given options to install the JDK, the sample files, and various other extra files; choose the options you want and those files will be installed.

Solaris
Sun's JDK for Solaris runs on Solaris 2.3, 2.4, and 2.5, as well as the x86 version of Solaris.

The CD-ROM for this book contains the tarred and zipped JDK in the directory jdk/solaris/jdk1.02.tgz. Using the utilities gunzip and tar, you can extract the contents of that file anywhere on the file system you would like. For example, if you copy the .tgz file to your home directory and use the following commands to extract it, you'll end up with a java directory that contains the full JDK:

gunzip ./jdk1.02.tgz
tar xvf ./jdk1.02.tar

Note that in the directory java\lib there is a file called classes.zip. Do not unzip this file; it needs to remain in zip form for it to work correctly. The file java\src.zip contains the source code for many of the JDK libraries; you can unzip this one if you're interested in the source code.

The sample files are also contained on the CD-ROM in authors/authors.tar. Create a directory where the sample files will live (for example, a directory called javasamples in your home directory), copy the authors.tar file there, and then use the tar command to extract it, like this:

mkdir ~/javasamples
cp /cdrom/authors/authors.tar
tar xvf authors.tar

Configuring the JDK

If you've installed the JDK using the setup programs from the CD-ROM, chances are good that it has been correctly configured for you. However, because most common problems with Java result from configuration errors, I recommend that you double-check your configuration to make sure everything is right. And if you've installed the JDK from a source other than the CD-ROM, you'll definitely want to read this section to make sure you're all set up.

Windows
The JDK needs two important modifications to your autoexec.bat file in order to work correctly: The JDK\bin directory must be in your execution path, and you must have the CLASSPATH variable set up.

Edit your autoexec.bat file using your favorite editor (Notepad will do just fine). Look for a line that looks something like this:

PATH C:\WINDOWS;C:\WINDOWS\COMMAND;C:\DOS; ...

Somewhere in that line you should see an entry for the JDK; if you installed the JDK from CD-ROM, it'll look something like this (the dots are there to indicate that there may be other stuff on this line):

PATH C:\WINDOWS; ... C:\TEAchY~1\JDK\BIN; ...

If you cannot find any reference to JDK\BIN or JAVA\BIN in your PATH, you'll need to add it. Simply include the full pathname to your JDK installation to the end of that line, starting with C: and ending with BIN; for example, C:\JAVA\BIN or C:\Java\JDK\BIN.

Note
The directories Teach Yourself Java and TEAchY~1 are actually the same thing; the former is how the directory appears in Windows 95, and the latter is how it appears in DOS. Either one will work fine; there's no need to change it if one or the other appears. Note, however, that if the pathname contains spaces, it must be in quotes.

The second thing you'll need to add to the autoexec.bat file (if it isn't already there) is a CLASSPATH variable. Look for a line that looks something like this:

SET CLASSPATH=C:\TEAchY~1\JDK\lib\classes.zip;.;

The CLASSPATH variable may also have other entries in it for Netscape or Internet Explorer, but the one you're most interested in is a reference to the classes.zip file in the JDK, and to the current directory (.). If your autoexec.bat file does not include either of these locations, add a line to the file that contains both these things (the line shown above will work just fine).

After saving your autoexec.bat file, you'll need to restart Windows for the changes to take effect.

Macintosh
The JDK for Macintosh should need no further configuration after installation.

Solaris
To configure the JDK for Solaris, all you need to do is add the java/bin or jdk/bin directory to your execution path. Usually a line something like this in your .cshrc, .login, or .profile files will work:

set path= (~/java/bin/ $path)

This line assumes that you've installed the JDK (as the directory java) into your home directory; if you've installed it somewhere else, you'll want to substitute that pathname.

Make sure you use the source command with the name of the appropriate file to make sure the changes take effect (or log out and log back in again):

source ~/.login

Creating a Java Application

Now let's actually get to work. We'll start by creating a simple Java application: the classic Hello World example that many programming language books use to begin.

Java applications are different from Java applets. Applets, as you have learned, are Java programs that are downloaded over the World Wide Web and executed by a Web browser on the reader's machine. Applets depend on a Java-enabled browser in order to run.

New Term
Java applications, however, are more general programs written in the Java language. Java applications don't require a browser to run; in fact, Java can be used to create all the kinds of applications that you would normally use a more conventional programming language to create.

Java applications are standalone Java programs that do not require a Web browser to run. Java applications are more general-purpose programs such as you'd find on any computer.

A single Java program can be an applet or an application, or both, depending on how you write that program and the capabilities that program uses. Throughout this first week as you learn the Java language, you'll be writing mostly applications; then you'll apply what you've learned to write applets in Week 2. If you're eager to get started with applets, be patient. Everything that you learn while you're creating simple Java applications will apply to creating applets, and it's easier to start with the basics before moving onto the hard stuff. You'll be creating plenty of applets in Week 2.

Creating the Source File

As with all programming languages, your Java source files are created in a plain text editor, or in an editor that can save files in plain ASCII without any formatting characters. On UNIX, emacs, pico, and vi will work; on Windows, Notepad or DOS Edit are both text editors that will work (although I prefer to use the shareware TextPad). On the Macintosh, SimpleText (which came with your Mac) or the shareware BBedit will work. If you're using a development environment like Café or Roaster, it'll have its own built-in text editor you can use.

Note
If you're using Windows to do your Java development, you may have to make sure Windows understands the .java file extension before you start; otherwise, your text editor may insist on giving all your files a .txt extension. The easiest way to do this is to go to any Windows Explorer window, choose View|Options|File Types, choose New Type, and add Java Source File and .java to the Description of Type and Associated Extension boxes, respectively.

Fire up your editor of choice and enter the Java program shown in Listing 1.1. Type this program, as shown, in your text editor. Be careful that all the parentheses, braces, and quotes are there, and that you've used all the correct upper- and lowercase letters.

Note
You can also find the code for these examples on the CD-ROM as part of the sample code. However, it's a good idea to actually type these first few short examples in so that you get a feel for what Java code actually looks like.


Listing 1.1. Your first Java application.
1: class HelloWorld {
2:     public static void main (String args[]) {
3:         System.out.println("Hello World!");
4:     }
5: }

Warning
The number before each line is part of the listing and not part of the program; the numbers are there so I can refer to specific line numbers when I explain what's going on in the program. Do not include them in your own file.

After you've finished typing in the program, save the file somewhere on your disk with the name HelloWorld.java. This is very important. Java source files must have the same name as the class they define (including the same upper- and lowercase letters), and they must have the extension .java. Here, the class definition has the name HelloWorld, so the filename must be HelloWorld.java. If you name your file something else (even something like helloworld.java or Helloworld.java), you won't be able to compile it. Make absolutely certain the name is HelloWorld.java.

You can save your Java files anywhere you like on your disk, but I like to have a central directory or folder to keep them all in. For the examples in this chapter, I've put my files into a directory called TYJtests (short for Teach Yourself Java Tests).

Compiling and Running the Source File

Now it's time to compile the file. If you're using the JDK, you can use the instructions for your computer system contained in the next few pages. If you're using a graphical development environment, there will most likely be a button or option to compile the file (check with the documentation that came with your program).

Windows
To compile the Java source file, you'll use the command-line Java compiler that comes with the JDK. To run the compiler, you'll need to first start up a DOS shell. In Windows 95, the DOS shell is under the Programs menu (it's called MS-DOS Prompt).

From inside DOS, change directories to the location where you've saved your HelloWorld.java file. I put mine into the directory TYJtests, so to change directories I'd use this command:

CD C:\TYJtests

Once you've changed to the right directory, use the javac command as follows, with the name of the file as you saved it in Windows (javac stands for Java compiler). Note that you have to make sure you type all the same upper- and lowercase here as well:

javac HelloWorld.java

Note
The reason that I've emphasized using the original filename is that once you're inside the DOS shell, you might notice that your nice long filenames have been truncated to old-style 8.3 names and that, in fact, HelloWorld.java actually shows up as HELLOW~1.jav. Don't panic; this is simply a side effect of Windows 95 and how it manages long filenames. Ignore the fact that the file appears to be HELLOW~1.jav and just use the filename you originally used when you saved the file.

Figure 1.4 shows what I've done in the DOS shell so you can make sure you're following along.

Figure 1.4 : Compiling Java in the DOS shell.

If all goes well, you'll end up with a file called HelloWorld.class (or at least that's what it'll be called if you look at it outside the DOS shell; from inside DOS its called HELLOW~1.cla). That's your Java bytecode file. If you get any errors, go back to your original source file and make sure you typed it exactly as it appears in Listing 1.1 with the same upper- and lowercase. Also make sure the filename has exactly the same upper- and lowercase as the name of the class (that is, both should be HelloWorld).

Once you have a class file, you can run that file using the Java bytecode interpreter. The Java interpreter is called simply java, and you run it from the DOS shell as you did javac. Run your Hello World program like this from the command line, with all the same upper- and lowercase (and note that the argument to the java program does not have a .class extension):

java HelloWorld

If your program was typed and compiled correctly, you should get the phrase Hello World! printed to your screen as a response. Figure 1.5 shows how I did it.

Figure 1.5 : Running Java applications in the DOS shell.

Note
Remember, the Java compiler and the Java interpreter are different things. You use the Java compiler (javac) for your Java source files to create .class files, and you use the Java interpreter (java) to actually run your class files.

Macintosh
The JDK for the Mac comes with an application called Java Compiler. To compile your Java source file, simply drag and drop it on top of the Java Compiler icon. The program will compile your Java file and, if there are no errors, create a file called HelloWorld.class in the same folder as your original source file.

Tip
Putting an alias for Java Compiler on the desktop makes it easy to drag and drop Java source files.

If you get any errors, go back to your original source file and make sure you typed it exactly as it appears in Listing 1.1, with the same upper- and lowercase. Also make sure the filename has exactly the same upper- and lowercase as the name of the class (that is, both should be HelloWorld).

Once you've successfully generated a HelloWorld.class file, simply double-click it to run it. The application Java Runner, part of the Mac JDK, will start, and the program will ask you for command-line arguments. Leave that screen blank and click OK. A window labeled stdout will appear with the message Hello World!. Figure 1.6 shows that window.

Figure 1.6 : Running Java applications on the Mac using Java Runner.

That's it! Keep in mind as you work that you use the Java Compiler application to compile your .java files into .class files, which you can then run using Java Runner.

To compile the Java source file in Solaris, you'll use the command-line Java compiler that comes with the JDK. From a UNIX command line, cd to the directory that contains your Java source file. I put mine in the directory TYJtests, so to change directories I'd use this command:

cd ~/TYJtests

Once you're in the right directory, use the javac command with the name of the file, like this:

javac HelloWorld.java

If all goes well, you'll end up with a file called HelloWorld.class in the same directory as your source file. That's your Java bytecode file. If you get any errors, go back to your original source file and make sure you typed it exactly as it appears in Listing 1.1, with the same upper- and lowercase letters. Also make sure the filename has exactly the same upper- and lowercase letters as the name of the class (that is, both should be HelloWorld).

Once you have a class file, you can run that file using the Java bytecode interpreter. The Java interpreter is called simply java, and you run it from the command line as you did javac, like this (and note that the argument to the java program does not have a .class extension):

java HelloWorld

If your program was typed and compiled correctly, you should get the phrase Hello World! printed to your screen as a response. Figure 1.7 shows a listing of all the commands I used to get to this point (the part with [desire]~[1] is my system prompt).

Figure 1.7 : Compiling and running a Java application on Solaris.

Note
Remember that the Java compiler and the Java interpreter are different things. You use the Java compiler (javac) for your Java source files to create .class files, and you use the Java interpreter (java) to actually run your class files.

Creating a Java Applet

Creating applets is different from creating a simple application. Java applets run and are displayed inside a Web page with other page elements, and therefore have special rules for how they behave. Because of these special rules for applets, creating an applet may in many cases be more complex than creating an application.

For example, to create a simple Hello World applet, instead of merely being able to print a message as a set of characters, you have to make space for your message on the Web pages and then use special font and graphics operations to paint the message to the screen.

Note
Actually, you can run a plain Java application as an applet, but the Hello World message will print to a special window or to a log file, depending on how the browser has its output set up. You'll learn more about this next week.

Creating the Source File

In this example, you'll create a simple Hello World applet, place it inside a Web page, and view the result. As with the Hello World application, you'll first create the source file in a plain text editor. Listing 1.2 shows the code for the example.


Listing 1.2. The Hello World applet.
1: import java.awt.Graphics;
2: 
3: public class HelloWorldApplet extends java.applet.Applet {
4: 
5:     public void paint(Graphics g) {
6:        g.drawString("Hello world!", 5, 25);
7:    }
8:}

Save that file just as you did the Hello World application, with the filename exactly the same as the name of the class. In this case the class name is HelloWorldApplet, so the filename you save it to would be HelloWorldApplet.java. As with the application, I put the file in a directory called TYJch01, but you can save it anywhere you like.

Compiling the Source File

The next step is to compile the Java applet file. Despite the fact that this is an applet, you compile the file exactly the same way you did the Java application, using one of the following procedures:

javac HelloWorldApplet.java
javac HelloWorldApplet.java

Windows
From inside a DOS shell, cd to the directory containing your applet source file, and use the javac command to compile it (watch those upper- and lowercase letters):

Macintosh
Drag and drop the HelloWorldApplet.java file onto the Java Compiler icon.


Salaris
From a command line, cd to the directory containing your applet source file and use the javac command to compile it:

Including the Applet in a Web Page

If you've typed the file correctly, you should end up with a file called HelloWorldApplet.class in the same directory as your source file. That's your Java applet file; to have the applet run inside a Web page you must refer to that class file inside the HTML code for that page using the <APPLET> tag. Listing 1.3 shows a simple HTML file you can use.


Listing 1.3. The HTML with the applet in it.
1: <HTML>
2: <HEAD>
3: <TITLE>Hello to Everyone!</TITLE>
4: </HEAD><BODY>
5: <P>My Java applet says:
6: <APPLET CODE="HelloWorldApplet.class" WIDTH=150 HEIGHT=25>
7: </APPLET>
8: </BODY>
9: </HTML>

You'll learn more about <APPLET> later in this book, but here are two things to note about it:

Save the HTML file in the same directory as your class file, with a descriptive name and an .html extension (for example, you might name your HTML file the same name as your applet-HelloWorldApplet.html).

Note
As mentioned earlier with the Java source files, your text editor may insist on naming your HTML files with a .txt extension if Windows does not understand what the .html extension is used for. Select View|Options|File Types from any Windows Explorer window to add a new file type for HTML files to solve this problem.

Now you're ready for the final test-actually viewing the result of running your applet. To view the applet, you need one of the following:

If you're using a Java-enabled browser such as Netscape to view your applet files, you can use the Open File... item under the File menu to navigate to the HTML file containing the applet (make sure you open the HTML file and not the class file). In Internet Explorer, select File|Open and then Browse to find the file on your disk. You don't need to install anything on a Web server yet; all this works on your local system. Note that the Java applet may take a while to start up after the page appears to be done loading; be patient. Figure 1.8 shows the result of running the applet in Netscape.

Figure 1.8 : The applet running in Netscape.

If you don't have a Web browser with Java capabilities built into it, you can use the JDK's appletviewer program to view your Java applet.

appletviewer HTML/HelloWorldApplet.html

Windows or Solaris
To run the appletviewer in Windows or Solaris versions of the JDK, cd to the directory where your HTML and class files are contained and use the appletviewer command with the name of the HTML file you just created:

The appletviewer will show you only the applet itself, not the HTML text around the applet. Although the appletviewer is a good way to do simple tests of Java applets, it's a better idea to get a Java-enabled browser so that you can see your applet on its page in its full glory.

Troubleshooting

If you've run into any problems with the previous examples, this section can help. Here are some of the most common problems and how to fix them:

Summary

Today you've gotten a basic introduction to the Java language and its goals and features. Java is a programming language, similar to C or C++, in which you can develop a wide range of programs. The most common use of Java at the moment is in creating applets for HotJava, an advanced World Wide Web browser also written in Java. Applets are Java programs that are downloaded and run as part of a Web page. Applets can create animation, games, interactive programs, and other multimedia effects on Web pages.

Java's strengths lie in its portability-both at the source and at the binary level, in its object-oriented design-and in its simplicity. Each of these features helps make applets possible, but they also make Java an excellent language for writing more general-purpose programs that do not require a Java-enabled browser to run. These general-purpose Java programs are called applications.

To end this day, you experimented with an example of an applet and an example of an application, getting a feel for the differences between the two and how to create, compile, and run Java programs-or, in the case of applets, how to include them in Web pages. From here, you now have the foundation to create more complex applications and applets. Onward to Day 2, "Object-Oriented Programming and Java"!

Q&A

Q:
I know a lot about HTML, but not much about computer programming. Can I still write Java programs?
A:
If you have no programming experience whatsoever, you most likely will find programming Java significantly more difficult than HTML. However, Java is an excellent language to learn programming with, and if you patiently work through the examples and the exercises in this book, you should be able to learn enough to get started with Java.
Q:
What's the relationship between JavaScript and Java?
A:
They have the same first four letters.
A common misconception in the Web world today is that Java and JavaScript have more in common than they actually do. Java is the general-purpose programming language that you'll learn about in this book; you use it to create applets. JavaScript is a Netscape-invented scripting language that looks sort of like Java; with it you can do various nifty things in Web pages. They are independent languages, used for different purposes. If you're interested in JavaScript programming, you'll want to pick up another book, such as Teach Yourself JavaScript in a Week or Laura Lemay's Web Workshop: JavaScript, both also available from Sams.net Publishing.
Q:
According to today's lesson, Java applets are downloaded via a Java-enabled browser such as Netscape and run on the reader's system. Isn't that an enormous security hole? What stops someone from writing an applet that compromises the security of my system-or worse, that damages my system?
A:
Sun's Java team has thought a great deal about the security of applets within Java-enabled browsers and has implemented several checks to make sure applets cannot do nasty things:
  • Java applets cannot read or write to the disk on the local system.
  • Java applets cannot execute any programs on the local system.
  • Java applets cannot connect to any machines on the Web except for the server from which they are originally downloaded.

Note that some of these restrictions may be allowed in some browsers or may be turned on in the browser configuration. However, you cannot expect any of these capabilities to be available.

In addition, the Java compiler and interpreter check both the Java source code and the Java bytecodes to make sure that the Java programmer has not tried any sneaky tricks (for example, overrunning buffers or stack frames).

These checks obviously cannot stop every potential security hole (no system can promise that!), but they can significantly reduce the potential for hostile applets. You'll learn more about security issues for applets on Day 8, "Java Applet Basics," and in greater detail on Day 21, "Under the Hood."

Q:
I followed all the directions you gave for creating a Java applet. I loaded it into HotJava, but Hello World didn't show up. What did I do wrong?
A:
Don't use HotJava to view applets you've created in this book; get a more up-to-date browser such as Netscape or Internet Explorer. HotJava was an experimental browser and has not been updated since soon after its original release. The steps you take to define and write an applet have changed since then, and the applets you write now will not run on HotJava.
Q:
You've mentioned Solaris, Windows, and Macintosh in this chapter. What about other operating systems?
A:
If you use a flavor of UNIX other than Solaris, chances are good that the JDK has been ported to your system. Here are some examples:

(Thanks to Elliote Rusty Harold's Java FAQ at http://www.sunsite.unc.edu/javafaq/javafaq/html for this information.)

Q:
Why doesn't Java run on Windows 3.1?
A:
Technical limitations in Windows 3.1 make porting Java to Windows 3.1 particularly difficult. Rumor has it that both IBM and Microsoft are working on ports, but no real information is forthcoming.
Q:
I'm using Notepad on Windows to edit my Java files. The program insists on adding a .txt extension to all my files, regardless of what I name them (so I always end up with files like HelloWorld.java.txt). Short of renaming them before I compile them, what else can I do to fix this?
A:
Although you can rename the files just before you compile them, that can get to be a pain, particularly when you have a lot of files. The problem here is that Windows doesn't understand the .java extension (you may also have this problem with HTML's .html extension as well).

To fix this, go into any Windows Explorer window and select View|Options|File Types. From that panel, select New Type. Enter Java Source Files in the Description of Type box and .java into the Associated Extension box. Then click OK. Do the same with HTML files if you need to, and click OK again. You should now be able to use Notepad (or any other text editor) to create and save Java and HTML files.

Q:
Where can I learn more about Java and find applets and applications to play with?
A:
You can read the rest of this book! Here are some other places to look for Java information and Java applets:
  • The Java home page at http://www.java.sun.com/ is the official source for Java information, including information about the JDK, about the upcoming 1.1 release, and about developer tools such as the Java Workshop, as well as extensive documentation.
  • Gamelan, at http://www.gamelan.com/, is a repository of applets and Java information, organized into categories. If you want to play with applets or applications, this is the place to look.
  • For Java discussion, check out the comp.lang.java newsgroups, including comp.lang.java.programmer, comp.lang.java.tech, comp.lang.java.advocacy, and so on. (You'll need a Usenet newsreader to access these newsgroups.)