Blakes 21 Days Appendix E
APPENDIX E
Programming with the Java Development Kit
- Top
- 637 The Java Development Kit (JDK) can be used throughout this book to create, compile, and run Java programs.
- 637 The tools that make up the kit contain numerous features that many programmers don't explore.
- Some of the tools themselves might be new to you.
- 637 This appendix covers features of the kit that you can use to create more reliable, better-tested, and faster-running Java programs.
Overview of the JDK
- Top
- 638 Although you can use numerous integrated development environments to create Java programs,
- the most widely may still be the Java Development Kit (JDK) from Oracle, the set of command-line tools that are used to develop software with the Java language
- 638 There are two main reasons for the kit's popularity:
- It's free. You can download a copy at no cost from the official Java website at www.oracle.com/technetwork/java.
- It's first. Whenever a new version of the language is released, the first tools that support the new version are in the kit.
- 638 The kit uses the command line.
- This is also called the MS-DOS prompt, command prompt, or console under Windows and the shell prompt under UNIX.
- You enter commands using the keyboard, as in this example:
- 638 This command compiles a Java program called VideoBook.java using the kit's compiler.
- The command has two elements: the name of the compiler, javac, and the name of the program to compile, VideoBook.java.
- A space character separates the two elements.
- 638 Each kit command follows the same format: the name of the tool to use, followed by one or more elements indicating what the tool should do.
- These elements are called arguments.
- 638 The following illustrates the use of command-line arguments:
- java VideoBook add DVD "Broadcast News"
- 638 This command tells the Java Virtual Machine (JVM) to run a class file called VideoBook with three command-line arguments: the strings "add", "DVD", and "Broadcast News."
- Top
- 638 NOTE: You might think there are more than three command-line arguments because of the spaces in the string "Broadcast News".
- The quotation marks around that string cause it to be considered one command-line argument, which makes it possible to include spaces in an argument.
- Top
- 638 Some arguments used with the kit modify how a tool functions.
- These arguments are preceded by a hyphen character and are called options.
- 639 The following command shows the use of an option:
- 639 This command tells the JVM to display its version number rather than trying to run a class file.
- It's a good way to find out whether the kit is correctly configured to run Java programs on your system.
- Here's an example of the output run on a system equipped with Java 8:
Output
java version "1.8.0_60"
Java (TM) SE Runtime Environment (build1.8.0_60-b27)
Java HotSpot (TM) 64-Bit Server VM (build 25.60-b23, mixed mode)
- Top
- 639 The version reflects Oracle's internal number for Java 8, which is 1.8
- 639 In some instances, you can combine options with other arguments.
- For example, if you compile a Java class that uses deprecated methods,
- you can see more information on these methods by compiling the class with a -deprecation option, as in the following:
- javac -deprecation OldVideoBook.java
The java Virtual Machine
- Top
- 639 java, the Java Virtual Machine, is used to run Java applications from the command line.
- It takes as an argument the name of a class file to run, as in the following example:
- 639 Although Java class files end with the .class extension, this extension is not specified when the JVM is used.
- The machine also is called the Java interpreter.
- 639 The class loaded by the JVM must contain a class method called main() that takes the following form:
public static void main(String[] arguments) {
// method here
}
- 639 Some simple Java programs might consist of only one class - the one containing the main() method.
- In more complex programs that use other classes, the JVM automatically loads any other classes that are needed.
- 639 The JVM runs bytecode, compiled instructions that the machine executes.
- After a Java program is saved in bytecode as a .class file, it can be run by different JVMs without modifications.
- If you have compiled a Java program, it will be compatible with any JVM that fully supports Java
- Top
- 640 NOTE: Interestingly, Java is not the only language that you can use to create Java bytecode.
- NetRexx, JPython, JRuby, JudoScript, and several dozen other languages compile into .class files of executable bytecode thru the use of compilers specific to those languages.
- Robert Tolksdorf maintains a comprehensive list of these languages at www.is-research.de/info/vmlanguages.
- 640 You can specify the class file that the JVM will run in two different ways.
- If the class is not part of any package, you can run it by specifying the class's name, as in the preceding java BidMonitor example.
- If the class is part of the package, you must specify the class by using its full package and class name.
- 640 For example, consider a SellItem class that is part of the org.cadenhead.auction package.
- To run this application, you would use the following command:
- java org.cadenhead.auction.SellItem
- Top
- 640 Each element of the package name corresponds to its own subfolder.
- The JVM looks for the SellItem.class file in several different places:
- The org\cadenhead\auction subfolder of the folder where the java command was entered
- (If the command was entered from the C:\J21work folder,
- for example, the SellItem.class file can be run successfully if it is in the C:\J21work\org\cadenhead\auction folder.)
- The org\cadenhead\auction subfolder of any folder in your Classpath setting
- 640 If you're creating your own packages,
- an easy way to manage them is to add a folder to your Classpath that's the root folder for any packages you create,
- such as C:\javapackages or something similar.
- After creating subfolders that correspond to the name of the package, place the package's class files in the correct subfolder.
- 640 You can specify a Classpath when running a Java application with the command-line option -cp.
- Here's an example:
- java -cp . org.cadenhead.auction.SellItem
- 640 This command sets the Classpath to ".", which represents the current folder.
- 641 Java supports assertions, a debugging feature that works only when requested as a command-line option.
- To run a program using the JVM and make use of any assertions it contains, use the command-line option -ea,
- as in the following example:
- 641 The JVM executes all assert statements in the application's class and all other class files it uses, with the exception of classes from the Java Class Library.
- 641 To remove that exception and make use of all assertions, run the class with the -esa option.
- 641 If you don't specify one of the options that turns on the assertions feature, the JVM ignores all assert statements.
The javac Compiler
- Top
- 641 The Java compiler, javac, converts Java source code into one or more class files of bytecode that a JVM can run.
- 641 Java source code is stored in a file with the .java file extension.
- This file can be created with any text editor that can save a document without any special formatting codes.
- The terminology varies depending on the text-editing software being used, but these files are often called plain text, ASCII text, DOS text, or something similar.
- 641 A Java source code file can contain more than one class, but only one of these classes can be declared to be public.
- A class can contain no public classes at all if desired, although this isn't possible with applets because of the rules of inheritance.
- 641 If a source code file contains a class that has been declared to be public, the filename must match the name of that class.
- For example, the source code for a public class called BuyItem must be stored in a file called BuyItem.java.
- 641 To compile a file, you run the javac tool with the name of the source code file as an argument, as in the following:
- 641 You can compile more than one source file by including each separate file name as a command-line argument, such as this command:
- javac BuyItem.java SellItem.java
- 641 You also can use wildcard characters such as * and ?. Use the following command to compile all .java files in a folder:
- 642 When you compile one or more Java source code files, a separate .class file is created for each Java class that compiles successfully.
- Top
- 642 Another useful option when running the compiler is -deprecation, which causes the compiler to describe any deprecated methods that are being employed in a Java program.
- 642 A deprecated method is one that Oracle has replaced with a better alternative, either in the same class or in a different class.
- Although the deprecated method works, at some point Oracle may decide to remove it from the class.
- The deprecation warning is a strong suggestion to stop using that method as soon as you can.
- 642 Normally, the compiler issues a single warning if it finds any deprecated methods in a program.
- The -deprecation option causes the compiler to list each method that has been deprecated, as in the following command:
- javac -deprecation SellItem.java
- Top
- 642 If you're more concerned with the speed of a Java program than the size of its class files, you can compile its source code with the -o option.
- This creates class files that have been optimized for faster performance.
- Methods that are static, final, or private might be compiled inline, a technique that makes the class file larger but causes the methods to be executed more quickly.
- 642 If you plan to use a debugger to look for bugs in a Java class,
- compile the source with the -g option to put all debugging information in the class file, including references to line numbers, local variables, and source code.
- (To keep all this out of a class, compile with the -g:none option.)
- 642 Normally, the Java compiler dosesn't provide a lot of information as it creates class files.
- In fact, if the source code compiles successfully and no deprecated methods are employed, you won't see any output from the compiler.
- No news is good news in this case.
- Top
- 642 If you want to see more information on what the javac tool is doing as it compiles source code, use the -verbose option.
- The more verbose compiler describes how long it takes to complete different functions, the classes that are loaded, and the overall time required.
The appletviewer Browser
- Top
- 642 The appletviewer tool runs Java programs that require a web browser and are presented as part of a Hypertext Markup Language (HTML) document.
- It takes an HTML document as a command-line argument, as in the following example:
- appletviewer NewAuctions.html
- 643 If the argument is a web address instead of a reference to a file, appletviewer loads the HTML document at that address. For example:
- appletviewer http://www.javaonthebrain.com
- 643 Figure E.1 shows an applet loaded from this page, a site developed by cartoonist and Java game programmer Karl Hornell.
Figure E.1 - Opening Java web applets outside of a browser. - goes here
- Top
- 643 When appletviewer loads an HTML document, every applet on that document begins running in its own window.
- The size of these windows depends on the height and width attributes that were set in the applet's html tag.
- 643 Unlike a web browser, appletviewer cannot be used to view the HTML document itself.
- If you want to see how the applet is laid out in relation to the other contents of the document, you must use a Java-capable web browser.
- 643 CAUTION: The Java Plug-in from Oracle enables web browsers to run Java applets.
- The Plug-in is included in the Java Runtime Environment, a JVM for running Java programs that is installed along with the Java Development Kit.
- If it isn't already present on your system, you can download it from Oracle's website at www.java.com
- 643 Using appletviewer is reasonably straightforward, but you might be unfamiliar with some of the menu options that are available as the viewer runs an applet.
- 643 The following menu options are available:
- The Restart and Reload options are used to restart the applet's execution.
- The difference between these two options is that Restart does not unload the applet before restarting it, whereas Reload does.
- The Reload option is equivalent to closing the applet viewer and opening it again on the same web page.
- The Start and Stop options are used to call the applet's start() and stop() methods directly.
- The Clone option creates a second copy of the same applet running in its own window.
- The Tag option displays the program's applet or object tag, along with the HTML for any param tags that configure the applet.
- 644 Another option on the Applet pull-down menu is Info, which calls the applet's getAppletInfo() and getParameterInfo() methods.
- A programmer can implement these methods to provide more information about the applet and the parameters it can handle.
- 644 The getAppletInfo() method returns a string that describes the applet.
- The getParameterInfo() method returns an array of string arrays that specify the name, type, and description of each parameter.
- 644 Listing E.1 contains a Java applet that demonstrates the use of these methods.
Listing E.1 The Full Text of AppInfo.java
- Top
- page 644-645
import java.awt.*;
public class AppInfo extends javax.swing.JApplet {
String name, date;
int veration;
public String getAppletInfo() {
String response = "This applet demonstrates the "
+ "use of the Applet's Info feature.";
return response;
}
public String[][] getParameterInfo() {
String[] p1 = { "Name", "String", "Programmer's name" };
String[] p2 = { "Date", "String", "Today's date" };
String[] p3 = { "Version", "int", "Version number" };
String[][] response = { p1, p2, p3 };
return response;
}
private void init() {
name = getParameter("Name");
date = getParameter("Date");
String versText = getParameter("Version");
if (versText != null) {
version = Integer.parseInt(versText);
}
}
public void paint(Graphics screen) {
Graphics2D screen2D = (Graphics2D) screen;
screen2D.drawString("Name: " + name, 5, 50);
screen2D.drawString("Date: " + date, 5, 100);
screen2D.drawString("Version: " + version, 5, 150);
}
}
Explanation
- Top
- 645 The main function of this applet is to display the value of three parameters: Name, Date, and Version.
- The getAppletInfo() method returns the following string:
- This applet demonstrates the use of the Applet's Info feature. reserve
- 645 The getParameterInfo() method is a bit more complicated if you haven't worked with multidimensional arrays.
- The following things are taking place:
- Line 13 defines the return type of the method as a two-dimensional array of String objects.
- Line 14 creates an array of String objects with three elements: "Name", "String", and "Programmer's name".
- These elements describe one of the parameters that can be defined for the AppInfo applet.
- They describe the name of the parameter ("Name" in this case), the type of data that the parameter will hold (a string), and a description of the parameter ("Programmer's name").
- The three-element array is stored in the p1 object.
- Lines 15 and 16 define two more String arrays for the Date and Version parameters.
- Line 17 uses the response object to store an array that contains three string arrays: p1, p2, and p3.
- Line 18 uses the response object as the method's return value.
- 645 Listing E.2 contains a web page that can be used to load the AppInfo applet.
Listing E.2 The Full Text of AppInfo.html
- Top
- page 645
<applet code="AppInfo.class" height="200" width="170">
<param name="Name" value="Rogers Cadenhead">
<param name="Date" value="08/15/15">
<param name="Version" value="R7">
</applet>
- Top
- 645 Figure E.2 shows the applet running with appletviewer, and Figure E.3 is a screen capture of the dialog box that opens when the viewer's Info menu option is selected.
- reserve
Figure E.2 - The AppInfo applet running in appleviewer. - goes here
Figure E.3 - The Info dialog box of the AppInfo applet. - goes here
- Top
- 646 These features require a browser that makes this information available to users.
- The kit's appletviewer handles this thru the Info menu option, but actual browsers do not offer anything like it.
The javadoc Documentation Tool
- Top
- 646 The Java documentation creator, javadoc, takes a .java source file or package name as input and generates detailed documentation in HTML format.
- 646 For javadoc to create full documentation for a program, a special type of comment statement must be used in the program's source code.
- Tutorial programs in this book use //, /*, and */ in source code to create comments - information for people who are trying to make sense of the program.
- 646 Java also has a more structured type of comment that the javadoc tool can read.
- This comment is used to describe program elements such as classes, variables, objects, and methods.
- It takes the following format:
-
/** A descriptive sentence or paragraph.
* @tag1 Description of this tag.
* @tag2 Description of this tag.
*/
- 647 A Java documentation comment should be placed immediately above the program element it is documenting and should succinctly explain what the program element is.
- For example, if the comment precedes a class statement, it describes the class's purpose.
- 647 In addition to the descriptive text, different items can be used to document the program element further.
- These items,called tags, are preceded by an (@) and are followed by a space and a descriptive sentence or paragraph.
- Top
- 647 Listing E.3 contains a thoroughly documented version of the AppInfo applet called AppInfo2.
- The following tags are used in this program:
- @author - The program's author. This tag can be used only when a class is documented. It is ignored unless the -author option is used when javadoc is run.
- @version text - The program's version number. This also is restricted to class documentation. It requires the -version option when you're running javadoc, or the tag will be ignored.
- @return text - The variable or object returned by the method being documented.
- @serial text - A description of the data type and possible values for a variable or object that can be serialized - saved to disk along with the values of its variables and retrieved later.
Listing E.3 The Full Text of AppInfo2.java
- Top
import java.awt.*;
/** This class displays the values of three parameters:
* Name, Date, and Version.
* @author <a href="http://java21days.com/">Rogers Cadenhead</a>
* @version 7.0
*/
public class AppInfo2 extends javax.swing.JApplet {
/**
* @serial The programmer's name.
*/
String name;
/**
* @serial The current date.
*/
String date;
/**
* @serial The program's version number.
*/
int version;
/**
* This method describes the applet for any browsing tool that
* request information from the program
* @return A String describing the applet.
*/
public String getAppletInfo() {
String response = "This applet demonstrates the "
+ "use of the Applet's Info feature.";
return response;
}
/**
* This method describes the parameters that the applet can take
* for any browsing tool that requests this information.
* @return An array of String[] objects for each parameter.
*/
public String[][] getParameterInfo() {
String[] p1 = { "Name", "String", "Programmer's name" };
String[] p2 = { "Date", "String", "Today's date" };
String[] p3 = { "Version", "int", "Version number" };
String[][] response = { p1, p2, p3 };
return response;
}
/**
* This method is called when the applet is first initialized.
*/
public void init() {
name = getParameter("Name");
date = getParameter("Date");
String versText = getParameter("Version");
if (versText != null) {
version = Integer.parseInt(versText);
}
}
/**
* This method is called when the applet's display window is
* being repainted.
*/
public void paint(Graphics screen) {
Graphics2D screen2D = (Graphics2D) screen;
screen2D.drawString("Name: " + name, 5, 50);
screen2D.drawString("Date: " + date, 5, 100);
screen2D.drawString("Version: " + version, 5, 150);
}
}
- Top
- 648 The following command creates HTML documentation from the source code file AppInfo2.java:
javadoc - author -version AppInfo2.java
- 649 The Java documentation tool creates several different web pages in the same folder as AppInfo2.java.
- These pages document the program in the same manner as Oracle's official documentation for the Java Class Library.
- Top
- 649 To see the documentation that javadoc has created for AppInfo2, load the newly created web page index.html on your web browser.
- Figure E.4 shows this page loaded with Google Chrome.
Figure E.4 - Java documentation for the AppInfo2 program. - goes here
- Top
- 649 The javadoc tool produces extensively hyperlinked web pages.
- Navigate thru the pages to see where the information in your documentation comments and tags show up.
- 649 If you're familiar with HTML markup, you can use the HTML tags such as A, TT, and B within your documentation comments.
- Line 5 of the AppInfo2 program uses an A tag to turn the text "Rogers Cadenhead" into a hyperlink to this book's website.
- 649 The javadoc tool also can be used to document an entire package by specifying the package name as a command-line argument.
- HTML files are created for each .java file in the package, along with an HTML file indexing the package.
- 650 If you want the Java documentation to be produced in a different folder than the default, use the -d option followed by a space and the folder name.
- 650 The following command creates Java documentation for AppInfo2 in a folder called C:\JavaDocs\ :
javadoc -author -version -d C:\JavaDocs\ AppInfo2.java
- Top
- 650 The following list details the other tags you can use in Java documentation comments:
- @deprecated text provides a note that indicats that the class, method, object, or variable has been deprecated.
- This causes the javac compiler to issue a deprecation warning when the feature is used in a program that's being compiled.
- @exception class description is used with methods that throw exceptions.
- This tag documents the exception's class name and its description.
- @param name description is used with methods.
- This tag documents the name of an argument and a description of the values the argument can hold.
- @see class indicates the name of another class, which will be turned into a hyperlink to the Java documentation for that class.
- This can be used without restriction in comments.
- @see class#method indicates the name of a method of another class, which will be used for a hyperlink directly to the documentation for that method.
- This can be used without restriction.
- @since text indicates the note describing when a method or feature was added to Java's class library.
The jar Java File Archival Tool
- Top
- 650 When you deploy a Java program, keeping track of all the class files and other files required by the program can be cumbersome.
- 650 To make this easier, the kit includes a tool called jar that can pack all a program's files into a Java archive - also called a JAR file.
- The jar tool also can be used to unpack the files in one of these archives.
- 650 JAR files can be compressed using the zip format or packed without using compression.
- 650 To use the tool, type the command jar followed by command-line options and a series of filenames, folder names, or wildcards.
- 651 The following command packs all of a folder's class and GIF image files into a single Java archive called Animate.jar:
- jar cf Animate.jar *.class *.gif
- 651 The argument cf specifies two command-line options that can be used when running the jar program.
- The c option indicates that a Java archive file should be created and f indicates that the name of the archive file will follow as one of the next arguments.
- 651 You also can add specific files to a Java archive with a command such as the following:
- jar cf MusicLoop.jar MusicLoop.class muskratLove.mpl shopAound.mp3
- 651 This creates a MusicLoop.jar archive containing three files: MusicLoop.class, muskratLove.mpl, and shopAound.mp3
- Top
- 651 Run jar without any arguments to see a list of options that can be used with the tool.
- 651 One use of jar is to put all files necessary to run a Java applet in a single JAR file.
- This makes it much easier to deploy the applet on the Web.
- 651 The standard way of placing a Java applet on a web page is to use an applet or object tag to indicate the applet's primary class file.
- A Java-enabled browser then downloads and runs the applet.
- Any other classes and any other files that the applet needs are downloaded from the web server.
- 651 The problem with running applets in this way is that every file an applet requires
- - helper classes, images, audio files, text files, or anything else
- - requires a separate connection from a web browser to the server containing the file.
- This can significantly increase the amount of time it takes to download an applet and everything it needs to run.
- 651 If you can reduce the number of files the browser has to load from the server by putting many files into one Java archive,
- a web browser can download and run your applet more quickly.
- If the files in a Java archive are compressed, it loads even more quickly.
- 651 After you create a Java archive, the archive attribute is used with the applet tag to show where the archive can be found.
- You can use Java archives with an applet with tags such as the following:
<applet code="MusicLoop.class" archive="MusicLoop.jar" width="45" height="42">
</applet>
- 651 This tag specifies that an archive called MusicLoop.jar contains files used by the applet.
- Browsers and browsing tools that support JAR files will look inside the archive for files that are needed as the applet runs.
- Top
- 652 CAUTION: Although a Java archive can contain class files, the archive attribute does not remove the need for the code attribute.
- A browser still needs to know the name of the applet's main class file to load it.
- 652 When you use an object tag to display an applet that uses a JAR file, the applet's archive file is specified as a parameter using the param tag.
- The tag should have the name attribute "archive" and a value attribute with the name of the archive file.
- 652 The following example is a rewrite of the preceding example to use object instead of applet:
<object code="MusicLoop.class" width="45" height="42">
<param name="archive" value="MusicLoop.jar">
</object>
The jdb Debugger
- Top
- 652 jdb, the Java debugger, is a sophisticated tool that helps you find and fix bugs in Java programs.
- You also can use it to better understand what is taking place behind the scenes in the JVM as a program is running.
- It has a large numebr of features, including some that might be beyond the expertise of a Java programmer who is new to the language.
- 652 You don't need to use debugger to degug Java programs.
- This is fairly obvious, especially if you've been creating your own Java programs as you read this book.
- After the Java compiler generates an error, the most common response is to load the source code into an editor,
- find the line cited in the error message, and try to spot the problem.
- You repeat this dreaded compile-curse-find-fix cycle until the program compiles without complaint.
- 652 After using this debugging method for a while, you might think that the debugger is unnecessary to the programming process because it's such a complicated tool to master.
- This reasoning makes sense when you're fixing problems that cause compiler errors.
- Many of these problems are simple things such as a misplaced semicolon, unmatched { and } braces, or the use of the wrong type of data as a method argument.
- However, when you start looking for logic errors - more subtle bugs that don't stop the program from compiling and running - a debugger is an invaluable tool.
- 652 The Java debugger has two features that are useful when you're searching for a bug that can't be found by other means:
- single-step execution and breakpoints.
- Single-step execution pauses a Java program after every line of code executed.
- Breakpoints are points where execution of the program pauses.
- Using the Java debugger, these breakpoints can be triggered by specific lines of code, method calls, or caught exceptions.
- 653 The Java debugger works by running a program using a version of the JVM over which it has complete control.
- 653 Before you use the Java debugger with a program, you compile the program with the -g option, which causes extra information to be included in the class file.
- This information greatly aids in debugging.
- Also, you shouldn't use the -o option, because its optimization techniques might produce a class file that does not directly correspond with the program's source code.
Debugging Applications
- Top
- 653 If you're debugging an application, you can run the jdb tool with a Java class as an argument. This is shown in the following:
- 653 This example runs the debugger with WriteBytes.class, an application that's available from the book's website at www.java21days.com.
- Blake's Note: After clicking www.java21days.com, you need to select the book which get you to the page where you can find Appendix E.
- Visit the site, select the Appendix E page, and then save the files WriteBytes.class and WritesBytes.java in the same folder from which you run the debugger.
- 653 The WritesBytes application writes a series of bytes to disk to produce the file pic.gif.
- 653 The debugger loads this program but does not begin running it, displaying the following output:
- Top
- 653 You control the debugger by typing commands at the > prompt.
- 653 To set a breakpoint in a program, you use the stop in or stop at commands.
- The stop in command sets a breakpoint at the first line of a specific method in a class.
- You specify the class and method name as an argument to the command, as in the following example:
- stop in SellItem.SetPrice
- 653 This command sets a breakpoint at the first line of the SetPrice() method.
- Note that no arguments or parentheses are needed after the method name.
- 653 The stop at command sets a breakpoint at a specific line number within a class.
- You specify the class and number as an argument to the command, as in the following example:
- stop at WriteBytes:14
- 654 If you're trying this with the WriteBytes class, you see the following output after entering this command:
Deferring breakpoint WriteBytes:14
It will be set after the class is loaded.
- Top
- 654 You can set as many breakpoints as you want within a class.
- To see the breakpoints that are currently set, use the clear command without any arguments.
- The clear command lists all current breakpoints by line number rather than method name, even if they were set using the stop in command.
- 654 By using clear with a class name and line number as an argument, you can remove a breakpoint.
- If the hypothetical SellItem.SetPrice method were located at line 215 of SellItem, you could clear this breakpoint with the following command:
- clear SellItem:215
- 654 Within the debugger, you can begin executing a program with the run command.
- The following output shows what the debugger displays after you begin running the WriteBytes class:
run WriteBytes
VM Started: Set deferred breakpoint WriteBytes:14
Breakpoint hit: "thread=main", WriteBytes.main(), line=14 bci=413
14 for (int =0; i < data.length; i++)
- Top
- 654 After you have reached a breakpoint in the WriteBytes class, experiment with the following commands:
- list - At he point where execution stopped, this command displays the source code of the line and several lines around it.
- This requires access to the .java file of the class where the breakpoint has been hit,
- so you must have WriteBytes.java in either the current folder or one of the folders in your Classpath.
- locals - This command lists the values for local variables that are currently in use or will soon be defined.
- print text - This command displays the value of the variable, object, or array element specified by text.
- step - This command executes the next line and stops again.
- cont - This command continues running the program at the point it was halted.
- !! - This command repeats the previous debugger command.
- Top
- 655 After trying out these commands within the application, you can resume running the program by clearing the breakpoint and using the cont command.
- Use the exit command to end the debugging session.
- 655 The WriteBytes application creates a file called pic.gif.
- You can verify that this file ran successfully by loading it with a web browser or image-editing software.
- You'll see a small letter J in black and white.
- 655 After you have finished debugging a program and you're satisfied that it works correctly, recompile it without the -g option.
Debugging Applets
- Top
- 655 You can't debug an applet by loading it using the jdb tool.
- Instead, use the -debug option of appletviewer, as in the following example:
- appletviewer -debug AppInfo.html
- 655 This loads the Java debugger, and when you use a command such as run, appletviewer begins running also.
- Try this example to see how these tools interact.
- 655 Before you use the run command to execute the applet, set a breakpoint in the program at the first line of the getAppletInfo method.
- Use the command:
- stop in AppInfo.getAppletInfo
- 655 After you begin running the applet, the breakpoint won't be hit until you cause the getAppletInfo() method to be called.
- You do so by selecting Applet, Info from appletviewer's menu.
Advanced Debugging Commands
- Top
- 655 With the features you have learned about so far, you can use the debugger to stop execution of a program and learn more about what's taking place.
- This might be sufficient for many of your debugging tasks, but the debugger also offers many other commands.
- These include the following:
- up moves up the stack frame so that you can use locals and print to examine the program at the point before the current method was called.
- down moves down the stack frame so that you can examine the program after the method call.
- 655 A Java program often has places where a chain of methods is called.
- One method calls another method, which calls another method, and so on.
- At each point where a method is being called, Java keeps track of all the objects and variables within that scope by grouping them.
- This grouping is called a stack, as if you were stacking these objects like a deck of cards.
- The various stacks in existance as a program runs are called the stack frame.
- 656 By using up and down along with commands such as locals, you can better understand how the code that calls a method interacts with that method.
- Top
- 656 You also can use the following commands within a debugging session:
- classes list the classes currently loaded into memory.
- methods list the methods of a class.
- memory shows the total amount of memory and the amount that isn't currently in use.
- threads list the threads that are executing.
- 656 The threads command numbers all the threads.
- This enables you to use the suspend command followed by a number to pause that thread, as in suspend 1.
- You can resume a thread by using the resume command followed by the thread's number.
- 656 Another convenient way to set a breakpoint in a Java program is to use the catch text command,
- which pauses execution when the Exception class named by text is caught.
- 656 You also can cause an exception to be ignored by using the ignore text command with the Exception class named by text.
Using System Properties
- Top
- 656 One handy feature of the kit is that the command-line option -D can modify the performance of the Java Class Library.
- 656 If you have used other programming languages before learning Java,
- you might be familiar with environment variables, which provide information about the operating system in which a program is running.
- An example is the Classpath setting, which indicates the folders where the JVM should look for a class file.
- 656 Because different operating systems have different names for their environment variables, a Java program cannot read them directly.
- Instead, Java includes a number of different system properties that are available on any platform with a Java implementation.
- 656 Some properties are used only to get information.
- The following system properties are among those that should be available on any Java implementation:
- java.version is the version number of the JVM.
- java.vendor is a string identifying the vendor associated with the JVM.
- os.name is the operating system in use.
- os.version is the version number of that operating system.
- Top
- 657 Other properties can effect how the Java Class Library performs when being used inside a Java program.
- An example is the java.io.tmpdir property, which defines the folder that Java's input and output classes use as a temporay workspace.
- 657 You can set a property at the command line by using the -D option followed by the property name, an equal sign, and the property's new value, as in this command:
- java -Duser.timezone=Asia/Jakarta Auctioneer
- 657 The use of the system property in this example sets the default time zone to Asia/Jakarta before running the Auctioneer class.
- This affects any Date objects in a Java program that do not set their own zone.
- 657 These property changes are not permanent; they apply only to that particular execution of the class and any classes it uses.
- Top
- 657 TIP: In the java.util package, the TimeZone class includes a class method called getProperties()
- that returns a string array containing all the time zone identifiers that Java supports.
- The following code displays these identifiers:
String[] ids = java.util.Timezone.getAvaialbleIDs();
for (int i = 0; i < ids.length; i++) {
System.out.println(ids[i]);
}
- Top
- 657 You also can create your own properties and read them using the getProperty() method of the System class, which is part of the java.lang package.
- 657 Listing E.4 contains the source code of a simple program that displays the value of a user-created property.
Listing E.4 - The full text of ItemProp.java
- Top
- Page 658
class IremProp {
public static void main(String90 arguments) {
String n = System.getProperty("Item.name");
System.out.println("The item is named " + n);
}
}
- Top
- 658 If you run this program without setting the item.name property on the command line, the output is the following:
- 658 You can set the item.name property using the -D option, as in this command:
- java -Ditem.name="Microsoft Bob" ItemProp
- 658 The output is the following:
- The item is named Microsoft Bob
- 658 The -D option is used with the JVM.
- To use it with appletviewer as well, all you have to do differently is precede the -D with -J.
- The following command shows how this can be done:
- appletviewer -J-Dtimezone=Asia/Jararta AppInfo.html
- 658 This example causes appletviewer to use the default time zone Asia/Jarkarta with all applets on the web page AppInfo.html.
The keytool and jarsigner Code Signing Tools
- Top
- 658 On Day 14, "Developing Swing Applications," the process of packaging an application into a JAR file that can be run from a web page is described.
- This requires that the JAR be signed with a digital certificate.
- For testing purposes, the keystore and jarsigner tools in the KIT can be used to create a key and use it to digitally sign a JAR file.
- 658 The first step is to use keytool to create a key and assign it an alias and password:
- keytool keytool -genkey -alias examplekey -keypass swordfish
- 658 The -genkey argument generates a new key, which in this example is named "examplekey" and has the password "swordfish".
- If this is the first time keytool has been used, you're prompted for a password that protects access to the key database, which is called a keystore.
- Top
- 659 After a key has been placed in the keystore, it can be used with the jarsigner tool to sign an archive file.
- This tool requires the keystore and key passwords and the key's alias.
- Here's how the Animate.jar archive could be signed with the examplekey key:
jarsigner -storepass bazinga -keypass swordfish Animate.jay examplekey reserve
- 659 The keystore password in this example is "bazinga".
- The security certificate used to sign the archive will last 90 days and will be described as an "untrusted source"
- when an application is run through Java Web Start or when an applet is run in a web browser.
- 659 Because running a Java program in a browser from an untrusted source violates Java's default security policy,
- the only way to run a self-signed JAR file is to add an exception to the Java Control Panel.
- Run the control panel, which on Windows is part of the Windows Control Panel.
- Choose the Security tab to bring it to the front; then click Edit Site List to add the domain name of the source of the applet
- (such as http://cadenhead.org if you wanted to run the PageData Java Web Start application from the book's website at www.java21days.com).
End of Page