Previous Page TOC Next Page


— 2 —
Using Java

Java is one of the most hyped products of the last decade, with good reason. It offers capabilities that have been dreamed of but unrealized for years. However, enthusiasm for Java should be tempered with a realization of its limitations. These limitations restrict Java's usefulness to certain types of applications.

This chapter explores the capabilities and restrictions of Java. This chapter first discusses the frontiers that Java applets open up to the Web, like sound and interactivity. Next, this chapter points out the restrictions that Java places on applets. Finally, this chapter discusses the capabilities of standalone Java applications and the future of Java.

Applets: Enhancing the Web

Sun realized early on in the development of the World Wide Web that eventually people would want to expand the capabilities of Web pages beyond form-based interaction with CGI scripts. Java was a perfect fit for this type of expansion. Because Java was originally designed to work on many different types of hardware, it was platform-independent; likewise, because Java was meant to run on consumer appliances, it was relatively small, which was a major advantage on the Internet where bandwidth was relatively limited.

To exploit this market, Sun created in essence a new type of program that can be created in Java: an applet. Applets are created to run in Web pages and thus can leverage Web browsers for a great deal of functionality not available to standalone applications. In Java, applets and applications are completely different things—this point is important and often misunderstood. An applet can only run in a Web browser(or in a special program meant to run applets like the appletviewer), but a Java application can run by itself on the operating system. For example, an applet could be a small window that displays current stock data and gives a price when users enter sample amounts of the stock to buy. An application could be an entire portfolio manager that keeps personal histories of many stocks and the current value of a person's holdings.

In designing the specification for applets, Sun opened up Web pages to a great deal of the functionality normally associated with standalone applications. Except for a few restrictions that are discussed later, you can build an applet containing most of the features users expect from commercial applications.

Adding Sound to Your Web Pages

Users of the WWW have clamored for the capability to add sounds to Web pages for a long time. Many Web pages have offered sound files that users could download and then play on their local machines. Unfortunately, because a variety of sound formats are available, this process isn't always a viable method of adding sound. For example, Real Audio is a company that has begun to add sound capabilities to the Web using proprietary formats and sound players. WAV files are a popular sound format, as are AU files.

The only sound format that Java applets are currently able to use is the AU format, which was developed by Sun. This will likely change in the next major revision of Java. In the meantime, most popular sound editing applications allow files to be saved as in the AU format.

Java provides a standard way to play sounds in any applet. The fact that Java applets are actual programs and not just HTML tags provides a great deal of flexibility in how sounds are played. For instance, not only can an applet play a sound when a user enters a Web page, it can also play a series of sounds associated with pictures. (Chapter 13 explains how to construct such an applet.)

Adding Animation and Graphics

One of the biggest complaints about Web pages is that they just sit there until the user does something. Server-push animation is one solution to this problem, but it puts a huge strain on the server because every frame of the animation must be downloaded again and again to the browser. In addition, when the Net is running slow (as it too often does), server-push animation causes the animations to crawl along at a snail's pace. In fact, the experience of watching a server-push animation on a slow link can be approximated by staring at Figure 2.1 for 15 seconds and then blinking.

Figure 2.1. The Netscape server-push animation: slow and not smooth.

Java provides a much better solution. Instead of the server doing all the work and taxing the network when showing an animation, a Java applet can download all the frames of the animation once and then display them (see Figure 2.2). With this approach, the server only has to provide the Java applet and one copy of the frames, and then the animation applet can run for hours with no further contact with the server.

Figure 2.2. The Sun Java logo animation provides smooth continuous animation with no load on the server.

Moreover, Java has the built-in capability to draw graphics. All sorts of shapes can be drawn easily: triangles, circles, rectangles, and polygons to name a few (see Figure 2.3). By using these routines to create graphics and animations, you can include a huge amount of interesting graphics in just a few kilobytes of Java code, creating an impressive applet that doesn't require much download time.

Figure 2.3. A sample applet with graphics generated by Java.

Interactivity

