Owl Sams Teach Yourself Java 2 in 24 Hours
The 24 Hours line of books from Sams Publishing offers the best entry-level tutorials for people who are new to a subject. To give you a better idea of the approach taken by Sams' Teach Yourself Java 2 in 24 Hours, this page reproduces Chapter 1 of the book. Read it for an introduction to computer programming and how the book will teach Java 2.

Chapter 1: Becoming a Programmer

From Sams' Teach Yourself Java 2 in 24 Hours by Rogers Cadenhead

Computer programming is insanely difficult. It requires a four-year degree in computer science, thousands of dollars in computer hardware and software, a keen analytical intellect, the patience of Job, and a strong liking for caffeinated drinks. If you're a programming novice, this is probably what you've heard about computer programming. Aside from the part about caffeine, all of the rumors are greatly exaggerated.

Programming is a lot easier than most people think. There are several reasons why you might believe otherwise:

  • Computer programmers have been telling people for years that programming is hard. This belief makes it easier for us to find high-paying jobs (or so I've heard) and gives us more leeway to goof off during business hours.
  • Computer programming manuals are often written in a language that only a Scrabble player could appreciate. Strange acronyms like OOP, RAD, COM, and MUMPS are used frequently along with newly invented jargon like instantiation, bytecode, and makefile.
  • Many computer programming languages have been available only with software packages costing $200 or more, which is a lot of cabbage.

Because of the growth of the Internet and other factors, this is a great time to learn programming. Useful programming tools are being made available at low cost (or no cost), often as downloads from World Wide Web sites. The goal of this book is to teach programming to the person who has never tried to program before or the person who tried programming but hated it with an intense passion. The English language will be used as much as possible instead of jargon and obscure acronyms, and all new programming terms will be thoroughly explained as they are introduced.

If I've succeeded, you will finish Sams' Teach Yourself Java 2 in 24 Hours with enough programming skill to be a danger to yourself and others. You'll be able to write programs, dive into other programming books with more confidence, and learn programming languages more easily. You also will have developed skills with Java, the most exciting programming language to be introduced in a decade.

The first hour of this book provides some introductory material about programming and gives you instructions on how to set up your computer so you can write Java programs. The following topics will be covered:

  • Choosing which programming language to learn first
  • What Java is
  • Using programs to boss your computer around
  • How programs work
  • How program errors called bugs are fixed
  • Acquiring the free Java Development Kit
  • Installing the Kit
  • Getting ready to write programs

Choosing a Language

As you might have surmised at this point, computer programming is not as hard as it's cracked up to be. If you're comfortable enough with a computer to create a nice-looking resume, balance a checkbook with software such as Intuit Quicken, or create your own home page on the Web, you can write programs.

The key to learning how to program is to start with the right language. The programming language you choose to use often depends on the tasks you want the computer to accomplish. Each language has things it is well-suited for and things that are difficult, or perhaps impossible, to do with the language. For example, many people use some form of the BASIC language when they are learning how to program because BASIC is good for learning how to write programs.

Note: The BASIC language was invented in the 60s to be easy for students and beginners to learn (the B in BASIC stands for Beginner's). The downside to using some form of BASIC is that it's easy to fall into some sloppy programming habits with the language. Those habits can make it much more difficult to write complex programs and improve them later.

Microsoft Visual Basic combines the ease of BASIC with some powerful features to aid in the design of Windows software. (VBScript, which is short for Visual Basic Script, offers the simplicity of BASIC for small programs that run in conjunction with World Wide Web pages.) Visual Basic has been used to write thousands of sophisticated programs for commercial, business, and personal use. However, Visual Basic programs can be slower than Windows programs written in other languages such as Borland C++. This difference is especially noticeable in programs that use a lot of graphics -- games, screen savers, and the like. Because of that, game programmers and other multimedia developers don't use Visual Basic to create graphical programs such as Age of Empires and Quake.

This book uses the Java programming language, which was developed by Sun Microsystems. Though Java is more difficult to learn than a language such as Visual Basic, it is a good starting place for several reasons. One of the biggest advantages of learning Java is that you can use it on the World Wide Web. If you're an experienced Web surfer, you have seen numerous Java programs in action. They can be used to create animated graphics, present text in new ways, play games, and help in other interactive efforts.

Another important advantage is that Java requires an organized approach for programs to work. The language is very particular about the way programs must be written, and it balks if programmers do not follow all of its rules. When you start writing Java programs, you might not see the language's choosy behavior as an advantage. You'll write a program and will have several errors to fix before the program will be finished. Some of your fixes might not be correct, and they will have to be redone. If you don't structure a program correctly as you are writing it, errors will result. In the coming hours, you'll learn about these rules and the pitfalls to avoid. The positive side of this extra effort is that your programs will be more reliable, useful, and error-free.

Java was invented by Sun Microsystems developer James Gosling as a better way to create computer programs. Gosling was unhappy with the way that the C++ programming language was working on a project he was doing, so he created a new language that did the job better. It's a matter of contentious debate whether Java is superior to other programming languages, of course, but the amount of attention paid to the language today shows that it has a large number of adherents. Book publishers obviously dig it -- more than 1,000 books have been published about the language since its introduction. (This is my fourth, and I will write more of them until prohibited by municipal, state, or federal law.) Regardless of whether Java is the best language, it definitely is a great language to learn today. There are numerous resources for Java programmers on the Web, Java job openings are increasing, and the language has become a major part of the Internet's past, present, and future. You'll get a chance to try out Java during Hour 2, "Writing Your First Program."

Learning Java or any other programming language makes it much easier to learn subsequent languages. Many languages are similar to each other, so you won't be starting from scratch when you dive into a new one. For instance, many C++ programmers find it fairly easy to learn Java because Java borrows a lot of its structure and ideas from C++. Many programmers are comfortable using several different languages and will learn new ones as needed.

Note: C++ has been mentioned several times in this hour, and you might be tripping over the term wondering what it means and, more importantly, how it's pronounced. C++ is pronounced C-Plus-Plus, and it's a programming language that was developed by Bjarne Stroustrop and others at Bell Laboratories. C++ is an enhancement of the C programming language, hence the Plus-Plus part of the name. Why not just C+, then? The Plus-Plus part is a computer programming joke you'll understand later on.

Telling the Computer What to Do

A computer program, also called software, is a way to tell a computer what to do. Everything that the computer does, from booting up to shutting down, is done by a program. Windows 95 is a program. Ms. Pac-Man is a program. The dir command used in MS-DOS to display file names is also a program. Even the Michaelangelo virus is a program.

Computer programs are made up of a list of commands the computer handles in a specific order when the program is run. Each of these commands is called a statement.

If you're a science fiction fan, you're probably familiar with the concept of household robots. If not, you might be familiar with the concept of henpecked spouses. In either case, someone gives very specific instructions telling the robot or spouse what to do, something like the following:

Dear Theobald,

Please take care of these errands for me while I'm out lobbying members of Congress:

Item 1: Vacuum the living room.

Item 2: Go to the store.

Item 3: Pick up butter, lozenges, and as many SnackWells Devil's Food Cakes as you can carry.

Item 4: Return home.


Snookie Lumps

If you tell a loved one or artificially intelligent robot what to do, there's a certain amount of leeway in how your requests are fulfilled. If lozenges aren't available, cough medicine might be brought to you instead. Also, the trip to the store can be accomplished through a variety of routes. Computers don't do leeway. They follow instructions literally. The programs that you write will be followed precisely, one statement at a time.

The following is one of the simplest examples of a computer program, written in BASIC. Take a look at it, but don't worry yet about what each line is supposed to mean.

1 PRINT "Shall we play a game?"


Translated into English, this program is equivalent to giving a computer the following to-do list:

Dear personal computer,

Item 1: Display the question, "Shall we play a game?"

Item 2: Give the user a chance to answer the question.


Snookie Lumps

Each of the lines in the computer program is a statement. A computer handles each statement in a program in a specific order, in the same way that a cook follows a recipe or Theobald the robot followed the orders of Snookie Lumps when he vacuumed and shopped at the market. In BASIC, the line numbers are used to put the statements in the correct order. Other languages, such as Java, do not use line numbers, favoring different ways to tell the computer how to run a program.

Figure 1.1 shows the sample BASIC program running on the Bywater BASIC interpreter, which is available for free in several shareware file repositories on the World Wide Web and can run on any DOS or UNIX platform. Bywater BASIC is among many free BASIC interpreters that can be found on the Internet for Microsoft Windows, Apple Macintosh, UNIX, and Linux systems.

Figure 1.1: An example of a BASIC program running on the Bywater BASIC shell and interpreter developed by Ted A. Campbell.

Note: The quote "Shall we play a game?" is from the 1983 movie WarGames, in which a young computer programmer (portrayed by Matthew Broderick) saves mankind after nearly causing global thermonuclear war and the near-extinction of humankind. You'll learn how to do that in the next book of this series, Sams' Teach Yourself to Create International Incidents with Java in 24 Hours.

Because of the way programs operate, it's hard to blame the computer when something goes wrong while your program runs. After all, the computer was just doing exactly what you told it to do. Unless your hardware is on the fritz, a pesky virus is attacking your system, or your operating system is having a bad day, the blame for program errors lies with the programmer. That's the bad news. The good news is that you can't do any permanent harm to your computer with the programming errors you make. No one was harmed during the making of this book, and no computers will be injured as you learn how to program with Java.

How Programs Work

Most computer programs are written in the same way that you write a letter -- by typing each statement into a word processor. Some programming tools come with their own word processor, and others can be used with any text-editing software. You can use the Java Development Kit, which you will learn about later in this hour, with any of your favorite editors.

When you have finished writing a computer program, you save the file just like saving any other document to disk. Computer programs often have their own filename extension to indicate what type of file they are. Java programs have the extension .java; an example of a Java program file name is Calculator.java.

Note: If you use a fancy word processing program that has features such as boldfaced text, different font sizes, and other stylistic touches, do not use those features while writing a computer program. Programs should be prepared as text files with no special formatting. For example, when using Microsoft Word to write a program, save the file in Text Only mode instead of saving it as a Word document. Notepad, a word processor that comes with Windows, saves all files as unformatted text.

For this program to run, you need some help. The kind of help that's needed depends on the programming language you're using. Some languages require an interpreter to run their programs. The interpreter is a program that interprets each line of a computer program and tells the computer what to do. Most versions of BASIC are interpreted languages. The advantage of interpreted languages is that they are faster to test. When you are writing a BASIC program, you can try it out immediately, spot any errors, fix them, and try again. The primary disadvantage is that interpreted languages run more slowly than other programs.

Other programming languages require a compiler. The compiler takes a computer program and translates it into a form that the computer can understand. It also does what it can to make the program run as efficiently as possible. The compiled program can be run directly, without the need for an interpreter. Compiled programs run more quickly than interpreted programs, but they take more time to test. You have to write your program and compile it before trying it out. If you find an error and fix it, you must compile the program again to verify that the error is gone.

Java is unusual because it requires a compiler and an interpreter. You'll learn more about this later as you write Java programs.

How Programs Don't Work

Many new programmers become discouraged when they start to test their programs. Errors appear everywhere. Some of these are syntax errors, which are identified by the computer as it looks at the program and becomes confused by what you wrote. Other errors are logic errors, which are only noticed by the programmer as the program is being tested, if they are noticed at all. Logic errors sneak by the computer unnoticed, but they will cause it to do something unintended.

As you start to write your own programs, expect to encounter errors. They're a natural part of the process. Programming errors are called bugs, a term that dates back a century or more to describe errors in technical devices. The process of fixing errors has its own term also: debugging. Whether you want to or not, you'll get a lot of debugging experience as you learn how to write computer programs.

While you're learning Java by reading this book, it's likely that many thousands of your programming colleagues will be hard at work on the biggest debugging project in history: the "Year 2000 problem." This crisis is caused by computer programs that will experience logic errors on Jan. 1, 2000, because of the way the programs incorrectly handle year values beyond 1999.

The biggest contributor to this problem is that many programmers decided to store year dates as two-digit values: 1967 became 67, 1998 became 98, and so on. Memory was at a premium for most programmers in the past decades when most of the affected programs were written, so the two digits saved came in handy elsewhere.

The Year 2000 problem rears its head when a computer compares two of these two-digit dates and one of them is higher than 99. A person who is 32 years old in 1999 (99-67=32) becomes -67 years old in 2000 (00-67=-67). Try buying the right number of candles for that person's birthday cake.

If you're wondering how programmers could have let this happen, most didn't think their work would still be running in 2000. This lack of foresight has turned into the Godzilla of all logic bugs.

Next Stop: Java

Before you can start writing Java programs, you need to acquire and set up some kind of Java programming software. Although several different products are available for the development of Java programs, including many terrific ones that make programming much easier, the starting place for most new Java programmers is the Java Development Kit. All of the examples in this book use the Kit, and you are encouraged to forsake all other Java programming tools as you go through the remaining 23 hours of tutelage. The material will make more sense to programmers using the Kit, and it builds experience that will be beneficial no matter which development software you use later on.

The Java Development Kit (also referred to as the JDK) is in version 2 as of this writing. It is a set of tools that enable you to write and test Java programs, and the version number of the Kit corresponds with a version number of the language itself.

This book teaches the techniques of Java 2, the edition of the language first introduced in 1998. The first programming tool to offer full support for Java 2 is version 2 of the Java Development Kit.

To create all of the programs in this book, you must either use Java Development Kit 2 or another Java programming tool that fully supports Java 2. There are many different software packages that offer the ability to create Java programs, but all of these are not created equal when language support is concerned.

Some of these programming tools only support Java 1.0.2, the initial version of the language, which was released by Sun Microsystems in late 1995. Other tools support Java 1.1, which was released in mid-1997.

Users of Microsoft Windows systems may be dismayed to learn that the Java Development Kit is not graphical. You run programs from a command line (the C:\> prompt that will be familiar to MS-DOS users) instead of using a mouse and a point-and-click environment. Figure 2 shows the Kit in use in an MS-DOS window on a Windows 95 system. The Java program WarGames.java is compiled, and then it is run.

Caution: The examples of this book were prepared on a Microsoft Windows 95 system, and some references in the text are specific to Windows users. However, all of the material is intended for users of the Java Development Kit on any of the platforms for which it is currently available. All of the code in this book's tutorial programs will work regardless of the system you're using.

Figure 1.2: A program being compiled and run with the Java Development Kit version 2.

At the time of this writing, the Java Development Kit version 2 is available directly from Sun Microsystems for the following systems:

  • Microsoft Windows NT or Windows 95 systems
  • Solaris SPARC and Solaris x86 systems

The Windows 95/NT version of the Kit is provided in two versions. One version is listed as an EXE file, which means that you can install it by clicking the file's icon when you download it. This version is the easiest to set up. The other version can be downloaded as a .Zip archive file.

The World Wide Web page from which to download versions of the Kit is found at http://java.sun.com/products/JDK/1.2/.

Although Sun Microsystems has not announced plans to make version 2 of the Kit available for other systems, other companies have created implementations of the Java language for non-Windows and non-Solaris systems. Details about these implementations are provided in the "Products and APIs" section of Sun's official Java site, which is available at http://java.sun.com.

At present, Sun offers a list of available Java development tools organized by operating system at http://java.sun.com/cgi-bin/java-ports.cgi.

If your system can handle the Java Development Kit, download it from the Web and save it on your system in a temporary folder. The file is several megabytes in size, so you'll have time during the download to make coffee, knit a cardigan, or gnaw your foot off to escape any bear traps it might be caught in.

Workshop: Installing the JDK

After the Java Development Kit has been downloaded to a temporary folder, you're ready to install it. Sun's own installation documentation supplements the information provided during this hour, so be sure to consult it if you have any questions about how the installation should be handled.

Windows Installation

Windows 95 and Windows NT versions of the Kit can be installed by double-clicking the name of the downloaded file. After you confirm that you're ready to install the Kit, a dialog box will open enabling you to determine how it will be installed on your system (see Figure 1.3).

Figure 1.3: Selecting how Java Development Kit 2 will be installed.

The default settings for this wizard should be fine for the work you'll be during in this book, with the possible exception of the Destination Directory setting. The JDK will be installed in a folder with a name based on the version you're downloading, such as \jdk2). You can select a different folder by using the Browse button.

Tip: As a hedge against any configuration problems that may occur, you should install the Kit into the folder \jdk2 either by accepting it as the default choice or by using Browse, if necessary, to select it. All troubleshooting sections will refer to \jdk2 as the place where the Kit has been installed.

Solaris Installation

Other versions of the Kit are packed as an archive file that has been compressed to reduce its size. These versions will have a filename extension such as .zip, .z, .gz, or .tar in the name. To use these, you must use decompressing software such as WinZip, untar, gzip, or PKZip.

If you don't own any software that can handle archive files, you can find programs for all common archive types on the Web. The file search engine at http://www.shareware.com offers a way to find archive utilities for all popular operating systems. Searching for text such as unzip or untar will turn up several programs that can handle these archive formats.

The Kit's installation archive should be decompressed into a directory that does not already have a subdirectory called jdk2. Otherwise, you might overwrite some existing files.

Next, you should make sure you can access the file correctly by using chmod a+x shell command on the filename.

For example, SPARC users would use the following command:

% chmod a+x jdk12-solaris2-sparc.bin

To install the JDK after making the chmod change, use a shell window to enter the command ./ followed by the archive filename. The following is an example:

% ./jdk12 -solaris2-sparc.bin

If you already have ./ in your $PATH environment variable, you won't have to include it in the command.

Testing the Installation

The Java Development Kit includes a Readme file in the main folder where the Kit was installed. This file gets its name for a good reason: You should read it right away to find out about any last-minute notes from the developers of the Kit. Any bugs, warnings, and major announcements about the Kit will be included in Readme.

Once you have installed the Kit, it should work right away. Along the same lines, rush hour should really rush, nothing should ever be described as "completely unfinished," and ATMs should be described as AT machines, not ATM machines.

However, the most commonplace errors to watch for during the first several hours of this book are a result of a misconfigured Kit.

Windows users can test their Kit installation by using the MS-DOS Prompt command (Start, Programs, MS-DOS prompt on most systems). This brings up an MS-DOS window where you can enter commands with your keyboard. You'll explore this feature fully during the next hour.

For now, you need to enter a command that tests whether your system can find the Java Development Kit you just installed. Enter the following in the MS-DOS window:

java -version

If you're using version 2 of the Kit, you should see the following message in response:

java version "2"

The version number might be more specific than 2 if you have downloaded a newer release of Java Development Kit 2, such as 2.1. The more specific number should be displayed in response to the java -version command.

If you see the wrong version number or get a "Bad command or file name" error, your system can't find the right version of java.exe, the program that runs Java programs. This must be corrected before you can start writing Java programs. Read Appendix D, "Configuring the Java Development Kit," to learn how to take care of this problem.

Sun Microsystems also offers help on the installation process at http://java.sun.com/products/JDK/1.2/.

Official Documentation

In addition to the Java Development Kit, Sun Microsystems offers comprehensive documentation for the Java language in Web page format. You don't need this information to use this book because each topic is discussed fully as it is introduced, but these pages will come in handy when you write your own programs.

You can download the entire documentation, but it might be more convenient to browse it as needed from Sun's Web site. The most up-to-date Java documentation is available at http://java.sun.com/products/JDK/1.2/docs/index.html.


During this hour, you were introduced to the concept of programming a computer -- giving it a set of instructions that tell it what to do. You also downloaded and installed the Java Development Kit that will be used as you write sample programs throughout the book.

If you are still confused about programs, programming languages, or Java in general, that's understandable at this point. Everything will make more sense to you in the next hour, "Writing Your First Program," which takes a slow trip through the process of creating a Java program.


  • Q: What does the Internet have to do with making it easier to learn programming?
    A: Because of the dramatic growth of the World Wide Web, companies such as Microsoft, Netscape, and Sun Microsystems are trying to attract as many programmers as possible to their languages and related technology. To do this, they are offering many programming tools for free over the Web, such as the Java Development Kit and the Microsoft Visual Basic 5 Control Creation Edition, and are offering others for free 30- or 90-day trial periods, such as SunSoft Java WorkShop. There also are numerous free products distributed over the Internet for programmers. To find out where these products are, visit a Web directory such as Yahoo! at http://www.yahoo.com and search for a language that interests you. It's much cheaper today to learn programming than it was five years ago.
  • Q: What is it about BASIC that makes it easier to fall into bad habits while writing programs?
    A: One thing you'll learn as you start writing Java programs is that you have to be organized. If you don't structure your program in the correct way, it won't work. BASIC doesn't have this kind of requirement. You can write in a disorganized manner and still get the program to work successfully. Later on, however, you'll have a much harder time figuring out the program if you try to fix a bug or add an improvement.
  • Q: BASIC? C++? Java? What are the names of these languages supposed to mean?
    A: Like many programming languages, BASIC is an acronym that describes what it is: Beginner's All Symbolic Instruction Code. C++ is a programming language that was created to be an improvement on the C language, which itself was an improvement of the B programming language. Java goes against the tradition of naming a language with an acronym or other meaningful term. It's just the name that Java's developers liked the best when brainstorming for possible monikers -- beating out WebRunner, Silk, Ruby, and others.
  • Q: There are more than 1,000 books about Java programming?
    A: According to the official JavaWorld count, there are at least that many. The online Java magazine, which is available at http://www.javaworld.com, maintains a guide to all upcoming and in-print books related to Java and other Internet technology. This guide is available at http://www.javaworld.com/javaworld/books/jw-books-index.html.
  • Q: Why are interpreted languages slower than compiled ones?
    A: For the same reason that a person interpreting a live speech is a lot slower than a translator interpreting the printed speech later on. The live interpreter has to think about each statement that's being made as it happens, while the other interpreter can work on the speech as a whole and take some shortcuts to speed up the process. Compiled languages can be much faster than interpreted languages because they can do things to make the program more efficient.
  • Q: Is C++ harder to learn than Java?
    A: It's a matter of personal opinion, but Java does seem more approachable for beginners than C++. C++ and its predecessor, C, are widely regarded as "programmer's languages," meaning that they were designed for the needs of experienced programmers. There are a lot of features in C and C++ that make them faster -- and more powerful -- during program creation, but these features often come at the expense of understandability. Java takes a more simplified approach to programming than C++ and is probably a better place to start.


Test your knowledge of the material covered in this chapter by answering the following questions.


  1. Which of the following is not a reason that people think computer programming is painfully difficult?
    • (a) Programmers spread that rumor to improve their employment prospects.
    • (b) Jargon and acronyms are all over the place.
    • (c) Mind-control waves are sent out by the CIA promoting this belief.
  2. What kind of tool runs a computer program by figuring out one line at a time?
    • (a) A slow tool
    • (b) An interpreter
    • (c) A compiler
  3. Why did James Gosling hole up in his office and create Java?
    • (a) He was unhappy with the language he was using on a project.
    • (b) His rock band wasn't getting any gigs.
    • (c) When you can't download any image files at work, the World Wide Web is pretty dull.


  1. c. Of course, the CIA could have forced me to say this.
  2. b. Compilers figure out the instructions beforehand so the program can run faster.
  3. a. The Web was still a little-known idea when Gosling wrote Java.


If you'd like to better introduce yourself to the subjects of Java and computer programming, do the following activities:

  • Visit Sun's official Java site at http://java.sun.com and read some of the introductory articles that are presented in the Read About Java section.
  • Using English sentences instead of a programming language, write a set of instructions to add 10 to a number selected by a user and then multiply the result by 5. Break the instructions into as many short one-sentence lines as you can.

To see solutions to the activities at the end of each hour, visit the book's Web site.