Previous Page TOC Next Page See Page



slug: Web Programming with Java, 113-0, 02 WPJ02CH.DOC

2


Getting Started


by Kathryn Jones


Obtaining the Java SDK


This book helps you accomplish any and all of the goals outlined in the last chapter with the help of the Java Developer's Kit (JDK) and a Java-capable Web browser, which you will need to install on your computer. The JDK includes all of the primary tools of the Java development environment: the compiler, interpreter, debugger, and AppletViewer. You'll need the browser to run applets from pages on the Internet. Consequently, you must have a TCP/IP connection to the Internet for your browser to take advantage of Java's networking capabilities.

You can install the JDK from the CD-ROM included with this book. Insert the CD-ROM into your CD-ROM drive and refer to the readme file for setup instructions.

http://java.sun.com

or

http://www.javasoft.com

If you do not have a CD-ROM drive, you can download the JDK from the Java Web site or the Java FTP site. To download from the Sun Java home page, connect to the following URL:

http://java.sun.com.

The Java home page of Sun Microsystems lists several links. Two of the links are Developer's Corner and Downloads. You should be able to navigate through either of these links to get to the JDK page. This page provides you with detailed instructions for downloading and installing the JDK on your platform.

ftp://java.sun.com/pub/

or

ftp://www.blackdown.org/pub/Java/pub/

To download from the FTP site, FTP to the following:

ftp://java.sun.com/pub/

Download the JDK for your platform using binary transfer mode and follow the detailed instructions for installing the JDK on your platform.

You need to configure your particular system after downloading the JDK. The most important step after downloading and extracting the JDK is setting the classpath. If you are a Windows 95 user, you need to insert into the following line into your autoexec.bat file:

set classpath=.;c:\java;c:\java\lib\classes.zip

This method is also assuming that the JDK is installed on your C drive. On NT, you have to go into the Control Panel, then choose System, and then in User Environment Variables, under the dialog box, enter the name of the new variable in the Variable text area, as follows:

Path=c:\java

If you have any trouble downloading from Sun, try one of the Java mirror sites that are listed on the Java home page.

http://www.gamelan.com

http://www.javasoft.com



Java's home page is one of your most valuable sources of information on Java. Because Java is still evolving as a network programming language, you should regularly check that home page for news on releases, bugs, fixes, and information on third-party Java product development. You might also find the Frequently Asked Questions sections useful. Here are a couple of other Web sites among a rapidly growing number of Java sites that are worth exploring:

Currently, three 32-bit Web browsers support Java applets: Netscape Navigator 2.0 or greater, Microsoft Internet Explorer 3.0, and Sun HotJava. At the time of this writing, Netscape Navigator 2.0 (or later) and Microsoft's Internet Explorer 3.0 are the only Web browsers capable of working with applets created with the latest JDK tools. Sun's Web browser, HotJava version 1.0 preBeta1, is compatible with the FCS applet API. HotJava is worth downloading because it is currently one of the largest applications written in Java, and it includes source code. Be sure to check the Java home page for updates on the release of HotJava and the JDK.

You can download HotJava from the Sun Java home page. FTP sites are listed there for downloading the JDK.

http://www.netscape.com

Until the next release of HotJava, Netscape Navigator 2.0 or later is necessary for your Java development efforts. You can download Netscape Navigator from the Netscape home page at:

http://www.netscape.com

Be sure to follow Netscape's installation instructions for your platform.

You might also want to use third-party development tools that will ease your development efforts. In August 1996,, four products with visual development environments are available for Java: Microsoft's Visual J++, SunSoft's Java Workshop, Borland Latte (these also include tools for compiling and debugging Java applications), and Symantec Cafe. In the near future, undoubtedly several more development environments and tools will be available to you to make Java programming easier.

You'll find information about the Java Workshop on Sun's Java home page. You can explore the Borland and Symantec Java home pages for information regarding their products:

http://www.borland.com/Product/java
http://cafe.symantec.com/