Adding animations and sounds to a Web page are both wonderful examples of what Java can do, but Java really shines when it comes to interacting with a user. Drawing an image is one thing, but allowing the user to click different sections of it and have the applet respond is quite another.

Java can accept both mouse and keyboard input; the decision on how to use this capability is completely up to the programmer of the applet. Suppose you were working on a calculator applet, and you had a keypad on the screen that users could click to enter numbers. Users might also want to be able to type numbers from their keyboards. No problem. Applets can accept input from the mouse and keyboard; Java applets can be as flexible as you need them to be.

The capability to take input from the user and respond to it is what makes Java so powerful. This capability opens up a whole new world of Web possibilities, from games to interactive showrooms to almost anything imaginable.

A Real User Interface

Although many simple applications won't require it, Java can create the kind of user interfaces that people are familiar with by using the Abstract Windows Toolkit or AWT. All the standard components are available: buttons, checkboxes, lists, scrollbars, and so forth. The AWT will be discussed in detail in Chapter 12, "Building a User Interface."

Unfortunately, programming user interfaces is not a easy task, and the AWT reflects this fact. However, the AWT is certainly manageable for programming relatively simple interfaces, and many of the harder concepts and code can be easily transferred from program to program. Chapter 11 talks more about developing user interfaces.

Suppose you are doing a lot of Web design, and you want to look at different colors to add to your pages. Web browsers let you specify the background color of pages and the color of active and visited links so that you can have more control over a page's design. Unfortunately, you can't just say that you want something to be green. To specify a color in most browsers, you need to know the RGB values, or even the hexadecimal value, of a color. Suppose you want an applet that enables users to see how a certain RGB color appears inside their Web browser. It would make sense to use sliders to select from a range of colors and to have text fields that let the user enter the components of the color directly (see Figure 2.4).

Figure 2.4. The ColorPicker applet.

One of the great strengths of Java is that applets written in it do not have an instantly recognizable "Java" look. Instead, all the components used in Java take on the look of the operating system the applet is currently running on. For example, look at the Spreadsheet applet supplied with the Java Developer's Kit. Figure 2.5 shows the Macintosh version, with a typical Macintosh look and feel. Figure 2.6 shows the same applet running under Windows 95. The applets function the same, but they provide the user of each operating system with a look and feel consistent with the platform the applet is running on.

Figure 2.5. The Spreadsheet applet running on a Macintosh.

Figure 2.6. The same Spreadsheet applet running under Windows 95.

Restrictions

Java has its downsides. It is impossible to be all things to all people, and for many factors, mostly to do with security, Java applets have a few serious limitations.

No Access to Files

In version 1.0 of Java, applets don't have any access to files on the user's machine. Because of this restriction, applets cannot save any information permanently to the local machine. Although this restriction seriously limits the functionality of applets, it is quite understandable given the possibilities of what rogue applets would be capable of if they could write to hard drives.

For example, if Java applets could write file information, they could be used to spread viruses by writing the virus directly to a user's machine over the Internet, or marketers could use them to get information about what software you use. Fortunately, Java was designed to prevent these events by limiting the access provided to the file system in an effort to make Java safe for everyone.

This situation may change in the future to open up applets to a more complex area. A word processor applet is often given as an example of an eventual large Java applet. For this applet, it would be highly desirable (if not essential) to have some form of local file access in order to save and open documents.

Applets Have No Memory

Because of the lack of access to files, applets forget everything each time they are reloaded. As a result, there are no built-in ways to keep configuration information for each user of an applet; everyone gets the same applet in the same state when it's run off a Web page. Any information that needs to be kept from session to session must be stored on the server and downloaded to the applet each time it is run. This transfer of information also means that some type of user validation needs to occur between the browser and the server. Because each applet can't be configured for a different user, applets wouldn't be very useful as newsreaders, mail programs, or any other kind of program that needs to be configured for an individual user. But they could still be useful for programs that share a configuration for many users, such as a sales or inventory applet.

