Owl Teach Yourself Java 2 in 21 Days, Second Edition
HOME / ORDER THE BOOK / OTHER BOOKS / THANKS

21st Century Java

Chapter 1 of the book Sams Teach Yourself Java 2 in 21 Days, Second Edition, by Laura Lemay and Rogers Cadenhead

Big companies like IBM are embracing Java far more than most people realize. Half of IBM is busy recoding billions of lines of software to Java. The other half is working to make Java run well on all platforms, and great on all future platforms.

-- PBS technology commentator Robert X. Cringely

In 1995, when Sun Microsystems first released the Java programming language, it was an inventive toy for the World Wide Web that had the potential to be much more.

The word "potential" is an unusual compliment, because it comes with an expiration date. Sooner or later, potential must be realized or new words such as "letdown," "waste," and "major disappointment to your mother and I" are used in its place.

Now in its fourth major release, Java appears to have lived up to the expectations that accompanied its arrival. More than two million people have learned the language and are using it in places such as NASA, IBM, Kaiser Permanente, ESPN, and New York's Museum of Modern Art. More than 1,700 books have been written about it, according to the most recent JavaWorld Magazine count.

First used to create simple programs on World Wide Web pages, Java can be found today in each of the following places and many more:

  • Web servers
  • Relational databases
  • Mainframe computers
  • Telephones
  • Orbiting telescopes
  • Personal digital assistants
  • Credit card-sized "smartcards"

Over the next 21 days, you will write Java programs that reflect how the language is being used in the 21st century. In some cases, this is very different than how it was originally envisioned.

Although Java remains useful for Web developers trying to enliven sites, it extends far beyond the Web browser. Java is now a popular general-purpose programming language, and some surveys indicate that there are more professional Java programmers than C++ programmers.

As you develop your skills during the 21 one-day tutorials in Sams Teach Yourself Java 2 in 21 Days, Second Edition, you'll be in a good position to judge whether the language has lived up to years of hype.

You'll also become a Java programmer with a lot of potential.

Exploring Java 2

Whenever Sun releases a new version of Java, it makes a free development kit available over the Web to support that version. This book was created using the kit, which is called Java 2 Software Development Kit, Standard Edition, Version 1.3.

Although the authors of a book like this have no business poking fun at long-winded titles, Sun has given its main Java development tool a name that's longer than most celebrity marriages.

For the sake of a few trees, in this book the language will usually be referred to simply as Java and the kit as SDK 1.3. You might see the kit referred to elsewhere as Java Development Kit 1.3 or JDK 1.3.

If you work your way through the 21 days of this book, you'll become well-versed in Java's capabilities, including graphics, file input and output, user-interface design, event handling, JavaBeans, and database connectivity. You will write programs that run on Web pages and others that run on your personal computer, Web servers, and other computing environments.

Today's goals are reasonably modest. You'll learn about the following topics:

  • What Java is like today and how it got there
  • Why Java is worth learning
  • Why Java is being chosen for software projects
  • What you need to start writing Java programs
  • How to create your first program

Java's Past, Present, and Future

Based on the enormous amount of press Java has received over the past several years and the huge number of books about Java, you might have an inflated impression of what Java is capable of.

Java is a programming language that's well suited to designing software that works in conjunction with the Internet. It's also an object-oriented programming language, making use of a methodology that is becoming increasingly useful in the world of software design. Additionally, it's a cross-platform language, which means its programs are designed to run without modification on Microsoft Windows, Apple Macintosh, Linux, Solaris, and other systems. Java extends beyond desktops to run on devices such as televisions, smart cards, and cellular phones.

Java is closer to programming languages such as C, C++, Python, Visual Basic, and Delphi than it is to a page-description language such as HTML, a Web scripting language such as JavaScript, or a data-description language such as XML.

Interactive Web Programming

Java first became popular because of its capability to run on World Wide Web pages. Netscape Navigator, Microsoft Internet Explorer, and other browsers can download a Java program included on a Web page and run it locally on the Web user's system.

These programs, which are called applets, appear on a Web page in a similar fashion to images. Unlike images, applets can be interactive -- taking user input, responding to it, and presenting ever-changing content.

Applets can be used to create animation, charts, graphs, games, navigational menus, multimedia presentations, and other interactive effects.

Figure 1.1 shows an applet running in the Opera 3.61 Web browser. This applet, Every Icon, is an interactive work of art implemented as a Java program by John F. Simon, Jr., an artist and programmer who has taught at the School of Visual Arts in Manhattan. It has been shown at the 2000 Whitney Biennial art exhibition and purchased by the Guggenheim Museum and the San Francisco Museum of Modern Art.

