Chapter 2

Getting Started with the JDK


CONTENTS


After reading about the features of the Java programming language in Chapter 1, "Introducing Java," you are probably eager to get started. Before you can dive into development for Java, you need to install a developer's environment on your computer. Although commercial vendors are racing to get Java development packages to the market, everything you need to get started creating hot new Java applications is available directly from JavaSoft. This free development environment straight from the creators of Java is called the Java Developer's Kit, or JDK.

To give you a jump start on Java development, this chapter details how to obtain, install, and configure the JDK on your computer. After you read the section on the Java environment, you might want to jump to the section detailing how to install a Java developer's environment on your particular computer system. In this chapter, you will find sections designed to give you a quick start no matter what operating system you use. You will find quick starts for UNIX platforms, including Solaris and AIX; Windows 95/NT; Macintosh; and OS/2.

If you are a current C/C++ programmer, insight into making the transition from C/C++ to Java is also essential for getting started with Java. For this reason, the chapter covers key concepts for making that transition.

The Java Developer's Environment

The development environment for Java is surprisingly rich, especially considering that the Java programming language is fairly new. Most Java developers and programmers find that the JDK contains everything they need to get started creating powerful Java programs. This is because the developer's kit includes the Java programming language core functionality, the Java Application Programming Interface (API) complete with multiple package sets, and essential tools for creating Java programs.

The Java Developer's Kit is currently available for most operating systems. You can obtain the Sun Solaris, Windows 95/NT, and Macintosh versions directly from JavaSoft. Because the JavaSoft FTP site is extremely busy, however, you might have to use a mirror site to obtain the source code for the JDK. Table 2.1 is a list of the main JavaSoft FTP site and mirror sites for the Solaris, Windows 95/NT, and Macintosh versions of the JDK.

When you access one of the FTP sites listed in this section, you will want to use the directory path given instead of the full path to the JDK. This will allow you to see the entire contents of the associated directory. In this way, you can download the most current version of the JDK for your system.

Table 2.1. FTP sites for the Java JDK.
Site
URL Path to JDK
FTP Site
JavaSoft FTPftp://ftp.javasoft.com/pub ftp.javasoft.com
USA mirrorftp://sunsite.unc.edu/pub/languages/java sunsite.unc.edu
USA mirrorftp://java.dnx.com java.dnx.com
UK mirrorftp://sunsite.doc.ic.ac.uk/packages/java sunsite.doc.ic.ac.uk
Sweden mirrorftp://ftp.luth.se/pub/infosystems/www/hotjava ftp.luth.se
German mirrorftp://sunsite.informatik.rwth-de/pub/mirror/ Âjava.sun.comaachen.de sunsite.informatik
Ârwth-de.
Japan mirrorftp://ftp.glocom.ac.jp/mirror/java.sun.com ftp.glocom.ac.jp
Korea mirrorftp://ftp.kaist.ac.kr/pub/java ftp.kaist.ac.kr

Other versions of the JDK also are available. You will find versions for OS/2, AIX, and most UNIX platforms. The OS/2 and AIX versions of the JDK are available from IBM, but you have to register to use the IBM developers area. You can access IBM's online registration form at the following URL:

http://www.hursley.ibm.com/javainfo/download/index.html

There is, in fact, little difference in the actual workings of the developer's environment for most UNIX versions of the JDK. This means that once you obtain a JDK source for your computer, you can use most of the tips you will find in the Solaris section to help you get started. Because there are some key differences in the AIX configuration of the JDK, AIX users will find a section that outlines these differences.

Similarly, the OS/2 version of the JDK strongly relates to the Windows 95/NT version of the JDK. Therefore, although you will find a section for OS/2, you should first review the Windows 95/NT installation instructions.

The Java API and Core Language Functions

The heart of the Java programming language is contained in a set of packages called java.lang, which is a part of the Java Application Programming Interface. Although the java.lang package provides the core functionality of the Java programming language, it is not the only package included in the Java Developer's Kit.

The JDK includes the following packages: java.applet, java.awt, java.awt.image, java.awt.peer, java.io, java.lang, java.net, and java.util. These packages provide everything you need to start creating powerful Java applications quickly. The JDK also includes an additional package called sun.tools.debug, which is designed to make the application-debugging process easier.

Currently, you can also obtain the Java database connectivity application programming interface, which enables developers to write Java applications that access databases. The initial specification for the Java database classes was released in March 1996. A brief explanation of all packages currently available is shown in Table 2.2. (See Part IV, "The Java Application Programming Interface," for the complete inside scoop, including the hot new database classes.)

Table 2.2. Java packages.
Package
Package Name
Description
java.applet AppletA set of classes that relate to the applet environment and are generally used when viewing applets
java.awt Abstract Windowing ToolkitA set of classes that provide graphical interface tools such as buttons, controls, scrollbars, and windows
java.awt.image AWT ImageA set of classes related to using images
java.awt.peer AWT PeerA set of classes for AWT peer classes and methods
java.sql Database connectivityA set of classes that enable developers to write Java applications that access databases
java.io I/OA set of classes that provide standard input/output and file I/O utilities
java.lang LanguageThe core set of classes for the Java language that provide basic functions, such as string and array handling
java.net NetworkA set of classes that provide tools for accessing networks by protocols, such as FTP, Telnet, and HTTP
java.util UtilityA set of classes that provide core utility functions such as encoding/decoding, hash tables, and stacks
sun.tools.debug DebugA set of classes that provide debugging functions and tools

Tools in the JDK

The Java Developer's Kit includes many terrific tools that make programming in Java a joy. You use these tools to create Java bytecode, to view your programs, and to debug your code. In the current version of the JDK, the Java interpreter and the Java compiler have been modified to load classes from zip files. Table 2.3 shows a brief description of these tools. (See Chapter 5, "Java Tools and the JDK: A Primer," for a detailed description of how to use these tools.)

Table 2.3. Tools in the JDK.
Executable
Tool Name
Description
appletviewer The Java applet viewerUsed to view applets without a Web browser
java The Java interpreterRuns Java bytecode
javac The Java compilerCompiles Java programs into bytecode
javadoc The Java API documentation generatorCreates API documentation in HTML format from Java source code
javah The Java header and stub file generatorCreates C-language header and stub files from a Java class, which allows your Java and C code to interact
javap The Java class file disassemblerDisassembles Java files and prints out a representation of Java bytecode
jdb The Java language debuggerHelps you find and fix problems in your Java code

Power Start for Solaris

Solaris is the operating system used by most Sun Microsystems UNIX platforms. Because JavaSoft is an operating company of Sun Microsystems, the original Java developer's environment was created for Solaris version 2.3 or higher. Whereas the first developer's environment was very basic and included the HotJava browser and a limited API package set for the Alpha release of Java, the current developer's environment contained in the Java Developer's Kit is quite advanced and includes all the packages and tools discussed earlier in the chapter.

Note
The main operating system used on Sun Microsystems computers was originally called SunOS. When Sun moved to Solaris, the company tried to make a smooth transition to the new environment by calling the revisions of the old operating system Solaris 1.x and calling the new environment Solaris 2.x. The new naming scheme actually caused some confusion and continues to be a source of confusion today. To clear up your own understanding, keep in mind that when someone refers to Solaris 1.x they are referring to the old SunOS 4.x. When someone refers to Solaris 2.x, they are referring to SunOS 5.x. Consequently, Solaris 2.3 and SunOS 5.3 are essentially the same thing.

Because Solaris is a UNIX-based operating system, you should be able to use the tips and suggestions found throughout this section to help you install the JDK on any UNIX platform, providing that the JDK has been specifically compiled for your particular flavor of UNIX. Before installing the JDK, you should ensure that you have enough space on your hard drive for the installation. For Solaris, you retrieve a 4.5MB compressed file. When you install the JDK, you will need an additional 7.9MB of disk space. Although you can remove the compressed JDK file after a successful installation, you still need about 13MB of disk space initially.

Here are the steps to follow to set up a Java developer's environment on your computer:

  1. Obtain the Java Developer's Kit
  2. Install the Java Developer's Kit
  3. Test the installation

Obtaining the Java Developer's Kit

The JDK for Solaris includes the complete set of tools for viewing, creating, and debugging Java programs and the precompiled code packages from the standard API. To obtain the source file for the JDK, you need to open an FTP session with one of the FTP sites listed in the "The Java Developer's Environment" section of this chapter.

Warning:
If you have a pre-release version of the JDK installed on your system, you need to remove it before installing JDK 1.0 or later to remove files and directories that are no longer used with JDK 1.0 or later versions. However, before you do this, you should move any source code you created that is in the directories you will be deleting.
From the shell prompt, you can type the following to remove the previous installation of the JDK in its entirety:
rm -rf \file\path
\file\path is the actual path to the previous installation of Java, such as
rm -rf \java
For JDK 1.0 or later, you do not need to set Java-related environment variables for the base installation to work. You should check to see if you set Java-related environment variables when you last installed the JDK. You can do this by typing the following from the command line:
env | egrep "JAVA_HOME|CLASSPATH|LD_LIBRARY_PATH"
If the egrep command returns no output, you did not set these variables and can continue with the installation. If the egrep command lists settings for these variables, you will want to consider unsetting them in your .cshrc or .profile files as appropriate. You will find a sidebar later in this chapter called "Creating Your Own Packages and Classes for UNIX" that can help you make these changes.

You can obtain the JDK source file from an FTP site in one of two ways:

In the example that follows, the JDK source is downloaded from JavaSoft. If the JavaSoft FTP site is busy, you can obtain the source from any of the mirror sites listed in Table 2.1. Because file paths on the Internet tend to change, you should follow these steps in order:

  1. Change to the directory where you want to install the JDK. When you uncompress and unpack the compressed JDK file later in the installation, you will be creating a directory called java under this directory.
  2. Start the FTP session. You will be prompted to enter a user name and password. Use the name anonymous and a password as youruserid@yourhostname, such as william@tvp.com. Here is how you start an FTP session with the JavaSoft FTP server:
    $ ftp ftp.javasoft.com
    Connected to ftp.javasoft.com.
    220 java3 FTP server ready.
    Name (ftp.javasoft.com): anonymous
    331 Guest login ok, send your complete e-mail address as password.
    Password: userid@hostname.com
    230-
    230-    Welcome to the Java home site.
    230-
    230 Guest login ok, access restrictions apply.
    Remote system type is UNIX.

  3. The JDK binary file is generally located in a subdirectory called pub, so you want to change to the pub directory. On some mirror sites you will have to go through several subdirectories to get to Java's pub subdirectory. For example, on the Sunsite mirror (sunsite.unc.edu) you will have to change directories to pub/languages/java/pub. Start by listing the contents of the current directory and then changing to the pub directory:

    ftp> ls
    200 PORT command successful.
    150 Opening ASCII mode data connection for /bin/ls.
    total 24
    lrwxrwxrwx   1 root     1  7 May 19 20:02 bin -> usr/bin
    dr-xr-xr-x   2 root     1    512 May 19 21:09 dev
    dr-xr-xr-x   2 nobody   1   1536 Jun 21 21:36 docs
    dr-xr-xr-x   2 root     1    512 May 19 20:04 etc
    dr-xr-xr-x   5 500      1    512 Jun 14 01:13 pub
    drwx-wx-wx   2 root     1    512 Jun 22 00:56 tmp
    dr-xr-xr-x   4 nobody   1    512 Jun 19 20:04 usr
    -r--r--r--   1 root     1   1255 May 27 01:33 welcome.msg
    226 Transfer complete.
    ftp> cd pub
    250 CWD command successful.

  4. When you are in the publication directory for the Java programming language, you should list the contents of the directory. You want to download the most current version of the JDK. The most recent Solaris version in the example is JDK-1_1-solaris2-sparc.tar.Z. Download the appropriate source:

    ftp> ls
    200 PORT command successful.
    150 Opening ASCII mode data connection for /bin/ls.
    total 61148
    -r--r--r--   1 root     1    4595974 Jan 23 16:35 JDK-1_1-solaris2-sparc.tar.Z
    -r--r--r--   1 root     1    3720379 Jan 23 16:35 JDK-1_1-win32-x86.exe
    -r--r--r--   1 root     1    2243968 Feb 14 00:56 JDK-1_1-mac.sea.bin
    -r--r--r--   1 root     1    3049734 Feb 14 00:56 JDK-1_1-mac.sea.hqx
    -r--r--r--   1 nobody   1    4508131 Dec 12 18:35 JDK-1_0-solaris2-sparc.tar.Z
    -r--r--r--   1 nobody   1    3717250 Dec 12 18:36 JDK-1_0-win32-x86.exe
    -r--r--r--   1 root     1    15868 Feb 14 00:56 README
    -r--r--r--   1 nobody   1   5476531 Sep 11 02:05
    Âhotjava-beta2-solaris2-sparc.tar.Z
    -r--r--r--   1 nobody   1    3849659 Sep 11 02:06 hotjava-beta2-win32-x86.exe
    226 Transfer complete.
    ftp> bin
    200 Type set to I.
    ftp> get JDK-1_1-solaris2-sparc.tar
    local: JDK-1_1-solaris2-sparc.tar remote: JDK-1_1-solaris2-sparc.tar
    200 PORT command successful.
    150 Opening BINARY mode data connection for JDK-1_1-solaris2-sparc.tar
    Â(4595974 bytes).
    226 Transfer complete.
    4595974 bytes received
    ftp>quit

    Installing the Java Developer's Kit

    After you obtain the source file, you should check to make sure the size of the file you downloaded matches the file size listed on the FTP site. If the file sizes are not identical, your file might have been corrupted during download. In that case, you want to delete the file from your system and try to download the JDK source file again.

    Next, you need to uncompress and unpack the files. You can do this using the following command:

    zcat JDK-1_1-solaris2-sparc.tar.Z | tar xf -
    Note
    The zcat command lists the contents of the compressed files and directories. The output of this is sent to the UNIX tape archive command tar, which extracts the files and directories but does not list the extraction to the screen. Although you should be able to use this command no matter which flavor of UNIX you are running, you can also uncompress and extract the files using the following series of commands:
    uncompress JDK-1_1-solaris2-sparc.tar
    tar -xf JDK-1_1-solaris2-sparc.tar

    Note
    When you uncompress and unpack the compressed JDK file, you will be creating a directory called java under the current directory. If you are installing JDK 1.0 or later versions for Solaris on your system, the following files and subdirectories will be located under the java directory:
    -r--r--r--   1        2826 Jan 12 06:20 COPYRIGHT
    -r--r--r--   1        8195 Jan 16 16:45 README
    drwxr-xr-x   3        1024 Jan 12 11:09 bin
    drwxr-xr-x  25        1024 Jan 12 11:11 demo
    drwxr-xr-x   3        1024 Jan 12 11:09 include
    -r--r--r--   1        1017 Jan 16 16:49 index.html
    drwxr-xr-x   3        1024 Jan 12 11:10 lib
    -rw-rw-r--   1      372227 Jan 16 16:48 src.zip

    The src.zip file contains the source code for some of the classes used in the JDK. Because these classes represent a good cross-section of the functionality introduced by the Java API and are written in the Java programming language, you can learn a lot by examining them. Therefore, I highly recommend that you unzip the src.zip file and make a note to go through some of the files after you read this book. By unzipping the src.zip file, you create the following directory structure on your file system:

    src/
    src/java/
    src/java/lang/
    src/java/util/
    src/java/io/
    src/java/net/
    src/java/awt/
    src/java/awt/peer/
    src/java/awt/test/
    src/java/awt/image/
    src/java/applet/
    src/sun/
    src/sun/tools/
    src/sun/tools/ttydebug/

    All the executables-except for the Java source-level debugger, jdb-come in two forms. Executables with the suffix _g are for debugging and support all of Java's mechanisms for debugging. Executables without the suffix _g are optimized for normal use and support only limited debugging options. You will find the following executable files for the JDK tools in the bin directory:

    java/bin:
    total 5
    -r-xr-xr-x   1         833 Jan 12 06:10 appletviewer
    lrwxrwxrwx   1          13 Feb 23 01:09 java -> .java_wrapper
    lrwxrwxrwx   1          13 Feb 23 01:09 java_g -> .java_wrapper
    lrwxrwxrwx   1          13 Feb 23 01:09 javac -> .java_wrapper
    lrwxrwxrwx   1          13 Feb 23 01:09 javac_g -> .java_wrapper
    -r-xr-xr-x   1          71 Jan 12 06:16 javadoc
    lrwxrwxrwx   1          13 Feb 23 01:09 javah -> .java_wrapper
    lrwxrwxrwx   1          13 Feb 23 01:09 javah_g -> .java_wrapper
    lrwxrwxrwx   1          13 Feb 23 01:09 javap -> .java_wrapper
    lrwxrwxrwx   1          13 Feb 23 01:09 javap_g -> .java_wrapper
    lrwxrwxrwx   1          13 Feb 23 01:09 jdb -> .java_wrapper
    drwxr-xr-x   2        1024 Jan 12 11:09 sparc
    -r-xr-xr-x   1        1911 Jan 12 06:10 upgrade

    Most of the tools in the bin directory are symbolically linked to a Korn shell script called .java_wrapper. The function of the wrapper script is to set the environment variables Java needs if you forget to do it. It does this by finding the location of the Java tool you are trying to execute, backing up one directory, and setting this value to an environment variable called JAVA_HOME. The value for JAVA_HOME is the base directory where you installed the JDK.

    The script then uses the value associated with the JAVA_HOME variable to set two other important environment variables: CLASSPATH and LD_LIBRARY_PATH. The CLASSPATH variable is used to find the Java class files. The wrapper script generally sets this path to

    java/classes:java/lib/classes.zip

    The default CLASSPATH tells the Java interpreter and compiler to look for your class files in the following order:

    1. In the directory java/classes or the equivalent directory on your system
    2. In the zipped file with a file path java/lib/classes.zip or the equivalent file path on your system

    The LD_LIBRARY_PATH variable is used to find essential library files. The wrapper script generally sets this path to java/lib/sparc.

    The final thing the wrapper script does is to locate and execute the tool you are trying to use. The compiled source for most of the Solaris JDK tools is actually located in java/bin/sparc. If you examine the files for the Java compiler and the Java debugger located in java/bin/sparc, you will also find that these are wrapper scripts.

    Although it is good to know where the actual executables for the tools are located, you should only execute them via the wrapper script and from the java/bin directory. For this reason, you might want to add the full file path to java/bin to the search path specified in your .cshrc or .profile file. This will allow you to run the JDK tools without having to specify the full path to the binaries.

    Peter's Principle:
    Creating Your Own Packages and Classes for UNIX
    If you plan to create your own packages or to store Java classes you create in a directory other than the java/classes directory, you should set the CLASSPATH variable to the location you plan to use for your packages and class files. C shell users will want to do this by editing the .cshrc file in your home directory and adding a statement that sets the correct path to your Java classes, such as the following:
    setenv CLASSPATH /myjavaclasses
    The wrapper script is dynamic and will prepend the directories you specify for classes to the default CLASSPATH. This means that if you add the directory /myjavaclasses to the general CLASSPATH default by setting the environment variable as shown, the Java interpreter and compiler will search for Java class files on your system in the following order:
    1. In the directory or directories you specified when you set the CLASSPATH environment variable
    2. In the directory java/classes or equivalent directory on your system
    3. In the zipped file with a file path java/lib/classes.zip or equivalent file path on your system
    For these changes to take effect in the current command tool or shell environment, you will need to source your .cshrc file or type the setenv command at the shell prompt. This updates the current environment settings.
    If you are using Bourne shell as your main UNIX shell, you can set the CLASSPATH in your .profile file. Do this by editing the .profile file in your home directory and adding statements that set and export the CLASSPATH variable's path, such as
    CLASSPATH=/myjavaclasses
    export CLASSPATH
    For these changes to take effect in the current command tool or shell environment, you will need to set the CLASSPATH variable and export it from the command line, like this:
    CLASSPATH=$HOME/java;export CLASSPATH

    Another directory you will want to check is the demo directory. The demo directory contains many demonstration applets. By previewing these demos, you can see Java in action. The include directory contains C-language header and stub files. These files are primarily used to set paths and definitions needed by Java and that are essential to Java interaction with C.

    The lib directory contains essential library files and the zip file for all classes included in the Java API, called classes.zip. Loading classes from zipped files makes it possible to compress the entire contents of the Java API into one file. The Java runtime class loader and the Java compiler extract any class files they need from classes.zip.

    Warning:
    Although you can unzip the src.zip file, you should not unzip the classes.zip file. The classes.zip file contains all the classes and methods in the Java API. If you unzip this file, you will create hundreds of unnecessary files on your hard drive.

    Testing the Installation

    A great way to test your new Java developer's environment is to preview one of the demo applets included in the JDK. As you can see from the following code, each demo applet is located in the demo directory and has its own subdirectory:

    demo:
    total 23
    drwxr-xr-x   4        1024 Jan 12 11:11 Animator
    drwxr-xr-x   2        1024 Jan 12 11:11 ArcTest
    drwxr-xr-x   2        1024 Jan 12 11:11 BarChart
    drwxr-xr-x   2        1024 Jan 12 11:11 Blink
    drwxr-xr-x   4        1024 Jan 12 11:11 BouncingHeads
    drwxr-xr-x   2        1024 Jan 12 11:11 CardTest
    drwxr-xr-x   2        1024 Jan 12 11:11 DitherTest
    drwxr-xr-x   2        1024 Jan 12 11:11 DrawTest
    drwxr-xr-x   2        1024 Jan 12 11:11 Fractal
    drwxr-xr-x   3        1024 Jan 12 11:11 GraphLayout
    drwxr-xr-x   2        1024 Jan 12 11:11 GraphicsTest
    drwxr-xr-x   3        1024 Jan 12 11:11 ImageMap
    drwxr-xr-x   3        1024 Jan 12 11:11 ImageTest
    drwxr-xr-x   3        1024 Jan 12 11:11 JumpingBox
    drwxr-xr-x   3        1024 Jan 12 11:11 MoleculeViewer
    drwxr-xr-x   2        1024 Jan 12 11:11 NervousText
    drwxr-xr-x   3        1024 Jan 12 11:11 ScrollingImages
    drwxr-xr-x   2        1024 Jan 12 11:11 SimpleGraph
    drwxr-xr-x   2        1024 Jan 12 11:11 SpreadSheet
    drwxr-xr-x   4        1024 Jan 12 11:11 TicTacToe
    drwxr-xr-x   3        1024 Jan 12 11:11 TumblingDuke
    drwxr-xr-x   4        1024 Jan 12 11:11 UnderConstruction
    drwxr-xr-x   3        1024 Jan 12 11:11 WireFrame

    In the subdirectories for each demonstration applet, you will find all the files necessary to run the applet and to see how the applet was created. For example, the directory for the TicTacToe applet contains the following:

    TicTacToe.class  The compiled class file for the TicTacToe applet

    TicTacToe.java The source code for the TicTacToe applet

    audio directory Contains AU sound files the applet uses

    example1.html  A sample HTML document for viewing the applet

    images directory  Contains the images the applet uses

    To test the installation, you can view the applet by accessing the example1.html file with your Java-capable Web browser. You can also view the applet using the appletviewer tool that comes with the JDK. If you are currently in the java base directory, you can type the following to view the TicTacToe demo applet with appletviewer:

    bin/appletviewer demo/TicTacToe/example1.html

    The good news is that if you can run the demo applet, your base installation worked correctly. If you have any problems running the TicTacToe applet with appletviewer, check your current path by typing pwd at the shell prompt. You should change directories to the base java directory and try to run appletviewer again. Normally, the base java directory is /java or a subdirectory under your home directory called java.

    If you get the error message Exception in thread NULL when running the Java interpreter, compiler, or appletviewer, you should check the setting for your CLASSPATH environment variable by typing the following from the command line:

    env | grep CLASSPATH

    The current setting for CLASSPATH should not list the class directory from an older JDK release. For Java to run properly on your system, you must set the CLASSPATH variable correctly. If you do not plan to use packages and classes stored in a directory other than the java base directory, you will want to edit your .cshrc or .profile file and remove the line that sets the CLASSPATH variable. If you plan to use packages and classes stored in a directory other than the java base directory, you should update the setting for the CLASSPATH variable. Refer back to the sidebar titled "Creating Your Own Packages and Classes for UNIX" to see how to do this.

    Anyone who wants to maintain a separate class directory should check to see if they have set the CLASSPATH environment variable correctly. An easy way to do this is to temporarily move one of the demonstration class files to the location where you plan to store your Java class files. The new location must be empty if you follow this example.

    From the java/demo/TicTacToe directory, type

    mv TicTacToe.class /destination/file/path

    where /destination/file/path is the actual file path to the destination directory, such as

    mv TicTacToe.class /myclasses/new/TicTacToe.class

    You should now be able to run the TicTacToe demo on appletviewer without having to specify the path to the class file for the applet. From the java/demo/TicTacToe directory, type the following to test this:

      /  /bin/appletviewer example1.html

    If you cannot view the applet, you should check your environment settings by typing the following from the command line:

    env | grep CLASSPATH

    The grep should return your updated setting for CLASSPATH, such as

    CLASSPATH=/myclasses/new

    If the grep command returns no output or the CLASSPATH variable is set incorrectly, refer back to the sidebar "Creating Your Own Packages and Classes for UNIX" for helpful information.

    Power Start for Windows 95/NT

    Members of the Microsoft Windows family of operating systems are the most-used operating systems in the world. Windows 95 is the long-awaited enhancement to Windows 3.1, and Windows NT is a network-optimized version of Windows. After Sun Microsystems created the Solaris version of the Java Developer's Kit, it ported the JDK to Windows NT.

    Because much of the inner workings of the Windows NT operating system are essentially the same as those of the Windows 95 operating system, the JDK was modified for use on both the Windows NT and Windows 95 platforms. The current developer's environment for Windows 95/NT is quite advanced and includes all the packages and tools discussed earlier in this chapter.

    Note
    Although the friendly folks at IBM are working on a Windows 3.1 version of the JDK, at the time of this writing there is not a JDK for Windows 3.1 systems. However, because Windows 95/NT are Windows-based operating systems, you should be able to use the tips and suggestions you'll find throughout this section to help you install the JDK on systems running Windows 3.1 if a version of the JDK specifically compiled for use on Windows 3.1 systems is made available.

    Before installing the JDK, you should ensure that you have enough space on your hard drive for the installation. For Windows 95/NT, you will retrieve a 3.7MB self-extracting archive file. When you install the JDK, you will need an additional 5.6MB of disk space. Although you can remove the self-extracting archive file after a successful installation, you still need about 10MB of disk space initially.

    To set up a Java developer's environment on your computer, follow these steps:

    1. Obtain the Java Developer's Kit
    2. Install the Java Developer's Kit
    3. Test the installation

    Obtaining the Java Developer's Kit

    The JDK for Windows 95/NT includes the complete set of tools for viewing, creating, and debugging Java programs and the precompiled code packages from the standard API. To obtain the source file for the JDK, you need to open an FTP session with one of the FTP sites listed in the section "The Java Developer's Environment" at the beginning of this chapter.

    Warning:
    If you have a prerelease version of the JDK installed on your system, you want to remove it before installing JDK 1.0 or later to remove files and directories that are no longer used with JDK 1.0 or later versions. However, before you do this, you should move any source code you created that is located in the directories you will be deleting. From the MS-DOS prompt, you can type the following to remove the previous installation of the JDK in its entirety:
    deltree /Y C:\file\path
    C:\file\path
    is the actual path to the previous installation of Java, such as
    deltree /Y C:\java
    You should also check to see if you set Java-related file paths when you last installed the JDK. You can do this by typing the following at the MS-DOS prompt:
    TYPE C:\AUTOEXEC.BAT
    This command lists the contents of your AUTOEXEC.BAT file to the MS-DOS prompt window. You should now check for Java-related file paths and environment variables. Java-related file paths include any file paths where the old version of the JDK was installed. Java-related environment variables include JAVA_HOME, CLASSPATH, and LD_LIBRARY_PATH.
    If you did not set Java-related paths, you can continue with the installation. If you set Java-related paths, you want to check the validity of these settings when you follow the steps for setting and/or updating your paths as discussed in the sidebar titled "Setting Your Paths for Java in Windows 95/NT," found in the next section of this chapter.

    You can obtain the JDK source file from an FTP site in one of two ways:

    • With your Web browser, enter the URL path to the FTP site as listed in the "URL Path to JDK" column of Table 2.1.
    • From the shell prompt or Telnet session prompt, open an FTP session to the FTP site as listed in the "FTP Site" column of Table 2.1.

    In the following example, the JDK source is downloaded from JavaSoft. If the JavaSoft FTP site is busy, you can obtain the source from any of the mirror sites listed in Table 2.1. Because file paths on the Internet tend to change, you should follow these steps sequentially:

    1. Start the FTP session. You will be prompted to enter a username and password. Use the name anonymous and a password as youruserid@yourhostname, such as william@tvp.com. Here is how you start an FTP session with the JavaSoft FTP server:

      $ ftp ftp.javasoft.com
      Connected to ftp.javasoft.com.
      220 java3 FTP server ready.
      Name (ftp.javasoft.com): anonymous
      331 Guest login ok, send your complete e-mail address as password.
      Password: userid@hostname.com
      230-
      230-    Welcome to the Java home site.
      230-
      230 Guest login ok, access restrictions apply.
      Remote system type is UNIX.
    2. List the contents of the current directory. The JDK binary file is generally located in a subdirectory called pub, so you want to change to the pub directory. On some mirror sites you have to go through several subdirectories to get to Java's pub subdirectory. For example, on the Sunsite mirror (sunsite.unc.edu) you have to change directories to pub/languages/java/pub. Start by listing the contents of the current directory and then changing to the pub directory:

      ftp> ls
      200 PORT command successful.
      150 Opening ASCII mode data connection for /bin/ls.
      total 24
      lrwxrwxrwx   1 root     1  7 May 19 20:02 bin -> usr/bin
      dr-xr-xr-x   2 root     1    512 May 19 21:09 dev
      dr-xr-xr-x   2 nobody   1   1536 Jun 21 21:36 docs
      dr-xr-xr-x   2 root     1    512 May 19 20:04 etc
      dr-xr-xr-x   5 500      1    512 Jun 14 01:13 pub
      drwx-wx-wx   2 root     1    512 Jun 22 00:56 tmp
      dr-xr-xr-x   4 nobody   1    512 Jun 19 20:04 usr
      -r--r--r--   1 root     1   1255 May 27 01:33 welcome.msg
      226 Transfer complete.
      ftp> cd pub
      250 CWD command successful.
    3. When you are in the publication directory for the Java programming language, you should list the contents of the directory. You want to download the most current version of the JDK. The most recent Windows 95/NT version in the example is JDK-1_1-win32-x86.exe. Download the appropriate source:

      ftp> ls
      200 PORT command successful.
      150 Opening ASCII mode data connection for /bin/ls.
      total 61148
      -r--r--r--   1 root     1    4595974 Jan 23 16:35 JDK-1_1-solaris2-sparc.tar.Z
      -r--r--r--   1 root     1    3720379 Jan 23 16:35 JDK-1_1-win32-x86.exe
      -r--r--r--   1 root     1    2243968 Feb 14 00:56 JDK-1_1-mac.sea.bin
      -r--r--r--   1 root     1    3049734 Feb 14 00:56 JDK-1_1-mac.sea.hqx
      -r--r--r--   1 nobody   1    4508131 Dec 12 18:35
      ÂJDK-beta2-solaris2-sparc.tar.Z
      -r--r--r--   1 nobody   1    3717250 Dec 12 18:36 JDK-1_0-win32-x86.exe
      -r--r--r--   1 root     1    15868 Feb 14 00:56 README
      -r--r--r--   1 nobody   1   5476531 Sep 11 02:05
      Âhotjava-beta2-solaris2-sparc.tar.Z
      -r--r--r--   1 nobody   1    3849659 Sep 11 02:06 hotjava-beta2-win32-x86.exe
      226 Transfer complete.
      ftp> bin
      200 Type set to I.
      ftp> get JDK-1_1-win32-x86.exe
      local: JDK-1_1-win32-x86.exe remote: JDK-1_1-win32-x86.exe
      200 PORT command successful.
      150 Opening BINARY mode data connection for JDK-1_1-win32-x86.exe
      Â(3720379 bytes).
      226 Transfer complete.
      3720379 bytes received
      ftp>quit

    Installing the Java Developer's Kit

    After you obtain the source file, you should check to make sure the size of the file you downloaded matches the file size listed on the FTP site. If the file sizes aren't identical, your file might have been corrupted during download. In that case, you want to delete the file from your system and try to download the JDK source file again.

    To install the JDK from the MS-DOS prompt, follow these steps:

    1. Open a DOS window.
    2. Change to the directory that contains the JDK source file.
    3. Move the JDK to where you want to install it. To install Java in c:\java, which is recommended, you can use the following command:

      move JDK-1_1-win32-x86.exe c:\
    4. The self-extracting file will install itself if you type the name of the executable at the DOS prompt, like this:

      JDK-1_1-win32-x86.exe

    When you run the self-extracting archive file, you will be creating a directory called java under the current directory. If you are installing JDK 1.0 or later for Windows 95/NT on your system, the following files and subdirectories will be located under the java directory:

      Directory of C:\java
    BIN            <DIR>        02-23-96  2:32p bin
    LIB            <DIR>        02-23-96  2:32p lib
    DEMO           <DIR>        02-23-96  2:32p demo
    COPYRI~1             2,826  01-12-96 10:11a COPYRIGHT
    README               8,237  01-16-96  1:46p README
    INDEX~1  HTM         1,017  01-16-96  1:48p index.html
    IncLUDE        <DIR>        02-23-96  2:32p include
    SRC      ZIP       371,854  01-16-96  1:47p src.zip

    The src.zip file contains the source code for some of the classes used in the JDK. Because these classes represent a good cross-section of the functionality introduced by the Java API and are written in the Java programming language, you can learn a lot by examining them. Therefore, I highly recommend that you unzip the src.zip file and make a note to go through the some of the files after you read this book.

    Tip
    The class files in the src.zip file are stored with Windows 95/NT long filenames. You will need an unzip utility, such as WinZip95 or EZ-Zip, that supports long filenames.

    By unzipping the src.zip file, you create the following directory structure on your file system:

    src\
    src\java\
    src\java\lang\
    src\java\util\
    src\java\io\
    src\java\net\
    src\java\awt\
    src\java\awt\peer\
    src\java\awt\test\
    src\java\awt\image\
    src\java\applet\
    src\sun\
    src\sun\tools\
    src\sun\tools\ttydebug\

    You will find the JDK tools in the bin directory. The bin directory contains the following executable and dynamic link library files:

      Directory of C:\java\bin
    JAVAI    DLL       162,304  01-12-96  9:30a javai.dll
    JAVA     EXE         4,608  01-12-96  9:30a java.exe
    JAVAW    EXE         4,608  01-12-96  9:30a javaw.exe
    JAVAP    EXE        72,192  01-12-96  9:30a javap.exe
    JAVAH    EXE        40,448  01-12-96  9:26a javah.exe
    JAVAI_G  DLL       265,216  01-12-96  9:35a javai_g.dll
    JAVA_G   EXE         5,632  01-12-96  9:35a java_g.exe
    JAVAW_G  EXE         6,144  01-12-96  9:35a javaw_g.exe
    JAVAP_G  EXE        98,304  01-12-96  9:35a javap_g.exe
    JAVAH_G  EXE        54,784  01-12-96  9:31a javah_g.exe
    NET      DLL        14,336  01-12-96  9:37a net.dll
    NET_G    DLL        17,920  01-12-96  9:37a net_g.dll
    JAVAC    EXE         4,608  01-12-96  9:40a javac.exe
    JAVAC_G  EXE         6,144  01-12-96  9:40a javac_g.exe
    AGENT    DLL        14,848  01-12-96  9:41a agent.dll
    AGENT_G  DLL        18,432  01-12-96  9:42a agent_g.dll
    JDB      EXE         4,608  01-12-96  9:42a jdb.exe
    JDB_G    EXE         6,144  01-12-96  9:42a jdb_g.exe
    JAVADOC  EXE         4,608  01-12-96  9:43a javadoc.exe
    JAVADO~1 EXE         6,144  01-12-96  9:43a javadoc_g.exe
    AWT      DLL       139,264  01-12-96  9:45a awt.dll
    AWT_G    DLL       177,664  01-12-96  9:46a awt_g.dll
    JPEG     DLL        63,488  01-12-96  9:46a jpeg.dll
    JPEG_G   DLL        89,088  01-12-96  9:47a jpeg_g.dll
    MMEDIA   DLL         6,144  01-12-96  9:47a mmedia.dll
    MMEDIA_G DLL         7,680  01-12-96  9:47a mmedia_g.dll
    APPLET~1 EXE         5,120  01-12-96  9:49a appletviewer.exe
    APPLET~2 EXE         7,168  01-12-96  9:49a appletviewer_g.exe
    MFC30    DLL       322,832  01-12-96  8:00a mfc30.dll
    MSVCRT20 DLL       253,952  01-12-96  8:00a msvcrt20.dll

    The executables and link libraries come in two forms. Those files with the suffix _g are compiled and linked with debugging information. Executables with the suffix _g support all of Java's mechanisms for debugging. Executables without the suffix _g are optimized for normal use and support only limited debugging options. Many of the files in this directory are used by the Java environment itself and are, in fact, the Windows 95/NT interface to Java. They include the following:

    awt.dll Java uses the awt.dll libraries to display graphics and to create graphical interfaces to buttons, scrollbars, and pop-up windows.
    jpeg.dll Java uses the jpeg.dll libraries to interpret and display JPEG images.
    mmedia.dll Java uses the mmedia.dll libraries to perform multimedia functions that include displaying GIF images and playing AU sound files.
    net.dll Java uses the net.dll libraries when you perform network operations.

    Peter's Principle:
    Setting Your Paths for Java in Windows 95/NT
    After installing the JDK, you should update your AUTOEXEC.BAT file so your computer can find the Java executables and class libraries. Follow these steps for updating your AUTOEXEC.BAT file:
    1. Type the following:

      EDIT C:\AUTOEXEC.BAT
    2. Add the full path to the Java executables to your PATH statement, which allows you to run the JDK tools without having to specify the full path to the binaries. If you installed Java under the C:\ directory, which is recommended, you would place the following line after your current PATH statement in your AUTOEXEC.BAT file:

      PATH=%path%;C:\JAVA\BIN
    3. Setting the CLASSPATH variable is optional. However, if you installed a previous version of the JDK, you should either remove the line that assigns the CLASSPATH variable or set the CLASSPATH environment variable to the location of the classes.zip file.

      If you installed Java under the C:\ directory, you would add the following line to your AUTOEXEC.BAT file:

      SET CLASSPATH=C:\JAVA\LIB\CLASSES.ZIP

      If you plan to create your own packages or to store Java classes in a private directory, you should prepend the directory path to the setting for the CLASSPATH variable. For example, if you wanted to store your class files in the directory c:\myclasses, you would set the CLASSPATH variable as follows:

      SET CLASSPATH=C:\MYCLASSES;C:\JAVA\LIB\CLASSES.ZIP
    4. Optionally, if you installed the JDK anywhere other than your file system's root directory and under a directory named java, you will have to set the JAVA_HOME environment variable. If you installed the JDK in C:MYJAVA, you would set this variable as follows:

      SET JAVA_HOME=C:\MYJAVA
    5. Save and close your AUTOEXEC.BAT file.
    6. Reboot your computer. This sets the working environment for all future sessions. You can set your current working environment for use with Java. Your current working environment only applies to the MS-DOS prompt into which you enter the path setting. You must use the actual path to your Java executables. If you installed Java under the C:\ directory, you would type the following at the MS-DOS prompt:

      PATH=%PATH%;C:\JAVA\BIN;

    Another directory you will want to check is the demo directory, which contains many demonstration applets. By previewing these demos, you can see Java in action. The include directory contains C-language header and stub files. These files are primarily used to set paths and definitions needed by Java and essential to Java interaction with C.

    The lib directory contains essential library files and the zipped file for all classes included in the Java API, called classes.zip. Loading classes from zipped files makes it possible to compress the entire contents of the Java API into one file. The Java runtime class loader and the Java compiler extract any class files they need from classes.zip.

    Warning:
    Although you can unzip the src.zip file, you should not unzip the classes.zip file. The classes.zip file contains all the classes and methods in the Java API. If you unzip this file, you will create hundreds of unnecessary files on your hard drive.

    Testing the Installation

    A great way to test your new Java developer's environment is to preview one of the demo applets included in the JDK. As you can see from the following code, each demo applet is located in the demo directory and has its own subdirectory:

      Directory of C:\java\demo
    WIREFR~1       <DIR>        02-23-96  2:32p WireFrame
    TICTAC~1       <DIR>        02-23-96  2:32p TicTacToe
    BOUncI~1       <DIR>        02-23-96  2:32p BouncingHeads
    MOLECU~1       <DIR>        02-23-96  2:32p MoleculeViewer
    ARCTEST        <DIR>        02-23-96  2:32p ArcTest
    DRAWTEST       <DIR>        02-23-96  2:32p DrawTest
    CARDTEST       <DIR>        02-23-96  2:32p CardTest
    SPREAD~1       <DIR>        02-23-96  2:32p SpreadSheet
    BLINK          <DIR>        02-23-96  2:32p Blink
    TUMBLI~1       <DIR>        02-23-96  2:32p TumblingDuke
    NERVOU~1       <DIR>        02-23-96  2:32p NervousText
    FRACTAL        <DIR>        02-23-96  2:32p Fractal
    BARchART       <DIR>        02-23-96  2:32p BarChart
    UNDERC~1       <DIR>        02-23-96  2:32p UnderConstruction
    JUMPIN~1       <DIR>        02-23-96  2:32p JumpingBox
    SCROLL~1       <DIR>        02-23-96  2:32p ScrollingImages
    DITHER~1       <DIR>        02-23-96  2:32p DitherTest
    IMAGEMAP       <DIR>        02-23-96  2:32p ImageMap
    GRAPHL~1       <DIR>        02-23-96  2:32p GraphLayout
    GRAPHI~1       <DIR>        02-23-96  2:32p GraphicsTest
    SIMPLE~1       <DIR>        02-23-96  2:32p SimpleGraph
    ANIMATOR       <DIR>        02-23-96  2:32p Animator
    IMAGET~1       <DIR>        02-23-96  2:32p ImageTest

    In the subdirectories for each demonstration applet, you will find all the files necessary to run the applet and to see how the applet was created. For example, the directory for the TicTacToe applet contains the following:

    TicTacToe.class The compiled class file for the TicTacToe applet
    TicTacToe.java The source code for the TicTacToe applet
    audio directory Contains AU sound files the applet uses
    example1.html A sample HTML document for viewing the applet
    images directory Contains the images the applet uses

    To test the installation, you can view the applet by accessing the example1.html file with your Java-capable Web browser. You can also view the applet using the appletviewer tool that comes with the JDK. If you are currently in the java base directory, you can type the following to view the TicTacToe demo applet with appletviewer:

    appletviewer demo\TicTacToe\example1.html

    If you are currently in the java\demo\TicTacToe directory, you can type the following to view the TicTacToe demo applet with appletviewer:

    appletviewer example1.html

    When you run appletviewer, the TicTacToe applet should display on your screen. Because the TicTacToe applet uses threads, appletviewer may write something similar to the following in the
    MS-DOS prompt area:

    thread applet-TicTacToe.class find class TicTacToe
    Opening stream to: file:/C:/java/demo/TicTacToe/TicTacToe.class to get TicTacToe

    The good news is that if you can run the demo applet, your base installation worked correctly. If you have any problems running the TicTacToe applet with appletviewer, first make sure you are in the correct directory. Next, make sure your PATH statement and environment are set correctly. When you type PATH at the MS-DOS prompt, you should see the previous path settings and the updated path setting for Java. When you type SET at the MS-DOS prompt, you should see the previous environment settings and the setting for Java's CLASSPATH environment variable, providing that you set this variable.

    If you get the error message Exception in thread NULL when running the Java interpreter, compiler, or appletviewer, you should check the setting for your CLASSPATH environment variable. You can do this by typing SET at the MS-DOS prompt. The CLASSPATH variable must specify the full path to the classes.zip file and should not list the class directory from an older JDK release.

    Anyone who wants to maintain a separate class directory should check to see if they have set the CLASSPATH environment variable correctly. An easy way to do this is to temporarily move one of the demonstration class files to the location where you plan to store your Java class files. The new location must be empty if you follow this example.

    From the java\demo\TicTacToe directory, type

    mkdir c:\destination\file\path
    move TicTacToe.class \destination\file\path

    where \destination\file\path is the actual file path to the destination directory, such as

    mkdir c:\myclasses
    move TicTacToe.class c:\myclasses

    You should now be able to run the TicTacToe demo on appletviewer without having to specify the path to the class file for the applet. From the java\demo\TicTacToe directory, type the following to test it:

    appletviewer example1.html

    If you cannot view the applet, you should check your environment settings. You can do this by typing SET at the MS-DOS prompt.

    The SET command should return your updated setting for CLASSPATH, such as

    CLASSPATH=C:\MYCLASSES;C:\JAVA\LIB\CLASSES.ZIP

    If the CLASSPATH variable is set incorrectly, you should refer back to the sidebar "Setting Your Paths for Java in Windows 95/NT."

    Power Start for Macintosh

    The Macintosh has one of the friendliest operating systems available, and it is unfortunate that Mac owners had to wait so long for an initial implementation of the Java Developer's Kit. The first version of the Macintosh JDK released for general use was a limited-use Beta version that included the AWT and network packages but lacked many of the other packages found on other systems. Also, the Beta JDK only allowed you to create applets for use with external viewers.

    The reasons for these limitations in the Beta JDK are many, but one of the major reasons is that the Macintosh operating system is fundamentally different from most other operating systems. The developers of the Beta JDK found that the folder hierarchy used in other JDKs did not make sense on a Mac. For example, on other systems the binary executables are stored in a bin directory. A "bin" folder on a Macintosh does not make much sense. Therefore, the developers moved the executables to the top-level folder.

    Additionally, the command line used on other systems allows the tools in the JDK to be very basic and streamlined. Typing things at a command line, however, goes against the principles upon which the Mac is founded. Mac users like their drag-and-drop functionality, and that is what the developers of the Mac JDK set it to provide. However, graphical tools are inherently more complex than command-line tools, and that's why developing the Mac JDK was such a slow process.

    The current Macintosh JDK is much more advanced and includes AWT, Networking, and Multimedia libraries. These three libraries provide the core functionality of the standard API on other systems. To run Java on your Mac, you should be running System 7.5 or higher on a Power Macintosh or a Macintosh with at least a 68030 processor.

    Before installing the JDK, you should ensure that you have enough space on your hard drive for the installation. You will retrieve a 2.5MB compressed installer file. When you install the JDK, you need an additional 6MB of disk space. Although you can remove the compressed installer file after a successful installation, you still initially need about 9MB of disk space.

    To set up a Java developer's environment on your Macintosh, follow these steps:

    1. Obtain the Java Developer's Kit
    2. Install the Java Developer's Kit
    3. Test the installation

    Obtaining the Java Developer's Kit

    The JDK for Macintosh includes the complete set of tools for viewing, creating, and debugging Java programs and the precompiled code packages from the standard API. To obtain the source file for the JDK, you need to open an FTP session with one of the FTP sites listed in Table 2.1.

    Warning:
    If a prerelease version of the JDK is installed on your system, you want to remove it before installing JDK 1.0 or later. This will remove files and directories that are no longer used with JDK 1.0 or later versions. However, before you do this, you should move any source code you created that is located in the directories you will be deleting. You can remove a previous installation by putting the top-level folder into the trashcan-don't forget to flush!

    You can obtain the JDK source file from an FTP site in one of two ways:

    • With your Web browser, enter the URL path to the FTP site as listed in the "URL Path to JDK" column of Table 2.1.
    • Using an FTP tool, open an FTP session to the FTP site as listed in the "FTP Site" column of Table 2.1.

    In the example that follows, the JDK source code is downloaded from JavaSoft. If the JavaSoft FTP site is busy, you can obtain the source from any of the mirror sites listed in Table 2.1. Because file paths on the Internet tend to change, you should follow the steps sequentially.

    1. Start the FTP session using your FTP tool of your choice or a Web browser. The URL path to JavaSoft is

      ftp://ftp.javasoft.com/pub

      The FTP site you want to access with the FTP tool is ftp.javasoft.com. When you have successfully connected, you should see a listing of files and folders in the base directory.
    2. Click on the pub directory. You should see a listing of the contents of the pub directory. You want to download the most current version of the JDK for Mac. Currently, the JDK is available in both Macintosh binary (JDK-1_1-mac.sea.bin) and Macintosh hqx format (JDK-1_1-mac.sea.hqx). Select and retrieve the version you want to download by clicking on it.

    Installing the Java Developer's Kit

    After you obtain the compressed installer file, you should check to make sure the size of the file you downloaded matches the file size listed on the FTP site. If the file sizes are not identical, your file might have been corrupted during download. In this case, you want to delete the file from your system and try to download the JDK source file again.

    Before you can install the JDK, you need to decompress the installer file. You should use Stuffit to decompress the Macintosh binary file and DeHQX or BinHex4 to decompress the hqx file.

    Note
    If you used Fetch or Anarchie to download the files, the installer file was automatically decompressed when the download finished.

    To install the JDK, simply run the installer program. You can change the name of the folder that will contain the JDK if you want. I prefer the folder name Java or JDK to the default. Folders and files created during the installation include the following:

    Java Compiler The Java compiler
    Applet Viewer An application used to view applets without a Web browser.
    Classes A folder for class files used by the compiler and Applet Viewer
    Java.shlb The Java runtime shared library for Powerpc
    lib A folder containing libraries for the Java interpreter and compiler
    Sample Applets A folder containing sample applets and source code

    Testing the Installation

    A great way to test your new Java developer's environment is to preview one of the sample applets included in the JDK. You can view the sample applets with your Java-capable Web browser or with the Applet Viewer tool that comes with the JDK.

    To use the Applet Viewer tool, do the following:

    1. Open the folder named Sample Applets.
    2. Open the folder named TicTacToe.
    3. Drop the file example1.html on the application Applet Viewer.

    You should now be able to view the sample applet.

    Power Start for OS/2

    IBM's OS/2 operating system is a popular alternative to Microsoft Windows. The OS/2 version of the Java Developer's Kit is basically a port from the Windows 95/NT version. The first version of the OS/2 JDK released for general use was a Beta version. Because the Beta version was basically a direct port from the Windows 95/NT version, it had many problems. The current version of the JDK is much more advanced and features better support for the native OS/2 environment.

    The OS/2 JDK requires OS/2 2.x or OS/2 Warp. IBM recommends a 486-class machine with 12MB+ RAM and OS/2 Warp for optimal performance, especially because you need OS/2 Warp to play Java audio files. You will also need an HPFS disk with at least 15MB of free space. Be forewarned that the JDK requires long-name support. Before installing the JDK, you should ensure that you have enough space on your hard drive for the installation. Additionally, to use the networking features of Java, you need TCP/IP software such as Warp IAK or TCP/IP 2.0+.

    To set up a Java developer's environment on your computer, follow these steps:

    1. Obtain the Java Developer's Kit
    2. Install the Java Developer's Kit
    3. Test the installation

    Obtaining the Java Developer's Kit

    The JDK for OS/2 includes the complete set of tools for viewing, creating, and debugging Java programs and the precompiled code packages from the standard API. To obtain the source file for the JDK, you have to register to use the IBM developers area on the Web.

    Warning
    If you have a pre-release version of the JDK installed on your system, you want to remove it before installing JDK 1.0 or later to remove files and directories that are no longer used with JDK 1.0 or later versions. However, before you do this, you should move any source code you created that is located in the directories you will be deleting. From the OS/2 command prompt, you can type the following to remove the previous installation of the JDK in its entirety:
    deltree /Y C:\file\path
    where C:\file\path is the actual path to the previous installation of Java, such as
    deltree /Y C:\java
    You should also check to see if you set Java-related file paths when you last installed the JDK. You can do this by typing the following at the OS/2 command prompt:
    TYPE C:\CONFIG.SYS
    The previous command should list the contents of your CONFIG.SYS file. You should now check for Java-related file paths. Java-related file paths include any file paths where the old version of the JDK was installed.
    If you did not set Java-related paths, you can continue with the installation. If you set Java-related paths, you want to check the validity of these settings when you follow the steps for setting and/or updating your paths as discussed in the sidebar "Setting Up Your Java Environment in OS/2," which appears in the next section.

    Obtaining the JDK source for OS/2 is as easy as 1, 2, 3:

    1. With your Web browser, enter the URL path to IBM's Web site and follow the link from this index page to IBM's online registration form for software developers:

      http://www.hursley.ibm.com/javainfo/download/index.html
    2. After you fill out and submit the form, you will receive an e-mail message verifying your username and password. This message should come back to you in a few minutes. After you receive a user ID and password, you will be able to access the private developers area and download the JDK source. You can click on the appropriate link on the index page listed earlier or try to access the OS/2 developers area directly at

      http://www.hursley.ibm.com/javainfo/Developer/os2/index.html
    3. The developers page should have a link to a zip file containing the JDK source. Click on the link to download the JDK for OS/2.

    Installing the Java Developer's Kit

    Before you can install the JDK, you need to unzip the compressed source file. If you do not have an unzip utility that supports long filenames, Infozip's UNZIP version 5.12 or later works well.

    To install the JDK, follow these steps:

    1. From an OS/2 command prompt, change to the directory that contains the JDK source file.
    2. Move the JDK to where you want to install it. To install Java in c:\javaos2, you can use the following command:
      move filename c:\
      where filename is the actual name of the zip file, such as
      move JAVAOS2.ZIP c:\
    3. Unzip the file. Be sure to set the -d directories and subdirectories flag if your unzip utility requires it. If you are using Infozip's UNZIP, you can type the following:
      unzip javaos2.zip

    When you unzip the JDK source file, you will be creating a directory called javaos2 under the current directory. If you are installing the JDK for OS/2 on your system, subdirectories located under the javaos2 directory include the following:

    .hotjava Directory containing network property files
    applet Output directory for applet viewer log files
    bin Directory containing the JDK tools
    classes Directory containing class files used by the compiler and applet viewer
    demo Directory containing demonstration applets and source code
    dll Directory containing dynamic linked library files needed by the Java compiler and interpreter
    include Directory containing include files for building native classes
    lib Directory containing library and Java property files
    src Directory containing the source for a subset of the classes from the API

    The executables and link libraries come in two forms. Those files with suffix _g are compiled and linked with debugging information. Executables with the suffix _g support all of Java's mechanisms for debugging. Executables without the suffix _g are optimized for normal use and support only limited debugging options. The dynamic linked libraries are used by the Java environment itself and are, in fact, the OS/2 interface to Java.

    The classes in the src directory represent a good cross-section of the functionality introduced by the Java API and are written in the Java programming language. You can learn a lot by examining them. Therefore, I highly recommend that you make a note to go through some of the files after you read this book.

    Another directory you want to check is the demo directory, which contains many demonstration applets. By previewing these demos, you can see Java in action. The include directory contains C-language header and stub files. These files are primarily used to set paths and definitions needed by Java and essential to Java interaction with C. Finally, the lib directory contains essential library files.

    Peter's Principle:
    Setting Up Your Java Environment in OS/2
    After installing the JDK, you should update your CONFIG.SYS file so your computer can find the Java executables and class libraries. Follow these steps for updating your CONFIG.SYS file:
    1. Type the following at the OS/2 command prompt:
      EDIT C:\CONFIG.SYS
    2. Add the full path to the Java dll directory to the current path for the LIBPATH environment variable. This allows Java to find the DLL files. If you installed the JDK in c:\javaos2, the full path to the dll directory is
      c:\javaos2\dll
    3. Add the full path to the Java bin directory to the current path setting. This allows Java to find the binary executables for Java. If you installed the JDK in c:\javaos2, the full path to the bin directory is
      c:\javaos2\bin
    4. Optionally, if you installed the JDK in a directory other than javaos2, you will have to set the HOME and the JAVA_HOME environment variables. If you installed the JDK in C:MYJAVA, you would set these variables as follows:
      SET HOME=C:\MYJAVA
      SET JAVA_HOME=C:\MYJAVA
    5. Save and close your CONFIG.SYS file.
    6. Reboot your computer. Rebooting your computer sets the working environment for all future sessions. Optionally, you can type the following from the OS/2 command prompt to set your current working environment for use with Java. Your current working environment applies only to the OS/2 command prompt into which you enter the environment and path settings. You must use the actual path to your Java executables and dynamic link libraries. If you installed Java under the C:\javaos2 directory, you would type the following at the OS/2 command prompt:
      SET PATH=%PATH%;C:\JAVAOS2\BIN;
      SET LIBPATH=%LIBPATH%;C:\JAVAOS2\DLL;

    Testing the Installation

    A great way to test your new Java developer's environment is to preview one of the demo applets included in the JDK. Each demo applet is located in the demo directory and has its own subdirectory. In the subdirectories for each demonstration applet, you will find all the files necessary to run the applet and to see how the applet was created. For example, the directory for the TicTacToe applet contains the following:

    TicTacToe.class The compiled class file for the TicTacToe applet
    TicTacToe.java The source code for the TicTacToe applet
    audio directory Contains AU sound files the applet uses
    example1.html A sample HTML document for viewing the applet
    images directory Contains the images the applet uses

    To test the installation, you can view the applet by accessing the example1.html file with your Java-capable Web browser. You can also view the applet using the appletviewer tool that comes with the JDK. If you are currently in the javaos2 directory, you can type the following to view the TicTacToe demo applet with the appletviewer tool:

    start applet demo\TicTacToe\example1.html

    If you are currently in the java\demo\TicTacToe directory, you can type the following to view the TicTacToe demo applet with the appletviewer:

    start applet example1.html

    When you run the appletviewer tool, you should see the applet and something similar to the following should be written to the javaos2\applet log files:

    thread applet-TicTacToe.class find class TicTacToe
    Opening stream to: file:/C:/javaos2/demo/TicTacToe/TicTacToe.class
    Âto get TicTacToe

    The good news is that if you can run the demo applet, your base installation worked correctly. If you have any problems running the TicTacToe applet with the applet viewer tool, first make sure you are in the correct directory. Next, make sure your PATH statement and environment are set correctly. When you type PATH at the OS/2 command prompt, you should see the previous path settings and the updated path setting for Java. When you type SET at the OS/2 command prompt, you should see the previous environment settings and the updated setting for the LIBPATH environment variable. Additionally, if you set the HOME and JAVA_HOME variables, you should see these settings as well when you type SET at the command prompt.

    Performance Tuning for OS/2

    A nice feature of the JDK for OS/2 is the capability to do additional performance tuning. In particular, the OS/2 JDK allows you to set three environment variables either permanently in your CONFIG.SYS or temporarily at the OS/2 command prompt.

    Additional performance-tuning environment variables include the following:

    JAVA_CONNECT_TIMEOUT=n Used to adjust the time that Java will wait for a network connection before it reports a timeout. The default value for this variable is 30 seconds. Valid values for n are from 1 through 1,000,000.
    JAVA_AUDIO_VOLUME=v Used to adjust the audio volume from Java as a percentage of the maximum allowable volume. The default value for this variable is 50. Valid values for v are from 0 through 100.
    JAVA_AUDIO_RATE=n Used to set the preferred playback sample rate for audio. By default, Java first tries to play audio at 8,000 samples and then tries 11,025 samples. You can override this default by setting n to a specific value: 8 for 8,000 samples per second or 11 for 11,025 samples per second.

    Power Start for AIX

    One major flavor of UNIX for which the JDK is currently available is AIX. As you will see, the steps for installing the AIX version of the JDK are very similar to the steps for installing the Solaris version. This is because the underlying architecture for both Solaris and AIX is UNIX-based.

    The AIX JDK requires AIX version 4.1.3 or higher. Before installing the JDK, you should ensure that you have enough space on your hard drive for the installation. For AIX, you will retrieve a 4.9MB compressed file. When you install the JDK, you will need an additional 9MB of disk space. Although you can remove the compressed JDK file after a successful installation, you still initially need about 15MB of disk space.

    To set up a Java developer's environment on your computer, follow these steps:

    1. Obtain the Java Developer's Kit
    2. Install the Java Developer's Kit
    3. Test the installation

    Obtaining the Java Developer's Kit

    The JDK for AIX includes the complete set of tools for viewing, creating, and debugging Java programs and the precompiled code packages from the standard API. To obtain the source file for the JDK, you have to register to use the IBM developers area on the Web.

    Warning:
    If you have a pre-release version of the JDK installed on your system, you want to remove it before installing JDK 1.0 or later to remove files and directories that are no longer used with JDK 1.0 or later versions. However, before you do this, you should move any source code you created that is located in the directories you will be deleting.
    From the shell prompt, you can type the following to remove the previous installation of the JDK in its entirety:
    rm -rf \file\path
    where \file\path is the actual path to the previous installation of Java, such as
    rm -rf \java

    Obtaining the JDK source for AIX is as easy as 1, 2, 3:

    1. With your Web browser, enter the URL path to IBM's Web site and follow the link from this index page to IBM's online registration form for software developers:
      http://www.hursley.ibm.com/javainfo/download/index.html
    2. After you fill out and submit the form, you will receive an e-mail message verifying your username and password. This message should come back to you in a few minutes. After you receive a user ID and password, you will be able to access the private developers area and download the JDK source. You can click on the appropriate link on the index page listed earlier or try to access the AIX developer's area directly at
      http://www.hursley.ibm.com/javainfo/Developer/aix/index.html
    3. The developers page should have a link to a zip file containing the JDK source. Click on the link to download the JDK for AIX.

    Installing the Java Developer's Kit

    The AIX JDK source file is compressed and packed. You need to uncompress and unpack the files. The following steps will guide you through the installation process:

    1. Change to the directory that contains the JDK source file.
    2. Move the JDK to where you want to install it. To install Java in /java, which is recommended, you can use the following command:
      mv filename /
      where filename is the actual name of the file, such as
      mv java1.1.tar.Z /
    3. Uncompress and unpack the file. You can do this using the following command:
      uncompress filename | tar -xf -
      where filename is the actually name of the file, such as
      uncompress java1.1.tar.Z | tar -xf -

    When you uncompress and unpack the compressed JDK file, you will be creating a directory called java under the current directory. If you are installing the JDK for AIX on your system, the following are some of the files and subdirectories that will be located under the java directory:

    bin Directory containing the JDK tools
    classes Directory containing the compiled class files for the Java API
    demo Directory containing demonstration applets and source code
    include Directory containing C-language header and stub files
    lib Directory containing runtime library and Java property files
    lib/ums Directory containing audio libraries for systems with audio hardware on the motherboard
    lib/aix Directory containing AIX-specific libraries and audio libraries for systems without audio hardware on the motherboard
    java Directory containing the source for a subset of the classes from the API

    You will find the following executable files for the JDK tools in the bin directory. All the executables-except for the Java source-level debugger, jdb-come in two forms. Executables with the suffix _g are for debugging and support all of Java's mechanisms for debugging. Executables without the suffix _g are optimized for normal use and support only limited debugging options.

    Another directory you want to check is the demo directory, which contains many demonstration applets. By previewing these demos, you can see Java in action. The include directory contains C-language header and stub files. These files are primarily used to set paths and definitions needed by Java and essential to Java interaction with C. Finally, the lib directory contains essential library files.

    You should now add the full path to the java/bin directory to your search path. This will allow you to execute the JDK tools from any directory.

    Testing the Installation

    A great way to test your new Java developer's environment is to preview one of the demo applets included in the JDK. In the subdirectories for each demonstration applet, you will find all the files necessary to run the applet and to see how the applet was created. For example, the directory for the TicTacToe applet contains the following:

    TicTacToe.class The compiled class file for the TicTacToe applet
    TicTacToe.java The source code for the TicTacToe applet
    audio directory Contains AU sound files the applet uses
    example1.html A sample HTML document for viewing the applet
    images directory Contains the images the applet uses

    To test the installation, you can view the applet by accessing the example1.html file with your Java-capable Web browser. You can also view the applet using the appletviewer tool that comes with the JDK. If you are currently in the java base directory, you can type the following to view the TicTacToe demo applet with appletviewer:

    bin/appletviewer demo/TicTacToe/example1.html

    The good news is that if you can run the demo applet, your base installation worked correctly. If you have any problems running the TicTacToe applet with appletviewer, check your current path by typing pwd at the shell prompt. You should change directories to the base java directory and try to run appletviewer again. Normally the base java directory is

    /java

    or a subdirectory under your home directory called

    java

    Making the Transition from C/C++ to Java

    Since the release of Java Alpha in 1995, thousands of frustrated C/C++ programmers have chased the Java dream. From the hype surrounding Java and the rejoicing in the press, they expected to become expert Java programmers in no time. After all, like I said, Java is modeled after C and C++.

    The problem is that you must always crawl before you walk. However, you will find that making the transition from C/C++ to Java is easy if you take the time to learn about the fundamental differences between C/C++ and Java. This section highlights these differences so you know what you can and cannot do in Java right from the start.

    Java Has No Compile to Machine Code

    C/C++ source code is compiled to machine code. This compiled source is usable only on the specific platform for which it was compiled. As you know, a compiled C/C++ program is directly executable. Java source code, on the other hand, is compiled to an intermediate form called bytecode that is neither machine code nor source code.

    One benefit of compiling to bytecode is that Java bytecode is not platform specific and is usable on any platform to which the Java programming language has been ported. You execute Java source code using an interpreter that executes the bytecode and translates it to a machine-readable form.

    Another benefit of compiling to an intermediate form is that no link step is required. The Java interpreter dynamically links in classes on demand.

    Java Has No External C Syntax

    In C++, you can get to existing C procedures and system calls using the extern C syntax that declares the C procedure to be outside the normal C++ namespace. In Java, there is no extern C syntax; as a result, you cannot use existing C or C++ code directly. In fact, it is rather difficult to use C++ code at all.

    Before you abandon ship, you should realize that Java incorporates a wide range of functionality into the Java API. As specified earlier in this chapter, the API includes packages for graphics, multimedia, networking, system utilities, file I/O, and much more. This means that most of the common functions for which you would want to use your C/C++ libraries are already in the Java API.

    Don't worry-for those C/C++ functions that you really need, there is a way to use them in Java. It is, however, indirect and not as easy as using the external C syntax. To use C functions in Java, you must define a method whose purpose is to interface to the C function. Within the method, you must specify how the C function will interact with Java. Using C++ programs in Java is a bit more convoluted. You must define a method whose purpose is to interface to a C class that invokes C++ functions and member functions from C.

    Looking Ahead:
    (See Chapter 22, "Integrating Native Programs and Libraries," for complete details on using C/C++ functions with Java.)

    Generally, you will use C/C++ or another programming language when you want to implement platform-specific functionality or increase the speed of your application. Keep in mind that when you use other programming languages with Java, you may be sacrificing the platform independence of your application.

    Java Has No Multiple Inheritance

    An object that is a member of one class, a parent of another class, and needs to inherit the full functionality of both classes is one example of the need for multiple inheritance. Often when you are programming advanced object-oriented applications, you need to use classes that inherit the functionality of more than one class. In fact, the more advanced your application is, the more likely that you will need to use multiple inheritance.

    Many experienced C++ programmers dig deep into their tool chests, find some old code they have written that uses multiple inheritance, and press on. In Java, this is not possible because Java does not support multiple inheritance. Java replaces multiple inheritance with interfaces. Current C++ programmers will find that the concept of interfaces is easier to understand and use than multiple inheritance, which is another plus for Java.

    Interfaces allow you to define the protocols for methods and final variables without having to worry about the specific implementation. Once you declare an interface, other interfaces or classes can implement that interface. A class that implements an interface can have its own functionality. Additionally, both classes and interfaces can implement multiple interfaces. However, the one limitation to interfaces is that you must write code to reimplement the desired functionality in each class implementing an interface.

    An interface guarantees that all objects inherited from it will provide the same methods as the interface. This allows for a more object-oriented approach to programming. Even classes that are inherited from multiple interfaces will always implement the methods of their interfaces. For example, a class derived from the television interface and the radio interface will have all the methods available to both interfaces.

    Java Has No Namespace Problems

    Anyone who has worked in a large C++ environment has probably encountered namespace problems. The simple fact is that when you have different programmers working on different sections of a project, someone is bound to create a class with the same name as a totally different class in some other part of the project. When this happens, you have namespace pollution and a big headache, especially if the overlap is not discovered until a late stage of the project-like when you are integrating the code modules for testing. Correcting a namespace problem costs time and money.

    Java avoids namespace problems by creating a namespace with many levels that are considered in precedence order from the highest level, the package namespace, to the lowest level, the nested local block namespace. Each component level in the namespace is used to build a unique object name. Thus, two classes with the same name in different packages are unique.

    Java Has No Pointers

    Experienced C/C++ programmers know that most bugs in C/C++ code relate to problems with pointers and memory management. This is because practically everyone who has ever programmed in C or C++ has at one time or another had problems with pointers and memory management. These two areas of C/C++ programming are a trial by fire that you either learn flawlessly or have problems with forever after. As you know from Chapter 1, Java does not use pointers and automatically manages memory for you, which in itself is cause for celebration.

    Technical Note:
    To be 100% technically accurate, Java does not actually eliminate the concept of pointers. Every instance of an object is referenced via a pointer. The only functionality that pointers have is to retrieve the value of the object to which it is pointing. Programmers and users cannot manipulate these pointers, which is a significant change from how pointers are used in C/C++. In C/C++, as most programmers know, you handle the pointers yourself and pray they don't go astray. Therefore, when you read that Java has no pointers, it means that, for all intents and purposes, Java eliminates pointers as most programmers know them.

    Java Has No Separate Header Files

    Header files are an important part of C++ programming. Many programmers use header files as impromptu documentation, primarily because header files can tell you at a glance how a particular class should be used. When you want to see the interface to a function, you bring up the header file and find the function. Java does not have header files. The signature of a method must appear simultaneously with its declaration. This means there is no convenient place to find answers quickly.

    If having to wade through pages of code to learn how to use a particular class is not appealing, there is an upside. The Java Developer's Kit includes two tools that make this task easier: javap and javadoc. The Java disassembler, javap, can be used to print class signatures. The Java API documentation generator, javadoc, creates HTML documentation from comments embedded in source files. This means if you have good inline documentation, javadoc can be used to create documentation in a more traditional and easier-to-use form.

    A lack of header files also has its advantages. Because the signature of a method must appear simultaneously with its declaration, it is more difficult to get a library that is missing the implementation of some member function. It is also more difficult to use files that are not in sync with the implementation.

    Java Has No Stand-alone Functions

    Something C++ programmers will need to get used to is that Java has no stand-alone functions. Java is first and foremost an object-oriented programming language. In Java, all Java applications are objects and all Java classes are derived from the primitive class Object.

    Some Java Programs Have No main Function

    Some Java programs, called applets, do not need a main function. However, each Java class may have a main method, and all Java applications include the equivalent of the main function. When a stand-alone application is executed, the main method is implemented and this is how parameters are passed into the application. When an applet is executed, initialization and start methods are implemented.

    Java Has No Templates

    In C++ you can write generic methods called templates that allow you to write one block of code that describes an implementation for several similar types of arguments. This enables you to create a method that accepts both integer and floating-point values, which saves you from having to write two methods that do essentially the same thing. You can also use templates to automatically generate classes, and that capability is a big plus.

    Although Java's use of the Object class as the parent for all other classes could be construed as an implementation of templates, there is no functional equivalent of C++ templates in Java. Because of this, you would have to have separate methods for similar-type arguments. However, you can generally reuse methods simply by cutting, pasting, and making minor modifications as necessary.

    Java Has Exception Handling

    Error conditions that are not expected to occur under normal conditions are called exceptions. When an exception occurs, bad things happen. For example, a negative number is passed to a function that computes the square root of a number. The function expects all numbers it receives to be positive real numbers. It receives a negative number instead, and an exception occurs. Sometimes programs die right then and there; other times they do more insidious things, such as passing incorrect pointers that eventually access protected areas of the system.

    Although there is no definitive way to handle exceptions in C++, many bleary-eyed C++ programmers will be happy to know that exceptions are a fundamental part of the Java programming language. In Java, if you call a method that could throw an exception, you must check to see if any of the possible exceptions occurred and handle them. Additionally, the Java compiler checks for exception handling and will tell you if you have not handled the exceptions for a particular method. As you will see in Chapter 8, "Tying It All Together: Threads, Exceptions, and More," building exception handling into your methods is easy. It also avoids yet another problem area in C/C++ programming.

    Java Has Automated Garbage Collection

    Keeping track of which chunks of memory are in use and which are not is a major headache in C++. Many C++ classes use destructors to free up chunks of memory that are no longer needed, but this does not always work. If you delete objects that are still in use, the program will crash. If you forget to delete objects that are no longer in use, the program will crash when your system runs out of memory. If you point to the wrong area of memory, you can overwrite essential data and crash the program.

    Java avoids memory-related problems by automating garbage collection. To do this, the Java runtime environment tracks which chunks of memory are in use and which aren't. When a chunk of memory is no longer needed, the system automatically clears it. When a chunk of memory is needed, the system automatically allocates it.

    As a result, you no longer have to worry about freeing memory when it's no longer in use. However, Java does not eliminate the need for destructors completely. You still might need destructors for certain classes, especially when you want to ensure that a process cleans up gracefully after it is terminated. Fortunately, Java provides an easy way to clean up processes gracefully using a finalize method. The finalize method can be used like a C++ destructor to do final cleanup on an object before garbage collection occurs. (See the section titled "The finalize Method," in Chapter 7, "Building Objects," for more information.)

    Summary

    The Java Developer's Kit contains everything you need to get started creating hot new Java applications. Versions of the JDK are currently available for Windows 95/NT, Macintosh, OS/2, and most UNIX platforms including Solaris and AIX. By installing the JDK on your system, you create a developer's environment complete with essential tools and precompiled code. For current C/C++ programmers, installing the JDK on your system is only the first step toward getting started. The next step is to review the differences between Java and C/C++, so you know exactly what you can and cannot do in the Java programming language.