Although this problem isn't drastic, the lack of access to files needs to be considered early on in developing any substantial applets. Once an applet begins to have user interaction, the complexity begins to grow immediately, and concerns such as configuration and file access need to be addressed. Workarounds certainly exist, but keep in mind that they will need to be handled by the applet programmers themselves. Chapter 10 deals with configuring applets, and Chapter 11 explains user interfaces. Applets are still quite flexible in spite of these restrictions. Java can still perform a wide variety of tasks, and careful planning to work out details of configuration and access pays off in saved time in the long run.

Speed

One of Java's greatest strengths is the Java Virtual Machine(JVM), which was discussed in Chapter 1. When a Java applet is compiled, it is translated into a binary file for a generic microprocessor (which means that the code is never platform-specific). When the applet is later run in a Java-enabled browser, the JVM interprets the applet code instruction by instruction and executes it.

The price of platform independence is speed. You can expect a Java applet to run 10 to 20 times slower than many equivalent programs on any given platform. Most programs you use are specifically compiled for that particular operating system or computer. Languages such as C allow programs to be optimized for speed on a per platform basis, so although you can't run the same program on a Macintosh that you can on a Windows 95 machine, you do gain speed on the platform the software was written for. Because Java applets aren't optimized for speed on each platform, they will generally run slower than an application that was written in a language like C. As a result, Java's usefulness is limited in speed-dependent applications like intensive graphics processing, large games, or any type of serious numeric processing.

This lack of speed might seem like a major drawback at first, but Java applets can prove quite useful in spite of their slowness. For example, Java applets can gain perceived speed by being smaller and more focused in the tasks they perform. Users often equate efficiency with speed and might choose a Java applet that gets the job done over a large applet bloated with features.

Overall though, it makes sense when first considering an applet you may want to write to think about whether it fits well into the context of what Java offers. For instance, it might make sense to embed an applet that allows the user to enter customer information into a database. However, you would not want to write a complex customer analysis tool that assembled marketing profiles and sales statistics in Java.

Limitations of Connections

One of the important things to keep in mind about standards like Java is that not only do you need to be concerned about restrictions imposed by the standard itself, but you also need to be concerned about restrictions imposed by various implementations of that standard. For example, in the Netscape Navigator, an applet can only open up a communications connection, or socket, back to the host that the applet was downloaded from. This setup prevents malicious applets from doing all sorts of nasty things such as trying to break into machines on your network by using your machine as a gateway or sending bogus mail to people that when traced back can be proven to come from your machine.

Unfortunately, this setup also means that some communications that you may find useful are not allowed, such as an interface to a multiuser 3-D environment or an embedded terminal applet. Keep in mind that these types of applets are possible, but the Web server and the actual game/chat/whatever server must be the same machine. For example, if you wanted to write a Java applet that functioned as an interface for Internet Relay Chat (IRC) (a very popular interactive chat application available on the Internet), you would not be able to contact any IRC server on the Internet (as current IRC programs do). Instead, you would have to contact an IRC server that was running on the same machine people downloaded your applet from. As you can see, that restriction doesn't prevent you from writing such an applet, but it does limit its functionality. Keep in mind that this restriction isn't a limitation of Java per se, but it is a restriction imposed by Netscape.

Security on the Net

Most of Java's limitations center around the justifiable concern for security on the Net. The ability to run programs over the Net is an extremely attractive proposition, but if Java were to get an early reputation for being an ideal way to distribute viruses and break security on remote machines, its popularity would decrease quickly.

In this vein, Java is, if anything, a bit paranoid in what it will and won't allow. It would be reasonable, for example, to allow users to grant permission to applets to contact outside hosts. For example, if you had a chat applet, you might want to give users the option of connecting to an outside chat server. Java could just ask permission before connecting to remote hosts as a matter of protocol, which would have the same effect as limiting the hosts Java can contact. However, adding such features would weaken the security slightly, and wherever there is a way to break security, someone will try. Providing such features would also involve working out a number of different implementations of security to deal with the variety of communications protocols and Web browsers available on the Net.

There's never any guarantee that something is perfectly safe, but the general consensus is that Java strikes a pretty good balance between paranoid restrictions and total freedom by allowing the implementations to determine just how much access the applet should have to other machines.

