Tải bản đầy đủ

Sybex ground up java nov 2003 ISBN 0782141900

Ground-UpJava
ISBN:0782141900
byPhilip
Heller
Sybex©2003(488pages)
Inadditiontolearningthe
coreJavalanguage,youwill
alsoacquireabroad
understandingofvital
programmingconcepts,
includingvariables,control,
memory,indirection,
compilation,andcalling.
TableofContents
Ground-UpJava
Introduction
AnIntroductionto
Chapter1 - ComputersThatWill
ActuallyHelpYouinLife
Chapter2 - Data
Chapter3 - Operations

Chapter4 - Methods
Chapter5 - ConditionalsandLoops
Chapter6 - Arrays
Chapter7 - IntroductiontoObjects
Chapter8 - Inheritance
Chapter9 - PackagesandAccess
Chapter10 - Interfaces
Chapter11 - Exceptions


Chapter12 - TheCoreJavaPackages
andClasses
Chapter13 - FileInputandOutput
Chapter14 - Painting
Chapter15 - Components
Chapter16 - Events
Chapter17 - FinalProject
Downloadingand
AppendixA InstallingJava
AppendixB - SolutionstotheExercises
Glossary
Index
ListofFigures
ListofTables


BackCover
ThisisthefirsteffectiveJavabookfortruebeginners.
Sure,booksbeforenowfocusedonbasicconceptsand
keytechniques,andsomeevenprovidedworking
examplesonCD.Still,theylackedthepowerto
transformsomeonewithnoprogrammingexperience
intosomeonewhosees,whoreally“getsit.”
WorkingwithGround-UpJava,youwilldefinitelygetit.
ThisisduetotheclarityofPhilHeller’sexplanations,
andthesmoothlyflowingorganizationofhis
instruction.He’soneofthebestJavatrainersaround.
Butwhat’sreallyrevolutionaryarehismorethan30
animatedillustrations.Eachofthesesmallprograms,
visualandinteractiveinnature,vividlydemonstrates
howitssourcecodeworks.Youcanmodifyitin
differentways,distinctlyalteringthebehaviorofthe
program.Asyouexperimentwiththesetools—andyou
canplaywiththemforhours—you’llgainboththe
skillsandthefundamentalunderstandingneededto
completeeachchapter’sexercises,whichsteadily
increaseinsophistication.NootherbeginningJava
bookcantakeyousofar,soquickly,andnonewillbe
halfasmuchfun.
AbouttheAuthor
PhilipHellerisaconsultant,author,educator,and
novelist.HeistheleadauthorforSybex’sbestselling
JavaCertificationStudyGuideandJavaExamNotesas
wellasaleadingeducatorforJavaUniversityanda
well-knownspeakeronJavatopics.Philhelpedcreate


theJavaprogrammeranddeveloperexamsforSun
andistheirleadingcertificationtrainer.Philiscurrently
writingthesecondvolumeintheGrandfatherDragon
series.


Ground-UpJava
PhilipHeller
AssociatePublisher:JoelFugazzotto
AcquisitionsEditor:DeniseSantoroLincoln,TomCirtin
DevelopmentalEditor:TomCirtin
ProductionEditor:DennisFitzgerald
TechnicalEditor:MarcusCuda
Copyeditor:SeanMedlock
Compositor:MaureenForys,HappenstanceType-O-Rama
GraphicIllustrator:JeffreyWilson,HappenstanceType-O-Rama
CDCoordinator:DanMummert
CDTechnician:KevinLy
Proofreaders:EmilyHusan,LaurieO’Connell,NancyRiddiough
Indexer:TedLaux
CoverDesigner/Illustrator:RichardMiller,CalyxDeisgns
Copyright©2004SYBEXInc.,1151MarinaVillageParkway,Alameda,
CA94501.Worldrightsreserved.Nopartofthispublicationmaybe
storedinaretrievalsystem,transmitted,orreproducedinanyway,
includingbutnotlimitedtophotocopy,photograph,magnetic,orother
record,withouttheprioragreementandwrittenpermissionofthe
publisher.
LibraryofCongressCardNumber:2003110719
ISBN:0-7821-4190-0
SYBEXandtheSYBEXlogoareeitherregisteredtrademarksor
trademarksofSYBEXInc.intheUnitedStatesand/orothercountries.
ScreenreproductionsproducedwithFullShot99.FullShot99©1991–
1999InbitIncorporated.Allrightsreserved.FullShotisatrademarkof
InbitIncorporated.
TheCDinterfacewascreatedusingMacromediaDirector,COPYRIGHT
1994,1997-1999MacromediaInc.FormoreinformationonMacromedia
andMacromediaDirector,visithttp://www.macromedia.com.