Figure 1.1: A Java applet running on a Web page displayed in the Opera Web browser.

NOTE: The Every Icon applet is designed to display every possible icon that can be drawn using black or white squares in a simple 32-by-32 grid. Though the applet displays icons quickly, it takes more than 16 months on a Pentium-equipped computer to display all 4.29 billion variations possible on the top line of the grid alone. Displaying all variations on the top 2 lines would take around 16 billion years. You can find Every Icon and other art projects on Simon's Web site.

Applets are downloaded over the World Wide Web just like HTML-formatted pages, graphics, and any other element of a Web site. On a Web browser that is equipped to handle Java, the applet will begin running when it finishes downloading.

Applets are written with the Java language, compiled into a form that can be run as a program, and placed on a Web server.

Most applets are written using Java 1.0 or Java 1.1, the first two versions of the language, because the leading browser developers have been slow to add built-in support for subsequent versions.

You can develop applets using Java 2, but the person viewing your applet must be using a browser that supports it. Sun has developed a free browser add-on called the Java Plug-in, and it can be downloaded to add current Java support to most popular browsers.

NOTE: You'll learn more about applets, browsers, and the Java Plug-in during Day 7, "Writing Java Applets."

Like Visual C++, Visual Basic, and Delphi, Java is a robust language that can be used to develop a wide range of software, supporting graphical user interfaces, networking, database connectivity, and other sophisticated functionality.

Java programs that don't run within a Web browser are called applications.

Java Grew from a Little Oak

The Java language was developed at Sun Microsystems in December 1990 as part of the Green project, a small research effort into consumer electronics. Researchers were working on a programming language for smart appliances of the future to talk to each other in the tradition of The Jetsons TV series -- step one in realizing a society in which giant glass bubbles drop down over your body and dress you every morning.

To put its research into action, Green developed a prototype handheld device called the Star 7, a PalmPilot-like gadget that could communicate with others of its own kind.

The original idea was to develop the Star 7 operating system in C++, the hugely popular object-oriented programming language developed by Bjarne Stroustrup. However, Green project member James Gosling became fed up with how C++ was performing on the task, so he barricaded himself in his office and wrote a new language to better handle the Star 7.

The language was named Oak in honor of a tree Gosling could see out his office window. It was later renamed Java in honor of the lawyers who found out about another product called Oak and didn't want to go out on a limb.

Because Java was designed for embedded electronic devices instead of state-of-the-art PCs, it had to be small, efficient, and easily portable to a wide range of hardware devices. It also had to be reliable. People have learned to live with occasional system crashes and lockups in a 30MB software application. However, there aren't many people willing to debug an elevator while its programmers work out the kinks.

Although Java wasn't catching on as an appliance-development tool, just as things were looking grim for the Green project, the World Wide Web started to take off. Many of the things that made Java good for the Star 7 turned out to be good for the Web:

  • Java is small -- Programs load reasonably quickly on a Web page
  • Java is secure -- Safeguards protect against programs that cause damage, whether accidental or intentional
  • Java is portable -- Owners of Windows, Macintosh, Linux, and other operating systems can run the same program in their Web browsers without modification

In order to demonstrate Java's potential, in 1994 project members created HotJava, a Web browser that could run Java applets. The browser demonstrated two things about Java: what it offered the World Wide Web and what kind of program Java could create. Green programmers had used their new language to create the browser, rather than implementing it in C++.

Netscape became the first company to license the Java language in August 1995, incorporating a Java interpreter in its industry-leading Navigator Web browser. Microsoft followed by licensing Java for Internet Explorer, and millions of people could run interactive programs in their browsers for the first time.

Spurred by this huge audience of Web users, more than 300,000 people learned Java programming from 1995 to 1996. Sun added hundreds of employees to its Java effort, believing that the language was ideally suited for a wide variety of desktop, portable, and network computing platforms beyond the Web.

Versions of the Language

Sun has released four major versions of the Java language:

  • Java 1.0 -- A small Web-centered version uniformly available in all popular Web browsers
  • Java 1.1 -- A 1997 release with improvements to the user interface, completely rewritten event handling, and a component technology called JavaBeans
  • Java 2 with SDK 1.2 -- A significantly expanded version released in 1998 with retooled graphical user interface features, database connectivity, and many other improvements
  • Java 2 with SDK 1.3 -- A 2000 release that adds new core features such as improved multimedia, more accessibility, and faster compilation

A Java development kit has always been available at no cost from Sun's Java Web site, and this availability is one of the factors behind the language's rapid growth. It is the first development tool that supports new versions of Java, often six months to a year before other Java development software.