Whenever the issue of allowing users to download executable files to their local machines is discussed, the issue of viruses comes up. In the past, viruses have spread from pre-packaged software, from bulletin boards offering software for users to download, and from users exchanging software. So the transmission of viruses is a valid concern when discussing the downloading of Java applets off the Web. As stated earlier, Java's developers decided that the best way to deal with this issue was to prevent applets from accessing the file system on users' machines. This decision means that Java applets are completely incapable of transferring a virus to your machine. Yes, this decision affects the power of applets and their flexibility, but faced with the choice of adding flexibility or releasing a product that could spread computer viruses around the world willy-nilly, the Sun engineers opted for the security, and users are thankful. Overall, Java provides robust security while still allowing for innovation—a combination that serves the user community best.

Standalone Applications

Although Java's capability to produce applets has gotten almost all the attention (and is of course the main focus of this book), Java has many more capabilities. An applet is just one type of program that Java can generate. Java can just as easily generate a standalone application that doesn't require a browser to function but is run on the machine like any other program.

The differences between applets and applications are more philosophical than physical. For example, contrast a spreadsheet with a loan calculator. A loan calculator is essentially a spreadsheet with a very specific function: to calculate the total costs of a loan and monthly payments. You can look at these two programs as an applet (the loan calculator) and an application (the full spreadsheet). From a programming standpoint, the loan calculator is significantly easier to program because it has a predefined, small number of functions, it requires less functionality, and it has a smaller user interface. The finished versions of both programs will have drastic differences in memory requirements. The spreadsheet application will require more RAM to operate because it can perform more tasks. Whereas the spreadsheet might require a megabyte (or more) of RAM, the loan calculator might only require 100K of RAM because it has a fixed number of elements and performs limited functions. Size is also important: a full spreadsheet application might take up 1M or more, and a loan calculator might take up only 350 to 500K. When you are waiting for both of these programs to download over the Web, the advantage of a smaller size program is obvious. So if you are adding a well-defined service to a Web page, applets offer many advantages over applications. Although applets might not offer the same level of flexibility, they do allow the integration of specialized functions into a very distributable medium, the World Wide Web.

Because an application runs outside of a Web browser, it has pretty much complete access to the local system. It can read and write files and connect to any desired host. If you want, you can even write a Web HTTP server in Java—Java is that general of a programming language.

Native methods are a built-in way to get around Java being relatively slow. If you find a portion of your program is running too slowly, you can use Native Methods to translate it to C and then compile and access it directly from your Java program. You can expect that portion of your program to speed up by 10 to 20 times after this procedure. Because Java is considerably easier to program in than C, this feature is a tremendous advantage. You convert only the parts of the program that absolutely require the speed. Although native methods would be a great way to speed up an applet, there is not currently a way to have a browser automatically download them, mainly for security reasons (because the code would be native to the machine, it could contain viruses that Java would have no way of detecting).

The ability to produce applications may not seem to be a big deal right now, but it's nice to know that if an applet grows to be a size that you feel it would make a worthwhile application, you can convert it without having to start from scratch or rewrite it in another language.

The Future of Java

Because Java is a relatively new addition to the Internet, you may be wondering what the future of Java might have in store. Now that you have an understanding of what Java can and cannot do, the following sections provide a glimpse at what the future has in store for Java.

New Development Tools

Java is currently in the 1.0 release. Many enhancements and improvements must be made before Java can be considered a major development platform. Many programming languages begin as text-based languages. You write the programs using plain ASCII text, and the programs run in a text mode, with text-based interfaces and text output. From this point, graphical user interfaces (GUIs) are often added. GUIs allow a more natural interaction with programs, making them more user-friendly and accessible to the average computer user.