TRADEMARKS:SYBEXhasattemptedthroughoutthisbookto
distinguishproprietarytrademarksfromdescriptivetermsbyfollowingthe
capitalizationstyleusedbythemanufacturer.
Theauthorandpublisherhavemadetheirbesteffortstopreparethis
book,andthecontentisbaseduponfinalreleasesoftwarewhenever
possible.Portionsofthemanuscriptmaybebaseduponpre-release
versionssuppliedbysoftwaremanufacturer(s).Theauthorandthe
publishermakenorepresentationorwarrantiesofanykindwithregardto
thecompletenessoraccuracyofthecontentshereinandacceptno
liabilityofanykindincludingbutnotlimitedtoperformance,
merchantability,fitnessforanyparticularpurpose,oranylossesor
damagesofanykindcausedorallegedtobecauseddirectlyorindirectly
fromthisbook.
ManufacturedintheUnitedStatesofAmerica
10987654321
ToLaura,onwhoseviolin
Areplayedthesongsofspheresandheroes,
Abovethisworld’smortaldin,
Abovetheplaneofonesandzeroes.
Acknowledgements
FirstandforemostgratitudetoDeniseSantoroLincoln,TomCirtin,and
SteveCavin.ThankstoMichelle,Ricardo,andeveryoneatPB&G
ProductionsforkeepingmeoutdancingwhenIshouldhavebeenwriting.
ThanksalwaystoSimonRoberts,SuzanneBlackstock,andKathy
Collina.AndthankstoalltheacesatSybex:DennisFitzgerald,Sean
Medlock,KevinLy,DanMummert,andMaureenForysandJeffWilsonat
HappenstanceType-O-Rama.


Introduction


Overview
Thisbookisunique.There’snothinglikeit.Itisthefirstofitskind.It’s
importantthatyouunderstandwhy,sopleasereadon.
ForalongtimeIthoughtitwasimpossibletowriteanintroductoryJava
programmingbookthatcouldbeunderstoodbypeoplewithno
programmingexperience.Itwouldbelikeafishwritingaboutwater.No
onehasbetterknowledgeofthesubjectmatter,butittakesmorethan
thattointroduceatopictoanewcomer.Fishareintimatelyaccustomed
towater,andtheycan’trelatetouslandmammals,whoneedtohave
everythingexplainedandbrokendown.Afishmightsay,“Wiggleyourtail
fintoswimforward,anddon’tforgettouseyourgills.”Thatwouldbe
glaringlyobvioustoanotherfish,butuselesstoyouandme.It’shardfor
afishtoimaginewhatlifewouldbelikewithouttailfinsorgills.Abook
aboutwater,evenifthewisestfishintheoceanwroteit,wouldbefullof
accurate,butuseless,information.
ThesameistrueaboutJava.Programmingisacraft,likeplayinga
musicalinstrumentorglassblowing.Andlikeanyothercraft,ithasits
conventions,jargon,andtechniques.Forpractitionersofthecraft,those
conventions,jargon,andtechniquesbecomedeeplyingrainedhabits,
householdlanguage,andtheeventsofeverydaylife.It’sverydifficultto
writeaboutone’sown“habitat.”
Inthe1970’s,alanguagecalledCbecamepopular.Inthe1980’s,Cwas
modifiedtosupportobject-orientedprogramming.Themodifiedlanguage
wascalledC++.Thisisanexampleofcraftjargon.InC,thesymbol“++”
means,verybroadlyspeaking,“abitmore.”SoC++means“Candabit
more,”andthemeaningiscleartoanyCprogrammer.
The1990’ssawanotherevolution.C++isahighlyeffectivelanguage,but
itcanalsobedifficult.Moreover,ithadnoinnatesupportforrecently
inventedtechnologies,suchashigh-resolutionmulti-colordisplays,
databases,ortheWorldWideWeb.ThenewevolutionwascalledJava.
Thenameisn’taplayonwordsanditisn’tanabbreviationforanything.


