Skip to main content.

Web Based Programming Tutorials


Java Unleashed Second Edition

Chapter 1 -- Introducing Java

Chapter 1

Introducing Java

by Rogers Cadenhead


This represents the end result of nearly 15 years of trying to come up with a better programming language and environment for building simpler and more reliable software.
-Sun Microsystems cofounder Bill Joy

A year ago, Java was just an island and one of the cooler synonyms for coffee (along with joe and demitasse). But anyone who has come within five feet of a Web page, computer magazine, or business newspaper in 1996 has heard of Java, the programming language from Sun Microsystems.

If you haven't been initiated into the Secret Personhood of Java yet, you might be wondering what all the fuss is about. It's just a programming language, for cryin' out loud! It's not some kind of cross-dressing basketball player, Latino dance craze, or teeth whitener.

Figure 1.1 shows a Java program being used to test students on Egyptian history.

Figure 1.1: A Java program to administer student testing (courtesy of David Benjamin and Auburn University).

The test software itself isn't remarkable-numerous computer-based education programs are being used in schools today. What is noteworthy about the program are the following points:

Java represents a fundamental shift in the way software can be designed and experienced. This, more than anything else, is why Sun's invention is the computer nerd's Macarena.

The Macarena is a Latino dance craze that involves lots of repetitive motion, arm gyration, and an occasional pelvic swivel. If you're unfamiliar with the term, insert your own annoying aerobic trend into the previous paragraph and repeat as desired.

Shortly after Sun introduced Java in late 1995, company cofounder Bill Joy described the language as follows:

Java is just a small, simple, safe, object-oriented, interpreted or dynamically optimized, byte-coded, architecture-neutral, garbage-collected, multithreaded programming language with a strongly typed exception-handling mechanism for writing distributed, dynamically extensible programs.

At this point, you probably are saying one of two things: "Duh!" or "Huh?"

If you're in the "huh?" camp, this chapter is for you. It discusses what Java is, where Java came from, and where Java is going. The "duh!" camp canenefit from this overview as well-and there's enough advanced material in Java Unleashed for even the most grizzled Java veteran.

Java's first official beta release was in November 1995, two months after Netscape became the first company to license the language from Sun. You may be questioning whether someone can become a "grizzled veteran" after little more than a year. However, many of us in the computer programming community have rather-shall we say-unique approaches to wellness and diet which contribute to premature grizzling.

The first thing to discuss, before getting into what Bill Joy meant in that Mother of All Sentences, is where Java came from.

How Java Was Developed

The story of Java is a tale of two situations-the worst of times followed by the best of times. It's a story about how a promising language didn't amount to a hill of coffee beans in this crazy world-until the crazy world got a little crazier and a new mass medium was born: the World Wide Web.

One for the Toasters

Five years ago, James Gosling was part of Green, an isolated research project at Sun that was studying how to put computers into everyday household items. The researchers wanted to make smart appliances like thoughtful toasters, lucid lamps, and sagacious Salad Shooters-the Jetsons' vision of the future realized. The group also wanted these devices to communicate with each other.

To get a hands-on look at the issue, the Greens built a prototype device called Star7. This gadget was a handheld remote control operated by touching animated objects on the screen. A Star7 user could navigate by fingertip through a universe of rooms and objects. The universe featured Duke-immortalized later as Java's mascot (see Figure 1.2).

Figure 1.2: Duke, Java's mascot.

The most remarkable ability of the Star7 device was how it communicated with other Star7 devices. An on-screen object could be passed from one device to another. The prototype was a distributed operating system in which each device was a part of the whole-exactly the kind of thing that would be needed for the freezer to tell the vacuum to tell the humans that the ice machine is on strike until someone cleans it.

The original plan was for the Star7 operating system to be developed in C++. However, as Gosling said in a speech at the JavaOne conference in May 1996, "The tools kept breaking. It was at a fairly early breaking point when I was so disgusted that I went to my office and started typing." He wasn't writing hate mail to Bjarne Stroustrup, the primary developer of C++. Instead, Gosling holed up in his office and wrote a new language that was better for the purposes of the Green project than C++. He called the language Oak in honor of a tree that could be seen from his office window.