Just as you would add a GUI to make your programs more friendly, many programming languages have begun to add GUIs as well. If you have ever done any development with a package such as Delphi or Visual Basic, you have probably seen this kind of programming interface. These graphics-based programming interfaces are called Integrated Development Environments (IDEs). For any programming language, an IDE can help make programming easier. To understand how an IDE might improve Java, look at the current text-based methods for programming with Java:

  1. You write a program using a text editor of your choice. Some editors are better at handling the nuances of code than others, but you manage to get your code finished.

  2. You run the code through the Java compiler. If you were working in a dream world, the code would compile without problems, but in reality, the compiler spits out a list of bugs in your code. You have to either write down, print out, or otherwise keep track of the bugs, and go back into your text editor to fix them.

  3. Having fixed the bugs (or so you think), you compile the code again. If everything has been corrected, you are ready to run the code. If not, repeat Step 2.

  4. You run the code. There aren't any bugs, but things don't run exactly the way you had planned. Go back to Step 1.

As you can see, this process can become rather involved and quite long. With an IDE, the process might be like the following:

  1. Using a Java editor you create your code, and then click a Compile button.

  2. The compiler highlights possible errors in your code, and you can fix them in your editing window. Each time, you can try compiling without ever leaving the editor.

  3. When the bugs are fixed, the IDE automatically runs the code for you. Now you can see how your applet is running, and fix errors in the edit window.

As you can see, an IDE can provide valuable programming tools, such as an editor with features designed around the language you are using and a built-in compiler and run-time environment, so you can have all of your programming components available at once. IDEs often have many debugging features and some advanced features like automatic backups and version tracking. Two good examples of current IDEs are Symantec's Café (see Figure 2.7) and JavaWeb (see Figure 2.8).

Figure 2.7. Symantec's Café An Integrated Development Environment for Java extends the existing C++ package.

Currently Java development is all done at the command line. There is not a specialized Java editor, and the appletviewer is not a full-featured run-time environment. But several beta Java IDEs are available on the Web now, including the following:

Figure 2.8. The JavaWeb Integrated Development Environment is based on a Web interface that allows you to interact with and code Java through your Web browser.

In addition to these early IDEs, many large development companies have licensed Java from Sun and are making plans to incorporate Java into their own development environments. Some of these companies, such as Borland and MetroWerks, have a great deal of experience in development tools, and some great Java products are likely to be available in the near future.

Increasing Speed

Because the bytecode for Java is not machine-specific, Java often encounters problems with speed. The code is not optimized for any specific platform, so performance suffers across the board. Consequently, Sun has already begun to plan a run-time compiler to help optimize Java's speed.

The run-time compiler, called the Just-in-Time Compiler, basically allows you to download Java code and recompile it using native code on the machine you are using to increase speed. However, the JIT Compiler does have a major drawback: compile time. Because the JIT is a compiler, it takes time to actually compile the code. For smaller applets, this amount of time might not be a big deal, but for complicated applets, the compile time might be significant. The recompiled version of the software might execute faster, but the increased time it takes to compile the program can be a significant trade-off.

The Just-in-Time Compiler is not the only new compiler in the works. Several other companies are hard at work producing compilers of their own. Some of these compilers will be geared at optimizing code like JIT, and others may even be server-side compilers that compile optimized code before downloading.

Integrating with Other Applications

Another method for gaining speed discussed in earlier in this chapter is native methods. Using a C or C++ native method in conjunction with an applet can greatly increase the speed of applets. Access to native methods or cross-compilers might be available in the future to help you increase the performance of your applets even more.

You could even string together collections of applets to create larger and more detailed applets or applications. With some scripting tools such as JavaScript, you could squeeze even more mileage out of applets by using JavaScript to glue them together to produce a larger, more complete program without having to write more Java code.

Automatic Applet Updates

One of the most difficult issues facing companies that have software deployed throughout their organizations is keeping the versions of that software constant throughout the organization. This task is not easy because it requires that a new version of the software be downloaded on a regular basis. If some people forget to update their software regularly, the situation can become confusing.

Java applets circumvent this problem by being downloaded over the network automatically every time they need to be run. The applet can be updated on the server whenever needed, and when users execute the applet, they will automatically get the latest version.

JavaScript

