JavaProgramming:BeginningBeginners’
Guide
ByKeshavPatel
LearnToProgramMedia
Vernon,Connecticut
LearnToProgram.tv,Incorporated27HartfordTurnpikeSuite206Vernon,CT06066
contact@learntoprogram.tv
(860)840-7090
©2015byLearnToProgram.tv,Incorporated
Allrightsreserved.Nopartofthisdocumentmaybereproducedortransmittedinanyformorbyanymeans,electronic,mechanical,photocopying,recording,orotherwise,withoutpriorwrittenpermissionof
LearnToProgram.tv,Incorporated.
LimitofLiability/DisclaimerofWarranty:Whilethepublisherandauthorhaveusedtheirbesteffortsinpreparingthisbook,theymakenorepresentationsorwarrantieswithrespecttotheaccuracyorcompletenessofthe
contentsofthisbookandspecificallydisclaimanyimpliedwarrantiesofmerchantabilityorfitnessforaparticularpurpose.Nowarrantymaybecreatedorextendedbysalesrepresentativesorwrittensalesmaterials.Theadvice
andstrategiescontainedhereinmaynotbesuitableforyoursituation.Youshouldconsultwithaprofessionalwhereappropriate.Byfollowingtheinstructionscontainedherein,thereaderwillinglyassumesallrisksin
connectionwithsuchinstructions.Neitherthepublishernorauthorshallbeliableforanylossofprofitoranyothercommercialdamages,includingbutnotlimitedtospecial,incidental,consequential,exemplary,orother
damagesresultinginwholeorpart,fromthereaders’useof,orrelianceupon,thismaterial.
AbouttheBeginningBeginners’GuideSeries
ThisBeginningBeginner’sseriesofbookswasbornoutofafrustration:MostBeginningbooksonwebandmobile
developmentwerenotdesignedfortruebeginners.
Ofteninbeginners’booksthelanguagewasovercomplicatedandladenwithjargonthatonlythosewithprogramming
experienceunderstand.Thebooksassumetoomuchpriorknowledgeorexperience.Intheend,manypeoplenewto
programminggnashedtheirteethinfrustrationandgaveup.
Thefactisthatprogrammingiscompletelyapproachableandevenfuntolearniftaughtcorrectly.
That’sexactlywhattheBeginningBeginners’Guideseriesaimstodo:Helptruebeginnerslearntocode.
Thisseriesofprogrammingbooksisforyouifyou’veneverwrittenalineofcodebefore—orifyou’vetriedtolearn
fromotherbooksunsuccessfully.YouCANlearntocodewell.Youdon’thavetobemathematicallyoriented,oruber-
intelligent.
Learningtocodewon’talwaysbeeasy—butitisdoable.IfyoucanmanipulateanExcelspreadsheet,youcanlearn
programming.
Here’shopingthattheprocessforyouisasrewardingasitisforustoteach.
Shouldyouhavequestionsorcomments,pleaseemailmedirectlyatmark@learntoprogram.tv.
-MarkLassoff,FounderLearnToProgramMedia
Page4
TABLEOFCONTENTS
ABOUTTHEBEGINNINGBEGINNERS’GUIDESERIES………….4
CHAPTER1:WRITINGYOURFIRSTPROGRAM…………………….8
CHAPTER2:INPUTANDOUTPUT……………………………………… 22 CHAPTER3:VARIABLES…………………………………………………… 40 CHAPTER4:CONDITIONALSANDLOOPS………………………… 56 CHAPTER5:DEALINGWITHDATA…………………………………… 77
CHAPTER6:PUTTINGITALLTOGETHER………………………….103
ONLINECOURSESFROMLEARNTOPROGRAM…………………125
Chapter1:WritingYourFirstProgram
Welcome.Ifthisisyourfirsttimeprogramming,congratulations!You’reabouttostartan
adventurethatmostfindveryrewarding.Ifyouaretryingtolearnafteraprevious
abortiveattempt,youdeserverecognitionaswell.Tacklingprogrammingisn’talways
easy—butit’snotoutsidethegraspoftheaverageperson,either.
Overtheyears,I’vetaughtprogrammingtoover500,000peoplebothonlineandin
person.TheprogrammersI’vemetovertheyears—bothbeginnersandseasonedvets— havecomefromavarietyofbackgrounds.I’vefoundthatbothPhDsandhighschool
dropoutscanmakegoodprogrammers.I’vehadmathematicians,psychiatrists,and12
year-oldsinmyclassesovertheyearsandallhavebeenabletolearnsomeprogramming.
Youwilllearntoo.Inthisintroductorychapter—whichisspeciallydesignedforthe
slightlyapprehensivebeginner—Iamgoingtotakeyoustep-by-stepthroughtheprocess
ofwritingyourfirstprogram.Youdon’tneedanyspecialequipmentexceptalaptopor
desktopcomputer.
Sowithoutfurtherdelay,let’sgetstarted!
WhatYou’reGoingtoLearn
Thisfirstchapterwillserveasanintroductiononsettingupyourprogramming
environmentandgettingstarted.Eachchapterfollowingisdesignedtotakeyouthrough
thebasicsofacertainaspectofdevelopmentandgiveyouafoundationforgreater
learning.Justtogiveyousomecontext,here’swhat’scomingupintherestofthebook:
Chapter2:InputandOutput
Inputandoutputarekeytoanyprogram.Inthischapterwe’lllookathowtogetdatainto
andoutofaprogram.
Chapter3:UnderstandingVariables
Variablesarekeybuildingblocksinanyprogram.Thischaptertakesreadersthrough
declaringandutilizingvariablesinexpressions.Videotutorialincluded.
Chapter4:ConditionalsandLoops
ConditionalsandLoopsarestructureswhichallowprogramstomakedecisionsthatalter
theexecutionoftheprogramandresult.Thesewillbedemonstratedandexplainedinthis
chapter.
Chapter5:DealingwithData
Almosteveryusefulprogram,tosomeextent,dealswithdata.Inthischapteryou’lllearn
howtostorevariousformsofdatainaprogram.
Chapter6:PuttingitAllTogether
Inthisfinalchapter,readerswilllearnhowtocreateausefulprogramthatprocessesand
storesdata,usingtheskillsdevelopedinthepreviouschapters.
Beforewewriteanyprograms,wehavetogetyourdevelopmentenvironmentsetup.I won’tmakeyoubuyanythingandyou’llhaveafewoptionstochoosefrom.
Figure1.1:TheAuthor’sDevelopmentEnvironment.DoobieBrothers’musicnotincluded
SettingUpYourDevelopmentEnvironment
We’regoingtobeusingalanguagecalledJavainthisbook.InstallingJavaonyour
machineisrathersimpleandtheprocessisgenerallythesameformostmajoroperating
systems.Withyourbrowseryou’regoingtowanttonavigatetooracle.com.Oracleisthe
companythatmaintainsJava,andtheJDK(JavaDevelopmentKit)thatyouneedto
downloadtowritecodeinJava.
OnceatOracle.com,find“Downloads”onthetopmenubarandclickon“Javafor Developers”under“PopularDownloads”.
Figure1.2:Oracle.comwiththeDownloadsmenuopen.
Afterclickingthatlinkyouwillseeadownloadpage.Adialogboxwillappearthatreads JDK,withadownloadbuttonunderit.Whenyouclickit,itwillredirectyoutoapage whereyoucanselectyouroperatingsystem.Thewebsitewillprovideasetofinstructions
detailinghowtogoaboutinstallingtheJDKontoyourcomputer.Figure1.3:Theterminal
intheauthor’scomputer.Notethattheauthorchangedthedefaultcolorsthroughthe
terminal’spreferences
Intheeventthatyou’drathernotgothroughtheprocessofinstallingaJDKtoyour
machineIrecommendyouusethevirtualLinuxserverprovidedbymyfriendsat
Koding.com.Pointyourbrowsertowww.Koding.comandregisterfortheirfreeaccount.
ThefreeaccountgivesyouavirtualLinuxmachinethatyoucanaccessthroughyourweb
browser—anditcancompileandrunJavacoderightoutofthebox!Nodownloadsare
required.It’swhatIusedtowritethecodewe’llbeusinginthisbook.
Onceyouhaveyouraccount,clickthebuttontoturnonyourVirtualMachine(VM)and getcoding.You’llbeusingatexteditoronKodingtotypeJavafilesandtheterminalto runthem.
Figure1.4:CommandLine(orTerminal)inKoding.com.
WritingandRunningYourCode
Nowthatyouhaveyourenvironmentsetup,it’stimeto(finally)writesomecode.We’ll
writecodeinatexteditor.Atexteditorisdifferentthanawordprocessor.Aword
processorwillintroduceinvisibleformattingcodeintoafile.Ifyouweretoruncode
writteninawordprocessoritwouldlikelycauseanerrorduetotheembeddedformatting
code.
Atexteditor,ontheotherhand,savesthetextyouenteraspuretext—without introducinganyunnecessaryformatting.Thetextproducedbyatexteditorcanbeeasily processedbytheJavacompiler.Withinthecommandlineenvironmentsinthe Koding.comvirtualmachineandontheMactherearetwotexteditorsyoucanuse.They
areknownasnanoandvi.Thesetexteditorshaveaheritagethatgoesbacktothe1970s—
soasyouusethemyoucantrulyfeel“oldschool!”Theotheroptionistousethedefault
texteditoronKoding,TextEditonaMacorNotepadonWindows.They’reallratherself-
explanatory,althoughsomemayneedafewsettingschangedtohighlightJavacode.Asa
sidenote,makesurethatwheneveryoufirstsaveyourcodefiles,yousavethemas
“filename.java”.
nano
NanoisaneasytouseLinuxbasededitor.It’sprettyintuitive.Youcansimplystarttyping
yourcodewhenthenanoenvironmentloads.Nanohasanumberofcontrolcodeswhich
arelistedatthebottomofyourscreenforyourreference.Themostimportanttonoteare
CTRLOwhichsavesyourfileandCTRL-Xwhichexitsnanoandreturnsyoutothe
commandline.
Bydefault,nanowillsaveyourfileinthesamefolderyouwereinwhenyouopenednano
itself.
Figure1.5:Thenanotexteditor.
Youcanstartnanobytypingnanoandthenhitenteronthecommandline.
vi
viisaslightlymorecomplex(andevenmore“oldschool”)texteditor.Themost
importantthingtounderstandaboutviisthattherearetwomodes:commandmodeand
insertmode.Toenterinsertmode,press‘i’onyourkeyboard.Whenyouwanttomove
intocommandmodetoissuecommandslikewriteandquit,hittheESCkey.Ifyouscrew
upandfindyourselfinthewrongmode,pressESCalotandthatseemstogetyouback
intocommandmodefromwhereveryouareat.
There’sanoldjokeaboutvithatgoeslikethis:vihastwomodes,andyou’reinthewrong
one.(Ifyoudon’tthinkthat’sfunnyrightnow,youwillafteryouuseviforabit!)
Whenyouentervi,typeitomoveintoinsertmodeandyou’llbeabletotypeyourcode. Whenyou’redone,hitESCtomoveintocommandmode.Allcommandsmustbe precededbyacolon.Sotowriteyourfileyou’llenter:w.Toquityou’llenter:q.vialso letsyoucombinecommands.Forexample,thecombination:wqwillwriteyourfileand thenquitbacktothecommandline.
Figure1.6:viwantsyoutohelppoorchildreninUganda.Itofferslimitedhelpfornew
programmersworldwide.
Youcanstartvibytypingviandthenhittingreturnonthecommandline.
Sonowyoushouldhaveyourtexteditorstartedandbereadytoenteryourcode.Enterthe
followingcodeintoyourtexteditorexactlyasitappears:
publicclassHelloWorld{
publicstaticvoidmain(String[]args){
System.out.println(“Thisismyfirstprogram!”);System.out.println(“Programmersarerockstars!”);}
}
Itshouldbeatleastsomewhatevidentwhatthiscodedoes.Theprintln()functionprints
contenttothecommandline.Inthiscaseyouareprintingtwostrings.Stringsaresimply
linesofcharacters.Stringsarealwaysenclosedinquotes.
Onceyou’vetypedthecode,it’stimetorunit.Innano,saveyourfilebytypingCTRL-W.
Whenprompted,enterthefilename
HelloWorld.java.The“.java”extensionindicatesthatthisisaJavasourcecodefile.Next
enterCTRLXtoquitandyou’llreturntothecommandline.Invi,entercommandmode
andthensaveyourfilebytyping:wHelloWorld.java.Thiswritesyourfileunderthe
appropriatefilename.Finally,invi,hit:qtoquitandreturntothecommandline.Inany
othereditor,includingtheoneonKoding,generallyyoucanopenamenuandclick‘save
as’justlikeyouwouldinanyothercomputerprogram.
Noticethatthefilenamewegavethisprogrammatchesthenameoftheclass (HelloWorld).ThisistheJavastandard.Thisstandardmakesclassfileseasilyidentifiable inbuildwhenyouhavemultiplesourcefiles.Soforhousekeepingpurposes,whenever youmakeanew‘.java’filemakesurethatthenameoftheclassinthecode(whichis writtenafter‘publicclass’inthefirstlineofthecode.)matchesthenameofthefile.This wayanyonereadingyourcodewillknowwhich‘.class’fileisassociatedwithwhat‘.java’ file.
Figure1.7:SavingyourfileinKoding.
Nowthatyouhavetypedyourcodeintoaneditor,openyourterminal,andyourcursor
shouldappearattheprompt.Runtheprogrambyenteringthefollowingattheprompt
(don’ttypethe‘$’—thatjustrepresentsthepromptitself):
$javacHelloWorld.java$javaHelloWorld
ThefirstlineherecommandsJavatocompilethesourcecodethatyouwroteintowhat’s
knownasJavabytecodeandwriteittoa‘.class’file.Thisbytecodeisexecutedbythe
JavaVirtualMachine(orJVM)wheneveryourunyourprogram.JVMscanbeinstalledon
numerousdevices,fromcellphonestosupercomputers,andtheyalldothesamething:run
Javacode.TheresultofthisisJava’sabilitytorunonmultipleplatforms.Solongasa
JVMisinstalledonamachine,itcanrunthecompiledJavacodethatyouwrite.
ThesecondlineinstructsJavatoactuallyrunwhat’sinthe‘.class’file.Notethatthe‘.class’
isimplied.Youdon’thavetotypeitwhenyourunyourcode.Ifyouopenthefolderwhere
thefileissaved,youwillseeitasa‘.class’filethough.
Ifyou’vedoneeverythingcorrectlyyoushouldseetheresultofyourprogramprinted
beforethenextprompt.
Figure1.8:ExecutionoftheHelloWorld.javaprogram
Ifyouroutputdoesn’tlooksimilartofigure1.9,youneedtoloadyourtexteditorandcode
againandfindyourerror.Youcanreloadyourcodeatthecommandlinepromptwiththe
followingcommand:
vi:viHelloWorld.java
nano:nanoHelloWorld.java
Inanyothereditor,openthefileasyouwouldanyother.
Somecommonerrorsinclude:
-Notclosingbrackets
-Forgettingsemicolonsattheendoflines
-Mistyping“publicstaticvoidmain(String[]args)”(It’scasesensitive!)
Congratulations!Youhavesuccessfullywrittenyourfirstprogram.
Understandingtheprintln()function
Intheprecedingexampleweusedtheprintlnfunctiontooutputastring.Theprint
functionisalsocapableofprintingoutthefollowingtypesofdata:
Integers:Integersare“wholenumbers”anddon’thaveadecimalpoint.InJava,youcan
printanintegerlikethis:
System.out.println(2573);
FloatingPointNumbers:Floatsaremoreprecisenumbersthatincludeadecimalpoint.In
Javayoucanprintafloatingpointnumberlikethis:
System.out.println(3.45783);
Expressions:Expressionsmustbeevaluatedbeforearesultisdetermined.Expressionsare
usuallyarithmeticproblems.ToprintanexpressioninJava:
System.out.println(3.0/(6+4));
Intheexpressionabove,thepartoftheexpressioninparenthesiswillbeevaluatedfirst
duetotheorderofoperations.Theresultprintedis0.3.
We’lllookatexpressionsmorecloselyinournextchapter.
Asasidenote,it’sgoodtounderstandthattheprintlnfunctionisaversionofthe
print()function.The‘ln’attheendstandsforline.Thismeansafterprintingwhatyou
placeintheparenthesesthefunctionwillmakeanewlinetoprintthenextexpression.The
‘print’functionwillsimplyprintwhateveryouputintheparenthesiswithoutintroducing
itsownformatting.
Chapter2:InputandOutput
Inthischapterwe’regoingtolookmorecloselyatinputandoutput,whichareperhapsthe
twomostcriticalactivitiesinanyprogram.Inthepreviouschapterwelookedcloselyat
theoutputweproducedwiththeprintlncommand.Withprintlnwewereabletooutput
threetypesofdatatothecommandlinescreen:strings,integers,andfloatingpoint
numbers.Theprogramswewrote,however,hadnocapacitytotakeinputandprocess
data.
Inthischapterwe’regoingtolookcloselyattwotypesofinput.Firstinputstatementswill
allowustoprogrammaticallyrequestinputfromtheuser.We’llthenusecommandline
parameterstoprovideinputstoourprogram.
Aswelookatoutput,we’llalsolookatdirectingouroutputtoafileinsteadofbacktothe
commandline.
Sonowit’stimetoputonyourfavoriteprogrammingmusic(IsuggestTheCure),open
nano,vioryourfavoritetexteditorandstartcoding…
InputStatements
We’regoingtostartwithaprogramthatcalculatestheareaofarectanglebasedona
sideAinputandasideBinput.KeythefollowingJavacodeintoyourtexteditor:
importjava.util.Scanner;
publicclassSquare{
publicstaticvoidmain(String[]args){
System.out.println(“RECTANGLEAREACALCULATOR”);
Scannerinput=newScanner(System.in);
System.out.println(“What’sthelengthofsideA?“);floatsideA=input.nextFloat();
System.out.println(“What’sthelengthofsideB?“);floatsideB=input.nextFloat();
floatarea=sideA*sideB;
System.out.println(“Theareaofyourrectangleis:“+area); Onceyouaresureyouhavekeyedintheprogramcorrectlyandsavedit,goaheadandrun theprogramonthecommandline.IsavedmineasSquare.java.Youroutputshouldlook
similartofigure2.1:
Figure2.1:ExecutionoftheSquare.javaprogramwhichtakesinputfromtheuserviathe
Java.nextFloat()function.
Onthefirstlineofthisprogram,weencountertheimportstatement.Importsareusedin
manylanguagestoaddanadditionallibraryofcommandstothelanguagethatarenotin
thelanguagecore.Inthiscase,we’readdingtheScannerobjectfromtheutillibrary
whichcontainsanumberofutilitiesandusefulobjects.
Ifyouwanttoimporttheentirelibrary,allyouhavetodoisreplaceScannerwithan
asterisk(*).
Forexample:
importjava.util.*;
Whilethisisuseful,understandthatinmuchlargerprogramsimportinganentire
libraryjusttogetoneobjectlikewe’redoingheremakesyourprogramlessefficient.It’s
likegrabbingyourwholetoolboxwhenyoujustneedahammer.
Now,basedoncontextandtheprogramexecution,you’veprobablyalreadyguessedwhat
thenextInt()functiondoes.Let’sbreakitdown:
publicstaticvoidmain(String[]args){
ScannergrabAge=newScanner(System.in);
System.out.println(“Howoldareyou?”);
intage=grabAge.nextInt();
}
ThefirstlineofthisclasscreatesaScannerobject.Scannersaretheobjectweuseto
obtaininputfromthecommandline.
Intheexampleabove,whatevertheusertypesattheprompt“Howoldareyou?”isgoing
tobeassignedtothevariableageviatheScanner’snextIntmethod.We’regoingtotakea
closerlookatvariablesinthenextchapter—forrightnow,justconsidervariablesa
temporarystorageplaceforvalues.Thesevaluescanbestrings,floats,orintegers.You
mustdeclarevariablesbeforeusingthem.Generallythesyntaxisthedatatypefollowedby
anametoreferencethevariable.
Youmaybewonderingwhatadatatypeis.Datatypedetermineswhatavariablecan
contain,andwhatoperationscanbeperformedonit.Someexamplesofdatatypesinclude
integers,strings,andfloatingpointnumbers.
Here’sanexampleofthedeclarationofanintegervariable:
intname;
Note:Intindicatesthatthedatatypeforthisvariableisaninteger.
RemembertoimporttheScannerobjectortheutillibrarybeforedeclaringaScanner
object.Otherwise,yourprogramwillencounteranerror.
Let’stryanewexample.CreateanewfileinyourtexteditorcalledStringInput.java.You
candothisinvi,forexample,bytypingthefollowingcommandonthecommandline:vi
StringInput.java.
Keyinthefollowingcode:
importjava.util.Scanner;
publicclassStringInput{
publicstaticvoidmain(String[]args){
Scannerinput=newScanner(System.in);System.out.println(“What’syourname?“);
Stringname=input.nextFloat();
System.out.println(“Hello“+name);}
}
Exityourtexteditorandcompiletheprogramfromyourcommandlinewiththecommand
javacStringInput.java.
Figure2.2:Uhoh.Thiscan’tbegood.We’vemadeanerror.Howdowefixit?
Sowhathappened?Insteadofcompilingandallowingthecodetorun,theprogramexited withanerror.Luckilytheerroriseasytofix.ThenextFloat()functionisdesignedto acceptthefloatdatatypeandonlythatdatatype.Whenyouenteranythingthatisn’ta
floatingpointnumber,itcausestheerroryouseeinfigure2.2.Wehaveadifferent
functionthatisintendedforstringuse,callednextLine().
Edityourcodeasfollows:
importjava.util.Scanner;publicclassStringInput{
publicstaticvoidmain(String[]args){
Scannerinput=newScanner(System.in);System.out.println(“What’syourname?“);
Stringname=input.nextLine();
System.out.println(“Hello“+name);}
}
Note:Thescannerhasafunctiontoobtaineverykindofdatatype.
Herearesomeexamples:
nextLine():Strings
nextInt():Integers
nextFloat():FloatingpointnumbersnextDouble():Doubles
Youcanprobablyrecognizethepattern.Thedocumentationofthemethodsforthe
Scannerobjectisavailablehere:
http://docs.oracle.com/Javase/7/docs/api/Java/util/Scanner.html
LearninghowtoreadtheJavadocumentationisanimportantskillitself.
Figure2.3:
SomuchbetterwithnextLine()!
Whenyou’reworkingwithstrings,youshouldusethenextLine()functionwhichdoesnot
scanforadatatypeotherthanStrings.It’llalwaysreturnwhatevertheuserenterintothe
promptasastring,includingnumbersorsymbols.
Errors
Theprecedingexamplewasprobablyoneofthefirstexamplesofanerrorthatyou’ve
encountered.ThistypeoferrorisknownasaRuntimeerror.It’soneofthreetypesof
errorsthatcanoccurwhenwritingJavacode.
Thesethreetypesare:
Syntaxerrors:
Syntaxerrorsareissueswiththeformattingofyourcode.Examplesincludeforgetting
semicolons,notclosingyourbracketsormisspellingmethodnames.Texteditorsgenerally
doagreatjobofpointingtheseout,sofixingthemisrathersimple.
Runtimeerrors:
Runtimeerrorsareabittrickiertocatch.Syntactically,allruntimeerrorsarecorrect,so
yourtexteditorwon’tpointthemouttoyou.Theissueoccurswhensomething
unexpectedhappensandresultsintheprogramfailingtoexecuteatruntime.Theresultis
yourprogramfailstocompileorexecuteproperly.Examplesincludetryingtodivideby
zeroortryingtocallupafilethatdoesn’texist.Javawon’tencountertheerroruntilit
attemptstoexecutethecode.
Logicerrors:
Theseareerrorsintheactuallogicbehindtheprogram.Theyarethemostchallenging
errorstofix,becausethecodeisn’ttechnicallywrong,it’sjustnotgivingthecorrect
result.Somelogicalerrorsgoundetectedevenaftertheprogramisreleased.Examples
includethingslikedividingwhereyoushouldbemultiplying,printingthewrongoutput,
oropeningthewrongfile.Ifyouhavealogicerror,you’rehavingaPICNIC.(ProblemIn
Chair,NotInComputer.)
ParameterizedInput
Yourcurrentworkflowforcesyoutocompileandthenrunyourcodebeforepassinginput.
IncludingparameterswithyourJavacommandpassesinputandexecutesyourcodein
tandem.Theresultingcommandlookslikethis:
$javaClassNamearg1arg2arg3
Intheexampleabove,westillusetheJavacommandandtheclassnameoftheprogram
we’dliketorun.Wefollowtheclassnamewithargumentswhichgetsentasinputtothe
program.Thiscouldbeadvantageousinsituationswherewewantourprogramtorun
unattendedlikewhenwe’recrunchingnumbers.Forexample,ifwewantedaprogramto
receivetheusersnameandageasinput,theparametersmightlooksomethinglikethis:
$javamoreInputKeshav17Thevalues“Keshav”and“17”,whichareseparatedbya
singlespace,arepassedtotheprogram.Let’sseehow.Keyinthefollowingexampleand
saveitasMoreInput.java:
publicclassMoreInput{
publicstaticvoidmain(String[]args){
System.out.println(“Yournameis:“+args[0]);System.out.println(“Yourageis:“+
args[1]);
System.out.println(“Allthearguments:“);
System.out.println(args[0]+“,“+args[1]);}
}
Next,let’sruntheprogramandsupplycommandlineargumentsasinput:
$javaMoreInputKeshav17Youshouldgetaresultsimilartotheonepicturedinfigure
2.4:
Figure2.4:CommandlineparametersbeingprocessedasinputontheKodingcommand
line.
NOTE:Thetermsparameterandargumentcanbeusedinterchangeably.
TheargumentscomeintoJavanumberedsequentially,soinourcase,theuser’snameis
argumentnumberzeroandtheageisargumentnumberone.Incode,wecalltheseargs[0]
andargs[1],respectively.Ifyoustudythescreenshotcarefully,youmaynoticesomething
interesting-args[1]isnotthefirstparameter.
ThisisbecauseJavastartscountingat0,ratherthan1.Thismeansthatthefirstargument
weentered,whichinthiscasewasaname,isactuallyinslot0.AsaresultJavaisoften
referredtoasazero-indexedlanguage.
OutputtoaFilestream
Sofarthecode’soutputhasonlybeendirectedtothecommandline.Thisdoesn’talways
havetobethecase.Outputcanbedirectedtoafileformorepermanentstorage.Being
abletostoredata(moreorless)permanentlyisanimportantskillforprogrammersto
learn.Let’swriteaprograminwhichweasktheusertoenterseveralpiecesofdataand
wethenstorethoseinafile.
Keyinthefollowingcode:
importjava.io.*;
importjava.util.Scanner;publicclassStorage{
publicstaticvoidmain(String[]args){
Scannergrab=newScanner(System.in);
System.out.println(“What’syourname?”);Stringname=grab.nextLine();
System.out.println(“What’syouremail?”);Stringmail=grab.nextLine();
System.out.println(“What’syourfavoriteband?”);
Stringband=grab.nextLine();
Stringfname=name.replaceAll(”“,””)+“.txt”;
try{PrintWritersaver=newPrintWriter(fname);
saver.println(“Name:”+name);saver.println(“Email:”+mail);saver.println(“Band:”+band);saver.close();
}
catch(FileNotFoundExceptione){System.out.println(“Ohno,itdidn’twork!”);
}System.out.println(name+“|”+mail+“|”+band+”hasbeenstoredto“+name+“.txt.”);}
}
Thisisdefinitelythemostcomplexprogramwe’vewrittenyet.Goaheadandrunitonthe
commandlineandmakesureyoudon’tgetanyerrors.Ifyou’rehavingissuesrememberto
checktheimports.Ifeverythingrunscorrectly,yourcommandlineshouldlooksomething
likethis:
Figure2.5:TheprogramstoredthedatainafilecalledKeshav.txtwhichisnowavailable
inthedirectorylistingbyusingthelscommandonthecommandline.
Note:Iwroteandsavedthefileinaseparatefolder,andneededtonavigatetowherethe
filewasbeforehandusingthecd(changedirectory)command.
Whilethecodeforthisprogramissomewhatlongerthanwhatyouareusedtoatthis
point,itisstillfairlystraightforward.Whentheprogramrunsitpromptstheuserfortheir
name,email,andnameoftheirfavoriteband.Wethencreateanewvariablecalledsaver.
Savertakestheinformationtheusertypedandformatsittoincreasereadability.Itthen
printstheinformationtoafile.
TheobjectsweusetoprinttoafilearelocatedintheJava.iolibraryandwe’regoingto
needacoupleofobjects,soimportthewholething.
Thefnamevariable,whichstoresthefilenameforthefilewe’recreating,ispopulated
bythevariablethatholdstheuser’sfirstname.WhenwecreatethenewPrintWriterobject,
wepassinthefilename.ThisisrequiredsothePrintWriterknowswhattonamethefileit
creates.
Thenextpartoftheprogramiswheretheactionhappens:
publicstaticvoidmain(String[]args){
try{PrintWritersaver=newPrintWriter(fname);
saver.println(“Name:”+name);
saver.println(“Email:”+mail);
saver.println(“Band:”+band);
saver.close();
}
catch(FileNotFoundExceptione){
System.out.println(“Ohno,itdidn’twork!”);
}
System.out.println(name+“|”+mail+“|”+band+”hasbeenstoredto“+name+
“.txt.”);
}
}
ThefirstthingwedointheprogramiscreateaPrintWriter.Thisisanobjectthatallows
ustocreateandthenprinttorawtext(.txt)files.Wenameditsaverandpassinthestring
fnameasaparameter.Whenthewritercreatedourfile,thisstringbecamethefile’sname.
NextweuseourPrintWriterobjectandbeganprintingstringstothetextfile.Finallywe
closedtheobjectandprintedtotheconsolethatwehavecreatedafilewiththe
informationthattheuserprovideduswith.
Notethatthisentireprocessisdonewithinatry-catchstatement.Atrycatchstatementis
usedtohandleexceptions,whichareeventsthatinterferewiththeexecutionofyour
program.Inthetryblockweputcodethatcouldpossiblycause(AKAthrow)an
exception.Inthecatchblock,weputcodethatexecutesifanexceptionisthrown.The
parenthesescontainthetypeofexceptionandthenamewegiveit.Inthiscasewejustprint
“Ohno,itdidn’twork!”intheeventthatwegetanexception.
Figure2.6Weopened“Keshav.txt”inthetexteditorandyoucanseethedatathathas
beenwrittentothedisk.
Congratulations!You’vewrittenaprogramthatstoresdatapermanently.Youarewellon
yourwaytobeingaprogrammer!
Chapter3:Variables
Inthepreviouschapter,welookedatinputandoutput,whichallowustogetdataintoand
outofourJavaprogram.Inthischapterwe’lltakeacloserlookatoneofthemost
importantaspectsofprogramming—variables.Youmaynotequatevariableswith
computerprogramming,butyou’velikelybeenusingvariablessincehighschoolifyou
tookcoursesinAlgebra,Chemistry,andPhysics.Inclassic“solveforx”problems,xisa
variable.
Let’sfirsttakealookathowtheJavaprogrammingenvironmenthandlesvariables.
DeclaringandInitializingVariables
Javaiswhatisknownasastrongly-typedlanguage.Thismeansthatvariablesneedtobe
declaredbeforetheycanbeused.InJava,variablesaredifferentiatedbythetypeofdata
theyhold.Thetypeofdataisreferredtothevariable’sdatatype.
TherearetwotypesofvariablesinJava:primitivetypeandclass(alsocalledreference)
type.
PrimitiveVariables
InJava,thereareeightprimitivedatatypes.Theyarethebyte,short,int,long,float,
double,booleanandchars.
Thedeclarationandinitializationstatementsaregenerallyveryshort,andreservea
specificamountofmemorydependingonwhattypethevariableis.Here’sanexampleof
adeclarationandinitializationforaninteger,doneinoneline:
intname=93;
ClassVariables
Classtypevariables,alsocalledreferencetypevariables,aregenerallymorecomplexthan
primitivetypes.Inmostcasesprimitivetypesarethebuildingblocksofclasstype
variables.Whenyoudeclareandinitializeaclasstypevariable,thenamedoesn’t
representtheobjectitself,ratheritpointstothememorylocationthathasalloftheparts
andinformationthatmakeuptheobject.
Therearehundredsofdifferentclasstypevariablesoutthere,andtheyalldodifferent
things.Oneyou’vealreadyencounteredisaScanner.
Here’sthedeclarationandinitialization,onemoretime:
Scannername=newScanner(<parameters>);
Strings
StringsinJavaareactuallyclassorreferencetypevariables.Theycan,however,be
declaredlikeprimitives.ThiswasasortofshortcutputinbytheJavadeveloperstomake
dealingwithstringsabiteasier,asthey’reoneofthemostcommondatatypesandareused
justasmuchastheprimitives.(Thinkabouthowmuchyou’veusedthemalready!)
Ifyoulike,youcandeclarestringslikeyouwouldclasstypevariables,butthere’sreally
noadvantageindoingso.
Itwouldlooklikethis:
StringblogName=newString(“Edukwest!”);
NOTE:Duetostringsbeingclasstype,theycannotbecomparedlikeprimitivetypes
usingthegeneralcomparisonoperatorslike<,>or==.
Here,we’vecreatedavariablecalledblogNameandinitializeditwiththestringvalue
“Edukwest!”Theequalssigninthiscontextistheassignmentoperator.Thestringvalue
“Edukwest!”isbeingassignedtothevariableblogName.
Onceavariablehasbeendeclared,generallyyoucandoquitealotwithit.Here’san
exampleofusingvariablestochangewhatisprintedinasentence.
Keyinthefollowingcode.(Feelfreetosubstituteyourownvaluesforthevariables.)
Noticethatcommentsareindicatedbytwoslashes(//).Multi-linecommentscanbemade
withaslashandanasteriskandclosedwithanasteriskandaslash.(/*comment!*/)
publicclassVariables{
publicstaticvoidmain(String[]args){
floatgpa=3.95f;intage=17;
Stringname=“Keshav”;
//Notethatthefirstwordofthevariabledeclarationisthetype.
System.out.println(name+”is“+age+”andwishedhehada“+gpa+”gpa.”);
}
}
SaveyourfileasVariables.javaandrunitwiththeJavacommand.Youroutputshould
appearsimilartofigure3.1
Figure3.1:Variables.javaexecutingintheKoding.comvirtualLinuxenvironment.
Thefirstwordinthedeclarationisthetypeofvariablebeingcreated.Toreview,thetypes
ofvariablesinthisprogramare:
String:Stringvariablesarecomprisedofaseriesofcharactersinaparticularorderthat
havenomathematicalvalue.
Integer:Integervariablescontainwholenumbervalueswithnodecimalpoint.
FloatingPointValues:Floatingpointvariablescontainmoreprecisenumbersthathavea
wholenumberandfractionalamountrepresentedbyadecimalpointvalue.
Variablesaredynamic,inthatthevaluecanbechangedorreassignedthroughthelifeof
theprogram.Imagine,forexample,thatinavideogameyouhaveavariablethattracks
theplayer’sscore.Astheplayer’sscorechanges,thatvaluewouldgoupuntilthegameis
over.Oncethegameends,thevalueinsidetheplayer’sscorevariablemightbereassigned
thevaluezero.
Considerthefollowingcode:
importjava.util.*;publicclassVar2{
publicstaticvoidmain(String[]args){Scannernames=newScanner(System.in);
StringfirstName,lastName,middleName,fullName;
System.out.println(“What’syourfirstname?”);
firstName=names.nextLine();
System.out.println(“What’syourlastname?”);
lastName=names.nextLine();
fullName=firstName+”“+lastName;
System.out.println(fullName);
System.out.println(“What’syourmiddlename?”);
middleName=names.nextLine();
fullName=firstName+”“+middleName+”“+lastName;
System.out.println(fullName);
}
}
Enteringthecodeandrunningtheprogramyieldsthefollowingresult:
Figure3.2:DuringthelifetimeofthefullNamevariable,thevalueisreassigned
NotethatwhenwefirstdeclarethefullNamevariable,itisassignedthevaluesoffirst
andlastconcatenatedbythe+sign.Thatvalueisthenprintedtotheconsole.Asthe
programcontinuestoexecute,thevalueoffullNameisreassignedtoincludethevariable
middleaswell.Whenavariableisassignedanewvalue,itsoriginalvalueisclearedand
replacedwiththenewvalue.
Inthisprogram,wealsodeclaredfourStringsinoneline.Duetoallthevariablesbeingof
theStringtype,wewereabletoseparatethefourstring’snameswithcommas,andassign
themvalueslateron.Beingastaticallytypedlanguage,Javarequiresustodeclareour
variablesbeforeuse.Beingastaticallytypedlanguagedoesn’tnecessarilymeanwehave
toassigninitialvalues(orinitialize)thevariablesupondeclaration.Youcandothiswith
alltypesofvariables.
ArithmeticwithVariables
VariablesarefrequentlyusedaspartofarithmeticexpressionsinJava.ArithmeticinJava
isnodifferentthanthearithmeticyoulearnedingradeschool.Thefollowingsymbolsare
used:
+Addition
-Subtraction
*Multiplication
/Division
%Modulus
Ifyouarenewtoprogramming,modulusmaybeunfamiliartoyou,buttheconceptis
easy—modulusistheremainderafterdivision.Forexample:
10%3=1
11%3=212%3=0
Ifrequentlyusemoduluswhenprogramminginordertodetermineifanumberisevenor
odd.Anyevennumberusedwithmodulustwowillresultinzero.
TalktheTalk:Mostprogrammerswillsay‘mod’forshortwhentheyaretalkingabout
modulus.
Mathwithvariableslooksprettymuchasyou’dexpect.Thereareafewodditiesthatwe’ll
coverlaterthough.
Keyinthefollowingexampleprogram.You’refreetoforgocopyingthecomments:
publicclassMathDemo{ publicstaticvoidmain(String[]args){
intalpha=3;intbravo=13;
System.out.println(alpha+bravo);System.out.println(alphabravo);System.out.println(bravo*alpha);
System.out.println(bravo/alpha);//Note:
13/3isnotreallyawholenumber.
System.out.println(bravo%alpha);
System.out.println((double)bravo/(double)alpha);
/*Becausewe’vecastedthenumbersasdoubles,therealvalueisdisplayed.*/
}
}
Inthisprogram,twovariablesaredeclaredasalphaandbravo.Thentheoperandsareput
infiveexpressionsusingaddition,subtraction,multiplication,divisionandmodulus.
Bothofthesenumbers,however,areintegers.Integerscanonlybewholenumbers
between(2^31)-1or-2^31.Soexpressionsoftheintegerdatatypehaveanynumbersafter
thedecimalpointtruncated.
Thismeansthatifanexpressionresultsin3.9,butisprintedasanint,it’llsimplyprint3.
Wecanavoidthisissuebydoingwhat’sknownastypecasting.Thischangesthe
variable’stypejustbeforedoingthemathandprinting,meaningwe’llgettherealanswer
ratherthananapproximation.
Javarequiresyoutoidentifythetypesofyourvariables.Whenusing
variablesofdifferenttypestogether,youmayhavetoexplicitlystatewhat
typeofvariableyouwanttheanswertobe.Asaruleofthumb:small
variablestypesautomaticallytransferup,butlargevariablesmust
manuallybecasteddown.
Thisisthehierarchy:
byte<short<int<long<float<double
Usinganintwithafloatrequiresnotypecasting.Gettingananswerasan
intwithafloatandintDOESrequireyoutoexplicitlycastyourvariable.
Afinalprintstatementusesthemodulusstatementinanexpression.Whenyourunthe
programwiththeJavacommand,theresultshouldappearsimilartothis:
Figure3.3:Javaprogramevaluatingseveralmathematicalexpressionsandoutputtingthe
resulttotheconsole.
Whenworkingwitharithmeticinprogramming,it’simportanttokeepinmindtheorderof
operations.Javawillalwaysfollowtheorderofoperationswhendoingmath.Asaresult
it’sagoodideatomakesurethatanyexpressionsyouformulatetakeintoaccountthe
orderofoperationstopreventlogicerrors.
Figure3.4:DifferentexpressionsareevaluatedinaJavaprogramdemonstratingtheorder
ofoperations.
Wastheresultalwayswhatyouexpected?Theorderofoperationsdetermineswhatpartof
amathematicalexpressionisevaluatedfirst.Expressionsareevaluatedfromlefttoright
generally,butthespecificorderofoperationsis:
1)Parenthesis2)Exponents
3)Multiplication4)Division
5)Addition
6)Subtraction
NOTE:Despitemultiplicationcomingbeforedivisionandadditioncomingbefore
subtraction,Javatreatsthemasthoughtheyareonthesamelevelandevaluatesthemleft
toright.
Acommonerrormadebynewprogrammersistoincorrectlyinterprettheorderof
operationswithinamath-relatedproblem.Whenthishappens,aprogramwillstillrun,but
oftengiveanincorrectresult.
TherearemanymoreadvancedmathematicstoolsavailableinJavawithintheMathclass.
Utilizingthisclasswillallowyoutoroundnumbers,useexponents,squareroots,and
muchmore.Thedocumentationisavailablehere:
http://docs.oracle.com/Javase/7/docs/api/Java/lang/Math.html
WorkingwithStrings
Manipulatingstringsisacommontaskforprogrammers.Imagine,forexample,you’re
givenalistofdatawherefirstandlastnamesarecombinedintoasinglefield.Using
stringmanipulationtechniques,you’dhavetoseparatethemintoseparatefieldsby
extractingdatafromthestring.
Java’sStringMethodswillallowyoutomanipulatestringsineverywayimaginable.
YoucanseethedocumentationontheStringMethodshere:
http://docs.oracle.com/Javase/7/docs/api/Java/lang/String.html
Let’sworkwithafewStringMethods.Copythefollowingprogram.Thisprogram
demonstratesjustafewofthestringfunctions.Youdon’thavetotypetheembedded
commentsifyoudon’twantto.Theyarejustforyourreference.
publicclassStrings{
publicstaticvoidmain(String[]args){
Stringphrase=“Thequickbrownfoxjumpedoverthelazydogs.”;
//PrintsthenumberofcharactersintheStringSystem.out.println(phrase.length());
//Findstheindexofthewordfox.
System.out.println(phrase.indexOf(“fox”));
//Replacejumpedwithanewword.
System.out.println(phrase.replace(“jumped”,“hopped”));
//Changescase
System.out.println(phrase.toUpperCase());System.out.println(phrase.toLowerCase());
}}
Onceyouruntheprogram,youshouldseearesultsimilarfigure3.5:
Figure3.5:StringmanipulationresultinJava
Asyoucansee,Java’sstringmanipulationfeaturesarepowerful.
Chapter4:ConditionalsandLoops
Inthelastchapterwetookacloselookatvariables.Inthischapter,we’regoingtouse
variablesagain.First,we’llusevariablestomakedecisionsandexecutebranchingwithin
ourprogram.Thenwe’llusevariablestocreateloopsthatiteratethroughaportionofcode
anumberoftimes.Conditionalsandloops,thetwoconceptsthatwehaven’tcoveredupto
now,arefoundinjustabouteveryprogramminglanguage.Sofar,theprogramswe’ve
writtenareallserial—theygothroughthesamestepsinthesameordereachtime.With
theadditionofconditionalsandloopstoourprogrammingrepertoire,yourprogramswill
beabletovarytheirpathbasedonconditionsyouset.Soundslikefun,right?
SimpleConditionals
Let’sstartbywritingsomecode.Fireupyourdevelopmentenvironmentandenterthe
followingcode(Makesurethefileandclassnamesmatch):
importjava.util.*;
publicclassDrink{ publicstaticvoidmain(String[]args){ ScannerageGetter=newScanner(System.in); System.out.println(“Howoldareyou?”); intage=ageGetter.nextInt();
if(age>=21){
System.out.println(“Youcanlegallydrink!”);}
}
}
Onceyou’veenteredtheprograminyourtexteditor,runitthreeseparatetimes.Thefirst
time,enteranageolderthan21.Thenexttimeyourunit,enteranageyoungerthan21.
Whenyourunitonefinaltime,enter21exactly.Tomakesuretheprogramrunscorrectly
wewanttotestallthepossiblescenariosforexecution.
Youroutputshouldappearsimilartofigure4.1:
Figure4.1:Programbeingtestedforthreedifferenttypesofuserresponses
Thisprogramisprettystraightforward.What’snewistheifstatement.Inthiscasewe’re
determiningifthevaluetheuserenteredisgreaterthanorequalto21.Theportionofthe
ifstatementwrittenlikethis:age>=21isknownasthecondition.Everyconditional
statementhasaconditionthatisevaluatedtobetrueorfalse.Ifit’strue,thecodeindented
underneathandinbracketstheconditionalstatementisexecuted.Ifit’sfalsegenerallyit’s
skipped.
Noteintheexampleshowninfigure4.1,theprogramresponds“Youarelegallyableto
drink”onlyiftheuserentersavalue21orgreater.Javausesbracketstocontainblocksof
code,soafteryouopenthebracketmakesureyoucloseitbackuporelseyourprogram
won’tcompileproperly.Makesurethatyouonlykeepthecodeyouwanttoexecute
withinthebracketsoftheconditional.
Ifthecodeblockthatrunsiftheconditionistrueextendsmorethanoneline,pleasenote
thateachlineshouldbewithinthebracketsoftheconditional.It’salsogoodpracticeto
havethesamelevelofindentationbelowtheconditionalstatement.Itwon’taffecthowthe
coderuns,butitmakesthecodelookmuchcleaner.Otherprogrammersreadingyourcode
willthankyou.
WhatElse?
Theprogramwewroterespondsonlyiftheconditionalisevaluatedastrue.Ifthe
conditionalisevaluatedasfalse,theuserreceivesnoresponse.Thisislikelyconfusingfor
theuser.We’regoingtoaddtotheprogramsothatitreactsonewayiftheconditionis
evaluatedastrueandanotherwayiftheconditionisevaluatedasfalse.Addtheindicated
codetoyourclass.
importjava.util.*;
publicclassDrink{
publicstaticvoidmain(String[]args){ ScannerageGetter=newScanner(System.in); System.out.println(“Howoldareyou?”); intage=ageGetter.nextInt();
if(age>=21){
System.out.println(“Youcanlegallydrink!”);}
else{
System.out.println(“You’renotofdrinkingage.”);}
}
}
Aftermodifyingyourprogramcode,runthroughthethreepossiblescenariosasyoudid
before.Testacasewheretheuserisunder21,anotherwheretheuserisolderthan21,and
afinalscenariowheretheuserisexactly21.Youroutputshouldappearsimilartofigure
4.2:
Don’tforgettosaveandrecompile!
Figure4.2Resultwiththeelsestatementadded
Asyoucantell,theadditionoftheelsestatementgavearesultifavalueunder21was
entered.Whentheuserentersavalueunder21,theconditionisevaluatedasfalseandthe
elsestatementblockistriggered.Onceagain,onlythecodeinthebracketsisconsidered
partofthestatementblock.
Let’saddalittlebitmorecodetoourprogram:
importjava.util.*;
publicclassDrink{
publicstaticvoidmain(String[]args){
ScannerageGetter=newScanner(System.in);
System.out.println(“Howoldareyou?”); intage=ageGetter.nextInt();
if(age>=21){
System.out.println(“Youcanlegallydrink!”);}
else{
System.out.println(“You’renotofdrinkingage.”);}
if(age==21){
System.out.println(“Congratulations,Here’safreedrink.”);
}
}
}Now,iftheusersaystheyareexactly21,theprogramwillprintthecongratulatory
message.Notethatthecomparisonoperator==wasusedtodenoteequality.Ifthevaluein
ageisexactly21,theconditionalisevaluatedastrue.
Hereareallthecomparisonoperatorsthatyoucanusewithifstatements:
==Equal
>GreaterThan
>=GreaterThanorEqual
<LessThan
<=LessThanorEqual
!=NotEqual
Note:theseoperatorscanonlybeusedforprimitivetypeslikeintsorfloats!Forreference
typesthereisgenerallyamethodthatcanbeusedtocompareelementsinstead.Usually
it’sthe.equals()method.
Whileyoucanalreadyseethepowerofconditionals,let’saddalayerofcomplexity:what
ifyouwantedtotesttwovaluesatonce?
CompoundConditionals
Let’spretendthatwe’rewritingsoftwareforacollegetodeterminewhetherornota specificstudentmadethehonorroll.Inourcollege,inordertobeeligibleforhonorsyou
mustbothhaveaGPAgreaterthan3.5andattemptmorethan12credithours.
CreateanewprograminyourtexteditorcalledHonors.javaandenterthecodebelowin
thefile:
importjava.util.*;
publicclassHonors{
publicstaticvoidmain(String[]args){
ScannergpaGet=newScanner(System.in);
ScannerhoursGet=newScanner(System.in);
System.out.println(“WhatwasyourGPAthissemester?”);
doublegpa=gpaGet.nextDouble();
System.out.println(“Howmanycredithoursdidyouattemptthissemester?”);
inthours=hoursGet.nextInt();
if(gpa>3.5&&hours>12){
System.out.println(“Congratulations!
Youmadehonorroll!”);
}
else{
System.out.println(“Sorry,youdidn’tmakehonorroll.Betterlucknexttime.”);}
}
}
Testyourprogramandseewhatkindofresultyouget.Yourresultshouldbesimilarto
whatappearsinfigure4.3:
Figure4.3:Twoconditionsaretestedsimultaneously.
You’llnoticethatintheifstatementwejoinedtwoconditionsbytwoamperstamps(&&),
which,inthiscase,isactingasanoperator.Inthisifstatementbothconditionsjoinedby
&&mustbeevaluatedastrueinorderforthewholestatementtobeevaluatedastrue.You
canusetwoverticalbars(||)asanoperatorinothercircumstanceswhereoneconditionor
theothermustbetrue.Youcanjoinanyamountofconditionsinasingleifstatementwith
&&and||operators.
TalktheTalk:Generallywhenreadingcode,aprogrammerwillread‘&&’as“and”and
willread‘||’as“or”.Sothelineif(a>b&&c<d||d<c)willbereadas“ifaisgreaterthan
bandcislessthand,orifdislessthanc(theconditionis)true”.
ComplexConditionalswithelse-if
Sofartheconditionalswe’vecreatedcanmakedecisionsinaneither/orscenario—either
youareeligibletodrink,oryou’renot.However,lifeismorecomplexthanthis,whichis
whyifstatementscanbepairedwithelse-ifstatements.Thiscombinationwillletyou
choosefromseveraloptionsasintheprogrambelow.
PleasekeyinthisprogramandrunitwiththeJavacommandtoseetheresult:
importjava.util.*;
publicclassComplexConditionals{
publicstaticvoidmain(String[]args){
ScannerageGet=newScanner(System.in);
System.out.println(“Howoldareyou?”);
intage=ageGet.nextInt();
if(age<18){
System.out.println(“You’reakid!”);System.out.println(“Gotoschool.”);
}
elseif(age<29){
System.out.println(“Timetoestablishyourself.”); System.out.println(“GoodLuck!”);}
elseif(age<39){
System.out.println(“Thesearetheyearstofocusonyourcareer.”);
System.out.println(“Getajob.”);
}
elseif(age<49){
System.out.println(“Timetostartthinkingaboutretirement.”);
System.out.println(“Ihopeyou’reputtingmoneyaway.”);
}
elseif(age<59){
System.out.println(“Maintainyourhealththroughexercise.”);
System.out.println(“Getatrainer.”);}
else{
System.out.println(“Youareold”);}
}}
Withapologiestothose59andolder,thisprogramprovidesfeedbackbasedontheagethe
userenters.Firsttheuserenterstheirageandthisvalueisassignedtothevariableage. Thevalueenteredbytheuseristhentestedinthefirstpartoftheifstatement.Iftheageis
lessthan18,theprogramrespondswith“You’reakid!Gotoschool.”
Ifthefirstconditionturnsouttobefalse,theelseifconditionisevaluated.Iftheageis
lessthan29theappropriateadviceisdispensed.Ifnot,thenextstatementisevaluated.If
noneoftheconditionsassociatedwiththeelseifstatementsarefoundtobetrue,thenthe
unfortunateelsestatementattheendoftheprogramruns.
Keepinmindthatelseifstatementsareonlyrunifallofthepreviousconditionsarefound
tobefalse.Notealsotheindentationusedthroughouttheelse/elseif/elseisconsistent.
Thisisforhousekeepingpurposes.Readabilityisaimportantpartofprogramming.
WhileLoops
Loopsallowyoutorunablockofcodeanumberoftimes.Eachtimethatblockofcodeis
executedisknownasaniteration.Loopsarecriticaltomanydifferenttypesofprograms.
Imagineacardgamewhereturnsaretakenandcardsaredealt—allwithloops.Ifyou
thinkaboutit,youcanprobablyidentifyloopsinmanydifferenttypesofsoftwarethat
youuseeveryday.Theprocessofwaitingfortheusertoinputsomething,processingthat
inputandthenwaitingfortheuseragainisoftencodedinaloopstructure.
Let’scodeasimpleloop:
publicclassLoop{ publicstaticvoidmain(String[]args){
inttracker=0;
while(tracker<100){
System.out.println(tracker);
tracker+=5;}
}
}
RuntheprogramwiththeJavacommandandtheresultshouldappearsomethinglikewhat
youseeinfigure4.4:
Figure4.4:Theresultofawhileloop
Inthefirstlineofthisprogramwedeclareandinitializeavariabletrackerwiththevalue
0.Nextcomesourwhilestatementwhichstatesthatwhilethevalueoftrackerislessthan
100,thecodeblockinsidethebracketsofthewhilestatementwillexecute.Inthiscase,
thecodeblockprintsthevalueoftrackertotheconsoleandthenincreasesthevalue
trackerby5.
Notethatthex+=5notationisshorthandforx=x+5.+=isknownasacombined
assignmentoperator.
TalktheTalk:Programmersgenerallycall“+=”“plusequals”.Sowhendescribingthis codeonewouldsay“xplusequalsfive”Here’sanotherloopexampleprogramforyouto
try.IsavedmineasLoop2.java.
importjava.util.*;
publicclassLoop2{
publicstaticvoidmain(String[]args){
ScannerbandName=newScanner(System.in);Stringband=””;
while(!band.equals(“XXX”)){
System.out.println(“NameofabandyoulikeorXXXtostop.”);
band=bandName.nextLine();
if(!band.equals(“XXX”)){
System.out.println(band+”ROCKS!”);}
}
}Note:Duetostringsbeingareferencetype,youhavetousethe.equals()methodto
checkforequality.Thismethodreturnstrueifthestringsareequalandfalseifnot.
RuntheprogramwiththeJavacommandandyoushouldseearesultsimilartofigure4.5:
Figure4.5Theuserinputstextinsidealoop.
Whenthisprograminitiallyruns,thevariablebandissettoanemptystring.Thevalueof
bandiscomparedtothestring“XXX”eachtimethroughtheloop.Iftheloopisanything
otherthan“XXX”theloopiteratesagain.IfthevalueisnotXXX,thenameofthebandis
echoedbacktotheconsole.
Noticethatalloftheopeningbracketshaveacompanion.Ifyougetlostincodethathasa
numberofclosingbracketsinarow,here’satrick:Therealwaysmustbethesamenumber
ofopeningandclosingbracketsinaclass–Ifyouhavemoreopeningbracketstrypairing
eachoneoffuntilyouwherefindyou’remissingclosingbrackets.
Don’tTryThisatHome
Acommonerrorinprogrammingisanendlessloop.Theseendlessloopscanconsume
moreandmorecomputingresourcesandeventuallymaketheprogram,oryourcomputer
crash.Considerthefollowingcode:
publicclassLetsBreakTheComputer{ publicstaticvoidmain(String[]args){
doublex=1;
while(0<x){
System.out.println(x);
X*=300000;}
}
You’llnotethatthecontinuationconditionwillalwaysbetrueinthisexample—thevalue ofxwillalwaysbegreaterthanzero.Thevalueofxveryrapidlygetsoutofhandand,in fact,becomestoobigtostoreinmemory.IranthisintheKoding.comenvironment.It
tookmeabout10minutestostoptheexecutionoftheprogramaskoding’senvironment
waslaggingduetotheprogram.
Figure4.6:Atthispointtheenvironmentwasfrozenduetoanendlessloop.Everyso
oftenitwouldprint“Infinity”acouplehundredtimesandthenfreezerightbackup.
Youcantrythisexampleonyourown.I’mnotresponsibleforanydamagedone.
(Damagewon’tbepermanent…havefun!)
Forloops
Sowe’vedeterminedthatforgettingtoputaproperiteratorinyourwhileloopcanbebad
foryourprogram.Howcanweavoidhavinganendlesswhileloop?Theanswerisafor
loop.Forloopsdothesamethingaswhileloops,howevertheywillonlyexecuteaset
numberoftimesbecauseyouareforcedtoplaceaniteratorandvariableaspartofthe
loop’ssyntaxinadditiontoaconditional.Asaresultit’sextremelydifficulttocreateafor
loopthatexecutesendlessly.
Here’sanexampleofaverysimpleforloop.Itdoesthesamethingasourfirstloop:Prints
0to100,whilecountingbyfives.
ThisloopisinafilecalledLoop3:
publicclassLoop3{
publicstaticvoidmain(String[]args){
for(intx=0;x<100;x+=5){System.out.println(x);}
}
}
Thesyntaxoftheloopissimple.Firstwehavealocalvariablexthatisinitializedand
declared.Localvariablescannotbeaccessedorchangedoutsideoftheloop.Then,we
haveaconditional.Theconditionalfulfillsthesamepurposeasinthewhileloop.Whenit
isnolongertruetheloopwillstopiterating.Finallywehavewhat’sknownasaniterator.
Thisisareassignmentofthevariableyouinitiallydeclaredforthisloop.Theiteratoris
thereasonthatit’sgenerallyhardtoaccidentlymakeanendlessloop.Notethatthesethree
statementsareseparatedbysemicolonsasthoughtheyweretheendoflines.Here’sthe
resultofexecutingthiscode:
Figure4.7:Theresultoftheforloopisthesameastheresultofouroriginalwhileloop.
Chapter5:DealingwithData
Inthelastchapterweexaminedcontrolstructures,conditionals,andloops,whichare
criticalinmostprogramminglanguages.Theyallowyourprogramstomakedecisions
basedonthecriteriathatyousetasthedeveloper.Inthischapter,we’regoingtoswitch
gearsandexaminedataandhowit’sstored.We’lltakeacloselookatfourdatastructures:
Arrays,ArrayLists,Immutables,andHashTables.Youmaynothavegivenmuchthought
todatabefore.Theeasiestwaytoconceptualizedataisasorganizedinformation.
Differenttypesofinformationlenditselftobeingorganizedindifferentways.For
example,ifyourdataisagrocerylist,thenanArraywouldbetheoptimalwaytoorganize
yourdata.However,ifyouwantedtostorestudentgradesondifferentassignmentsovera
periodoftime,anArraywouldn’tworkwellatall.Therearemanydifferentdata
structuresusedbyprogrammersandeachisoptimizedforadifferenttypeofdata.
Let’sstartwithasimplegrocerylist.
Arrays
We’veallmadeagrocerylistbefore,butyoulikelyhaven’tstoreditinJavacode.Let’sdo
thatnowusingthefollowinglineofcode:(Remembertoputthisinyourmainmethod!)
String[]groceries={
“oranges”,“apples”,“milk”,“bread”,“butter”,“pepp
er”,“salt”,“sugar”,“pears”
};
Unlikevariableswhichstoreasingleunitofdata,we’vestoredmultipleelementsinour
array.I’msureyoucanimagineanumberofsituationswherethiscouldbeconvenient.In
thiscase,allofthemembersorelementsofourarrayarestrings.Thisisbecausewe
declaredourarrayasaStringarray.“String”isthedatatypeofthearray’smembers.
Hereisanotherarraytoaddtoyourcode.Thistimeit’scomprisedofdoublevalues:
double[]gpas={
3.25,2.26,1.99,3.55,4.0,3.21,2.56,3.06,
2.72
};
Now,here’swherearraysbecomeabitmoreinteresting.Arrayshaveanumberofbuilt-in
methodsthatyoucanusetomanipulatethem;Thereareincludedfunctionsthatdothings
likecountthemembersofthelistorsortthem.Youcouldwriteyourowncodetodoall
this,butitwouldbealotofwork.
Beforewestartwiththereallyfancystuff,let’stakealookathowweextractdatafrom
theArray.Goaheadandcopythecodebelow.You’refreetoskipoverthecommentsif
youlike.Remembertokeepthefilenameandtheclassnameconsistent!
publicclassArrays{ publicstaticvoidmain(String[]args){ String[]groceries={ “oranges”,“apples”,“milk”,“bread”,“butter”,“pepper”,“salt”,“sugar”,“pears” }; double[]gpas={
3.25,2.26,1.99,3.55,4.0,3.21,2.56,3.06,2.72
};
System.out.println(groceries[0]);//returns‘oranges’
System.out.println(groceries[1]);//returns‘apples’
System.out.println(gpas[3]);//returns‘3.55’
}
}
Onceyou’resurethatthecodeistypedcorrectlyinyourtexteditor,executethecodewith
theJavacommand.Don’tforgettocompile!Youroutputshouldlooklikethis:
Figure5.1:JavaArraysprogramoutputusingtheKoding.comenvironment
Payspecialattentiontotheprintstatements.You’llnotethateachprintstatement
referencesoneofourarraysandaspecificindexwithinthatlistsurroundedbybrackets.
ListsinJava,likemostlanguages,areindexed,meaningthateachmemberofthelistis
assignedanumberusedtoreferenceit.Thefirstmemberofalistisalwaysindexzero.
Ourgrocerylistwouldhavethefollowingindexes:
IndexMember
0oranges1apples
2milk
3bread
4butter
5pepper
6salt
7sugar
8pears
Whencombinedwithprintmethod,thegeneralformofretrievingdatafromanarrayis:
ArrayName[#];
Where“#”istheindexyouarepointingto.
Onethingtokeepinmindisthatyourarrayisonlyaslongasyouinitiallymakeit.Ifyou
trytoaccessanon-existentarrayindex,yourprogramisgoingtoexitwithanerror.Let’s
addonelinetoourcurrentprogram:
System.out.println(gpas[9001]);
Whenyouruntheprogramyoushouldseeanoutputsimilartothefollowing:
Figure5.2:Usinganindexthatisoutofrangeresultsinanexception.
DeclaringEmptyArrays
Allofthearrayswe’vefilledsofar,havebeenfilledmanually.We’vethenprintedthem
bycallingindexesindividually.Wedon’thavetodothis.Thedeclarationandinstantiation
(fancywordforcreation)ofanarraycanbedonewithnovaluessolongasyouknowhow
manyelementsyouplanonputtinginsideofyourarray.
Hereisanexampleofhowtodoso:
int[]vals=newint[10];
Inthiscase,wearecreatinganintegerarraywith10slots.Theslotsarecurrentlyfilled
withintegerscontainingthevaluezero,aszeroisthedefaultvalueforanintegerwithout
anexplicitlyassignedvalue.
Ratherthanputtingaseriesofvaluesafterthedeclarationstatement,wecommandedthe
JVMtomakeanewemptyarraywithenoughspacefortenintegertypenumbers.
Remember,Javaiszero-indexedsothelastslotinthisarrayisn’tcalledbyputtingaten
inthebrackets.tenissimplythenumberofelementswithinthearray.Thelastelementis
referencedwithanine.
vals[9];
Theabovewillaccessthelastslotofthearray.Thefirstslotisaccessedbyplacinga0in
thebrackets.
Thetechnicaltermforthewayarrayscountis“zero-based”.(Javaiszero-indexed.Arrays
arezero-based).
EditingArrayMembers
Youcanalsousetheindexofanarraymembertochangethevaluesofdifferentmembers
inthelist.Thisisdonewithanassignmentstatementasinassigningavaluetoastandard
variable.ThefollowingstatementwillchangethezerothindexoftheGPAlist:
gpas[0]=4.0
Notethattheindexesoftheothermembersofthearrayarenotaffected.
Thisisalsoonewaythatwecanfillouremptyarrays.Wewouldsimplyreassignan
emptyslottoavaluewewouldlike.
SortingArrays
We’vemanipulatedandstoredalotofdatasofar.Wehavenot,however,organizedmuch
data.
Arraysareapowerfulorganizationaltool.Onereasonisbecauseofthesort()method.It
doesexactlywhatitsoundslike—itsortsthemembersofthearray.Thesortmethodis
calledabitdifferentlyfromnormalmethodsthough.Sort()iscalledasastaticmemberof
thearrayclasslikethis:
Arrays.sort(<Array>);
Makeanewfileandcopythiscode.MyfileiscalledArraySortDemo.java:
importjava.util.Arrays;
publicclassArraySortDemo{
publicstaticvoidmain(String[]args){
String[]groceries={
“oranges”,“apples”,“milk”,“bread”,“butter”,“pepper”,“salt”,“sugar”,“pears”
};
System.out.println(“
for(Stringa:groceries){
System.out.print(a+”“);
}
System.out.println();
System.out.println(“
Arrays.sort(groceries);
for(Stringa:groceries){System.out.print(a+”“);}
System.out.println();
UNSORTEDARRAY
”);
SORTEDARRAY
”);
}
}
Note:Don’tworryifyoudon’tunderstandtheforloops.They’reusedtoprintourarray.
We’llcovertheminthenextsection.
RunyourprogramwiththeJavacommand.Youroutputshouldlooksomethinglikethis:
Figure5.3:Afterthesort()functionruns,thegrocerieslistisreindexed.It’snowin
alphabeticalorder!
Thesortmethodwillalsoordernumbersfromsmallesttolargest,andorganizeother
primitivedata.
PrintingArrays
Sofartheonlywaywe’vebeenprintinginformationfromarraysisthroughreferencing
anindividualarrayelement.Butwhatifweneedtoprintoutawholearray?
Copythisfilebelow:
publicclassPrintingArrays{
publicstaticvoidmain(String[]args){
int[]oneToTen={1,2,3,4,5,6,7,8,9,10
};
System.out.println(oneToTen);
}
}
Executingthecodeaboveresultsinnon-readabletext:
Figure5.4:
PassingthevariablenameprintedaninternalreferenceusedbytheJavacompiler.Odd.
Instead,wehavetousealoop.Thereareseveralwaystodothis;I’mgoingtoshowyou
thetwoeasiestandmostfrequentlyused.
Withaforloop
Thefirstmethodusesasimpleforlooptoprintoutthearray.Replacetheprintmethod
withthesefewofcodeinPrintingArrays:
for(intx=0;x<oneToTen.length;x++){System.out.println(oneToTen[x]);}
Nowifyourunyourprogramyou’llseethatthecontentsofyourarrayhavebeenprinted:
Figure5.5:Awesome!Weprintedthearray.
Thewaythisloopworksisverysimple.Thelocalvariablewecreatetotrackthenumber
oftimesourloophasiteratedisusedastheindexvaluewhenwecallanarrayelement.As
aresultafteriteration,thevalueofthevariableincreasesbyoneandtheslotwe’re
referencingchanges.
Inotherwords:xstartsaszero.Thenextiterationchangesx’svaluefromzerotoone.Due
tothesquarebracketscontainingthedynamicvariablexratherthanastaticnumberthe
indexthatwearecalling,whichwasoriginallyindexzero,switchestoindexone.
Thenumberofiterationsissetusingthe.lengthpropertywhichreturnsthetotalnumber
ofelementsinourarray.
Withafor-eachloop
Thesecondmethodofprintingisthroughtheuseofamodifiedforloopcalledafor-each
loop.Thesyntaxforthisloopissimplerthanthatoftheregularforloop.
AddthefollowingcodetotheendofyourPrintingArraysprogram:
System.out.println(“
for(intprint:oneToTen){System.out.println(print);}
Thefirstlineinthissnippetofcodeprintsaseparator,soweknowwhichloopis
generatingtheoutput.
Nextistheforeachloop.Thestatementwithintheforloop’sparenthesesisshorter,
consistingoftwocomponentsratherthanthree.Thisstatementalsofailstoconformto
whatwe’velearnedabouttraditionalforloops,asitlacksaniteratorandconditional.This
differentstatementiswhatmakesthisafor-eachloopratherthanaregularforloop.
Whatevercodeisputinsidetheloopwillbeperformedforeachmemberofthearray.
Inthiscasewe’reprintingthearray.
Thestatementwithintheparenthesesoftheloopconsistsofavariabledeclaration,whose
typemustmatchthetypeofthearrayyouintendedtocallthelooponandthenameofthe
arrayyouintendtousetheloopon.
Ifyou,forexample,wantedtoprintourgrocerylistarray,thefor-eachloopwouldlook
likethis:
for(Stringitem:groceries){
System.out.println(item);}
Becausegroceriesisanarrayofstrings,thevariable‘item’isastringaswell.
Thisneedstobetrueforallvariablesanddatatypesdeclaredforuseinafor-eachloop.If
youintendtoprintanarrayofintegers,theholdervariablethatisdeclaredwithinthe
parenthesesmusthaveatypeofinteger.
ArraysareobjectsandyoucanuseanumberofmethodsassociatedwiththeArrayobject. YoumightwanttotakealookattheofficialJavadocumentationandseethefunctionsthat youcanusewitharrays.Thedocumentationisavailableat
http://docs.oracle.com/Javase/7/docs/api/Java/util/Arrays.html.
Remember:Learninghowtoreaddocumentationisavaluableskill.
ArrayLists
Arraysareveryuseful,buttheyarealsoratherlimitedinwhattheycando.Anexampleis
thearray’sinabilitytobeexpandedafterinstantiation.IfIhaveanarraywithtenelements
Ican’taddaneleventhelementtotheendofthearray.WithArrayListswegainnew
functionalityandtheabilitytoadddifferenttypesofobjectsintoonedatastructure,but
thatisn’tdoneoften.
Atthispointyoumaybewonderingwhywebotherwitharraysatallifwehave
ArrayLists.Theanswerisefficiency.ArrayListstakeupmorememorythanarrays.In
Withaforeachloop
”);
biggerprogramsthismeanstheycancauseittorunslowerthanifwejustusedarrays.
ArrayLists,justlikeScanners,arereferenceorclasstypeobjects.Theirdeclarationlooks
likethis:
ArrayListname=newArrayList();
ItshouldbenotedthatArrayListscannotbefilleduponinitializationlikearrays.Theonly
waytofillthemisthroughthe.add()method.Youshouldalsobeawarethatunlessyou
putanintegerintheparenthesisoftheArrayList’sconstructoritwillbemadewitha
defaultsizeoftenslots.
IfyourArrayListisfullthe.add()methodwillsimplyaddanewmemberandappend
whatyouplacedintheparenthesistotheendofthelist.
Nowlet’stryanexample.IputmineinafilecalledArrayLists:
publicclassArrayLists{
publicstaticvoidmain(String[]args){
ArrayListlanguages=newArrayList(3);languages.add(“Spanish”);
languages.add(“French”);
languages.add(“English”);
System.out.println(languages.size());
languages.add(“German”);
System.out.println(languages.size());}
}
ThefirstlineinthemainmethoddeclaresanewArrayListthatwenamedlanguagesand
gaveitasizeofthree.
TalktheTalk:Thereareseveralwaystosayyouusedamethod.Themostcommonterms
are‘call’or‘invoke’.WhenIprogrammersays‘Iinvokedthemethod’heorsheisreally
sayingtheyusedthemethod.
ThenextthreelinesofcodeinvoketheaddmethodtofilluptheArrayList.Thenthesize
methodiscalledtoseehowlargetheArrayListis.Afterthatonemoreelementis
appendedtotheendoftheArrayList,increasingthesizefromtheoriginalthreeslotsto
four.
Whenyourunthecode,youroutputshouldappearsomethinglikethis:
Figure5.6:
WecanseehowthesizeofourArrayListincreasedwhenweaddedanelementtotheend.
Javaprintedtwonotesinadditiontotheoutputoftheprogram.Thisoccuredbecausewe
areusinganunparameterizedArrayList.AnunperamiterizedArrayListisanArrayList
that’stypehasn’tbeenspecified.Asaresultvariablesofdifferenttypescanbestored
withinthesameArrayListandcauseexceptionsduetotypemismatches.
Toalleviatethisissue,wehavetotypeourlisttotakeonespecificobjectlikearraysdo.
Ratherthanastandarddeclarationandinstantiation,weaddaslightmodificationtoeach
partsoitlookslikethis:
ArrayList<DataType>name=newArrayList<DataType>();
TalktheTalk:AnunparamaterizedArrayListacceptswhat’sknownasagenerictype.A
generictypeisatypethatcanbespecifiedlaterbytheprogrammerinordertoimprove
functionality.Thetypecanbeanything,includingcustomclassesthatyouimplementand
designyourself.
Let’smodifythecodeinourArrayLists.javafiletofollowthispractice:
publicclassArrayLists{
publicstaticvoidmain(String[]args){
ArrayList<String>languages=newArrayList<String>(3);
languages.add(“Spanish”);
languages.add(“French”);
languages.add(“English”);
System.out.println(languages.size());
languages.add(“German”);
System.out.println(languages.size());}
}
Nowwhenwerecompileandrunourcode,there’snoproblem!
Figure5.7:Muchbetter.TypingourArrayListgotridofthatpeskywarning.
NowthefinalthingtoknowaboutArrayListsishowtoobtaindatafromthem.Unlike
arrays,wedon’treferencebyindexes.Instead,weuseamethodtoretrievethedata:The
.get(#)method.Thenumberintheparenthesesistheindexvalueoftheelementyouwant
toaccess.JustlikeArrays,ArrayListsarezero-based.
Addthefollowinglinetoyourcode,recompileandruntoseeitinaction:
System.out.println(languages.get(0));
Whenyourecompileandrun,theoutputshouldlooksomethinglikethis:
Figure5.8:
WegotthenprintedthefirstelementofourArrayList.
ThereareanumberofothermethodsforArrayListsthatareratheruseful.Themost
notablebeingthe.set()method,whichreplacesvaluesmuchlikereassigningwitharrays.
Theofficialdocumentationislocatedhere:
http://docs.oracle.com/Javase/7/docs/api/Java/util/ArrayList.html
Immutables
ImmutablesareverysimilartoArrayListswithoneimportantexception:Immutablesare
non-dynamic.ThismeansonceanImmutableisdefinedthevalueswithinitcannotbe
changed.Let’sstartanewprogramwherewewilldefineanImmutable.
CopythiscodeintoafilenamedImmutablesDemo.java:importjava.util.*;
publicclassImmutablesDemo{
publicstaticvoidmain(String[]args){
//Note:Arrayscannotbemadeimmutable.Soinstead,weuseLists.
String[]turn={“600”,“800”,“1024”,“1280”,“1366”,“1920”};
List<String>list=Java.util.Arrays.asList(turn);
List<String>unmodList=
Collections.unmodifiableList(list);
for(Stringp:unmodList){
System.out.println(p);
}
System.out.println();
System.out.print(unmodList.get(0));
unmodList.add(“464”);}
}
CompilethecodethenrunitusingtheJavacommandandcarefullyexaminetheoutput.
Figure5.9:Notethatwe’reabletoaccessthecompleteimmutable,asingleindexwithin
theimmutable,butwhenreassigningavaluewithinanimmutable,anerrorisgenerated.
Animmutableisnon-dynamicandonceinitiated,thevalueswithinitcannotbechanged.
Immutableareforstoringdatathatdoesnotchangeoverthelifeofaprogram.For
example,intheprogramabove,thescreenwidthsareunlikelytochange.
HashTables
HashTablesareyetanotherdatastructure.Theyareperfectforstoringpaireddata,
sometimesknownaskey:valuedata.Inthistypeofdata,insteadofanumericalindex,
eachdatapointisindexedbyakeywhichisdeterminedbytheprogrammer.Statenames
andstatecapitalsortownsandzipcodesarebothexamplesofwhereHashTablescanbe
usefulforstoringdata.
SeasonedprogrammersmayfindHashTablestobeverysimilartoDictionaries.Thisis
becauseHashTableswerederivedfromthem.(Dictionariesaretheparentclassof
Hashtables)
Considerthefollowingprogram:
importjava.util.*;
publicclassHashTabs{
publicstaticvoidmain(String[]args){
Hashtable<String,String>statesAndCapitols=newHashtable<String,String>();
statesAndCapitols.put(“Connecticut”,“Hartford”);statesAndCapitols.put(“New
York”,“Albany”);statesAndCapitols.put(“Mississippi”,“Jackson”);
statesAndCapitols.put(“Maine”,“Augusta”);statesAndCapitols.put(“Montana”,“Helena”);
statesAndCapitols.put(“Texas”,“Austin”);
StringConnCap=statesAndCapitols.get(“Connecticut”);
System.out.println(ConnCap);
}}
WhenyouruntheprogramwiththeJavacommandyou’llseetheoutput“Hartford”.This
istheresultofthekey(orindex)for“Hartford”being“Connecticut.”Notetheprint
commandandhowitisusedtoaccessthevalueintheHashTable.
Justlikearrays,Java’sHashTablesareanobjectandhavefunctionsthatcanbeassociated
withthem.Let’stakealookatoneofthesefunctions.Updateyourcodesoitappearslike
this:
portjava.util.*;
publicclassHashTabs{
publicstaticvoidmain(String[]args){
Hashtable<String,String>statesAndCapitols=newHashtable<String,String>();
statesAndCapitols.put(“Connecticut”,“Hartford”);statesAndCapitols.put(“New
York”,“Albany”);statesAndCapitols.put(“Mississippi”,“Jackson”);
statesAndCapitols.put(“Maine”,“Augusta”);statesAndCapitols.put(“Montana”,“Helena”);
statesAndCapitols.put(“Texas”,“Austin”);StringConnCap=
statesAndCapitols.get(“Connecticut”);
System.out.println(ConnCap);
System.out.println(“Values:“+statesAndCapitols.values());
System.out.println(“Keys:“+statesAndCapitols.keySet());
}
}
RunyourcodeonthecommandlineusingtheJavacommand.Yourresultshouldappear
similartofigure5.10:
Figure5.10:Outputdemonstratingtwoofthefunctionsusedwithdictionaries—values()
andkeySet()
You’llnotethatthevalues()functionreturnsallofthevaluesinthedictionary,whilethe
keySet()functionreturnsallofthekeys.Thisshortchaptercanonlygiveyouabroad
introductiontoworkingwithdatainprogramming.Almosteveryprogram,tosome
degree,workswithdata.Beingeffectiveatworkingwithdataisanimportantpartofany
programmer’stoolbox.
Chapter6:PuttingItAllTogether
Classesandobjectsrepresentnotjustaprogrammingconcept,butawayoflookingatthe
worldandsolvingproblems.Classesandobjects,atahighlevel,representaprocessof
classification—anactivitythatisasoldasscience.Whenwecreateaclass,wecreatea
modelofanobjectthatbreakstheobjectdowntoitscoreactivitiesandattributes.Javais
anObjectOrientedlanguage,meaningthatitiscompletelydependentontheClassand
Objectstructureandeverythingmustbecontainedinone.Javaisn’ttheonlylanguagethat
supportsobjects.It’sgoodtohaveanunderstandingofobjectsastheyareaverycommon
occurrenceinprogramming.
ClassVersusObjects
Ioftentellmystudentstothinkofaclassasablueprintofanobject.Fromthatblueprint,
manyinstancesoftheclass(objects)canbecreated.Thinkofplannedhousing
communities:asingleblueprintmaybeusedtobuildmanydifferenthomes.Thesehomes
mayvaryinsubstantialways—theymaybedifferentcolors,havedifferentkitchen
counters,anddifferentfixturesinthebathrooms—buttheyareallstillbasedonthesame
blueprint.
Inprogramming,aclassdefineshowanobjectoftheclassisdescribedandwhatitcando.
Itmightbeusefultothinkofclassesasasetofadjectivesandasetofverbs.The
adjectivesgiveusawaytodescribetheclass,whiletheverbstelluswhattheclasscando.
Thesetofadjectivesusedtodescribeaclassareknownasfields.Thesetofverbs
associatedwithaclassareknownasmethods.
Ifweweredescribingaclass“vehicle”wemightincludethefollowingmethodsand
properties:
Fields(Adjectives)Methods(Verbs)
coloraccelerate()
weightdecelerate()
heheightturnLeft()
topSpeedturnRight()
vehicleTypestartIgnition()
stopIgnition()
Obviouslythismodelisgreatlysimplified.Ifweweretrulytryingtorepresentavehiclein
code,we’dlikelyhavetouseseveralinterrelatedclasses.InJavawealsohavetodeclare
thetypeofdataeachpropertywouldhold.Forexample,thecolorpropertywouldholda
string,whileweight,heightandtopspeedcouldbeintegers.Whenwecreateaninstance
oftheVehicleClassthatwedefinedintheprevioustable,wemightassignavaluetoallof
theproperties,likethis:
Stringcolor=“blue”;doubleweight=5565.3;intheight=48;
inttopSpeed=90;
StringvehicleType=“car”;
Thisexampleassumesaninstance(object)createdcalledtheVehicle.
CodingaClassinJava
Let’swritethecodethatrepresentsanAnimalclassinJava.We’llalsocreateaninstance
ofthatclasscalledmyDoginanotherfile,abitlater.
publicclassAnimal{
privatestaticintnumberOfAnimals=0;publicintlength;
publicStringcolor;
publicdoubleweight;
publicbooleanhasFur;
publicAnimal(intLength,doubleWeight,StringColor,booleanFur){
color=Color;
weight=Weight;
hasFur=Fur;
length=Length;
numberOfAnimals++;
}
Therearedefinitelyafewnewthingshere.Thefirstisthatwedon’thaveapublicstatic
voidmain.Thisisbecausethisprogramdoesn’truninthewaythatwe’vebeenseeingso
far.ThemainmethodisgenerallytheentrancepointfortheJVMtostartexecutingour
code.Itwillbeinourdriverclass,whichwe’llwritelater.Westartourdefinitionofthe
classwiththepublicclasskeywordsandthenthenameoftheclass—inthiscase,
“Animal.”Thepublickeywordgivesinformationaboutvisibility.IttellstheJVMthatany
classisallowedtomakeobjectsfromthisclassandcallitsmethods.TheClasskeyword
informsJavaastowhatthisfileis.Next,you’llnoticeIdeclareavariablecalled
numOfAnimalsandinitializeitatzero.ThenumOfAnimalsvariableisdesignedtodo
someinternalhousekeepingintheclass.Itsjob,specifically,istotrackhowmany
instancesofAnimalwecreate.Thestatickeywordbetweenthedatatypeandthevisibility
level(whichinthiscaseisprivate)iswhatenablesustousethisvariableasatracker.
Staticmeansthatyoudon’thavetocreateaninstanceofaclassinordertoaccessor
modifythisinformation.Thismeansthateachobjectdoesn’thaveaninstanceof
“numOfAnimals”ratheritexistsintheclass.
AfternumOfAnimalsIsimplycreateanumberofvariablesdetailinginformationabout
ouranimal:thingssuchasweight,color,lengthandifithasfurornot.
Akeywordisareservedwordthatcannotbeusedforanythingotherthanitsintended functions.Examplesinclude:public,private,for,whileanddo.Generallykeywordswill behighlightedbyyourtexteditor.TheeditorI’musingonKodingcolorsthempurple,as
seenontheleftsideoffigure6.1.Keywordscannotbeusedasvariable,functionorclass
names,duetothefactthatthey’realreadyreserved.
WethendefinewiththepublickeywordintheAnimalfilewhat’sknownasa
“constructor”.Thismethodisveryimportant.Itdoesthreethings:detailstheinformation
thatweneedinordertomakeanobjectbasedonthisclass,preformsanyinternal
housekeepingandassignsinitialvaluestothefields.Itwillbeexecutedeverytimethatan
objectiscreatedbasedonofyourclass.
Theconstructoriscalledbythedriverclassbelow.
InamedmineAnimalDriver.java:
publicclassAnimalDriver{
publicstaticvoidmain(String[]args){
AnimalmyDog=newAnimal(19,12,“brown”,“true”);
}
}
TheparticularinstanceofAnimalthatwearecreating,calledmyDog,hasalengthof19,
weightof12,isbrownandhasfur.Thefirstfourlinesofconstructorassignthesevalues
thatarepassedintotheinstance.Youmaybewonderinghowwedeterminedtheorderof
theinformationtoputintotheclass.Theanswerisprettysimple;theconstructoraccepts
argumentsintheorderthattheclass’sconstructoriscoded.Inourclass,theorderofthe
datatypeswas:int,double,StringandBoolean.Thismeanswhenwecalltheconstructor,
that’stheorderthatargumentsmustfollow.
Figure6.1:Creatingtheclass(left)anddriverclass(right)inKoding
Examinethefollowingline:
numOfAnimals++;
ThislineisdesignedtoincrementthevalueofnumOfAnimals,theinternalhousekeeping
variablethatkeepstrackofhowmanyinstancesofAnimalthatwegenerate.Theactual
instanceisgeneratedwiththecodeinthedriverclasswhichcanbeseenhereinafile
calledAnimalDriver.java:
publicclassAnimalDriver{
publicstaticvoidmain(String[]args){
AnimalmyDog=newAnimal(19,12,“brown”,“true”);
}
}
AddingSomeMethods
Let’schangeupandaddtoourinitialcode:
publicclassAnimal{
privatestaticintnumberOfAnimals=0;publicintlength;
publicStringcolor;
publicdoubleweight;publicbooleanhasFur;publicbooleanisHungry;
publicAnimal(intLength,doubleWeight,StringColor,booleanFur,booleanHungry){
color=Color;
weight=Weight;
hasFur=Fur;
isHungry=Hungry;length=Length;
numberOfAnimals++;
}
publicStringwalk(){
return“Animaliswalking”;
}
publicStringeat(){
isHungry=false;
weight+=.1;
return“Animalhaseaten.\n”+“Animalnowweighs:“+
weight+”pounds”;
}
publicStringgetLength(){
return“Animal’slengthis“+length;
}
}Nowthatwe’veaddedtoouranimalclass,weneedtoaddtothedriverclassinorderto
continuetesting.
RewritethecodeinyourAnimalDriverfilesoitlookslikethis,thenrecompileandrunit. publicclassAnimalDriver{ publicstaticvoidmain(String[]args){
AnimalmyDog=newAnimal(19,12,“brown“,true);
System.out.println(myDog.walk());System.out.println(myDog.eat());
System.out.println(myDog.getLength());
}
}
WhenyourunthecodewiththeJavacommand,theresultshouldappearsomethinglike
this:
Figure6.2:Creatinganinstanceofaclassandmanipulatingit
You’llnoticethatI’veaddedanadditionalproperty,withthedatatypeBooleantothe
class:hungry.Thispropertyisdesignedsimplytotrackwhetherornottheinstanceof
Animalishungry.WhenwecreatetheinstanceofAnimalcalledmyDog,wesetthevalue
ofthehungrypropertytotrue.
We’vealsoaddedtwomethodstoourclass.Thefirstmethod,walk(),simplyprintsoutthe
message“Animaliswalking.”
Thesecondmethod,eat(),ismorecomplex.Itinteractswiththepropertiesoftheobject. First,theeat()methodsetsthevalueofthehungrypropertyto“false.”Ittheninformsthe userthattheAnimaliseatingviatheprintstatement.Finally,becausetheanimaliseating,
weaccesstheweightpropertyandadd.1toitsvalue.
AftertheclassdefinitionandtheinstantiationofthemyDoginstance,werunthewalk()
andeat()methods.
You’llnoticethatallofthesemethodsusethereturnkeyword.
Thedefinitionofthesemethodscontainswhat’sknownasa“returntype”.Itappearsinthe
declarationofthemethodafterthevisibilitylevel.ThisisthereasontheScannerobject
needsseveralmethodstotakeinputfromtheprompt;methodscanonlyreturnone
datatype&oneobject.Inallofourinstances,we’rereturningastring.Whenwecallthe
methodsinourAnimalDriverclass,whateverthemethodreturnstouswillbeastring.
ThismeanswecansetaStringtocapturethereturnvalueofourmethodinavariable:
publicStringwalkText=myDog.walk();
Notethatwhilewehavesofarreturnedprimitivetypeslikeint,floatorboolean,wecan
alsoreturnreferencetypessuchasArrayLists.
Thereturnkeyworditselfdoestwothings.
Thefirstthingissendbacktothemethodcallwhateveryouputontherestoftheline.If
youputanexpression,itsendsbacktheresult.Ifyouputastringitsendsbackthewhole
string.
Thenextthingthereturnkeyworddoesismarksthecompletionofthemethod.Assoonas
yourmethodreturnssomethingitwillexitregardlessofwhatisafterthereturninthe
code.Thisisusefulbecauseyoucouldplacethereturnstatementwithinanifstatement
andhaveitendpre-maturelyundersetcriteria.
Somemethodsdon’thavetoreturnanything.Anexamplethatwe’veencounteredisprint
method.Inthiscasethereturntypeis“void”,whichgoesinplaceofthedatatype.An
exampleofamethodwiththiskindofdeclarationisasfollows.
publicvoidname(<Datatype>Parameter){}
Itshouldbenotedthatthereturnkeywordcanbeusedtoforceavoidmethodtoexitas
well.Simplytype“return”,andasemicolontoendtheline,andstoptheexecutionofthe
method.
MultipleInstances
You’llrememberfromourinitialdiscussionthataclassismerelyablueprintandmultiple
objectscanbeconstructedfromthatclass.Enterthisrevisedcodeinyourtexteditor:
publicclassAnimal{
privatestaticintnumberOfAnimals=0;publicStringname;
publicintlength;
publicStringcolor;
publicdoubleweight;
publicbooleanhasFur;
publicbooleanisHungry;
publicAnimal(StringName,StringColor,intLength,doubleWeight,booleanFur,
booleanHungry){
color=Color;
weight=Weight;hasFur=Fur;
isHungry=Hungry;length=Length;name=Name;
}
publicStringwalk(){
returnname+”iswalking”;
}
publicStringeat(){
isHungry=false;
weight+=.1;
returnname+”haseaten.\n”+name+”nowweighs:“
+weight+”pounds”;
}
publicStringgetLength(){
returnname+“‘slengthis“+length;
}
}
I’veaddedyetanotherpropertytotheAnimalclass.Thenamepropertyisdesignedto
holdthenameoftheAnimalinstance.Keepinmind;thisisdistinctfromthenameofthe
codereferencetotheinstance.
Nowlet’supdateourAnimalDriverclasstoreflectthenewfunctionality.
Copythisrevisedcode:
publicclassAnimalDriver{
publicstaticvoidmain(String[]args){
AnimalmyDog=newAnimal(“Sparky”,“Grey”,17,56.4,true,true);
AnimalyourDog=newAnimal(“Rover”,“Brown”,19,41.8,true,true);
System.out.println(myDog.walk());System.out.println(myDog.eat());
System.out.println(yourDog.walk());System.out.println(yourDog.eat());
System.out.println(yourDog.getLength());
}
}
TheoriginalAnimalinstancemyDoghasavalueof“Sparky”inthenameproperty,while
thenewobjecthasavalueof“Rover”inthenameproperty.
Runningthenewcodeshouldresultinoutputsimilartothefollowing:
Figure6.3:TwoinstancesofAnimalobjectsarecreated—SparkyandRover.
ExtendingClasses
Theobjectorientedstructuredoesmorethanallowustosimplyrepresentobjectsascode
inonefile.Itallowsustobuildanentirehierarchyofobjectstorepresentourreallife
problemspace.Let’stakeanotherlookatVehicles.
Intheworldwehavenumeroustypesofvehicles.Someworkontheground,somework
inthewaterandothersintheair.Toproperlyrepresentavehicleinanobjectoriented
manner,weneedtodeterminewhattheyallhaveincommon.Allvehicleshaveatop
speed,aweightandacolor.Allvehiclesareeithermoving,orstill.
Asaresultwecancreateanewobjectthatcontainsallofthesecommonattributes,sowe
don’thavetocodethemeachtimewewanttocreateavariantofavehicle.
Copythefollowingcode,andsaveitasVehicle.java:
publicclassVehicle{
inttopSpeed;
Stringcolor;
doubleweight;booleanisMoving;
publicVehicle(intsetSpeed,StringsetColor,doublesetWeight,booleantellIfMoving){
topSpeed=setSpeed;color=setColor;
weight=setWeight;
isMoving=tellIfMoving;
}
publicbooleanstartMoving(){
isMoving=true;
return“Vehicleismoving.”;}
publicbooleanstopMoving(){
isMoving=false;
return“Vehicleisn’tmoving.”;}
}
Thecodeabovesummarizesthebasicattributeofvehicles.Butifweneedtorepresenta
car,thereisinformationweneedthatwouldn’tberelevantifwewererepresentingaboat.
ButwewouldstillneedalloftheattributesdescribedintheVehicleclass.Doesthismean
wecopyallofthiscodeintotwodifferentfilesinjusttorepresentthesetypesofvehicles?
Wecould,butthatwouldbeinefficient.Insteadweextendthevehicleclass.
Byextendingthevehicleclass,wecreatewhatisknownasachildclass.Thechildclass
inheritsthefields,methodsandeventheconstructoroftheparent(Vehicleinourcase)
class.
Openupanewfileinyourtexteditor,andsavethefollowingcodeas
GroundVehicle.java:
publicclassGroundVehicleextendsVehicle{
intnumWheels;StringvehicleType;
publicGroundVehicle(intsetSpeed,StringsetColor,doublesetWeight,boolean
tellIfMoving,intsetNumWheels,Stringtype){
super(setSpeed,setColor,setWeight,tellIfMoving);numWheels=setNumWheels;
vehicleType=type;
}
publicStringstartMoving(){
isMoving=true;
returnvehicleType+”isdriving”;
}
publicStringstopMoving(){
isMoving=false;
returnvehicleType+”isn’tdriving”;}
publicStringwhatColor(){
returncolor;
}
}
Thefirstlineofthiscodeisslightlydifferentfromwhatyou’reusedtofromthischapter.
Thereistheadditionofthe“extends”keywordfollowedbyVehicle.ThisnotifiesJavathat
GroundVehicleisachildofVehicle.InotherwordsGroundVehicleisderivedfrom
Vehicle.
InJava,allclasses,regardlessofiftheycontaintheextendskeyword,areanextensionof
theObjectclass.AsaresultatthetopofeveryhierarchaltreesitstheObjectclass.
Ourtreeappearsasfollows:
GroundVehicleisaVehiclewhichisanObject.
TalktheTalk:Inobjectorientedprogrammingwhenaprogrammerreferencestheparent
ofachildtheysaythechildclasssharesan“isa/an”relationshipwiththeparentclass.
Thenextlinesofthecodeaddtwonewfieldstoourobject.numWheelscontainsthe
numberofwheelsourGroundVehicleobjecthas.ThevehicleTypevariableallowsusto
passinastringlike“car”,“motorcycle”or“truck”.Bothofthesenewvariablesexistin
additiontoallofthevariablesintheVehicleclass.Vehicle’svariablescanbeaccessed
throughthe“super”keyword.SinceGroundVehicleisasubclassofVehicle,
GroundVehiclehasinheritedVehicle’sattributesandfunctionality.
Thesuperkeywordallowsyoutoreferencefields,constructorsandmethodsofthedirect
parent(classafterthe“extends”keyword)class.
Wealreadyreferencedtheconstructorbyusingthesuperkeywordintheconstructorof
ourGroundVehicleclass.Wetreatedthesuperkeywordliketheinstantiationstatementof
Vehicle.
Thenormalinstantiationwouldlooklikethis:
newVehicle(100,“Orange”,1034.2,false);
“newVehicle”hasbeenreplacedby“super”withintheconstructorandasaresultallof
thehiddenfieldswithinGroundVehiclewillbepopulateduponconstructionduetous
invokingtheparentclass’sconstructor.
Aftertheconstructorwehavethreemethods.Theychangeonevariablewithinthevehicle
classandthenreturnastringthatconfirmstheirchange.Readthenameofthefirsttwo
methodsinGroundVehicleandthenthefirsttwomethodsinVehicle.Whenmethodsina
childclasssharethesamenameasmethodsintheirsuperclass,theyoverridethe
superclassmethod.Wearechangingthefunctionalityofthemethodandnothingmore.If
wechangedanythingmore,suchasthereturntype,wewouldbeoverloadingthemethod.
Remember,weneedadriverclassinordertouseourobjects.
CopythefollowingcodeintoafilenamedVehicleDriver.java:
publicclassVehicleDriver{
publicstaticvoidmain(String[]args){
VehicletransportationMachine=newVehicle(50,“Blue”,210,false);
System.out.println(transportationMachine.startMoving());
}
}Theresultingoutputofthiscodeis:
Figure6.4:TheoutputisthestringwetypedintheVehicleDriverclass,asthatiswhatwe
putafterthereturnstatement.
Let’saddsomeadditionalcodetoourVehicleDrivertogetabetterideaofwhat’sgoing
on.AddthiscodeintoyourVehicleDriverclass:
GroundVehiclehorseAndBuggy=newGroundVehicle(5,“Black”,300,false,4,“Horse
andBuggy”);
Stringresult=horseAndBuggy.startMoving();
System.out.println(result);
Oncewerecompileandruntheoutputlookssomethinglikethis:
Figure6.5:ThemorespecificmethodinourGroundVehicleclassresultedinamore
specificoutput.
ThefirstlineofthiscodesnippetistheinstantiationfortheGroundVehicleobjectwhich
weusetomakeahorseandbuggy.Thenextlinemakesastring,andsetsittotheoutput
ofthestartMovingmethod.Thefinallineprintsresult.
Finallylet’slookatonemorethingthatclassextensionsarecapableof.
Copytheselastfewlinesintothedriverclass:
VehiclegoKart=newGroundVehicle(25,“Yellow”,3,true,4,“GoKart”);
System.out.println(goKart.startMoving());
Lookatthedeclarationandinstantiationoftheobject.Theydonotmatch.Howeverwhen
wecompileandrunthiscode,therearenoissuesduetothefactthatGroundVehicleisa
typeofVehicle.SincetheGroundVehicleclassisderivedfromtheVehicleclass,aVehicle
typevariablecanbeusedtoholdaGroundVehicletypeobject,likewe’vedoneinour
code.
HoweveraGroundVehicletypevariablecannotbeusedtoholdaVehicletypeobject!A
GroundVehicleisaVehicle,butaVehicleisnotnecessarilyaGroundVehicle.
GroundVehiclehasparametersthatnotallVehicleshave,anexamplebeingnumberof
wheels.
Thisistrueinallprogrammingtrees.Thelessvagueobjectscanbecontainedwithinmore
vaguevariables.Vaguerobjectshowevercannotbecontainedwithinamorespecific
variable.
ThisalsomeansthatyoucanplaceaGroundVehicle,oraVehiclewithinanObjecttype
variable,asallreferencetypeobjectsarederivedfromtheObjectclass.(Everythingisan
object.)
Atthispointyoumaybewonderingwhathappenswhenyoucallthe“startMoving”
methodonthenextline.WillitusethemorespecificmethodwithintheGroundVehicle
classorthevaguemethodwithintheVehicleclass?
Wellifyoucompileandrunthecode,theresultlookslikethis:
Figure6.6:Itusedthemorespecificmethod!
DespitethevariablebeingoftheVehicletype,theobjectthatthevariablereferencedwas
ofthetypeGroundVehicle.DuetotheobjectbeingoftheGroundVehicletype,whenwe
calledthemethodontheobjectitdidwhatitwassupposedtodoandexecutedthecode
thatithadaccessto:Themorespecificmethod.
Iencourageyoutoaddcodeandexperimentwiththevehicleclass,ormakeyourown
classesandmethodstoseewhatyoucando.
Agoodprojectwouldbetorepresentsomeotherrealsystemincode.Thissectionwas
designedtogiveyouonlyabasicintroductiontoobject-orientedprogrammingwith
classesandobjects.However,youwillfindthatthesefoundationalconceptscanbe
appliedtomanymodernprogramminglanguages.
Theendofthissectionalsobringsustotheconclusionofthisbook.Younowknowthe
foundationsofprogrammingusingtheJavaprogramminglanguage.Youwillfindthis
informationusefulwhetheryoucontinueyourstudyinJava,ormovetootherareasof
development,suchaswebapplicationsormobile.
Whateverdirectionyougo,Iwishyouthebestofluck.
OnlineCoursesfromLearnToProgram
BecomeaCertifiedWebDeveloperLevelOne BecomeaCertifiedWebDeveloperLevelTwo CertifiedMobileDeveloper RoadmaptoWebDeveloper
HTMLandCSSforBeginners(withHTML5
JavascriptforBeginners ProgrammingforAbsoluteBeginners PHPandMySQLforBeginners jQueryforBeginners
CSSDevelopmentwithCSS3
Node.jsforBeginners AdvancedJavascriptDevelopment AJAXDevelopment SQLDatabaseforBeginners RubyonRailsforBeginners Famo.usJavascriptFramework GitHubFundamentalsCreatingaPHPLoginScript FrontEndDeveloperwithAdobeDreamweaver CodelessWebDevelopmentwithAdobeMuse
MobileAppDevelopmentwithHTML5
10Appsin10Weeks
JavaProgrammingforBeginners SwiftLanguageFundamentals iOSDevelopmentforBeginners AndroidDevelopmentforBeginners
10Appsin10Weeks:iOSEdition
PythonforBeginners
Construct2forBeginners
GameDevelopmentwithUnity MobileGameDevelopmentforiOS
3DFundamentalswithiOS
ProjectManagementusingMicrosoftProject .NetforBeginners C++forBeginnersJoomlaforBeginners UserExperienceDesignFundamentals
PhotoshopCS6TrainingforCoders
DesignforCoders
CProgrammingforBeginners
ObjectiveCforBeginners
IntroductiontoWebDevelopment
GameDevelopmentFundamentalswithPython
Mult mai mult decât documente.
Descoperiți tot ce are Scribd de oferit, inclusiv cărți și cărți audio de la editori majori.
Anulați oricând.