In addition to Java's development kit, there are more than two dozen commercial development tools available for Java programmers. Some of the most popular:

  • Symantec Visual Café
  • Borland JBuilder
  • IBM Visual Age for Java
  • Sun Forte for Java

If you are going to use something other than SDK 1.3 to create Java programs as you read this book, you need to make sure that your development tool is up-to-date in its support for Java 2.

NOTE: The programs in this book were tested with Java 2 SDK 1.3.0, the most current version of the kit available as the book went to press.

Java's Outlook

Anyone who can accurately predict the future of Java should be going after venture capital instead of writing a book. The technology firm Kleiner, Perkins, Caufield and Byers (KPCB) is investing $100 million in start-up companies on the basis of their future plans involving Java, and has already given millions to Active Software, Marimba, Viant, and a dozen other companies.

With the caveat that neither author of this book is pursuing venture capital, we predict a bright future for Java over the coming decade.

The new version of Java 2 incorporates the following key improvements:

  • HotSpot -- A new technology that runs Java programs more quickly and takes up less memory
  • JavaSound -- Greatly enhanced support for 8- and 16-bit playback and recording of WAV, AU, AIFF, and MIDI sound formats
  • Swing -- More than two dozen added features to components used in the graphical user interface of Java programs
  • Performance -- In addition to HotSpot, Sun has improved the speed and reliability of several aspects of the language: animation, database connectivity, networking, and multi-threaded programs, which handle multiple tasks at the same time

You will work with these and other new features in the next three weeks.

NOTE: You can find out how to apply for the Java investment fund at the KPCB Web site. If your idea is funded and you become an overnight Internet millionaire, be aware that Macmillan USA does not forbid its authors from receiving a generous finder's fee.

Why to Choose Java

Java applets were a breakthrough in interactive content on the Web, and many top sites used them to deliver news, present information, and attract visitors. Today, ESPN.Com uses Java applets for live events in its fantasy sports leagues, which have more than 100,000 subscribers.

Although there are still thousands of applets on the Web today, the most exciting Java-related developments are occurring elsewhere. Sun has extended the language far beyond its roots as an interesting Web technology.

A great example of this is Jini, Sun's Java-based technology for connecting computers and other devices together. The goal of Jini is effortless networking -- connect two devices together and they instantly form a network, requiring no installation or configuration.

Jini, which ironically returns Java to the original goals of the Green Project, is just one of the new areas where the language is being employed.

Regardless of where you find it running, Java's strengths remain its object-oriented nature, ease of learning, and platform neutrality.

Java Is Object-Oriented

If you're not yet familiar with object-oriented programming, you get plenty of chances to become so during the next week.

Object-oriented programming -- also called OOP -- is a way of conceptualizing a computer program as a set of separate objects that interact with each other. An object contains both information and the means of accessing and changing that information -- an efficient way to create computer programs that can be improved easily and used later for other tasks.

Java inherits many of its object-oriented concepts from C++ and borrows concepts from other object-oriented languages as well. You learn more this beginning on Day 2, "Object-Oriented Programming."

Java Is Easy to Learn

In part, Java was first created at the Green project in rejection of the complexity of C++. C++ is a language with numerous features that are powerful but easy to employ incorrectly.

Java was intended to be easier to write, compile, debug, and learn than other object-oriented languages. It was modeled strongly after C++ and takes much of its syntax from that language.

NOTE: The similarity to C++ is so strong that most Java books, including previous editions of this one, make frequent comparisons between the features of the two languages. Today, it's more common for a Java programmer to learn this language either before or in place of C++. For this reason, you won't see many references to C++ in this book after today.

Despite Java's similarities to C++, the most complex and error-prone aspects of that language have been excluded from Java. You won't find pointers or pointer arithmetic because those features are easy to use incorrectly in a program and even harder to fix. Strings and arrays are objects in Java, as is everything else except a few simple data structures such as integers, floating-point numbers, and characters.

Additionally, memory management is handled automatically by Java rather than requiring the programmer to allocate and deallocate memory, and multiple inheritance is not supported.

Experienced C++ programmers will undoubtedly miss these features as they start to use Java, but everyone else will learn Java more quickly because of their absence.

Although Java is easier to learn than many other programming languages, a person with no programming experience at all will find Java challenging. It is more complicated than working in something such as HTML or JavaScript, but definitely something a beginner can accomplish.

NOTE: Macmillan USA publishes another line of Java tutorials aimed directly at beginning programmers: Sams Teach Yourself Java 2 in 24 Hours, Second Edition, is written by Rogers Cadenhead, one of the coauthors of this book.

