Ads 468x60px

Monday, July 25, 2011

The Java Development Environment

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:
class HelloWorld {
     public static void main (String args[]) {
     System.out.println("Hello World!");
Save the file as 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.


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 file name.)
javac [ options ]
javac_g [ options ]
For your example, run the following command:
If the code compiles correctly, you will see two files in your classes directory: 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 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.
-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.


You can use the Java interpreter to verify and execute your code. To run the Java interpreter, enter the executable name, options, class name (without the file name 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.
-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.


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 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 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.
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.
-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. The password prints when invoked by the -debug option.


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.
Restart Runs the loaded applet again.
Reload Reloads the applet from disk. Useful if the class has changed since it was loaded.
Clone Creates a 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 Table 2.6. They provide the network and security options of AppletViewer.

Table 2.6. AppletViewer properties.
Http proxy serverrequired
Http proxy portrequired
Firewall proxy serverrequired
Firewall proxy portrequired
Network accessSeveral levels-no access, only access to applet's host, unrestricted access
Class accessrestricted or unrestricted 


Post a Comment