From the start, Gosling's language was created so that simple, bug-free, network-capable programs could be written with it. Like C++, Oak was object oriented-a powerful way of developing computer programs that has many advantages over other methods but is difficult to master. Oak was designed to be easier to learn and use than other object-oriented languages.

Oak programs had to be platform independent because consumer appliance manufacturers need the ability to replace a higher-priced CPU with a cheaper one whenever possible to cut costs. Unlike computer owners, an appliance consumer isn't looking for a math coprocessor and 33MHz of added computational speed when buying a lawn edger. The consumer also is less likely to tolerate a bug in the edger's software or hardware, especially if said glitch causes unexpected limb loss.

The Green project had an impressive demonstration device, operating system, and programming language. Sun's higher-ups gave the go-ahead and the project was incorporated as FirstPerson in November 1992. The group focused its efforts on cable set-top boxes and the potentially billion-dollar interactive television (ITV) industry. Don't laugh-this was the early 1990s.

As the FirstPerson team was busy gunning to do Time-Warner's interactive TV trial in Spring 1993, an event took place that would become very important later to the FirstPerson people, long after they struck out in the ITV business. The first visual World Wide Web browser, Mosaic 1.0, was developed by Marc Andreesen, an undergraduate student working at the National Center for Supercomputing Applications.

Caught in the Web

For the next 12 months, the FirstPerson project tried to sell one of the ITV or consumer electronics companies on the use of Oak and the Green operating system. The future of Java can trace its roots back to the project's failure to attract a big client in its chosen field. After Time-Warner chose SGI over FirstPerson, and a deal with 3DO for the FirstPerson OS did not materialize, the project was cut in half and it started scrambling for a new raison d'être.

In mid-1994, the folks who stuck with Oak found their reason for being: the World Wide Web. When Oak was created, the Web was a little-known service bouncing around the high-energy physics community. However, Andreesen's graphical Web browser had sparked an international phenomenon, and the Web was rapidly becoming a mass medium. The Oak technology was well-suited for this medium, especially because of its ability to run on multiple platforms. More importantly, it introduced something that wasn't available anywhere else-programs that could be run on user's computers safely from a Web page.

Patrick Naughton and Jonathan Payne finished WebRunner, a Web browser that brought back the star of the Star7, Duke. Sun realized it had something promising on its hands, but soon found that Oak could not be trademarked because of a product already using the name.

When Sun needed to rename Oak, no one used Gosling's "look out the office window" method of naming. This is perhaps fortunate. Ask yourself if Java would have been as successful under any of the following names:
  • Shrubbery
  • OfficeBuildingNextDoor
  • LightPole
  • WindowWasher
  • SecretaryLeavingForLunch
  • WeirdSecurityGuard
  • FatGuyMowing

After brainstorming sessions in January 1995 to supplant the Oak name, Java won for the language and HotJava replaced WebRunner as the browser's name. Java does not stand for Just Another Vague Acronym, or any other acronym or meaningful term. Like rock bands (Deep Blue Something, Smashing Pumpkins) and celebrity offspring (Moon Unit Zappa, Chastity Bono), Java was the name chosen because it sounded the coolest. It won out over DNA, Silk, Ruby, and WRL (WebRunner Language).

The project now had a cool name, a cool new purpose, and a HotJava browser to show it off. On March 23, 1995, it attracted a cool new admirer: that Andreesen kid. In a front-page story, the San Jose Mercury News reported that Sun was working on a project to make Web pages "as lively as a CD-ROM." The story included the following quote from Andreesen, who had become a vice president at Netscape (and a Bill Gates starter kit): "What these guys are doing is undeniably, absolutely new," Andreesen told the Mercury News. "It's great stuff. There's so much stuff people want to do over the network that they haven't had the software to do. These guys are really pushing the envelope."

