Вы находитесь на странице: 1из 19

4/18/2015

Chapter1:JavaFundamentalsJavaABeginner'sGuide,6thEdition

Java A Beginner's Guide, 6th Edition

NEXT

PREV

Introduction

Chapter 2: Introdu

Recent

Topics
Tutorials

Highlights

Settings
Feedback(http://community.safaribooksonline.com)
Sign Out

Settings
Chapter1
JavaFundamentals

days left in your trial. Subscribe.

Feedback(http://community.safaribooksonline.com/)
KeySkills&Concepts
KnowthehistoryandphilosophyofJava
UnderstandJavascontributiontotheInternet

Sign Out

Understandtheimportanceofbytecode
KnowtheJavabuzzwords
Understandthefoundationalprinciplesofobjectoriented
programming
Create,compile,andrunasimpleJavaprogram
Usevariables
Usetheifandforcontrolstatements

Enjoy Safari? Subscribe Today

Createblocksofcode

Understandhowstatementsarepositioned,indented,and

terminated

KnowtheJavakeywords
UnderstandtherulesforJavaidentifiers

heriseoftheInternetandtheWorldWideWebfundamentally
reshapedcomputing.PriortotheWeb,thecyberlandscapewas

dominatedbystandalonePCs.Today,nearlyallcomputersare
connectedtotheInternet.TheInternet,itself,wastransformed
originallyofferingaconvenientwaytosharefilesandinformation.
Todayitisavast,distributedcomputinguniverse.Withthesechanges
cameanewwaytoprogram:Java.
JavaisthepreeminentlanguageoftheInternet,butitismorethanthat.
Javarevolutionizedprogramming,changingthewaythatwethinkabout
boththeformandthefunctionofaprogram.Tobeaprofessional
programmertodayimpliestheabilitytoprograminJavaitisthat
important.Inthecourseofthisbook,youwilllearntheskillsneededto
masterit.
ThepurposeofthischapteristointroduceyoutoJava,includingits
history,itsdesignphilosophy,andseveralofitsmostimportantfeatures.
Byfar,thehardestthingaboutlearningaprogramminglanguageisthe
factthatnoelementexistsinisolation.Instead,thecomponentsofthe
languageworkinconjunctionwitheachother.Thisinterrelatednessis
especiallypronouncedinJava.Infact,itisdifficulttodiscussoneaspect
ofJavawithoutinvolvingothers.Tohelpovercomethisproblem,this
chapterprovidesabriefoverviewofseveralJavafeatures,includingthe
generalformofaJavaprogram,somebasiccontrolstructures,and
operators.Itdoesnotgointotoomanydetailsbut,rather,concentrates
onthegeneralconceptscommontoanyJavaprogram.
TheOriginsofJava

https://www.safaribooksonline.com/library/view/javaabeginners/9780071809252/ch01.html

1/19

4/18/2015

Chapter1:JavaFundamentalsJavaABeginner'sGuide,6thEdition

Computerlanguageinnovationisdrivenforwardbytwofactors:
improvementsintheartofprogrammingandchangesinthecomputing
environment.Javaisnoexception.Buildingupontherichlegacy
inheritedfromCandC++,Javaaddsrefinementsandfeaturesthat
reflectthecurrentstateoftheartinprogramming.Respondingtothe
riseoftheonlineenvironment,Javaoffersfeaturesthatstreamline
programmingforahighlydistributedarchitecture.
JavawasconceivedbyJamesGosling,PatrickNaughton,ChrisWarth,
EdFrank,andMikeSheridanatSunMicrosystemsin1991.This
languagewasinitiallycalledOakbutwasrenamedJavain1995.
Somewhatsurprisingly,theoriginalimpetusforJavawasnotthe
Internet!Instead,theprimarymotivationwastheneedforaplatform
independentlanguagethatcouldbeusedtocreatesoftwaretobe
embeddedinvariousconsumerelectronicdevices,suchastoasters,
microwaveovens,andremotecontrols.Asyoucanprobablyguess,many
differenttypesofCPUsareusedascontrollers.Thetroublewasthat(at
thattime)mostcomputerlanguagesweredesignedtobecompiledfora
specifictarget.Forexample,considerC++.
AlthoughitwaspossibletocompileaC++programforjustaboutanytype
ofCPU,todosorequiredafullC++compilertargetedforthatCPU.The
problem,however,isthatcompilersareexpensiveandtimeconsuming
tocreate.Inanattempttofindabettersolution,Goslingandothers
workedonaportable,crossplatformlanguagethatcouldproducecode
thatwouldrunonavarietyofCPUsunderdifferingenvironments.This
effortultimatelyledtothecreationofJava.
AboutthetimethatthedetailsofJavawerebeingworkedout,asecond,
andultimatelymoreimportant,factoremergedthatwouldplayacrucial
roleinthefutureofJava.Thissecondforcewas,ofcourse,theWorld
WideWeb.HadtheWebnottakenshapeataboutthesametimethatJava
wasbeingimplemented,Javamighthaveremainedausefulbutobscure
languageforprogrammingconsumerelectronics.However,withthe
emergenceoftheWeb,Javawaspropelledtotheforefrontofcomputer
languagedesign,becausetheWeb,too,demandedportableprograms.
Mostprogrammerslearnearlyintheircareersthatportableprograms
areaselusiveastheyaredesirable.Whilethequestforawaytocreate
efficient,portable(platformindependent)programsisnearlyasoldas
thedisciplineofprogrammingitself,ithadtakenabackseattoother,
morepressingproblems.However,withtheadventoftheInternetand
theWeb,theoldproblemofportabilityreturnedwithavengeance.After
all,theInternetconsistsofadiverse,distributeduniversepopulatedwith
manytypesofcomputers,operatingsystems,andCPUs.
Whatwasonceanirritatingbutalowpriorityproblemhadbecomea
highprofilenecessity.By1993,itbecameobvioustomembersoftheJava
designteamthattheproblemsofportabilityfrequentlyencountered
whencreatingcodeforembeddedcontrollersarealsofoundwhen
attemptingtocreatecodefortheInternet.Thisrealizationcausedthe
focusofJavatoswitchfromconsumerelectronicstoInternet
programming.So,whileitwasthedesireforanarchitectureneutral
programminglanguagethatprovidedtheinitialspark,itwasthe
InternetthatultimatelyledtoJavaslargescalesuccess.
HowJavaRelatestoCandC++
JavaisdirectlyrelatedtobothCandC++.Javainheritsitssyntaxfrom
C.ItsobjectmodelisadaptedfromC++.JavasrelationshipwithCand
C++isimportantforseveralreasons.First,manyprogrammersare
familiarwiththeC/C++syntax.ThismakesiteasyforaC/C++
programmertolearnJavaand,conversely,foraJavaprogrammerto
learnC/C++.
Second,Javasdesignersdidnotreinventthewheel.Instead,they
furtherrefinedanalreadyhighlysuccessfulprogrammingparadigm.The
modernageofprogrammingbeganwithC.ItmovedtoC++,andnowto
Java.Byinheritingandbuildinguponthatrichheritage,Javaprovidesa
powerful,logicallyconsistentprogrammingenvironmentthattakesthe
bestofthepastandaddsnewfeaturesrequiredbytheonline
environment.Perhapsmostimportant,becauseoftheirsimilarities,C,
C++,andJavadefineacommon,conceptualframeworkforthe
professionalprogrammer.Programmersdonotfacemajorriftswhen
switchingfromonelanguagetoanother.
OneofthecentraldesignphilosophiesofbothCandC++isthatthe
programmerisincharge!Javaalsoinheritsthisphilosophy.Exceptfor
thoseconstraintsimposedbytheInternetenvironment,Javagivesyou,
theprogrammer,fullcontrol.Ifyouprogramwell,yourprogramsreflect
it.Ifyouprogrampoorly,yourprogramsreflectthat,too.Putdifferently,
Javaisnotalanguagewithtrainingwheels.Itisalanguagefor
professionalprogrammers.
JavahasoneotherattributeincommonwithCandC++:itwasdesigned,
tested,andrefinedbyreal,workingprogrammers.Itisalanguage
groundedintheneedsandexperiencesofthepeoplewhodevisedit.
Thereisnobetterwaytoproduceatopflightprofessionalprogramming

https://www.safaribooksonline.com/library/view/javaabeginners/9780071809252/ch01.html

2/19

4/18/2015

Chapter1:JavaFundamentalsJavaABeginner'sGuide,6thEdition

language.
BecauseofthesimilaritiesbetweenJavaandC++,especiallytheir
supportforobjectorientedprogramming,itistemptingtothinkofJava
assimplytheInternetversionofC++.However,todosowouldbea
mistake.Javahassignificantpracticalandphilosophicaldifferences.
AlthoughJavawasinfluencedbyC++,itisnotanenhancedversionof
C++.Forexample,itisneitherupwardlynordownwardlycompatible
withC++.Ofcourse,thesimilaritieswithC++aresignificant,andifyou
areaC++programmer,youwillfeelrightathomewithJava.Another
point:JavawasnotdesignedtoreplaceC++.Javawasdesignedtosolve
acertainsetofproblems.C++wasdesignedtosolveadifferentsetof
problems.Theywillcoexistformanyyearstocome.
HowJavaRelatestoC#
AfewyearsafterthecreationofJava,MicrosoftdevelopedtheC#
language.ThisisimportantbecauseC#iscloselyrelatedtoJava.Infact,
manyofC#sfeaturesdirectlyparallelJava.BothJavaandC#sharethe
samegeneralC++stylesyntax,supportdistributedprogramming,and
utilizethesameobjectmodel.Thereare,ofcourse,differencesbetween
JavaandC#,buttheoveralllookandfeeloftheselanguagesisvery
similar.ThismeansthatifyoualreadyknowC#,thenlearningJavawill
beespeciallyeasy.Conversely,ifC#isinyourfuture,thenyour
knowledgeofJavawillcomeinhandy.
GiventhesimilaritybetweenJavaandC#,onemightnaturallyask,
WillC#replaceJava?TheanswerisNo.JavaandC#areoptimizedfor
twodifferenttypesofcomputingenvironments.JustasC++andJava
willcoexistforalongtimetocome,sowillC#andJava.
JavasContributiontotheInternet
TheInternethelpedcatapultJavatotheforefrontofprogramming,and
Java,inturn,hadaprofoundeffectontheInternet.Inadditionto
simplifyingwebprogrammingingeneral,Javainnovatedanewtypeof
networkedprogramcalledtheappletthatchangedthewaytheonline
worldthoughtaboutcontent.Javaalsoaddressedsomeofthethorniest
issuesassociatedwiththeInternet:portabilityandsecurity.Letslook
morecloselyateachofthese.
JavaApplets
AnappletisaspecialkindofJavaprogramthatisdesignedtobe
transmittedovertheInternetandautomaticallyexecutedbyaJava
compatiblewebbrowser.Furthermore,anappletisdownloadedon
demand,withoutfurtherinteractionwiththeuser.Iftheuserclicksalink
thatcontainsanapplet,theappletwillbeautomaticallydownloadedand
runinthebrowser.Appletsareintendedtobesmallprograms.Theyare
typicallyusedtodisplaydataprovidedbytheserver,handleuserinput,
orprovidesimplefunctions,suchasaloancalculator,thatexecute
locally,ratherthanontheserver.Inessence,theappletallowssome
functionalitytobemovedfromtheservertotheclient.
ThecreationoftheappletchangedInternetprogrammingbecauseit
expandedtheuniverseofobjectsthatcanmoveaboutfreelyin
cyberspace.Ingeneral,therearetwoverybroadcategoriesofobjects
thataretransmittedbetweentheserverandtheclient:passive
informationanddynamic,activeprograms.Forexample,whenyouread
youremail,youareviewingpassivedata.Evenwhenyoudownloada
program,theprogramscodeisstillonlypassivedatauntilyouexecuteit.
Bycontrast,theappletisadynamic,selfexecutingprogram.Sucha
programisanactiveagentontheclientcomputer,yetitisinitiatedby
theserver.
Asdesirableasdynamic,networkedprogramsare,theyalsopresent
seriousproblemsintheareasofsecurityandportability.Obviously,a
programthatdownloadsandexecutesautomaticallyontheclient
computermustbepreventedfromdoingharm.Itmustalsobeabletorun
inavarietyofdifferentenvironmentsandunderdifferentoperating
systems.Asyouwillsee,Javasolvedtheseproblemsinaneffectiveand
elegantway.Letslookabitmorecloselyateach.
Security
Asyouarelikelyaware,everytimethatyoudownloadanormal
program,youaretakingariskbecausethecodeyouaredownloading
mightcontainavirus,Trojanhorse,orotherharmfulcode.Atthecoreof
theproblemisthefactthatmaliciouscodecancauseitsdamagebecauseit
hasgainedunauthorizedaccesstosystemresources.Forexample,avirus
programmightgatherprivateinformation,suchascreditcardnumbers,
bankaccountbalances,andpasswords,bysearchingthecontentsofyour
computerslocalfilesystem.InorderforJavatoenableappletstobe
safelydownloadedandexecutedontheclientcomputer,itwasnecessary
topreventanappletfromlaunchingsuchanattack.
JavaachievedthisprotectionbyconfininganapplettotheJava
executionenvironmentandnotallowingitaccesstootherpartsofthe
computer.(Youwillseehowthisisaccomplishedshortly.)Theabilityto
downloadappletswithconfidencethatnoharmwillbedoneandthatno

https://www.safaribooksonline.com/library/view/javaabeginners/9780071809252/ch01.html

3/19

4/18/2015

Chapter1:JavaFundamentalsJavaABeginner'sGuide,6thEdition

securitywillbebreachedisconsideredbymanytobethesinglemost
innovativeaspectofJava.
Portability
PortabilityisamajoraspectoftheInternetbecausetherearemany
differenttypesofcomputersandoperatingsystemsconnectedtoit.Ifa
Javaprogramweretoberunonvirtuallyanycomputerconnectedtothe
Internet,thereneededtobesomewaytoenablethatprogramtoexecute
ondifferentsystems.Forexample,inthecaseofanapplet,thesame
appletmustbeabletobedownloadedandexecutedbythewidevarietyof
differentCPUs,operatingsystems,andbrowsersconnectedtothe
Internet.Itisnotpracticaltohavedifferentversionsoftheappletfor
differentcomputers.Thesamecodemustworkinallcomputers.
Therefore,somemeansofgeneratingportableexecutablecodewas
needed.Asyouwillsoonsee,thesamemechanismthathelpsensure
securityalsohelpscreateportability.
JavasMagic:TheBytecode
ThekeythatallowsJavatosolveboththesecurityandtheportability
problemsjustdescribedisthattheoutputofaJavacompilerisnot
executablecode.Rather,itisbytecode.Bytecodeisahighlyoptimizedset
ofinstructionsdesignedtobeexecutedbytheJavaruntimesystem,
whichiscalledtheJavaVirtualMachine(JVM).Inessence,theoriginal
JVMwasdesignedasaninterpreterforbytecode.Thismaycomeasabit
ofasurprisebecausemanymodernlanguagesaredesignedtobe
compiledintoexecutablecodeduetoperformanceconcerns.However,
thefactthataJavaprogramisexecutedbytheJVMhelpssolvethemajor
problemsassociatedwithwebbasedprograms.Hereiswhy.
TranslatingaJavaprogramintobytecodemakesitmucheasiertoruna
programinawidevarietyofenvironmentsbecauseonlytheJVMneeds
tobeimplementedforeachplatform.Oncetheruntimepackageexists
foragivensystem,anyJavaprogramcanrunonit.Remember,although
thedetailsoftheJVMwilldifferfromplatformtoplatform,all
understandthesameJavabytecode.IfaJavaprogramwerecompiledto
nativecode,thendifferentversionsofthesameprogramwouldhaveto
existforeachtypeofCPUconnectedtotheInternet.Thisis,ofcourse,
notafeasiblesolution.Thus,theexecutionofbytecodebytheJVMisthe
easiestwaytocreatetrulyportableprograms.
ThefactthataJavaprogramisexecutedbytheJVMalsohelpstomakeit
secure.BecausetheJVMisincontrol,itcancontaintheprogramand
preventitfromgeneratingsideeffectsoutsideofthesystem.Safetyis
alsoenhancedbycertainrestrictionsthatexistintheJavalanguage.
Whenaprogramisinterpreted,itgenerallyrunsslowerthanthesame
programwouldrunifcompiledtoexecutablecode.However,withJava,
thedifferentialbetweenthetwoisnotsogreat.Becausebytecodehas
beenhighlyoptimized,theuseofbytecodeenablestheJVMtoexecute
programsmuchfasterthanyoumightexpect.
AlthoughJavawasdesignedasaninterpretedlanguage,thereisnothing
aboutJavathatpreventsontheflycompilationofbytecodeintonative
codeinordertoboostperformance.Forthisreason,theHotSpot
technologywasintroducednotlongafterJavasinitialrelease.HotSpot
providesajustintime(JIT)compilerforbytecode.WhenaJITcompiler
ispartoftheJVM,selectedportionsofbytecodearecompiledinto
executablecodeinrealtimeonapiecebypiece,demandbasis.Itis
importanttounderstandthatitisnotpracticaltocompileanentireJava
programintoexecutablecodeallatoncebecauseJavaperformsvarious
runtimechecksthatcanbedoneonlyatruntime.Instead,aJIT
compilercompilescodeasitisneeded,duringexecution.Furthermore,
notallsequencesofbytecodearecompiledonlythosethatwillbenefit
fromcompilation.Theremainingcodeissimplyinterpreted.However,
thejustintimeapproachstillyieldsasignificantperformanceboost.
Evenwhendynamiccompilationisappliedtobytecode,theportability
andsafetyfeaturesstillapplybecausetheJVMisstillinchargeofthe
executionenvironment.

AsktheExpert

Q:IhaveheardaboutaspecialtypeofJavaprogramcalled
aservlet.Whatisit?

A:Aservletisasmallprogramthatexecutesonaserver.Justas
appletsdynamicallyextendthefunctionalityofawebbrowser,
servletsdynamicallyextendthefunctionalityofawebserver.Itis
helpfultounderstandthatasusefulasappletscanbe,theyarejust
onehalfoftheclient/serverequation.Notlongaftertheinitial
releaseofJava,itbecameobviousthatJavawouldalsobeusefulon
theserverside.Theresultwastheservlet.Thus,withtheadventof
theservlet,Javaspannedbothsidesoftheclient/serverconnection.
Althoughthecreationofservletsisbeyondthescopeofthis
beginnersguide,theyaresomethingthatyouwillwanttostudy
furtherasyouadvanceinJavaprogramming.(Coverageofservlets
canbefoundinmybookJava:TheCompleteReference,publishedby

https://www.safaribooksonline.com/library/view/javaabeginners/9780071809252/ch01.html

4/19

4/18/2015

Chapter1:JavaFundamentalsJavaABeginner'sGuide,6thEdition

OraclePress/McGrawHillEducation.)

TheJavaBuzzwords
NooverviewofJavaiscompletewithoutalookattheJavabuzzwords.
AlthoughthefundamentalforcesthatnecessitatedtheinventionofJava
areportabilityandsecurity,otherfactorsplayedanimportantrolein
moldingthefinalformofthelanguage.Thekeyconsiderationswere
summedupbytheJavadesignteaminthefollowinglistofbuzzwords.
Simple

Javahasaconcise,cohesivesetoffeaturesthat
makesiteasytolearnanduse.

Secure

Javaprovidesasecuremeansofcreating
Internetapplications.

Portable

Javaprogramscanexecuteinany
environmentforwhichthereisaJavaruntime
system.

Objectoriented

Javaembodiesthemodern,objectoriented
programmingphilosophy.

Robust

Javaencourageserrorfreeprogrammingby
beingstrictlytypedandperformingruntime
checks.

Multithreaded

Javaprovidesintegratedsupportfor
multithreadedprogramming.

Architecture

Javaisnottiedtoaspecificmachineor

neutral

operatingsystemarchitecture.

Interpreted

Javasupportscrossplatformcodethroughthe
useofJavabytecode.

High

TheJavabytecodeishighlyoptimizedforspeed

performance

ofexecution.

Distributed

Javawasdesignedwiththedistributed
environmentoftheInternetinmind.

Dynamic

Javaprogramscarrywiththemsubstantial
amountsofruntimetypeinformationthatis
usedtoverifyandresolveaccessestoobjectsat
runtime.

AsktheExpert

Q:Toaddresstheissuesofportabilityandsecurity,why
wasitnecessarytocreateanewcomputerlanguagesuchas
JavacouldntalanguagelikeC++beadapted?Inother
words,couldntaC++compilerthatoutputsbytecodebe
created?

A:WhileitwouldbepossibleforaC++compilertogenerate
somethingsimilartobytecoderatherthanexecutablecode,C++has
featuresthatdiscourageitsuseforthecreationofInternetprograms
themostimportantfeaturebeingC++ssupportforpointers.A
pointeristheaddressofsomeobjectstoredinmemory.Usinga
pointer,itwouldbepossibletoaccessresourcesoutsidetheprogram
itself,resultinginasecuritybreach.Javadoesnotsupportpointers,
thuseliminatingthisproblem.

ObjectOrientedProgramming
AtthecenterofJavaisobjectorientedprogramming(OOP).Theobject
orientedmethodologyisinseparablefromJava,andallJavaprograms
are,toatleastsomeextent,objectoriented.BecauseofOOPs
importancetoJava,itisusefultounderstandinageneralwayOOPs
basicprinciplesbeforeyouwriteevenasimpleJavaprogram.Laterin
thisbook,youwillseehowtoputtheseconceptsintopractice.
OOPisapowerfulwaytoapproachthejobofprogramming.
Programmingmethodologieshavechangeddramaticallysincethe
inventionofthecomputer,primarilytoaccommodatetheincreasing
complexityofprograms.Forexample,whencomputerswerefirst
invented,programmingwasdonebytogglinginthebinarymachine
instructionsusingthecomputersfrontpanel.Aslongasprogramswere
justafewhundredinstructionslong,thisapproachworked.Asprograms
grew,assemblylanguagewasinventedsothataprogrammercoulddeal
withlarger,increasinglycomplexprograms,usingsymbolic
representationsofthemachineinstructions.Asprogramscontinuedto
grow,highlevellanguageswereintroducedthatgavetheprogrammer
moretoolswithwhichtohandlecomplexity.Thefirstwidespread
languagewas,ofcourse,FORTRAN.AlthoughFORTRANwasavery
impressivefirststep,itishardlyalanguagethatencouragesclear,easy
tounderstandprograms.
The1960sgavebirthtostructuredprogramming.Thisisthemethod
encouragedbylanguagessuchasCandPascal.Theuseofstructured

https://www.safaribooksonline.com/library/view/javaabeginners/9780071809252/ch01.html

5/19

4/18/2015

Chapter1:JavaFundamentalsJavaABeginner'sGuide,6thEdition

languagesmadeitpossibletowritemoderatelycomplexprogramsfairly
easily.Structuredlanguagesarecharacterizedbytheirsupportforstand
alonesubroutines,localvariables,richcontrolconstructs,andtheirlack
ofrelianceupontheGOTO.Althoughstructuredlanguagesareapowerful
tool,eventheyreachtheirlimitwhenaprojectbecomestoolarge.
Considerthis:Ateachmilestoneinthedevelopmentofprogramming,
techniquesandtoolswerecreatedtoallowtheprogrammertodealwith
increasinglygreatercomplexity.Eachstepoftheway,thenewapproach
tookthebestelementsofthepreviousmethodsandmovedforward.Prior
totheinventionofOOP,manyprojectswerenearing(orexceeding)the
pointwherethestructuredapproachnolongerworks.Objectoriented
methodswerecreatedtohelpprogrammersbreakthroughthesebarriers.
Objectorientedprogrammingtookthebestideasofstructured
programmingandcombinedthemwithseveralnewconcepts.Theresult
wasadifferentwayoforganizingaprogram.Inthemostgeneralsense,
aprogramcanbeorganizedinoneoftwoways:arounditscode(whatis
happening)orarounditsdata(whatisbeingaffected).Usingonly
structuredprogrammingtechniques,programsaretypicallyorganized
aroundcode.Thisapproachcanbethoughtofascodeactingondata.
Objectorientedprogramsworktheotherwayaround.Theyare
organizedarounddata,withthekeyprinciplebeingdatacontrolling
accesstocode.Inanobjectorientedlanguage,youdefinethedataand
theroutinesthatarepermittedtoactonthatdata.Thus,adatatype
definespreciselywhatsortofoperationscanbeappliedtothatdata.
Tosupporttheprinciplesofobjectorientedprogramming,allOOP
languages,includingJava,havethreetraitsincommon:encapsulation,
polymorphism,andinheritance.Letsexamineeach.
Encapsulation
Encapsulationisaprogrammingmechanismthatbindstogethercodeand
thedataitmanipulates,andthatkeepsbothsafefromoutside
interferenceandmisuse.Inanobjectorientedlanguage,codeanddata
canbeboundtogetherinsuchawaythataselfcontainedblackboxis
created.Withintheboxareallnecessarydataandcode.Whencodeand
dataarelinkedtogetherinthisfashion,anobjectiscreated.Inother
words,anobjectisthedevicethatsupportsencapsulation.
Withinanobject,code,data,orbothmaybeprivatetothatobjector
public.Privatecodeordataisknowntoandaccessiblebyonlyanother
partoftheobject.Thatis,privatecodeordatacannotbeaccessedbya
pieceoftheprogramthatexistsoutsidetheobject.Whencodeordatais
public,otherpartsofyourprogramcanaccessiteventhoughitisdefined
withinanobject.Typically,thepublicpartsofanobjectareusedto
provideacontrolledinterfacetotheprivateelementsoftheobject.
Javasbasicunitofencapsulationistheclass.Althoughtheclasswillbe
examinedingreatdetaillaterinthisbook,thefollowingbriefdiscussion
willbehelpfulnow.Aclassdefinestheformofanobject.Itspecifiesboth
thedataandthecodethatwilloperateonthatdata.Javausesaclass
specificationtoconstructobjects.Objectsareinstancesofaclass.Thus,a
classisessentiallyasetofplansthatspecifyhowtobuildanobject.
Thecodeanddatathatconstituteaclassarecalledmembersoftheclass.
Specifically,thedatadefinedbytheclassarereferredtoasmember
variablesorinstancevariables.Thecodethatoperatesonthatdatais
referredtoasmembermethodsorjustmethods.MethodisJavastermfor
asubroutine.IfyouarefamiliarwithC/C++,itmayhelptoknowthat
whataJavaprogrammercallsamethod,aC/C++programmercallsa
function.
Polymorphism
Polymorphism(fromGreek,meaningmanyforms)isthequalitythat
allowsoneinterfacetoaccessageneralclassofactions.Thespecific
actionisdeterminedbytheexactnatureofthesituation.Asimple
exampleofpolymorphismisfoundinthesteeringwheelofan
automobile.Thesteeringwheel(i.e.,theinterface)isthesamenomatter
whattypeofactualsteeringmechanismisused.Thatis,thesteering
wheelworksthesamewhetheryourcarhasmanualsteering,power
steering,orrackandpinionsteering.Therefore,onceyouknowhowto
operatethesteeringwheel,youcandriveanytypeofcar.
Thesameprinciplecanalsoapplytoprogramming.Forexample,
considerastack(whichisafirstin,lastoutlist).Youmighthavea
programthatrequiresthreedifferenttypesofstacks.Onestackisusedfor
integervalues,oneforfloatingpointvalues,andoneforcharacters.In
thiscase,thealgorithmthatimplementseachstackisthesame,even
thoughthedatabeingstoreddiffers.Inanonobjectorientedlanguage,
youwouldberequiredtocreatethreedifferentsetsofstackroutines,with
eachsetusingdifferentnames.However,becauseofpolymorphism,in
Javayoucancreateonegeneralsetofstackroutinesthatworksforall
threespecificsituations.Thisway,onceyouknowhowtouseonestack,
youcanusethemall.

https://www.safaribooksonline.com/library/view/javaabeginners/9780071809252/ch01.html

6/19

4/18/2015

Chapter1:JavaFundamentalsJavaABeginner'sGuide,6thEdition

Moregenerally,theconceptofpolymorphismisoftenexpressedbythe
phraseoneinterface,multiplemethods.Thismeansthatitispossibleto
designagenericinterfacetoagroupofrelatedactivities.Polymorphism
helpsreducecomplexitybyallowingthesameinterfacetobeusedto
specifyageneralclassofaction.Itisthecompilersjobtoselectthe
specificaction(i.e.,method)asitappliestoeachsituation.You,the
programmer,dontneedtodothisselectionmanually.Youneedonly
rememberandutilizethegeneralinterface.
Inheritance
Inheritanceistheprocessbywhichoneobjectcanacquiretheproperties
ofanotherobject.Thisisimportantbecauseitsupportstheconceptof
hierarchicalclassification.Ifyouthinkaboutit,mostknowledgeismade
manageablebyhierarchical(i.e.,topdown)classifications.Forexample,
aRedDeliciousappleispartoftheclassificationapple,whichinturnis
partofthefruitclass,whichisunderthelargerclassfood.Thatis,thefood
classpossessescertainqualities(edible,nutritious,etc.)whichalso,
logically,applytoitssubclass,fruit.Inadditiontothesequalities,the
fruitclasshasspecificcharacteristics(juicy,sweet,etc.)thatdistinguishit
fromotherfood.Theappleclassdefinesthosequalitiesspecifictoan
apple(growsontrees,nottropical,etc.).ARedDeliciousapplewould,in
turn,inheritallthequalitiesofallprecedingclasses,andwoulddefine
onlythosequalitiesthatmakeitunique.
Withouttheuseofhierarchies,eachobjectwouldhavetoexplicitlydefine
allofitscharacteristics.Usinginheritance,anobjectneedonlydefine
thosequalitiesthatmakeituniquewithinitsclass.Itcaninheritits
generalattributesfromitsparent.Thus,itistheinheritancemechanism
thatmakesitpossibleforoneobjecttobeaspecificinstanceofamore
generalcase.
ObtainingtheJavaDevelopmentKit
NowthatthetheoreticalunderpinningofJavahasbeenexplained,itis
timetostartwritingJavaprograms.Beforeyoucancompileandrun
thoseprograms,however,youmusthavetheJavaDevelopmentKit(JDK)
installedonyourcomputer.TheJDKisavailablefreeofchargefrom
Oracle.Atthetimeofthiswriting,thecurrentreleaseoftheJDKisJDK
8.ThisistheversionusedbyJavaSE8.(SEstandsforStandardEdition.)
BecauseJDK8containsmanynewfeaturesthatarenotsupportedby
earlierversionsofJava,itisrecommendedthatyouuseJDK8(orlater)
tocompileandruntheprogramsinthisbook.Ifyouuseanearlier
version,thenprogramscontainingnewfeatureswillnotcompile.
TheJDKcanbedownloadedfrom
www.oracle.com/technetwork/java/javase/downloads/index.html(http://www.oracle.com/technetwork/java/javase/downloads/index.html)
Justgotothedownloadpageandfollowtheinstructionsforthetypeof
computerthatyouhave.AfteryouhaveinstalledtheJDK,youwillbeable
tocompileandrunprograms.TheJDKsuppliestwoprimaryprograms.
Thefirstisjavac,whichistheJavacompiler.Thesecondisjava,which
isthestandardJavainterpreterandisalsoreferredtoastheapplication
launcher.
Oneotherpoint:TheJDKrunsinthecommandpromptenvironmentand
usescommandlinetools.Itisnotawindowedapplication.Itisalsonot
anintegrateddevelopmentenvironment(IDE).

NOTE

Inadditiontothebasiccommandlinetoolssuppliedwiththe
JDK,thereareseveralhighqualityIDEsavailableforJava,
suchasNetBeansandEclipse.AnIDEcanbeveryhelpfulwhen
developinganddeployingcommercialapplications.Asa
generalrule,youcanalsouseanIDEtocompileandrunthe
programsinthisbookifyousochoose.However,the
instructionspresentedinthisbookforcompilingandrunninga
JavaprogramdescribeonlytheJDKcommandlinetools.The
reasonsforthisareeasytounderstand.First,theJDKisreadily
availabletoallreaders.Second,theinstructionsforusingthe
JDKwillbethesameforallreaders.Furthermore,forthe
simpleprogramspresentedinthisbook,usingtheJDK
commandlinetoolsisusuallytheeasiestapproach.Ifyouare
usinganIDE,youwillneedtofollowitsinstructions.Because
ofdifferencesbetweenIDEs,nogeneralsetofinstructionscan
begiven.

AsktheExpert

Q:Youstatethatobjectorientedprogrammingisan
effectivewaytomanagelargeprograms.However,itseems

https://www.safaribooksonline.com/library/view/javaabeginners/9780071809252/ch01.html

7/19

4/18/2015

Chapter1:JavaFundamentalsJavaABeginner'sGuide,6thEdition

thatitmightaddsubstantialoverheadtorelativelysmall
ones.SinceyousaythatallJavaprogramsare,tosome
extent,objectoriented,doesthisimposeapenaltyfor
smallerprograms?

A:No.Asyouwillsee,forsmallprograms,Javasobjectoriented
featuresarenearlytransparent.AlthoughitistruethatJavafollows
astrictobjectmodel,youhavewidelatitudeastothedegreetowhich
youemployit.Forsmallerprograms,theirobjectorientednessis
barelyperceptible.Asyourprogramsgrow,youwillintegratemore
objectorientedfeatureseffortlessly.

AFirstSimpleProgram
Letsstartbycompilingandrunningtheshortsampleprogramshown
here:

Youwillfollowthesethreesteps:
1.Entertheprogram.
2.Compiletheprogram.
3.Runtheprogram.
EnteringtheProgram
TheprogramsshowninthisbookareavailablefromMcGrawHill
Educationswebsite:
www.oraclepressbooks.com(http://www.oraclepressbooks.com).
However,ifyouwanttoentertheprogramsbyhand,youarefreetodo
so.Inthiscase,youmustentertheprogramintoyourcomputerusinga
texteditor,notawordprocessor.Wordprocessorstypicallystoreformat
informationalongwithtext.Thisformatinformationwillconfusethe
Javacompiler.IfyouareusingaWindowsplatform,youcanuse
WordPadoranyotherprogrammingeditorthatyoulike.
Formostcomputerlanguages,thenameofthefilethatholdsthesource
codetoaprogramisarbitrary.However,thisisnotthecasewithJava.
ThefirstthingthatyoumustlearnaboutJavaisthatthenameyougiveto
asourcefileisveryimportant.Forthisexample,thenameofthesource
fileshouldbeExample.java.Letsseewhy.
InJava,asourcefileisofficiallycalledacompilationunit.Itisatextfile
thatcontains(amongotherthings)oneormoreclassdefinitions.(For
now,wewillbeusingsourcefilesthatcontainonlyoneclass.)TheJava
compilerrequiresthatasourcefileusethe.javafilenameextension.As
youcanseebylookingattheprogram,thenameoftheclassdefinedby
theprogramisalsoExample.Thisisnotacoincidence.InJava,allcode
mustresideinsideaclass.Byconvention,thenameofthemainclass
shouldmatchthenameofthefilethatholdstheprogram.Youshouldalso
makesurethatthecapitalizationofthefilenamematchestheclassname.
ThereasonforthisisthatJavaiscasesensitive.Atthispoint,the
conventionthatfilenamescorrespondtoclassnamesmayseem
arbitrary.However,thisconventionmakesiteasiertomaintainand
organizeyourprograms.
CompilingtheProgram
TocompiletheExampleprogram,executethecompiler,javac,
specifyingthenameofthesourcefileonthecommandline,asshown
here:

ThejavaccompilercreatesafilecalledExample.classthatcontainsthe
bytecodeversionoftheprogram.Remember,bytecodeisnotexecutable
code.BytecodemustbeexecutedbyaJavaVirtualMachine.Thus,the
outputofjavacisnotcodethatcanbedirectlyexecuted.
Toactuallyruntheprogram,youmustusetheJavainterpreter,java.To
doso,passtheclassnameExampleasacommandlineargument,as
shownhere:

Whentheprogramisrun,thefollowingoutputisdisplayed:

https://www.safaribooksonline.com/library/view/javaabeginners/9780071809252/ch01.html

8/19

4/18/2015

Chapter1:JavaFundamentalsJavaABeginner'sGuide,6thEdition

WhenJavasourcecodeiscompiled,eachindividualclassisputintoits
ownoutputfilenamedaftertheclassandusingthe.classextension.
ThisiswhyitisagoodideatogiveyourJavasourcefilesthesamename
astheclasstheycontainthenameofthesourcefilewillmatchthename
ofthe.classfile.WhenyouexecutetheJavainterpreterasjustshown,
youareactuallyspecifyingthenameoftheclassthatyouwantthe
interpretertoexecute.Itwillautomaticallysearchforafilebythatname
thathasthe.classextension.Ifitfindsthefile,itwillexecutethecode
containedinthespecifiedclass.

NOTE

If,whenyoutrytocompiletheprogram,thecomputercannot
findjavac(andassumingthatyouhaveinstalledtheJDK
correctly),youmayneedtospecifythepathtothecommand
linetools.InWindows,forexample,thismeansthatyouwill
needtoaddthepathtothecommandlinetoolstothepaths
definedforthePATHenvironmentalvariable.Forexample,if
JDK8wasinstalledundertheProgramFilesdirectory,thenthe
pathtothecommandlinetoolswillbesimilartoC:\Program
Files\Java\jdk1.8.0\bin.(Ofcourse,youwillneedtofindthe
pathtoJavaonyourcomputer,whichmaydifferfromtheone
justshown.AlsothespecificversionoftheJDKmaydiffer.)You
willneedtoconsultthedocumentationforyouroperating
systemonhowtosetthepath,becausethisprocedurediffers
betweenOSes.

TheFirstSampleProgramLinebyLine
AlthoughExample.javaisquiteshort,itincludesseveralkeyfeatures
thatarecommontoallJavaprograms.Letscloselyexamineeachpartof
theprogram.
Theprogrambeginswiththefollowinglines:

Thisisacomment.Likemostotherprogramminglanguages,Javalets
youenteraremarkintoaprogramssourcefile.Thecontentsofa
commentareignoredbythecompiler.Instead,acommentdescribesor
explainstheoperationoftheprogramtoanyonewhoisreadingitssource
code.Inthiscase,thecommentdescribestheprogramandremindsyou
thatthesourcefileshouldbecalledExample.java.Ofcourse,inreal
applications,commentsgenerallyexplainhowsomepartoftheprogram
worksorwhataspecificfeaturedoes.
Javasupportsthreestylesofcomments.Theoneshownatthetopofthe
programiscalledamultilinecomment.Thistypeofcommentmustbegin
with/*andendwith*/.Anythingbetweenthesetwocommentsymbolsis
ignoredbythecompiler.Asthenamesuggests,amultilinecommentmay
beseverallineslong.
Thenextlineofcodeintheprogramisshownhere:

Thislineusesthekeywordclasstodeclarethatanewclassisbeing
defined.Asmentioned,theclassisJavasbasicunitofencapsulation.
Exampleisthenameoftheclass.Theclassdefinitionbeginswiththe
openingcurlybrace({)andendswiththeclosingcurlybrace(}).The
elementsbetweenthetwobracesaremembersoftheclass.Forthe
moment,dontworrytoomuchaboutthedetailsofaclassexcepttonote
thatinJava,allprogramactivityoccurswithinone.Thisisonereason
whyallJavaprogramsare(atleastalittlebit)objectoriented.
Thenextlineintheprogramisthesinglelinecomment,shownhere:

ThisisthesecondtypeofcommentsupportedbyJava.Asingleline
commentbeginswitha//andendsattheendoftheline.Asageneral
rule,programmersusemultilinecommentsforlongerremarksand
singlelinecommentsforbrief,linebylinedescriptions.
Thenextlineofcodeisshownhere:

https://www.safaribooksonline.com/library/view/javaabeginners/9780071809252/ch01.html

9/19

4/18/2015

Chapter1:JavaFundamentalsJavaABeginner'sGuide,6thEdition

Thislinebeginsthemain()method.Asmentionedearlier,inJava,a
subroutineiscalledamethod.Asthecommentprecedingitsuggests,this
isthelineatwhichtheprogramwillbeginexecuting.AllJava
applicationsbeginexecutionbycallingmain().Theexactmeaningof
eachpartofthislinecannotbegivennow,sinceitinvolvesadetailed
understandingofseveralotherofJavasfeatures.However,sincemany
oftheexamplesinthisbookwillusethislineofcode,letstakeabrief
lookateachpartnow.
Thepublickeywordisanaccessmodifier.Anaccessmodifierdetermines
howotherpartsoftheprogramcanaccessthemembersoftheclass.When
aclassmemberisprecededbypublic,thenthatmembercanbeaccessed
bycodeoutsidetheclassinwhichitisdeclared.(Theoppositeofpublicis
private,whichpreventsamemberfrombeingusedbycodedefined
outsideofitsclass.)Inthiscase,main()mustbedeclaredaspublic,
sinceitmustbecalledbycodeoutsideofitsclasswhentheprogramis
started.Thekeywordstaticallowsmain()tobecalledbeforeanobject
oftheclasshasbeencreated.Thisisnecessarybecausemain()iscalled
bytheJVMbeforeanyobjectsaremade.Thekeywordvoidsimplytells
thecompilerthatmain()doesnotreturnavalue.Asyouwillsee,
methodsmayalsoreturnvalues.Ifallthisseemsabitconfusing,dont
worry.Alloftheseconceptswillbediscussedindetailinsubsequent
chapters.
Asstated,main()isthemethodcalledwhenaJavaapplicationbegins.
Anyinformationthatyouneedtopasstoamethodisreceivedby
variablesspecifiedwithinthesetofparenthesesthatfollowthenameof
themethod.Thesevariablesarecalledparameters.Ifnoparametersare
requiredforagivenmethod,youstillneedtoincludetheempty
parentheses.Inmain()thereisonlyoneparameter,Stringargs[],
whichdeclaresaparameternamedargs.Thisisanarrayofobjectsof
typeString.(Arraysarecollectionsofsimilarobjects.)Objectsoftype
Stringstoresequencesofcharacters.Inthiscase,argsreceivesany
commandlineargumentspresentwhentheprogramisexecuted.This
programdoesnotmakeuseofthisinformation,butotherprograms
shownlaterinthisbookwill.
Thelastcharacteronthelineisthe{.Thissignalsthestartofmain()s
body.Allofthecodeincludedinamethodwilloccurbetweenthe
methodsopeningcurlybraceanditsclosingcurlybrace.
Thenextlineofcodeisshownhere.Noticethatitoccursinsidemain().

Thislineoutputsthestring"JavadrivestheWeb."followedbyanewline
onthescreen.Outputisactuallyaccomplishedbythebuiltinprintln()
method.Inthiscase,println()displaysthestringthatispassedtoit.As
youwillsee,println()canbeusedtodisplayothertypesofinformation,
too.ThelinebeginswithSystem.out.Whiletoocomplicatedtoexplain
indetailatthistime,briefly,Systemisapredefinedclassthatprovides
accesstothesystem,andoutistheoutputstreamthatisconnectedtothe
console.Thus,System.outisanobjectthatencapsulatesconsoleoutput.
ThefactthatJavausesanobjecttodefineconsoleoutputisfurther
evidenceofitsobjectorientednature.
Asyouhaveprobablyguessed,consoleoutput(andinput)isnotused
frequentlyinrealworldJavaapplications.Sincemostmodern
computingenvironmentsarewindowedandgraphicalinnature,console
I/Oisusedmostlyforsimpleutilityprograms,fordemonstration
programs,andforserversidecode.Laterinthisbook,youwilllearn
otherwaystogenerateoutputusingJava,butfornow,wewillcontinue
tousetheconsoleI/Omethods.
Noticethattheprintln()statementendswithasemicolon.All
statementsinJavaendwithasemicolon.Thereasonthattheotherlines
intheprogramdonotendinasemicolonisthattheyarenot,technically,
statements.
Thefirst}intheprogramendsmain(),andthelast}endstheExample
classdefinition.
Onelastpoint:Javaiscasesensitive.Forgettingthiscancauseyou
seriousproblems.Forexample,ifyouaccidentallytypeMaininsteadof
main,orPrintLninsteadofprintln,theprecedingprogramwillbe
incorrect.Furthermore,althoughtheJavacompilerwillcompileclasses
thatdonotcontainamain()method,ithasnowaytoexecutethem.So,
ifyouhadmistypedmain,thecompilerwouldstillcompileyourprogram.
However,theJavainterpreterwouldreportanerrorbecauseitwouldbe
unabletofindthemain()method.
HandlingSyntaxErrors
Ifyouhavenotyetdoneso,enter,compile,andrunthepreceding
program.Asyoumayknowfromyourpreviousprogramming
experience,itisquiteeasytoaccidentallytypesomethingincorrectly
whenenteringcodeintoyourcomputer.Fortunately,ifyouenter
somethingincorrectlyintoyourprogram,thecompilerwillreporta
syntaxerrormessagewhenittriestocompileit.TheJavacompiler

https://www.safaribooksonline.com/library/view/javaabeginners/9780071809252/ch01.html

10/19

4/18/2015

Chapter1:JavaFundamentalsJavaABeginner'sGuide,6thEdition

attemptstomakesenseoutofyoursourcecodenomatterwhatyouhave
written.Forthisreason,theerrorthatisreportedmaynotalwaysreflect
theactualcauseoftheproblem.Intheprecedingprogram,forexample,
anaccidentalomissionoftheopeningcurlybraceafterthemain()
methodcausesthecompilertoreportthefollowingtwoerrors:

Clearly,thefirsterrormessageiscompletelywrongbecausewhatis
missingisnotasemicolon,butacurlybrace.
Thepointofthisdiscussionisthatwhenyourprogramcontainsasyntax
error,youshouldntnecessarilytakethecompilersmessagesatface
value.Themessagesmaybemisleading.Youmayneedtosecond
guessanerrormessageinordertofindtherealproblem.Also,lookat
thelastfewlinesofcodeinyourprogramthatprecedethelinebeing
flagged.Sometimesanerrorwillnotbereporteduntilseverallinesafter
thepointatwhichtheerroractuallyoccurred.
ASecondSimpleProgram
Perhapsnootherconstructisasimportanttoaprogramminglanguageas
theassignmentofavaluetoavariable.Avariableisanamedmemory
locationthatcanbeassignedavalue.Further,thevalueofavariablecan
bechangedduringtheexecutionofaprogram.Thatis,thecontentofa
variableischangeable,notfixed.Thefollowingprogramcreatestwo
variablescalledvar1andvar2:

Whenyourunthisprogram,youwillseethefollowingoutput:

Thisprogramintroducesseveralnewconcepts.First,thestatement

declaresavariablecalledvar1oftypeinteger.InJava,allvariables
mustbedeclaredbeforetheyareused.Further,thetypeofvaluesthatthe
variablecanholdmustalsobespecified.Thisiscalledthetypeofthe
variable.Inthiscase,var1canholdintegervalues.Thesearewhole
numbervalues.InJava,todeclareavariabletobeoftypeinteger,
precedeitsnamewiththekeywordint.Thus,theprecedingstatement
declaresavariablecalledvar1oftypeint.
Thenextlinedeclaresasecondvariablecalledvar2:

Noticethatthislineusesthesameformatasthefirstlineexceptthatthe
nameofthevariableisdifferent.
Ingeneral,todeclareavariableyouwilluseastatementlikethis:
typevarname
Here,typespecifiesthetypeofvariablebeingdeclared,andvarnameis
thenameofthevariable.Inadditiontoint,Javasupportsseveralother
datatypes.
Thefollowinglineofcodeassignsvar1thevalue1024:

InJava,theassignmentoperatoristhesingleequalsign.Itcopiesthe
valueonitsrightsideintothevariableonitsleft.
Thenextlineofcodeoutputsthevalueofvar1precededbythestring
"var1contains":

https://www.safaribooksonline.com/library/view/javaabeginners/9780071809252/ch01.html

11/19

4/18/2015

Chapter1:JavaFundamentalsJavaABeginner'sGuide,6thEdition

Inthisstatement,theplussigncausesthevalueofvar1tobedisplayed
afterthestringthatprecedesit.Thisapproachcanbegeneralized.Using
the+operator,youcanchaintogetherasmanyitemsasyouwantwithin
asingleprintln()statement.
Thenextlineofcodeassignsvar2thevalueofvar1dividedby2:

Thislinedividesthevalueinvar1by2andthenstoresthatresultin
var2.Thus,afterthelineexecutes,var2willcontainthevalue512.The
valueofvar1willbeunchanged.Likemostothercomputerlanguages,
Javasupportsafullrangeofarithmeticoperators,includingthoseshown
here:
+

Addition

Subtraction

Multiplication

Division

Herearethenexttwolinesintheprogram:

Twonewthingsareoccurringhere.First,thebuiltinmethodprint()is
usedtodisplaythestring"var2containsvar1/2:".Thisstringisnot
followedbyanewline.Thismeansthatwhenthenextoutputis
generated,itwillstartonthesameline.Theprint()methodisjustlike
println(),exceptthatitdoesnotoutputanewlineaftereachcall.
Second,inthecalltoprintln(),noticethatvar2isusedbyitself.Both
print()andprintln()canbeusedtooutputvaluesofanyofJavasbuilt
intypes.
Onemorepointaboutdeclaringvariablesbeforewemoveon:Itis
possibletodeclaretwoormorevariablesusingthesamedeclaration
statement.Justseparatetheirnamesbycommas.Forexample,var1and
var2couldhavebeendeclaredlikethis:

AnotherDataType
Intheprecedingprogram,avariableoftypeintwasused.However,a
variableoftypeintcanholdonlywholenumbers.Thus,itcannotbeused
whenafractionalcomponentisrequired.Forexample,anintvariable
canholdthevalue18,butnotthevalue18.3.Fortunately,intisonlyone
ofseveraldatatypesdefinedbyJava.Toallownumberswithfractional
components,Javadefinestwofloatingpointtypes:floatanddouble,
whichrepresentsingleanddoubleprecisionvalues,respectively.Ofthe
two,doubleisthemostcommonlyused.
Todeclareavariableoftypedouble,useastatementsimilartothat
shownhere:

Here,xisthenameofthevariable,whichisoftypedouble.Becausex
hasafloatingpointtype,itcanholdvaluessuchas122.23,0.034,or
19.0.
Tobetterunderstandthedifferencebetweenintanddouble,trythe
followingprogram:

Theoutputfromthisprogramisshownhere:

https://www.safaribooksonline.com/library/view/javaabeginners/9780071809252/ch01.html

12/19

4/18/2015

Chapter1:JavaFundamentalsJavaABeginner'sGuide,6thEdition

Asyoucansee,whenvarisdividedby4,awholenumberdivisionis
performed,andtheoutcomeis2thefractionalcomponentislost.
However,whenxisdividedby4,thefractionalcomponentispreserved,
andtheproperanswerisdisplayed.
Thereisoneothernewthingtonoticeintheprogram.Toprintablank
line,simplycallprintln()withoutanyarguments.

AsktheExpert

Q:WhydoesJavahavedifferentdatatypesforintegersand
floatingpointvalues?Thatis,whyarentallnumericvalues
justthesametype?

A:Javasuppliesdifferentdatatypessothatyoucanwriteefficient
programs.Forexample,integerarithmeticisfasterthanfloating
pointcalculations.Thus,ifyoudontneedfractionalvalues,thenyou
dontneedtoincurtheoverheadassociatedwithtypesfloator
double.Second,theamountofmemoryrequiredforonetypeofdata
mightbelessthanthatrequiredforanother.Bysupplyingdifferent
types,Javaenablesyoutomakebestuseofsystemresources.
Finally,somealgorithmsrequire(oratleastbenefitfrom)theuseof
aspecifictypeofdata.Ingeneral,Javasuppliesanumberofbuiltin
typestogiveyouthegreatestflexibility.

TryThis11

ConvertingGallonstoLiters

Althoughtheprecedingsampleprogramsillustrateseveralimportant
featuresoftheJavalanguage,theyarenotveryuseful.Eventhoughyou
donotknowmuchaboutJavaatthispoint,youcanstillputwhatyouhave
learnedtoworktocreateapracticalprogram.Inthisproject,wewill
createaprogramthatconvertsgallonstoliters.Theprogramwillwork
bydeclaringtwodoublevariables.Onewillholdthenumberofthe
gallons,andthesecondwillholdthenumberoflitersafterthe
conversion.Thereare3.7854litersinagallon.Thus,toconvertgallons
toliters,thegallonvalueismultipliedby3.7854.Theprogramdisplays
boththenumberofgallonsandtheequivalentnumberofliters.
1.CreateanewfilecalledGalToLit.java.
2.Enterthefollowingprogramintothefile:

3.Compiletheprogramusingthefollowingcommandline:

4.Runtheprogramusingthiscommand:

Youwillseethisoutput:

5.Asitstands,thisprogramconverts10gallonstoliters.However,
bychangingthevalueassignedtogallons,youcanhavetheprogram
convertadifferentnumberofgallonsintoitsequivalentnumberof
liters.

TwoControlStatements
Insideamethod,executionproceedsfromonestatementtothenext,top
tobottom.However,itispossibletoalterthisflowthroughtheuseofthe
variousprogramcontrolstatementssupportedbyJava.Althoughwewill
lookcloselyatcontrolstatementslater,twoarebrieflyintroducedhere
becausewewillbeusingthemtowritesampleprograms.
TheifStatement

https://www.safaribooksonline.com/library/view/javaabeginners/9780071809252/ch01.html

13/19

4/18/2015

Chapter1:JavaFundamentalsJavaABeginner'sGuide,6thEdition

YoucanselectivelyexecutepartofaprogramthroughtheuseofJavas
conditionalstatement:theif.TheJavaifstatementworksmuchlikethe
IFstatementinanyotherlanguage.Itssimplestformisshownhere:
if(condition)statement
Here,conditionisaBooleanexpression.Ifconditionistrue,thenthe
statementisexecuted.Ifconditionisfalse,thenthestatementis
bypassed.Hereisanexample:

Inthiscase,since10islessthan11,theconditionalexpressionistrue,
andprintln()willexecute.However,considerthefollowing:

Inthiscase,10isnotlessthan9.Thus,thecalltoprintln()willnottake
place.
Javadefinesafullcomplementofrelationaloperatorsthatmaybeused
inaconditionalexpression.Theyareshownhere:

Operator

Meaning

<

Lessthan

<=

Lessthanorequal

>

Greaterthan

>=

Greaterthanorequal

==

Equalto

!=

Notequal

Noticethatthetestforequalityisthedoubleequalsign.
Hereisaprogramthatillustratestheifstatement:

Theoutputgeneratedbythisprogramisshownhere:

Noticeoneotherthinginthisprogram.Theline

declaresthreevariables,a,b,andc,byuseofacommaseparatedlist.As
mentionedearlier,whenyouneedtwoormorevariablesofthesame
type,theycanbedeclaredinonestatement.Justseparatethevariable
namesbycommas.
TheforLoop
Youcanrepeatedlyexecuteasequenceofcodebycreatingaloop.Java

https://www.safaribooksonline.com/library/view/javaabeginners/9780071809252/ch01.html

14/19

4/18/2015

Chapter1:JavaFundamentalsJavaABeginner'sGuide,6thEdition

suppliesapowerfulassortmentofloopconstructs.Theonewewilllookat
hereistheforloop.Thesimplestformoftheforloopisshownhere:
for(initializationconditioniteration)statement
Initsmostcommonform,theinitializationportionoftheloopsetsaloop
controlvariabletoaninitialvalue.TheconditionisaBoolean
expressionthatteststheloopcontrolvariable.Iftheoutcomeofthattest
istrue,theforloopcontinuestoiterate.Ifitisfalse,theloopterminates.
Theiterationexpressiondetermineshowtheloopcontrolvariableis
changedeachtimetheloopiterates.Hereisashortprogramthat
illustratestheforloop:

Theoutputgeneratedbytheprogramisshownhere:

Inthisexample,countistheloopcontrolvariable.Itissettozerointhe
initializationportionofthefor.Atthestartofeachiteration(including
thefirstone),theconditionaltestcount<5isperformed.Iftheoutcome
ofthistestistrue,theprintln()statementisexecuted,andthenthe
iterationportionoftheloopisexecuted,whichincreasescountby1.This
processcontinuesuntiltheconditionaltestisfalse,atwhichpoint
executionpicksupatthebottomoftheloop.Asapointofinterest,in
professionallywrittenJavaprograms,youwillalmostneverseethe
iterationportionoftheloopwrittenasshownintheprecedingprogram.
Thatis,youwillseldomseestatementslikethis:

ThereasonisthatJavaincludesaspecialincrementoperatorthat
performsthisoperationmoreefficiently.Theincrementoperatoris++
(thatis,twoplussignsbacktoback).Theincrementoperatorincreasesits
operandbyone.Byuseoftheincrementoperator,thepreceding
statementcanbewrittenlikethis:

Thus,theforintheprecedingprogramwillusuallybewrittenlikethis:

Youmightwanttotrythis.Asyouwillsee,theloopstillrunsexactlythe
sameasitdidbefore.
Javaalsoprovidesadecrementoperator,whichisspecifiedas.This
operatordecreasesitsoperandbyone.
CreateBlocksofCode
AnotherkeyelementofJavaisthecodeblock.Acodeblockisagrouping
oftwoormorestatements.Thisisdonebyenclosingthestatements
betweenopeningandclosingcurlybraces.Onceablockofcodehasbeen
created,itbecomesalogicalunitthatcanbeusedanyplacethatasingle
statementcan.Forexample,ablockcanbeatargetforJavasifandfor
statements.Considerthisifstatement:

Here,ifwislessthanh,bothstatementsinsidetheblockwillbe
executed.Thus,thetwostatementsinsidetheblockformalogicalunit,
andonestatementcannotexecutewithouttheotheralsoexecuting.The
keypointhereisthatwheneveryouneedtologicallylinktwoormore
statements,youdosobycreatingablock.Codeblocksallowmany
algorithmstobeimplementedwithgreaterclarityandefficiency.
Hereisaprogramthatusesablockofcodetopreventadivisionbyzero:

https://www.safaribooksonline.com/library/view/javaabeginners/9780071809252/ch01.html

15/19

4/18/2015

Chapter1:JavaFundamentalsJavaABeginner'sGuide,6thEdition

Theoutputgeneratedbythisprogramisshownhere:

Inthiscase,thetargetoftheifstatementisablockofcodeandnotjusta
singlestatement.Iftheconditioncontrollingtheifistrue(asitisinthis
case),thethreestatementsinsidetheblockwillbeexecuted.Trysettingi
tozeroandobservetheresult.Youwillseethattheentireblockis
skipped.

AsktheExpert

Q:Doestheuseofacodeblockintroduceanyruntime
inefficiencies?Inotherwords,doesJavaactuallyexecutethe
{and}?

A:No.Codeblocksdonotaddanyoverheadwhatsoever.Infact,
becauseoftheirabilitytosimplifythecodingofcertainalgorithms,
theirusegenerallyincreasesspeedandefficiency.Also,the{and}
existonlyinyourprogramssourcecode.Javadoesnot,perse,
executethe{or}.

Asyouwillseelaterinthisbook,blocksofcodehaveadditional
propertiesanduses.However,themainreasonfortheirexistenceisto
createlogicallyinseparableunitsofcode.
SemicolonsandPositioning
InJava,thesemicolonisaseparatorthatisusedtoterminatea
statement.Thatis,eachindividualstatementmustbeendedwitha
semicolon.Itindicatestheendofonelogicalentity.
Asyouknow,ablockisasetoflogicallyconnectedstatementsthatare
surroundedbyopeningandclosingbraces.Ablockisnotterminatedwith
asemicolon.Sinceablockisagroupofstatements,withasemicolon
aftereachstatement,itmakessensethatablockisnotterminatedbya
semicoloninstead,theendoftheblockisindicatedbytheclosingbrace.
Javadoesnotrecognizetheendofthelineasaterminator.Forthis
reason,itdoesnotmatterwhereonalineyouputastatement.For
example,

isthesameasthefollowing,toJava:

Furthermore,theindividualelementsofastatementcanalsobeputon
separatelines.Forexample,thefollowingisperfectlyacceptable:

Breakinglonglinesinthisfashionisoftenusedtomakeprogramsmore
readable.Itcanalsohelppreventexcessivelylonglinesfromwrapping.
IndentationPractices
Youmayhavenoticedinthepreviousexamplesthatcertainstatements
wereindented.Javaisafreeformlanguage,meaningthatitdoesnot
matterwhereyouplacestatementsrelativetoeachotheronaline.
However,overtheyears,acommonandacceptedindentationstylehas
developedthatallowsforveryreadableprograms.Thisbookfollowsthat
style,anditisrecommendedthatyoudosoaswell.Usingthisstyle,you
indentonelevelaftereachopeningbrace,andmovebackoutonelevel
aftereachclosingbrace.Certainstatementsencouragesomeadditional
indentingthesewillbecoveredlater.

TryThis12

https://www.safaribooksonline.com/library/view/javaabeginners/9780071809252/ch01.html

16/19

4/18/2015

Chapter1:JavaFundamentalsJavaABeginner'sGuide,6thEdition

ImprovingtheGallonstoLitersConverter

Youcanusetheforloop,theifstatement,andcodeblockstocreatean
improvedversionofthegallonstolitersconverterthatyoudevelopedin
thefirstproject.Thisnewversionwillprintatableofconversions,
beginningwith1gallonandendingat100gallons.Afterevery10
gallons,ablanklinewillbeoutput.Thisisaccomplishedthroughtheuse
ofavariablecalledcounterthatcountsthenumberoflinesthathave
beenoutput.Payspecialattentiontoitsuse.
1.CreateanewfilecalledGalToLitTable.java.
2.Enterthefollowingprogramintothefile:

3.Compiletheprogramusingthefollowingcommandline:

4.Runtheprogramusingthiscommand:

Hereisaportionoftheoutputthatyouwillsee:

TheJavaKeywords
FiftykeywordsarecurrentlydefinedintheJavalanguage(seeTable1
1).Thesekeywords,combinedwiththesyntaxoftheoperatorsand
separators,formthedefinitionoftheJavalanguage.Thesekeywords
cannotbeusedasnamesforavariable,class,ormethod.

https://www.safaribooksonline.com/library/view/javaabeginners/9780071809252/ch01.html

17/19

4/18/2015

Chapter1:JavaFundamentalsJavaABeginner'sGuide,6thEdition

Table11TheJavaKeywords

Thekeywordsconstandgotoarereservedbutnotused.Intheearly
daysofJava,severalotherkeywordswerereservedforpossiblefuture
use.However,thecurrentspecificationforJavadefinesonlythe
keywordsshowninTable11.
Inadditiontothekeywords,Javareservesthefollowing:true,false,
andnull.ThesearevaluesdefinedbyJava.Youmaynotusethesewords
forthenamesofvariables,classes,andsoon.
IdentifiersinJava
InJavaanidentifierisanamegiventoamethod,avariable,orany
otheruserdefineditem.Identifierscanbefromonetoseveralcharacters
long.Variablenamesmaystartwithanyletterofthealphabet,an
underscore,oradollarsign.Nextmaybeeitheraletter,adigit,adollar
sign,oranunderscore.Theunderscorecanbeusedtoenhancethe
readabilityofavariablename,asinline_count.Uppercaseand
lowercasearedifferentthatis,toJava,myvarandMyVarareseparate
names.Herearesomeexamplesofacceptableidentifiers:

Remember,youcantstartanidentifierwithadigit.Thus,12xisinvalid,
forexample.
YoucannotuseanyoftheJavakeywordsasidentifiernames.Also,you
shouldnotusethenameofanystandardmethod,suchasprintln,asan
identifier.Beyondthesetworestrictions,goodprogrammingpractice
dictatesthatyouuseidentifiernamesthatreflectthemeaningorusageof
theitemsbeingnamed.
TheJavaClassLibraries
ThesampleprogramsshowninthischaptermakeuseoftwoofJavas
builtinmethods:println()andprint().Thesemethodsareaccessed
throughSystem.out.SystemisaclasspredefinedbyJavathatis
automaticallyincludedinyourprograms.Inthelargerview,theJava
environmentreliesonseveralbuiltinclasslibrariesthatcontainmany
builtinmethodsthatprovidesupportforsuchthingsasI/O,string
handling,networking,andgraphics.Thestandardclassesalsoprovide
supportforagraphicaluserinterface(GUI).Thus,Javaasatotalityisa
combinationoftheJavalanguageitself,plusitsstandardclasses.Asyou
willsee,theclasslibrariesprovidemuchofthefunctionalitythatcomes
withJava.Indeed,partofbecomingaJavaprogrammerislearningto
usethestandardJavaclasses.Throughoutthisbook,variouselementsof
thestandardlibraryclassesandmethodsaredescribed.However,the
Javalibraryissomethingthatyouwillalsowanttoexploremoreonyour
own.

Chapter1SelfTest
1 .WhatisbytecodeandwhyisitimportanttoJavasusefor
Internetprogramming?
2 .Whatarethethreemainprinciplesofobjectoriented
programming?
3 .WheredoJavaprogramsbeginexecution?

4 .Whatisavariable?

5 .Whichofthefollowingvariablenamesisinvalid?
A.count
B.$count
C.count27
D.67count
6 .Howdoyoucreateasinglelinecomment?Howdoyou
createamultilinecomment?
7 .Showthegeneralformoftheifstatement.Showthegeneral

https://www.safaribooksonline.com/library/view/javaabeginners/9780071809252/ch01.html

18/19

4/18/2015

Chapter1:JavaFundamentalsJavaABeginner'sGuide,6thEdition

formoftheforloop.
8 .Howdoyoucreateablockofcode?
9 .Themoonsgravityisabout17percentthatofearths.Write
aprogramthatcomputesyoureffectiveweightonthemoon.
10.AdaptTryThis12sothatitprintsaconversiontableofinches
tometers.Display12feetofconversions,inchbyinch.Outputa
blanklineevery12inches.(Onemeterequalsapproximately39.37
inches.)
11.Ifyoumakeatypingmistakewhenenteringyourprogram,
whatsortoferrorwillresult?
12.Doesitmatterwhereonalineyouputastatement?

Recommended / Queue / Recent / Topics / Tutorials / Settings / Blog(http://blog.safaribooksonline.com) /


Feedback(http://community.safaribooksonline.com/) / Sign Out
2015 Safari(http://www.safaribooksonline.com/).
Terms of Service / Privacy Policy

https://www.safaribooksonline.com/library/view/javaabeginners/9780071809252/ch01.html

19/19