Appendix 1:

Other Features of Java

THIS TEXTBOOK does not claim to cover all the features of the Java programming language, or even to give comprehensive coverage to the features that it does cover. The primary purpose of the book is to explain programming, not Java. Nevertheless, it can serve as a good starting point for learning Java. This appendix briefly surveys some of the features of Java that were not covered in the book. It will acquaint you with some of the terms you might hear when people discuss Java, and it will point you towards some of the things you might want to learn more about as you continue your study of Java programming.

JAR Files and Resources

Each programming example in this book uses just a few class files, at most. A large Java project might use hundreds. People might hesitate to welcome a program that comes in hundreds of small files onto their hard drives. Fortunately, Java makes it possible to combine a collection of files into a single Java archive file, or "JAR" file. If all the class files needed to run a Java program are placed into a JAR file, then only that one file will be needed. Many Java programming environments can be configured to make JAR files when they compile a program. The command-line programming environment, in which the "javac" command is used for compilation, also has a "jar" command for making JAR files. For example, the following command makes a JAR file named "myprog.jar" and copies all the class files in the current directory into that JAR file:

            jar  cfv  myprog.jar  *.class

The "cfv" means "Create a jar archive as a File and be Verbose about telling me what you are doing." The "*.class" matches all files that end with ".class". The contents of a JAR file are compressed, by default, so the JAR file actually takes up less space than the files it contains.

A JAR file can be used for an applet. It just has to be specified in the <applet> tag:

            <applet archive="myprog.jar" code="MyApplet.class" 
                                                 width=200 height=100>

A JAR file can be used for a stand-alone application by specifying it as part of the "classpath":

            java  -classpath myprog.jar  MyApplication

In addition to class files, a JAR file can contain images, sounds, and other resource files needed by a program. It's fairly easy to load such resources into a program. An image resource, for example can be loaded in almost the same way as an independent image file, using the getImage() method of an applet or a Toolkit. The location of the resource just has to be specified differently. For example, if an applet class named MyApplet is loaded from a JAR file, and that file contains an image file named "icon.gif", then the following command will load the image:

      Image icon = getImage( MyApplet.class.getResource("icon.gif") );