JavaabandonedthepartsofC++thathadprovedtobemoretrouble
thantheywereworth,anditaddedsupportformoderntechnologies.
Sometimespeoplecalledit“C++--++”.There’sanothersymbol,“—”,that
roughlymeans“abitless.”So“C++--++”means“C++andabitlessand
thenabitmore.”
Javacaughtonlikeamidsummerbonfire.AhugeportionoftheCand
C++programmingpopulationswitchedatoncetoJavaandneverlooked
back.Whyweresomanyprogrammersabletomaketheswitchso
easily?Iwasoneofthem.Ihadbeenearningalivingprogrammingin
C++.Itookayearofftowriteanovelaboutsomedragons.Iranoutof
moneybeforeIfinishedthenovel.Luckily,itwasamonthafterJavawas
introduced.WithinweeksIconsideredmyselfacompetentJava
programmer,andwithinmonthsIwasteachingitandwritingaboutit.The
creditgoesnottomebuttothedesignersofJava.IfyouknowCand
C++,Javaiseasy.It’slikelearningPortugueseifyoualreadyspeak
SpanishandItalian.LikeeveryoneelsewholearnedJavaatthattime,I
hadyearsofexperiencewiththeconcepts,techniques,andjargonthat
wasneeded.
Butwhataboutpeoplewhodon’thaveanyprogrammingexperience?
WhenIwaslearningJava,thereweretwobooksonthesubject.Today
therearethousands.(I’mresponsibleforafewofthem.)Notoneofthem,
excepttheonethatyou’reholdingrightnow,doesagoodjobof
presentingprogrammingconceptsfromthegroundup.Theothersare
accurateforthemostpart,buttheyaren’thelpful.
SoIhadtoaskmyself:canIintroduceJavafromthegroundup,concept
byconcept?EventuallyIrealizedthatIcouldonlydoitifIcoulduse
somethingmorethanwordsandpictures.Whichbringsmetowhythis
bookisunique.Itisuniquebecause…


TheIllustrationsareAlive!
IrealizedthatwhatIreallywantedwasamagicblackboard.
Thinkofacomputerasahugesetofboxes,eachboxcontaininga
number.Thenumbersrepresenttextorcolorsordata,orwhateverelse
canbemodeledbyaprogram.Thenumberschangeovertimein
complicatedways.Describingthelifecycleofaprogramisalmost
impossibleifyoucanonlyusewordsandpictures.Iwantedtocreate
picturesthatwouldchangeovertime.AndIwantedsomethingbeyond
animatedcartoonsthatwouldbethesameeachtimeyouwatchedthem.
Iwantedlivingillustrationsthatwouldrespondtoyourcuriosity.Iwanted
togiveyouthepowertoask“whatif…”questionsoftheillustrations.
Iwantedsomethingthatcanonlybedoneonacomputer.
TheCD-ROMthatcomeswiththisbookhasmorethan30animated
illustrations.Theseareprogramsthatyourunonyourcomputer.The
bookgivesyoucompleteinstructionsonhowtousethem.Theillustration
onthenextpageisanexample.

ThisisascreenshotofNestedLoopLab,whichappearsinChapter5,
“ConditionalsandLoops.”Thetextintheupper-centralpartofthescreen
(“intcolor=5”andsoon)isJavacode.Theswirlyimageatthe
bottomistheresultofrunningthecode.Thevariouscontrolsletyouvary
thecode,experimentingwithdifferentvaluesuntilyougetafeelforwhat
theprogramisdoing.


Theanimatedillustrationsareliketrainingwheelsonabicycle.Whenyou
firstlearntoride,therearesomanythingsthatcangowrong.Without
trainingwheelsyouspendalotofjusttimecrashingandgettingbackup.
Trainingwheelsletyoudeveloptherightsenseofbalance.Theanimated
illustrationswon’tletyoucreatecodethatcrashes.Theyprovideasafe
environmentinwhichyoucandeveloptherightsenseofbalance.
Later,ofcourse,it’stimetotakeoffthetrainingwheels.Attheendof
eachchapteryou’llfindasetofexercisesthatwillhaveyouwritingyour
owncode.Suggestedsolutionstotheexercisesappearatthebackofthe
book.
Tothebestofmyknowledge,Ground-UpJavaisthefirstbookeverto
useanimatedillustrations.Sowehavenodataonhoweffectivetheyare
asateachingtool.Myguessisthattheyareworththeirweightingold.
Everyonewhohasseenthemhasbeenveryenthusiastic.Butyouare
themostqualifiedjudge.Trythem!Pleaseletmeknowwhatyouthink.
Youcane-mailyourcommentstogroundupjava@sgsware.com.I’m
especiallyinterestedinknowingwhichanimatedillustrationsworkedthe
bestforyou,andwhichonesdidn’t.I’dalsoliketohearanysuggestions
youmighthaveformoreanimationstoappearinfuturerevisionsofthis
book.Youareinvitedtobepartofthedevelopmentofanimated
illustrationsasanewtechnologyforlearning.
Andnow…