Java Is Platform Neutral

Because it was created to run on a wide variety of devices and computing platforms, Java was designed to be platform neutral, working the same no matter where it runs.

This was a huge departure in 1995, when Visual C++, Visual Basic, and other leading programming environments were designed almost exclusively to support Microsoft Windows 95 or Windows NT.

The original goal for Java programs to run without modification on all systems has not been realized. Java developers routinely test their programs on each environment they expect it to be run on, and sometimes are forced into cumbersome workarounds as a result. Even different versions of the same Web browser can require this kind of testing -- Java game programmer Karl Hörnell calls it a "hopeless situation."

However, Java's platform-neutral design still makes it much easier to employ Java programs in a diverse range of different computing situations.

As with all high-level programming languages, Java programs are originally written as source code, a set of programming statements entered into a text editor and saved as a file.

When you compile a program written in most programming languages, the compiler translates your source file into machine code -- instructions that are specific to the processor your computer is running. If you compile your code on a Windows system, the resulting program will run on other Windows systems but not on Macs, PalmPilots, and other machines. If you want to use the same program on another platform, you must transfer your source code to the new platform and recompile it to produce machine code specific to that system. In many cases, changes to the source will be required before it will compile on the new machine, because of differences in its processors and other factors.

Java programs are compiled into machine code for a virtual machine -- a sort of computer-within-a-computer. This machine code is called bytecode, and the virtual machine interprets this code by converting it into a specific processor's machine code.

The virtual machine is more commonly known as the Java interpreter, and every environment that supports Java must have an interpreter tailored to its own operating system and processor.

Java also is platform neutral at the source level. Java programs are saved as text files before they are compiled, and these files can be created on any platform that supports Java. For example, you could write a Java program on a Windows 98 machine, upload it to a Linux machine over the Internet, and then compile it.

Java interpreters can be found in several places. For applets, the interpreter is either built into a Java-enabled browser or installed separately as a browser plug-in.

If you're used to the way other languages create platform-specific code, you might think the Java interpreter adds an unnecessary layer between your source file and the compiled machine code.

The interpreter does cause some significant performance issues -- as a rule, Java bytecode executes more slowly than platform-specific machine code produced by a compiled language such as C or C++.

Sun, IBM, Symantec and other Java developers are addressing this with technology such as HotSpot, a new faster virtual machine included with Java 2, and compilers that turn bytecode into platform-specific machine code. Every new generation of processors also increases Java's sometimes laggard performance.

For some Java programs, speed might not be as much of an issue as portability and ease of development. The widespread deployment of Java in large business and government projects shows that the loss in speed is less of an issue than it was for early versions of the language.

Diving into Java Programming

Now that you've been introduced to Java as a spectator, it's time to put some of these concepts into play and create your first Java program.

Before you can get started, you must have SDK 1.3 or a fully compatible development environment on your system.

Selecting a Java Development Tool

If you're using a Microsoft Windows or Apple MacOS system, you probably have a Java interpreter installed that can run Java programs. Usually, this interpreter is part of a Web browser and only can run applets.

To develop Java programs, you need more than an interpreter. You also need a compiler and other tools that are used to create, run, and debug programs.

The programs in this book were tested with SDK 1.3, a set of command-line programs including a compiler, interpreter, appletviewer, file archiver, and several other programs.

A command-line program is one that must be run by typing a command at a prompt.

NOTE: On a Windows 95 or 98 system, you can get to a command-line prompt by clicking the Start button on the Taskbar, choosing Programs, and then clicking MS-DOS Prompt.

Here's an example of a command you could type when using the development kit:

javac RetrieveMail.java

This command tells the javac program -- the Java compiler included with Java 2 SDK 1.3 -- to read a source code file called RetrieveMail.java and turn it into one or more files of compiled bytecode.

People who are comfortable with MS-DOS, Linux, and other command-line environments will be at home using SDK 1.3. Everyone else will have to become accustomed to the lack of niceties such as a graphical environment and a mouse as they develop programs.

If you have another Java development tool and you're certain it is completely compatible with SDK 1.3, you can use it to create the sample programs in this book.

CAUTION: If you have any doubts regarding compatibility, or this book is your first experience with the Java language, you should use SDK 1.3. All the examples in the book were prepared using it.

Installing the Software Development Kit

SDK 1.3 is currently available for the following platforms:

  • Windows 98
  • Windows 95
  • Windows 2000
  • Windows NT

The kit requires a computer with a Pentium processor that is 166 MHz or faster, 32MB of memory, and 65MB of free disk space. Sun recommends at least 48MB of memory if you're going to work with Java 2 applets.