The getResource() method is used to locate a resource. It returns a URL that specifies the location of the resource. (The getResource() method in this example is an instance method in an object, MyApplet.class, that represents the class to which the applet belongs. Objects that represent classes are another feature of Java that I haven't mentioned before. The idea is that the system will look for the image file in the same places it looked for the class and will find it in the same JAR file.)


All drawing in Java is done through an object of type Graphics. The Graphics class provides basic commands for drawing shapes and text and for selecting a drawing color. These commands are adequate in many cases, but they fall far short of what's needed in a serious computer graphics program. Java has another class, Graphics2D, that provides a larger and more serious set of drawing operations. Graphics2D is a sub-class of Graphics, so all the old routines from the Graphics class are also available in a Graphics2D.

The paintComponent() method of a JComponent gives you a graphics context of type Graphics that you can use for drawing on the component. In fact, the graphics context actually belongs to the sub-class Graphics2D (in Java version 1.2 and later), and can be type-cast to gain access to the advanced Graphics2D drawing methods:

            public void paintComponent(Graphics g) {
               Graphics2D g2;
               g2 = (Graphics2D)g;
                . // Draw on the component using g2.

Drawing in Graphics2D is based on shapes, which are objects that implement an interface named Shape. Shape classes include Line2D, Rectangle2D, Ellipse2D, Arc2D, and CubicCurve2D, among others. CubicCurve2D can be used to draw Bezier Curves, which are used in many graphics programs. Graphics2D has commands draw(Shape) and fill(Shape) for drawing the outline of a shape and for filling its interior. Advanced capabilities include: lines that are more than one pixel thick, dotted and dashed lines, filling a shape with a texture (this is, with a repeated image), filling a shape with a gradient, and drawing translucent objects that will blend with their background.

In the Graphics class, coordinates are specified as integers and are based on pixels. The shapes that are used with Graphics2D use real numbers for coordinates, and they are not necessarily bound to pixels. In fact, you can change the coordinate system and use any coordinates that are convenient to your application. In computer graphics terms, you can apply a "transformation" to the coordinate system. The transformation can be any combination of translation, scaling, and rotation.


A program that is well-documented is much more valuable than the same program without the documentation. Java comes with a tool called javadoc that can make it easier to produce the documentation is a readable and organized format. Javadoc is especially useful for documenting classes and packages of classes that are meant to be used by other programmers. A programmer who wants to use pre-written classes shouldn't need to search through the source code to find out how to use them. If the documentation in the source code is in the correct format, javadoc can separate out the documentation and make it into a set of web pages. The web pages are automatically formatted and linked into an easily browseable Web site. Sun Microsystem's on-line documentation for the standard Java API was produced using javadoc.

Javadoc is actually very easy to use. In a source code file, javadoc documentation looks like a regular multi-line comment, except that it begins with "/**" instead of with "/*". Each such comment is associated with some class, member variable, or method. The documentation for each item must be placed in a comment that precedes the item. (This is how javadoc knows which item the comment is for.) The comments can include certain special notations. For example, the notation "@return" is used to begin the description of the return value of a function. And "@param <parameter-name>" marks the beginning of the description of a parameter of a method. For example, here is a short utility method with a javadoc comment:

          * Return the real number represented by the string s,
          * or return Double.NaN if s does not represent a legal
          * real number.
          * @param s String to interpret as real number.
          * @return the real number represented by s.
         public static double stringToReal(String s) {
             try {
                return Double.parseDouble(s);
             catch (NumberFormatException e) {
                return Double.NaN;

Sun's Java Software Development Kit includes javadoc as a program that can be used on the command line. This program takes one or more Java source code files, extracts the javadoc comments from them, and prepares Web pages containing the documentation. Integrated development environments for Java typically include a menu command for generating javadoc documentation.


If the World-Wide Web -- and information technology in general -- is to be a truly global phenomenon, it shouldn't be tied to one country's language or customs. An internationalized computer program or applet is one that can adapt itself to the locale where it is being run. A locale in Java is specified as a language together with a country. These, in turn, are designated by standard two-letter codes, such as "en" for English, "es" for Spanish, "US" for the United States, "ES" for Spain, and "MX" for Mexico. The locale determines not only the language that is used but also details such as the output format of dates and numbers. A Java virtual machine has a default locale built into it. If it's running in the United States, the default locale is probably en_US. In Mexico, it would be es_MX.

The classes java.text.DateFormat and java.text.NumberFormat make it possible to display dates and numbers in a form that is appropriate for the default locale (or some other locale if you want). For example, the commands

            DateFormat df = DateFormat.getDateTimeInstance();
            String now = df.format( new Date() );

print the current date and time (as returned by "new Date()"), formatted according the conventions of the default locale. The output will look different in different countries.

Any text that is displayed to the user by a program -- labels on buttons, commands in menus, messages in dialog boxes, and so on -- should be in the language that is appropriate for the locale where the program is being run. Java makes it possible to put all the strings used by a program into a resource bundle and to use a different resource bundle for each locale. The actual strings do not appear in the program itself. They are in separate files. One file might contain the strings in English; another file, the same strings translated into Spanish; and a third file, the same strings in Japanese. The program can then be run in English, Spanish, and Japanese locales, and it will use a different language in each local. To make the program run correctly in a French locale, it's only necessary to create a new resource bundle, with the strings translated into French. It's not necessary to modify the program in any way. The class java.util.ResourceBundle represents a set of strings to be used by a program, and makes it possible to load the set of strings that is most appropriate for the default locale. When the program wants to display a string, it gets the string from the resource bundle. The string will be in the appropriate language for the default locale, assuming that a resource bundle for that language is available.

Pluggable Look-And-Feel

Macintosh programs don't look quite the same or work quite the same as Windows programs. Linux and UNIX have several different GUI styles, but none of them look or work exactly like Macintosh or Windows. Java programs are supposed to work on any computing platform. Ideally, they should have the right look-and-feel for the platform where they are running. In Swing, this is made possible by pluggable look-and-feel, or PLAF. The look-and-feel of a Swing interface can be managed using the class javax.swing.UIManager, which contains static methods for setting the default look-and-feel of newly created JComponents and for determining what look-and-feels are installed on the computer where the program is running. To change the look-and-feel of a JComponent that already exists, you can call its updateUI() method (after calling UIManager.setLookAndFeel()). To change the look-and-feel of a component and all the components that it contains, you can use SwingUtilities.updateComponentTreeUI(comp), where comp is the component.

Java has a cross-platform look-and-feel called "Metal" that will look about the same on all platforms. Other look-and-feels might be available, depending on the platform and the Java virtual machine that is being used. On MacOS X, for example, the default look-and-feel for Java is similar to the Mac's "Aqua" interface.

PLAF is supported by the basic architecture of Swing components. Swing uses a Model-View-Controller architecture in which the model (that is, the data) for a component is separate from the view (that is, the on-screen visual representation of the data). The data for a JButton is stored in an object of type ButtonModel. The data for a JTextComponent is stored in an object of type Document. When the look-and-feel is changed, the model is not affected, but the view can change. Most of the time, you don't need to be aware of the distinction between components and their models, but in some cases you need access to the model. For example, if you want to install a listener to respond to each change that is made to the contents of a JTextComponent, you have to register a DocumentListener with the text component's model: textinput.getDocument().addDocumentListener(listener).


A JavaBean is a component that can be combined with other components to make a complete program. JavaBeans can be assembled into a program using a visual development environment, which allows a programmer to add beans to a program, configure them, and set up interactions between them by dragging icons, using menus, clicking buttons, and so on. Sophisticated programs can be assembled with little or no programming. If you use an integrated development environment for Java programming, there's a good chance that it has some support for visual programming.

JavaBeans are objects, not classes. Many JavaBeans are GUI components, but this is not a requirement and a JavaBean might have no visual representation at all. Objects belonging to Java's standard GUI component classes are JavaBeans and can be used in visual development environments.

JavaBeans can be defined by any class that follows a few rules. The class should have a default constructor (one with no parameters). This allows a visual development environment to create a new bean in a default state without providing any information to the constructor. To be useful, a bean should have one or more properties, which are just values associated with the bean. Beans are configured by setting the values of their properties. A visual development environment recognizes a property by the fact that there are "get" and "set" methods for the bean. For example, if a bean has methods:

            String getTitle();
            void setTitle(String title);

then the bean has a property named "Title" of type String. You don't have to do anything else to define a property; just provide the "get" and "set" methods. Beans can, optionally, use PropertyChangeEvents to communicate. When a property of a bean is changed, it can emit an event. Other beans can register to listen for these events, so that they can respond when the property changes. Of course, beans might also generate other types of events, such as ActionEvents. A visual development environment should make it possible to route these events to other beans or possibly to write some code to respond to the events.

JavaBeans exist to enable the production of reusable objects and to promote the development of an "object economy" in which such objects are widely distributed and readily available.

Distributed Computing

Java is a language that was designed from the beginning to work in a networked computing environment. Applets can be downloaded over a network, and basic network communication is supported by the package. But this is just the beginning. Java has built-in support for distributed computing. In distributed computing, a program uses more than one computer. Different parts of the program run on different computers and communicate over a network. The program has access to much larger computing resources than are available on any one computer.

In Java, this is made possible by allowing a method that is running on one computer to call a method in an object that is on another computer. The parameters for the method are transmitted across the network, and the return value is sent back after the method has completed.

Java has support for two types of distributed object computing. RMI (Remote Method Invocation) is used for communication between two Java objects running on different computers. Java also supports CORBA (Common Object Request Broker Architecture), a standard that allows communication between objects written in different programming languages.

Servlets and JSP

Java is most visible on the client side of the Web, in the form of applets running in Web browsers. However, Java is also very useful on the server side. A servlet is a Java program that is meant to be executed by a Web server. This is similar to the way that applets are executed by a Web browser. If a Web server is capable of executing servlets, then its capabilities can be extended indefinitely by writing new servlets for it. Java is certainly not the only programming language used in this way, but it is an attractive choice because of its security, network-awareness, and large collection of APIs.

Servlets are often used to generate Web pages. Many Web pages are static -- they are simple, unchanging HTML files. When a server receives a request for such a page from a Web browser, all it has to do is send the HTML file to the browser. However, there are also dynamic Web pages. A dynamic web page is generated on demand each time the page is requested. The content of the page can be different each time it is requested. This can happen, for example, because the content depends on data that was typed into a Web form by the user or on information from a database. To serve up a dynamic page, the server has to run a program. Servlets can be used in this way. The servlet decides what should be on the page and creates the HTML code for displaying that content. The server then sends this HTML code to the Web browser that requested the page.

The task of writing dynamic Web pages can be simplified by using Java Server Pages (JSP) instead of servlets. A Java server page is an HTML file with some Java code embedded in it. When a Web server receives a request for the page, the Java code is executed to generate the dynamic part of the page. JSP is used on many Web sites. You can recognize a JSP page because the file name for the page will end with ".jsp".

Servlets and JSP are not part of the standard edition of Java, J2SE, but they are included in the enterprise edition, J2EE.

More Features

Java has APIs (Application Programming Interfaces) for many more features, and the list seems to be growing all the time. It's unlikely that any one person can master them all. What can be mastered are the principles and techniques on which they are all built. After that, it's just a matter of poking around in the documentation.... Here are a few more of the things you might run into:

[ Main Index ]