One of the most promising advances in Java looming on the horizon is JavaScript. JavaScript had its humble beginnings at Netscape as LiveScript, a language designed to bring scripting to the World Wide Web. Today, much of JavaScript is still based on LiveScript, and the ability to script applets is still in the future. But the promise of scriptable applets is very appealing to many Web designers.

The idea behind the JavaScript scripting language is the ability to manipulate Web objects and Java objects without using a high-level programming language. JavaScript would enable users to customize applets and even control how applets function or the environment in which they execute. JavaScript could also be a powerful tool for scripting Java objects together rather than using them in code.

Well-designed objects can function as applet components, and JavaScript could allow these components to be combined without programming. This capability would be very appealing because programming in Java is by no means trivial, and JavaScript has been designed from the ground up to be programmable by the average user. Thus, an applet that allows a color to be chosen from a list could be a part of a larger script that implements an online store.

In its current stages, JavaScript is limited to scripting various Web and browser functions. Making applets work with JavaScript will involve development on both sides, Java and JavaScript. JavaScript will need to have accepted methods for controlling and customizing applets. The Java language will also need to incorporate methods for passing control and communicating with JavaScript scripts. The promise of flexibility and ease of use will drive developers towards these goals, but implementation might have to wait until later versions.

Cosmo

Anyone creating or using Java applets will notice that the graphics capabilities of Java, while commendable, are somewhat limited. Java includes a number of graphics methods that allow you to create some interesting graphics, but in today's multimedia world, many potential uses for Java would be much easier to program with a expanded graphics toolkit. Cosmo is designed to be that toolkit.

In order to produce a higher level of graphics using Java, Sun has embarked on a partnership with Silicon Graphics (SGI), the industry's graphics specialists. The project has been named Cosmo and promises to include some interesting developments in Java and high-performance, 3-D graphics.

Cosmo includes special 3-D libraries, a motion engine, and media libraries designed to add video, audio, and other multimedia functions to Java applets. Unfortunately, use of Cosmo is currently limited to the SGI platform, but development in this area of Java is sure to continue. Cosmo is currently available in a beta version from http://www.sgi.com/Products/cosmo/code/.

The Java "Real" Machine?

All the possible advances mentioned so far have been based around software enhancements. However, Java was originally conceived to be integrated into consumer electronics, and Sun is still pursuing some of those options.

On the hardware side of Java development is JavaChips. These are a series of chips that are based on the Sparc line already produced by Sun. The JavaChips will be modified versions of Sparc chips designed to run code from the Java Virtual Machine. Sun has already begun showing demonstrations of the chips and potential products and plans a variety of hardware uses for Java.

Sun is planning to release JavaChips in three versions, each customized for a different application: a low-end chip for consumer electronics, a midrange chip for handheld devices, and a high-end chip for desktop machines. Sun has also shown prototypes of Java terminals. These mini-machines would have ethernet cards, monitors, and keyboards to enable you to interact with Java programs over a local-area network or the Internet. The advantage of using a Java terminal would be increased speed and much lower cost than traditional desktop computers. Sun is competing with other companies racing to cash in on a potential Net terminal market, so the future of Java might just include some new computing machinery.

Summary

This chapter has shown you the promises of Java. You've looked at how Java stands to change the way people use the World Wide Web. You've seen how Java applets can enhance Web pages with new interactive design and increased functionality.

You've also looked at the structure of Java applets from a user's point of view. This chapter covered the differences between applets designed for functionality and applications designed for flexibility. You've also looked at some of the security issues surrounding Java and the applets and have seen some of the things that lurk on the Java horizon.

Now it's time to get to the nitty-gritty Java world. The following chapters take you through all of the essential components you'll need to start adding applets to your Web pages. The discussion of applets and their uses continues in the next few chapters, which also talk about the methods for using applets and various Java browsers available on the Net. The following chapters also talk about some applets available on the Web and point you to some Java resources. Chapter 6 examines design issues, and Chapter 7 deals with the Java Developer's Kit. Then you'll get into Java programming. Before you know it, you'll be creating your own Java applets!

Previous Page TOC Next Page