ÇáãÓÇÚÏ ÇáÔÎÕí ÇáÑÞãí

ãÔÇåÏÉ ÇáäÓÎÉ ßÇãáÉ : SAMS PUBLISHING " JAVA UNLEASHED " VOL 1



Argonaut
08-10-2005, 04:26 PM
ÈÓã Çááå ÇáÑÍãä ÇáÑÍíã
ÇáÓáÇã Úáíßã æÑÍãÉ Çááå æÈÑßÇÊå
åÐÇ ÇáßÊÇÈ ãÍãí ÈãæÌÈ ÞæÇäíä ÇáÍÞæÞ ÇáãáßíÉ æÇáÝßÑíÉ æÃí ÇÓÊÚãÇá ÛíÑ ãÑÎÕ íÚÇÞÈ ÈãæÌÈ ÇáÞÇäæä

ÔÈÇÈ Çáíßã åÐÇ ÇáßÊÇÈ ÇáÐí ÞÏ ÊÕá ÞíãÊå Çáì 50 ÏæáÇÑ
Ãí ãÔßáÉ (äÞÕ ¡ÊæÒíÚ ¡Îáá) íÑÌì ßÊÇÈÊå åäÇ
ÇÎÑ ÊÍÏíË áå ÚÇã 1997
æÔßÑÇ
ÑãÖÇä ßÑíã:ciao:

Argonaut
08-10-2005, 04:29 PM
JAVA UNLEASHED

Everything You Need To Know To Master Java!

Introduction



Nothing short of the World Wide Web itself has captured the attention of the Internet community as much as Java. Java, a Web programming technology, could forever alter the course of software development, especially in regard to the Internet. Java sports all features necessary for extending the Web in ways previously impossible. Java was designed with issues such as portability and reliability in mind. Java is an absolute essential for applications that are to run on the Internet. Java has stirred up so much excitement mainly because of what you can do with it on the Web. Java first introduced inline sound and animation in Web pages, and also added interactive Web pages, including games implemented in Java. Because of Java, the entire concept of the Web and what it can do is being redefined. In Java Unleashed, you will learn what Java is, what it can do, and how to use it. Many aspects of Java programming are covered, with lots of example source code to try out in your own Web pages. You can find out the difference between Java and C++, and what Java class libraries are. Aside from programming, there are plenty of other areas covered that you may need and will surely find interesting. For example, Java networking definitely delivers. You can write your own chat program, and learn how to load a URL from a Java applet. The Java networking support will not disappoint you! You can learn about Netscape 2.0's Java-related capabilities, security issues and master Java language fundamentals. You will also learn how to create games to be played on the Internet, and extend Java with content and protocol handlers. Ready to add spice to your Web site? With Java applets, the most popular usage of the Java programming language, you can learn how to write and design applets with the Java applet package. When learning Java, you will be able to exploit the full power and functionality of JavaScript, which can enhance your Web site even more. Also, the impact of Java on various real-world issues is discussed, along with what the future holds for Java and the Web in general. Copyright (c) 1996 by Sams.net Publishing FIRST EDITION International Standard Book Number: 1-57521-049-5

Trademarks All terms mentioned in this book that are known to be trademarks or service marks have been appropriately capitalized. Sams.net Publishing cannot attest to the accuracy of this information. Use of a term in this book should not be regarded as affecting the validity of any trademark or service mark. Java is a trademark of Sun Microsystems, Inc.

Argonaut
08-10-2005, 04:34 PM
Chapter 1