If you're using another platform, such as the Apple Macintosh, you can check to see whether it has an SDK 1.3[nd]compliant environment by visiting Sun's Java platform ports page.

You can download SDK 1.3 from Sun's Java Web site.

The Web site's Products & APIs section offers links to the different Java development kits and related products from Sun. The product you should download is called Java 2 Software Development Kit, Standard Edition, version 1.3.

When you're looking for this product, you might find that the SDK has a third number after 1.3, such as SDK 1.3.1. To fix bugs and security problems, Sun periodically issues new releases of the SDK and numbers them with an extra period and digit after the main version number. Choose the most current version of SDK 1.3 that's offered, whether it's numbered 1.3.0, 1.3.1, 1.3.2, or higher.

CAUTION: Take care not to download two similarly named products from Sun by mistake -- the Java 2 Runtime Environment, Standard Edition, version 1.3 or the Java 2 Software Development Kit, Standard Edition, Source Release.

You can also go directly to the download page.

To set up SDK 1.3, you must run an installation program that you have either downloaded from Sun or run from a CD.

Sun's Web site contains instructions for several ways to receive SDK 1.3's installation file. After choosing the version of the SDK that's designed for your operating system, you can download it as a single file that's around 25-30MB in size or download a bunch of smaller files. If you choose the latter option, follow Sun's documentation regarding how to combine them together before installing the kit.

After you have a single installation file -- either by downloading it or combining a bunch of smaller files -- you're ready to set up the development kit.

Windows Installation

Before installing SDK 1.3, you should make sure that no other Java development tools are installed on your system. Having more than one Java programming tool installed is likely to cause configuration problems when you use SDK 1.3.

Also, you should close all other Windows programs before installing SDK 1.3.

To set up the program on a Windows system, double-click the installation file or click Start, Run from the Windows taskbar to find and run the file.

The SDK Setup Wizard will guide you through the process of installing the software. If you accept Sun's terms and conditions for using the software, you'll be asked where to install the program, as shown in Figure 1.2.

Figure 1.2: Choose a destination location for SDK 1.3.

The Setup Wizard will suggest installing the program in a new jdk1.3 folder in the main hard drive on your system. Click the Next button to accept this choice, or Browse if you want to pick a different location.

TIP: Any configuration problems you might have with the SDK will be easier to fix if you install it in the folder recommended by the Setup Wizard.

The Setup Wizard will place a large number of programs and data files in the folder you have selected. Make a note of the folder, because you'll need to know it later when configuring how SDK 1.3 works on your system.

The next thing you'll be asked is what parts of the kit to install. This dialog box is shown in Figure 1.3.

Figure 1.3: Selecting components of SDK 1.3 to install.

By default, the wizard will install all components of the SDK:

  • Program Files -- The executable programs needed to create, compile, and test your Java projects.
  • Native Interface Header Files and Old Native Interface Header Files -- Files used only by programmers who are combining Java code with programs written in other languages. You can omit these for the tutorials in this book.
  • Demos -- Java 2 programs, with versions you can run and source files you can examine to learn more about the language.
  • Java Sources -- The source code for the thousands of programs that make up the Java 2 class library.

If you accept the default installation, you need around 50-55MB of free hard disk space. You can save space by omitting everything but the program files, but the demo programs are nice to have around as you're experimenting with the language.

Neither the native header files nor Java source files are needed for any of the material in this book -- both are primarily of interest to experienced Java programmers.

After you choose the components to install, click the Next button and the Setup Wizard will install the SDK 1.3 on your system.

Configuring the SDK

After the Setup Wizard installs SDK 1.3, you must adjust your computer's environment variables to include references to the SDK.

Experienced MS-DOS and command-line users can finish setting up the SDK by adjusting two settings, and then rebooting the computer:

  • Edit the computer's PATH variable and add a reference to the SDK's bin folder (which is C:\jdk1.3\bin if you installed the SDK into the C:\jdk1.3 folder).
  • Remove the CLASSPATH variable if you are not using it for some other Java-related programming. If you are, make sure that it contains a reference to the current folder -- a period character ("." without the quotation marks).

These instructions might sound like gobbledygook to people who are used to a graphical, mouse-driven operating system such as Windows.

The following two sections cover how to set the PATH and CLASSPATH correctly on the different Windows systems supported by the SDK.

Users of other operating systems should follow the instructions provided by Sun on its SDK download page.

Windows 95 and 98 Configuration

To set your computer's PATH variable on a Windows 95 or 98 system, use the Windows Notepad text editor to open the AUTOEXEC.BAT file on your computer. It should be located in the root folder of the main hard drive on your computer (usually C:).