Be sure to keep an eye out for new tools that will help you program with Java. Because Java is such a new technology, the race is on for software companies to offer Java tools and integration.



The only tools that you need in order to use this book are the JDK and Netscape Navigator 2.0 (32-bit) or later.


The Java Development Environment


The Java Developer's Kit provides you with four basic tools that help you write, compile, debug, test, and run Java code. These tools are the Java compiler, the Java interpreter, the Java debugger, and the Java AppletViewer. Java's other tools, such as the Java API documentation generator (javadoc), the Java disassembler (javap), and the Java header and stub file creator (javah) are included in the JDK, but they are not necessary for the purposes of this book. The Java tools, combined with Java libraries of utility classes and methods, form the complete Java system.

The following section describes the basic Java tools that you will use and explains how they are useful.

Your Text Editor


You can write your Java source code using any standard text editor, such as Notepad, Write, or Edit for Windows NT/95 users and TextEdit for Solaris users. A variety of text editors more suitable for development can be found on the Internet. You might want to use a text editor that comes with a development application, such as Visual C++. Java source code is generally saved with the extension .java.

The Java Compiler


Your Java source code can be compiled using javac, the Java compiler. It compiles source code into bytecode for the interpreter to execute. Compiled Java code is automatically given the extension .class by the compiler.

One important change that the Java team made from C was in compiling. C is a compiled language. It outputs binary machine code, which can be run only on the machine for which it is compiled. Compiled C code executes quickly, but it is architecture-dependent. As stated before, one of the important features of Java is that it is architecture-neutral. Java accomplishes architecture independence by splitting the compiling function across two tools: the Java compiler and the Java interpreter. The Java compiler outputs bytecode, similar to machine code but written for the Java virtual machine, which doesn't exist. The interpreter verifies this bytecode, converts it into machine code of the hardware platform it is installed on, and executes it. Source code must only be written for one machine: the virtual machine. The interpreter takes care of the rest. Therefore, the Java language is both compiled and interpreted.

The Java Interpreter


Java's interpreter is called java. It converts the bytecode output from the javac compiler to machine code and executes it.

Java is unlike purely interpreted languages, which generally interpret source code before execution, sacrificing performance. Another important feature of Java that Sun boasts is high performance. Execution by Java's interpreter is near to the speed of binary executables produced by compiled languages. The reason for this is that Java code is compiled to an intermediate stage where the file is still architecture-neutral, but close enough to machine code that it can run efficiently. In addition, Java's multithreading feature can improve performance by moving interpreter operation to the background. Multithreading is discussed in Chapter 15, "Interfacing with a Database: Catalog Applet."

In addition to architecture-independence, the other advantage of using the Java interpreter is security. The interpreter can evaluate classes to ensure that the bytecodes being interpreted do not violate any language constraints or perform illegal activities on the system or memory. This can prevent many viruses from spreading.

The interpreter runs outside the browsing environment. It provides the programmer with the ability to run stand-alone applications that have nothing to do with the Internet but that are portable and platform-independent.

The Java Debugger


You can debug your code using the Java debugger, called jdb. It helps you find and fix bugs in Java code.

The Java debugger provides a command-line debugging environment for Java programs. Debugging can be done on a local or remote Java interpreter.

The Java AppletViewer


You can test your applets using the Java applet viewer, called AppletViewer. It provides a programmer with a way of testing applets outside of a full-blown Web browser.

Although Netscape Navigator has Java functionality and can be used to view applets, its security features prevent it from loading applets from the local drive. It also doesn't have the networking capabilities of the Java AppletViewer. Therefore, the AppletViewer is the best tool for full applet capability.

Compiling with Java


When using the JDK, the process of compiling is currently performed in a command line (shell environment). This section describes in detail how you use the Java tools; it steps you through creating and compiling your first Java program.

The first step is to run the text editor of choice and create the classic HelloWorld program. Type the following lines of source code exactly as written here:

// HelloWorld.java
class HelloWorld {
     public static void main (String args[]) {
     System.out.println("Hello World!");
     }
}

Save the file as HelloWorld.java in the classes directory. Don't be concerned at this point with what this code means. The next chapter explains the fundamentals of the Java language, and this program's syntax becomes clear to you.

Javac/javac_g


After saving your source code with the extension .java, you can compile it using the Java compiler, javac. To run the javac compiler, execute it with the following syntax. (Note that javac expects an extension after the filename.)

javac [ options ] filename.java
javac_g [ options ] filename.java

For your example, run the following command:

javac HelloWorld.java

If the code compiles correctly, you will see two files in your classes directory: HelloWorld.java and HelloWorld.class. The .class file has now been converted to bytecode.

The following error message might result if you mistyped the javac commands. Retype the command carefully if you receive this error:

For Windows NT/95:  bad command or file name
For Solaris:  /bin/sh: javac: not found

The next error means that an expression is mistyped in your source code. Check your source code for errors if you receive this message:

Invalid expression statement

The following error means that either the javac command or your Java file cannot be found. If you receive this error, make sure that your path includes the directory containing the Java tools so you are able to run the tools from any directory without an explicit mapping to them. Also, make sure you are running the command from the same directory as your HelloWorld.java file.

Error Message For Windows NT/95:

 Bad command or file name

Error Message For Solaris:

 /bin/sh: javac: not found

When you run the compiler, you can feed it certain options that change its behavior. Table 2.1 provides a list of all of the command-line options that you can feed javac and a description of each option.

Table 2.1. Command-line options for javac.

Option Function -classpath path Sets path where javac looks for classes it needs. Directory list is colon-delimited. -d directory Specifies the root directory for creating a directory tree for a hierarchy of packages. -g Turns on debugging tables in code generation for later debugging of bytecodes. -nowarn Suppresses warnings that the compiler produces. -O Optimizes code produced by inlining static, final, and private methods. -verbose Prints messages about the source file and classes.

javac_g is a non-optimized version of javac that is suitable for use with debuggers such as jdb.

Java/java_g


You can use the Java interpreter to verify and execute your code. To run the Java interpreter, enter the executable name, options, classname (without the filename extension, unlike javac), and arguments as outlined here:

java [ options ] classname args
java_g [ options ] classname args

For our example, run the following command:

java HelloWorld

This should produce the following output:

Hello World!

Ordinarily, you compile source code with javac and then execute it using Java. However, Java can be used to compile and run bytecode when the -cs option is used. As each class is loaded, its modification date is compared to the modification date of the class source file. If the source has been modified more recently, it is recompiled and the new bytecode file is loaded. Java repeats this procedure until all the classes are correctly compiled and loaded.

java_g is a non-optimized version of Java that is suitable for use with debuggers such as jdb.

There are several options that you can feed the interpreter that change its behavior. Table 2.2 lists all of the command-line options for the Java interpreter.

Table 2.2. Command-line options for Java.

Command Function -cs, -checksource Recompiles any class whose .java source file is later than its .class file. -classpath path Overrides the CLASSPATH environment variable. -mx x Sets maximum size of memory allocation pool to x. Pool must be larger than 1,000 bytes and a k or m must be appended to the number to indicate size. The default is 16MB. -ms x Sets the size of the memory allocation pool to x. Pool must be larger than 1,000 bytes and a k or m must be appended to the number to indicate size. The default is 1MB.. -noasyncgc Turns off asynchronous garbage collection. The only time garbage collection occurs is when the program calls for it or runs out of memory. -ss x Sets the maximum stack size for C threads to x. Must be greater than 1,000 bytes and a k or m must be appended to the number to indicate size. -oss x Sets the maximum stack size for Java threads to x. -v, -verbose Prints a message to stdout when a class is loaded. -verify Uses verifier on all code. -verifyremote Uses verifier only on classes loaded with classloader. -noverify Disables verifier. -verbosegc Prints a message when garbage collector frees memory. -t Prints trace of an instruction being executed. Only available with javag. -debug Allows jdb connection to current session of Java interpreter. Displays password when debugging session is started. -DpropName=newVal Enables user to change values at runtime. Requires the full packaging extension to the class variable.