[/url] ("]Java Makes Executable Content Possible

By the mid 1990s, ("]hypertext, users of the Web were able to select and view information from all over the world. However, while this system of hypertext gave users a high degree of selectivity over the information they chose to view, their level of interactivity with that information was low. Hypermedia had opened up many options for new kinds of sensory input a user might receive, including access to graphics, text, or even videos. However, the Web lacked true interactivity—real-time, dynamic, and visual interaction between the user and application.

Java brings this missing interactivity to the Web. With a Java-enabled Web browser, you can encounter animations and interactive applications. Java programmers can make customized media formats and information protocols that can be displayed in any Java-enabled browser. Java’s features enrich the communication, information, and interaction on the Web by enabling users to distribute executable content—rather than just HTML pages and multimedia files—to users. This ability to distribute executable content is the power of Java.

With origins in Sun Microsystem’s work to create a programming language to create software that can run on many different kinds of devices, Java evolved into a language for distributing executable content through the Web. Today, Java brings new interest to Web pages through applications that can all give the user immediate feedback and accept user input continuously through mouse or keyboard entries.

In this chapter, I first present a description and definition of Java and explore what Java brings to Web communication. Then I present a brief “armchair” tour of some examples of what Java can do. If you want to go directly to programming in Java, see the other parts of this book. Otherwise, read this chapter and the others in this part for a survey of the potential of Java and the basics of its technical organization. These chapters should prepare you for the more detailed look at existing Java programming in the rest of this book.

[url=")

Java animates pages on the Web and makes interactive and specialized applications possible. Figure 1.1 illustrates how the software used with the Web can support a variety of communication. With hypertext, the basis for information organization on the Web, you can select what information to view. Programmers can create some ("]file:///D:/Java%20Unleashed/figicon.gif[/img] FIGURE 1.1.

("]interactivity through gateway programs that use files of hypertext on the Web as interfaces. When you use a Web page with such a gateway program, you can access databases or receive a customized response based on a query.

Java adds to these communication possibilities by making it possible to distribute executable content. This gives Web information providers the opportunity to create a hypertext page that engages users in continuous, real-time, and complex interaction. This executable content is literally downloaded to the user’s computer. Once downloaded, the executable content might run an animation, perform computation, or guide a user through more information at remote network sites.

The Web’s software supports selectivity, display, computation, and interactivity.[/size]

A METAPHOR FOR JAVA One metaphor for hypertext is that it offers a visually static page of information (which can include text, graphics, sound, and video). The ("]hypertext page can also have “depth” where it contains hyperlinks connecting to other documents or resources. Java transforms this static page metaphor into a more dynamic one. The information on a Java page on the Web does not have to be visually static or limited to a pre-defined set of ways to interact with users. Users encountering Java programs can take part in a wider variety of interactive behavior, limited only by the imagination and skill of the Java programmer. Java thus transforms a hypertext page into a stage, complete with the chance for actors and players to appear and things to happen. And, instead of the user being in the audience, a user of a Java-enabled Web browser is actively a part of the activity on this stage, changing what transpires and reacting to it, and shaping the information content delivered on the Web.

Java thus brings Web pages alive through animation and a higher degree of interaction than what is possible through gateway programming alone.

JAVA’S HOMESun Microsystems, the developers of Java, provide a one-stop collection of information about Java on the Web at [u]http://java.sun.com/ ("][url="). This site includes a full range of the latest information on Java and Java-enabled browsers. Links from this site take you to detailed announcements, release information, documentation, and links to Java demonstrations.

Argonaut
08-10-2005, 04:36 PM
What Is Java?

The name Java [/url]Sun Microsystems and refers to the programming language developed by Sun and released in public alpha and beta versions in 1995. Java is used to create executable content that can be distributed through networks. Used generically, the name Java refers to a set of software tools for creating and implementing executable content using the Java programming language.

In order for users to use Java content, they must have a key piece of Java software—the ("]is a trademark of ("][url=")Java content on the Web, a user’s Web browser must be Java-enabled. In the alpha release of Java, available during the spring and summer of 1995, only the special browser called ("] ("]HotJava could interpret programs created by the Java language. HotJava was developed by Sun to showcase the capabilities of the Java programming language. Other brands of Web browsers have since been upgraded to be able to interpret Java programs, most notably, the [url=")Netscape Navigator Web browser.

A Java-enabled Web browser has the same capabilities as a non-Java Web browser, but additionally has the capability to interpret and display Java’s executable content. A Web browser that is not Java-enabled does not recognize Java and thus can’t display the Java executable content. Thus, Java-enabled browsers “see” the Web plus more—applications written using Java.

As described in the section on Java’s origins (Java Origins and Direction), Java capability is expected to be integrated into future versions of other Web browsers and network tools.

You can download the ("]Java Developer’s Kit (JDK), which contains Java language development tools, from Sun Microsystems. Chapter 2 describes this software as well as Java’s technical design in more detail.

What Is Executable Content?

Executable content is a ("][url=") ("]general term that characterizes the important difference between the content that a Java-enabled Web browser downloads and the content a non–Java-enabled browser can download. Simply put: In aMultipurpose Internet Mail Extensions (MIME) specifications, whichinclude a variety of multimedia document formats. This content, once downloaded by the user’s browser, is displayed in the browser. The browser may employ a helper application (such as in displaying images, sound, and video). The overall pattern for the use of this content is user choice, browser download, and browser display.

A Java-enabled browser also follows this pattern, but adds another crucial step. First, the Java-enabled browser, following requests by the user, downloads content defined by MIME specifications and displays it. However, a Java-enabled browser recognizes a special hypertext tag called APPLET. When downloading a Web page containing an APPLET tag, ("][url=")bytecodes. The Java-enabled browser interprets these bytecodes and runs them as an executable program on the user’s host. The resulting execution on the user’s host then drives the animation, interaction, or further communication. This execution of content on the user’s host is what sets Java content apart from the hypertext and other multimedia content of the Web.

The process of using executable content in a Java-enabled browser, for the user, is seamless. The downloading and start of the execution of content happens automatically. The user does not specifically have to request this content or start its execution. And, as will be explored more in the next chapter, this executable content is platform-independent: Java programmers need not create separate versions of the applets for different computer platforms, as long as the user has a Java interpreter (or Java-enabled browser) installed on his or her computer.

Thus, when surfing the Web with a Java-enabled browser, you might find not only all the hypertext content that the pre-Java age Web offered, but also animated, executable, and distributed content. Moreover, this executable content can include instructions for handling new forms of media and new information protocols.

How Java Changes the Web

Java profoundly changes the ("]the Java-enabled browser knows that a special kind of Java program called an applet is associated with that Web page. The browser then downloads another file of information, as named in an attribute of the APPLET tag, that describes the execution of that applet. This file of information is written in what are called interactivity and ("]Web because it brings a richness of interactivity and information delivery not possible using previous Web software systems. Java makes it possible for programmers to create software that can be distributed across networks and run on many different kinds of computers. The resulting executable content shifts the site of activity from the Web server to the Web client (the Java-enabled browser).

Figure 1.2 illustrates the technical difference between Java’s [url=")hypertext selectivity and [url=""] ("")gateway programming. The figure illustrates how gateway programming allows for computation and response but not in realtime. Java’s interactivity is much richer and is centered on the client rather than the server.

Argonaut
08-10-2005, 04:38 PM
[/url] ("]Java Origins and Direction

According ("]http://www.sun.com/sunworldonline/swol-07-1995/swol-07-java.html ("]SunWorld Online ( ("] Gosling even as the World Wide Web was being developed in Switzerland in 1991. The goal of this early development team was to develop consumer electronic products that could be simple and bug-free. What was needed was a way to createplatform-independent code and thus allow the software to run on any [url=""] ("]Oak (later renamed Java). By the fall of 1992, the team had created a project named [url=""] ("][url=""] ("]WebRunner, was written using Java and completed early in the fall of 1994. Executives at Sun Microsystems were impressed and saw the technology and commercial possibilities that could result from a new browser: tools, servers, and development environments.

On May 23, 1995, Sun Microsystems, Inc. formally announced Java and HotJava at SunWorld ’95 in San Francisco. Throughout the summer of 1995, interest in Java grew rapidly. The first wave of developers downloaded and used the alpha release of Java and the HotJava browser and experimented with this new software. The alpha release of Java was the basis for the entries in the first Java contest, with prizes awarded in September 1995. In late September, the pre-beta release of Java was announced. The pre-beta release was Sun’s move toward stabilizingthe language so that programmers could begin investing their efforts into more significantapplications.

By the end of 1995, Java had gained the attention of the major players in the online world. Sun licensed Java to Netscape Communications, Inc. for use in its very popular Netscape Navigator browser. In addition, other major computer software and network players announced products involving Java, including Borland, Mitsubishi Electronics, Dimension X, Adobe, Lotus, IBM, Macromedia, Natural Intelligence, Oracle, and Spyglass. Most dramatic was Microsoft’s announcement on December 7, 1995 of their intent to license Java. Microsoft’s announcement was particularly dramatic, because, during the summer and fall of 1995, Bill Gates, chairman and CEO of Microsoft, had downplayed Java’s role, calling Java “just another language.” However, Microsoft’s year-end licensing announcement clearly showed that Microsoft considers Java part of an overall Internet strategy.

Java’s Current Status and Timeline

A JAVA ONLINE BIBLIOGRAPHY</FONT>You can connect to a bibliography of online articles and key press releases tracing the history and current status of Java at [url="http://www.december.com/works/java/bib.html"][u]http://www.december.com/works/java/bib.html ("] “Internet PC” (IPC), a device which would provide an inexpensive view into the Internet. An IPC would have minimal hardware and software in it and be specifically dedicated to supporting a Java-enabled Web browser, which could be continuously upgraded. Potentially, such an IPC could be a cheap, efficient way to encounter Web information. Widespread use of such IPCs could overthrow years of “API lock” on personal computing communications based on the Microsoft Windows/Intel (“Wintel”) standards.

For the most current information on Java’s software releases for different platforms, see Sun Microsystem’s Java site: [u]http://java.sun.com/ ("]http://www.december.com/works/java/info.html (http://www.december.com/works/java/info.html).

Argonaut
08-10-2005, 04:40 PM
Java Future Possibilities

Java technology is not necessarily limited only to the Web. Java technology can be deployed in embedded systems, such as handheld devices, telephones, and VCRs. Mitsubishi Electronics has been working to use Java technology in these devices.

The association of Netscape and Sun Microsystems that brought Java technology into Netscape browsers by late 1995 will be sure to have significance for Net software. With Netscape Navigator’s widespread installed base, the use of Java in applications could rapidly increase. Therefore, other Web browser manufacturers might be compelled to also license Java in order to keep pace with the information environment on the Web.

The market for third-party object and tool libraries for Java is also a potential bonanza. Software layers on top of “raw” Java will enable developers to use more sophisticated tools to create applications and users to more easily build and incorporate Java applets in their Web pages. Chapter 2 describes how Java’s nature as an object-oriented programming language makes it particularly amenable for creating reusable, extensible software components.

By integrating Java with [/url] ("] ("]http://www.vrml.org/[/u] (http://www.vrml.org/)), developers can create virtual worlds that are not only three-dimensional but also animated and interactive. ("] http://www.dnx.com[/u] ("]Dimension X (Iced Java which has the potential to take Web communication and interaction to an even richer level.

Illustrations of Java’s Potential ("]

Java is a new programming language, and programmers outside of Sun Microsystems have just begun to explore its potential. Since the public release of Java in its alpha and beta versions, however, many good examples of Java have already been developed. The rest of this chapter shows you examples of the kinds of functionality that Java can support, with an emphasis on the unique way Java enables the distribution of animated, executable content. Information on developing applications which can achieve this potential of Java is in later parts of this book.

ALPHA, BETA, JAVA</FONT>The initial, or alpha, release of Java is incompatible with later releases: the alpha bytecodes won’t run in beta or later Java-enabled browsers; also, the alpha Java language used an HTML APP tag rather than the APPLET tag of the beta and later versions of Java. The development sections of this book focus on the beta version of Java which is upward compatible with later versions of Java.

Animation

Java’s ("][/color][/size][/u]

Tumbling Duke, mascot of Java. (Courtesy of Arthur van Hoff, Sun Microsystems)

Animation isn’t limited to cartoon figures, however. Pages can have animated logos or text that moves or shimmers across the screen. Java animations also need not just be a decorative pre-generated figure, but can be a graphic that is generated based on computation. Figure 1.4 shows a bar chart applet.

file:///D:/Java%20Unleashed/figicon.gif FIGURE 1.4.



("] applications put animated figures on Web pages. Figure 1.3 shows a still image of Duke, the mascot of Java, who tumbles across a Web page displayed in the browser. Duke tumbles across the page, cycling through a set of graphic images that loop while the user has this page loaded.

<A href="file:///D:/Java%20Unleashed/049-5g/01/01jun03.gif">file:///D:/Java%20Unleashed/figicon.gif FIGURE 1.3. [url=")A bar chart applet. (Courtesy of Sun Microsystems)

Interaction

While the ("] [color=#3e09f7][b]FIGURE 1.5.



("]chemical modeling is more complicated. To the user, however, the chemical models seem three-dimensional, giving an insight into the nature of the atomic structure of these elements as no book could.

Three-dimensional chemical models. (Courtesy of Sun Microsystems)

The chemical models in Figure 1.5 respond to user clicks of the mouse. Another variation on this animation involves providing the user with a way to interact with an interface to get feedback. The “impressionist” drawing canvas in Figure 1.6 is an excellent example of this. Paul ("]http://reality.sgi.com/grafica/impression/imppaint.html (http://reality.sgi.com/grafica/impression/imppaint.html). He originally developed this technique for creating this kind of graphic in 1988 for a Silicon Graphics IRIS workstation. Later patented, this technique drives his Java applet. The result is that you can draw using various size brushes on a canvas and reveal one of several pictures.

file:///D:/Java%20Unleashed/figicon.gif FIGURE 1.6.



(file:///D:/Java%20Unleashed/049-5g/01/01jun06.gif)Interactive impressionist drawing. (Courtesy of Paul Haeberli at Silicon Graphics)

Another variation on interactivity is ("][url=")real-time interactivity. Figure 1.7 shows an interactive application that involves moving graphics that the user manipulates. This is the game of [url=""] ("")Tetris, in which you can try to line up the falling tile shapes to completely fill the rectangle. Using designated keys for playing, you interact with the interface to steer the falling shapes. This Tetris implementation demonstrates the possibilities for arcade-like games using Java technology.

Argonaut
08-10-2005, 04:42 PM
Interactivity and Computation

The Tetris game described in the previous section, for example, demonstrates how interactivity and animation can work together. Both applets customized their animated output based on user input, so both applets were actually performing computation. However, an example that shows this computational capability in more concrete terms is in Figure 1.8, a simple spreadsheet.

This file:///D:/Java%20Unleashed/figicon.gif FIGURE 1.8.



("][/url]spreadsheet works in much the same manner as the other applets, but emphasizes that the computational possibilities can enable users to have an environment in which to work instead of just a puzzle to solve. The spreadsheet shown enables you to change the contents of any of the 24 cells (A1 through D6) by replacing its label, value, or formula. (Not all cells are shown in the figure.) This is just like a real spreadsheet, which is more of an environment in which the user can work than a fixed game such as the crossword puzzle. This subtle difference is a profound one: using Java, a user can obtain an entire environment for open-ended interaction rather than a fixed set of options for interaction—opening up the Web page into a Web stage.

A simple spreadsheet. (Courtesy of Sami Shaio, Sun Microsystems)[/size]



This ballistic simulator shown in Figure 1.9 (http://jersey.uoregon.edu/vlab/Cannon2/ (http://jersey.uoregon.edu/vlab/Cannon2/)) enables you to explore how a canon operates. You can adjust the muzzle angle and velocity, gravitational field strength, wind speed, and the density of the projectile. The purpose of this applet is to helpstudents understand the relation between muzzle velocity and gravitational potential and drag.

file:///D:/Java%20Unleashed/figicon.gif FIGURE 1.9.



("]A virtual canon. (Coding by Sean Russell, Software Manager, University of Oregon; Graphic images by Amy Hulse)[/size]

Just as the user can download a canon, so too can a user download a “kit” for doing almost anything. Patrick A. ("]http://www.geom.umn.edu/~worfolk/apps/Lorenz/[/u] (http://www.geom.umn.edu/~worfolk/apps/Lorenz/)). The user can see the results offile:///D:/Java%20Unleashed/figicon.gif FIGURE 1.10.



("] the numerical integration (the equations in the bottom of Figure 1.10) as well as graphical representations of their numerical solution.

Numerical Simulation of the Lorenz Equations. (Courtesy of The Geometry Center, University of Minnesota)[/size]

Communication

The preceding ("] ("]Burchard has created a system for users to share “chats” over the Web using a Java applet http://www.cs.princeton.edu/~burchard/www/interactive/chat/express.html[/u] (http://www.cs.princeton.edu/~burchard/www/interactive/chat/express.html)).

Not only do users see each other’s text, but they can follow each other on tours of the Web. Figure 1.11 shows this “chat touring” applet in action.

file:///D:/Java%20Unleashed/figicon.gif FIGURE 1.11 (file:///D:/Java%20Unleashed/049-5g/01/01jun11.gif)

Of course, communication takes place all the time on nearly all Web pages through text or other media. But a Java-enabled browser can also display multimedia. Figure 1.12 illustrates a player piano applet—you see the keyboard play and hear the music at the same time.

file:///D:/Java%20Unleashed/figicon.gif FIGURE 1.12 (file:///D:/Java%20Unleashed/049-5g/01/01jun12.gif)

Java can also be used to support mass communication in new ways. The ("] FIGURE 1.13[/u] ("]Nando Times is a Web-based news service that has been very innovative in news delivery on the Web. Using Java, this news agency now provides a tickertape of headlines across its front page. The text under the Nando banner in Figure 1.13 scrolls continuously to show the world, national, sports, and political top stories at the moment. The four pictures under the labels for these categories also change, giving a “slide show” that is very effective in displaying new information without requiring the user to select it for viewing. This transforms the Web into something people can watch to get new information.

("]Sports Network (www.sportsnetwork.com). This provides you with a life sportswire pop-up window. You can follow NFL and NHL action live, as it happens. As the scores change, this display changes, so that the sports-minded can keep up with the current games and scores. Like the Nando Times news feed, this sports feed changes the Web into something to watch in addition to something to interact with.

Applications and Handlers

In addition to applets FIGURE 1.14 (file:///D:/Java%20Unleashed/049-5g/01/01jun14.gif)

Another kind of software program available with Java is a ("]handler. A [url=")protocol handler enables a Java programmer to specify how a Java browser should interpret a particular type of protocol. The HotJava browser knows how to interpret the Internet protocols such as HTTP, FTP, Gopher, and others because of the browser distribution code. But if new protocols are invented, a Java programmer can specify how they should be handled by creating a protocol handler.

Another type of handler is a [url=""] ("")content handler. This handler translates a particular specification for a file type based on Multipurpose Internet Mail Extensions (MIME). This content handler will specify how the HotJava browser should handle a particular type of file type. By creating a specification in a content handler, all Java-enabled browsers will be able to view this special format.

The handlers and applications that Java makes possible have the potential to dramatically extend what can be browsed on the Web. No longer will information developers have to be concerned about making sure their users have the proper software to view a particular type of file or handle a new kind of protocol. The protocol and content handlers, like the executable content Java makes possible as applets, can be distributed as needed to requesting Java-enabled browsers.

Argonaut
08-10-2005, 04:43 PM
[/url]illustrate only some of the potential of Java. A few of these examples are “toy” demonstrations meant to show the possibilities of Java. What kind of communication might Java foster? The Nando Times example shows an innovative application for providing information in a way that lets you to sit back and observe rather than selecting hypertext links.

Java opens up a new degree of interactivity and customizability of interaction for the Web. Earlier Web development techniques of creating pages and linking them together will still be necessary in a Java-flavored Web. However, Java creates possibilities for richer kinds of content to be developed. The user can interact with and change the appearance of a Web page along with the state of a database using a Java-enabled browser. Thus, Java profoundly changes the texture of the Web in the following ways:


Java creates places to stop on the paths of the Web: A well-done Java application on a single hypertext page can engage a user for a long time. Rather than just text, sound, images, or videos to observe, a Java page can offer a place to play, learn, or communicate and interact with others in a way that isn’t necessarily based on going somewhere else on the Web through hyperlinks. If the hypertext links of the Web are like paths, the Java pages are like the towns, villages, and cities to stop on these paths and do something other than just observe or “surf.”
Java increases the dynamism and competitiveness of the Web: Just as new browser technology prompted Web developers to create still more applications and pages to exploit these features, so too does Java technology promise a new round of content development on the Web.
Java enriches the interactivity of the Web: Java’s ("]What Java Might Make Possible

The previous examples [url=""] ("]interactivity is far richer, more immediate, and more transparent than the interactivity possible through gateway programming. Gateway programming still should have a role in Web applications, just as page design and multimedia presentation will still play a role. However, Java’s interactivity brings new possibilities of what can happen on the Web. With Java, transactions on the Web can be more customized, with immediate and ongoing feedback to the user.
Java transforms the Web into a software delivery system: Java’s essential design as a language to deliver [url=")executable content makes it possible for programmers to create software of any kind and deliver it to users of Java-enabled browsers. Rather than having to focus on the interface, the Java programmer focuses on the interaction desired and lets the built-in features of the graphics take care of the rest of the implementation. The result is that very simple programs like the drawing and spreadsheet applications can be created quickly and distributed worldwide.
The true potential of Java to transform the Web is still in its initial stages. New potential applications for commerce, information delivery, and user interaction still await the imagination and skill of future Java developers.

Summary ("")

Java is a programming language designed to deliver executable content over networks. A user or programmer should know what kinds of interaction Java can make possible and what its true potential can be: enlivening the Web, enriching the display of information in the form of animation and interactive applications.


Java enriches the interactivity possible on the Web. Rather than making just informational content possible, Java can support interactive content in the form of software that can be downloaded and run on any computer host with the Java interpretation environment installed.
Java developed from ideas about platform-independent executable code. Sun Microsystems researchers have developed Java to be a powerful programming and information delivery system for use with the Web.
Java makes animation, interaction, computation, distributed applications, and new forms of communication possible. Through protocol and content handlers, Java has the potential to make new formats and new protocols available for use on the Web.
Java transforms the Web into a software delivery system where users have things to do rather than just places to go. Java may change the surfing behavior of Web users into playing and learning behavior in new interactive environments.

Argonaut
08-10-2005, 04:44 PM
Chapter 2

A Hello to Java ("]Java’s Design Is Flexible and Dynamic[/url]

The Java programming language is uniquely suited for distributing executable content over networks. Java also offers a set of functions similar to many other programming languages. This chapter presents an overview of the technical design of Java. I begin with a minimal example of a “hello world” Java program. This should help you understand how Java and HTML connect. Using this information, you can then try out some of the Java programs shown in later parts of this book.

Java also has specialized characteristics. In the second part of this chapter, I discuss in more technical detail how Java supports executable, distributed applications.

hypertext markup language (HTML) associates a Java program called an applet to a page on the Web. Viewed through a Java-enabled Web browser, a page with a Java applet can come alive with animation or interaction.

Java’s Connection to the Web

As a language for ("]APPLET. Figure 2.1 summarizes this connection:


In response to a request from a user of a Web browser, a document on a Web server written in HTML is downloaded to the user’s browser.
If the HTML document contains an APPLET tag and the user’s Web browser is Java-enabled, the browser looks for the value of the Code attribute which identifies the Java bytecodes defining the applet.
The applet bytecodes are downloaded from the Web server (or possibly some other Web server or network site identified by attributes of the APPLET tag) and placed on the user’s host computer.
The user’s Java-enabled browser interprets these bytecodes and runs the applet in the user’s browser. The applet commonly will provide a visual indication that it is operating and possibly accept input from some combination of the user’s cursor position, mouse buttons, or keyboard. Once the applet is downloaded, it need not be downloaded again, even if the applet code defines repeated loops or other interaction. The user might use a downloaded applet several times over the course of an online session without any more network retrievals.
file:///D:/Java%20Unleashed/figicon.gif FIGURE 2.1.



("]Java’s connection to the Web through the APPLET tag.[/size]

A technical understanding of Java also requires a familiarity with ("]HTML. HTML is the markup language used to create the documents displayed in Web browsers. HTML is not a layout language for describing how a page of hypertext should look (although there are many features of HTML that can be used to manipulate a page’s appearance). Rather, HTML tags the structure of a document and the meaning of text, so that a browser can display it in a scheme based on that browser’s design and the user’s preferences for the font size, style, and other features.

An HTML document consists of text and tags that mark the structure of the document. Tags in an HTML HTML document:

<HTML><HEAD> <TITLE>Example HTML Document</TITLE></HEAD><BODY> <P> This is the body of the document. <OL> <LI>This is the first item in an ordered list. <LI>This is the second item. </OL></BODY></HTML>When a Web browser interprets these HTML tags and text, it displays the document without the brackets < and >. A text-only browser renders this simple HTML example as

Example HTML DocumentThis is the body of the document. 1. This is the first item in an ordered list. 2. This is the second item.The document [u]http://www.december.com/works/wdg/quickref.html ("]A Simple Java Program[/b]

The APPLET ("][url=") tag in an HTML document identifies the name of a Java program called an applet to be included in a Web page. The name of ("][url=") the applet is called its class name. This name is associated with the executable bytecodes that run the applet.

For example, the following HTML example demonstrates how you can include an applet in a Web document. If you want to test this, put the following lines in a file called HelloWorld.html:

<HTML><HEAD> <TITLE>HelloWorld</TITLE></HEAD><BODY> <P>”This is it!” <APPLET Code=”HelloWorld.class” Width=”600" Height=”300"> </APPLET></BODY></HTML>Note that there is an open APPLET tag, <APPLET>, and a close APPLET tag, </APPLET>. The ("]attributes shown here are Code, to identify the class file which contains the Java bytecodes and the Width and Height attributes, measured in pixels, to describe how much room should be reserved on the Web page for the applet.

Argonaut
08-10-2005, 04:46 PM
THE APPLET TAG SYNTAX</FONT>Java uses an APPLET tag to place [/url] ("]General Format[/color]

<APPLET Codebase = “path to directory containing class files” Code = “name of class file” Width = “width of applet in pixels” Height = “height of applet in pixels”> <PARAM Name=”parameter name” Value=”value of parameter”> <PARAM Name=”parameter name” Value=”value of parameter”></APPLET>The parameter values are given to the applet for use in its computations.

Here is a sample use of the APPLET tag:

<APPLET Codebase = “http://java.sun.com/applets/applets/TumblingDuke/” Code = “TumbleItem.class” Width = “400” Height = “95”> <PARAM Name=”maxwidth” Value = “100”> <PARAM Name=”nimgs” Value = “16”> <PARAM Name=”offset” Value = “-57”> <PARAM Name=”img” Value = “http://java.sun.com/applets/applets/TumblingDuke/&Acirc;images/tumble”></APPLET>

Of course, you need to create the Java source code for the applet named HelloWorld. You can find more details on programming in Java in Chapter 12, “Java Language Fundamentals.” For now, here is a minimal Java applet as a simple demonstration:

import java.awt.Graphics;/** A first hello. */public class HelloWorld extends java.applet.Applet { public void init() { resize(600, 300); } public void paint(Graphics context) { context.drawString(“Hello, world!”, 50, 100); }}THE HelloWorld JAVA SOURCE CODEThe ("]http://www.december.com/works/java.html[/u] ("]source code for HelloWorld is on the CD-ROM that accompanies this book. I also provide the source code for the HelloWorld and other introductory Java applets at my book support Web page for Presenting Java at
A file called HelloWorld.html. This is the hypertext markup language (HTML) source file.
A file called HelloWorld.java. This is the Java language source file.
A file called HelloWorld.class. This is the Java bytecode file.
[/list]Figure 2.2 summarizes the Java source code and compilation relationships.

If you have a Java-enabled browser, you can test this applet. Use the browser to open the file HelloWorld.html. Alternatively, you can also use the applet viewer supplied with the Java Developer’s Kit (JDK) to view applets without having to make an HTML page to reference them. Figure 2.3 shows what this example looks like in Netscape Navigator.

file:///D:/Java%20Unleashed/figicon.gif FIGURE 2.2.



(file:///D:/Java%20Unleashed/049-5g/02/02jun02.gif)Java source code and compilation relationships.

file:///D:/Java%20Unleashed/figicon.gif FIGURE 2.3.



(file:///D:/Java%20Unleashed/049-5g/02/02jun03.gif)Java browser display of the HelloWorldapplet.

("]Java Technical Overview

The preceding example ("]HotJava browser interprets the bytecodes for the particular architecture of the user. This is a key characteristic of Java’s technical design.

The Network Communication Support Ring Around Java

Java’s technicalCyberspace is the mental model people have for communicating or interacting online or through computers. Cyberspace activity includes variety of information, communication, and interaction. Cyberspace can be thought of as consisting of non-networked and networked regions. The networked region in cyberspace includes activity on connected local, regional, and global computer networks. The non-networked region might be standalone personal computer applications like word processors or CD-ROMs that contain no network references.
The Internet computer ("] characteristics also place it within the larger context of online communication. We can step back from the Java source and bytecode files and look at the “big picture” of how Java fits into cyberspace.

The operation of Java and Java-enabled browsers on the Web requires the interoperation of a variety of network systems. Of course, you don’t have to understand the interoperation of all of these systems to use Java or a Java-enabled browser. But, stepping back a bit from the applet-scale view of Java, we can look at its place in a “support ring” of networks and applications.

The goal of Java is to bring executable content to the Web. When installed, a Java-enabled browser can provide an interface to animated and interactive applications. To view and interact with these applications, you must have a computer with a Java-enabled browser installed. If you want to download content from all over the Web, of course you also must have an Internet connection.

Beginning with the widest context for the operation of the Java technology, let’s take a look at the systems necessary to support Java when delivering information globally (again, Java can be used on local networks not requiring the Internet, collapsing the set of support rings described here considerably):


[url=") known as a browser, is a software program that interprets and displays information disseminated using a variety of Internet information protocols. A Web browser is a user’s interface into the Web. A pre-Java Age (Mosaic class) browser usually operates in conjunction with a variety of helper applications to display multimedia. A Java-enabled browser can dynamically learn new protocols and media content types, so that it need not rely on these helper applications. However, a Netscape 2.0 browser, while Java-enabled, still makes use of helper applications, because the entire content of the Web isn’t Java-ized.
HTML ("]network serves as a vehicle for data communication for many information dissemination protocols. Through gateways, many other networks in cyberspace can exchange data with the Internet. Because of this and also because of the large amount of information available on it, the Internet serves as a common ground for the networked region of cyberspace.
The Web is an application that relies on a client/server model for data communication for distributing hypermedia. While the Web can operate on local networks that have no connection to the Internet, the Web is popularly known for its collection of information that is available globally through the Internet.
A Web client,The HTML ("]A Java programmer prepares a file of human-readable Java source code. This ("]source code defines an applet, which is a class in the hierarchy of classes that make up the Java language.
A Java programmer compiles a Java source code and makes the resulting bytecodes available for use through a reference to them in an APPLET tag in an HTML document.
[url=")[url=""] ("")HotJava, or any other Java-enabled browser, downloads hypertext as well as the executable bytecodes of the applet. The browser interprets and displays the applet, allowing a user to view or interact with the applet.
Figure 2.4 summarizes the support rings for Java as it is used for worldwide distribution of information.

Argonaut
08-10-2005, 04:47 PM
Again, you don’t have to know how to set up the entire range of networks, software, and equipment in Java’s “support ring.” All you need is to install a Java-enabled browser on your Internet-accessible system. From your point of view as a user, your main focus is your browser, or the interior fourth ring, of Figure 2.4. A Java programmer, in contrast, inhabits the seventh ring, and tries to meld the user’s experience of the Web’s hypertext with the specialized content Java makes possible.

You can use Figure 2.4 to help place yourself in cyberspace as you fulfill different roles as an information user or producer.

Characteristics of Java as a Programming Language

While users may want [/url] ("]http://java.sun.com/[/u] (http://java.sun.com/)), Java is a

“ …simple, object-oriented, distributed, interpreted, robust, secure, architecture neutral, portable, high-performance, multithreaded, and dynamic language.”

This characterization identifies the key technical features of Java as shown in the following sections.

Simple

The developers ("] ("]
Java does not support the struct, union, and pointer data types.
Java does not support typedef or #define.
Java differs in its handling of certain operators and does not permit operatoroverloading.
Java does not support multiple inheritance.
Java handles command-line arguments differently than C or C++.
Java has a String class as part of the java.lang package. This differs from the null-terminated array of characters as used in C and C++.
Java has an automatic system for allocating and freeing memory (garbage collection), so it is unnecessary to use memory allocation and de-allocation functions as in C and C++.
[/list]Object-Oriented

Like C++, ("]Distributed[/b]

Unlike the ("]Interpreted[/b]

When the ("]Robust[/b]

Robust ("]software doesn’t “break” easily because of programming bugs or logic errors in it. A programming language that encourages robust software often places more restrictions on the programmer when he or she is writing the source code. These restrictions include those on data types and the use of pointers. The C programming language is notoriously lax in its checking of compatible data types during compilation and runtime. C++ was designed to be more strongly typed than C; however, C++ retains some of C’s approach toward typing. In Java, typing is more rigorous: a programmer cannot turn an arbitrary integer into a pointer by casting, for example. Also, Java does not support pointer arithmetic but has arrays instead. These simplifications eliminate some of the “tricks” that C programmers could use to access arbitrary areas of memory. In particular, Java does not allow the programmer to overwrite memory and corrupt other data through pointers. In contrast, a C programmer often can accidentally (or deliberately) overwrite or corrupt data.

Secure

Because ("] Java works in networked environments, the issue of security is one that should be of concern to developers. Plans are in the works for Java to use public-key encryption techniques to authenticate data. In its present form, Java puts limits on pointers so that developers cannot forge access to memory where not permitted. These aspects of Java enable a more secure software environment. The last section of this chapter outlines the layers of Java’s security in more detail.

Architecture Neutral

The Java [url=") ("]compiler creates bytecodes that are sent to the requesting browser and interpreted on the browser’s host machine, which has the Java interpreter or a Java-enabled browser installed.

Portable

The quality ("]of being architecture neutral allows for a great deal of portability. However, another aspect of portability is how the hardware interprets arithmetic operations. In C and C++, source code may run slightly differently on different hardware platforms because of how these platforms implement arithmetic operations. In Java, this has been simplified. An integer type in Java, int, is a signed, two’s complement 32-bit integer. A real number, float, is always a 32-bit floating-point number defined by the IEEE 754 standard. These consistencies make it possible to have the assurance that any result on one computer with Java can be replicated on another.

High-Performance

Although Java[url=") ("] bytecodes are interpreted, the performance sometimes isn’t as fast as direct compilation and execution on a particular hardware platform. Java compilation includes an option to translate the bytecodes into machine code for a particular hardware platform. This can give the same efficiency as a traditional compile and load process. According to Sun Microsystems testing, performance of this bytecode to machine code translation is “almost indistinguishable” from direct compilation from C or C++ programs.

Multithreaded

Java is a [url=") ("]language that can be used to create applications in which several things happen at once. Based on a system of routines that allow for multiple “threads” of events based on C. A. R. Hoare’s monitor and condition paradigm, Java presents the programmer with a way to support real-time, interactive behavior in programs.

Dynamic

Unlike C++ code, which often requires complete recompilation if a parent class is changed, Java uses a method of interfaces to relieve this dependency. The result is that Java programs can allow for new methods and instance variables in objects in a library without affecting their dependent client objects.

Argonaut
08-10-2005, 04:48 PM
Java Software Components

Another aspect[/url] ("]http://java.sun.com/[/u] (http://java.sun.com/)) for complete details on obtaining the Java Developer’s Kit (JDK). Programmers need to learn the vocabulary of the pieces of the JDK as well as terms for what can be created with it.

Java Language Constructs

Java is the ("]
applications: Standalone programs written in Java and executed independently of a browser. This execution is done using the Java interpreter, java, included in the Java code distribution. The input and output of these applications need not be through the command line or text only. The HotJava browser itself is a Java application.
("]applets: Programs that are referenced in HTML pages through the APPLET tag and displayed in a Java-enabled browser. The simple “hello world” program shown at the start of this chapter is an applet.
("]protocol handlers: Programs that are loaded into the user’s HotJava browser and interpret a protocol. These protocols include standard ones such as HTTP orprogrammer-defined protocols.
native methods: Methods that are declared in a Java class but implemented in C. These native methods essentially allow a Java programmer to access C code from Java.
[/list]Java Distribution Software

The ("]
Java Compiler. This is the software used to translate the human-readable Java source code to machine-readable bytecodes. The Java compiler is invoked using javac command.
("]Java Applet Viewer. This lets you run and test applets without having to create an HTML page to refer to it. Note that the beta release of the JDK included an applet viewer instead of an updated HotJava browser.
Prototype Debugger. This is a command-line debugger that uses this API.
[/list]The Java Application Programming Interface (API)

The ("]Java Debugger API and
All packages. These include:
java.applet
java.awt
java.awt.image
java.awt.peer
java.io
java.lang
java.net
java.util
All classes in a package. At the package level, information available includes:
Interfaces
Classes
Exceptions
Documentation on each class. This includes:
Variables
Constructors
Methods

[/list]The Java Virtual Machine Specification

A document available from the Sun Microsystems Java site (http://java.sun.com/ (http://java.sun.com/)) called “The ("][url=")Java ("]Virtual Machine,’ specifies how the Java language is designed to exchange executable content across networks. The aim of this specification is to describe Java as a non-proprietary, open language that may be implemented by many companies and sold as a package.

The Java Virtual Machine specification describes in abstract terms how Java operates. This leaves the details of implementation up to the programmers who creates Java interpreters and compilers. The Java Virtual Machine specification also concretely defines the specific interchange format for Java code. This is called “The Java Security[/b]

Because a ("]HotJava browser downloads code across the network and then executes it on the user’s host, security is a major concern for Java-enabled browser users and Java programmers.

HotJava includes several layers of security, including the following:


The Java language itself includes tight restrictions on memory access very different from the memory model used in the C language. These restrictions include removal of pointer arithmetic and removal of illegal cast operators.
A bytecode verification routine in the Java interpreter verifies that bytecodes don’t violate any language constructs (which might happen if an altered Java compiler were used). This verification routine checks to make sure the code doesn’t forge pointers, access restricted memory, or access objects other than according to their definition. This check also ensures that method calls include the correct number of arguments of the right type, and that there are no stack overflows.
A verification of class name and access restrictions during loading.
An interface security system that enforces security policies at many levels.
At the file access level, if a bytecode attempts to access a file to which it has no permissions, a dialog box will pop up enabling the user to continue or stop the execution.
At the network level, future releases will have facilities to use public-key encryption and other cryptographic techniques to verify the source of the code and its integrity after having passed through the network. This encryption technology will be the key to secure financial transactions across the network.
At runtime, information about the origin of the bytecode can be used to decide what that code can do. The security mechanism can tell if a bytecode originated from inside a firewall or not. You can set a security policy that restricts code that you don’t trust.
[url=""]Summary ("][url=")

The Java programming language is uniquely designed to deliver executable content across networks. As a language, it flexibly offers features for programmers to create a variety of software. Java also assures interoperability among platforms as well as security:


The Java programming language works in conjunction with a special kind of browser and bytecode interpreter. Java can exist within the context of World Wide Web communication and therefore “sits on top of” a set of applications on networks for data communications to support information retrieval.
The Java language is object-oriented and specially designed to support distributed, executable applications.
In operation, the Java language compiler creates bytecodes that are downloaded across the network to a user’s computer. The user’s computer runs these bytecodes.
Components of Java software include the HotJava browser, the Java interpreter, the Java compiler, and tools for developing Java applications.
Java’s designs for security are tailored for distributing executable content on networks.

Argonaut
08-10-2005, 11:59 PM
Chapter 3

Overview of the Web ("]Java Transforms the World Wide Web[/url]

The World Wide Web has dramatically changed the online world and continues to grow in popularity. As a communication system, the Web can give information providers the ability to distribute and collect information globally and instantly. For users, the Web is a dynamic view into the works and ideas of millions of people and organizations worldwide. With origins in ideas about nonlinear thinking, the Web is an information integrator on the Internet and plays a major role in online cyberspace.

What Java brings to the Web is a new way of communicating. Instead of relying on the Web servers to provide information and functionality, Java’s executable content makes Java-enabled Web browsers “smart.”

This chapter briefly explores how Java transforms the World Wide Web. The Web supports a range of communication, information, and interaction using hypertext for organizing information. Multimedia used with hypertext, called hypermedia, can enrich the Web’s information. Special programming techniques used with the Web’s hypertext, such as gateway programming or languages such as Java or Virtual Reality Modeling Language, can expand the Web’s possibilities for interactivity, information delivery, and communication.

To learn Java’s power as it can be used for the global distribution of information, you should first understand what the Web is and the significance of Java’s changes to it. If you are a seasoned Web user, you probably have already realized from the previous two chapters how Java extends the Web’s potential; you might want to skip to Chapter 4 to begin looking at specifics. This chapter takes a close look at the Web and Java’s part in it.

[/b]

Vannevar Bush described a system for associatively linking information in his July 1945 article in The Atlantic Monthly, “As We May Think.” (This article is available on the Web at http://www.isg.sfu.ca/~duchier/misc/vbush/ ("]Wide Web was originally developed to meet the information needs of researchers in the high-energy physics community. Today, the World Wide Web offers a system for distributing hypermedia information locally or globally. Technically, the World Wide Web enables a seamless, global system of multimedia communication. This information is organized associatively and delivered according to user requests. This section briefly surveys the historical origins of the Web and how the confluence of ideas in network technology has reached fruition in the global Web of today. Java is just the latest installment of a series of innovations in hypertext and Web communication.

Ideas Leading to the Web[url=").)

The Origins of Hypertext

Bush called his system a memex (memory extension), and proposed it as a tool to help the human mind cope with information. Having observed that previous inventions had expanded human abilities for dealing with the physical world, Bush wanted his memex to expand human knowledge in a way that took advantage of the associative nature of human thought.

In 1965, ("]The Origins of the Web

Vannevar Bush’s and Ted Nelson’s ideas about information systems showed up in another project in the late 1980s. In March 1989, Tim [url=""] ("")Berners-Lee, a researcher at the Conseil European pour la Recherche Nucleaire (CERN) European Laboratory for Particle Physics in Geneva, Switzerland, proposed a hypertext system to enable efficient information-sharing for members of the high-energy physics community. Berners-Lee had a background in text processing, real-time software, and communications, and had previously developed a hypertext system he called “Enquire” in 1980. Berners-Lee’s 1989 proposal, called “HyperText and CERN,” circulated for comment. The following were important components of the proposal:


A user interface that would be consistent across all platforms and that would enable users to access information from many different computers
A scheme for this interface to access a variety of document types and information protocols
A provision for “universal access,” which would enable any user on the network to access any information
By late 1990, an operating prototype of the World Wide Web ran on a NeXT computer, and a line-mode user interface (called “WWW”) was completed. The essential pieces of the Web were in place, although not widely available for network use.

Throughout the early 1990s, interest in the Web grew and spread worldwide. In March 1991, the WWW interface was used on a local network, and by May of that year, it was made available on central CERN machines. On January 15, 1992, the WWW interface became publicly available from CERN, and the CERN team demonstrated the Web to researchers internationally throughout the rest of the year.

Argonaut
09-10-2005, 01:15 AM
Mosaic: The First “Killer” App

In 1993, interest [/url]in the Web grew very rapidly. A young undergraduate who was then at the University of Illinois at Urbana-Champaign named Marc ("]National Center for Supercomputing Applications (NCSA), and lead a team that developed a browser for the Web called Mosaic. The group released an alpha version of Mosaic for the X Window System in February 1993 that was among the first crop of graphical interfaces to the Web. Mosaic, with its fresh look and graphical interface presenting the Web using a point-and-click design, fueled great interest in the Web and online information. By the end of 1993, attendees at the Internet World conference and exposition in New York City were eager to learn about graphical interfaces to the Web. The New York Times hailed Mosaic as the Internet’s “killer application.”

In 1994, more commercial players got into the Web game. Companies announced commercial versions of Web browser software, including Spry, Inc. Marc Andreessen and colleagues left NCSA in March to form, with Jim Clark (former chairman of Silicon Graphics), a company that later became known as Netscape Communications Corporation ( http://home.netscape.com/ ("] ("]World Wide Web Consortium, or W3C.

The Web Today

Today, the W3C ([url="http://www.w3.org/hypertext/WWW/Consortium/"][u] http://www.w3.org/hypertext/WWW/Consortium/ ("]Laboratory for Computer Science (LCS) at MIT collaborating with CERN ([u] http://www.cern.ch/ ("]Institut National de Recherche en Informatique et en Automatique (INRIA), a French research institute in computer science ([u]http://www.inria.fr/ ("] rapid growth and technical developments, the Web in 1996 retains the essential functional components it had in its 1990 form. Its popularity as a view of the Internet, however, has muddied popular understanding of it, because the Web is sometimes viewed as equivalent to the Internet and browsers are sometimes thought of as equivalent to the Web rather than a view into it. However, the Web is a very distinct system from the Internet and its browsers. First, the Web is not a network, but an application system (a set of software programs). Second, the World Wide Web can be deployed and used on many different kinds of networks (not necessarily just Internet networks) and it can even be used on no network at all or on a local network unconnected to any other.

A METAPHOR FOR THE WEB</FONT>Imagine a library in which all the spines of the books have been removed and the gravity in the building has been turned off, allowing the pages to float freely. If people could connect one page to another using very light threads taped to the pages, this would be similar to the way the Web’s hypertext is arranged. Pages free-float, so that users might encounter a work from any page within it, and reach other works by following the threads leading off a page.

Here is a more technical definition of the Web:

The World Wide Web is a hypertext information and communicationsystem popularly used on the Internet computer network with data communications operating according to a client/server model. Web clients (browsers) can access multiprotocol and hypermedia information.

Figure 3.1 summarizes the technical organization of the Web based on this definition.

file:///D:/Java%20Unleashed/figicon.gif[u] FIGURE 3.1.



("] Modeling Language (VRML) technologies placed the Web at the start of another cycle of rapid change and alteration. Java, in development for several years at Sun Microsystems, promises to make the Web far more interactive than ever before possible. (See Chapter 1, “Java Makes Executable Content Possible.”) Virtual Reality Modeling Language, which can allow developers to model three-dimensional scenes for delivery through special Web browsers, may also dramatically change what the Web has to offer. For more information on VRML, see Chapter 34, “VRML and Java.”

A Definition of the World Wide Web

Despite itsThe technical organization of the Web.[/size]

("]How Does Java Transform the Web?

Java changes the Web by bringing more “intelligence” to Web browsers. Although Java-enabled browsers have user interfaces that are much the same as many other Web browsers, their technical operation marks a significant shift in focus. Java’s executable content requires Java-enabled browsers to be smart; that is, they must be able to interpret executable content.

Java Supports Client-Side Interactivity

A client-server model[url=") for networked computer systems involves three components: the client, the server, and the network. A ("] ("]client is a software application that most often runs on the end-user’s computer host. A[url=") server is a software application that most often runs on the information provider’s computer host. Client software can be customized to the user’s hardware system and it acts as an interface from that system to information provided on the server. The user can initiate a request for information or action through the client software. This request travels over the network to the server. The server interprets the request and takes some desired action. This action might include a database lookup or a change in recorded database information. The results of the requested transaction (if any) are sent back to the client for display to the user. All client/server communication follows a set of rules, or ("]protocols, which are defined for the client/server system. Figure 3.2 summarizes these relationships, showing the flow of a request from a client to a server and the passing back of information from a server to a client. A client might access many servers employing the protocols both the server and client understand.

The distributed form of “request” and “serve” activities of the [url=")client/server model allows for many efficiencies. Because the client software interacts with the server according to a predefined protocol, the client software can be customized for the user’s particular computer host. (The server doesn’t have to worry about the hardware particularities of the client software.) Forexample, a Web client (a browser) can be developed for Macintosh computers that can access any Web server. This same Web server might be accessed by a Web browser written for a UNIX workstation running the X Window system. This makes it easier to develop information, because there is a clear demarcation of duties between the client and the server. Separate versions of the information need not be developed for any particular hardware platform, because the customizations necessary are written into client software for each platform. An analogy to the client/server model is the television broadcast system. A customer can buy any kind of television set (client) to view broadcasts from any over-the-air broadcast tower (server). Whether the user has a wristband TV or a projection screen TV, the set receives information from the broadcast station in a standard format and displays it appropriate to the user’s TV set. Separate TV programming need not be created for each kind of set, such as for color or black-and-white sets or different size sets. New television stations that are created will be able to send signals to all the currently in-use television sets.

Argonaut
09-10-2005, 01:21 AM
Java brings another dimension to the client/server model. Of course, Java does follow the basic model: A Java-enabled browser is a client that sends requests to Web servers for information. The Java-enabled browser interprets and displays the information sent from the server. This information includes both the hypertext as well as any bytecodes. These bytecodes are Java’s new twist on this model. The Java clients execute the content distributed from the servers. These bytecodes, as described in Chapter 2, are also architecture-neutral, just like the other information sent from the Web server.

Java Can Eliminate the Need for Helper Applications

Helper applications[/url] ("]Java and Communication Contexts on the Web ("]Java Adds to the Web’s Communication Contexts and Potential[/b]

The Java language and its browsers are part of the larger context for communication on the Web. Whether you write and distribute applets or just observe them, you take part in communication activities and traditions that have been developing on the Web for many years. Because Java is still so new, it has not yet appeared in all Web communication contexts. You’ll see more specific examples of Java used on the Web in later chapters of this book. This subsection briefly reviews the Web’s context and potential and how Java can be a part of it.

on the Web can take many forms and take place in many contexts. Genres, or traditional ways for communicating, have evolved on the Web. These genres correspond, in many ways, to offline human communication contexts:


Interpersonal: ("][url=") ("]The Web provides a way for users to create a home page, which typically conveys personal or professional information. The practice of creating a ("]home page emerged from the technical necessity of defining the “default” page that a Web browser displays when requesting information from a Web server when only the host name or a host and directory name is given. Home pages are thus traditionally the top-level page for a server, organization, or individual. When created by individuals, home pages often reveal detailed personal information about their authors and are often listed in directories of home pages. Also, individuals often follow the tradition of linking to colleagues’ or friends’ pages, creating electronic tribes. (Mathematically, these electronic tribes are defined by the cliques of home pages in the directed graph describing the Web.) When used interpersonally, personal home pages offer one-to-one communication, although the technical operation of all pages on the Web is one-to-many.
“applets”[url=") have not yet become prominent, but Java may enable individuals to create an executable “persona” with which other Web users can interact.
Group: As described in the interpersonal definition, cliques of personal pages can define a particular Web tribe or group. Similarly, people can form associations on the Web that are independent of geography and focused on interest in a common topic. Subject-tree breakdowns of information on the Web often evolve from collaborative linking and the development of resource lists and original material describing a subject. (See the following section’s discussion about locating subject-based information on the Web.) Similarly, groups of people associate on the Web based on common interests in communication.
Organizational: Many of the ("] ("] initial Web servers appearing on the Web belong to an organization, not individuals, so the home page for a server often identifies the institution or organization that owns the server. In this way, the genre of the [url=")Campus-Wide Information System (CWIS) evolved on Web servers of educational institutions. Similarly, commercial, governmental, and non-governmental organizations have followed the pattern established by CWISs to a large degree.
organizations now use Java in their Web pages to add interest and provide service to users. You will see examples of these pages in the next chapter.
Mass: Just as other media have been used for one-to-many dissemination of information (newspapers, radio, television), so too is the Web used for mass communication. Many commercial and non-commercial magazines and other publications are distributed through the Web. Moreover, as noted previously, all publicly available Web pages are potentially readable to anyone using the Web, and are thus potentially one-to-many communication.
is being used actively for mass communication, as shown in the example from the Nando Times in Chapter 1.
The key concept to understand is that the Web as a communication system can be flexibly used to communicate in a variety of ways. The classification of the communication (in the categories listed) depends on who is taking part in the communication. The exact classification of any expression on the Web can be blurred by the potentially global reach of any Web page. Thus, a personal home page may be used interpersonally, but it may be accessed far more times on the Web than a publication created and intended for mass consumption. Java’s capability for delivering interactive content adds new possibilities to each of these categories.

Java and the Web’s Potential ("] ("] system for communication that can be used in many contexts, ranging from individual communication on home pages through group communication and mass communication. In addition to these contexts, the Web also serves the following functions:


Information Delivery: A[url=") Web browser provides the user with a “viewer” to look into FTP space, Gopherspace, or hypertext information on the Web. The structure of hypertext enables user selectivity because of the many ways a user can choose to follow links in hypertext. Java adds the potential for new protocol handlers and content handlers.
Communication: People can use Web hypertext to create forums for sharing information, discussion, and helping group members make contact with each other. Java’s executable content introduces new forms of more interactive communication.
Interaction: Using ("] gateway programming, a Web developer can build some degree of interactivity into an application, providing the user with a way to receive customized information based on queries. Gateway programs can also enable a user to change or add to an information structure. A higher degree of interactivity is possible using Java because of its executable content. (Chapter 1 surveys Java’s unique contribution to the Web’s interactivity.)
Computation: Using ("][url=") ("]gateway programming, the Web can be used to provide an interface to other applications and programs for information processing. Based on user selections, a Web application can return a computed or customized result through a gateway program. Java programmers can create software for computation that can be distributed and executed.
Figure 3.3 shows the important distinction between ("]file:///D:/Java%20Unleashed/figicon.gif[/img][u] FIGURE 3.3.



(file:///D:/Java%20Unleashed/049-5g/03/03jun03.gif)Web selectivity and gateway interactivity. ("]

[url=")


The Web emerged from ideas about the associative, nonlinear organization of information. Java is another step in this evolution.
The Web is a hypertext information and communication system popularly used on the Internet in a client/server model, offering hypermedia display capabilities through appropriate browsers, some of which require helper applications.
Java-enabled browsers bring client-side interactivity and computation to the Web and can eliminate the need for helper applications.
Communication on the Web can assume many forms and take place in many contexts, ranging from individual communication to group and mass communication. Java can potentially augment the Web’s communication contexts and functions.

Argonaut
09-10-2005, 01:24 AM
Chapter 4

[/url] ("]Java Animates Web Pages

The Java language and Java-enabled browsers allow a more visually dynamic Web than possible before. Instead of hypertext pages containing only still images with helper applications to display video, Java Web pages can include animated graphics, text, and any moving visual elements a Java programmer can dream up.

This chapter surveys several Java applets that implement animation. In some cases, the chapter also includes key portions of the source code to demonstrate how these applets are made. If you want to understand these code portions in more detail, you can read more about Java programming basics in later parts of this book. If not, you can skip over the programming sections for now and return to them later. If you’d like to try out the applets described here, you should be familiar with Java’s connection with HTML as described in Chapter 2.

The purpose of this chapter is to familiarize you with the many types of animation possible using applets. If you are ready to place applets on your Web pages, this chapter will also be invaluable to you; it contains instructions for including some publicly available demonstration applets that you can customize and include on a hypertext page.

A TREASURE TROVE OF JAVA APPLETS</FONT>Visit the Gamelan web site at http://www.gamelan.com/ ("] ("]Applets in Motion[/b]

If you are a new user of a Java-enabled browser, you will immediately notice that some Java pages contain moving text, figures, and animations. These moving images are made possible by Java applets that implement Java’s Runnable interface. These applets don’t just display static text or graphics; they can execute their content continuously.

NervousText

One example of ("]Leach modified this applet so that it can display any programmer-defined string. Figure 4.1 shows both Wyszynski’s and David Leach’s NervousText applets on a Web page.

file:///D:/Java%20Unleashed/figicon.gif[u] FIGURE 4.1.



("]Wyszynski at the Center for Applied Large-Scale Computing. Wyszynski’s NervousText applet displays HotJava! in jostling on-screen letters. David The Nervous Text applet.[/size]

The NervousText applet is a good demonstration of how an applet can be included on any Web page, not just Web pages created by the applet’s developer. You are not limited to using only applets that you write. You can modify and use other developer’s applets from their sites, just as you link to hypertext pages at other sites. In fact, sharing applets across the Net is what Java’s capability to distribute executable content is all about.

You use the APPLET tag in HTML to place a publicly available applet in a Web page. The ("][url=")Codebase attribute identifies the path (using a Uniform Resource Locator, or URL) to a Java class anywhere on a publicly available server on the Net. The Code attribute then specifies the applet’s class name.

In general, the APPLET tag on an HTML page works like this:

<APPLET ("]beta version of a NervousText applet in your page like this:

<APPLET Codebase=”http://www.javasoft.com/JDK-prebeta1/applets/NervousText/” ("] Codebase = “path (URL) of directory containing class files” Code = “name of class file” Width = “width of applet in pixels” Height = “height of applet in pixels”> <PARAM Name=”parameter name” Value=”value of parameter”> <PARAM Name=”parameter name” Value=”value of parameter”></APPLET>In Figure 4.1, Leach’s modification uses a parameter called msg to set the value of the message that the applet displays.

You can include a [url=") Code=”NervousText.class” Width=”200" Height=”50"><PARAM Name = “text” Value=”HotJava-Beta”></APPLET>Note that the parameters use the PARAM tag in HTML, and that these parameter tags occur between the opening <APPLET> tag and closing </APPLET> tag. When the Java-enabled browser reads the PARAM attributes Name and Value, it passes these values to the applet.

USING JAVA APPLETS WITHOUT JAVA</FONT>You can put together a Web page that includes applets you didn’t create or at any location using the APPLET element. You don’t have to have a Java-enabled browser or the Java compiler to serve applets. You need only a reference to the class file of the applet. If you use applets that are at remote locations, you need to identify where on the Net the class file for the applet exists. To do so, use the Codebase attribute of the APPLET tag. Of course, users who do not have a Java-enabled browser cannot observe the applets.

If you use a remote applet in this way, consider downloading and serving a copy of the class file from your own site. Before taking this step, however, check with the information provider. And, of course, check out the applet’s behavior—it is executable content and runs on the computer of anyone requesting to view it.



David Leach’s modification of NervousText demonstrates the programming technique of passing values to the applet with parameters. In the Java applet code, David uses the getAttribute method to find out the value of the parameter msg passed from the HTML tags to the Java applet. Leach’s class definition includes the data string userString; and the init() method includes this line:

userString = getAttribute(“msg”);David uses this string in the paint() method to derive the characters that draw the applet. The trick of making the letters “nervous” is to vary their coordinates in the paint() method by using a random number generator for their X and Y coordinates:

x_coord = (int) (Math.random()*10+15*i);y_coord = (int) (Math.random()*10+36);TickerTape

Similar to the ("] ("][url=")Heinicke at HotWired and later modified by David ("] NervousText applet, another good demonstration of Java’s animation capabilities is TickerTape. This applet was originally developed by Sven [url=")Leach and John ("] Stone at the University of Missouri-Rolla. Many others have subsequently created variations on the TickerTape applet.

ARE JAVA USERS WASTING BANDWIDTH?After a Java[url=") applet’s bytecodes have been downloaded across the network, the user’s host is the processor that interpets them. The information provider’s host works only to distribute the bytecodes. Users of applets, therefore, might typically use far less bandwidth and far less time on the information provider’s computer than might Web surfers.

Also, class files containing bytecodes aren’t all that large. For example, the TickerTape applet (see Figure 4.2) is 3,186 bytes—easily smaller than many graphics files routinely downloaded from the HotWired server. Therefore, although users may see more action with applets, they are not necessarily using more bandwidth on the Web. Of course, leaving a browser on autopilot (such as in the Surf-o-Matic applet in Chapter 6) and walking away would cause a browser to use much bandwidth for downloading Web pages.

Information providers must be very careful about the size and processing power required by their applets; a CPU-intensive applet could bring the user’s computer to its knees.



Figure 4.2 shows the display of the TickerTape applet. The text in the lines scrolls continuously to the left; with the bottom ticker line moving very rapidly.

Argonaut
18-10-2005, 03:05 PM
ÇÚÊÐÑ ááÌãíÚ ÓæÝ ÇæÞÝ ßÊÇÈÉ ÇáãæÖæÚ áÈÚÖ ÇáæÞÊ
æÔßÑÇ
ÑãÖÇä ßÑíã

Argonaut
06-11-2005, 03:25 PM
file:///G:/Java%20Unleashed/figicon.gif FIGURE 4.2.



(file:///G:/Java%20Unleashed/049-5g/04/04jun02.gif)TickerTape applet eaxample.

The TickerTape applet uses a key programming trick to cause the letters to move. The code changes the X position of the string by an amount equal to the speed attribute prior to repainting the string in each cycle. Here’s the code to do this:

xpos -= speed;This line of code subtracts the value of speed from the current horizontal position of the string. The line is a quick way of writing the equivalent xpos = xpos - speed.

You can include a beta version of a more elaborate kind of ticker tape on a Web page like this:

<APPLETfile:///G:/Java%20Unleashed/figicon.gif FIGURE 4.3.



("][/url] Codebase = “http://www.digitalfocus.com/digitalfocus/faq/” Code = “reloadImage.class” Width=”600" Height=”70"> <PARAM Name=”rateOfMovement” Value=”2"> <PARAM Name=”sleepInterval” Value=”40"> <PARAM Name=”msgYLocation” Value=”12"> <PARAM Name=”passedMsg” Value=”Microsoft announces support for Java....Pigs were seen flying in Wyoming.....Martians endorse Java....java to be used in ballot boxes during next elections...”> <PARAM Name=”secondaryMsg” Value=”This just in......Netscape stock fell 20% after Microsoft announced i-net strategy....Next release of PowerBuilder to be java aware.....stay tuned...”></APPLET>Figure 4.3 shows a ticker tape with controls in action.

TickerTape applet with controls.[/size]

Fireworks

Another ("]variation on animation is to have graphics—rather than words only—flash across a page. Erik Wistrand has created an applet that transforms a Web page into a fireworks show (see Figure 4.4).

Similar to the TickerTape applet, you can include the Fireworks applet on a Web page, and you can control aspects of its appearance. The fireworks parameters set the number of rockets, points, size of points, duration of rockets, and even the constant of gravity.

This example sets a series of 50 rockets on a page (shown in Figure 4.4). The COLOR parameter uses hexadecimal (base 16) notation to describe the red, green, and blue values of the background image color.

file:///G:/Java%20Unleashed/figicon.gif FIGURE 4.4.



("]Fireworks applet example. [/size]

("]Animation

Not all animations involve moving text for aesthetic purposes. Other animations occur in instructional pages or as part of a user’s interaction with a Web page.

Juggling

Chris Seguin hashttp://www.acm.uiuc.edu/webmonkeys/juggling/ ("] created a juggling instructional page ( FIGURE 4.5. [/u]



(file:///G:/Java%20Unleashed/049-5g/04/04jun05.gif)The Java juggling page.

Drawing on Famous Pictures

Another variation ("] ("] FIGURE 4.6.



("]authorship and ownership that Java is opening on the Web. The author of the HTML page used an applet written by one person and an image created by another (and painted by still another—Leonardo da Vinci—long ago!) to create an environment for the user to alter the image. Who is the author of the resulting Web page and who finally owns the melded pieces? The talent of the Java programmer who made the applet? The Web page creator who put the pieces together? The browser manufacturer? The user who marks the image? The creator of the original image? da Vinci perhaps never would have imagined his painting would be transmitted around the world to be defaced with such glee. These questions raise just some of the legal and intellectual property issues involved in the use of Java and the Web.Marking on the world and the Mona Lisa. [/size]

A Live Feedback Imagemap

Still another ("]variation on Java graphics is to make images function just like HTML imagemaps; when the user clicks on certain parts of the image, other resources are retrieved. Jim ("] FIGURE 4.7.



(file:///G:/Java%20Unleashed/049-5g/04/04jun07.gif)Live feedback imagemap.

The Weather

While the images ("]Schwerzler, with weather data provided by University of Michigan, this Java applet lets you look at current weather conditions. Figure 4.8 shows the infrared satellite image for the United States. Other options are available, as shown in the figure, for obtaining other weather information.

file:///G:/Java%20Unleashed/figicon.gif FIGURE 4.8.



("]Steremberg and Christopher Weather map. [/size]

("]Commercial Sites Using Java

The demonstrations in this chapter show many of Java’s animation capabilities. But Java is more than a good show; it is also already at work on commercial Web sites. The Nando Times uses Java (refer back to Figure 1.13), as do George Coates Performance Works (refer back to Figure 1.10), ESPNET SportsZone (refer back to figure 1.14), Dimension X (http://www.dimensionx.com/ ("]http://www.hotwired.com/ (http://www.hotwired.com/)), and Sun Microsystems (http://www.sun.com/ (http://www.sun.com/)). Because Java brings so much visual interest to a Web page, it has great potential to draw attention, convey specialized information, and provide entertainment.

The Rolling Stones

The ("]Rolling Stones is a rock band that made a big splash on the http://www.eit.com/techinfo/mbone/mbone.html (http://www.eit.com/techinfo/mbone/mbone.html)) when they used it to simulcast part of their November 18, 1994, Dallas Cotton Bowl concert. Today, the Stones Web site ( http://www.stones.com/ (http://www.stones.com/)) is making a splash with Java.

The Stones site contains several interesting Java applets:


A Stones puzzle (http://www.stones.com/javapuzzle.html (http://www.stones.com/javapuzzle.html)) in which you slide the squares to make the famous tongue logo.
The Stones Java devil (http://www.stones.com/new.html (http://www.stones.com/new.html)), which animates the What’s New page for the site.
On the opening page of the Stones Voodoo Lounge (http://www.stones.com/javaindex.html (http://www.stones.com/javaindex.html)), animated flags move back and forth across the screen. This page is shown in Figure 4.9.
file:///G:/Java%20Unleashed/figicon.gif FIGURE 4.9.



(file:///G:/Java%20Unleashed/049-5g/04/04jun09.gif)The Rolling Stones Voodoo Lounge with Java.

Accurate Information System Consultant

Other commercial providers are using Java to add interest to their pages through animation. ("]http://accurate.com.my[/u] ("]Accurate Information Systems ( FIGURE 4.10.



(file:///G:/Java%20Unleashed/049-5g/04/04jun10.gif)Accurate Information System Consultant ticker tape greeting.

Summary ("")

You can use Java applets to place animations on Web pages. A user can set the parameters of an existing applet using the PARAM tag and bring a customized applet to his or her own Web page. Developers can create new applets to provide this functionality and make them available for users.


Text can shimmer using NervousText. Users can include this applet on their pages by using the APP element. By setting attributes of the applet, the user can control characteristics and behavior of the applet.
Text can scroll, as shown in the TickerTape applet.
Graphics can repeat a visual pattern, such as in the Fireworks applet.
Moving applets can teach a lesson, as in the Juggling applet.
The Magic applet enables users to alter graphics, allowing them to draw on an image.
A Java applet can perform the equivalent function of an HTML imagemap. Java’s advantage over traditional imagemaps is that Java imagemaps can give instant feedback regarding the user’s cursor position. Feedback does not need to be delayed until after a mouse click.
Many companies already use Java, including rock bands and computer companies, to provide interest on Web pages.

Argonaut
06-11-2005, 03:27 PM
Chapter 5

[/url] ("]Java makes web pages interactive

Java’s capability to animate Web pages is just the surface of what you might first notice when experiencing the Web through a Java-enabled browser. Not only do items move on Java Web pages, but applets can also accept user input through mouse clicks or keyboard entries. Java enables people to create Web pages with embedded puzzles, chemical models, games, and even communication systems. (For some illustrations of these, refer to the figures in Chapter 1.)

This chapter surveys some Java applets that provide interactivity. These Java applets range from simple games to instructional modules. Because, as of this writing, Java is still in its infancy, this chapter shows just a glimpse of the rich interactivity Java may bring to the Web.

This chapter also points out key programming tricks used in each of these applets. You can learn the basics of Java programming in Part III of this book.

WHAT IS INTERACTIVITY?The word interactivity interactive with the advent of the Java age.



[url=""]Interactive Games ("]

Games are a ("]Hang Duke

Patrick Chan at Sun Microsystems developed an applet called ("]file:///G:/Java%20Unleashed/figicon.gif[/img] FIGURE 5.1.



("]Hang Duke; the applet has been distributed with the Java browser as a demonstration. Figure 5.1 shows Duke, the mascot of Java. Notice that the user couldn’t guess the word; consequently, Duke is in an advanced hanging stage.

The Hang Duke game.[/size] The applet accepts input from the keyboard and displays correct letters in the appropriate slots in the word; each incorrect letter appears near the top of the gallows, and for each wrong letter, another part of Duke’s form is drawn.

The Hang Duke applet demonstrates how the simple metaphor of pencil-and-paper game translates easily to the Web with Java.

Hang Duke is a runnable applet. A key part of its source code accepts letters from the user through a method that detects key presses:

public void keyDown(int keyPressed)The parameter keyPressed is an integer representing a character. This code can be changed to a character and placed in a string expression by casting, like this: (char)keyPressed.

3-D Tennis

Eiji Ito has ("] created a simulation of tennis using a Java applet. By using your mouse to move your “racket” in a three-dimensional representation of a room, you can play tennis by blocking a ball. This applet is at <A href="http://www.sfc.keio.ac.jp/~t93034ei/ja1.html"">http://www.sfc.keio.ac.jp/~t93034ei/ja1.html.

Figure 5.2 shows the tennis game in action. The bar at the right keeps track of the times that the player misses the ball, growing smaller until the game is over.

<A href="file:///G:/Java%20Unleashed/049-5g/05/05jun02.gif">file:///G:/Java%20Unleashed/figicon.gif FIGURE 5.2.





3-D Tennis implemented in Java. <A id=I17 name=I17>Educational Applications

The Java <A id=I18 name=I18><A id=I19 name=I19><A id=I20 name=I20>game applets described so far in this chapter are innovative in that they use Java technology to enable users to interact with Web pages. This interactivity can also be put to a more exciting use: education. Educators have been adopting the Web for several years now for course support webs, information about their schools, and even instructional modules. However, the Web’s static text, its relatively low level of interactivity, and its limited capabilities for multimedia, have made it useful for information delivery but not as amenable to creating truly innovative, engaging applications. This section highlights some early Java applications that highlight its potential for education.

Fractal Figures

Fractals<A id=I21 name=I21><A id=I22 name=I22><A id=I23 name=I23><A id=I24 name=I24> are geometric shapes whose individual parts resemble the whole shape. Fractals can be generated by starting from a basic shape, and then changing the shape based on patterns echoing the structure of the overall shape. Snowflakes are like fractals: their forms at the lowest level of detail reflect a crystalline pattern similar to the whole shape. Because fractals are so hard to explain in words, what a better candidate for a Java application?<A id=I25 name=I25>

Jim Graham at Sun Microsystems has created a Java applet that shows an algorithm that generates a fractal. (Check out <A href="http://java.sun.com/applets/applets/fractal/index.html">http://java.sun.com/applets/applets/fractal/index.html.) Figures 5.3, 5.4, and 5.5 show this applet. The first panel displays a rendering of a snowflake curve. Starting from a simple peaked line (see Figure 5.3), more peaks are added on the line segments until the entire curve resembles the ragged, yet precisely intricate snowflake shape (progressing through Figure 5.4 and Figure 5.5).

Similarly, the last fractal shown in Figures 5.3 to 5.5 is called a Hilbert curve. Starting with a set of lines forming a Y, the algorithm adds detail until the entire fractal appears similar to a fine oriental rug—a pattern like a maze formed from a precise algorithm.

Argonaut
06-11-2005, 03:29 PM
Chapter 6

The Significance of Network Distribution and Retrieval ("]Java distributes content [/url]

Because Java is designed for distributing executable content, all Java applets, except those on the user’s local host, are distributed across networks. However, Java’s power as a language for expressing executable content involves more than the distribution of applets. Java also makes the following possible:


Protocol handlers that communicate to a Java-enabled browser how to handle a new method of processing information.
Content handlers that give a Java-enabled browser the capability to interpret new data formats.
Java language statements to access network resources. This enables Java programs to retrieve resources in a user’s Java-enabled browser.
This chapter examines these capabilities in detail, showing examples and key Java statements that make these features possible. Later parts of this book will guide you through more details of Java programming. In particular, the java.net package is covered in Chapter 28, and protocol and content handlers are covered in Chapters 30 and 31.

applet (Magic) that allowed you to draw on images (refer to Figure 4.6). The network relationships involved in this simple applet are fairly significant. Figure 6.1 shows the connections among the content distribution, network retrieval, and display involved in this applet.

The figure shows the network retrieval taking place:


The Web server www.rpi.edu ("]The IMG and APPLET elements in the file marker.html cause the HotJava browser to request an image from the Web server www.paris.org and an applet from www.rosebud.com.
The resulting image, applet, and hypertext page are assembled in the user’s HotJava browser. The applet executes on the user’s computer.
This network interaction involves three Web servers and the user’s computer, besides the routers involved with the Internet network connections that relay the information from two continents. This intermingling of content demonstrates the integration Java can help accomplish. As a Web client, a Java-enabled browser is already an information integrator for many protocols. Combined with capabilities to distribute and retrieve content, Java adds another dimension to information retrieval and integration.

file:///G:/Java%20Unleashed/figicon.gif FIGURE 6.1.



(file:///G:/Java%20Unleashed/049-5g/06/06jun01.gif)Summary of information transfer in Magic applet demonstration.

("]Handling New Protocols and Formats

The most significant feature ("]of a Java-enabled browser is that it is not fixed. Instead of relying on a built-in set of code for handling information delivery protocols and a fixed set of helper applications to handle media formats, a Java-enabled browser is set up so that it can adjust to learn new protocols and media formats.

This capability significantly changes the Web:


Developers no longer have to rely on just the fixed set of protocols.
Java-enabled browsers can respond to new protocols. These protocols may support new applications or may be new kinds of protocols for information transfer.
Retrieving and Sharing Network Information ("]

The protocol and ("][url=")writing about his ("]content handlers can expand what a Java-enabled browser can interpret and display, opening the Web for delivery of diverse information. Java also has the capability to enrich how browsers retrieve information, giving Java programmers the chance to make applets to retrieve network information.

Surf-o-matic

Patrick Chan, Surf-o-matic demonstration program at [url="http://java.sun.com/applets/applets/autopilot/index.html"][u]http://java.sun.com/applets/applets/autopilot/index.html ("]http://www.yahoo.com/ (http://www.yahoo.com/)) random list of Web pages is very large and is used in the example in Figure 6.2.

file:///G:/Java%20Unleashed/figicon.gif FIGURE 6.2.



(file:///G:/Java%20Unleashed/049-5g/06/06jun02.gif)Surf-o-matic in action.

Figure 6.2 shows Surf-o-matic as it is retrieving a new page. Even in its present form, it is a useful standalone application. One use is as a kiosk application to demonstrate the content of the Web.

Surf-o-matic is based on Matthew Gray’s Web Autopilot, which uses the Netscape browser’s client-pull feature. However, a HotJava browser can use Java code to implement this same type of task; it then does not have to revert to a client-pull technique. Patrick Chan’s demonstration in Surf-o-matic is a quick example showing this flexibility of Java for network information retrieval.

JavaScript

JavaScript ("]Common Gateway Interface (CGI) programming. Instead, a JavaScript program gives the user the answer to the calculation. This shift changes the site of computation from the information provider’s server to the user’s client and host.

file:///G:/Java%20Unleashed/figicon.gif [b]FIGURE 6.3.



("]JavaScript in action. [/size]

A Java Graffiti Board

Dan ("]Guinan developed a Java http://www.tisinc.com/beta/chalkboard.html ("]Graffiti Chalkboard that demonstrates sharing information using a Java applet. This applet is located at FIGURE 6.4.



(file:///G:/Java%20Unleashed/049-5g/06/06jun04.gif)The Java Graffitti Board.

Summary ("")

Java not only changes what can happen on a Web page, it also changes what can be retrieved and displayed on a Web page. Special handlers for new protocols and content extend what a Java-enabled browser can find and interpret. Java enables network information retrieval within applets, making it possible for an applet to “take over” a user’s display and exhibit a series of network resources or provide a way for users to share information across a network.

Argonaut
06-11-2005, 03:30 PM
Chapter 7

Overview of Java Tools ("]Putting together your toolkit [/url]

One of the most difficult aspects of learning and using Java is sorting out what the different applications of Java can do for you. There has and will continue to be much hype surrounding Java that can easily result in confusion as to what each new Java licensee brings to the table. Not only is Java quickly gaining acceptance as a programming standard, it is also spawning a new generation of development tools.

In this chapter, you learn about the various ways Java is being used in both new and existing products, including browsers and development tools. The goal is to provide you with a broad perspective on the Java development world so you can be more informed when deciding how to put together your own Java development toolkit. You will also learn about some of the most popular online resources for keeping up with the fast-moving animal known as Java.

that have jumped up and pledged allegiance to Java is growing at a surprising rate. With the Java bandwagon steadily rolling along, it is somewhat difficult to see how and where Java fits into many of the products that promise Java support. This is especially true when it comes to Java development tools. The products and tools important to Java development can be broken down into three categories, which follow:


Browsers
Development Environments
Programming Libraries
This chapter focuses on each of these categories and discusses the Java Developer’s Kit and online sources of Java development information. Keep in mind that Java is still a growing technology, so many of the development tools are still in their infancy. Some haven’t even reached the prototype stage, whereas a few others are ready for prime time. It’s important for you to plan your Java development around what tools are available and what tools are on the horizon.

("][url=") ("] of Java applications to affect Java development is that of Web browsers. Without Java-compatible browsers, Java applets wouldn’t be very useful. Java browsers practically serve as the operating system for Java programs. For this reason, Java is highly dependent on the availability and success of Java browsers. Fortunately, all the major players in the browser market have signed on to Java and promised to support it. Following is a list of major companies with Web browser products that have promised some support for Java either presently or in the near future:

Netscape

Sun

Microsoft

Spyglass

A quick overview of each of the major players and its connection to Java is presented in the following sections.

Netscape Navigator

The biggest player in the Web browser world, Netscape, is at the front of the Java support line. Netscape has already delivered a commercial browser with complete support for Java: Netscape Navigator 2.0. With the lion’s share of the Web browser market prior to this release, Netscape Navigator alone will secure Java among Web users and developers alike.

Netscape has gone a step further than just supporting the Java language and run-time system. They also helped develop JavaScript, which is an object-based scripting language based on Java. The aim of JavaScript is to allow the rapid development of distributed client-server applications. However, the practical uses of JavaScript will no doubt expand as it gains acceptance. If you want to learn more about JavaScript, you’re in luck; Part IX of this book, “JavaScript,” is devoted entirely to JavaScript programming. If you want more information on Netscape Navigator itself, just sit tight because the next chapter is all about Netscape Navigator.

HotJava

The HotJava ("][url=") ("]Microsoft Internet Explorer[/b]

You didn’t seriously think ("] Microsoft would sit idly by while Java soaked up so much press attention! Of course not. After some delay, Microsoft finally agreed to license the Java technology. It isn’t clear yet exactly what technologies Microsoft plans to integrate Java into. It’s safe to say that Microsoft’s Internet Explorer Web browser will probably be the first Microsoft product to support Java. Considering the fact that Internet Explorer is tightly linked to Windows 95, it has the potential to gain a significant share of the Web browser market.

As of this writing, there is no tentative date for when a Java-compatible version of Internet Explorer will be available. Because Netscape has already beat them to the punch, you can probably expect Microsoft to get Internet Explorer up to speed with Java pretty rapidly.

Spyglass Mosaic

Spyglass Mosaic is ("][url=") ("]another popular Web browser that has announced future support for Java. Like Microsoft, Spyglass has given no solid dates of when their Mosaic browser might be available with Java support. Again, with all of the different browsers battling head-to-head over supporting new technologies, you can probably expect a Java-compatible version of Mosaic very soon.

Java Developer’s Kit (JDK) provides the core tools and information necessary for developing programs in Java. The JDK is the first thing you should take into consideration when putting together your own Java development toolkit. Although third-party add-ons and development environments promise to make Java development smoother and easier, the JDK provides all the essential tools and information necessary to write professional Java applets immediately. Also, the JDK is Sun’s official development kit for Java, which means you can always count on it providing the most extensive Java support.

The JDK includes a Java runtime interpreter, a compiler, a debugger, lots of applet demos, and the complete Java API source code, along with a few other useful tools. For more information on the JDK, check out Chapter 10, “The Java Developer’s Kit.”

[url=""]Development Environments ("] most uncharted region of Java programming is that of development environments. In a time when developers have become spoiled with graphical drag-and-drop programming tools, everyone expects the same out of a Java development environment. Indeed, they are on their way, but Java is still very new.

Most of the big players in the programming-tool business have announced some type of development environment for Java. Some of this Java support will arrive in the form of add-ons for existing products, while others will be entirely new products. It’s interesting to note that a few of the development environments are themselves being developed in Java, which means that they will be available for all of the platforms that support Java. All the Java development environments are covered in more detail in Chapter 11, “Other Tools and Environments.”

Symantec Espresso

Symantec is the biggest PC-development tool player to have a Java development environment ready for testing. ("][url=") ("]Symantec Espresso is an add-on for their Symantec C++ development system for Windows 95/NT that enables you to use the C++ facilities for Java development. Espresso features a project management system, a powerful editor, and browser tools. Symantec Espresso is already available and is a free add-on for users of Symantec C++.

Borland Latte

Borland, the developerMicrosoft Visual C++[/b]

Although there have[url=""] ("") been no formal announcements, it is very likely that Microsoft is busily working on their own Java development environment. Microsoft is committed to creating powerful development tools, and Java is no exception. In the meantime, the Visual C++ environment for Windows 95/NT is actually fairly well suited as-is for Java development. Chapter 11, “Other Tools and Environments,” contains information on how to configure Visual C++ to work with Java.

Argonaut
06-11-2005, 03:32 PM
JavaMaker

JavaMaker[/url] is a simple development environment—developed by Heechang Choi—that runs under Windows 95 and Windows NT. It doesn’t have too many bells and whistles, but it does manage to put a front-end on the JDK. JavaMaker (currently still in beta) comes with a multiple document interface text editor and interfaces directly with the Java compiler and applet viewer. If you want to keep things simple, JavaMaker is a very useful application—even in its current prerelease state.

Natural Intelligence’s Roaster

If you are a Macintosh user, ("] ("] you’re probably thinking this discussion of development environments is skewed toward Windows. Not so! Natural Intelligence, the company that makes the popular Macintosh script editor Quick Code Pro, has released a Macintosh Java development environment. Natural Intelligence’s Java Applet Development Kit, Roaster, provides an integrated development environment with a built-in class disassembler, debugger, and compiler. It is currently available for Power Macintosh, with a 68000 version expected soon.

Metrowerk’s CodeWarrior

Lest you believeSilicon Graphic’s Cosmo[/b]

Silicon Graphics has entered the Java foray in big way with its Cosmo development tools suite. The Cosmo technologies are aimed at providing more extensive multimedia and 3D graphics support to the Web. A core component of Cosmo is Cosmo Code, which is a Java development environment that promises to deliver a staggering array of features. Cosmo Code includes a runtime interpreter, compiler, graphical debugger, visual browser, and the Cosmo Motion and Cosmo MediaBase libraries. The core components of the Cosmo Code development kit are already available in beta form for Irix systems.

Programming Libraries ("]is object oriented, it is hard to overlook the potential for reusing Java objects. There is already a surprisingly large amount of Java classes available for free; most of which include source code. Additionally, a few commercial Java object libraries are appearing that show a lot of promise.

Even though the commercial Java tools market is still in an embryonic state, one company in particular looks poised to provide some very interesting and powerful class libraries: Dimension X. ("]JACK (Java Animation Creation Kit) is a tool for creating Java animation applets through a simple drag-and-drop interface. For more information on VRML and Dimension X, see Chapter 34, “VRML and Java.”

Online Resources ("]

In the dynamic ("] ("]http://www.javasoft.com/ (http://www.javasoft.com/)Figure 7.1 shows what Sun’s Java Web site looks like.

file:///G:/Java%20Unleashed/figicon.gif [b]FIGURE 7.1.



(file:///G:/Java%20Unleashed/049-5g/07/07jun01.gif)Sun's Java Web site.

Gamelan

Look no further than ("]http://www.gamelan.com/ ("]Gamelan for the end-all Java resource directory! With the possible exception of the official Java Web site at Sun, Gamelan is by far the most useful and comprehensive source of Java information anywhere. It has Java conveniently divided up into different categories, with each leading to a wealth of information and sample applets. Check out Gamelan yourself and you’ll see what I mean. Its URL follows:

file:///G:/Java%20Unleashed/figicon.gif[/img] FIGURE 7.2.



(file:///G:/Java%20Unleashed/049-5g/07/07jun02.gif)The Gamelan Web site.

SunWorld Online ("]http://www.sun.com/sunworldonline/ ("]

SunWorld Online is an online journal published by IDG Communications that often contains useful information that relates to Java. It has a regular column called “Java Developer” that usually tackles an interesting topic related to Java programming. SunWorld Online is located at the following URL:

file:///G:/Java%20Unleashed/figicon.gif[/img] FIGURE 7.3.



(file:///G:/Java%20Unleashed/049-5g/07/07jun03.gif)The Sun World Online Web site.

Digital Espresso ("]http://www.io.org/~mentor/phpl.cgi?J___Notes.html ("]

Digital Espresso is an online weekly summary of the traffic appearing in the various Java mailing lists and newsgroups. Digital Espresso is an excellent Java resource because it pulls information from a variety of sources into a single Web site. Following is the URL for Digital Espresso:

file:///G:/Java%20Unleashed/figicon.gif[/img][u] FIGURE 7.4.



(file:///G:/Java%20Unleashed/049-5g/07/07jun04.gif)The Digital Espresso Web site.

Summary ("")

You learned in this chapter that putting together a Java toolkit isn’t as easy as going out and buying a development environment. Because Java is such a new technology, many of the development options for developers have yet to mature into solid applications. At this stage, it’s important to know what is available and what is being promised in the future.

You also learned about the different Java-compatible Web browsers and development environments that are in the works, along with a few that are available now. You then learned about the Java Developer’s Kit and some class libraries that have the potential to raise the ante on Java development. Finally, some online resources for keeping up-to-date with Java were discussed.

Because Java-supported browsers are so important to Java developers, the next chapter focuses on what will possibly be the most established of the Java Web browsers: Netscape Navigator.

Argonaut
06-11-2005, 03:33 PM
Chapter 8

Netscape Products ("]Netscape [/url]

Netscape is without a doubt the largest player in the Web browser business. It is insanely popular Netscape Navigator Web browser dwarfs all other browsers in terms of market share, with no signs of any significant losses in the near future. It is certainly going to see some fierce competition, but Netscape is staying on top of things and integrating the latest technology into Netscape Navigator.

Java currently is the most important of these new technologies. With the advent of Navigator 2.0, Netscape has provided complete support for the Java language. Additionally, Netscape has collaborated with Sun to create a scripting language based on Java called JavaScript. Together, these two technologies promise to keep Netscape firmly rooted as the king of the Web browser hill. For Web developers, this means that interactivity on the Web has finally comeof age.

NOTEAs of this writing, the Macintosh and Windows 3.1 versions of Netscape Navigator still do not have support for Java. However, you can expect support to arrive for these platforms in the near future.

In this chapter, you learn about how Java and JavaScript impact Netscape’s new product line, especially the Navigator Web browser. Netscape Navigator 2.0 provides very strong support for Java and JavaScript, as you’ll see.

("]Java-specific aspects of the latest release of Netscape Navigator, it’s important to bring you up to date with this version of the popular Web browser, along with other Web-related products being offered by Netscape. First, Netscape has opted for two different versions of Navigator, standard and gold. Navigator 2.0 is the logical upgrade to the original Navigator Web browser. Navigator Gold 2.0 includes Navigator 2.0, along with a Web development environment, enabling users to edit HTML files graphically.

Additionally, Netscape is releasing Live Wire, which is a Web development environment that provides the tools necessary to create and manage Web sites. Live Wire includes Navigator Gold and the JavaScript scripting language. And if Live Wire isn’t enough for you, Netscape also has Live Wire Pro, which adds to Live Wire the capability to browse, search, and update relational databases.

To summarize, Netscape is offering the following Java-supported products to the Webcommunity:

Navigator 2.0

Navigator Gold 2.0

Live Wire

Live Wire Pro

Netscape’s new Web tools will no doubt set the standard for others to follow. With its new features and wide support for new technologies, Navigator 2.0 should easily match the popularity of its predecessor. However, as impressive as the new Navigator browser appears to be, Netscape may ultimately gain more from the release of Navigator Gold and Live Wire. The early integration of Java into all of these products has set the stage to bring Java to the Web in full force.

Navigator 2.0

Navigator 2.0 is thefile:///G:/Java%20Unleashed/figicon.gif[/img] FIGURE 8.1.



("]Shockwave. Additionally, a plug-in supporting Apple’s QuickTime multimedia standard is expected soon. Navigator 2.0 is also the first browser to provide complete Java support. Figure 8.1 shows what Netscape Navigator 2.0 looks like.

Netscape Navigator 2.0.[/size] The new Navigator update also adds enhanced performance through client-side image maps, progressive JPEG images, and streaming audio and video. Its new security features include digital ID, secure courier for financial transactions, and secure e-mail and news. Navigator 2.0 also features advanced layout capabilities, including frames, which enable the display of multiple, independently scrollable panels on a single screen. Each of these panels can have a different Web address as its source.

Navigator Gold 2.0

Navigator Gold 2.0 is a tool built around Navigator 2.0 that enables Web developers to design and edit HTML documents graphically. The ("]Live Wire and Live Wire Pro[/b]

Netscape’s Live Wire goes a step beyond Navigator Gold by providing an environment that lets developers graphically build and manage applications and multimedia content for the Internet. Live Wire’s graphical design approach is aimed at simplifying the management of complex Web document hyperlinks. Live Wire includes Navigator Gold and the JavaScript scripting language. Netscape is also offering Live Wire Pro, which adds database connectivity to Live Wire. With Live Wire Pro, users can interact with relational databases on the Web.

Netscape Support for Java ("]2.0 is the first major Web browser to provide support for Java. Although this aspect of Navigator has generated a significant amount of press attention, it’s important to realize that the bulk of Navigator’s Java support takes place behind the scenes. Many Navigator users will likely see Web pages come to life and not fully realize that Java is the technology making it all happen. The point is that the Java support in Navigator affects the content of Web pages viewed in Navigator a great deal, but affects the Navigator interface and options very little.

Because the Java support in Navigator is a behind-the-scenes issue, it isn’t always clear what parts of a Web page are using Java. If you saw a Java Web page and didn’t know anything about Java, you might just think that Web page developers were pulling off neat tricks with CGI or some other scripting language. But you are well on your way to becoming a Java expert, so you know better; Java opens the door to doing things that are impossible with scripting languages like CGI.

Java programs appear in Navigator as applets that are embedded in Web pages. Java applets are referenced in HTML source code using a special APPLET tag. Navigator parses these tags and automatically launches an internal Java interpreter that executes the Java applets. By implementing a Java runtime interpreter, Navigator provides the layer of functionality that allows all Java applets to run. Beyond this, there isn’t really anything particularly special about the way Navigator supports embedded Java applets. This simply means that the only significant component in Navigator necessary to support Java is the integrated Java runtime interpreter.

Other than seeing functionality in Web pages that you’ve never seen before, there’s not much in Navigator to inform you that a Java applet is running. A few small things you might notice are the various messages that appear in the Navigator status bar when an applet is preparing to run. You may also notice a significant delay while Java applets are being transferred to your machine, especially those that use a lot of graphics and sound.

Another Java-specific feature of Navigator is located under the Options menu. The ("] file:///G:/Java%20Unleashed/figicon.gif[/img] FIGURE 8.2.



("]Navigator Java Output window looks like.

The Netscape Navigator Java Output window.[/size] ("]Configuring Java with Netscape

When you first install Netscape Navigator, ("][url=") ("]Java support is automatically installed and enabled by default. Remember, the Java support in Navigator is built-in, so you don’t have to do anything special to get it working. As a result, you can immediately start viewing and interacting with Java-enhanced Web sites.

The only real Java-specific option in Navigator is whether or not you want Java support enabled. Most of the time you will want to leave Java support enabled, so that you can enjoy the benefits of the Java technology. However, if you are experiencing problems with Java or with a particular Java Web site, you can disable Navigator Java support. To do this, select the file:///G:/Java%20Unleashed/figicon.gif[/img] FIGURE 8.3.



("]Security Preferences command from the Navigator Options menu. The Disable Java checkbox is used to enable/disable Java support. Figure 8.3 shows the Navigator Security Preferences dialog box.

If Java is disabled, you will still be able to view Java-enhanced Web sites, you just won’t be able to view or interact with the Java applets contained within them.

The Netscape Navigator Security Preferences dialogue box.[/size] ("]Java Applets

There are file:///G:/Java%20Unleashed/figicon.gif[/img] FIGURE 8.4.



(file:///G:/Java%20Unleashed/049-5g/08/08jun04.gif)

A crossword puzzle Java applet running in Netscape Navigator. The different applications for Java are limitless. Figure 8.5 shows a very interesting application of Java: an instructional dance applet.

file:///G:/Java%20Unleashed/figicon.gif FIGURE 8.5.



(file:///G:/Java%20Unleashed/049-5g/08/08jun05.gif)

An instructional dance Java applet running in Netscape Navigator. If you want to check out some of the Java applet demos, take a look at the Java Applet Demos Web page on Netscape’s Web site, which is shown in Figure 8.6:

[u]http://www.netscape.com/comprod/products/navigator/version_2.0/java_applets/ ("]file:///G:/Java%20Unleashed/figicon.gif FIGURE 8.6.



(file:///G:/Java%20Unleashed/049-5g/08/08jun06.gif)

Netcape's Java Applet Demos Web site. If you want to find out more about creating your own Java applets that can be integrated into Web pages, check out Part V of this book, “Applet Programming.”

("]JavaScript

JavaScript is a scripting language described by Netscape as a lightweight version of Java. JavaScript promises to enable less technical Web users and developers the capability to create interactive content for the Web. You can think of JavaScript as a higher level complement to Java. Netscape Navigator supports JavaScript by providing an internal JavaScript interpreter.

JavaScript was designed with the goal of creating a simple and easy-to-use cross-platform scripting language that could connect objects and resources from both HTML and Java. While Java applets are primarily developed by programmers, JavaScript is intended to be used by HTML document authors to dynamically control the interaction and behavior of Web pages. JavaScript is unique in that is has been designed to be complementary to both HTML and Java.

If you can believe it, JavaScript is actually an even newer technology than Java. Because JavaScript was developed jointly by Sun and Netscape, it is almost guaranteed to be widely adopted by the Web community. However, it may still take some time before you see truly compelling applications of JavaScript. Part IX of this book, “JavaScript,” is entirely devoted to understanding and using JavaScript.

[url=")

The latest release of Netscape’s line of Web products promises to further establish Netscape as the premier Web tool provider. A central technology present in these tools is Java, which brings interactivity to the Web. Netscape Navigator, along with already being the most popular Web browser available, is the first major Web browser to fully support Java.

In this chapter, you learned about the different tools available from Netscape and how Java relates to them. You also learned about JavaScript, and how it is positioned to provide a higher level option to HTML developers wishing to add interactivity without learning Java inside and out. Netscape’s early support for both Java and JavaScript is a sure sign that these technologies are here to stay.

Now that you have an idea about how the most popular Web browser supports Java, you may be interested in learning about a new browser developed by the creators of Java, Sun Microsystems. The next chapter takes a close look at HotJava, Sun’s new Web browser that is tightly integrated with Java.

Argonaut
06-11-2005, 03:35 PM
Chapter 9

This Is HotJava ("]HotJava [/url]

Java applets are only as useful as the Web browsers that support them. Although Netscape Navigator is certainly a strong contender for the Java support crown, Sun has its own browser that is specifically designed with Java in mind: HotJava. The HotJava Web browser builds on the techniques established by NCSA Mosaic and Netscape Navigator, while adding the capability to add new behaviors dynamically. The tight link to the Java language is what enables HotJava to have this dynamic behavior.

In this chapter, you learn all about HotJava, including its major features and how to install and use it. Although HotJava as a software product is still in the development stages, it is readily available and quite usable in its current alpha form. This chapter explores the primary features of HotJava and how they impact Web navigation and the Java language.

("]file:///G:/Java%20Unleashed/figicon.gif[/img] FIGURE 9.1.



("] into the specifics of how to install and use HotJava, it’s important to take a look at why HotJava is important. Actually, if you first want to literally take a look at HotJava, check out Figure 9.1.

The HotJava Web browser. [/size]

Figure 9.1 shows what HotJava looks like. You’ll learn about how to use HotJava a little later in this chapter. For now, it’s important to understand why HotJava is significant as a Web browser. There are a variety of technical innovations in HotJava that promise to make it more extensible than other Web browsers. These innovations stem largely from the fact that HotJava is designed around supporting the Java language.

The primary innovation that sets HotJava apart from other browsers is its extensibility. Where other browsers have most or all of their components hardwired to the executable browser application, HotJava opts for a more distributed approach. This means that by itself, HotJava doesn’t really support any object types or Internet protocols. But its extensible design provides a very open path to add support without modifying the HotJava application itself. Furthermore, HotJava can be extended to provide new support automatically and on demand without the user even having to know.

Following is a list of the major features in HotJava:


Dynamic Object Types
Dynamic Protocols
Network Security
Dynamic Object Types

Along with dynamic ("] content within Web pages, HotJava also aims to be dynamic on a few other fronts. One of these fronts is the support for dynamic object types. An object type refers basically to a file format, such as the popular GIF (Graphics Interchange Format) graphics files. Although most Web browsers provide support for the most popular object types right now, who’s to say what new object types will appear in the future? Obviously no one knows what object types will become popular in the future. For this reason, HotJava takes an open-ended approach to supporting object types. HotJava is capable of dynamically linking to Java code for handling a particular object type on the fly. Rather than Sun having to create a new version of HotJava each time a new object type appears on the scene, HotJava can instead locate an object handler and deal with it dynamically. Incidentally, content handlers. Figure 9.2 shows the difference between HotJava’s dynamic connection to objects and a conventional Web browser’s built-in support for objects.

Notice in the figure that both approaches provide similar support for object types that are currently popular. The difference arises when new types are introduced; HotJava transparently attaches to the handlers for new object types, whereas other browsers must implement handlers internally.

You may be wondering where the object handlers come from, and how HotJava knows about them to begin with. Typically, the vendor that creates an object will also create a handler routine for interpreting the object. As long as the handler is present on a server with the objects in question, HotJava can link to the code and automatically upgrade itself to support the new object type. While other Web browser developers are busily hacking in patches to support new object types, HotJava users will be automatically and transparently upgrading each time they encounter a new object type.

file:///G:/Java%20Unleashed/figicon.gif[u] FIGURE 9.2.



("]How HotJava and conventional Web browsers differ in their handling of objects . [/size]

Dynamic Protocols

Similar to its ("]which define the location of Internet resources. An example URL follows:

[u]http://www.javasoft.com/ ("]protocol handler is a separate piece of code that defines how to interpret information from a particular protocol. Figure 9.3 shows the difference between how HotJava and conventional browsers manage protocols.

file:///G:/Java%20Unleashed/figicon.gif[u] FIGURE 9.3.



("]How HotJava and conventional Web browsers differ in their handling of protocols. [/size]

You may have noticed that Figure 9.3 looks very similar to Figure 9.2. Indeed, HotJava’s support for new protocols parallels its support for new object types. The same approach of forcing outside handlers to provide the specific implementations for new objects works equally well when dealing with new protocols.

Network Security

When you ("] start thinking about interactive content and what it means to the broad base of users it will affect, there is an unavoidable issue of security. To get an idea of how important the issue of security is, think back to how things were before the Web. Prior to the Web, online services, independent bulletin boards, and private networks served as the primary electronic communication mediums. Most of these mediums were and still are completely based on static content. Even so, the instances of viruses and other security-related problems have always been in relative abundance. In most of these cases, users would knowingly transfer a file to their computer that was assumed to be safe. The file would end up doing harm to their machine once it was transferred. Obviously, the users wouldn’t have transferred the file if they had known about the virus beforehand. The point is that even with users having complete control over which files are transferred, viruses have still flourished.

Now consider the possibilities for security breaches with interactive content in the global Internet environment. Given that users are able to interact with Web pages in an interactive environment, the software must be able to respond dynamically. You’ve probably guessed that this creates a potentially dangerous situation. This brings us to the next key issue in the design of HotJava: security.

In HotJava, you can specify security options relating to what access you want to allow incoming executable content to have to your machine. You can specify whether and how much you want to allow applets to be able to read, write, or change files on your machine. You can set up security regions in HotJava by creating firewalls. A firewall is typically a set of computers within a certain domain name. Usually these computers are assumed to be safe, so they are listed as being located behind the firewall. You’ll learn more about configuring firewalls later in this chapter.

[url=""]Java and HotJava ("]

The majority of the features ("][url=")implemented in HotJava stem from the fact that HotJava is designed around supporting Java. Before getting into more specifics regarding HotJava, it is important to clarify the relationship between Java and HotJava.

To recap prior chapters, Java is an object-oriented programming language derived in many ways from C++. Java enables you to write programs and applets that can be embedded in Web pages and executed interactively. HotJava is a Web browser written in Java that implements object and protocol handlers as external libraries. HotJava is akin to Netscape Navigator or NCSA Mosaic, with the primary difference being that it is written in the Java language and is far more extensible.

Java Versions

The Java language and ("]HotJava’s Support for Java

But there’s always a catch! [url=""]The problem right now is that Sun has focused its efforts on polishing Java, and has kind of dropped the ball on bringing HotJava up to date. What this means is that the alpha release of HotJava, which is the latest, only supports alpha Java applets. You can’t program to the final Java API and incorporate the applets into the current version of HotJava. Hopefully, by the time you read this Sun will be closer to releasing a beta or even final version of HotJava, but it’s still too early to guess.

So, you may be wondering how to deal with this problem? Do you go ahead and write outdated alpha code so you can use HotJava, or do you blindly write final code and pray that a new version of HotJava that will run the final code will be released soon? The answer is neither. In light of this problem, Sun released an applet viewer program that supports the final release of Java. Additionally, Netscape Navigator 2.0 is supposed to fully support the Java final release. You’ll learn more about the applet viewer in Chapter 10, “The Java Developer’s Kit.” You can use either of these applications as a test bed for final release Java applets.

You’re probably wondering why bother discussing HotJava when it’s currently not even useful for working with the final release of Java? The answer is that HotJava is an important technology, and all release delays aside, it will still be an important application for Web users and Java programmers in the future. Furthermore, because it is itself written in Java, it will be without a doubt the most Java-compatible browser around. In the meantime, you can still have a lot of fun with HotJava by running the many alpha Java programs that are available.

Argonaut
06-11-2005, 03:38 PM
[/url] ("]Setting Up HotJava

Installing and configuring HotJava is pretty straightforward. Before you begin installing HotJava, you may want to check and see if there is a newer release than the one you have. At the time of this writing, the latest release of HatJava was alpha release 3. This version will run alpha Java applets fine, but you may want to check directly with Sun to find out the latest version of HotJava available. Sun maintains a Web site devoted entirely to Java and HotJava. You actually saw the Java URLhttp://www.javasoft.com/[/u] (http://www.javasoft.com/)This is the same place where you can download the latest release of the Java Developer’s Kit (JDK). You’ll learn more about the JDK in Chapter 10. This is also the primary location for learning the latest news and support issues surrounding Java and HotJava. Figure 7.1 in Chapter 7 shows what the Java Web site at Sun looks like.

HotJava usually comes compressed in a self-extracting archive. To ("] install HotJava, you simply execute the archive file from the directory where you want HotJava installed. For example, if you want to install HotJava on a Windows 95 machine, you would execute the self-extracting archive file from the C:\ root directory. The archive will automatically create a HotJava directory below C:\ and build a directory structure within it to contain the rest of the support files. All the related files are automatically copied to the correct locations in the HotJava directory structure.

NOTEThe current alpha release of HotJava only supports the Solaris and Windows 95/NT platforms. It is expected that a commercial release of HotJava will also support Macintosh and Windows 3.1, but at this point it is still speculation.Once HotJava is installed, you are ready to run it. You run ("]Security dialog box shown in Figure 9.4. Just click the Apply button for now and everything will be OK. You’ll learn more about the security options in this dialog box a little later in this chapter.

file:///G:/Java%20Unleashed/figicon.gif FIGURE 9.4.

("]The HotJava Security dialog box. [/size]

HotJava uses three system environment variables to determine various options for the browser. These environment variables follow: ("]


HOTJAVA_HOME
WWW_HOME
HOTJAVA_READ_PATH
HOTJAVA_WRITE_PATH
The HOTJAVA_WRITE_PATH specifies a list of files and directories that Java applets have write access to. Any files or directories not explicitly given read or write permission through these variables will be inaccessible to Java applets.

[url=""]Using HotJava ("]HOTJAVA_READ_PATH variable specifies a colon-separated list of files and directories to which Java applets have read access. The default setting for HOTJAVA_READ_PATH is <hotjava-install-dir>:$HOME/public_html/. You give read access to new files and directories by adding a colon and the file or directory onto the end of the list. For example, if you wanted to give the Docs directory read access, and it was located just off of the root directory, you would set HOTJAVA_READ_PATH to the following:

<hotjava-install-dir>:$HOME/public_html/:$HOME/Docs/Similarly,

Now that you ("][url=") ("]have HotJava up and running, you’re ready to learn some more about how to use it. The HotJava browser application is composed of five major parts, which follow:


The menu bar
The URL edit box
The client area
The toolbar
The status bar
To see where these parts are located in HotJava, refer back to Figure 9.1, which shows the HotJava application window. The URL edit box is located just below the menu bar and is used to manually enter document URLs. You’ll learn how to enter URLs in HotJava in the next section of this chapter.

The ("][url=") ("]client area of HotJava is located just below the URL edit box and extends down to the toolbar near the bottom of the application window. The client area takes up most of HotJava’s screen real estate, and is where documents are displayed. Because the client area is where documents are displayed, it is also the display area for Java applets.

The [url=")HotJava toolbar consists of five buttons and is located just below the client area. These buttons are used to navigate through Web pages. The Left and Right Arrow buttons are used to move forward and backward through documents that you have already viewed. The Home button takes you to the default home page for HotJava. If you recall, this page is specified by the WWW_HOME environment variable. The Reload button is used to reload the current document. And finally, the Stop button is used to stop the loading of a document.

The status bar is used to inform you of the status of operations. For example, while a document is being fetched, the status bar displays a message notifying you that it is fetching the document. The status bar also displays the names of links to documents when you drag the mouse over them.

Working with URLs

Document URLs ("] ("]Menu Commands

The HotJava ("][url=")[url=""] ("") menu commands provide access to all the functionality in HotJava. These menu commands can be grouped into five categories, which correspond to the pull-down menu names shown in the menu bar. Following are the menu command categories:


File
Options
Navigate
Goto
Help

Argonaut
06-11-2005, 03:40 PM
File Commands

The File menu [/url] ("]commands consist of commands related to managing URL documents. Some commands are listed under the File menu but remain unsupported in the alpha release of HotJava. The following File menu commands are supported under the alpha 3 release of HotJava:


Open
Reload
View Source
Quit
The Open ("]Reload command is exactly the same as clicking the Reload button on the toolbar. The ("]command exits the HotJava application.

Options Commands

The Options ("][url=") ("] ("] menu commands are used to specify HotJava environment options. A few commands are listed under the Options menu but remain unsupported in the alpha release of HotJava. The following Options commands are supported under the alpha 3 release of HotJava:


Security
Properties
Flush Cache
Progress Monitor
The Security[url=") ("] command opens a dialog box where you specify the level of security to be applied to incoming executable content. This is the same dialog shown in Figure 9.4 that is displayed the first time you run HotJava. The dialog box provides the following security modes to choose from: No access, Applet host, Firewall, or Unrestricted. The No access security mode specifies that HotJava cannot load any Java applets. This is the safest, but obviously most restricted security mode. The next safest mode is Applet host, which specifies that HotJava can only run Java applets residing on the local machine. Next comes the Firewall security mode, which specifies that HotJava can only run applets from behind the firewall. Finally, the Unrestricted mode allows HotJava to load any Java applets.

If you select the Firewall Configure Firewall button. When you click this button, the dialog box shown in Figure 9.5 appears.

The purpose of this dialog box is to enable you to specify which systems are located behind the firewall; that is, which systems are considered safe. You specify systems within the firewall by entering the domain or host name of the system, selecting whether it is a domain or host in the drop-down list, and then clicking the Add button. You can change or delete firewall entries by using the Change and Delete buttons. Once you are happy with the firewall settings, click Apply to accept them.

The ("]Properties menu command opens a dialog box which lets you change general HotJava properties. The Properties dialog box is shown in Figure 9.6.

[url="file:///G:/Java%20Unleashed/049-5g/09/09jun07.gif"]file:///G:/Java%20Unleashed/figicon.gif[u] FIGURE 9.5.



("]The HotJava Configure Firewall dialog box. [/size]

file:///G:/Java%20Unleashed/figicon.gif FIGURE 9.6.



(file:///G:/Java%20Unleashed/049-5g/09/09jun08.gif)The HotJava Properties dialog box.

The first few properties in this dialog box enable you to specify different proxies and their associated ports. The FTP Proxy is the host name and port number of an ("]Firewall Proxy refers to the host name and port number of a local firewall proxy server. The Caching Proxy refers to the host name and port number of a caching server. If you don’t want to use any of the proxies, just leave the check boxes next to each one unchecked.

The Underline anchors property determines whether or not HTML anchors (links) are underlined when displayed. The ("][url=") ("]Delay image loading and ("][url=")Flush Cache menu command flushes any images and audio that have been cached by HotJava. Typically HotJava will cache the most recently used images and audio to your hard drive in order to speed up loading time. You may want to use the Flush Cache command if you know a cached image or sound has changed and should be transferred again.

The ("]file:///G:/Java%20Unleashed/figicon.gif[/img] FIGURE 9.7.



(file:///G:/Java%20Unleashed/049-5g/09/09jun09.gif)The HotJava Progress Monitor window.

The progress monitor is considered an experimental tool, but is still interesting in its current form. You can watch and see the status of different objects as they are loaded.

Navigate Commands

The Navigate ("]menu commands provide you with a means to navigate through documents. The commands listed under the Navigate pull-down menu that are supported under the alpha release of HotJava follow:


Forward
Back
Home
Show History
Add Current to Hotlist
Show Hotlist
The Forward ("][url=")command moves to the document viewed prior to selecting the Back command or button. This means that the Forward command can only be used after you have used the ("] Back command. The Back command moves back to the last document viewed. The ("][url=")Home command displays the default HotJava home page, which is specified in the WWW_HOME environment variable. All three of these commands perform the exact same functionality as their equivalent buttons on the toolbar.

HotJava automatically maintains a history list of documents that have been viewed. The ("] Show History command displays the history list and enables you to revisit a document in the list. Figure 9.8 shows what the ("]file:///G:/Java%20Unleashed/figicon.gif[/img][u] FIGURE 9.8.



("]HotJava History List window looks like.

The HotJava History List Window. [/size]

To open a document in the history list, simply click on the document and click the Visit button. The history list is cleared each time you start HotJava.

Along with the history list, HotJava also keeps up with a hotlist, which is a list of favorite documents. The ("]file:///G:/Java%20Unleashed/figicon.gif[/img] FIGURE 9.9.



(file:///G:/Java%20Unleashed/049-5g/09/09jun11.gif)The HotJava Hotlist window.

You can visit a document in the hotlist by clicking on the document and clicking the Visit button. You can also delete documents from the list using the Delete button. There is one additional feature of the hotlist that you may be curious about: a check box labeled In Goto Menu. This check box enables you to choose documents in the hotlist that will also appear as menu selections under the Goto pull-down menu.

Goto Commands

The Goto menu ("]Add Current, which adds the current document to the hotlist and the Goto menu itself.

Help Commands

The Help ("][url=") ("] ("] menu consists of a variety of links to useful HTML documents, along with one command. Each document link is pretty self-explanatory, so you can explore them on your own. The only command on the Help menu is the file:///G:/Java%20Unleashed/figicon.gif[/img][u] FIGURE 9.10.



("]Search HotJava Documentation command. This command enables you to search the HotJava documentation for a particular topic. Figure 9.10 shows what the documentation search dialog box looks like.

The HotJava documentation search dialog box. [/size]

To search on a topic, just type the topic in the query edit box and click the Search button. Documents found matching the topic are listed in the list box. To go to one of the matching documents, just click on it in the list box.

Status Icons

HotJava ("][url=")provides visual status indicators when it is loading document information. These indicators, or icons, are displayed in place of the object they are loading until the object has been successfully loaded. The different status icons supported by HotJava follow:


Raised gray box
Yellow box
Yellow box with arrow
Orange box
Red box
Red box with arrow
The ("][url=")raised gray box means that an image or applet is still loading. The yellow box means that delayed image loading is in effect for an image. To load the image you must click on the icon. The orange box is similar to the yellow box except it deals with Java applets rather than images; it specifies that delayed applet loading is in effect for an applet. To load the applet, just click on the icon.

Both ("]yellow box with an arrow means that delayed image loading is in effect for an image and that the image is a link to another document. Clicking on the arrow opens the linked document, and clicking on any other part of the icon loads the image. The [url=")red box icons mean that an error has occurred while attempting to load an image or applet. The difference between the two is that the icon with an arrow specifies that a document link has failed to load, rather than the image or applet itself.

Summary ("")

In this chapter you learned all about the HotJava Web browser and how it relates to Java. It is not clear whether Sun intends for HotJava to be a serious competitor in the Web browser market. Nevertheless, it will be the browser to watch when it comes to providing complete Java support in the future. As a result of its support for Java, HotJava has the potential to be a technologically superior Web browser through its extensible support of dynamic content, objects, and Internet protocols.

The only downside to HotJava at this point is that it is still an unfinished product, and as a result has a versioning conflict with the latest version of Java. Nevertheless, it is only a matter of time before HotJava will be a crucial Internet technology, simply because of its tight link to the Java language.

Now that you have HotJava pretty well figured out, it92's time to press on and learn more about Java itself. The next chapter covers the Java Developer’s Kit, which is the standard toolkit for developing Java programs.

Argonaut
06-11-2005, 03:46 PM
Chapter 10

[/url]JDK and the tools and information supplied with it. Although some of the tools are discussed in more detail in later chapters, this chapter gives you a broad perspective on using the tools to develop Java programs using the JDK.

In this chapter you learn what tools are shipped in the JDK and how they are used in a typical Java development environment. With the information presented in this chapter, you will be well on your way to delving further into Java development; the Java Developer’s Kit is the first step toward learning to program in Java.

[b]Getting the Latest Version ("]The Java developer's kit

The Java Developer’s Kit, or JDK, is a comprehensive set of tools, utilities, documentation, and sample code for developing Java programs. Without it, you wouldn’t be able to do much with Java. This chapter focuses on the

Before you get startedhttp://www.javasoft.com/ ("] learning about the Java Developer’s Kit, it’s important to make sure that you have the latest version. As of this writing, the latest version of the JDK is the final release 1. This version will probably be around for a while, so you’re probably OK. Just to be sure, you can check Sun’s Java Web site to see what the latest version is. The URL for this site follows:

JDK, simply execute the archive file from the directory where you want the JDK installed. The archive will automatically create a java directory within the directory you extract it from, and build a directory structure to contain the rest of the JDK support files. All the related files are then copied to the correct locations in the JDK directory structure automatically.

[b]Overview ("]

The JavaThe Runtime Interpreter ("] Developer’s Kit contains a variety of tools and Java development information. Following is a list of the main components of the JDK:


The Runtime Interpreter
The Compiler
The Applet Viewer
The Debugger
The Class File Disassembler
The Header and Stub File Generator
The Documentation Generator
Applet Demos
API Source Code
The runtime interpreter is the core runtime module for the Java system. The compiler, applet viewer, debugger, class file disassembler, header and stub file generator, and documentation generator are the primary tools used by Java developers. The applet demos are interesting examples of Java applets, which all come with complete source code. And finally, if you are interested in looking under the hood of Java, the complete source code for the Java API (Application Programming Interface) classes is provided.

[url=")

The Java runtime interpreter (java) is a stand-alone version of the Java interpreter built into the HotJava browser. The runtime interpreter provides the support to run Java executable programs in compiled, bytecode format. The runtime interpreter acts as a command-line tool for running nongraphical Java programs; graphical programs require the display support of a browser. The syntax for using the runtime interpreter follows:

java Options Classname ArgumentsThe Classname ("] ("][url=")argument specifies the name of the class you want to execute. If the class resides in a package, you must fully qualify the name. For example, if you want to run a class called Roids that is located in a package called ActionGames, you would execute it in the interpreter like this:

java ActionGames.RoidsWhen the Java interpreter ("] ("]executes a class, what it is really doing is executing the main method of the class. The interpreter exits when the main method and any threads created by it are finished executing. The main method accepts a list of arguments that can be used to control the program. The Arguments argument to the interpreter specifies the arguments passed into the main method. For example, if you have a Java class called TextFilter that performs some kind of filtering on a text file, you would likely pass the name of the file as an argument, like this:

java TextFilter SomeFile.txtThe Options [url=")argument specifies options related to how the runtime interpreter executes the Java program. Following is a list of the most important runtime interpreter options:


-debug
-checksource, -cs
-classpath Path
-verbose, -v
-verbosegc
-verify
-verifyremote
-noverify
-DPropertyName=NewValue
The ("]-checksource and ("]-checksource option causes the interpreter to compare the modification dates of the source and executable class files. If the source file is more recent, the class is automatically recompiled.

NOTEThe [url=")-verbose options provide shorthand versions, -cs and -v. You can use these shorthand versions as a convenience to save typing.

The Java interpreter uses an environment variable, CLASSPATH, to determine where to look for user-defined classes. The -verbose option causes the interpreter to print a message to standard output each time a Java class is loaded. Similarly, the ("]CLASSPATH variable contains a semicolon-delimited list of system paths to user-defined Java classes. Actually, most of the Java tools use the CLASSPATH variable to know where to find user-defined classes. The -classpath option informs the runtime interpreter to override CLASSPATH with the path specified by Path.

The -verifyremote option. The ("]-verify option causes the interpreter to run the bytecode verifier on all code loaded into the runtime environment. The verifier’s default function is to only verify code loaded into the system using a class loader. This default behavior can also be explicitly specified using the -D option enables you to redefined property values. PropertyName specifies the name of the property you want to change, and NewValue specifies the new value you want to assign to it.

[url=")

The Java compiler (javac) is used to compile Java source code files into executable Java bytecode classes. In Java, source code files have the extension .java. The Java compiler takes files with this extension and generates executable class files with the .class extension. The compiler creates one class file for each class defined in a source file. This means that many times a single Java source code file will compile into multiple executable class files. When this happens, it means that the source file contains multiple class definitions.

The Java compiler is a command-line utility that works similarly to the Java runtime interpreter. The syntax for the Java compiler follows:

javac Options FilenameThe Filename ("] ("]
-classpath Path
-d Dir
-g
-nowarn
-verbose
-O
[/list]The -d option determines the root directory where compiled classes are stored. This is important because many times classes are organized in a hierarchical directory structure. With the -d option, the directory structure will be created beneath the directory specified by Dir. An example of using the -d option follows:

javac -d ..\ FlowerIn this example, the output file Flower.class would be stored in the parent directory of the current directory. If the file Flower.java contained classes that were part of a package hierarchy, the subdirectories and output classes would fan out below the parent directory.

The ("]-classpath option tells the compiler to override the CLASSPATH environment variable with the path specified by Path. This causes the compiler to look for user-defined classes in the path specified by Path. The [url=")-g compiler option causes the compiler to generate debugging tables for the Java classes. Debugging tables are used by the Java debugger, and contain information such as local variables and line numbers. The default action of the compiler is to only generate line numbers.

The -verbose option has somewhat of an opposite effect as -nowarn; it prints out extra information about the compilation process. You can use -verbose to see exactly what source files are being compiled.

The ("]-nowarn option turns off compiler warnings. Warnings are printed to standard output during compilation to inform you of potential problems with the source code. It is sometimes useful to suppress warnings by using the -nowarn option. The [url=")-O option causes the compiler to optimize the compiled code. In this case, optimization simply means that static, final, and private methods are compiled inline. When a method is compiled inline, it means that the entire body of the method is included in place of each call to the method. This speeds up execution because it eliminates the method call overhead. Optimized classes are usually larger in size, to accommodate the duplicate code. The -O optimization option also suppresses the default creation of line numbers by the compiler.

Argonaut
06-11-2005, 03:48 PM
[/url] ("]The Applet Viewer

The applet ("] viewer is a tool that serves as a minimal test bed for final release Java applets. You can use the applet viewer to test your programs instead of having to wait for HotJava to support the final release of Java. Currently, the applet viewer is the most solid application to test final release Java programs, because the HotJava browser still only supports alpha release applets. You invoke the applet viewer from a command line, like this:

appletviewer Options URLThe Options argument specifies how to run the Java applet. There is only one option supported by the applet viewer, -debug. The ("]file:///G:/Java%20Unleashed/figicon.gif[/img][u] FIGURE 10.1.



(file:///G:/Java%20Unleashed/049-5g/10/10jun01.gif)

The MoleculeViewer applet running in the Java applet viewer. Figure 10.1 shows the ("] ("]The Debugger[/b]

The JavaOptions argument is used to specify different settings within a debugging session. Because the Java debugger is covered in detail in Chapter 36, “Java Debugging,” you won’t learn any more details about it in this chapter. If you are just dying to know more about Java debugging, feel free to jump ahead to Chapter 36 and get the whole scoop.

("][url=")Java class file disassembler (javap) is used to disassemble a class file. Its default output consists of the public data and methods for a class. The class file disassembler is useful in cases where you don’t have the source code for a class, but you’d like to know a little more about how it is implemented. The syntax for the disassembler follows:

javap Options ClassNamesThe ClassNames argument specifies the names of one or more classes to be disassembled. The Options argument specifies how the classes are to be disassembled. The disassembler supports the following options:


-c
-p
-h
-classpath Path
-verify
-version
The ("]-p option tells the disassembler to also include private variables and methods in its output. Without this option, the disassembler only outputs the public member variables and methods. The ("][url=")-h option specifies that information be created that can be used in C header files. This is useful when you are attempting to interface C code to a Java class that you don’t have the source code for. You’ll learn much more about interfacing Java to C code in Chapter 38, “Native Methods and Libraries.”

The -verify option tells the disassembler to run the verifier on the class and output debugging information. Finally, the ("]-classpath option specifies a list of directories to look for imported classes in. The path given by Path overrides the CLASSPATH environment variable. The ("]The Header and Stub File Generator[/b]

The ("]Java header and stub file generator (javah) is used to generate C header and source files for implementing Java methods in C. The files generated can be used to access member variables of an object from C code. The header and stub file generator accomplishes this by generating a C structure whose layout matches that of the corresponding Java class. The syntax for using the header and stub file generator follows:

javah Options ClassNameThe ("]The Documentation Generator[/b]

The [url=""] ("]Java documentation generator (javadoc) is a useful tool for generating API documentation directly from Java source code. The documentation generator parses through Java source files and generates HTML pages based on the declarations and comments. The syntax for using the documentation generator follows:

javadoc Options FileNameThe ("]Applet Demos[/b]

The JDKfile:///G:/Java%20Unleashed/figicon.gif[/img][u] FIGURE 10.2.



("] comes with a variety of interesting Java demo applets, all including complete source code. Following is a list of the demo Java applets that come with the JDK:


Animator
ArcTest
BarChart
Blink
BouncingHeads
CardTest
DitherTest
DrawTest
Fractal
GraphicsTest
GraphLayout
ImageMap
ImageTest
JumpingBox
MoleculeViewer
NervousText
ScrollingImages
SimpleGraph
SpreadSheet
TicTacToe
TumblingDuke
UnderConstruction
WireFrame
Rather than go through the tedium of describing each of these applications, I’ll leave most of them for you to explore and try out on your own. However, it’s worth checking out a few of them here and discuss how they might impact the Web.

The first demo applet is the BarChart applet, which is shown in Figure 10.2.

The Barchart Java applet.[/size]

The ("][url=")BarChart applet is a good example of how Java could be used to show statistical information on the Web graphically. The data represented by the bar graph could be linked to a live data source, such as a group of stock quotes. Then you could actually generate a live, to the minute, dynamically changing stock portfolio.

The ("] ("]file:///G:/Java%20Unleashed/figicon.gif[/img][u] FIGURE 10.3.



(file:///G:/Java%20Unleashed/049-5g/10/10jun03.gif)The GraphicsTest Java applet.

file:///G:/Java%20Unleashed/figicon.gif FIGURE 10.4.

(file:///G:/Java%20Unleashed/049-5g/10/10jun04.gif)The SimpleGraph Java applet.



On the business front, there’s nothing like a good spreadsheet. The ("]file:///G:/Java%20Unleashed/figicon.gif[/img] FIGURE 10.5.



(file:///G:/Java%20Unleashed/049-5g/10/10jun05.gif)

The SpreadSheet Java applet. Once you’ve gotten a headache playing with the SpreadSheet applet, it’s time to blow off a little steam with a game. The ("]file:///G:/Java%20Unleashed/figicon.gif[/img] FIGURE 10.6.



(file:///G:/Java%20Unleashed/049-5g/10/10jun06.gif)

The TicTacToe Java applet. The last applet you’re going to look at is the ("]file:///G:/Java%20Unleashed/figicon.gif[/img] FIGURE 10.7.



(file:///G:/Java%20Unleashed/049-5g/10/10jun07.gif)

The UnderConstruction Java Applet. Although running these demo applets is neat, the real thing to keep in mind is that they all come with complete source code. This means that you can rip them apart and figure out how they work, and then use similar techniques in your own Java programs. The most powerful way to learn is by example, and the demo applets that come with the JDK are great examples of robust Java applets.

("]API Source Code

The final component of the Java Developer’s Kit is the source code for the Java API. That’s right, the JDK comes with the complete source code for all the classes that make up the Java API. Sun isn’t concerned with keeping the internals of Java top secret. They followed the lead of the UNIX world and decided to make Java as available and readily understood as possible. Besides, the real value of Java is not the specific code that makes it work, it’s the idea behind it.

The API source code is automatically installed to your hard drive when you decompress the JDK, but it remains in compressed form. The assumption here is that not everyone is concerned about how the internals of Java are implemented, so why waste the space. However, it is sometimes useful to be able to look under the hood and see how something works. And Java is no exception. So, the API source code comes compressed in a file called src.zip, which is located in the java directory that was created on your hard drive during installation of the JDK. All the classes that make up the Java API are included in this file.

[url=")

The Java Developer’s Kit provides a wealth of information, including the tools essential to Java programming. In this chapter you learned about the different components of the JDK, including tools, applet demos, and the Java API source code. Although you learn more about some of these tools throughout the rest of the book, it’s important to understand what role each tool plays in the development of Java programs. A strong knowledge of the information contained in the Java Developer’s Kit is necessary to become a successful Java developer.

However, you shouldn’t stop with the Java Developer’s Kit. There are many third-party tools available and in the works that supplement the JDK and enable you to put together a more complete Java programming toolkit. The next chapter highlights these tools and describes how they impact Java development now, and what they may mean for the future.

Argonaut
06-11-2005, 03:49 PM
Chapter 11

Development Environments ("]Other tools and environments [/url]

Although the Java Developer’s Kit provides the essential Java development tools required to program in Java, there are a variety of other tools and development environments that are poised to make Java programming much easier. Languages like C and C++ have a rich field of development environments and add-on libraries. Many of the same companies that created these C and C++ environments and add-ons are busily working on Java versions of their already popular tools. Some of these tools are even available now.

In addition to the wave of third-party Java development environments, there are also new Java class libraries that promise to add functionality never before seen on the Web. Using these libraries, you will be able to plug Java classes into your own programs and benefit from Java’s code reuse capabilities. Because Java is truly a cross-platform language, these tools promise to bridge many gaps between different operating systems. What all of this means to you is that your trip through the world of Java development promises to be both dynamic and productive, not to mention fun.

provided with the Java Developer’s Kit are all command-line tools, except for the applet viewer. Even though the applet viewer is invoked from a command line, it provides graphical output and is therefore a graphical tool. Most modern development environments include graphical editors, graphical debuggers, and visual class browsers. Java is too modern a language not to have a modern development interface to match, and Java programmers know this. Fortunately, the software tool developers know this, too. Most of the major players in the development tool business have already announced Java environments. A few companies even have tools in beta and ready for testing.

These third-party development environments span different operating systems and range from C/C++ environment add-ons to entirely new products. The goal here is to let you in on what development environments are out there and how they impact Java programming.

Symantec Espresso

Symantec is the first ("][url=") ("]
Graphical Programming Editor
Visual Editors
Project Manager
Seamless Integration of the JDK Tools
Code Generators
[/list]If you own Symantec C++, you can download Espresso for free. To download Espresso or get the latest news about it, check out Symantec’s Java Web site:

http://www.symantec.com/lit/dev/javaindex.html (http://www.symantec.com/lit/dev/javaindex.html)Graphical Programming Editor

The graphical ("] ("]programming editor in Espresso provides all the features expected in a modern programming editor. It supports full-color syntax and keyword highlighting, along with providing an integrated macro language for extending the editor. The editor also provides navigational features to jump to any Java declaration inside a Java program or the standard Java class libraries.

Visual Editors

Espresso includes[url=") a couple of visual editors for managing the many classes involved in Java programming. The ("]file:///G:/Java%20Unleashed/figicon.gif[/img] FIGURE 11.1.



("]

The Espresso Class Editor. [/size]Espresso also includes a file:///G:/Java%20Unleashed/figicon.gif FIGURE 11.2.



("]Hierarchy Editor for viewing and managing the logical relationships between classes. Figure 11.2 shows what the Hierarchy Editor looks like.

The Espresso Hierarchy Editor. [/size]Project Manager

The Project ("] ("]Manager is a powerful component of Espresso that enables you to organize Java projects more effectively. The Project Manager supports projects within projects so you can keep up with nested libraries and project dependencies. Additionally, different project targets and options can be maintained through the Project Manager.

When you load or create a project in Espresso, the Project Manager launches a background source parser that automatically parses the Java source code and builds a bank of information about the project. This information is in turn used by the Class and Hierarchy Editors to provide browsing and editing support for all the Java classes in the project.

Seamless Integration of the JDK Tools

Espresso seamlessly[url=") integrates the JDK tools into the development environment with graphical support for the Java interpreter, compiler, and debugger. You can modify the command line arguments to these tools through graphical dialog box interfaces.

Code Generators

Espresso provides ("] two code generation tools, which are sometimes referred to as “wizards.” ("][url=")ProjectExpress is a code generation tool that automatically generates Java skeleton applications based on user preferences. ProjectExpress is useful in importing existing Java code into the Espresso environment. Using ProjectExpress, you specify the project type and then add the source files. ProjectExpress then automatically creates the project and loads the classes into Espresso. ("]

AppExpress is another code generation tool that comes with Espresso. AppExpress provides an easy way to create new Java projects that are fully functional from the get go. AppExpress is especially useful for beginning programmers, who will greatly benefit from not having to provide the core functionality necessary to get a Java program up and running. The Java code created by AppExpress is perfectly suited for modification by the user, providing a time saving jumpstart on the development process.

Borland Latte

Borland, ("]one of the largest development tool makers for the PC, has announced its contender in the Java market: Latte. Borland has stated that Latte will be heavily based on the graphical interface made popular in Delphi. Delphi is Borland’s popular object-oriented Pascal development environment. Unlike Espresso, Latte is slated to be a completely new product. Another interesting twist is the fact that Latte is itself being written in Java.

The downside to Latte is that there are no alpha or beta versions available as of yet. Borland says that it will deliver the Latte technology in several stages, with the first commercial release scheduled sometime during the first half of 1996. Borland also says that the Latte technology will focus on the following areas:


Visual Tools
Component-Based Architecture
High Performance Compilation
Scalable, Distributable Database Access
For more information on Borland Latte, check out their Java Web site:

[url="http://www.borland.com/Product/java/java.html"][u]http://www.borland.com/Product/java/java.html ("][url=")

Argonaut
06-11-2005, 03:51 PM
Microsoft Visual C++

Microsoft is the [/url] ("] ("]batch file to Visual C++, select file:///G:/Java%20Unleashed/figicon.gif[/img] FIGURE 11.3.



("]Customize from the Tools menu. Then select the Tools tab on the dialog box. You create a Java Compiler tool entry by first clicking the Add button and then filling out the information requested by the dialog box. First, type in the name of the tool, Java Compiler, and click OK. Then specify jcc.bat as the command in the Command edit box. You need to set the arguments to $(FileName)$(FileExt) in the Arguments edit box. Then set the initial directory to $(FileDir) in the Initial directory edit box. Finally, you need to specify that you want to redirect the output to the Output window, so check the appropriate check box. When you’ve done all this, you should see a dialog box similar to the one shown in Figure 11.3.

Setting up the Java Compiler tool using the Visual C++ Customize dialog box. [/size]You can now use the Java Compiler tool from the Tools menu to compile Java programs within Visual C++. The Java compiler output is even printed in the Output window of Visual C++! I’ll bet you didn’t know Visual C++ could do that.

In addition, you can also setup Visual C++ to run the Java applet viewer as a tool. Simply add appletviewer.exe as a tool just as you did for the compiler, but specify the HTML file you want to use in the Arguments edit box. In the Java demo applets, this HTML file is usually named example1.html. You can use this name to make things easier. The correct settings for the Applet Viewer Visual C++ tool are shown in Figure 11.4.

file:///G:/Java%20Unleashed/figicon.gif FIGURE 11.4.



(file:///G:/Java%20Unleashed/049-5g/11/11jun04.gif)Setting up the Java Applet Viewer using the Visual C++ Customize dialog box.

JavaMaker

The ("]file:///G:/Java%20Unleashed/figicon.gif[/img] FIGURE 11.5.



(file:///G:/Java%20Unleashed/049-5g/11/11jun05.gif)

The JavaMaker development environment. For more information on ("]http://net.info.samsung.co.kr/~hcchoi/javamaker.html[/u] ("]JavaMaker, or to download the latest version, check out the JavaMaker Web site:

Natural Intelligence’s Roaster[/b]

Natural Intelligence ("]http://www.natural.com/pages/products/roaster/[/u] ("]has announced that they have been working on a Macintosh Java development environment based on their popular Quick Code Pro script editor. The Applet Development Kit, also known as Roaster, should be entering a beta release stage at any time. Roaster is touted as having the following features:


A complete integrated development environment
A powerful programming editor
A high-performance compiler
A debugger
A class disassembler
A project manager
Power Macintosh support
The Roaster development environment promises to include multiple clipboards for better organization of code snippets, as well as powerful macro capabilities. The Roaster programming editor will feature context-sensitive font and color highlighting, as well as bookmarks for keeping track of Java code. It will also feature powerful search and replace features, including regular expression matching and batch search capabilities. For more information about Roaster, check out Natural Intelligence’s Roaster Web site:

Metrowerks CodeWarrior[/b]

Metrowerks, the creators of the ("] ("]http://www.metrowerks.com/[/u] ("]Metrowerks Web site:

Silicon Graphics Cosmo[/b]

One of the most interesting ("]
Visual Builder
Graphical Source Debugger
Visual Source Browser
[/list]To find out the latest information about Cosmo Code, or to download a copy to try out, refer to the Cosmo Web ("]http://www.sgi.com/Products/cosmo/[/u] ("]site:

Visual Builder[/b]

The Cosmo ("]Graphical Source Debugger[/b]

Cosmo Code ("]file:///G:/Java%20Unleashed/figicon.gif[/img] FIGURE 11.6.



("]includes its own graphical Java source debugger, which supports the following features:


Graphical display of Java source while debugging
Source-level traps
Call stack display
Data inspection and expression evaluation
Memory functions and explicit garbage collection
Thread controls
Exception handling support
Figure 11.6 shows what the Cosmo Code graphical source debugger looks like.

The Cosmo Code graphical source debugger. [/size]Visual Source Browser

The Cosmo ("]file:///G:/Java%20Unleashed/figicon.gif[/img] FIGURE 11.7.



(file:///G:/Java%20Unleashed/049-5g/11/11jun07.gif)

The Cosmo Code visual source browser. ("]Programming Libraries

Beyond the Java ("]development environments, third-party class libraries make up the other major market for Java tool vendors. Java provides a level of code compatibility and reuse previously unseen in the software world. A tool vendor is capable of creating a single class library in Java that spans all platforms. This opportunity has enormous appeal to tool developers, so expect to see an influx of Java class libraries in the very near future.

In the present, there are a decent amount of freeware type classes to pick and choose from, along with a few commercial class libraries that will be available any day. As far as getting the freely distributed, or noncommercial [url=")classes, check out the ("]http://www.gamelan.com/ ("]Gamelan Web site:

You can get the latest information on these libraries from ("]http://www.dnx.com/dnx/java.html (http://www.dnx.com/dnx/java.html)Ice

Dimension X’s Ice class ("][url=") ("]library is a high-performance 3D rendering package for Java. Ice is composed of two parts: a C library that implements low-level graphics primitives, and a set of Java classes that provide wrappers around the C library. Ice is designed with speed as a primary goal, along with the support of special-purpose 3D graphics hardware. With this in mind, the aim is for Ice to be used to generate interactive 3D graphics on the fly. Ice implements the following features:


Z-buffered polygons, lines, and points
Gouraud shading
Texture mapping
Support for up to eight light sources
Rich set of light and material properties
Fog and depth cueing
Support for 8-, 16-, 24-, and 32-bit frame buffers
8-bit dithering
Alpha blending
Motion-blur and anti-aliasing
Liquid Reality

Liquid Reality is the first set of classes to be built on top of the Ice class library. It is composed of a set of Java classes for building dynamic VRML worlds, and uses Ice to handle rendering the worlds. Liquid Reality really just provides one extension to VRML: when the VRML parser encounters a node type that it doesn’t understand, it queries the HTTP server that served the VRML file and requests a Java class describing the unknown node. Liquid Reality effectively provides VRML with the same kind of extensibility that HotJava provides to HTML documents.

[url=""]Summary ("][url=")

As you’ve learned in this chapter, the Java development scene is in a state of rapid growth. The wide variety of third-party tools available now and on the horizon will certainly change the face of Java programming. Armed with the knowledge of what tools are available and what they can do, you should now have more insight into planning your own Java development.

Additionally, you should realize that the tools mentioned in this chapter are really only the first wave of third-party Java development products. As Java becomes more established, more tool vendors will see the light and take the steps necessary to enter the Java tools marketplace. This is good news for Java users and developers, as competition among tool vendors will result in better development tools and more affordable prices. Just in case it hasn’t occurred to you yet, this is only the beginning!

Now that you know the whole scoop surrounding the different Java development tools, you’re probably ready to learn about the Java language itself. I mean, it’s fun to talk about the technology, but ultimately the Java language is the nuts and bolts that drive everything. The next part of the book, “The Java Language,” covers all the juicy details of the Java language.

Argonaut
06-11-2005, 03:52 PM
Chapter 12

Hello, World! ("]Java language fundamentals [/url]

Java is an object-oriented language. This means that the language is based on the concept of an object. Although a knowledge of object-oriented programming is necessary to put Java to practical use, it isn’t required to understand the fundamentals of the Java language. This chapter focuses on the language and leaves the object-oriented details of Java for Chapter 14, “Classes, Packages, and Interfaces.”

If you already have some experience with another object-oriented language such as C++ or Smalltalk, much of Java will be familiar territory. In fact, Java almost can be considered a new, revamped C++. Because Java is so highly derived from C++, many of the similarities and differences between Java and C++ will be highlighted throughout the next few chapters. Additionally, Appendix D provides a more thorough look at the differences between Java and C++.

This chapter covers the essentials of the Java language, including a few sample programs to help you hit the ground running.

("]
Listing 12.1. The HelloWorld class.
[/list]class HelloWorld { public static void main (String args[]) { System.out.println(“Hello, World!”); }}After compiling the program with the Java compiler (javac), you are ready to run it in the Java interpreter. The Java compiler places the executable output in a file called HelloWorld.class. This naming convention might seem strange considering the fact that most programming languages use the .EXE file extension for executables. Not so in Java! Following the object-oriented nature of Java, all Java programs are stored as Java classes that are created and executed as objects in the Java run-time environment. To run the ("] ("]. args is an array of String objects that represents command-line arguments passed to the class upon execution. Because HelloWorld doesn’t use any command-line arguments, you can ignore the args parameter. You’ll learn a little more about strings later in this chapter.

The main method is called when the HelloWorld class is executed. main consists of a single statement that prints the message “Hello, World!” to the standard output stream, as follows:

System.out.println(“Hello, World!”);This statement might look a little confusing at first because of the nested objects. To help make things clearer, examine the statement from right to left. First notice that the statement ends in a semicolon, which is standard Java syntax that has been borrowed from C/C++. Moving on to the left, you see that the “Hello, World!” string is in parentheses, which means it is a parameter to a function call. The method being called is actually the println method of the out object. The println method is similar to the printf method in C, except that it automatically appends a newline (\n) at the end of the string. The out object is a member variable of the System object that represents the standard output stream. Finally, the System object is a global object in the Java environment that encapsulates system functionality. ("]

That pretty well covers the HelloWorld class—your first Java program. If you got lost a little in the explanation of the HelloWorld class, don’t be too concerned. HelloWorld was presented with no prior explanation of the Java language and was only meant to get your feet wet with Java code. The rest of this chapter focuses on a more structured discussion of the fundamentals of the Java language.

[url=")

When you program to the Java compiler, the compiler parses the text and extracts individual tokens. A token is the smallest element of a program that is meaningful to the compiler. This actually is true for all compilers, not just the Java compiler. These tokens define the structure of the Java language. All of the tokens that comprise Java are known as the Java token set. Java tokens can be broken down into five categories: identifiers, keywords, literals, operators, and separators. The Java compiler also recognizes and subsequently removes comments and whitespaces.

The Java compiler removes all comments and whitespaces while tokenizing the source file. The resulting tokens then are compiled into machine-independent Java bytecode that is capable of being run from within an interpreted Java environment. The bytecode conforms to the hypothetical Java Virtual Machine, which abstracts processor differences into a single virtual processor. For more information on the Java Virtual Machine, check out Chapter 39, “Java’s Virtual Machine, Bytecodes, and More.” Keep in mind that an interpreted Java environment can be either the Java command-line interpreter or a Java-capable browser.

Identifiers

Identifiers are ("] submit a Java ("]tokens that represent names. These names can be assigned to variables, methods, and classes to uniquely identify them to the compiler and give them meaningful names to the programmer. HelloWorld is an identifier that assigns the name HelloWorld to the class residing in the HelloWorld.java source file developed earlier.

Although you can be creative in naming identifiers in Java, there are some limitations. All Java identifiers are case-sensitive and must begin with a letter, an [url=")underscore (_), or a dollar sign ($). Letters include both upper- and lowercase letters. Subsequent identifier characters can include the numbers 0 to 9. The only other limitation to identifier names is that the Java keywords, which are listed in the next section, cannot be used. Table 12.1 contains a list of valid and invalid identifier names.

Table 12.1. Valid and invalid Java identifiers.

ValidInvalid

HelloWorldHello WorldHi_MomHi_Mom!heyDude3 3heyDudetallshortpoundage#age

The Hello World identifier is invalid because it contains a space. The Hi_Mom! identifier is invalid because it contains an exclamation point. The 3heyDude identifier is invalid because it begins with a number. The short identifier is invalid because short is a Java keyword. Finally, the #age identifier is invalid because it begins with the # symbol.

Beyond the mentioned restrictions of naming Java identifiers, there are a few stylistic rules you should follow to make Java programming easier and more consistent. It is standard Java practice to name multiple-word identifiers in lowercase except for the beginning letter of words in the middle of the name. For example, the variable toughGuy is in correct Java style, whereas toughguy, ToughGuy, and TOUGHGUY are all in violation. This rule isn’t etched in stone—it’s just a good idea to follow because most other Java code you run into will follow this style. Another more critical naming issue regards the use of underscore and dollar sign characters at the beginning of identifier names. This is a little risky because many C libraries use the same naming convention for libraries, which can be imported into your Java code. To eliminate the potential problem of name clashing in these instances, it’s better to stay away from the underscore and dollar sign characters at the beginning of your identifier names. A good usage of the underscore character is to separate words where you normally would use a space.

Keywords

Keywords are predefined identifiers ("][url=") reserved by Java for a specific purpose and are used only in a limited, specified manner. Java has a richer set of keywords than C or C++, so if you are learning Java with a C/C++ background, be sure to pay attention to the Java keywords. The following keywords are reserved for Java:

abstract double int superboolean else interface switchbreak extend long synchronizedbyte false native thisbyvalue final new threadsafecase finally null throwcatch float package transientchar for private trueclass goto protected tryconst if public voidcontinue mplements return whiledefault import shortdoinstanceofstatic



Literals

Program elements ("] that are used in an invariant manner are called literals or constants. Literals can be numbers, characters, or strings. Numeric literals include integers, floating-point numbers, and Booleans. Booleans are considered numeric because of the C influence on Java. In C, the Boolean values for true and false are represented by 1 and 0. Character literals always refer to a single Unicode character. Strings, which contain multiple characters, still are considered literals even though they are implemented in Java as objects.

Argonaut
06-11-2005, 03:53 PM
NOTEIf you aren’t familiar with the [/url]Unicode character set, it is a 16-bit character set that replaces the ASCII character set. Because it is 16 bit, there are enough entries to represent many symbols and characters from other languages. Unicode is quickly becoming the standard for modern operating systems.

Integer Literals

Integer literals ("]are the primary literals used in Java programming and come in a few different formats: decimal, hexadecimal, and octal. These formats correspond to the base of the number system used by the literal. Decimal (base 10) literals appear as ordinary numbers with no special notation. Hexadecimal numbers (base 16) appear with a leading 0x or 0X, similar to C/C++. Octal (base 8) numbers appear with a leading 0 in front of the digits. For example, an integer literal for the decimal number 12 is represented in Java as 12 in decimal, 0xC in hexadecimal, and 014 in octal.

Integer literals default to being stored in the int type, which is a signed 32-bit value. If you are working with very large numbers, you can force an integer literal to be stored in the long type by appending an l or L to the end of the number, as in 79L. The long type is a signed 64-bit value.

Floating-Point Literals

Floating-point literals ("][url=") represent decimal numbers with fractional parts, such as 3.142. They can be expressed in either standard or scientific notation, meaning that the number 563.84 also can be expressed as 5.6384e2.

Unlike integer literals, floating-point literals default to the double type, which is a 64-bit value. You have the option of using the smaller 32-bit float type if you know the full 64 bits are not needed. You do this by appending an f or F to the end of the number, such as 5.6384e2f. If you are a stickler for details, you also can explicitly state that you want a double type as the storage unit for your literal, such as 3.142d. Because the default storage for floating-point numbers is double already, this isn’t necessary.

Boolean Literals

Boolean literals ("]are certainly a welcome addition if you are coming from the world of C/C++. In C, there is no Boolean type, and therefore no Boolean literals. The Boolean values True and False are represented by the integer values 1 and 0. Java fixes this problem by providing a boolean type with two possible states: true and false. Not surprisingly, these states are represented in the Java language by the keywords true and false.

Boolean literals are used in Java programming about as often as integer literals because they are present in almost every type of control structure. Any time you need to represent a condition or state with two possible values, a boolean is what you need. You’ll learn a little more about the boolean type later in this chapter. For now, just remember the two Boolean literal values: true and false.

Character Literals

Character literals ("][url=") represent a single Unicode character and appear within a pair of single quotation marks. Similar to C/C++, special characters (control characters and characters that cannot be printed) are represented by a backslash (\) followed by the character code. A good example of a special character is \n, which forces the output to a new line when printed. Table 12.2 shows the special characters supported by Java.

Table 12.2. Special characters ("]String Literals[/b]

String literals ("]Operators[/b]

Operators, also known as operands, specify an evaluation or computation to be performed on a data object or objects. These operands can be literals, variables, or function return types. The operators supported by Java follow:

+-*/%&|^~&&||!<><=>=<<>>>>>=?++- -==+=-=*=/=%=&=|=^=!=<<=>>=>>>=.[]()

Just seeing these operators probably doesn’t help you a lot in determining how to use them. Don’t worry—you’ll learn a lot more about operators and how they are used in the next chapter, “Expressions, Operators, and Control Structures.”

Separators

Separators ("] ("]are used to inform the Java compiler of how things are grouped in the code. For example, items in a list are separated by commas much like lists of items in a sentence. Java separators go far beyond commas, however, as you’ll find out in the next chapter. The separators supported by Java follow:

{};,:

Comments and Whitespace

Earlier you learned [url=")[url=""] ("")that comments and whitespace are removed by the Java compiler during the tokenization of the source code. You might be wondering, “What qualifies as whitespace and how are comments supported?” First, whitespace consists of spaces, tabs, and linefeeds. All occurrences of spaces, tabs, or linefeeds are removed by the Java compiler, as are comments. Comments can be defined in three different ways, as shown in Table 12.3.

Table 12.3. Types of comments supported by Java.

TypeUsage/* comment */ All characters between /* and */ are ignored.// comment All characters after the // up to the end of the line are ignored./** comment */ Same as /* */, except that the comment can be used with the javadoc tool to create automatic documentation.

The first type of comment (/* comment */) should be familiar if you have programmed in C before. All characters inside the /* and */ comment delimiters are ignored by the compiler. Similarly, the second type of comment (// comment) also should be familiar if you have used C++. All characters appearing after the // comment delimiter up to the end of the line are ignored by the compiler. These two comment types are borrowed from C and C++. The final comment type (/** comment */) works in the same fashion as the C-style comment type, with the additional benefit that it can be used with the Java Automatic Documentation tool, javadoc, to create automatic documentation from the source code. The javadoc tool is covered in Chapter 37, “Java Documentation.” The following are a few examples of using the various types of comments:

/* This is a C style comment. */// This is a C++ style comment./** This is a javadoc style comment. */

Argonaut
06-11-2005, 03:55 PM
[/url] ("]Data Types

One of thedeclaration statement for variables follows:

Type Identifier [, Identifier];The declaration statement tells the compiler to set aside memory for a variable of type Type with the name Identifier. The optional bracketed Identifier indicates that you can make multiple declarations of the same type by separating them with commas. Finally, as in all Java statements, the declaration statement ends with a semicolon.

Java data types can be divided into two categories: simple and composite. Simple data types are core types that are not derived from any other types. Integer, floating-point, Boolean, and character types are all simple types. Composite types, on the other hand, are based on simple types, and include strings, arrays, and both classes and interfaces in general. You’ll learn about arrays later in this chapter. Classes and interfaces are covered in Chapter 14, “Classes, Packages, and Interfaces.”

Integer Data Types

Integer ("][url=""] ("]data types are used to represent signed integer numbers. There are four integer types: byte, short, int, and long. Each of these types takes up a different amount of space in memory, as shown in Table 12.4.

Table 12.4. Java integer types.

TypeSizebyte8 bitsshort16 bitsint32 bitslong64 bits

To declare variables using theFloating-Point Data Types[/b]

Floating-point data types are used to represent numbers with fractional parts. There are two floating-point types: float and double. The float type reserves storage for a 32-bit single-precision number and the double type reserves storage for a 64-bit double-precision number.

Declaring floating-point variables ("][url=""] ("]is very similar to declaring integer variables. The following are some examples of floating-point variable declarations:

float temperature;double windSpeed, barometricPressure;boolean Data Type

The boolean[url=") data type is used to store values with one of two states: true or false. You can think of the boolean type as a 1-bit integer value, because 1 bit can have only two possible values: 1 or 0. However, instead of using 1 and 0, you use the Java keywords true and false. true and false aren’t just conveniences in Java; they are actually the only legal Boolean values. This means that you can’t interchangeably use Booleans and integers like in C/C++. To declare a Boolean value, just use the boolean type declaration:

boolean gameOver;Character Data Type

The character ("] ("]data type is used to store single Unicode characters. Because the Unicode character set is composed of 16-bit values, the char data type is stored as a 16-bit unsigned integer. You create variables of type ("]Casting Types[/b]

There will inevitably be times when you need to convert from one data type to another. The process of converting one data type to another is called casting. Casting often is necessary when a function returns a type different than the type you need to perform an operation. For example, the read member function of the standard input stream (System.in) returns an int. You must cast the returned int type to a char type before storing it, as in the following:

char c = (char)System.in.read();The cast is performed by placing the desired type in parentheses to the left of the value to be converted. The System.in.read function call returns an int value, which then is cast to a char because of the (char) cast. The resulting char value is then stored in the char variable c.

The storage size of the types you are attempting to cast is very important. Not all types will safely cast to other types. To understand this, consider the outcome of casting a long to an int. A long is a 64-bit value and an int is a 32-bit value. When casting a long to an int, the compiler chops off the upper 32 bits of the long value so it will fit into the 32-bit int. If the upper 32-bits of the long contain any useful information, it will be lost and the number will change as a result of the cast. Information loss also can occur when casting between different fundamental types, such as integer and floating-point numbers. For example, casting a double to a long would result in the loss of the fractional information, even though both numbers are 64-bit values.

When casting, the destination type should always be equal to or larger in size than the source type. Furthermore, you should pay close attention to casting across fundamental types, such as floating-point and integer types. Table 12.5 lists the casts that are guaranteed to result in no loss of information.

Table 12.5. Casts that result in no loss of information.

From TypeTo Typebyteshort, char, int, long, float, doubleshortint, long, float, doublecharint, long, float, doubleintlong, float, doublelongfloat, doublefloatdouble

[url=")

In Java, source ("] ("]code is broken up into parts separated by opening and closing [url=")curly braces ({ and }). Everything between curly braces is considered a block and exists more or less independently of everything outside of the braces. Blocks aren’t important just from a logical sense—they are required as part of the syntax of the Java language. Without any braces, the compiler would have trouble determining where one section of code ends and the next section begins. From a purely aesthetic viewpoint, it would be very difficult for someone else reading your code to understand what was going on without the braces. For that matter, it wouldn’t be very easy for you to understand your own code without the braces.

Braces are used to group related statements together. You can think of everything between matching braces as being executed as one statement. In fact, from an outer block, that’s exactly what an inner block appears like: a single statement. But what’s an outer block? Glad you asked, because it brings up another important point: Blocks can be hierarchical. One block can contain one or more nested subblocks.

It is standard Java programming style to identify different blocks with indentation. Every time you enter a new block you should indent your source code by a number of spaces, preferably two. When you leave a block you should move back, or deindent, two spaces. This is a fairly established convention in many programming languages. However, it is just a style and is not technically part of the language. The compiler would produce identical output even if you didn’t indent anything. Indentation is used for the programmer, not the compiler; it simply makes the code easier to follow and understand. Following is an example of the proper indentation of blocks in Java:

for (int i = 0; i < 5; i++) { if (i < 3) { System.out.println(i); }}Following is the same code without any block indentations:

for (int i = 0; i < 5; i++) {if (i < 3) {System.out.println(i);}}The first code listing clearly shows the breakdown of program flow through the use of indentation; it is obvious that the if statement is nested within the for loop. The second code listing, on the other hand, provides no visual cues as to the relationship between the blocks of code. Don’t worry if you don’t know anything about if statements and for loops; you’ll learn plenty about them in the next chapter, “Expressions, Operators, and Control Structures.”

The concept of scope is tightly linked to blocks and is very important when working with variables in Java. Scope refers to how sections of a program (blocks) affect the lifetime of variables. Every variable ("] ("] declared in a program has an associated scope, meaning that the variable only is used in that particular part of the program.

Scope is determined by blocks. To better understand blocks, take a look again at the HelloWorld class in Listing 12.1. The HelloWorld class is composed of two blocks. The outer block of the program is the block defining the HelloWorld class:

class HelloWorld {...}Class blocks[url=""] ("]) {... }The inner block is considered to be nested within the outer block of the program. Any variables defined in the inner block are local to that block and are not visible to the outer block; the scope of the variables is defined as the inner block.

To get an even better idea behind the usage of scope and blocks, take a look at the HowdyWorld class in Listing 12.2.


Listing 12.2. The ("][url=""] ("]HowdyWorld class.
class HowdyWorld { public static void main (String args[]) { int i; printMessage(); } public static void printMessage () { int j; System.out.println(“Howdy, World!”); }}The HowdyWorld class contains two methods: main and printMessage. [url=")main should be familiar to you from the HelloWorld class, except in this case it declares an integer variable i and calls the printMessage method. printMessage is a new method that declares an integer variable j and prints the message “Howdy, World!” to the standard output stream, much like the main method did in HelloWorld.

You’ve probably figured out already that HowdyWorld results in basically the same output as HelloWorld, because the call to printMessage results in a single text message being displayed. What you might not see right off is the scope of the integers defined in each method. The integer i defined in main has a scope limited to the body of the main method. The body of main is defined by the curly braces around the method (the method block). Similarly, the integer j has a scope limited to the body of the printMessage method. The importance of the scope of these two variables is that the variables aren’t visible beyond their respective scopes; the HowdyWorld class block knows nothing about the two integers. Furthermore, main doesn’t know anything about j, and printMessage knows nothing about i.

Scope becomes more important when you start nesting blocks of code within other blocks. The GoodbyeWorld class shown in Listing 12.3 is a good example of variables nested within different scopes.

[list]
Listing 12.3. The ("] ("]class GoodbyeWorld { public static void main (String args[]) { int i, j; System.out.println(“Goodbye, World!”); for (i = 0; i < 5; i++) { int k; System.out.println(“Bye!”); } }}The integers i and j have scopes within the main method body. The integer k, however, has a scope limited to the for loop block. Because k’s scope is limited to the for loop block, it cannot be seen outside of that block. On the other hand, i and j still can be seen within the for loop block. What this means is that scoping has a top-down hierarchical effect—variables defined in outer scopes still can be seen and used within nested scopes, but variables defined in nested scopes are limited to those scopes. Incidentally, don’t worry if you aren’t familiar with for loops, you’ll learn all about them in the next chapter, “Expressions, Operators, and Control Structures.”

For more reasons than visibility, it is important to pay attention to the scope of variables when you declare them. Along with determining the visibility of variables, the scope also determines the lifetime of variables. This means that variables actually are destroyed when program execution leaves their scope. Looking at the GoodbyeWorld example again, storage for the integers i and j is allocated when program execution enters the main method. When the for loop block is entered, storage for the integer k is allocated. When program execution leaves the for loop block, the memory for k is freed and the variable destroyed. Similarly, when program execution leaves main, all of the variables in its scope are freed and destroyed (i and j). The concept of variable lifetime and scope becomes even more important when you start dealing with classes. You’ll get a good dose of this in Chapter 14, “Classes, Packages, and Interfaces.”

("]Arrays

An array). The following are a few examples of arrays in Java:

int numbers[];char[] letters;long grid[][];If you are familiar with arrays in another language, you might be puzzled by the absence of a number between the square brackets specifying the number of items in the array. Java doesn’t allow you to specify the size of an empty array when declaring the array. You always must explicitly set the size of the array with the new operator or by assigning a list of items to the array on creation. The new operator is covered in the next chapter, “Expressions, Operators, and Control Structures.”

NOTEIt might seem like a hassle to always have to explicitly set the size of an array with the new operator. The reason for doing this is because Java doesn’t have pointers like C or C++ and therefore doesn’t allow you to just point anywhere in an array and create new items. By handling memory management this way, the bounds checking problems common with C and C++ have been avoided in the Java language.

Another strange thing you might notice about Java arrays is the optional placement of the square brackets in the array declaration. You are allowed to place the square brackets either after the variable type or after the identifier.

The following are a couple of examples of arrays that have been declared and set to a specific size by using the new operator or by assigning a list of items in the array declaration:

char alphabet[] = new char[26];int primes = {7, 11, 13};More complex structures for storing lists of items, such as stacks and hashtables, are also supported by Java. Unlike arrays, these structures are implemented in Java as classes. You’ll get a crash course in some of these other storage mechanisms in Chapter 19, “The Utilities Package.”

[url=""]Strings ("]strings are handled by a special class called String. Even literal strings are managed internally by an instantiation of a String class. An instantiation of a class is simply an object that has been created based on the class description. This method of handling strings is very different from languages like C and C++, where strings are represented simply as an array of characters. The following are a few strings declared using the Java String class:

String message;String name = “Mr. Blonde”;At this point it’s not that important to know the String class inside and out. You’ll learn all the gory details of the String class in Chapter 18, “The Language Package.”

[url=""]Summary ("][url=")

In this chapter, you have taken a look at the core components of the Java language. It is hoped that you now have a better insight about why Java has become popular in such a relatively short time. With vast improvements over the weaknesses of the C and C++ languages—arguably the industry language standards—Java will no doubt become more important in the near future. The language elements covered in this chapter are just the tip of the iceberg when it comes to the benefits of programming in Java.

Now that you are armed with the fundamentals of the Java language, it is hoped that you are ready to press onward and learn more about the Java language. The next chapter, “Expressions, Operators, and Control Structures,94" covers exactly what its title suggests. In it you will learn how to work with and manipulate much of the information you learned about in this chapter. In doing so, you will be able to start writing programs that do a little more than display cute messages on the screen.

Argonaut
06-11-2005, 04:00 PM
Chapter 13

Expressions and Operators ("]Expressions, operators, and control structures [/url]

In the previous chapter you learned about the basic components of a Java program. This chapter focuses on how to use these components to do more useful things. Data types are interesting, but without expressions and operators you can’t do much with them. Even expressions and operators alone are somewhat limited in what they can do. Throw in control structures and you have the ability to do some interesting things.

This chapter covers all of these issues and pulls together many of the missing pieces of the Java programming puzzle you’ve begun to assemble. You’ll not only expand your knowledge of the Java language a great deal, but also learn what it takes to write some more interesting programs.

("][url=")

x = y / 3;In this expression, x and y are variables, 3 is a literal, and = and / are operators. This expression states that the y variable is divided by 3 using the division operator (/), and the result is stored in x using the assignment operator (=). Notice that the expression was described from right to left. This is the standard technique for breaking down and understanding expressions in Java, as well as most other programming languages. This right-to-left evaluation of expressions isn’t just a technique for your own understanding of expressions—it’s how the compiler itself analyzes expressions to generate code.

Operator Precedence

Even with the ("] created variables, you typically want to do something with them. Operators enable you to perform an evaluation or computation on a data object or objects. Operators applied to variables and literals form expressions. An expression can be thought of as a programmatic equation. More formally, an expression is a sequence of one or more data objects (operands) and zero or more operators that produce a result. An example of an expression follows: compiler analyzing expressions right to left, there still are many times when the result of an ("] ()

++ -- ! ~

* / %

+ -

<< >> >>>

< > <= >=

== !=

&

^

&&

||

?:

=

In this list of operators, all of the operators in a particular row have equal precedence. The precedence level of each row decreases from top to bottom. This means that the [] operator has a higher precedence than the * operator, but the same precedence as the () operator.

Expression evaluation still moves from right to left, but only when dealing with operators that have the same precedence. Otherwise, operators with a higher precedence are evaluated before operators with a lower precedence. Knowing this, take a look at the same equation again:

x = 2 * 5 + 12 / 4Before using the right-to-left evaluation of the expression, first look to see if any of the operators have differing precedence. Indeed they do! The ("][url=")multiplication (*) and ("] ("][url=")addition operator (+), and then the ("]Integer Operators[/b]

There are ("]Unary[/b]

Unary ("] ("][url=").Decrement-- ("] ("][url=")Bitwise complement~ ("] ("][url=")operators (++ and --) ("]
Listing 13.1. The ("]class IncDec { public static void main (String args[]) { int x = 8, y = 13; System.out.println(“x = “ + x); System.out.println(“y = “ + y); System.out.println(“++x = “ + ++x); System.out.println(“y++ = “ + y++); System.out.println(“x = “ + x); System.out.println(“y = “ + y); }}The IncDec ("] ("]
Listing 13.2. The ("]class Negation { public static void main (String args[]) { int x = 8; System.out.println(“x = “ + x); int y = -x; System.out.println(“y = “ + y); }}The last Java unary integer operator is the ("][url=")bitwise complement operator (~), which performs a bitwise negation of an integer value. Bitwise negation means that each bit in the number is toggled. In other words, all of the binary zeros become ones and all the binary ones become zeros. Take a look at an example very similar to the one for the negation operator:

x = 8;y = ~x;In this example x is assigned the literal value 8 again, but it is bitwise complemented before being assigned to y. What does this mean? Well, without getting into the details of how integers are stored in memory, it means that all of the bits of the variable x are flipped, yielding a decimal result of -9. This result has to do with the fact that negative numbers are stored in memory using a method known as two’s complement (see the following note). If you’re having trouble believing any of this, try it yourself with the BitwiseComplement program shown in Listing 13.3.

NOTEInteger numbers ("]are stored in memory as a series of binary bits that can each have a value of 0 or 1. A number is considered negative if the highest-order bit in the number is set to 1. Because a bitwise complement flips all the bits in a number, including the high-order bit, the sign of a number is reversed.


Listing 13.3. The BitwiseComplement class.
class BitwiseComplement { public static void main (String args[]) { int x = 8; System.out.println(“x = “ + x); int y = ~x; System.out.println(“y = “ + y); }}

Argonaut
06-11-2005, 04:02 PM
Binary

Binary integer [/url] ("] ("][url=")Subtraction ("] ("][url=")*Division ("] ("][url=")%Bitwise AND ("] ("][url=")|Bitwise XOR ("] ("][url=")<<Right Shift ("] ("][url=")>>>

The addition, subtraction, multiplication, and division ("] ("][url=") ("] ("][url=")operators (+, -, *, and /) all do what you would expect them to. An important thing to note is how the division operator works; because you are dealing with integer operands, the division operator returns an integer divisor. In cases where the division results in a remainder, the modulus operator ("]
Listing 13.4. The ("]class Arithmetic { public static void main (String args[]) { int x = 17, y = 5; System.out.println(“x = “ + x); System.out.println(“y = “ + y); System.out.println(“x + y = “ + (x + y)); System.out.println(“x - y = “ + (x - y)); System.out.println(“x * y = “ + (x * y)); System.out.println(“x / y = “ + (x / y)); System.out.println(“x % y = “ + (x % y)); }}The results of running the Arithmetic program follow:

x = 17y = 5x + y = 22x - y = 12x * y = 85x / y = 3x % y = 2These results shouldn’t surprise you too much. Just notice that the division operation x / y, which boils down to 17 / 5, yields the result 3. Also notice that the modulus operation x % y, which is resolved down to 17 % 5, ends up with a result of 2, which is the remainder of the integer division.

Mathematically, a division by zero results in an infinite result. Because representing infinite numbers is a big problem for computers, division or modulus operations by zero result in an error. To be more specific, a runtime exception is thrown. You’ll learn a lot more about exceptions in Chapter 16, “Exception Handling.”

The bitwise ("] ("][url=")OR, ("]
Listing 13.5. The ("]class Bitwise { public static void main (String args[]) { int x = 5, y = 6; System.out.println(“x = “ + x); System.out.println(“y = “ + y); System.out.println(“x & y = “ + (x & y)); System.out.println(“x | y = “ + (x | y)); System.out.println(“x ^ y = “ + (x ^ y)); }}The output of running Bitwise follows:

x = 5y = 6x & y = 4x | y = 7x ^ y = 3To understand this output, you must first understand the binary equivalents of each decimal number. In Bitwise, the variables x and y are set to 5 and 6, which correspond to the binary numbers 0101 and 0110. The bitwise AND operation compares each bit of each number to see if they are the same. It then sets the resulting bit to 1 if both bits being compared are 1, and 0 otherwise. The result of the bitwise AND operation on these two numbers is 0100 in binary, or decimal 4. The same logic is used for both of the other operators, except that the rules for comparing the bits are different. The bitwise OR operator sets the resulting bit to 1 if either of the bits being compared is 1. For these numbers, the result is 0111 binary, or 7 decimal. Finally, the bitwise XOR operator sets resulting bits to 1 if exactly one of the bits being compared is 1, and 0 otherwise. For these numbers, the result is 0011 binary, or 3 decimal.

The left-shift, right-shift, and zero-fill-right-shift ("] ("][url=") ("]
Listing 13.6. The ("]class Shift { public static void main (String args[]) { int x = 7; System.out.println(“x = “ + x); System.out.println(“x >> 2 = “ + (x >> 2)); System.out.println(“x << 1 = “ + (x << 1)); System.out.println(“x >>> 1 = “ + (x >>> 1)); }}The output of Shift follows:

x = 7x >> 2 = 1x << 1 = 14x >>> 1 = 3The number being shifted in this case is the decimal 7, which is represented in binary as 0111. The first right-shift operation shifts the bits two places to the right, resulting in the binary number 0001, or decimal 1. The next operation, a left shift, shifts the bits one place to the left, resulting in the binary number 1110, or decimal 14. Finally, the last operation is a zero-fill right shift, which shifts the bits 1 place to the right, resulting in the binary number 0011, or decimal 3. Pretty simple, huh? And you probably thought it was difficult working with integers at the bit level!

Based on these examples, you may be wondering what the difference is between the right-shift (>>) and zero-fill-right-shift operators (>>>). ("] ("][url=") ("][url=")The right-shift operator appears to shift zeros into the leftmost bits, just like the zero-fill-right-shift operator, right? Well, when dealing with positive numbers, there is no difference between the two operators; they both shift zeros into the upper bits of a number. The difference arises when you start shifting negative numbers. Remember that negative numbers have the high-order bit set to 1. The right-shift operator preserves the high-order bit and effectively shifts the lower 31 bits to the right. This behavior yields results for negative numbers similar to those for positive numbers. That is, -8 shifted right by one will result in -4. The zero-fill-right-shift operator, on the other hand, shifts zeros into all the upper bits, including the high-order bit. When this shifting is applied to negative numbers, the high-order bit becomes 0 and the number becomes positive.

Relational

Argonaut
06-11-2005, 04:04 PM
The last [/url] ("] ("] ("][url=")<=Greater Than Or Equal To ("] ("][url=")==Not Equal To ("]
Listing 13.7. The ("]class Relational { public static void main (String args[]) { int x = 7, y = 11, z = 11; System.out.println(“x = “ + x); System.out.println(“y = “ + y); System.out.println(“z = “ + z); System.out.println(“x < y = “ + (x < y)); System.out.println(“x > z = “ + (x > z)); System.out.println(“y <= z = “ + (y <= z)); System.out.println(“x >= y = “ + (x >= y)); System.out.println(“y == z = “ + (y == z)); System.out.println(“x != y = “ + (x != z)); }}The output of running Relational follows:

x = 7y = 11z = 11x < y = truex > z = falsey <= z = truex >= y = falsey == z = truex != y = trueAs you can see, the println method is smart enough to print Boolean results correctly as true and false.

Floating-Point Operators

Similar to integer ("]Unary[/b]

The unary ("] ("][url=")++Decrement ("]Binary[/b]

The binary ("] ("][url=")Subtraction ("] ("][url=")*Division/ ("] ("]
Listing 13.8. The ("]class FloatMath { public static void main (String args[]) { float x = 23.5F, y = 7.3F; System.out.println(“x = “ + x); System.out.println(“y = “ + y); System.out.println(“x + y = “ + (x + y)); System.out.println(“x - y = “ + (x - y)); System.out.println(“x * y = “ + (x * y)); System.out.println(“x / y = “ + (x / y)); System.out.println(“x % y = “ + (x % y)); }}The output of FloatMath follows:

x = 23.5y = 7.3x + y = 30.8x - y = 16.2x * y = 171.55x / y = 3.21918x % y = 1.6The first four operations no doubt performed as you expected, taking the two floating-point operands and yielding a floating-point result. The final modulus operation determined that 7.3 divides into 23.5 an integral amount of 3 times, leaving a remaining result of 1.6.

Relational

The ("]Boolean Operators[/b]

Boolean operators act on Boolean types and return a Boolean result. The Boolean operators are listed in Table 13.6. ("][url=")

Table 13.6. The Boolean operators.

DescriptionOperator

Evaluation AND ("] ("][url=")|Evaluation XOR ("] ("][url=")&&Logical OR D="I228" NAME="I228"> ||Negation ("]!Equal To ("][url=")==Not Equal To ("]!=Conditional ("][url=")?:





The evaluation operators ("] ("][url=") ("](&, |, and ^) evaluate both sides of an expression before determining the result. The logical operators (&& and ||) avoid the right-side evaluation of the expression if it is not needed. To better understand the difference between these operators, take a look at the following two expressions:

boolean result = isValid & (Count > 10);boolean result = isValid && (Count > 10);The first expression uses the evaluation AND ("][url=")operator (&) to make an assignment. In this case, both sides of the expression always are evaluated, regardless of the values of the variables involved. In the second example, the logical AND operator (&&) is used. This time, the isValid Boolean value is first checked. If it is false, the right side of the expression is ignored and the assignment is made. This is more efficient because a false value on the left side of the expression provides enough information to determine the false outcome.

Although the logical operators are more efficient, there still may be times when you want to use the evaluation operators to ensure that the entire expression is evaluated. The following code shows how the evaluation AND operator is necessary for the complete evaluation of an expression:

while ((++x < 10) && (++y < 15)) { System.out.println(x); System.out.println(y);}In this example, the second expression (++y > 15) is evaluated after the last pass through the loop because of the evaluation AND operator. If the logical AND operator had been used, the second expression would not have been evaluated and y would not have been incremented after the last time around.

The Boolean operators negation, equal-to, and not-equal-to ("] ("][url=") ("] (!, ==, and !=) perform exactly as you might expect. The negation operator toggles the value of a Boolean from false to true or from true to false, depending on the original value. The equal-to operator simply determines whether two Boolean values are equal (both true or both false). Similarly, the not-equal-to operator determines whether two Boolean operands are unequal.

The conditional Boolean operator ("][url=") (?:) is the most unique of the Boolean operators, and is worth a closer look. This operator also is known as the ternary operator because it takes three items: a condition and two expressions. The syntax for the conditional operator follows:

Condition ? Expression1 : Expression2The Condition, which itself is a Boolean, is first evaluated to determine whether it is true or false. If Condition evaluates into a true result, Expression1 is evaluated. If Condition ends up being false, Expression2 is evaluated. To get a better feel for the conditional operator, check out the Conditional program in Listing 13.9.


Listing 13.9. The ("][url=")Conditional class.
class Conditional { public static void main (String args[]) { int x = 0; boolean isEven = false; System.out.println(“x = “ + x); x = isEven ? 4 : 7; System.out.println(“x = “ + x); }}The results of the Conditional program follow:

x = 0x = 7The integer variable x is first assigned a value of 0. The Boolean variable isEven is assigned a value of false. Using the conditional operator, the value of isEven is checked. Because it is false, the second expression of the conditional is used, which results in the value 7 being assigned to x.

String Operators

Along with integers, ("]floating-point numbers, and Booleans, strings also can be manipulated with operators. Actually, there is only one string operator: the concatenation operator (+). The concatenation operator for strings works very similarly to the addition operator for numbers—it adds strings together. The concatenation operator is demonstrated in the Concatenation program shown in Listing 13.10.


Listing 13.10. The ("][url=")[url=""] ("")Concatenation class.
class Concatenation { public static void main (String args[]) { String firstHalf = “What “ + “did “; String secondHalf = “you “ + “say?”; System.out.println(firstHalf + secondHalf); }}The output of Concatenation follows:

What did you say?In the Concatenation program, literal strings are concatenated to make assignments to the two string variables, firstHalf and secondHalf, upon creation. The two string variables are then concatenated within the call to the println method