Scroll down to the bottom of AUTOEXEC.BAT and add a new line that has the following format:

PATH SDKFolder\bin;%PATH%

Replace SDKFolder with the name of the folder where you installed the SDK and add the rest without modification. For example, if you installed the SDK into C:\jdk1.3, the line should be the following:

PATH C:\jdk1.3\bin;%PATH%

After you make this change, keep AUTOEXEC.BAT open and look for any lines that begin with the text SET CLASSPATH=.

If you don't find any, you're done setting up the SDK. Save AUTOEXEC.BAT and reboot your computer.

If you find any CLASSPATH lines, add a new blank line at the bottom of AUTOEXEC.BAT and enter a line with the following format:

SET CLASSPATH=.;SDKFolder\lib ools.jar;%CLASSPATH%

As you did with the PATH variable, replace SDKFolder with the folder where the SDK was installed. Save AUTOEXEC.BAT and reboot.

Windows NT and 2000 Configuration

To set any environment variables on a Windows NT or Windows 2000 system, choose Start, Control Panel, System, Environment from the taskbar. A dialog box will open where you can view the current values of environmental variables and make changes to them.

The PATH variable might be listed in System Variables or User Variables. PATH contains a list of folders separated by semicolons.

At the beginning of the PATH setting, insert the folder where you installed the SDK followed by the text \bin and a semicolon (";").

For example, if your PATH was c:\windows;c:\command and you installed the SDK into C:\jdk1.3, your new PATH should have the following value:

PATH c:\jdk1.3\bin;c:\windows;c:\windows\command

After making this change, look for a CLASSPATH variable. If you don't find it, you're done configuring the SDK. Click the Apply button to save your changes, and then reboot your computer.

If you do find CLASSPATH, place your cursor to the left of the existing CLASSPATH value and insert the SDK folder followed by the text \lib ools.jar;.;.

For example, if you installed the SDK into C:\jdk1.3 and your CLASSPATH had the value c:\javaclasses, your CLASSPATH variable should have the following value:

c:\jdk1.3\lib ools.jar;.;c:\javaclasses

After setting your CLASSPATH variable (if necessary), click the Apply button to make your changes permanent, and then reboot the computer.

Your First Java Program

Now that you have learned something about Java and installed development software, you're ready to start working with the language.

Before you do, you might want to take note of the most likely source of problems you'll run into -- errors caused by a misconfigured SDK.