The phenomenon was on. Netscape licensed the Java language for use in its browser a few months after the article ran, putting the language in front of millions of Netscape users. The first beta release of Java was made available for download in November 1995. Sun made a developer's kit and the source code for its product freely available to anyone who wanted it-and by that time, thousands of people and companies did.

Toasters are no smarter today than they were in 1991, so in that regard, Sun's research project has been a total failure. However, a new object-oriented, made-for-the-Internet programming language was created instead.

Now that you know about Java's ancestors, it's time to be introduced to the language.

What Java Is

The basics: Java is an object-oriented programming language developed by Sun Microsystems that plays to the strengths of the Internet.

Object-oriented programming (OOP) is an unusual but powerful way to develop software. In OOP, a computer program is considered to be a group of objects that interact with each other. Consider an embezzlement program implemented with Java: A Worker object skims some Money objects from the CompanyFunds object and puts them in its own BankAccount object. If another Worker object uses the DoublecheckFunds object, a Police object will be called.

The feature that is best known about Java is that it can be used to create programs that execute from World Wide Web pages. These programs are called applets. A check of the AltaVista search engine at finds more than 4,800 Web pages running applets as of this writing.

Java programs made such a big splash on the Web because they offered interactivity in a medium that was largely one way. The Web distributes almost all information in a passive manner. Someone using a browser asks for a page, looks it over, asks for another, looks it over, and so on. Lather, rinse, repeat.

