|
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 ProgrammerFrom Sams' Teach Yourself Java 2 in 24 Hours by Rogers CadenheadComputer 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:
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 a LanguageAs 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.
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.
Telling the Computer What to DoA 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:
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.
Translated into English, this program is equivalent to giving a computer the following to-do list:
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.
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 WorkMost 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
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 WorkMany 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: JavaBefore 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
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:
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 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 JDKAfter 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 InstallationWindows 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
Solaris InstallationOther 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 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 Next, you should make sure you can access the file correctly by using
For example, SPARC users would use the following command:
To install the JDK after making the chmod change, use a shell window to
enter the command
If you already have Testing the InstallationThe 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:
If you're using version 2 of the Kit, you should see the following message in response:
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 DocumentationIn 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. SummaryDuring 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&A
QuizTest your knowledge of the material covered in this chapter by answering the following questions. Questions
Answers
ActivitiesIf you'd like to better introduce yourself to the subjects of Java and computer programming, do the following activities:
To see solutions to the activities at the end of each hour, visit the book's Web site. |