Chapter 1_ Java Fundamentals - Java A Beginner's Guide, 6th Edition.pdf
Transcript of Chapter 1_ Java Fundamentals - Java A Beginner's Guide, 6th Edition.pdf
-
4/18/2015 Chapter1:JavaFundamentalsJavaABeginner'sGuide,6thEdition
https://www.safaribooksonline.com/library/view/javaabeginners/9780071809252/ch01.html 1/19
T
Chapter1
JavaFundamentals
KeySkills&Concepts
KnowthehistoryandphilosophyofJava
UnderstandJavascontributiontotheInternet
Understandtheimportanceofbytecode
KnowtheJavabuzzwords
Understandthefoundationalprinciplesofobjectorientedprogramming
Create,compile,andrunasimpleJavaprogram
Usevariables
Usetheifandforcontrolstatements
Createblocksofcode
Understandhowstatementsarepositioned,indented,andterminated
KnowtheJavakeywords
UnderstandtherulesforJavaidentifiers
heriseoftheInternetandtheWorldWideWebfundamentallyreshapedcomputing.PriortotheWeb,thecyberlandscapewas
dominatedbystandalonePCs.Today,nearlyallcomputersareconnectedtotheInternet.TheInternet,itself,wastransformedoriginallyofferingaconvenientwaytosharefilesandinformation.Todayitisavast,distributedcomputinguniverse.Withthesechangescameanewwaytoprogram:Java.
JavaisthepreeminentlanguageoftheInternet,butitismorethanthat.Javarevolutionizedprogramming,changingthewaythatwethinkaboutboththeformandthefunctionofaprogram.TobeaprofessionalprogrammertodayimpliestheabilitytoprograminJavaitisthatimportant.Inthecourseofthisbook,youwilllearntheskillsneededtomasterit.
ThepurposeofthischapteristointroduceyoutoJava,includingitshistory,itsdesignphilosophy,andseveralofitsmostimportantfeatures.Byfar,thehardestthingaboutlearningaprogramminglanguageisthefactthatnoelementexistsinisolation.Instead,thecomponentsofthelanguageworkinconjunctionwitheachother.ThisinterrelatednessisespeciallypronouncedinJava.Infact,itisdifficulttodiscussoneaspectofJavawithoutinvolvingothers.Tohelpovercomethisproblem,thischapterprovidesabriefoverviewofseveralJavafeatures,includingthegeneralformofaJavaprogram,somebasiccontrolstructures,andoperators.Itdoesnotgointotoomanydetailsbut,rather,concentratesonthegeneralconceptscommontoanyJavaprogram.
TheOriginsofJava
PREVIntroduction
NEXTChapter 2: Introdu
Java A Beginner's Guide, 6th Edition Recent
Topics
Tutorials
Highlights
Settings
Feedback(http://community.safaribooksonline.com)
Sign Out
Settings
days left in your trial. Subscribe.
Feedback(http://community.safaribooksonline.com/)
Sign Out
Enjoy Safari? Subscribe Today
-
4/18/2015 Chapter1:JavaFundamentalsJavaABeginner'sGuide,6thEdition
https://www.safaribooksonline.com/library/view/javaabeginners/9780071809252/ch01.html 2/19
Computerlanguageinnovationisdrivenforwardbytwofactors:improvementsintheartofprogrammingandchangesinthecomputingenvironment.Javaisnoexception.BuildingupontherichlegacyinheritedfromCandC++,Javaaddsrefinementsandfeaturesthatreflectthecurrentstateoftheartinprogramming.Respondingtotheriseoftheonlineenvironment,Javaoffersfeaturesthatstreamlineprogrammingforahighlydistributedarchitecture.
JavawasconceivedbyJamesGosling,PatrickNaughton,ChrisWarth,EdFrank,andMikeSheridanatSunMicrosystemsin1991.ThislanguagewasinitiallycalledOakbutwasrenamedJavain1995.Somewhatsurprisingly,theoriginalimpetusforJavawasnottheInternet!Instead,theprimarymotivationwastheneedforaplatformindependentlanguagethatcouldbeusedtocreatesoftwaretobeembeddedinvariousconsumerelectronicdevices,suchastoasters,microwaveovens,andremotecontrols.Asyoucanprobablyguess,manydifferenttypesofCPUsareusedascontrollers.Thetroublewasthat(atthattime)mostcomputerlanguagesweredesignedtobecompiledforaspecifictarget.Forexample,considerC++.
AlthoughitwaspossibletocompileaC++programforjustaboutanytypeofCPU,todosorequiredafullC++compilertargetedforthatCPU.Theproblem,however,isthatcompilersareexpensiveandtimeconsumingtocreate.Inanattempttofindabettersolution,Goslingandothersworkedonaportable,crossplatformlanguagethatcouldproducecodethatwouldrunonavarietyofCPUsunderdifferingenvironments.ThiseffortultimatelyledtothecreationofJava.
AboutthetimethatthedetailsofJavawerebeingworkedout,asecond,andultimatelymoreimportant,factoremergedthatwouldplayacrucialroleinthefutureofJava.Thissecondforcewas,ofcourse,theWorldWideWeb.HadtheWebnottakenshapeataboutthesametimethatJavawasbeingimplemented,Javamighthaveremainedausefulbutobscurelanguageforprogrammingconsumerelectronics.However,withtheemergenceoftheWeb,Javawaspropelledtotheforefrontofcomputerlanguagedesign,becausetheWeb,too,demandedportableprograms.
Mostprogrammerslearnearlyintheircareersthatportableprogramsareaselusiveastheyaredesirable.Whilethequestforawaytocreateefficient,portable(platformindependent)programsisnearlyasoldasthedisciplineofprogrammingitself,ithadtakenabackseattoother,morepressingproblems.However,withtheadventoftheInternetandtheWeb,theoldproblemofportabilityreturnedwithavengeance.Afterall,theInternetconsistsofadiverse,distributeduniversepopulatedwithmanytypesofcomputers,operatingsystems,andCPUs.
Whatwasonceanirritatingbutalowpriorityproblemhadbecomeahighprofilenecessity.By1993,itbecameobvioustomembersoftheJavadesignteamthattheproblemsofportabilityfrequentlyencounteredwhencreatingcodeforembeddedcontrollersarealsofoundwhenattemptingtocreatecodefortheInternet.ThisrealizationcausedthefocusofJavatoswitchfromconsumerelectronicstoInternetprogramming.So,whileitwasthedesireforanarchitectureneutralprogramminglanguagethatprovidedtheinitialspark,itwastheInternetthatultimatelyledtoJavaslargescalesuccess.
HowJavaRelatestoCandC++
JavaisdirectlyrelatedtobothCandC++.JavainheritsitssyntaxfromC.ItsobjectmodelisadaptedfromC++.JavasrelationshipwithCandC++isimportantforseveralreasons.First,manyprogrammersarefamiliarwiththeC/C++syntax.ThismakesiteasyforaC/C++programmertolearnJavaand,conversely,foraJavaprogrammertolearnC/C++.
Second,Javasdesignersdidnotreinventthewheel.Instead,theyfurtherrefinedanalreadyhighlysuccessfulprogrammingparadigm.ThemodernageofprogrammingbeganwithC.ItmovedtoC++,andnowtoJava.Byinheritingandbuildinguponthatrichheritage,Javaprovidesapowerful,logicallyconsistentprogrammingenvironmentthattakesthebestofthepastandaddsnewfeaturesrequiredbytheonlineenvironment.Perhapsmostimportant,becauseoftheirsimilarities,C,C++,andJavadefineacommon,conceptualframeworkfortheprofessionalprogrammer.Programmersdonotfacemajorriftswhenswitchingfromonelanguagetoanother.
OneofthecentraldesignphilosophiesofbothCandC++isthattheprogrammerisincharge!Javaalsoinheritsthisphilosophy.ExceptforthoseconstraintsimposedbytheInternetenvironment,Javagivesyou,theprogrammer,fullcontrol.Ifyouprogramwell,yourprogramsreflectit.Ifyouprogrampoorly,yourprogramsreflectthat,too.Putdifferently,Javaisnotalanguagewithtrainingwheels.Itisalanguageforprofessionalprogrammers.
JavahasoneotherattributeincommonwithCandC++:itwasdesigned,tested,andrefinedbyreal,workingprogrammers.Itisalanguagegroundedintheneedsandexperiencesofthepeoplewhodevisedit.Thereisnobetterwaytoproduceatopflightprofessionalprogramming
-
4/18/2015 Chapter1:JavaFundamentalsJavaABeginner'sGuide,6thEdition
https://www.safaribooksonline.com/library/view/javaabeginners/9780071809252/ch01.html 3/19
language.
BecauseofthesimilaritiesbetweenJavaandC++,especiallytheirsupportforobjectorientedprogramming,itistemptingtothinkofJavaassimplytheInternetversionofC++.However,todosowouldbeamistake.Javahassignificantpracticalandphilosophicaldifferences.AlthoughJavawasinfluencedbyC++,itisnotanenhancedversionofC++.Forexample,itisneitherupwardlynordownwardlycompatiblewithC++.Ofcourse,thesimilaritieswithC++aresignificant,andifyouareaC++programmer,youwillfeelrightathomewithJava.Anotherpoint:JavawasnotdesignedtoreplaceC++.Javawasdesignedtosolveacertainsetofproblems.C++wasdesignedtosolveadifferentsetofproblems.Theywillcoexistformanyyearstocome.
HowJavaRelatestoC#
AfewyearsafterthecreationofJava,MicrosoftdevelopedtheC#language.ThisisimportantbecauseC#iscloselyrelatedtoJava.Infact,manyofC#sfeaturesdirectlyparallelJava.BothJavaandC#sharethesamegeneralC++stylesyntax,supportdistributedprogramming,andutilizethesameobjectmodel.Thereare,ofcourse,differencesbetweenJavaandC#,buttheoveralllookandfeeloftheselanguagesisverysimilar.ThismeansthatifyoualreadyknowC#,thenlearningJavawillbeespeciallyeasy.Conversely,ifC#isinyourfuture,thenyourknowledgeofJavawillcomeinhandy.
GiventhesimilaritybetweenJavaandC#,onemightnaturallyask,WillC#replaceJava?TheanswerisNo.JavaandC#areoptimizedfortwodifferenttypesofcomputingenvironments.JustasC++andJavawillcoexistforalongtimetocome,sowillC#andJava.
JavasContributiontotheInternet
TheInternethelpedcatapultJavatotheforefrontofprogramming,andJava,inturn,hadaprofoundeffectontheInternet.Inadditiontosimplifyingwebprogrammingingeneral,Javainnovatedanewtypeofnetworkedprogramcalledtheappletthatchangedthewaytheonlineworldthoughtaboutcontent.JavaalsoaddressedsomeofthethorniestissuesassociatedwiththeInternet:portabilityandsecurity.Letslookmorecloselyateachofthese.
JavaApplets
AnappletisaspecialkindofJavaprogramthatisdesignedtobetransmittedovertheInternetandautomaticallyexecutedbyaJavacompatiblewebbrowser.Furthermore,anappletisdownloadedondemand,withoutfurtherinteractionwiththeuser.Iftheuserclicksalinkthatcontainsanapplet,theappletwillbeautomaticallydownloadedandruninthebrowser.Appletsareintendedtobesmallprograms.Theyaretypicallyusedtodisplaydataprovidedbytheserver,handleuserinput,orprovidesimplefunctions,suchasaloancalculator,thatexecutelocally,ratherthanontheserver.Inessence,theappletallowssomefunctionalitytobemovedfromtheservertotheclient.
ThecreationoftheappletchangedInternetprogrammingbecauseitexpandedtheuniverseofobjectsthatcanmoveaboutfreelyincyberspace.Ingeneral,therearetwoverybroadcategoriesofobjectsthataretransmittedbetweentheserverandtheclient:passiveinformationanddynamic,activeprograms.Forexample,whenyoureadyouremail,youareviewingpassivedata.Evenwhenyoudownloadaprogram,theprogramscodeisstillonlypassivedatauntilyouexecuteit.Bycontrast,theappletisadynamic,selfexecutingprogram.Suchaprogramisanactiveagentontheclientcomputer,yetitisinitiatedbytheserver.
Asdesirableasdynamic,networkedprogramsare,theyalsopresentseriousproblemsintheareasofsecurityandportability.Obviously,aprogramthatdownloadsandexecutesautomaticallyontheclientcomputermustbepreventedfromdoingharm.Itmustalsobeabletoruninavarietyofdifferentenvironmentsandunderdifferentoperatingsystems.Asyouwillsee,Javasolvedtheseproblemsinaneffectiveandelegantway.Letslookabitmorecloselyateach.
Security
Asyouarelikelyaware,everytimethatyoudownloadanormalprogram,youaretakingariskbecausethecodeyouaredownloadingmightcontainavirus,Trojanhorse,orotherharmfulcode.Atthecoreoftheproblemisthefactthatmaliciouscodecancauseitsdamagebecauseithasgainedunauthorizedaccesstosystemresources.Forexample,avirusprogrammightgatherprivateinformation,suchascreditcardnumbers,bankaccountbalances,andpasswords,bysearchingthecontentsofyourcomputerslocalfilesystem.InorderforJavatoenableappletstobesafelydownloadedandexecutedontheclientcomputer,itwasnecessarytopreventanappletfromlaunchingsuchanattack.
JavaachievedthisprotectionbyconfininganapplettotheJavaexecutionenvironmentandnotallowingitaccesstootherpartsofthecomputer.(Youwillseehowthisisaccomplishedshortly.)Theabilitytodownloadappletswithconfidencethatnoharmwillbedoneandthatno
-
4/18/2015 Chapter1:JavaFundamentalsJavaABeginner'sGuide,6thEdition
https://www.safaribooksonline.com/library/view/javaabeginners/9780071809252/ch01.html 4/19
securitywillbebreachedisconsideredbymanytobethesinglemostinnovativeaspectofJava.
Portability
PortabilityisamajoraspectoftheInternetbecausetherearemanydifferenttypesofcomputersandoperatingsystemsconnectedtoit.IfaJavaprogramweretoberunonvirtuallyanycomputerconnectedtotheInternet,thereneededtobesomewaytoenablethatprogramtoexecuteondifferentsystems.Forexample,inthecaseofanapplet,thesameappletmustbeabletobedownloadedandexecutedbythewidevarietyofdifferentCPUs,operatingsystems,andbrowsersconnectedtotheInternet.Itisnotpracticaltohavedifferentversionsoftheappletfordifferentcomputers.Thesamecodemustworkinallcomputers.Therefore,somemeansofgeneratingportableexecutablecodewasneeded.Asyouwillsoonsee,thesamemechanismthathelpsensuresecurityalsohelpscreateportability.
JavasMagic:TheBytecode
ThekeythatallowsJavatosolveboththesecurityandtheportabilityproblemsjustdescribedisthattheoutputofaJavacompilerisnotexecutablecode.Rather,itisbytecode.BytecodeisahighlyoptimizedsetofinstructionsdesignedtobeexecutedbytheJavaruntimesystem,whichiscalledtheJavaVirtualMachine(JVM).Inessence,theoriginalJVMwasdesignedasaninterpreterforbytecode.Thismaycomeasabitofasurprisebecausemanymodernlanguagesaredesignedtobecompiledintoexecutablecodeduetoperformanceconcerns.However,thefactthataJavaprogramisexecutedbytheJVMhelpssolvethemajorproblemsassociatedwithwebbasedprograms.Hereiswhy.
TranslatingaJavaprogramintobytecodemakesitmucheasiertorunaprograminawidevarietyofenvironmentsbecauseonlytheJVMneedstobeimplementedforeachplatform.Oncetheruntimepackageexistsforagivensystem,anyJavaprogramcanrunonit.Remember,althoughthedetailsoftheJVMwilldifferfromplatformtoplatform,allunderstandthesameJavabytecode.IfaJavaprogramwerecompiledtonativecode,thendifferentversionsofthesameprogramwouldhavetoexistforeachtypeofCPUconnectedtotheInternet.Thisis,ofcourse,notafeasiblesolution.Thus,theexecutionofbytecodebytheJVMistheeasiestwaytocreatetrulyportableprograms.
ThefactthataJavaprogramisexecutedbytheJVMalsohelpstomakeitsecure.BecausetheJVMisincontrol,itcancontaintheprogramandpreventitfromgeneratingsideeffectsoutsideofthesystem.SafetyisalsoenhancedbycertainrestrictionsthatexistintheJavalanguage.
Whenaprogramisinterpreted,itgenerallyrunsslowerthanthesameprogramwouldrunifcompiledtoexecutablecode.However,withJava,thedifferentialbetweenthetwoisnotsogreat.Becausebytecodehasbeenhighlyoptimized,theuseofbytecodeenablestheJVMtoexecuteprogramsmuchfasterthanyoumightexpect.
AlthoughJavawasdesignedasaninterpretedlanguage,thereisnothingaboutJavathatpreventsontheflycompilationofbytecodeintonativecodeinordertoboostperformance.Forthisreason,theHotSpottechnologywasintroducednotlongafterJavasinitialrelease.HotSpotprovidesajustintime(JIT)compilerforbytecode.WhenaJITcompilerispartoftheJVM,selectedportionsofbytecodearecompiledintoexecutablecodeinrealtimeonapiecebypiece,demandbasis.ItisimportanttounderstandthatitisnotpracticaltocompileanentireJavaprogramintoexecutablecodeallatoncebecauseJavaperformsvariousruntimechecksthatcanbedoneonlyatruntime.Instead,aJITcompilercompilescodeasitisneeded,duringexecution.Furthermore,notallsequencesofbytecodearecompiledonlythosethatwillbenefitfromcompilation.Theremainingcodeissimplyinterpreted.However,thejustintimeapproachstillyieldsasignificantperformanceboost.Evenwhendynamiccompilationisappliedtobytecode,theportabilityandsafetyfeaturesstillapplybecausetheJVMisstillinchargeoftheexecutionenvironment.
AsktheExpert
Q:IhaveheardaboutaspecialtypeofJavaprogramcalledaservlet.Whatisit?
A:Aservletisasmallprogramthatexecutesonaserver.Justasappletsdynamicallyextendthefunctionalityofawebbrowser,servletsdynamicallyextendthefunctionalityofawebserver.Itishelpfultounderstandthatasusefulasappletscanbe,theyarejustonehalfoftheclient/serverequation.NotlongaftertheinitialreleaseofJava,itbecameobviousthatJavawouldalsobeusefulontheserverside.Theresultwastheservlet.Thus,withtheadventoftheservlet,Javaspannedbothsidesoftheclient/serverconnection.Althoughthecreationofservletsisbeyondthescopeofthisbeginnersguide,theyaresomethingthatyouwillwanttostudyfurtherasyouadvanceinJavaprogramming.(CoverageofservletscanbefoundinmybookJava:TheCompleteReference,publishedby
-
4/18/2015 Chapter1:JavaFundamentalsJavaABeginner'sGuide,6thEdition
https://www.safaribooksonline.com/library/view/javaabeginners/9780071809252/ch01.html 5/19
OraclePress/McGrawHillEducation.)
TheJavaBuzzwords
NooverviewofJavaiscompletewithoutalookattheJavabuzzwords.AlthoughthefundamentalforcesthatnecessitatedtheinventionofJavaareportabilityandsecurity,otherfactorsplayedanimportantroleinmoldingthefinalformofthelanguage.ThekeyconsiderationsweresummedupbytheJavadesignteaminthefollowinglistofbuzzwords.
Simple Javahasaconcise,cohesivesetoffeaturesthatmakesiteasytolearnanduse.
Secure JavaprovidesasecuremeansofcreatingInternetapplications.
Portable JavaprogramscanexecuteinanyenvironmentforwhichthereisaJavaruntimesystem.
Objectoriented Javaembodiesthemodern,objectorientedprogrammingphilosophy.
Robust Javaencourageserrorfreeprogrammingbybeingstrictlytypedandperformingruntimechecks.
Multithreaded Javaprovidesintegratedsupportformultithreadedprogramming.
Architectureneutral
Javaisnottiedtoaspecificmachineoroperatingsystemarchitecture.
Interpreted JavasupportscrossplatformcodethroughtheuseofJavabytecode.
Highperformance
TheJavabytecodeishighlyoptimizedforspeedofexecution.
Distributed JavawasdesignedwiththedistributedenvironmentoftheInternetinmind.
Dynamic Javaprogramscarrywiththemsubstantialamountsofruntimetypeinformationthatisusedtoverifyandresolveaccessestoobjectsatruntime.
AsktheExpert
Q:Toaddresstheissuesofportabilityandsecurity,whywasitnecessarytocreateanewcomputerlanguagesuchasJavacouldntalanguagelikeC++beadapted?Inotherwords,couldntaC++compilerthatoutputsbytecodebecreated?
A:WhileitwouldbepossibleforaC++compilertogeneratesomethingsimilartobytecoderatherthanexecutablecode,C++hasfeaturesthatdiscourageitsuseforthecreationofInternetprogramsthemostimportantfeaturebeingC++ssupportforpointers.Apointeristheaddressofsomeobjectstoredinmemory.Usingapointer,itwouldbepossibletoaccessresourcesoutsidetheprogramitself,resultinginasecuritybreach.Javadoesnotsupportpointers,thuseliminatingthisproblem.
ObjectOrientedProgramming
AtthecenterofJavaisobjectorientedprogramming(OOP).TheobjectorientedmethodologyisinseparablefromJava,andallJavaprogramsare,toatleastsomeextent,objectoriented.BecauseofOOPsimportancetoJava,itisusefultounderstandinageneralwayOOPsbasicprinciplesbeforeyouwriteevenasimpleJavaprogram.Laterinthisbook,youwillseehowtoputtheseconceptsintopractice.
OOPisapowerfulwaytoapproachthejobofprogramming.Programmingmethodologieshavechangeddramaticallysincetheinventionofthecomputer,primarilytoaccommodatetheincreasingcomplexityofprograms.Forexample,whencomputerswerefirstinvented,programmingwasdonebytogglinginthebinarymachineinstructionsusingthecomputersfrontpanel.Aslongasprogramswerejustafewhundredinstructionslong,thisapproachworked.Asprogramsgrew,assemblylanguagewasinventedsothataprogrammercoulddealwithlarger,increasinglycomplexprograms,usingsymbolicrepresentationsofthemachineinstructions.Asprogramscontinuedtogrow,highlevellanguageswereintroducedthatgavetheprogrammermoretoolswithwhichtohandlecomplexity.Thefirstwidespreadlanguagewas,ofcourse,FORTRAN.AlthoughFORTRANwasaveryimpressivefirststep,itishardlyalanguagethatencouragesclear,easytounderstandprograms.
The1960sgavebirthtostructuredprogramming.ThisisthemethodencouragedbylanguagessuchasCandPascal.Theuseofstructured
-
4/18/2015 Chapter1:JavaFundamentalsJavaABeginner'sGuide,6thEdition
https://www.safaribooksonline.com/library/view/javaabeginners/9780071809252/ch01.html 6/19
languagesmadeitpossibletowritemoderatelycomplexprogramsfairlyeasily.Structuredlanguagesarecharacterizedbytheirsupportforstandalonesubroutines,localvariables,richcontrolconstructs,andtheirlackofrelianceupontheGOTO.Althoughstructuredlanguagesareapowerfultool,eventheyreachtheirlimitwhenaprojectbecomestoolarge.
Considerthis:Ateachmilestoneinthedevelopmentofprogramming,techniquesandtoolswerecreatedtoallowtheprogrammertodealwithincreasinglygreatercomplexity.Eachstepoftheway,thenewapproachtookthebestelementsofthepreviousmethodsandmovedforward.PriortotheinventionofOOP,manyprojectswerenearing(orexceeding)thepointwherethestructuredapproachnolongerworks.Objectorientedmethodswerecreatedtohelpprogrammersbreakthroughthesebarriers.
Objectorientedprogrammingtookthebestideasofstructuredprogrammingandcombinedthemwithseveralnewconcepts.Theresultwasadifferentwayoforganizingaprogram.Inthemostgeneralsense,aprogramcanbeorganizedinoneoftwoways:arounditscode(whatishappening)orarounditsdata(whatisbeingaffected).Usingonlystructuredprogrammingtechniques,programsaretypicallyorganizedaroundcode.Thisapproachcanbethoughtofascodeactingondata.
Objectorientedprogramsworktheotherwayaround.Theyareorganizedarounddata,withthekeyprinciplebeingdatacontrollingaccesstocode.Inanobjectorientedlanguage,youdefinethedataandtheroutinesthatarepermittedtoactonthatdata.Thus,adatatypedefinespreciselywhatsortofoperationscanbeappliedtothatdata.
Tosupporttheprinciplesofobjectorientedprogramming,allOOPlanguages,includingJava,havethreetraitsincommon:encapsulation,polymorphism,andinheritance.Letsexamineeach.
Encapsulation
Encapsulationisaprogrammingmechanismthatbindstogethercodeandthedataitmanipulates,andthatkeepsbothsafefromoutsideinterferenceandmisuse.Inanobjectorientedlanguage,codeanddatacanbeboundtogetherinsuchawaythataselfcontainedblackboxiscreated.Withintheboxareallnecessarydataandcode.Whencodeanddataarelinkedtogetherinthisfashion,anobjectiscreated.Inotherwords,anobjectisthedevicethatsupportsencapsulation.
Withinanobject,code,data,orbothmaybeprivatetothatobjectorpublic.Privatecodeordataisknowntoandaccessiblebyonlyanotherpartoftheobject.Thatis,privatecodeordatacannotbeaccessedbyapieceoftheprogramthatexistsoutsidetheobject.Whencodeordataispublic,otherpartsofyourprogramcanaccessiteventhoughitisdefinedwithinanobject.Typically,thepublicpartsofanobjectareusedtoprovideacontrolledinterfacetotheprivateelementsoftheobject.
Javasbasicunitofencapsulationistheclass.Althoughtheclasswillbeexaminedingreatdetaillaterinthisbook,thefollowingbriefdiscussionwillbehelpfulnow.Aclassdefinestheformofanobject.Itspecifiesboththedataandthecodethatwilloperateonthatdata.Javausesaclassspecificationtoconstructobjects.Objectsareinstancesofaclass.Thus,aclassisessentiallyasetofplansthatspecifyhowtobuildanobject.
Thecodeanddatathatconstituteaclassarecalledmembersoftheclass.Specifically,thedatadefinedbytheclassarereferredtoasmembervariablesorinstancevariables.Thecodethatoperatesonthatdataisreferredtoasmembermethodsorjustmethods.MethodisJavastermforasubroutine.IfyouarefamiliarwithC/C++,itmayhelptoknowthatwhataJavaprogrammercallsamethod,aC/C++programmercallsafunction.
Polymorphism
Polymorphism(fromGreek,meaningmanyforms)isthequalitythatallowsoneinterfacetoaccessageneralclassofactions.Thespecificactionisdeterminedbytheexactnatureofthesituation.Asimpleexampleofpolymorphismisfoundinthesteeringwheelofanautomobile.Thesteeringwheel(i.e.,theinterface)isthesamenomatterwhattypeofactualsteeringmechanismisused.Thatis,thesteeringwheelworksthesamewhetheryourcarhasmanualsteering,powersteering,orrackandpinionsteering.Therefore,onceyouknowhowtooperatethesteeringwheel,youcandriveanytypeofcar.
Thesameprinciplecanalsoapplytoprogramming.Forexample,considerastack(whichisafirstin,lastoutlist).Youmighthaveaprogramthatrequiresthreedifferenttypesofstacks.Onestackisusedforintegervalues,oneforfloatingpointvalues,andoneforcharacters.Inthiscase,thealgorithmthatimplementseachstackisthesame,eventhoughthedatabeingstoreddiffers.Inanonobjectorientedlanguage,youwouldberequiredtocreatethreedifferentsetsofstackroutines,witheachsetusingdifferentnames.However,becauseofpolymorphism,inJavayoucancreateonegeneralsetofstackroutinesthatworksforallthreespecificsituations.Thisway,onceyouknowhowtouseonestack,youcanusethemall.
-
4/18/2015 Chapter1:JavaFundamentalsJavaABeginner'sGuide,6thEdition
https://www.safaribooksonline.com/library/view/javaabeginners/9780071809252/ch01.html 7/19
Moregenerally,theconceptofpolymorphismisoftenexpressedbythephraseoneinterface,multiplemethods.Thismeansthatitispossibletodesignagenericinterfacetoagroupofrelatedactivities.Polymorphismhelpsreducecomplexitybyallowingthesameinterfacetobeusedtospecifyageneralclassofaction.Itisthecompilersjobtoselectthespecificaction(i.e.,method)asitappliestoeachsituation.You,theprogrammer,dontneedtodothisselectionmanually.Youneedonlyrememberandutilizethegeneralinterface.
Inheritance
Inheritanceistheprocessbywhichoneobjectcanacquirethepropertiesofanotherobject.Thisisimportantbecauseitsupportstheconceptofhierarchicalclassification.Ifyouthinkaboutit,mostknowledgeismademanageablebyhierarchical(i.e.,topdown)classifications.Forexample,aRedDeliciousappleispartoftheclassificationapple,whichinturnispartofthefruitclass,whichisunderthelargerclassfood.Thatis,thefoodclasspossessescertainqualities(edible,nutritious,etc.)whichalso,logically,applytoitssubclass,fruit.Inadditiontothesequalities,thefruitclasshasspecificcharacteristics(juicy,sweet,etc.)thatdistinguishitfromotherfood.Theappleclassdefinesthosequalitiesspecifictoanapple(growsontrees,nottropical,etc.).ARedDeliciousapplewould,inturn,inheritallthequalitiesofallprecedingclasses,andwoulddefineonlythosequalitiesthatmakeitunique.
Withouttheuseofhierarchies,eachobjectwouldhavetoexplicitlydefineallofitscharacteristics.Usinginheritance,anobjectneedonlydefinethosequalitiesthatmakeituniquewithinitsclass.Itcaninherititsgeneralattributesfromitsparent.Thus,itistheinheritancemechanismthatmakesitpossibleforoneobjecttobeaspecificinstanceofamoregeneralcase.
ObtainingtheJavaDevelopmentKit
NowthatthetheoreticalunderpinningofJavahasbeenexplained,itistimetostartwritingJavaprograms.Beforeyoucancompileandrunthoseprograms,however,youmusthavetheJavaDevelopmentKit(JDK)installedonyourcomputer.TheJDKisavailablefreeofchargefromOracle.Atthetimeofthiswriting,thecurrentreleaseoftheJDKisJDK8.ThisistheversionusedbyJavaSE8.(SEstandsforStandardEdition.)BecauseJDK8containsmanynewfeaturesthatarenotsupportedbyearlierversionsofJava,itisrecommendedthatyouuseJDK8(orlater)tocompileandruntheprogramsinthisbook.Ifyouuseanearlierversion,thenprogramscontainingnewfeatureswillnotcompile.
TheJDKcanbedownloadedfromwww.oracle.com/technetwork/java/javase/downloads/index.html(http://www.oracle.com/technetwork/java/javase/downloads/index.html)
Justgotothedownloadpageandfollowtheinstructionsforthetypeofcomputerthatyouhave.AfteryouhaveinstalledtheJDK,youwillbeabletocompileandrunprograms.TheJDKsuppliestwoprimaryprograms.Thefirstisjavac,whichistheJavacompiler.Thesecondisjava,whichisthestandardJavainterpreterandisalsoreferredtoastheapplicationlauncher.
Oneotherpoint:TheJDKrunsinthecommandpromptenvironmentandusescommandlinetools.Itisnotawindowedapplication.Itisalsonotanintegrateddevelopmentenvironment(IDE).
NOTE
InadditiontothebasiccommandlinetoolssuppliedwiththeJDK,thereareseveralhighqualityIDEsavailableforJava,suchasNetBeansandEclipse.AnIDEcanbeveryhelpfulwhendevelopinganddeployingcommercialapplications.Asageneralrule,youcanalsouseanIDEtocompileandruntheprogramsinthisbookifyousochoose.However,theinstructionspresentedinthisbookforcompilingandrunningaJavaprogramdescribeonlytheJDKcommandlinetools.Thereasonsforthisareeasytounderstand.First,theJDKisreadilyavailabletoallreaders.Second,theinstructionsforusingtheJDKwillbethesameforallreaders.Furthermore,forthesimpleprogramspresentedinthisbook,usingtheJDKcommandlinetoolsisusuallytheeasiestapproach.IfyouareusinganIDE,youwillneedtofollowitsinstructions.BecauseofdifferencesbetweenIDEs,nogeneralsetofinstructionscanbegiven.
AsktheExpert
Q:Youstatethatobjectorientedprogrammingisaneffectivewaytomanagelargeprograms.However,itseems
-
4/18/2015 Chapter1:JavaFundamentalsJavaABeginner'sGuide,6thEdition
https://www.safaribooksonline.com/library/view/javaabeginners/9780071809252/ch01.html 8/19
thatitmightaddsubstantialoverheadtorelativelysmallones.SinceyousaythatallJavaprogramsare,tosomeextent,objectoriented,doesthisimposeapenaltyforsmallerprograms?
A:No.Asyouwillsee,forsmallprograms,Javasobjectorientedfeaturesarenearlytransparent.AlthoughitistruethatJavafollowsastrictobjectmodel,youhavewidelatitudeastothedegreetowhichyouemployit.Forsmallerprograms,theirobjectorientednessisbarelyperceptible.Asyourprogramsgrow,youwillintegratemoreobjectorientedfeatureseffortlessly.
AFirstSimpleProgram
Letsstartbycompilingandrunningtheshortsampleprogramshownhere:
Youwillfollowthesethreesteps:
1.Entertheprogram.
2.Compiletheprogram.
3.Runtheprogram.
EnteringtheProgram
TheprogramsshowninthisbookareavailablefromMcGrawHillEducationswebsite:www.oraclepressbooks.com(http://www.oraclepressbooks.com).
However,ifyouwanttoentertheprogramsbyhand,youarefreetodoso.Inthiscase,youmustentertheprogramintoyourcomputerusingatexteditor,notawordprocessor.Wordprocessorstypicallystoreformatinformationalongwithtext.ThisformatinformationwillconfusetheJavacompiler.IfyouareusingaWindowsplatform,youcanuseWordPadoranyotherprogrammingeditorthatyoulike.
Formostcomputerlanguages,thenameofthefilethatholdsthesourcecodetoaprogramisarbitrary.However,thisisnotthecasewithJava.ThefirstthingthatyoumustlearnaboutJavaisthatthenameyougivetoasourcefileisveryimportant.Forthisexample,thenameofthesourcefileshouldbeExample.java.Letsseewhy.
InJava,asourcefileisofficiallycalledacompilationunit.Itisatextfilethatcontains(amongotherthings)oneormoreclassdefinitions.(Fornow,wewillbeusingsourcefilesthatcontainonlyoneclass.)TheJavacompilerrequiresthatasourcefileusethe.javafilenameextension.Asyoucanseebylookingattheprogram,thenameoftheclassdefinedbytheprogramisalsoExample.Thisisnotacoincidence.InJava,allcodemustresideinsideaclass.Byconvention,thenameofthemainclassshouldmatchthenameofthefilethatholdstheprogram.Youshouldalsomakesurethatthecapitalizationofthefilenamematchestheclassname.ThereasonforthisisthatJavaiscasesensitive.Atthispoint,theconventionthatfilenamescorrespondtoclassnamesmayseemarbitrary.However,thisconventionmakesiteasiertomaintainandorganizeyourprograms.
CompilingtheProgram
TocompiletheExampleprogram,executethecompiler,javac,specifyingthenameofthesourcefileonthecommandline,asshownhere:
ThejavaccompilercreatesafilecalledExample.classthatcontainsthebytecodeversionoftheprogram.Remember,bytecodeisnotexecutablecode.BytecodemustbeexecutedbyaJavaVirtualMachine.Thus,theoutputofjavacisnotcodethatcanbedirectlyexecuted.
Toactuallyruntheprogram,youmustusetheJavainterpreter,java.Todoso,passtheclassnameExampleasacommandlineargument,asshownhere:
Whentheprogramisrun,thefollowingoutputisdisplayed:
-
4/18/2015 Chapter1:JavaFundamentalsJavaABeginner'sGuide,6thEdition
https://www.safaribooksonline.com/library/view/javaabeginners/9780071809252/ch01.html 9/19
WhenJavasourcecodeiscompiled,eachindividualclassisputintoitsownoutputfilenamedaftertheclassandusingthe.classextension.ThisiswhyitisagoodideatogiveyourJavasourcefilesthesamenameastheclasstheycontainthenameofthesourcefilewillmatchthenameofthe.classfile.WhenyouexecutetheJavainterpreterasjustshown,youareactuallyspecifyingthenameoftheclassthatyouwanttheinterpretertoexecute.Itwillautomaticallysearchforafilebythatnamethathasthe.classextension.Ifitfindsthefile,itwillexecutethecodecontainedinthespecifiedclass.
NOTE
If,whenyoutrytocompiletheprogram,thecomputercannotfindjavac(andassumingthatyouhaveinstalledtheJDKcorrectly),youmayneedtospecifythepathtothecommandlinetools.InWindows,forexample,thismeansthatyouwillneedtoaddthepathtothecommandlinetoolstothepathsdefinedforthePATHenvironmentalvariable.Forexample,ifJDK8wasinstalledundertheProgramFilesdirectory,thenthepathtothecommandlinetoolswillbesimilartoC:\ProgramFiles\Java\jdk1.8.0\bin.(Ofcourse,youwillneedtofindthepathtoJavaonyourcomputer,whichmaydifferfromtheonejustshown.AlsothespecificversionoftheJDKmaydiffer.)Youwillneedtoconsultthedocumentationforyouroperatingsystemonhowtosetthepath,becausethisprocedurediffersbetweenOSes.
TheFirstSampleProgramLinebyLine
AlthoughExample.javaisquiteshort,itincludesseveralkeyfeaturesthatarecommontoallJavaprograms.Letscloselyexamineeachpartoftheprogram.
Theprogrambeginswiththefollowinglines:
Thisisacomment.Likemostotherprogramminglanguages,Javaletsyouenteraremarkintoaprogramssourcefile.Thecontentsofacommentareignoredbythecompiler.Instead,acommentdescribesorexplainstheoperationoftheprogramtoanyonewhoisreadingitssourcecode.Inthiscase,thecommentdescribestheprogramandremindsyouthatthesourcefileshouldbecalledExample.java.Ofcourse,inrealapplications,commentsgenerallyexplainhowsomepartoftheprogramworksorwhataspecificfeaturedoes.
Javasupportsthreestylesofcomments.Theoneshownatthetopoftheprogramiscalledamultilinecomment.Thistypeofcommentmustbeginwith/*andendwith*/.Anythingbetweenthesetwocommentsymbolsisignoredbythecompiler.Asthenamesuggests,amultilinecommentmaybeseverallineslong.
Thenextlineofcodeintheprogramisshownhere:
Thislineusesthekeywordclasstodeclarethatanewclassisbeingdefined.Asmentioned,theclassisJavasbasicunitofencapsulation.Exampleisthenameoftheclass.Theclassdefinitionbeginswiththeopeningcurlybrace({)andendswiththeclosingcurlybrace(}).Theelementsbetweenthetwobracesaremembersoftheclass.Forthemoment,dontworrytoomuchaboutthedetailsofaclassexcepttonotethatinJava,allprogramactivityoccurswithinone.ThisisonereasonwhyallJavaprogramsare(atleastalittlebit)objectoriented.
Thenextlineintheprogramisthesinglelinecomment,shownhere:
ThisisthesecondtypeofcommentsupportedbyJava.Asinglelinecommentbeginswitha//andendsattheendoftheline.Asageneralrule,programmersusemultilinecommentsforlongerremarksandsinglelinecommentsforbrief,linebylinedescriptions.
Thenextlineofcodeisshownhere:
-
4/18/2015 Chapter1:JavaFundamentalsJavaABeginner'sGuide,6thEdition
https://www.safaribooksonline.com/library/view/javaabeginners/9780071809252/ch01.html 10/19
Thislinebeginsthemain()method.Asmentionedearlier,inJava,asubroutineiscalledamethod.Asthecommentprecedingitsuggests,thisisthelineatwhichtheprogramwillbeginexecuting.AllJavaapplicationsbeginexecutionbycallingmain().Theexactmeaningofeachpartofthislinecannotbegivennow,sinceitinvolvesadetailedunderstandingofseveralotherofJavasfeatures.However,sincemanyoftheexamplesinthisbookwillusethislineofcode,letstakeabrieflookateachpartnow.
Thepublickeywordisanaccessmodifier.Anaccessmodifierdetermineshowotherpartsoftheprogramcanaccessthemembersoftheclass.Whenaclassmemberisprecededbypublic,thenthatmembercanbeaccessedbycodeoutsidetheclassinwhichitisdeclared.(Theoppositeofpublicisprivate,whichpreventsamemberfrombeingusedbycodedefinedoutsideofitsclass.)Inthiscase,main()mustbedeclaredaspublic,sinceitmustbecalledbycodeoutsideofitsclasswhentheprogramisstarted.Thekeywordstaticallowsmain()tobecalledbeforeanobjectoftheclasshasbeencreated.Thisisnecessarybecausemain()iscalledbytheJVMbeforeanyobjectsaremade.Thekeywordvoidsimplytellsthecompilerthatmain()doesnotreturnavalue.Asyouwillsee,methodsmayalsoreturnvalues.Ifallthisseemsabitconfusing,dontworry.Alloftheseconceptswillbediscussedindetailinsubsequentchapters.
Asstated,main()isthemethodcalledwhenaJavaapplicationbegins.Anyinformationthatyouneedtopasstoamethodisreceivedbyvariablesspecifiedwithinthesetofparenthesesthatfollowthenameofthemethod.Thesevariablesarecalledparameters.Ifnoparametersarerequiredforagivenmethod,youstillneedtoincludetheemptyparentheses.Inmain()thereisonlyoneparameter,Stringargs[],whichdeclaresaparameternamedargs.ThisisanarrayofobjectsoftypeString.(Arraysarecollectionsofsimilarobjects.)ObjectsoftypeStringstoresequencesofcharacters.Inthiscase,argsreceivesanycommandlineargumentspresentwhentheprogramisexecuted.Thisprogramdoesnotmakeuseofthisinformation,butotherprogramsshownlaterinthisbookwill.
Thelastcharacteronthelineisthe{.Thissignalsthestartofmain()sbody.Allofthecodeincludedinamethodwilloccurbetweenthemethodsopeningcurlybraceanditsclosingcurlybrace.
Thenextlineofcodeisshownhere.Noticethatitoccursinsidemain().
Thislineoutputsthestring"JavadrivestheWeb."followedbyanewlineonthescreen.Outputisactuallyaccomplishedbythebuiltinprintln()method.Inthiscase,println()displaysthestringthatispassedtoit.Asyouwillsee,println()canbeusedtodisplayothertypesofinformation,too.ThelinebeginswithSystem.out.Whiletoocomplicatedtoexplainindetailatthistime,briefly,Systemisapredefinedclassthatprovidesaccesstothesystem,andoutistheoutputstreamthatisconnectedtotheconsole.Thus,System.outisanobjectthatencapsulatesconsoleoutput.ThefactthatJavausesanobjecttodefineconsoleoutputisfurtherevidenceofitsobjectorientednature.
Asyouhaveprobablyguessed,consoleoutput(andinput)isnotusedfrequentlyinrealworldJavaapplications.Sincemostmoderncomputingenvironmentsarewindowedandgraphicalinnature,consoleI/Oisusedmostlyforsimpleutilityprograms,fordemonstrationprograms,andforserversidecode.Laterinthisbook,youwilllearnotherwaystogenerateoutputusingJava,butfornow,wewillcontinuetousetheconsoleI/Omethods.
Noticethattheprintln()statementendswithasemicolon.AllstatementsinJavaendwithasemicolon.Thereasonthattheotherlinesintheprogramdonotendinasemicolonisthattheyarenot,technically,statements.
Thefirst}intheprogramendsmain(),andthelast}endstheExampleclassdefinition.
Onelastpoint:Javaiscasesensitive.Forgettingthiscancauseyouseriousproblems.Forexample,ifyouaccidentallytypeMaininsteadofmain,orPrintLninsteadofprintln,theprecedingprogramwillbeincorrect.Furthermore,althoughtheJavacompilerwillcompileclassesthatdonotcontainamain()method,ithasnowaytoexecutethem.So,ifyouhadmistypedmain,thecompilerwouldstillcompileyourprogram.However,theJavainterpreterwouldreportanerrorbecauseitwouldbeunabletofindthemain()method.
HandlingSyntaxErrors
Ifyouhavenotyetdoneso,enter,compile,andruntheprecedingprogram.Asyoumayknowfromyourpreviousprogrammingexperience,itisquiteeasytoaccidentallytypesomethingincorrectlywhenenteringcodeintoyourcomputer.Fortunately,ifyouentersomethingincorrectlyintoyourprogram,thecompilerwillreportasyntaxerrormessagewhenittriestocompileit.TheJavacompiler
-
4/18/2015 Chapter1:JavaFundamentalsJavaABeginner'sGuide,6thEdition
https://www.safaribooksonline.com/library/view/javaabeginners/9780071809252/ch01.html 11/19
attemptstomakesenseoutofyoursourcecodenomatterwhatyouhavewritten.Forthisreason,theerrorthatisreportedmaynotalwaysreflecttheactualcauseoftheproblem.Intheprecedingprogram,forexample,anaccidentalomissionoftheopeningcurlybraceafterthemain()methodcausesthecompilertoreportthefollowingtwoerrors:
Clearly,thefirsterrormessageiscompletelywrongbecausewhatismissingisnotasemicolon,butacurlybrace.
Thepointofthisdiscussionisthatwhenyourprogramcontainsasyntaxerror,youshouldntnecessarilytakethecompilersmessagesatfacevalue.Themessagesmaybemisleading.Youmayneedtosecondguessanerrormessageinordertofindtherealproblem.Also,lookatthelastfewlinesofcodeinyourprogramthatprecedethelinebeingflagged.Sometimesanerrorwillnotbereporteduntilseverallinesafterthepointatwhichtheerroractuallyoccurred.
ASecondSimpleProgram
Perhapsnootherconstructisasimportanttoaprogramminglanguageastheassignmentofavaluetoavariable.Avariableisanamedmemorylocationthatcanbeassignedavalue.Further,thevalueofavariablecanbechangedduringtheexecutionofaprogram.Thatis,thecontentofavariableischangeable,notfixed.Thefollowingprogramcreatestwovariablescalledvar1andvar2:
Whenyourunthisprogram,youwillseethefollowingoutput:
Thisprogramintroducesseveralnewconcepts.First,thestatement
declaresavariablecalledvar1oftypeinteger.InJava,allvariablesmustbedeclaredbeforetheyareused.Further,thetypeofvaluesthatthevariablecanholdmustalsobespecified.Thisiscalledthetypeofthevariable.Inthiscase,var1canholdintegervalues.Thesearewholenumbervalues.InJava,todeclareavariabletobeoftypeinteger,precedeitsnamewiththekeywordint.Thus,theprecedingstatementdeclaresavariablecalledvar1oftypeint.
Thenextlinedeclaresasecondvariablecalledvar2:
Noticethatthislineusesthesameformatasthefirstlineexceptthatthenameofthevariableisdifferent.
Ingeneral,todeclareavariableyouwilluseastatementlikethis:
typevarname
Here,typespecifiesthetypeofvariablebeingdeclared,andvarnameisthenameofthevariable.Inadditiontoint,Javasupportsseveralotherdatatypes.
Thefollowinglineofcodeassignsvar1thevalue1024:
InJava,theassignmentoperatoristhesingleequalsign.Itcopiesthevalueonitsrightsideintothevariableonitsleft.
Thenextlineofcodeoutputsthevalueofvar1precededbythestring"var1contains":
-
4/18/2015 Chapter1:JavaFundamentalsJavaABeginner'sGuide,6thEdition
https://www.safaribooksonline.com/library/view/javaabeginners/9780071809252/ch01.html 12/19
Inthisstatement,theplussigncausesthevalueofvar1tobedisplayedafterthestringthatprecedesit.Thisapproachcanbegeneralized.Usingthe+operator,youcanchaintogetherasmanyitemsasyouwantwithinasingleprintln()statement.
Thenextlineofcodeassignsvar2thevalueofvar1dividedby2:
Thislinedividesthevalueinvar1by2andthenstoresthatresultinvar2.Thus,afterthelineexecutes,var2willcontainthevalue512.Thevalueofvar1willbeunchanged.Likemostothercomputerlanguages,Javasupportsafullrangeofarithmeticoperators,includingthoseshownhere:
+ Addition
Subtraction
* Multiplication
/ Division
Herearethenexttwolinesintheprogram:
Twonewthingsareoccurringhere.First,thebuiltinmethodprint()isusedtodisplaythestring"var2containsvar1/2:".Thisstringisnotfollowedbyanewline.Thismeansthatwhenthenextoutputisgenerated,itwillstartonthesameline.Theprint()methodisjustlikeprintln(),exceptthatitdoesnotoutputanewlineaftereachcall.Second,inthecalltoprintln(),noticethatvar2isusedbyitself.Bothprint()andprintln()canbeusedtooutputvaluesofanyofJavasbuiltintypes.
Onemorepointaboutdeclaringvariablesbeforewemoveon:Itispossibletodeclaretwoormorevariablesusingthesamedeclarationstatement.Justseparatetheirnamesbycommas.Forexample,var1andvar2couldhavebeendeclaredlikethis:
AnotherDataType
Intheprecedingprogram,avariableoftypeintwasused.However,avariableoftypeintcanholdonlywholenumbers.Thus,itcannotbeusedwhenafractionalcomponentisrequired.Forexample,anintvariablecanholdthevalue18,butnotthevalue18.3.Fortunately,intisonlyoneofseveraldatatypesdefinedbyJava.Toallownumberswithfractionalcomponents,Javadefinestwofloatingpointtypes:floatanddouble,whichrepresentsingleanddoubleprecisionvalues,respectively.Ofthetwo,doubleisthemostcommonlyused.
Todeclareavariableoftypedouble,useastatementsimilartothatshownhere:
Here,xisthenameofthevariable,whichisoftypedouble.Becausexhasafloatingpointtype,itcanholdvaluessuchas122.23,0.034,or19.0.
Tobetterunderstandthedifferencebetweenintanddouble,trythefollowingprogram:
Theoutputfromthisprogramisshownhere:
-
4/18/2015 Chapter1:JavaFundamentalsJavaABeginner'sGuide,6thEdition
https://www.safaribooksonline.com/library/view/javaabeginners/9780071809252/ch01.html 13/19
Asyoucansee,whenvarisdividedby4,awholenumberdivisionisperformed,andtheoutcomeis2thefractionalcomponentislost.However,whenxisdividedby4,thefractionalcomponentispreserved,andtheproperanswerisdisplayed.
Thereisoneothernewthingtonoticeintheprogram.Toprintablankline,simplycallprintln()withoutanyarguments.
AsktheExpert
Q:WhydoesJavahavedifferentdatatypesforintegersandfloatingpointvalues?Thatis,whyarentallnumericvaluesjustthesametype?
A:Javasuppliesdifferentdatatypessothatyoucanwriteefficientprograms.Forexample,integerarithmeticisfasterthanfloatingpointcalculations.Thus,ifyoudontneedfractionalvalues,thenyoudontneedtoincurtheoverheadassociatedwithtypesfloatordouble.Second,theamountofmemoryrequiredforonetypeofdatamightbelessthanthatrequiredforanother.Bysupplyingdifferenttypes,Javaenablesyoutomakebestuseofsystemresources.Finally,somealgorithmsrequire(oratleastbenefitfrom)theuseofaspecifictypeofdata.Ingeneral,Javasuppliesanumberofbuiltintypestogiveyouthegreatestflexibility.
TryThis11 ConvertingGallonstoLiters
AlthoughtheprecedingsampleprogramsillustrateseveralimportantfeaturesoftheJavalanguage,theyarenotveryuseful.EventhoughyoudonotknowmuchaboutJavaatthispoint,youcanstillputwhatyouhavelearnedtoworktocreateapracticalprogram.Inthisproject,wewillcreateaprogramthatconvertsgallonstoliters.Theprogramwillworkbydeclaringtwodoublevariables.Onewillholdthenumberofthegallons,andthesecondwillholdthenumberoflitersaftertheconversion.Thereare3.7854litersinagallon.Thus,toconvertgallonstoliters,thegallonvalueismultipliedby3.7854.Theprogramdisplaysboththenumberofgallonsandtheequivalentnumberofliters.
1.CreateanewfilecalledGalToLit.java.
2.Enterthefollowingprogramintothefile:
3.Compiletheprogramusingthefollowingcommandline:
4.Runtheprogramusingthiscommand:
Youwillseethisoutput:
5.Asitstands,thisprogramconverts10gallonstoliters.However,bychangingthevalueassignedtogallons,youcanhavetheprogramconvertadifferentnumberofgallonsintoitsequivalentnumberofliters.
TwoControlStatements
Insideamethod,executionproceedsfromonestatementtothenext,toptobottom.However,itispossibletoalterthisflowthroughtheuseofthevariousprogramcontrolstatementssupportedbyJava.Althoughwewilllookcloselyatcontrolstatementslater,twoarebrieflyintroducedherebecausewewillbeusingthemtowritesampleprograms.
TheifStatement
-
4/18/2015 Chapter1:JavaFundamentalsJavaABeginner'sGuide,6thEdition
https://www.safaribooksonline.com/library/view/javaabeginners/9780071809252/ch01.html 14/19
YoucanselectivelyexecutepartofaprogramthroughtheuseofJavasconditionalstatement:theif.TheJavaifstatementworksmuchliketheIFstatementinanyotherlanguage.Itssimplestformisshownhere:
if(condition)statement
Here,conditionisaBooleanexpression.Ifconditionistrue,thenthestatementisexecuted.Ifconditionisfalse,thenthestatementisbypassed.Hereisanexample:
Inthiscase,since10islessthan11,theconditionalexpressionistrue,andprintln()willexecute.However,considerthefollowing:
Inthiscase,10isnotlessthan9.Thus,thecalltoprintln()willnottakeplace.
Javadefinesafullcomplementofrelationaloperatorsthatmaybeusedinaconditionalexpression.Theyareshownhere:
Operator Meaning
< Lessthan
Greaterthan
>= Greaterthanorequal
== Equalto
!= Notequal
Noticethatthetestforequalityisthedoubleequalsign.
Hereisaprogramthatillustratestheifstatement:
Theoutputgeneratedbythisprogramisshownhere:
Noticeoneotherthinginthisprogram.Theline
declaresthreevariables,a,b,andc,byuseofacommaseparatedlist.Asmentionedearlier,whenyouneedtwoormorevariablesofthesametype,theycanbedeclaredinonestatement.Justseparatethevariablenamesbycommas.
TheforLoop
Youcanrepeatedlyexecuteasequenceofcodebycreatingaloop.Java
-
4/18/2015 Chapter1:JavaFundamentalsJavaABeginner'sGuide,6thEdition
https://www.safaribooksonline.com/library/view/javaabeginners/9780071809252/ch01.html 15/19
suppliesapowerfulassortmentofloopconstructs.Theonewewilllookathereistheforloop.Thesimplestformoftheforloopisshownhere:
for(initializationconditioniteration)statement
Initsmostcommonform,theinitializationportionoftheloopsetsaloopcontrolvariabletoaninitialvalue.TheconditionisaBooleanexpressionthatteststheloopcontrolvariable.Iftheoutcomeofthattestistrue,theforloopcontinuestoiterate.Ifitisfalse,theloopterminates.Theiterationexpressiondetermineshowtheloopcontrolvariableischangedeachtimetheloopiterates.Hereisashortprogramthatillustratestheforloop:
Theoutputgeneratedbytheprogramisshownhere:
Inthisexample,countistheloopcontrolvariable.Itissettozerointheinitializationportionofthefor.Atthestartofeachiteration(includingthefirstone),theconditionaltestcount
-
4/18/2015 Chapter1:JavaFundamentalsJavaABeginner'sGuide,6thEdition
https://www.safaribooksonline.com/library/view/javaabeginners/9780071809252/ch01.html 16/19
Theoutputgeneratedbythisprogramisshownhere:
Inthiscase,thetargetoftheifstatementisablockofcodeandnotjustasinglestatement.Iftheconditioncontrollingtheifistrue(asitisinthiscase),thethreestatementsinsidetheblockwillbeexecuted.Trysettingitozeroandobservetheresult.Youwillseethattheentireblockisskipped.
AsktheExpert
Q:Doestheuseofacodeblockintroduceanyruntimeinefficiencies?Inotherwords,doesJavaactuallyexecutethe{and}?
A:No.Codeblocksdonotaddanyoverheadwhatsoever.Infact,becauseoftheirabilitytosimplifythecodingofcertainalgorithms,theirusegenerallyincreasesspeedandefficiency.Also,the{and}existonlyinyourprogramssourcecode.Javadoesnot,perse,executethe{or}.
Asyouwillseelaterinthisbook,blocksofcodehaveadditionalpropertiesanduses.However,themainreasonfortheirexistenceistocreatelogicallyinseparableunitsofcode.
SemicolonsandPositioning
InJava,thesemicolonisaseparatorthatisusedtoterminateastatement.Thatis,eachindividualstatementmustbeendedwithasemicolon.Itindicatestheendofonelogicalentity.
Asyouknow,ablockisasetoflogicallyconnectedstatementsthataresurroundedbyopeningandclosingbraces.Ablockisnotterminatedwithasemicolon.Sinceablockisagroupofstatements,withasemicolonaftereachstatement,itmakessensethatablockisnotterminatedbyasemicoloninstead,theendoftheblockisindicatedbytheclosingbrace.
Javadoesnotrecognizetheendofthelineasaterminator.Forthisreason,itdoesnotmatterwhereonalineyouputastatement.Forexample,
isthesameasthefollowing,toJava:
Furthermore,theindividualelementsofastatementcanalsobeputonseparatelines.Forexample,thefollowingisperfectlyacceptable:
Breakinglonglinesinthisfashionisoftenusedtomakeprogramsmorereadable.Itcanalsohelppreventexcessivelylonglinesfromwrapping.
IndentationPractices
Youmayhavenoticedinthepreviousexamplesthatcertainstatementswereindented.Javaisafreeformlanguage,meaningthatitdoesnotmatterwhereyouplacestatementsrelativetoeachotheronaline.However,overtheyears,acommonandacceptedindentationstylehasdevelopedthatallowsforveryreadableprograms.Thisbookfollowsthatstyle,anditisrecommendedthatyoudosoaswell.Usingthisstyle,youindentonelevelaftereachopeningbrace,andmovebackoutonelevelaftereachclosingbrace.Certainstatementsencouragesomeadditionalindentingthesewillbecoveredlater.
TryThis12
-
4/18/2015 Chapter1:JavaFundamentalsJavaABeginner'sGuide,6thEdition
https://www.safaribooksonline.com/library/view/javaabeginners/9780071809252/ch01.html 17/19
ImprovingtheGallonstoLitersConverter
Youcanusetheforloop,theifstatement,andcodeblockstocreateanimprovedversionofthegallonstolitersconverterthatyoudevelopedinthefirstproject.Thisnewversionwillprintatableofconversions,beginningwith1gallonandendingat100gallons.Afterevery10gallons,ablanklinewillbeoutput.Thisisaccomplishedthroughtheuseofavariablecalledcounterthatcountsthenumberoflinesthathavebeenoutput.Payspecialattentiontoitsuse.
1.CreateanewfilecalledGalToLitTable.java.
2.Enterthefollowingprogramintothefile:
3.Compiletheprogramusingthefollowingcommandline:
4.Runtheprogramusingthiscommand:
Hereisaportionoftheoutputthatyouwillsee:
TheJavaKeywords
FiftykeywordsarecurrentlydefinedintheJavalanguage(seeTable11).Thesekeywords,combinedwiththesyntaxoftheoperatorsandseparators,formthedefinitionoftheJavalanguage.Thesekeywordscannotbeusedasnamesforavariable,class,ormethod.
-
4/18/2015 Chapter1:JavaFundamentalsJavaABeginner'sGuide,6thEdition
https://www.safaribooksonline.com/library/view/javaabeginners/9780071809252/ch01.html 18/19
Table11TheJavaKeywords
Thekeywordsconstandgotoarereservedbutnotused.IntheearlydaysofJava,severalotherkeywordswerereservedforpossiblefutureuse.However,thecurrentspecificationforJavadefinesonlythekeywordsshowninTable11.
Inadditiontothekeywords,Javareservesthefollowing:true,false,andnull.ThesearevaluesdefinedbyJava.Youmaynotusethesewordsforthenamesofvariables,classes,andsoon.
IdentifiersinJava
InJavaanidentifierisanamegiventoamethod,avariable,oranyotheruserdefineditem.Identifierscanbefromonetoseveralcharacterslong.Variablenamesmaystartwithanyletterofthealphabet,anunderscore,oradollarsign.Nextmaybeeitheraletter,adigit,adollarsign,oranunderscore.Theunderscorecanbeusedtoenhancethereadabilityofavariablename,asinline_count.Uppercaseandlowercasearedifferentthatis,toJava,myvarandMyVarareseparatenames.Herearesomeexamplesofacceptableidentifiers:
Remember,youcantstartanidentifierwithadigit.Thus,12xisinvalid,forexample.
YoucannotuseanyoftheJavakeywordsasidentifiernames.Also,youshouldnotusethenameofanystandardmethod,suchasprintln,asanidentifier.Beyondthesetworestrictions,goodprogrammingpracticedictatesthatyouuseidentifiernamesthatreflectthemeaningorusageoftheitemsbeingnamed.
TheJavaClassLibraries
ThesampleprogramsshowninthischaptermakeuseoftwoofJavasbuiltinmethods:println()andprint().ThesemethodsareaccessedthroughSystem.out.SystemisaclasspredefinedbyJavathatisautomaticallyincludedinyourprograms.Inthelargerview,theJavaenvironmentreliesonseveralbuiltinclasslibrariesthatcontainmanybuiltinmethodsthatprovidesupportforsuchthingsasI/O,stringhandling,networking,andgraphics.Thestandardclassesalsoprovidesupportforagraphicaluserinterface(GUI).Thus,JavaasatotalityisacombinationoftheJavalanguageitself,plusitsstandardclasses.Asyouwillsee,theclasslibrariesprovidemuchofthefunctionalitythatcomeswithJava.Indeed,partofbecomingaJavaprogrammerislearningtousethestandardJavaclasses.Throughoutthisbook,variouselementsofthestandardlibraryclassesandmethodsaredescribed.However,theJavalibraryissomethingthatyouwillalsowanttoexploremoreonyourown.
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
-
4/18/2015 Chapter1:JavaFundamentalsJavaABeginner'sGuide,6thEdition
https://www.safaribooksonline.com/library/view/javaabeginners/9780071809252/ch01.html 19/19
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
formoftheforloop.
8 .Howdoyoucreateablockofcode?
9 .Themoonsgravityisabout17percentthatofearths.Write
aprogramthatcomputesyoureffectiveweightonthemoon.
10.AdaptTryThis12sothatitprintsaconversiontableofinchestometers.Display12feetofconversions,inchbyinch.Outputablanklineevery12inches.(Onemeterequalsapproximately39.37inches.)
11.Ifyoumakeatypingmistakewhenenteringyourprogram,whatsortoferrorwillresult?
12.Doesitmatterwhereonalineyouputastatement?