jdb


If the compiler returns errors related to your code, you can use the Java debugger to debug your code. The most common way to start jdb on local classes is using the following syntax:

jdb classname [parameters]

To run the debugger, you are substituting the command for Java with jdb. This starts the Java interpreter with the class to be debugged and any specified parameters, and stops before executing the class's first process.

If you need to run jdb with Java interpreter that is already running, you can connect to the interpreter using the -host and -password options. In order to be able to retrieve the password from the Java interpreter session, it must have been invoked it using the -debug option. When you start Java using the -debug option, it provides a password with which the jdb can be started.

You can feed the Java debugger several command-line parameters that change its behavior. These parameters can be listed using jdb's help parameter. Table 2.3 lists all of these commands.

Table 2.3. Command-line parameters for the jdb.

Option Function catch classID Breaks for the specified exception. Classes Lists currently known classes. clear classID:line Clears a breakpoint. Cont Continues execution from breakpoint. down [n frames] Moves down a thread's stack. dump ID[ID..] Prints all object information. exit (or quit) Exits debugger. help (or ?) Lists commands. ignore classID Ignores the specified exception. list [line number] Prints source code. load classname Loads class. locals Prints all local variables in current stack frame. memory Reports memory usage. methods Lists methods in a class. print ID [ID..] Prints an object or field. resume [threadID..] Resumes threads. Default is all. run class [args] Starts execution of a loaded class. step Executes current line. stop in classID.method Sets a breakpoint in a method. stop at classID:line Sets a breakpoint at a line. suspend [threadID..] Suspends threads. Default is all. threads threadgroup Lists threads. thread threadID Sets default thread. threadgroups Lists threadgroups. threadgroup name Sets current threadgroup. up [n frames] Moves up a thread's stack. use [path] Displays or changes source path. where [threadID] or all Dumps a thread's stack. !! Repeats last command.

Table 2.4 lists the command-line options for jdb that are used when accessing a running interpreter.

Table 2.4. Command-line options for the jdb.

Command Function -host <hostname> Sets the name of the host machine on which the interpreter session to attach to is running. -password <password> Logs in to the active interpreter session. This is the password printed by the Java interpreter. Password prints when invoked by the -debug option.

AppletViewer


You can use the AppletViewer to test applets in a runtime environment. The AppletViewer takes HTML files that refer to the applet and displays them. The only option for AppletViewer is -debug. This starts the AppletViewer in the jdb.

To invoke the AppletViewer, change to the directory of the HTML file in which the applet is embedded and type the following command:

appletviewer filename.html

The AppletViewer program has a few menu options that you can use while it is running. Its menu also allows you to set network and security properties for appletviewer. Table 2.5 lists the AppletViewer menu options and their descriptions.

Table 2.5. Applet menu options.

Option Function Restart Runs the loaded applet again. Reload Reloads the applet from disk. Useful if the class has changed since it was loaded. Clone Creates new window based upon command-line arguments for the first. Tag Shows the applet tag used in the HTML document to start the applet. Info Provides any information about the applet that is available. Properties Allows the different configurations to be set for AppletViewer.

AppletViewer's properties are outlined in the following table. They provide the network and security options of AppletViewer. Table 2.6 lists the AppletViewer properties:

Table 2.6. AppletViewer properties.

Option Property Http Proxy server required Http proxy port required Firewall proxy server required Firewall proxy port required Network access Several levels--no access, only access to applet's host, unrestricted access Class access restricted or unrestricted

Summary


These tools, in combination with the Java class libraries that you will learn about in Chapter 3, "An Introduction to Java Classes," are everything you'll need to program with Java. Graphical development environments incorporates all of the tools I have discussed in this chapter, but make using them even easier.

Previous Page Page Top TOC Next Page See Page