Java is one of the best programming languages to learn because it's auseful, powerful, modern technology that's embraced by thousands of programmers around the world.. However, if you ca
Trang 1SAMS Teach Yourself Programming with Java™ in 24 Hours, FOURTH EDITION
By Rogers Cadenhead
Publisher: Sams Pub Date: September 30, 2005 ISBN: 0-672-32844-5
coverage of core Java programming topics has also been expanded A great starting
point for learning Java, this book is also a great primer to reading sams Teach Yourself
Java in 21 Days.
Trang 2SAMS Teach Yourself Programming with Java™ in 24 Hours, FOURTH EDITION
By Rogers Cadenhead
Publisher: Sams Pub Date: September 30, 2005 ISBN: 0-672-32844-5
Trang 3Sending Arguments to Applications
Applet Basics
Sending Parameters to Applets
Workshop: Viewing the Code Used to Run Applets Summary
Trang 4Q&A
Quiz
Activities
Part III WORKING WITH INFORMATION IN NEW WAYS Hour 9 Storing Information with Arrays
Trang 5Q&A
Quiz
Activities
Hour 12 Making the Most of Existing Objects The Power of Inheritance
Establishing Inheritance
Working with Existing Objects
Storing Objects of the Same Class in Vectors Workshop: Creating a Subclass
Workshop: Creating Your Own Component Summary
Trang 6Sliders
Change Listeners
Menus
Workshop: Using Image Icons and Toolbars Summary
Trang 7Catching Errors as You Set Up URLs
Handling Screen Updates in the paint() Method Starting the Thread
Trang 8Creating a Sample Program
Appendix D Where to Go from Here: Java Resources
Trang 9JAVA™ DEVELOPMENT TOOLS JAVAC COMPILER SUPPLEMENTAL LICENSE TERMS JAVA™ INTERFACE CLASSES J2EE™ DEPLOYMENT SPECIFICATION INTERFACE CLASSES
resolver-1_1_nb.jar Based on Sun's XML Resolver 1.0 Software License Agreement What's on the CD-ROM
Windows Installation Instructions
UNIX and UNIX-like Installation Instructions
Index
Trang 10Copyright © 2006 by Sams Publishing
All rights reserved No part of this book shall be reproduced, stored in a retrievalsystem, or transmitted by any means, electronic, mechanical, photocopying,recording, or otherwise, without written permission from the publisher No
patent liability is assumed with respect to the use of the information containedherein Although every precaution has been taken in the preparation of this book,the publisher and author assume no responsibility for errors or omissions Nor isany liability assumed for damages resulting from the use of the informationcontained herein
as affecting the validity of any trademark or service mark
Warning and Disclaimer
Every effort has been made to make this book as complete and as accurate aspossible, but no warranty or fitness is implied The information provided is on an
"as is" basis The author and the publisher shall have neither liability nor
responsibility to any person or entity with respect to any loss or damages arising
Trang 11Bulk Sales
Sams Publishing offers excellent discounts on this book when ordered inquantity for bulk purchases or special sales For more information, pleasecontact
Trang 12dedicating it to my mother But I digress Someone was looking out for me when I stumbled drunkenly into the love of my life at a three-keg toga bacchanalia at the University of Texas-Arlington in 1987 I will always cherish the first moment when you stared at me through thick beer goggles and decided I wasn't as weird looking as you originally suspected Rogers
Trang 14To the folks at Samsespecially Mark Taber, Scott Meyers, John Purdum, andAndy Beaster No author can produce a book like this on his own, regardless ofwhat my agent told Sams during contract negotiations Their excellent work willgive me plenty to take credit for later on
To Laura Lewin at the Studio B agency, who worked hard on my behalf in
regard to this title and many others
To my wife, Mary, and my sons, Max, Eli, and Sam Although our family has notfulfilled my dream of becoming a high-wire trapeze team like the Flying
Wallendas, I'm the world's proudest husband in a non-acrobatic family
Trang 15I'd also like to thank readers who have sent helpful comments about corrections,typos, and suggested improvements to the book The list includes Brian
Converse, Philip B Copp III, Wallace Edwards, M.B Ellis, Kevin Foad, AdamGrigsby, Mark Hardy, Kelly Hoke, Donovan Kelorii, Russel Loski, Jason
Saredy, Mike Savage, Peter Schrier, Gene Wines, Jim Yates, and others whoshall remain nameless because they helped me improve the book before I startedthis list
Trang 16As the reader of this book, you are our most important critic and commentator.
We value your opinion and want to know what we're doing right, what we could
do better, what areas you'd like to see us publish in, and any other words ofwisdom you're willing to pass our way
You can email or write me directly to let me know what you did or didn't likeabout this bookas well as what we can do to make our books stronger
Please note that I cannot help you with technical problems related to the topic of this book, and that due to the high volume of mail I receive, I might not be able
to reply to every message.
When you write, please be sure to include this book's title and author as well asyour name and phone or email address I will carefully review your commentsand share them with the author and editors who worked on the book
Associate Publisher Sams Publishing
201 West 103rd Street Indianapolis, IN 46290 USA
Trang 17For more information about this book or others from Sams Publishing, visit ourwebsite at www.samspublishing.com Type the ISBN (excluding hyphens) or thetitle of the book in the Search box to find the book you're looking for
Trang 18As the author of computer books, I spend a lot of time lurking in the computersection of bookstores, observing the behavior of shoppers browsing through thebooks as if they were hominid jawbones and I was a paleontologist
Because of my research, I've learned that if you have picked up this book andturned to the introduction, I only have about 12 more seconds before you put itdown and head to the coffee bar for a double tall latte decaf skim with two shots
of vanilla hold the whip
So I'll keep this brief: Computer programming with Java is a lot easier than itlooks I'm not supposed to tell you that, because there are thousands of
programmers who have used their Java skills to get high-paying jobs in softwaredevelopment, web application programming, and e-commerce The last thingany of them want is for their bosses to know that anyone who has persistenceand a little free time can learn this language, the most popular programminglanguage in use today By working your way through each of the one-hour
tutorials in Sams Teach Yourself Programming with Java in 24 Hours, Fourth
Edition, you'll be able to learn Java programming quickly.
Anyone can learn how to write computer programseven if they can't program aVCR Java is one of the best programming languages to learn because it's auseful, powerful, modern technology that's embraced by thousands of
programmers around the world
This book is aimed at non-programmers, new programmers who hated learningthe subject, and experienced programmers who want to quickly get up to speedwith Java It uses Java 2 version 5, the current version of the language
Java is the Tiger Woods of programming languages because of the things itmakes possible You can create programs that feature a graphical user interface,design software that makes the most of the Internet, read XML data, add
animation to World Wide Web pages, and more
This book teaches Java programming from the ground up It introduces the
Trang 19object-oriented programming
These terms might not mean much to you now In fact, they're probably the kind
of thing that makes programming seem like a secret ritual for a weird group ofhumans who have a language of their own However, if you can use a computer
to create an attractive resume, balance your checkbook, or create a home page,
you can write computer programs by reading Sams Teach Yourself Programming
with Java in 24 Hours, Fourth Edition.
Trang 20At this point, if you would rather have coffee than Java, please reshelve this book with the front cover facing outward on an endcap with access to a lot of the store's foot traffic.
Trang 22Computer programming is insanely difficult It requires a four-year degree incomputer science, thousands of dollars in computer hardware and software, akeen analytical intellect, the patience of Job, and a strong liking for caffeinateddrinks If you're a programming novice, this is probably what you've heard aboutcomputer programming Aside from the part about caffeine, all of the rumors aregreatly exaggerated
Programming is easier than most people think, although there are several reasonswhy 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-payingjobs and gives us more leeway to goof off during business hours
Computer programming manuals are often written in a language that only aScrabble player could appreciate Strange acronyms like OOP, RAD, COM,and MUMPS are used frequently along with newly invented jargon likeinstantiation, bytecode, and makefile
Many computer programming languages have been available only withsoftware 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 tolearn programming Useful programming tools are being made available at lowcost (or no cost), often as downloads from World Wide Web sites Thousands ofprogrammers are distributing their work under "open source" licenses so peoplecan examine how the programs were written, correct errors, and add their ownimprovements
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 anintense passion The English language will be used as much as possible instead
of jargon and obscure acronyms, and all new programming terms will be
Trang 23If I've succeeded, you will finish Sams Teach Yourself Programming with Java 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 moreconfidence, and learn programming languages more easily You also will havedeveloped skills with Java, the most innovative programming language to beintroduced in years
The first hour of this book provides some introductory material about
programming and gives you instructions on how to set up your computer so youcan write Java programs The following topics will be covered:
Trang 24to program because BASIC was created with beginners in mind.
Trang 25in other languages such as Borland C++ This difference is especially noticeable
in programs that use a lot of graphicsgames, screen savers, and the like
This book covers the Java programming language, which was developed by SunMicrosystems Though Java is more difficult to learn than a language such asVisual Basic, it is a good starting place for several reasons One advantage oflearning 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 Theycan be used to create chat rooms, play games, and help in other interactive
efforts
Another important advantage is that Java requires an organized approach forgetting 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 itsrules
When you start writing Java programs, you might not see the language's choosybehavior as an advantage You'll write a program and have several errors to fixbefore the program is finished Some of your fixes might not be correct, and they
Trang 26In the coming hours, you'll learn about these rules and the pitfalls to avoid Thepositive 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 betterway to create computer programs Gosling was unhappy with the way that theC++ 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 debatewhether Java is superior to other programming languages, of course, but theamount of attention paid to the language today shows that it has a large number
of adherents Book publishers obviously dig itmore than 1,000 books have beenpublished about the language since its introduction (This is my thirteenth, and Iwill keep writing more of them until prohibited by municipal, state, or federallaw.)
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 fill the classified ads in many cities, and the language hasbecome 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 learnsubsequent languages Many languages are similar to each other, so you won't bestarting 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 itsstructure and ideas from C++ Many programmers are comfortable using severaldifferent languages and will learn new ones as needed
Trang 27C++ is 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.
Trang 28Dear Rosie,
Please take care of these errands for me while I'm out lobbying members ofCongress:
Trang 29be accomplished through a variety of routes
Computers don't do leeway They follow instructions literally The programs thatyou write will be followed precisely, one statement at a time
The following is one of the simplest examples of a computer program, written inBASIC Take a look at it, but don't worry yet about what each line is supposed tomean
1 PRINT "Shall we play a game?"
2 INPUT A$
Translated into English, this program is equivalent to giving a computer thefollowing to-do list:
Trang 30Windows, Apple Macintosh, and Linux systems You can find out more about it
at http://www.libertybasic.com
Figure 1.1 An example of a BASIC program running in Liberty
BASIC.
Trang 31That's the bad news The good news is that you can't do any permanent harm toyour computer with the programming errors you make No one was harmedduring the making of this book, and no computers will be injured as you learnhow to program with Java.
Trang 32Most computer programs are written in the same way that you write a letterbytyping each statement into a word processor Some programming tools comewith their own word processor, and others can be used with any text-editingsoftware If you don't already have a tool that can be used for Java programming,you can use the free Java Development Kit, which you will learn about later inthis hour, with any of your favorite editors
When you have finished writing a computer program, you save the file just likesaving any other document to disk Computer programs often have their ownfilename extension to indicate what type of file they are Java programs have theextension java; an example of a Java program filename is
Calculator.java
Trang 33program that interprets each line of a computer program and tells the computerwhat to do Most versions of BASIC are interpreted languages The advantage ofinterpreted 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, andtry 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 Thecompiled program can be run directly, without the need for an interpreter
Compiled programs run more quickly than interpreted programs, but they takemore time to test You have to write your program and compile it before trying itout If you find an error and fix it, you must compile the program again to verifythat the error is gone
Java is unusual because it requires a compiler and an interpreter You'll learnmore about this later as you write Java programs
Trang 35Before you can start writing Java programs, you need to acquire and set up somekind of Java programming software Although several different products areavailable for the development of Java programs, including many terrific onesthat make programming much easier, the starting place for most new Java
programmers is the Java Development Kit, a set of tools for writing, debugging,and running Java programs All of the examples in this book were created andtested using the Kit, but they can be created with any Java development tool thatsupports the current version of the language
The Java Development Kit (also referred to as the JDK) is in version 5 as of thiswriting Whenever Sun releases a new version of Java, the first tool that supports
it is the Kit
To create all of the programs in this book, you must either use Java DevelopmentKit 5 or another Java programming tool that fully supports all of version 5'sfeatures
There are many different software packages that offer the capability to createJava programs, but all are not created equal when language support is concerned.Some of these programming tools only support Java 1.0, the initial version of thelanguage, which was released by Sun Microsystems in late 1995 Other toolssupport Java 1.1, which was released in mid-1997, version 1.2 (1998), version1.3 (2000), or version 1.4 (2003)
Some operating systems such as Mac OS X and Red Hat Enterprise Linux
include a copy of the JDK, but it's probably not the current version Before using
an JDK that was included with your operating system, make sure it supports Javaversion 5
Users of Microsoft Windows systems may be dismayed to learn that the JavaDevelopment Kit is not graphical You run programs from a command line (the
C:\> or D:\> prompt that will be familiar to MS-DOS users) instead of using amouse and a point-and-click environment Figure 1.2 shows the Kit in use in anMS-DOS window on a Windows XP system The Java program
Trang 36Figure 1.2 A program being compiled and run with the Java
Development Kit.
Trang 37documentation is available at http://java.sun.com/j2se/1.5.0/docs/api
Trang 38Every hour of this book ends with a workshop, a Java programming project youcan undertake to enhance your knowledge of the subject matter while it
percolates in your brain
However, you won't be doing any Java programming at all until you install aJava development tool on your computer
If you have a program such as Borland JBuilder, Sun NetBeans, or IntelliJ
IDEA, you can use it to develop the tutorial programs in the next 23 hours
However, you should already have some familiarity with how to use the
programlearning Java and a complex development tool at the same time can bedaunting
If you don't have a Java development tool, or the last paragraph scared you awayfrom using one that you own, you can use the Java Development Kit, which isavailable for free from Sun's Java website at http://java.sun.com
Though the process is relatively straightforward, there are some configurationissues that cause problems for many people trying to get started with the Kit,especially on a Windows system To find out how to download and install theKit and fix any configuration problems that arise, read Appendix A, "Using theJava Development Kit."
Trang 39During this hour, you were introduced to the concept of programming a
computergiving it a set of instructions that tell it what to do You also might havedownloaded and installed a Java development tool that will be used as you writesample programs throughout the book
If you are still confused about programs, programming languages, or Java ingeneral, that's understandable at this point Everything will make more sense toyou in the next hour, "Writing Your First Program," which takes a slow trip
through the process of creating a Java program
Trang 40Q1:What is it about BASIC that makes it easier to fall into bad habits while writing programs?
A1:
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 how the program functions when you try to fix a bug or add an improvement.
Q2:BASIC? C++? Java? What are the names of these languages supposed to mean?
A2:
Like many programming languages, BASIC gets its name from 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 monikersbeating out WebRunner, Silk, Ruby, and others.