Copyright ©1996, Que Corporation. All rights reserved. No part of this book may be used or reproduced in any form or by any means, or stored in a database or retrieval system without prior written permission of the publisher except in the case of brief quotations embodied in critical articles and reviews. Making copies of any part of this book for any purpose other than your own personal use is a violation of United States copyright laws. For information, address Que Corporation, 201 West 103rd Street, Indianapolis, IN 46290 or at support@mcp .com.
Notice: This material is excerpted from Special Edition Using Java, ISBN: 0-7897-0604-0. The electronic version of this material has not been through the final proof reading stage that the book goes through before being published in printed form. Some errors may exist here that are corrected before the book is published. This material is provided "as is" without any warranty of any kind.
Now that you have the Java Development Kit installed and decompressed, you can get to work, and you'll need to know a bit about your work environment.
The JDK environment is command-line driven, and unlike some programming languages, does not look attractive just sitting there. In other words, the Java environment is not graphical, as are other popular languages like Visual C++ or Visual Basic, which use a GUI (Graphical User Interface) environment.
Command-line driven also means that you call JDK's tools, including the compiler, from the command prompt (DOS Prompt for Windows NT, and 95), and you create the text of the Java file (filename.java) using an ASCII text editor such as the MS DOS-Editor or WinEdit.
This chapter discusses the Java environment. The main topics to be covered are:
This chapter only covers the features of 1.0 and 2.0 versions of the JDK, provided by Sun Microsystems (the versions downloaded from Sun Microsystems ). Other tools and Java compilers are available from third party vendors but are not discussed in this chapter. Features of other tools and compilers, are covered in chapter 6.
In a moment you'll put your installation to the test. Before you do this however, you may find it helpful to customize your Java environment. Although this step may seem unnecessary-since at a glance there doesn't seem to be much of an environment to customize-you might have to thank these seemingly insignificant tips for saving your fingers from repetitive typing, or preventing your hair from being pulled out when none of the Java tools seem to work!
It is good practice to make the tools of the environment accessible from all directories on your system. For MS Windows(NT, 95) users, this is achieved by placing the directory containing the tools in the path statement of the autoexec.bat file.
The Java compiler, as well as the other tools, are located in the directory [MyDrive]:\[MySubdir]\java\bin. Where [drive] is the drive letter of the drive where the JDK resides, and [MySubDir] is the name of the subdirectory, if any, in which Java was installed (decompressed). To make these files accessible from any other drive, or directory: edit your autoexec.bat file, and add [MyDrive]:\[MySubdir]\java\bin to the path statement (if your directory structure is different you will need to make the necessary adjustments). Figure 2.1 shows the path statement in my autoexec.bat file that has the location of my \java\bin directory added to it.
For Windows 95 users, the autoexec.bat file can be edited by using SysEdit (System Editor). In Windows 95, SysEdit can be executed by clicking on the Start Button, selecting Run, and then typing sysedit in the text box provided.
Fig. 2.1 The \java\bin directory added to the path statement in the Autoexec.bat file.
The DOS program, DOSKey, is a TSR (Terminate and Stay Resident) program that has, as one of its many functions, the ability to store text that the user has typed, in a memory lookup table of some sort, and allow the user to scroll through this table to find commands or executable text (program names), that have already been entered. This can become very useful in the Java environment since many commands may have to be called numerous times.
For instance, the case of having to recompile. With DOSKey installed, you only need to type this command once. If your code produces errors (and believe me it will!) on the first compile, you will need to recompile and then edit the file again. This becomes a tedious typing routine, especially if you need to do it six or seven times, or if your not an avid typist. DOSKey can limit this routine to as little as two keys.
The Up Arrow allows you to scroll up the memory table and find text that has already been used. Instead of retyping "javac filename.java" (to recompile your code), you could simply use the Up Arrow key to scroll through the memory table until you found "javac filename.java" and then hit enter. The Down Arrow key is used to scroll down the table, and the Escape Key is used to clear the entry.
DOSKey has some other interesting features, but these are not discussed in this chapter or in this book. For more information on DOSKey, type doskey/? At the command prompt. To have DOSKey installed on your system, just add [DosDrive]:\[DosSubdir]\DOSKey to the end of your autoexec.bat file. Where [DosDrive] is drive letter of the drive in which DOS is installed, and [DosSubdir] is the name of your DOS subdirectory. Figure 2.1 also shows the DOSKey program loaded in my autoexec.bat file.
To clear the command history table, use Alt+F7. To view this table, use F7. DOSKey will lose stored commands, if you exit from DOS. To prevent this from happening, use Alt+Tab to switch tasks rather than quitting DOS.
File structure, and organization can easily be overlooked by an anxious programmer who just wants to delve into coding, and not be bothered by aesthetics or 'good programming hygiene.' You will, however, see in the upcoming chapters, that organization is in fact vital to the performance of your Java applications, and applets. Some good principles to follow are as follows:
Now after all this preparation, let's see if our installation works. We would want to test both Java applets, and Java applications since each are handled differently by your system, and the Java environment.
A Java application is just what the name implies-a stand-alone Java program that is executed on your system by using the Java Interpreter. A Java applet is usually a remote Java program executed by a Web Browser (Netscape 2.0 for example). The Browser locates the applet by referencing its HTML tag (<applet code="myApplet" width = somewidth height = someheight> </applet>) embedded in a Web Page.
Java Applets are covered in chapter 16 (The Basics of Applet Construction), and Java Applications are covered in chapter 23 (Java Applications).
There is no better way to test our installation on an applet, than to actually write one. The following applet is a fairly simple one, and there is no need to skip to chapter 16 so that you can understand applets better and then return to this test.
FancyHello.java
Follow the these steps to test an applet in the Java environment.
Using an editor (I use MS DOS Editor) create a new file called FancyHello.java by typing in the following:
/* First java applet. This applet will be used to test my installation. */ import java.awt.*; public class FancyHello extends java.applet.Applet { Font f; int xpos,ypos; String HelloString; FontMetrics fm; public void paint (Graphics g) { HelloString = "Hello World!"; f = new Font("Helvetica", Font.BOLD + Font.ITALIC,24); fm = getFontMetrics(f); g.setFont(f); g.setColor(Color.blue); xpos = (this.size().width - fm.stringWidth(HelloString)) / 2; ypos = (this.size().height - fm.stringWidth(HelloString)) /2; g.drawString(HelloString, xpos, ypos); } }
(Don't worry about the syntax for now, it will be explained in later chapters.)
Save this file as FancyHello.java in your Java subdirectory.
From the command prompt, and within the same subdirectory that you saved your java file, type:
Since Java is case-sensitive, take care to type everything in exactly as it appears above. In a few seconds your command prompt will reappear. If you receive an error after the compiler is finished compiling, check your code for typographic errors.
Whenever I try to compile within a specific subdirectory, I get the error Bad command or filename Your \java\bin directory is probably not in your path statement. You can check your path statement for this directory by typing: path at the command prompt. If this subdirectory does not appear in the path statement, you can add it by editing the autoexec.bat file as explained earlier in this chapter. You must restart your system in order for this statement to be executed and the \java\bin directory added to your path.
Providing that the compiler returned no errors, the file FancyHello.class should have been automatically created in the same subdirectory. This is the compiled version of the Java code you just entered, and contains the bytecodes that are necessary to execute your Java program.
Now that you're done with compiling, your Java program is ready to execute.
But didn't we say before that applets were remote Java programs executed by a World Wide Web Browser? How could we test our applet without putting it out on the Internet?
Fortunately, the JDK comes with a tool called "appletviewer", that allows you to view test your Java applets stand-alone.
If you have a Java compatible browser such as Netscape Navigator 2.0, you can also test your applets stand-alone,by clicking File, then selecting Open file, and finally selecting the HTML document with the embedded applet tag in it, or by typing directly into the "Go to" edit box:
Figure 2.2 Shows the FancyHello Applet displayed in Netscape 2.0.
If you're using the alpha version of the HotJava browser, then you will be unable to view applets created with other versions of the JDK. In order to view the applet, you must acquire a Browser capable of viewing version applets, or use the appletviewer.
>Fig. 2.2 An applet displayed using Netscape 2.0.
This is a great time-saver to say the least, since you will often need to customize your applets before you actually put them out on the Internet. appletviewer executes applets via the same method a Web Browser does, and so it requires an HTML file with the applet tag specifying the compiled Java program (javafile.class) that is to be run.
If you have created HTML documents before, then you probably have an HTML editor, and you can use this editor to create a new HTML document and embed the applet tag within it. Since this is only a test applet, you can use any text editor to create the following HTML document:
<HTML> <HEAD> <TITLE>Testing My Installation</TITLE> <BODY> <APPLET CODE="FancyHello.class" WIDTH=400 HEIGHT=400> </APPLET> </BODY> </HTML>
Save this file as test.html in the same subdirectory as FancyHello.class. Now type:
at the command prompt. You should then get a copyright notice screen (fig. 2.3), to which you should respond by clicking the "Accept" button. If the HTML document above was entered correctly, your applet should now appear on your screen as shown in figure 2.4 .
Fig. 2.3 Appletviewer's Copyright Screen.
Fig. 2.4 The FancyHello Applet displayed using appletviewer.
If what you see is what you got, then you know for sure that your JDK can successfully run applets. If errors have occurred even after double checking your code for typos, or nothing happens when you call the specified commands, then it is possible that you have not installed the JDK correctly (refer back to chapter 3, and follow the steps again), or the JDK you downloaded is corrupted and therefore needs to be downloaded again.
Now that you know your Java applet works, let's test a Java application to see if our JDK works with Java applications as well.
We'll make the coding of our test Java Application a lot simpler than our previous example of the applet. If this example compiles and runs successfully, then it should mean that your JDK will work for more complex code.
Using your text editor, create a new file to be called TestApp.java and enter the following program:
class TestApp { public static void main(String args[]) { System.out.println("My Java installation works..."); } }Save this file as TestApp.java in your Java files subdirectory.
At the command prompt type:
If you typed everything in correctly, the compiler should automatically create the file TestApp.class in the same subdirectory as TestApp.java.
The Java Interpreter is used to run a Java program stand alone. When called, the Interpreter looks for the void main(String args[]) method specified in the application, and begins execution of the application from there.
At the command prompt type:
Again, if what you see is what you got, then you know that your installation works fine with applications, and applets(if the previous test was also successful).
Problem: I already checked for typos: every thing checks out fine and the code even compiles, but when I try to run the application by typing: java TestApp.class I get the following error: Can't find class TestApp/class When running a Java Application you only need to specify the class name, and not the class extension. The file should execute correctly if you typed: java TestApp instead.
The JDK comes with a collection of tools that are used with Java programs to perform various functions. This section discusses these tools, and lists their various functions.The Java environment tools consists of the following:
These tools should all be located in the \java\bin directory. To use any of these tools, type it's syntax (options described in this section should be typed in without the square brackets []) at the command prompt.
The appletviewer tool allows you to view your applet as a stand-alone Java program. It requires an HTML file with the applet tag embedded in it as shown in previous examples. This tool is the only one of the JDK collection that has a Graphical User Interface. Figure 2.5 shows the tool's GUI.
Fig. 2.5 Appletviewer's GUI Interface.
As shown in figure 2.5 the appletviewer's GUI has one menu - Applet. The menu items of this menu have the following functions:
Fig. 2.6 The Window associated with Appletviewer's Tag menu item.
Fig. 2.7 The Window associated with Appletviewer's Info menu item.
Fig. 2.8 The Window associated with Appletviewer's Properties menu item.
Appletviewer has the following syntax:
appletviewer [-debug] html_file
Where -debug is the option of running appletviewer from within the Java debugger.
See chapter 18 for more on debugging your Java applets.
The Java compiler is what actually converts your file - filename.java - into Java bytecode. This bytecode is then stored in a class file - filename.class . Both applets, as well as applications are compiled using javac. javac has the following syntax:
javac [options] filename.java
The options for javac are listed in table 2.1:
Options | Description |
---|---|
-nowrite | This option tells the compiler to compile the code, but do not create the class file. This is useful for testing your syntax without creating files, or overwriting previously created classes. |
-nowarn | This option turns off the compiler's warning messages.(Warning messages are displayed when the compiler wants to inform you of errors that might occur at run-time, although they do not affect compilation.) |
-verbose | This option tells the compiler to display information on the source, while it is compiling. This information includes: all classes being loaded, the time it takes to load these classes in milliseconds, as well as the total time it takes to compile the source code in milliseconds. |
-d dir | This option tells the compiler to use the directory dir as the first directory of a package.(Packages will be covered in chapter 8.) |
-classpath dirs | This option tells the compiler to look in the directories, listed in dirs for classes included in the source file. Multiple directories are separated by colons. For example: javac -classpath \java\demos : \MyDir\MyClasses Myfile.java |
-debug | This option runs the compiler in debug mode,and steps through the source code adding |
-o | This option tells the compiler to make the program's methods inline. Making the methods inline actually speeds up execution since the ntire method body will be inserted wherever it is called by the program, instead of having multiple calls refer back to a single method. |
-g | This option is used to prepare the bytecodes for debugging |
Table 2.1See chapter 5 for more information on the Java compiler.java (The Java interpreter)
The Java interpreter is what you use to run your compiled Java application. The syntax for the Interpreter is:
java [options] classname
Where classname only includes the name of the class and not the extension (.class). The Java Interpreter options are listed in table 2.2:
Table 2.2Java Interpreter options Options Description -help This option tells the interpreter to display all of the options. -version This option tells the Interpreter to display the version of the JDK that was used to compile the source code. -v (also -verbose)This option tells the Interpreter to display all the classes as they are loaded. (Performs the same functions as in the javac tool) -cs (also -checksource) This option makes the interpreter check to see if the source code is newer (not yet compiled) than it's class file. If this is the case, than the new version of source is compiled. -noasyncgc This option turns off asynchronous garbage collection. -verbosegc This option tells the Interpreter to print out a message each time garbage collection occurs. -verify This option tells the Interpreter to verify all classes that are loaded. -noverify This option turns off class verification -verifyremote This option tells the Interpreter to verify classes that were imported, or inherited. -mx val This option sets the maximum Java heap size to the value specified by val. The minimum heap size is 1kb (-mx 1k) and the default is 16mb (-mx 16m). (Use the letters 'm' and 'k' to specify megabytes or kilobytes for the value of val.) -ms val This option sets the initial Java heap size to the value specified by val . The minimum heap size is 1kb (-mx 1k) and the default is 1mb (-mx 1m). (Use the letters 'm' and 'k' to specify megabytes or kilobytes for the value of val.) -ss val This option is used to set the value of the stack size for a C process to the value specified in val. The stack size must be greater than 1kb (-ss 1k) -oss val This option is used to set the stack size of a Java process to the specified value in val.(-ss and -oss will be covered in later chapters) -debug This option is used with remote Java files that are to be later debugged with the jdb tool. The Interpreter will generate a password for you which will be used in the jdb's -password option(see jdb options later on in this chapter.) -prof This option tells the Interpreter to output profiling information to file \java.prof.
The Java disassembler is used to disassemble already compiled Java bytecode. After disassembling the code, information about the member variables and methods are printed. The syntax for the Java Disassembler is:
javap [options] classnames
Multiple classes can be disassembled. Use a single space to separate each class. The options available for the Disassembler are shown in table 2.3 .
Table 2.3javap options Option Description -version This option tells the compiler to display the version of the JDK that javap is being executed from. -p This option tells the disassembler to print out private, as well as public member variables and methods. (By default javap only prints out public member variables and methods) -c This option tells the disassembler to disassemble the source file, and display the bytecodes produced by the compiler. -h This option tells the disassembler to output information on the particular class that can be used in C header file to be used by a C program that wants to use the methods in that class. -classpath dirs This option tells the disassembler to look for class files, included in the source file, in the specified directories - dirs. For multiple directories, a colon is used to separate each directory. -verify This option runs the verifier on the source, and checks the classes being loaded. -v (verbose)This option causes the disassembler to display information on the source code in detail, as it disassembles.
javah [options] classnames
Where classname is the name of the Java class file without the .class extension. Javah options are listed in table 2.4 .
Table 2.4javah options Option Description -stubs This option tells the javah tool to create stub files instead of the default-eader files. (stub files will be further discussed in chapter 15) -d dir This option tells the javah tool what directory to create the header, or stub files in. -v This option tells the javah tool to print out the status as it creates the header or stub file. -o filename This option tells the javah tool to put the sub, and header files into the file specified by filename. This file could be a regular text file, or even a header (filename.h) or stub (filename.c) file. -version This option causes the javah tool to print out the build version.
The javadoc tool creates an HTML file based on the tags that are embedded in the /** */ type of comments within a Java source file. These HTML files are used to store information about the classes and/or methods and since they are in an HTML format, hyperlinks to other Web Pages that might be related to your Java program. Javadoc was actually used by the creators of the JDK to create the Java API Documentation (refer to Sun Microsystems for more information.) You can view the API online and you can also see the source code used to generate it in your \java\src\java directory. Figure 2.5 shows the resulting HTML document after using the javadoc tool on the FancyHello.java file written earlier in this chapter. Table 2.5 shows the tags that are recognizable by javadoc (These tags are inserted between the special comment indicators (/** */) and are ignored by the compiler.)
See the API appendix.
Fig. 2.9
Table 2.5javadoc Tags Tag Description @see class This tag puts a "See also" link in the HTML file to the class specified by class. @see class#method This tag puts a "See also" link in the HTML file to the method specified by method. @param param descr This tag is used to describe method arguments. @version ver This tag specifies the version of the program. @author name This tag includes the author's name in the HTML file. @return descr This tag is used to describe a method's return value. @exception class This tag is used to create a link to the Exceptions thrown by the class specified by class.
The Java debugger is the debugging tool for the Java environment. The debugger is completely command line driven. You can use the debugger to debug files located on your local system, or files that are located on a remote system. For remote Java files, the jdb must be used with the -host and -password options described in table 2.6. The jdb also consists of a list of commands that will not be covered in this chapter. See chapter 18-Debugging your Java Code-for more information on the jdb tool.
Table 2.6jdb options Options Description -host hostname This option tells the jdb where the remote Java program resides. Where hostname is the name of the remote computer (ex. well.com, sun.com, etc.) -password password This option passes to the jdb the password, for the remote Java file, issued by the Java Interpreter using the -debug option.
See chapter 18 for more on the Java debugger.
The environment variables are settings used to determine the HotJava and Java Interpreter environments for your system.
The environment variables are used by HotJava, and not Netscape. If you do not use the HotJava Browser, you may want to skip this section, or you may just want to skim through it to gain some knowledge on HotJava.
The environment variables are as follows:
This environment variable sets the HotJava default URL for the home page.
This environment variable sets the directory where HotJava will search for the necessary files that are needed to run the Browser.
This environment variable tells HotJava, the directory where file read access can is allowed to applets. This can be used as a security precaution for applets that might read unauthorized information, and return it to a remote site.
This environment variable tells HotJava, which directories are allowed to be written to by applets. Similar to HOTJAVA_READ_PATH, this variable can be used as a security measure to control the ability of applets writing files on your system.
This environment variable determines where all classes are imported from. Use semicolons to separate classes.