Appendix A, "Configuring the Software Development Kit," is a short tutorial for Windows users on how to use MS-DOS and correct errors in how the SDK is set up. (There's also an online tutorial, Using the Software Development Kit on a Windows System.) See the appendix if you have problems compiling and running the first several examples from Day 1 and Day 2 on a Windows system-- especially if you run into "bad command or filename" errors and "NoClassDefFound" errors.

TIP: You also might want to read the appendix simply to learn a few MS-DOS commands. Windows users will be using the MS-DOS Prompt window throughout the book to compile and run Java programs.

It's a programming tradition to make the first example in a book like this a short program that displays text. Usually the text is simply "Hello world," but this book will break from tradition a bit to display something a little longer -- one of the most famous patently untrue predictions in U.S. history:

"The advancement of the arts, from year
to year, taxes our credulity, and seems
to presage the arrival of that period
when human improvement must end."
        Henry Ellsworth
        U.S. Commissioner of Patents
        1843 Annual Report of the Patent Office

The program that displays Ellsworth's quote will be an application, so you'll run it at a command line with the Java interpreter rather than loading it with a Web browser like an applet.

Although a Java program can be designed to be both an applet and an application, almost all programs you encounter will be one or the other.

Creating the Source File

Java programs begin as source code -- a series of statements created using a text editor or word processor and saved as a text file. You can use any program you like to create these files, as long as it can save the file as plain unformatted text -- a format that's also called ASCII text or DOS text.

Windows users can write Java programs with Notepad or Write, two editors that are included with the operating system. You also can use Microsoft Word, but must save files as text rather than in Word's proprietary format. UNIX and Linux users can author programs with emacs, pico, and vi; Macintosh users have SimpleText for Java source file creation.

The Software Development Kit does not include a text editor, but most other Java development tools include a built-in editor for creating source code files.

Writing the Program

Run your editor of choice and enter the Java program shown in Listing 1.1. Be careful that all the parentheses, braces, and quotation marks in the listing are entered correctly, and capitalize everything in the program exactly as shown. If your editor requires a filename before you start entering anything, use Ellsworth.java.

Listing 1.1: Source Code of Ellsworth.java.

 1: public class Ellsworth {
 2:     public static void main(String[] arguments) {
 3:         String line1 = "The advancement of the arts, from year ";
 4:         String line2 = "to year, taxes our credulity, and seems ";
 5:         String line3 = "to presage the arrival of that period ";
 6:         String line4 = "when human improvement must end.";
 7:         String quote = line1 + line2 + line3 + line4;
 8:         String speaker = "Henry Ellsworth";
 9:         String title = "U.S. Commissioner of Patents";
10:         String from = "1843 Annual Report of the Patent Office";
11:         System.out.println('\u0022' + quote + '\u0022');
12:         System.out.println(" " + speaker);
13:         System.out.println(" " + title);
14:         System.out.println(" " + from);
15:     }
16: }

The line numbers and colons along the left side of Listing 1.1 are not part of the program -- they're included so that the authors of this book can refer to specific lines by number in each program. If you're ever unsure about the source code of a program in this book, you can compare it to a copy on the book's official World Wide Web site.

After you finish typing in the program, save the file somewhere on your hard drive with the name Ellsworth.java.

TIP: If you're a Windows user who is unfamiliar with MS-DOS, open the root folder on your main hard drive and create a new subfolder called J21work. Save Ellsworth.java and all other Java source files from this book into that folder to make it easier to find them within MS-DOS.

If you're using Windows, a text editor such as Notepad might add an extra .txt file extension to the filename of any Java source files you save (which turns a name like Ellsworth.java into Ellsworth.java.txt). To avoid this problem, place quotation marks around the filename when saving a source file. Figure 1.4 shows this technique being used to save the source file Ellsworth.java from Windows Notepad.

Figure 1.4: Saving a source file from Windows Notepad.

TIP: A better solution is to use Windows Explorer to permanently associate .java files with the text editor you'll be using. This enables you to open a source file for editing by double-clicking the file in a Windows folder. To learn how to set this up, see Appendix B, "Using a Text Editor with the Software Development Kit."

Java source files must be saved with the extension .java.

Compiling and Running the Program Under Windows

Now you're ready to compile the source file. If you're using a development tool other than SDK 1.3, you should consult that software's documentation for details on how to compile Java programs.

With the SDK, you need to use the command-line tool javac, the Java compiler. The compiler reads a .java source file and creates one or more .class files that can be run by the Java virtual machine.

The compiler requires a command line. Windows users should open an MS-DOS Prompt window, then change folders to the one that contains Ellsworth.java.

If you saved the file into a newly created J21work folder inside the root folder on your main hard drive, the following MS-DOS command will open that folder:

cd \J21work

When you are in the correct folder, you can compile Ellsworth.java by entering the following at a command prompt: 

javac Ellsworth.java

Figure 1.5 shows the MS-DOS commands used to switch to the \J21work folder and compile Ellsworth.java.

Figure 1.5: Compiling Java programs in an MS-DOS window.

The SDK compiler does not display any message if the program compiles successfully. If there are problems, the compiler lets you know by displaying each error along with a line that triggered the error.

If the program compiled without any errors, a file called Ellsworth.class is created in the same folder that contains Ellsworth.java.

The class file contains the Java bytecode that will be executed by the Java interpreter. If you get any errors, go back to your original source file and make sure that you typed it exactly as it appears in Listing 1.1.

After you have a class file, you can run that file using a Java interpreter. The SDK's interpreter is called java, and it also is run from the command line.

Run the Ellsworth program by switching to the folder containing Ellsworth.class and entering the following:

java Ellsworth

You should see the Henry Ellsworth quotation displayed along with his name, job, and the place he wrote it.

NOTE: Make sure to leave off the .class extension when running a Java program with the java tool-- entering java Ellsworth.class will result in a "NoClassDefFound" error. If you leave off the .class extension and still get this error, you probably need to adjust how the SDK is configured. Help for Windows users with this problem is provided in Appendix A.

Figure 1.6 shows the successful output of the Ellsworth application along with the commands used to get to that point.

Figure 1.6: Compiling and running a Java application.

You will begin learning about the syntax and structure of a Java program tomorrow -- the purpose of today's tutorial is to compile and run a program successfully.

For now, it can be instructive to simply read source code such as Ellsworth.java and make an educated guess about what is happening in each line.

If the Ellsworth program were written in English instead of Java, the 16 lines could take the following form:

  1. Create a Java class file called Ellsworth.
  2. Begin the main part of the program.
  3. Create a string called line1 and use it to hold the text "The advancement of the arts, from year" followed by a linefeed character (" ").
  4. Create a string called line2 and use it to hold "to year, taxes our credulity, and seems" followed by a linefeed.
  5. Create the line3 string and use it to hold "to presage the arrival of that period" followed by a linefeed.
  6. Create the line4 string and use it to hold "when human improvement must end."
  7. Create the quote string and use it to hold the text contained in line1, line2, line3, and line4, in that order.
  8. Create the speaker string and use it to hold "Henry Ellsworth".
  9. Create the title string and use it to hold "U.S. Commissioner of Patents".
  10. Create the from string and use it to hold "1843 Annual Report of the Patent Office."
  11. Display a quotation mark (the Unicode character \u0022), the text contained in the quote string, and another quotation mark.
  12. Display a tab character (" ") followed by the contents of the speaker string.
  13. Display a tab followed by the contents of title.
  14. Display a tab followed by the contents of from.
  15. End the main part of the program.
  16. End the program.

Don't worry if you didn't guess right on the function of these lines -- everything used in the Ellsworth program will be completely introduced this week.

Summary

Java is a different language today than it was in 1995.

This has a good side -- a proven market for Java programmers exists at present and the skills are in huge demand. Five years ago you couldn't find "Java" in a classified ad outside of Silicon Valley, and even there the market consisted of Sun, Netscape, and only a few others.

This also has a bad side -- Java is at least five times as large today as it was upon its first release, so there's much more to learn.

For this reason, today was the last day for Java to be described in the abstract. The next 20 days will be spent at the command line, creating Java applications and applets, running them with the interpreter or a Web browser, and exploring the fundamental concepts of the language.

Q&A

Q: The license for the SDK is only for 180 days. I thought the kit was free -- don't you think you should have mentioned that rather predominately in your book?

A: Sun Microsystems has always made the SDK available for free, and it seems highly doubtful at this point that the company would change the policy. Although Sun has not made any official statements regarding the duration of the license, it appears to be a way to encourage developers to upgrade to new versions when they become available. Sun updates the SDK frequently, by issuing either a bug- and security-fix minor upgrade or a full upgrade such as the move to Java 2.

Q: Java 1.0 programs could be created with JDK 1.0. Java 1.1 programs could be created with JDK 1.1. Why is Java 2 using SDK 1.3? Shouldn't it be either Java 2 SDK 2 or Java 1.3 SDK 1.3?

A: Sun changed its naming scheme after Java 1.1 and JDK 1.1. The language was renamed Java 2 to capitalize on all the different products and technologies available in addition to the Software Development Kit. Although the Java Development Kit (JDK) was renamed as the Software Development Kit after JDK 1.1, it was numbered as version 1.2 instead of 2.

As a result of the changes, Java 1.2 is often used as a synonym for Java 2, JDK 2 is used when referring to SDK 1.2, and now JDK 1.3 is used in place of SDK 1.3. Sun, which received industry praise for the marketing savvy behind the choice of "Java" as a name for the language, has created a lot of confusion with this new numbering.

The current version of the language is called Java 2 and the current software development kit is Software Development Kit 1.3. The best way to figure out whether you're using the right version is to use SDK 1.3 or a tool that is fully compatible with SDK 1.3.

Quiz

Review today's material by taking this three-question quiz.

Questions

  1. When Java was first introduced to the public, it was most useful in what computing environment?
    • (a) Web servers
    • (b) Web browsers
    • (c) Personal digital assistants
  2. What is the compiled form of a Java program called?
    • (a) Machine code
    • (b) Espresso
    • (c) Bytecode
  3. Why did James Gosling create the first version of the Java language?
    • (a) He was frustrated with how C++ was performing on a project.
    • (b) He was trying to save the Green project from being cancelled by Sun.
    • (c) When you put C++ on a resume, personnel directors think it was your average in school.

Answers

  1. b. Although Java could run on servers, the main source of interest in the language in 1995 was how it could run in a Web browser as part of a page.
  2. c. The Java compiler turns a source code file into bytecode. A Java interpreter translates that bytecode into platform-specific machine code.
  3. a. Gosling's inspiration was the difficulty in debugging a large-scale C++ project because of pointer errors, memory allocation problems, and similar issues.

Exercises

To extend your knowledge of the subjects covered today, try the following exercises:

  • Take the linefeed characters out of the Ellsworth program, recompile the program, and run it to see how this changes the output.
  • Visit Sun's Java applet showcase to see examples of Java programs running on the Web.

Where applicable, exercise solutions are offered on the book's Web site.

HOME / ORDER THE BOOK / OTHER BOOKS / THANKS

Workbench | Books | RSS Feed | RSS Spec | Copyright 2024 World Readable