It’sTimeToDownloadandInstallJava
Beforeyoucanstartwritingorrunning.Javaprograms,youneedto
downloadsomesoftware.(TheanimatedillustrationsareJavaprograms,
sotheywon’trunifyoudon’tdothedownload.)
Downloadingisfree.AfterJavaisloadedonyourharddrive,youhaveto
followafewstepstoinstallit.Thesearen’tdifficult,butthere’sroomfor
error,sopleasebecareful.Completeinstructionsareexplainedin
AppendixA,“DownloadingandInstallingJava.”
Andnowyou’reready.Havefun!


Chapter1:AnIntroductiontoComputersThat
WillActuallyHelpYouinLife


Overview
Javaisaprogramminglanguagethattellscomputerswhattodo.This
chapterwilllookatwhatcomputesreallyare,whattheycando,andhow
weuseprogramminglanguagestocontrolthem.
Wewillbeginbyexplodingthecommonmyththatcomputersdealonly
with0sand1s.Onceweestablishwhatcomputersreallyprocess,wewill
lookatthekindofprocessingtheyperform.
Thisisemphaticallynotanintellectualexercise.Spendingabitofeffort
herewillmakeyourlifemucheasierinthechaptersthatfollow.Many
conceptsthatappearlaterinthisbook,suchasdatatyping,referencing,
andvirtualmachines,willmakeverylittlesenseunlessyouunderstand
theunderlyingstructureofcomputers.Withoutthisunderstanding,
learningtoprogramcanbeconfusingandoverwhelming.Withtheright
fundamentals,though,itcanbeenjoyableandstimulating.


Memory:NotExactly0sand1s
Nodoubtyou'veheardthatcomputersonlyprocess0sand1s.Thiscan't
possiblybetrue.Computersareusedtocountvotesinelections,sothey
mustbecapableofcountingpast1.Computersarealsousedtomodel
thebehaviorofsubatomicparticleswhosemassesaretinyfractions,so
theymustbecapableofprocessingfractionsaswellaswholenumbers.
They'reusedforwritingdocuments,sotheymustbecapableof
processingtextaswellasnumbers.
Onthemostfundamentallevel,computersdonotprocess0sand1s,or
wholenumbers,orfractions,ortext.Computersareelectroniccircuits,so
alltheyreallyprocessiselectricity.Computercomponentsaredesigned
sothattheirinternalvoltagesareeitherapproximatelyzeroor
approximately5or6volts.Whenpartofacomputercircuitcarriesa
voltageof5or6volts,wesaythatithasavalueof1.Whenpartofa
circuitcarrieszerovoltage,wesaythatithasavalueof0.(Fortunately,
thisisalltheelectronicsknowledgeyouneedtobecomeamaster
programmer.)
It'sallamatterofinterpretation.Voltagesareinterpretedas0sand1s.
Asyou'llseelaterinthischapterandinChapter2,"Data,"the0sand1s
areorganizedintoclustersthatareinterpretedasnumbers.More
sophisticatedpartsofthecomputerinterpretthosenumbersascodes
thatrepresentfractions,ortext,orcolors,orimages,oranyoftheother
myriadclassesofobjectsthatcanberepresentedinacomputer.
Amoderncomputercontainsbillionsofmicroscopiccomponents,eachof
whichhasavalueof0or1.Anycircuitwhereweonlycareaboutthe
approximatevaluesofthevoltagesisknownasadigitalcircuit.
Computersthataremadeofdigitalcircuitryareknownasdigital
computers.
Note Theoppositeofdigitalisanalog.Inananalogcircuit,wecare
abouttheexactvoltagesofthecomponents.Analogcircuitsare
idealforcertainapplications,suchasradiosandmicrowave
ovens,buttheydon'tworksowellforcomputers.Analog
computerswereusedinthe1940s,buttheywerean