A Java applet running on a Web page provides a much richer experience-both in terms of information and user interaction. Information can change in response to user input or be updated dynamically as a Web page is viewed. Figure 1.3 shows an example of a Java applet that dynamically updates itself. The applet, offered by JavaWorld magazine (at the URL in conjunction with Quote.Com, updates a stock portfolio dynamically with quotes updated in real time.

Figure 1.3: A Java applet that updates a stock portfolio in real time (courtesy of Java World magazine).

Although Web-based programs are a strength of the language, Java is a general-purpose language that can be used to develop all kinds of programs.

A Java program is created as a text file with the file extension .java. It is compiled into one or more files of bytecodes with the extension .class. Bytecodes are sets of instructions similar to the machine code instructions created when a computer program is compiled. The difference is that machine code must run on the computer system it was compiled for, and bytecodes can run on any computer system equipped to handle Java programs.

The next section describes why Java is being used and takes a closer look at Bill Joy's adjective-stuffed description of the language.

Why Java Is Internationally Beloved

Although "internationally beloved" might be pushing it a bit, Java has quickly become a popular choice for computer programming-both on and off the Internet. A lot of the initial interest undoubtedly came from people who wanted to know whether Java lived up to the hype. In a short time, the language has become one of the biggest buzzwords of the Internet, spawning magazines, Web sites, training courses, conferences, and more than 120 books.

Even if Java was as underpublicized as Tonya Harding's singing career, the programming language has some advantages over other languages such as C++ and Visual Basic. These can be found in Bill Joy's description of the language.

As a reminder, Joy sang its praises as follows:


These adjectives can be tackled by dividing them into more manageable groups.

Java Is Small and Simple

When James Gosling retreated to his office to write the language that became Java, it was modeled after C and C++. The object-oriented approach, and most of Java's syntax, is adapted from C++. Programmers who are familiar with that language (or with C) will have a much easier time learning Java because of the common features.

However, Java has been described as "C++ minus" because of elements of C++ that were omitted. Gosling wanted to avoid the problems that the Green project had encountered when using C++ as it developed the Star7 prototype. The most complex parts of C++ were excluded from Java, such as pointers and memory management. These elements are complicated to use, and are thus easier to use incorrectly. Finding a pointer error in a large program is an experience not unlike searching for the one-armed man who framed you for murder. Memory management occurs automatically in Java-programmers do not have to write their own garbage-collection routines to free up memory.

Another design decision to make Java simpler is its elementary data types and objects. The language enforces very strict rules regarding variables-in almost all cases, you have to use variables as the data type they were declared to be, or use explicit casts to manipulate them. This arrangement permits mistakes in variable use to be caught when the program is compiled, rather than letting them creep into a running program where they're harder to find. As a result, programs behave in a more predictable manner.

Experienced programmers may have trouble adjusting to some of the changes and reductions from C++. However, Java's developers were trying to make the language easier to write, debug, and learn.

Java Is Object Oriented

Object-oriented programming (OOP) is a powerful way of organizing and developing software. The short-form description of OOP is that it organizes a program as a set of components called objects. These objects exist independently of each other, and they have rules for communicating with other objects and for telling those objects to do things. Think back to how Star7 devices were developed as a group of independent devices with methods for communicating with each other. Object-oriented programming is highly compatible with what the Green project was created to do and, by extension, for Java as well.

Java inherits its object-oriented concepts from C++ and other languages such as Smalltalk. The fact that a programming language is object oriented may not seem like a benefit to some. Object-oriented programming can be an intimidating subject to tackle, even if you have some experience programming with other languages. However, object-oriented programs are more adaptable for use in other projects, easier to understand, and more bugproof.

The language includes a set of class libraries that provide basic variable types, system input and output capabilities, and other functions. It also includes classes to support networking, Internet protocols, and graphical user interface functions.

There's a lot of excitement in the programming community because Java provides a new opportunity to use object-oriented techniques on the jobs. Smalltalk, the language that pioneered object-oriented programming in the 1970s, is well-respected but has never been widely adopted as a software-development choice. As a result, getting the go-ahead to develop a project using Smalltalk can be an uphill struggle. C++ is object oriented, but concerns about its use have already been described. Java is overcoming the hurdle in terms of usage, especially in regard to Internet programming and the development of distributed applications.

Tim Berners-Lee, the inventor of the World Wide Web, told the attendees at the JavaOne conference one big reason he's excited about the language: "We now have an excuse to really use object-oriented programming."

Java Is Safe

Another thing essential to Java's success is that it be safe. The original reason for Java to execute reliably was that people expect their waffle irons not to kill them or to exhibit any other unreliable behavior. This emphasis on security was well-suited for Java's adaptation to the World Wide Web.

A Java program that executes from a Web page is called an applet. All other Java programs are called applications. When an applet is encountered on a Web page (if the user's browser can handle Java), the browser downloads the applet along with the text and images on the page. The applet then runs on the user's computer. This act should raise a red flag-danger! danger!-because a lot of harmful things can occur when programs are executed: viruses, Trojan horses, the Microsoft Network, and so on.

Java provides security on several different levels. First, the language was designed to make it extremely difficult to execute damaging code. The elimination of pointers is a big step in this regard. Pointers are a powerful feature, as the programmers of C-like languages can attest, but pointers can be used to forge access to parts of a program where access is not allowed, and to access areas in memory that are supposed to be unalterable. By eliminating all pointers except for a limited form of references to objects, Java is a much more secure language.

Another level of security is the bytecode verifier. As described earlier, Java programs are compiled into sets of instructions called bytecodes. Before a Java program is run, a verifier checks each bytecode to make sure that nothing suspicious is going on.

In addition to these measures, Java has several safeguards that apply to applets. To prevent a program from committing random acts of violence against a user's disk drives, an applet cannot open, read, or write files on the user's system. Also, because Java applets can open new windows, these windows have a Java logo and text that identifies their identity. This prevents one of these pop-up windows from pretending to be something such as a user name and password dialog box.

There is no system of security that is completely foolproof, and there were several instances in the first year after Java's release where security bugs were brought to Sun's attention by programmers such as David Hopwood. The following Web site describes some of these incidents and outlines the issues regarding safe Internet programming:

Because of the multiple levels of security, and the continued efforts to improve these measures, Java is generally regarded as a secure means to execute code over the World Wide Web.

These safeguards are not an absolute guarantee against malicious programming. Several security experts have found ways to circumvent Java applet security during the first year of the language's availability, and the details were sent to JavaSoft and browser developers. There will undoubtedly be new security holes found in the future with Java, as there are with any system. If you are concerned about running Java applets on your computer, you should run only applets that have been approved by a Java directory such as Gamelan or another trusted source. Gamelan, which can be found at the URL, tests applets before offering them. You also should back up any essential data on your computer regularly-which is good practice in any case.

Java Is Platform Independent

Platform independence is another way of saying that Java is architecture neutral. If both terms leave you saying "huh?", they basically mean that Java programs don't care what system they're running on.

Most computer software is developed for a specific operating system. If Sid Software wanted its two-fisted 17th-century shoot-'em-up Quaker to run on Windows and Mac systems, it had to develop two versions of the software at a significant effort and expense. Platform independence is the ability of the same program to work on different operating systems; Java is completely platform independent.

Java's variable types have the same size across all Java development platforms-so an integer is always the same size, no matter which system a Java program was written and compiled on. Also, as shown by the use of applets on the Web, a Java .class file of bytecode instructions can execute on any platform without alteration.

Sun Microsystems has been aggressive in making Java available on different systems. As JavaSoft President Alan Baratz says, "Anything that feels, smells, walks, or talks like it has a processor-we'd like the Java platform to live on it." There are Java interpreters that can run programs for Microsoft Windows 95 and NT, Apple Macintosh 7.5, SPARC Solaris 2.3 or higher, and Intel x86 Solaris; other systems have Java versions under development.

Java's declaration of platform independence is often trumpeted by Java advocates as a major accomplishment because it opens up a much larger audience for programs than has been readily available in the past. Although no major commercial releases of Java-based software have been introduced as of this writing (other than JavaSoft products such as HotJava and the Java WorkShop programming environment), several have been announced.

Java Is That Other Stuff, Too

One adjective that has been left out thus far is that Java is multithreaded. Threads represent a way for a computer program to do more than one task at the same time. Many operating systems are multitasking. Windows 95, for example, enables a person to write a book chapter with Word in one window while using Netscape Navigator to download every known picture of E! host Eleanor Mondale in the other. (Speaking hypothetically, of course.)

A multithreaded language extends this schizophrenic behavior to programs so that more than one set of instructions can be executed concurrently. Java provides the tools to write multithreaded programs and to make these programs reliable in execution.

Another thing that should be highlighted is Java's network-centric nature. Sun, the company that trademarked the phrase, "the network is the computer," has created a language that backs it up. Star7 was able to pass an object from one device to another using radio signals, and Java makes it possible to create applications that communicate across the Internet in the same way.

Its networkability may be the area in which Java truly separates itself from other languages that can be used for development. As language creator James Gosling has remarked, "The thing that distinguishes Java is its approach to distributed programming."

Most of Bill Joy's accolades should make more sense to you at this point, although it may take a complete reading of Java Unleashed before you're ready to string together technical jargon like his with the proficiency of a Dilbert character.

Java Today

Now that you have an idea about what Java is and why you should use it, forsaking all others (or maybe not), you're ready to get started. To understand the status of Java development today, you should learn more about the Java Developer's Kit, the language Application Programming Interface (API), future APIs, and some examples of Java in action.

The Java Developers Kit

The Java Developers Kit (JDK) is a set of command-line tools that can be used to create Java programs. As of this writing, version 1.0.2 is the current release of the JDK, and it can be downloaded from the following Web address:

Sun supports the following platforms: Microsoft Windows 95 and NT, Solaris 2.x for SPARC and x86 systems, and Apple MacOS. The JDK includes the following tools: a compiler, an interpreter to run compiled Java standalone applications, an applet viewer to run Java applets, and other utilities.

There are numerous alternatives to JDK 1.0.2 that offer graphical user interfaces, tools to speed up debugging and program development, and other niceties. Some of these alternatives use the JDK transparently during use, while others replace the JDK's tools.

JavaSoft, the division of Sun Microsystems responsible for Java development, plans to release a new, expanded version of the JDK that may be available as you read this. The successor to JDK 1.0.2 will be version 1.1, and it is expected to include improved security, new windowing design classes, a way to group files into archives, and other enhancements.

The Java API

The Java Application Programming Interface (API) is a set of classes used to develop Java programs. These classes are organized into groups called packages. There are packages for the following tasks:

The API includes enough functionality to create sophisticated applets and applications. The Java API must be supported by all operating systems and Web software equipped to execute Java programs, so you can count on the existence of Java API class files when developing programs.

The Java API is at version 1.0.2 at this time; Sun will make no changes in future versions that would require changes to source code. Although enhancements are planned for future releases of the API, there will be no removals or changes to class behavior.

Extended APIs

In addition to the basic API that must be present with all Java implementations, Sun is developing extended APIs that extend the features of the language.

All but one of the following classes are in various stages of development at Sun:

Java Beans is the most likely of the extended APIs to appear first, although the enhanced security APIs are close to completion. If you guessed that the Socratic API was the false one, move forward two spaces-you're right. However, Microsoft could not take the risk that another company would be first to implement it-the Socratic API will begin development with ActiveX later this year.


In May 1996, JavaSoft announced plans to develop JavaOS, a compact operating system intended to run Java programs. The stated goal is to be the fastest and smallest platform that can handle Java. In addition to being a competitor to operating systems such as Microsoft Windows 95, JavaOS will put the language where it was originally intended to be: in appliances.

The operating system will be embedded on processor chips being developed by Sun. At the JavaOne conference, Mitsubishi demonstrated its own Java chip, which was being used to run a mobile Java terminal called the MonAMI.

The JavaOS and similar efforts are in a much earlier stage of development than other Java-related projects from Sun. However, JavaOS or some other hardware-based Java solutions should be available by early 1997.

Web Sites

One of the advantages of a Web-based phenomenon like Java is that it generates megabytes of information on the World Wide Web. Documentation, news, source code, and other material about Java is offered at thousands of sites. The following should get you started:

Usenet Newsgroups

Numerous messages are posted on Usenet newsgroups each day by people who are interested in Java. Some are from developers with experience in the language who can comment on advanced aspects of the language. Many are from newcomers who need help in their efforts to learn Java. In any case, Usenet is a great place to get technical assistance. (Some other Usenet messages are from America Online users who have become lost in their search for pictures of Pamela Anderson Lee, but that's another story entirely.)

The following newsgroups currently are available on Usenet, which can be accessed with an Internet account, a subscription to online services such as CompuServe and America Online, and other means:

Java Tomorrow

During its first year of release, Java has enjoyed the same advantages bestowed on child prodigies. Most of the talk has been about its great potential, and criticism is overshadowed by excited anticipation about what it will do in the future.

As an example of this, consider the words of Marc Andreesen, himself a child prodigy of sorts, after creating Mosaic while he was an undergraduate. Andreesen's endorsement was one of the reasons for Java's astonishing growth. He said the following at the JavaOne conference:

Java is a huge opportunity for all of us, all the developers in the industry, who are, all of a sudden, able to develop applications in days or weeks, instead of months or years; who have new ways of distributing those applications, making money from those applications without having to fight for retail shelf space.

One of the applications that has been announced is the WordPerfect Office Suite. Corel has stated that Office Suite will be redesigned entirely using Java, making it available for a wide range of platforms. IBM is redesigning its OS/2 Warp operating system to make it optimized for Java programs.

The technology venture capital firm, Kleiner, Perkins, Caufield, and Byers (KPCB), has offered $100 million to support companies doing work with Java.

Year two is going to be a little tougher on the tyke. If Java is to remain the object-oriented language of people's affections, it has to start fulfilling some of its promises.

Growing up isn't always an easy process for those who have achieved outlandish success early in life. Ask any former child star who has traded in a Screen Actors Guild card for a life of crime or a career in talk shows.

By picking up a book of this kind and learning about Java, you're one of the people who is expected to do something remarkable with it. The developers of Java, the nation's press, and those of us who make our living writing Java books by the ton are depending on you. Not to mention the folks at KPCB who gave up $100 million of their allowances to fund Java-related programming.

It's one of the prices you pay for being in the right place at the right time.