evolutionarydeadend.Allmoderncomputersaredigital.
Onesimplebutusefultypeofdigitalcircuitisknownasmemory.A
memorycircuitjuststoresadigitalvalue(0or1,becausewe
programmersdon'thavetothinkaboutvoltages).Asingleunitofmemory
iscalledabit,whichisanabbreviationfor"binarydigit."Youcanthinkof
abitasamicroscopicbox,thecontentsofwhichareavailabletotherest
ofthecomputer.Fromtimetotimethecomputermightchangethe
contents.BitsareusuallydrawnasshowninFigure1.1.


Figure1.1:Abit
Bitsareusuallyorganizedingroupsofeight,knownasbytes.Figure1.2
showsabytethatcontainsanarbitrarycombinationof0sand1s.


Figure1.2:Abyte
Notethattheindividualbitsarenumberedfromrighttoleft,andthatthe
numberingstartsfrom0.Computerdesignersalwaysstartnumbering
thingsfrom0ratherthan1.Thisistruewhethertheyarenumberingbits
inabyte,bytesinmemory(asweareabouttosee),orcomponentsinan
array(aswewillseeinChapter6).
Abytecancontain256combinationsofbitvalues:2possibilitiesforbit
#0times2possibilitiesforbit#1times2possibilitiesforbit#3,andsoon
upthroughbit#7.
Ifyoulookedatacomputerthroughamicroscopeandsawthebyte
showninFigure1.2,youmightwonderwhatvalueitcontained.You
wouldseethe0sand1s,butwhatwouldtheymean?It'sagreatquestion
thathasnogoodanswer.Abytemightrepresentanintegralnumber,a
fraction,partofanintegerorfraction,acharacterinadocument,acolor


inapicture,oraninstructioninaprogram.Italldependsonthebyte's
context.Asaprogrammer,youaretheonewhodictateshoweachbyte
willbeinterpreted.


MemoryOrganization
Typically,amodernpersonalcomputercontainsseveralhundredmillion
bytesofmemory.Theprefixmega(abbreviatedM)meansmillion,sowe
couldalsosaythatacomputerhasseveralhundredmegabytesorMB.
Programsandprogrammersneedawaytodistinguishonebytefrom
another.Thisisdonebyassigningtoeachbyteauniquenumber,known
asthebyte'saddress.Addressesbeginat0.Figure1.3shows4bytes.


Figure1.3:Severalbytes
IfFigure1.3showed512MBandwasdrawntothesamescale,itwould
beabout2,000mileshigh.
Asinglebyteisnotveryversatile,becauseitsvalueislimitedto256
possibilities.Itdoesn'tmatterwhetherthebyterepresentsanumberora
letteroranythingelse—incomputerapplications,256ofanythingisn't
muchofarange.Forthisreason,computersoftenusegroupsofbytes.
Twobytes,takentogetherasaunit,cantakeon256times256possible
values,or65,536.Fourbytescantakeon256times256times256times
256values,or4,294,967,296.Thisiswhereitstartstobeuseful.Eight
bytescantakeonapproximately20quintilliondifferentvalues.
Memoryisusuallyusedinchunksof1,2,4,or8bytes.(Laterwewillsee
thatarraysandobjectsusechunksofarbitrarysize.)Thechunkscan
representintegralnumbers,fractions,text,oranyotherkindof
information.Fromthisperspective,wecanseethatthestatement
"Computersonlydealwith0sand1s"istrueonlyinaverylimitedsense.


Thinkofitthisway:Acomputerisadigitalcircuit,andwethinkofits
componentsashavingvaluesthatrepresent0sor1s.Butifwelookone
levelbelowthedigitalcomponents,weseeonlyelectricity,notnumbers.
Andifwelookonelevelabovethedigitalcomponents,weseethatthe
bitsareorganizedintochunksof1ormorebytesthatrepresentmany
typesofinformation.
Inadditiontovarioustypesofdata,memorycanalsostorethe
instructionsthatoperateondata.Inthenextsection,wewilllookata
verysimplecomputerandseehowinstructionsanddatainteract.


AVerySimpleComputer
ThischapterwillintroduceaverysimplecomputercalledSimCom.
SimComisimaginary.Or,touseamorerespectableterm,itisvirtual.
NobodyhaseverbuiltaSimCom,butitissimulatedinoneofthe
animatedillustrationsontheCD-ROM.
Theprocessorsthatpoweryourowncomputer,thePentiums,SPARCs,
andsoon,arenotverydifferentqualitativelyfromSimCom.
Quantitatively,however,thereisahugedifference:therealprocessors
havevastlymoreinstructions,speed,andmemory.SimComisassimple
asacomputercanbewhilestillbeingausefulteachingtool.
ThepointofthissectionisnottomakeyouamasterSimCom
programmer.ThepointistouseSimComtointroducecertainprinciples
ofprogramming.Laterinthisbook,thesameprincipleswillbepresented
inthecontextofJava.Theseprinciplesinclude
High-levellanguages
Loops
Referencing
Two'scomplement
Virtualmachines
Inthissection,youwillseesometypicalprocessorelementsthatare
quitelow-level.ModernprogramminglanguageslikeJavadeliberately
isolateyoufromhavingtocontroltheseelements.However,itis
extremelyvaluabletoknowthattheyexistandwhattheydoonyour
behalf.
ThearchitectureofSimComisverysimple.Thereisabankof32bytesof
memory;eachbytecanbeusedasaninstructionorasdata.Thereis
oneextrabyte,calledtheregister,whichisusedlikescratchpaper.
Anothercomponent,calledtheprogramcounter,keepstrackofwhich
instructionisabouttobeexecuted.Figure1.4showsthearchitectureof


SimCom.


Figure1.4:SimComarchitecture
Thearrowinthefigureindicatestheprogramcounter.Thenext
instructiontobeexecutedwillbebyte#7.Notethatbyteaddressesstart
at0.
WhenSimComstartsup,itsetstheprogramcounterto0.Itthen
executesbyte0.(We'llseewhatthismeansinamoment.)Execution
maychangetheregisterorabyteofmemory,anditalmostalways
changestheprogramcounter.Thenthewholeprocessrepeats:The
instructionindicatedbytheprogramcounterisexecuted,andthe
programcounterismodified.ThiscontinuesuntilSimComisinstructedto
halt.
Bits7,6,and5ofaninstructionbytetellSimComwhattodo.Theyare
knownastheoperationcodeoropcodebits.Bits4through0contain
additionalinstructions;theyarecalledtheargumentbits.Thisdivisionof
bitsisshowninFigure1.5.



Figure1.5:Opcodeandargumentbits
TheSimComcomputerhas7opcodes.TheyareshowninTable1.1.
Table1.1:Opcodes
Opcode

Function

Abbreviation

000

Load

LOAD

001

Store

STORE

010

Add

ADD

011

Subtract

SUB

100

Jumptodifferent
currentinstruction

JUMP

101

Jumpifregisteriszero JUMPZ

110or111

Halt

HALT

The5argumentbitscontainavaluethatisthebase-2addressofa
memorybyte.TheLOADopcodecopiesthecontentsofthisaddressinto
theregister.Forexample,supposethecurrentinstructionis00000011.
Theopcodeis000(LOAD),andtheargumentis00011(whichisthe
base-2notationfor3).Whentheinstructionisexecuted,thevalueinbyte
#3iscopiedintotheregister.Notethatthevalue3isnotcopiedintothe
register.Theargumentisneveruseddirectly;itisalwaysanaddress
whosecontentsareused.
TheSTOREopcodecopiesthecontentsoftheregisterinthememory
bytewhoseaddressappearsintheargument.Forexample,00100001
causestheregistertobecopiedintobyte#1.
TheADDopcodeaddstwovalues.Onevalueisthevaluestoredinthe
bytewhoseaddressappearsintheargument.Theothervalueisthe


contentsoftheregister.Theresultoftheadditionisstoredintheregister.
Forexample,supposetheregistercontains00001100,andbyte#1
contains00000011.Theinstruction01000001causesthecontentsof
byte#1tobeaddedtothecontentsoftheregister,withtheresultbeing
storedbackintheregister.Notethattheargument(00001)isused
indirectly,asanaddress.Thevalue00001isnotaddedtotheregister;
rather,00001istheaddressofthebytethatgetsaddedtotheregister.
TheSUBopcodeislikeADD,exceptthatthevalueaddressedbythe
argumentissubtractedfromtheregister.Theresultisstoredinthe
register.
Aftereachofthesefouropcodesisexecuted,theprogramcounteris
incrementedby1.Thus,controlflowssequentiallythroughmemory.The
remainingthreeopcodesalterthisnormalflowofcontrol.TheJUMP
opcodedoesnotchangetheregisterormemory;itjuststoresits
argumentintheprogramcounter.Forexample,afterexecuting
10000101,thenextinstructiontobeexecutedwillbetheoneatbyte
00101,whichisthebase-2notationfor5.
TheJUMPZopcodeinspectstheregister.Iftheregistercontains
00000000,theprogramcounterissettotheinstruction'sargument.
Otherwise,theprogramcounterisjustincremented(thatis,increasedby
1)andcontrolflowsnormally.Thisisaverypowerfulopcode,becauseit
enablesthecomputertobesensitivetoitsdataandtoreactdifferentlyto
differentconditions.
Finally,theHALTopcodecausesthecomputertostopprocessing.
Let'slookatashortprogram:
00000100
01000100
00100100
11000000
Thefirstthingtonoticeaboutthisprogramisthatit'shardtoread.Let's
translateittoafriendlierformat:
LOAD4


ADD4
STORE4
HALT
Theprogramdoublesthevalueinbyte#4.Itdoesthisbycopyingthe
valueintotheregister,thenaddingthesamevalueintotheregister,and
thenstoringtheresultbackinbyte#4.
Thisexampleshowsthatanythingisbetterthanprogrammingby
manipulating0sand1s.Thesespelled-outopcodesandbase-10
numbersareacompromisebetweenthebinarylanguageofcomputers
andthehighlystructuredandnuancedlanguageofhumans.TheLOAD4
notationisknownasassemblylanguage.Inassemblylanguage,alineof
codetypicallycorrespondstoasinglecomputerinstruction,andthe
programmermustalwaysbeawareofthecomputer'sarchitectureand
state.Anassemblerisaprogramthattranslatesassemblylanguageinto
binarynotation.

PlayingwithSimCom
Unfortunatelywecouldn'tpackageaSimComwitheverycopyofthis
book,butwehavedonethenextbestthing.Thefirstanimatedillustration
onthebook'sCDisasimulationofaSimCominaction.
Note Ifyoudon'talreadyhaveJavainstalledonyourcomputer,now
isthetime.Ifyou'renotsurehow,pleaserefertoAppendixA,
"DownloadingandInstallingJava,"whichwalksyouthrough
theentireprocess.Throughoutthisbookyouwillbeinvitedto
runananimatedillustrationprogram,andyouwillbegivena
commandtotypeintoyourmachine.Itwillallmakesenseafter
yougothroughAppendixA.
ToruntheSimComsimulation,typethefollowingatyourcommand
prompt:
javasimcom.SimComFrame
Thesimulationallowsyoutoloadandrunpreexistingprogramsorcreate
yourownprograms.Figure1.6showsthesimulationinaction.



Figure1.6:SimCominaction
Eachbyteofmemoryisdisplayedinthreeformats:base-2,base-10,and
opcode-plus-argument.Theregisterisonlydisplayedinbase-2and
base-10;sincetheregisterisneverexecuted,thereisnovaluein
displayingwhichinstructionwouldbeexecuted.Youcanchangeanybyte
inmemorybyfirstclickinginsidethatbyte.Thiswillhighlightandselect
thebyteforediting.Then,ifyouclickonthebase-10region,youwillget
apanelthatletsyouselectanewbase-10value.Ifyouclickonthe
opcoderegion,youwillgetapanelthatletsyouselectanewopcode.To
changetheargument,firstclickontheargumentregionoftheselected
byte.Asyoumovethemouse,theclosestbyteaddresswilllightup.
Whentheaddressyouwantishighlighted,clickonittosetitasthe
argument.
Tryexecutingaverysimpleprogram.ClickFile‚ScenariosintheFile
menu,andselectLoad/Add/Store/.Thisprogramaddsbytes10and11
(notthenumbers10and11,butthecontentsofthememorybyteswhose
addressesare10and11),andstorestheresultinbyte12.Initially,bytes
10and11bothcontainzero,sotoseeinterestingresultsyouwillhaveto
changetheirvalues.Toseetheprograminaction,clicktheStepbutton.
Thisexecutesthecurrentinstructioninslowmotion.Toruncontinuously,
clicktheRunbutton,whichplaystheanimationuntilaHALTinstructionis


Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay

×

×