java in easy steps: covers java 9

253

Upload: others

Post on 11-Sep-2021

5 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Java in easy steps: Covers Java 9
Page 2: Java in easy steps: Covers Java 9
Page 3: Java in easy steps: Covers Java 9

IneasystepsisanimprintofInEasyStepsLimited16HamiltonTerrace·HollyWalk·LeamingtonSpaWarwickshire·CV324LYwww.ineasysteps.com

Page 4: Java in easy steps: Covers Java 9

SixthEdition

Copyright©2017byInEasyStepsLimited.Allrightsreserved.Nopartofthisbookmaybereproducedortransmittedinanyformorbyanymeans,electronicormechanical,includingphotocopying,recording,orbyanyinformationstorageorretrievalsystem,withoutpriorwrittenpermissionfromthepublisher.

Page 5: Java in easy steps: Covers Java 9

NoticeofLiabilityEveryefforthasbeenmadetoensurethatthisbookcontainsaccurateandcurrentinformation.However,InEasyStepsLimitedandtheauthorshallnotbeliableforanylossordamagesufferedbyreadersasaresultofanyinformationcontainedherein.

TrademarksAlltrademarksareacknowledgedasbelongingtotheirrespectivecompanies.

Page 6: Java in easy steps: Covers Java 9

Contents

1GettingstartedIntroductionInstallingtheJDKWritingafirstJavaprogramCompiling&runningprogramsCreatingavariableRecognizingdatatypesCreatingconstantsAddingcommentsTroubleshootingproblemsSummary

2PerformingoperationsDoingarithmeticAssigningvaluesComparingvaluesAssessinglogicExaminingconditionsSettingprecedenceEscapingliteralsWorkingwithbitsSummary

3MakingstatementsBranchingwithifBranchingalternativesSwitchingbranchesLoopingforLoopingwhiletrueDoingdo-whileloopsBreakingoutofloopsReturningcontrolSummary

4DirectingvaluesCastingtypevaluesCreatingvariablearrays

Page 7: Java in easy steps: Covers Java 9

PassinganargumentPassingmultipleargumentsLoopingthroughelementsChangingelementvaluesAddingarraydimensionsCatchingexceptionsSummary

5ManipulatingdataExploringJavaclassesDoingmathematicsRoundingnumbersGeneratingrandomnumbersManagingstringsComparingstringsSearchingstringsManipulatingcharactersSummary

6CreatingclassesFormingmultiplemethodsUnderstandingprogramscopeFormingmultipleclassesExtendinganexistingclassCreatinganobjectclassProducinganobjectinstanceEncapsulatingpropertiesConstructingobjectvaluesSummary

7ImportingfunctionsHandlingfilesReadingconsoleinputReadingfilesWritingfilesSortingarrayelementsMakingarraylistsManagingdatesFormattingnumbersSummary

8BuildinginterfacesCreatingawindowAddingpushbuttonsAddinglabels

Page 8: Java in easy steps: Covers Java 9

AddingtextfieldsAddingitemselectorsAddingradiobuttonsArrangingcomponentsChangingappearanceSummary

9RecognizingeventsListeningforeventsGeneratingeventsHandlingbuttoneventsHandlingitemeventsReactingtokeyboardeventsRespondingtomouseeventsAnnouncingmessagesRequestinginputSummary

10DeployingprogramsProducinganapplicationDistributingprogramsBuildingJavaarchivesDeployingapplicationsCreatingAndroidprojectsExploringprojectfilesAddingresources&controlsInsertingJavacodeTestingtheapplicationDeployingAndroidappsSummary

Page 9: Java in easy steps: Covers Java 9

Preface

Thecreationofthisbookhasprovidedme,MikeMcGrath,awelcomeopportunitytoupdatemypreviousbooksonJavaprogrammingwiththelatesttechniques.AllexamplesIhavegiveninthisbookdemonstrateJavafeaturessupportedbycurrentcompilersonbothWindowsandLinuxoperatingsystems,andthebook’sscreenshotsillustratetheactualresultsproducedbycompilingandexecutingthelistedcode,orbyimplementingcodesnippetsintheJavashell.

Conventionsinthisbook

Inordertoclarifythecodelistedinthestepsgivenineachexample,Ihaveadoptedcertaincolorizationconventions.ComponentsoftheJavalanguageitselfarecoloredblue;programmer-specifiednamesarered;numericandstringvaluesareblack;andcommentsaregreen,likethis:

//Storethenoutputatextstringvalue.Stringmessage=“WelcometoJavaprogramming!”;System.out.println(message);

Additionally,inordertoidentifyeachsourcecodefiledescribedinthesteps,acolorediconandfilenameappearsinthemarginalongsidethesteps,likethese:

App.java

App.class

App.jar

Page 10: Java in easy steps: Covers Java 9

App.xml

Grabbingthesourcecode

Forconvenience,IhaveplacedsourcecodefilesfromtheexamplesfeaturedinthisbookintoasingleZIParchive.Youcanobtainthecompletearchivebyfollowingtheseeasysteps:

Browsetowww.ineasysteps.comthennavigatetoFreeResourcesandchoosetheDownloadssectionFindJavaineasysteps,6thEditioninthelist,thenclickonthehyperlinkentitledAllCodeExamplestodownloadthearchiveNow,extractthearchivecontentstoanyconvenientlocationonyourcomputer

IsincerelyhopeyouenjoydiscoveringtheprogrammingpossibilitiesofJavaandhaveasmuchfunwithitasIdidinwritingthisbook.

MikeMcGrath

Page 11: Java in easy steps: Covers Java 9

1

Gettingstarted

WelcometotheexcitingworldofJavaprogramming.Thischaptershowshowtocreateandexecute

simpleJavaprograms,anddemonstrateshowtostoredatawithinprograms.

IntroductionInstallingtheJDKWritingafirstJavaprogramCompiling&runningprograms

CreatingavariableRecognizingdatatypesCreatingconstantsAddingcomments

TroubleshootingproblemsSummary

Introduction

TheJava™programminglanguagewasfirstdevelopedin1990byanengineeratSunMicrosystemsnamedJamesGosling.HewasunhappyusingtheC++programminglanguagesohecreatedanewlanguagethathenamed“Oak”,aftertheoaktreethathecouldseefromhisofficewindow.

Page 12: Java in easy steps: Covers Java 9

AsthepopularityoftheWorldWideWebgrew,SunrecognizedthatGosling’slanguagecouldbedevelopedfortheinternet.Consequently,Sunrenamedthelanguage“Java”(simplybecausethatnamesoundedcool)andmadeitfreelyavailablein1995.Developersaroundtheworldquicklyadoptedthisexcitingnewlanguageand,becauseofitsmodulardesign,wereabletocreatenewfeaturesthatcouldbeaddedtothecorelanguage.ThemostendearingadditionalfeatureswereretainedinsubsequentreleasesofJavaasitdevelopedintothecomprehensiveversionoftoday.

TheessenceofJavaisalibraryoffilescalled“classes”,whicheachcontainsmallpiecesofready-madeprovencode.Anyoftheseclassescanbeincorporatedintoanewprogram,likebricksinawall,sothatonlyarelativelysmallamountofnewcodeeverneedstobewrittentocompletetheprogram.Thissavestheprogrammeravastamountoftime,andlargelyexplainsthehugepopularityofJavaprogramming.Additionally,thismodulararrangementmakesiteasiertoidentifyanyerrorsthaninasinglelargeprogram.

Javatechnologyisbothaprogramminglanguageandaplatform.InJavaprogramming,thesourcecodeisfirstwrittenashuman-readableplaintextfilesendingwiththe.javaextension.Thesearecompiledintomachine-readable.classfilesbythejavaccompiler.ThejavainterpretercanthenexecutetheprogramwithaninstanceoftheJavaVirtualMachine(JavaVM):

Page 13: Java in easy steps: Covers Java 9

TheNewiconpicturedaboveindicatesaneworenhancedfeatureintroducedwiththelatestversionofJava.

AstheJavaVMisavailableonmanydifferentoperatingsystems,thesame.classfilesarecapableofrunningonWindows,LinuxandMacoperatingsystems–soJavaprogrammerstheoreticallyenjoythecross-platformabilityto“writeonce,runanywhere”.

InordertocreateJavaprograms,theJavaclasslibrariesandthejavaccompilerneedtobeinstalledonyourcomputer.InordertorunJavaprograms,theJava™RuntimeEnvironment(JRE)needstobeinstalledtosupplythejavainterpreter.AllofthesecomponentsarecontainedinafreelyavailablepackagecalledtheJava™Platform,StandardEditionDevelopmentKit(JDK).

TheJavaprogramsinthisbookuseversionJDK9,whichincorporatesboththeDevelopmentKititselfandtheRuntimeEnvironment,andcanbedownloadedfromtheOracle®websiteatwww.oracle.com/technetwork/java/javase/downloads

Page 14: Java in easy steps: Covers Java 9

TheOracledownloadpagealsofeaturesotherpackages,butonlytheJDK9packageisrequiredtogetstartedwithJavaprogramming.

TheJDK9packageisavailableinversionsfor32-bitand64-bitvariantsoftheLinux,Mac,SolarisandWindowsplatforms–accepttheOracleLicenseAgreement,thenselecttheappropriateversionforyourcomputertodownloadtheJavaDevelopmentKit.

ThereisnotruthintherumorthatJAVAstandsfor“JustAnotherVagueAcronym”.

Page 15: Java in easy steps: Covers Java 9

InstallingtheJDKSelecttheappropriateJavaDevelopmentKit(JDK)packageforyoursystemfromtheOracle®downloadspage,andthenfollowthesestepstoinstallJavaonyourcomputer:

UninstallanypreviousversionsoftheJDKand/orJavaRuntimeEnvironment(JRE)fromyoursystem

StarttheinstallationandaccepttheLicenseAgreementWhenthe“CustomSetup”dialogappears,eitheracceptthesuggestedinstallationlocationorclicktheChangebuttontochooseyourpreferredlocation–suchasC:\JavaforWindowssystemsorusrJavaforLinuxsystems

EnsurethatthePublicJREandDevelopmentToolsfeaturesareselectedfromthelist.Optionally,youmaydeselecttheotherfeaturesastheyarenotrequiredtostartprogrammingwiththisbook

ClicktheNextbuttontoinstallallthenecessaryJavaclasslibrariesandtoolsatthechosenlocation

Page 16: Java in easy steps: Covers Java 9

ApreviousversionoftheJREmaybeinstalledsoyourwebbrowsercanrunJavaapplets.ItisbesttouninstallthistoavoidconfusionwiththenewerversioninJDK9.

Youcanstartoutbyinstallingjusttheminimumfeaturestoavoidconfusion.

ThetoolstocompileandrunJavaprogramsarenormallyoperatedfromacommand-linepromptandarelocatedinthebinsub-directoryoftheJavadirectory.Theycanbemadeavailablesystem-widebyaddingtheirlocationtothesystempath:

• OnWindows,navigatethroughControlPanel,System,AdvancedSystemSettings,Advancedtab,EnvironmentVariables,thenselectthesystemvariablenamed“Path”.ClicktheEditbuttonandaddtheaddressofJava’sbinssub-directorytothelist(e.g.C:\Java\bin),thenclickOKtoapplythechange.

• OnLinux,addthelocationofJava’sbinsub-directorytothesystempathbyeditingthe.bashrcfileinyourhomedirectory.Forinstance,addPATH=$PATH:usrJava/binthensavethefile.

PathsthatcontainspacesmustbeenclosedwithindoublequotesandterminatedbyasemicolononolderversionsofWindows.Forexample,withthepath“C:\ProgramFiles\Java\jdk-9\bin”;

Youarenowabletotesttheenvironment:

Page 17: Java in easy steps: Covers Java 9

Youarenowabletotesttheenvironment:

Openacommand-linepromptwindow,suchasWindowsPowerShellorLinuxTerminalTypethecommandjava-versionthenhittheEnterkeytoseetheJavainterpreter’sversionnumberNext,typethecommandjavac-versionthenhittheEnterkeytoseetheJavacompiler’sversionnumberNow,typethecommandjshell-versionthenhittheEnterkeytoseetheJavashellversionnumberEnsurethatallversionnumbersmatch(9),andyou’rereadytobeginJavaprogramming

Ifthe.bashrcfileisnotvisibleinyourLinuxhomedirectorychooseView,ShowHiddenFilestorevealit.

TheJavashelljshellisanewfeatureinJava9.Thisinteractivetoolletsyouquicklytestsnippetsofcode,withouttheneedtofirstcompilethecode.Itisusedinthenextchaptertodemonstratethevarious“operators”availableinJavaprogramming.

Page 18: Java in easy steps: Covers Java 9

WritingafirstJavaprogramAllJavaprogramsstartastextfilesthatarelaterusedtocreate“class”files,whicharetheactualrunnableprograms.ThismeansthatJavaprogramscanbewritteninanyplaintexteditor,suchastheWindowsNotepadapplication.

FollowthesestepstocreateasimpleJavaprogramthatwilloutputthetraditionalfirstprogramgreeting:

Hello.java

Openaplaintexteditor,likeNotepad,andtypethiscodeexactlyasitislisted–tocreateaclassnamed“Hello”classHello

{

}

BetweenthecurlybracketsoftheHelloclass,insertthiscode–tocreatea“main”methodfortheHelloclasspublicstaticvoidmain(String[]args)

{

}

Betweenthecurlybracketsofthemainmethod,insertthislineofcode–statingwhattheprogramwilldoSystem.out.println(“HelloWorld!”);

Savethefileatanyconvenientlocation,butbesuretonameitpreciselyasHello.java–thecompleteprogramshouldnowlooklikethis:

Page 19: Java in easy steps: Covers Java 9

Javaisacase-sensitivelanguagewhere“Hello”and“hello”aredistinctlydifferent–traditionally,Javaprogramnamesshouldalwaysbeginwithanuppercaseletter.

Javaprogramsarealwayssavedastheirexactprogramnamefollowedbythe“.java”extension.

Theseparatepartsoftheprogramcodeontheoppositepagecanbeexaminedindividuallytounderstandeachpartmoreclearly:

TheProgramContainer

classHello{}

Theprogramnameisdeclaredfollowingtheclasskeyword,andfollowedbyapairofcurlybrackets.AlloftheprogramcodethatdefinestheHelloclasswillbecontainedwithinthesecurlybrackets.

Page 20: Java in easy steps: Covers Java 9

Allstand-aloneJavaprogramsmusthaveamainmethod.Javaappletsaredifferent,andtheirformatisexplainedlater.

TheMainMethod

publicstaticvoidmain(String[]args){}

Thisfearsome-lookinglineisthestandardcodethatisusedtodefinethestartingpointofnearlyallJavaprograms.Itwillbeusedinmostexamplesthroughoutthisbookexactlyasitappearsabove–soitmaybeusefultomemorizeit.

Thecodedeclaresamethodnamed“main”thatwillcontaintheactualprograminstructionswithinitscurlybrackets.

Keywordspublicstaticvoidprecedethemethodnametodefinehowthemethodmaybeused,andareexplainedindetaillater.

Thecode(String[]args)isusefulwhenpassingvaluestothemethod,andisalsofullyexplainedlaterinthisbook.

TheStatement

System.out.println(“HelloWorld!”);

Statementsareactualinstructionstoperformprogramtasks,andmustalwaysendwithasemicolon.Amethodmaycontainmanystatementsinsideitscurlybracketstoforma“statementblock”definingaseriesoftaskstoperform,buthereasinglestatementinstructstheprogramtooutputalineoftext.

Turntoheretodiscoverhowtocompileandrunthisprogram.

Createa“MyJava”directoryinwhichtosaveallyourJavaprogramfiles.OnWindowsusethe

Page 21: Java in easy steps: Covers Java 9

Compiling&runningprogramsBeforeaJavaprogramcanrun,itmustfirstbecompiledintoaclassfilebytheJavacompiler.ThisislocatedinJava’sbinsub-directory,andisanapplicationnamedjavac.Theinstructionsheredescribedhowtoaddthebinsub-directorytothesystempathsothatjavaccanbeinvokedfromanysystemlocation.

Followthesestepstocompiletheprogramhere:

Openacommand-linewindow,thennavigatetothedirectorywhereyousavedtheHello.javasourcecodefileTypejavacfollowedbyaspacethenthefullnameofthesourcecodefileHello.javaandhittheEnterkey

OnWindowsusetheWindowsPowerShellapportheolderCommandPromptapptoprovideacommand-lineprompt,andonLinuxuseaTerminalwindow.

AtaprompttypejavacandhitReturntorevealtheJavacompileroptions.

Ifthejavaccompilerdiscoverserrorsinthecodeitwillhaltanddisplayahelpful

Page 22: Java in easy steps: Covers Java 9

reportindicatingthenatureoftheerror–seeherefortroubleshootingproblems.

Ifthejavaccompilerdoesnotfindanyerrorsitwillcreateanewfilewiththeprogramnameandthe.classfileextension.

Youcanalsocompilethesourcecodefromanotherlocationifyoustatethefile’sfullpathaddresstothejavaccompiler–inthiscase,C:\MyJava\Hello.java

WhentheJavacompilercompletescompilation,thecommand-linepromptwindowfocusreturnstothepromptwithoutanyconfirmationmessage–andtheprogramisreadytorun.

TheJavaprograminterpreterisanapplicationnamedjavathatislocatedinJava’sbinsub-directory–alongsidethejavaccompiler.Asthisdirectorywaspreviouslyaddedtothesystempath,here,thejavainterpretercanbeinvokedfromanylocation.

Followthesestepstoruntheprogramthatwascompiledusingtheproceduredescribedonthepageopposite:

Openacommand-linepromptwindow,thennavigatetothedirectorywheretheHello.classprogramfileislocatedAttheprompt,typejavafollowedbyaspacethentheprogramnameHelloandhittheEnterkey

Page 23: Java in easy steps: Covers Java 9

Donotincludethe.classextensionwhenrunningaprogram–onlyusetheprogramname.

TheHelloprogramrunsandexecutesthetaskdefinedinthestatementwithinitsmainmethod–tooutput“HelloWorld!”.Uponcompletion,focusreturnstothepromptoncemore.

TheprocessofcompilingandrunningaJavaprogramistypicallycombinedinsequentialsteps,andisthesameregardlessofplatform.ThescreenshotbelowillustratestheHelloprogrambeingcompiledandrunincombinedstepsonaLinuxsystem:

Page 24: Java in easy steps: Covers Java 9

CreatingavariableInJavaprogramming,a“variable”issimplyausefulcontainerinwhichavaluemaybestoredforsubsequentusebytheprogram.Thestoredvaluemaybechanged(vary)astheprogramexecutesitsinstructions–hencetheterm“variable”.

Avariableiscreatedbywritingavariable“declaration”intheprogram,specifyingthetypeofdatathatvariablemaycontainandagivennameforthatvariable.Forexample,theStringdatatypecanbespecifiedtoallowavariablenamed“message”tocontainregulartextwiththisdeclaration:Stringmessage;

Variablenamesarechosenbytheprogrammerbutmustadheretocertainnamingconventions.Thevariablenamemayonlybeginwithaletter,dollarsign$,ortheunderscorecharacter_,andmaysubsequentlyhaveonlyletters,digits,dollarsigns,orunderscorecharacters.Namesarecase-sensitive,so“var”and“Var”aredistinctlydifferentnames,andspacesarenotallowedinnames.

VariablenamesshouldalsoavoidtheJavakeywordslistedinthetablebelow,asthesehavespecialmeaningintheJavalanguage.

abstract default goto package synchronized

assert do if private this

boolean double implements protected throw

break else import public throws

byte enum instanceof return transient

Page 25: Java in easy steps: Covers Java 9

case extends int short true

catch false interface static try

char final long strictfp void

class finally native String volatile

const float new super while

continue for null switch

Eachvariabledeclarationmustbeterminatedwithasemicoloncharacter–likeallotherstatements.

Strictlyspeaking,somewordsinthistablearenotactuallykeywords–true,false,andnullareallliterals;Stringisaspecialclassname;constandgotoarereservedwords(currentlyunused).Theseareincludedinthetablebecausetheymustalsobeavoidedwhennamingvariables.

Asgoodpractice,variablesshouldbenamedwithwordsoreasilyrecognizableabbreviations,describingthatvariable’spurpose.Forexample,“button1”or“btn1”todescribebuttonnumberone.Lowercaselettersarepreferredforsingle-wordnames,suchas“gear”,andnamesthatconsistofmultiplewordsshouldcapitalizethefirstletterofeachsubsequentword,suchas“gearRatio”–theso-called“camelCase”namingconvention.

Onceavariablehasbeendeclared,itmaybeassignedaninitialvalueoftheappropriatedatatypeusingtheequalssign=,eitherinthedeclarationorlateronintheprogram,thenitsvaluecanbereferencedatanytimeusingthevariable’sname.

Followthesestepstocreateaprogramthatdeclaresavariable,whichgets

Page 26: Java in easy steps: Covers Java 9

Followthesestepstocreateaprogramthatdeclaresavariable,whichgetsinitializedinitsdeclarationthenchangedlater:

Startanewprogramnamed“FirstVariable”,containingthestandardmainmethodclassFirstVariable

{

publicstaticvoidmain(String[]args){}

}

FirstVariable.java

Betweenthecurlybracketsofthemainmethod,insertthiscodetocreate,initialize,andoutputavariableStringmessage=“Initialvalue”;System.out.println(message);

Addtheselinestomodifyandoutputthevariablevaluemessage=“Modifiedvalue”;System.out.println(message);

SavetheprogramasFirstVariable.java,thencompileandruntheprogram

Ifyouencounterproblemscompilingorrunningtheprogram,youcanget

Page 27: Java in easy steps: Covers Java 9

helpfromTroubleshootingproblemshere.

Page 28: Java in easy steps: Covers Java 9

RecognizingdatatypesThemostfrequently-useddatatypesinJavavariabledeclarationsarelistedinthistable,alongwithabriefdescription:

Datatype: Description: Example:

char AsingleUnicodecharacter ‘a’

String AnynumberofUnicodecharacters “myString”

int Anintegernumber,from-2.14billionto+2.14billion 1000

float Afloating-pointnumber,withadecimalpoint 3.14159265f

boolean Alogicalvalueofeithertrueorfalse true

Duetotheirregularitiesoffloating-pointarithmeticthefloatdatatypeshouldneverbeusedforprecisevalues,suchascurrency–seeherefordetails.

Noticethatchardatavaluesmustalwaysbesurroundedbysinglequotes,andStringdatavaluesmustalwaysbesurroundedbydoublequotes.Also,rememberthatfloatdatavaluesmustalwayshavean“f”suffixtoensuretheyaretreatedasafloatvalue.

Inadditiontothemorecommondatatypesabove,Javaprovidesthesespecializeddatatypesforuseinexactingcircumstances:

Datatype: Description:

byte Integernumberfrom-128to+127

short Integernumberfrom-32,768to+32,767

Page 29: Java in easy steps: Covers Java 9

long Positiveornegativeintegerexceeding2.14billion

double Extremelylongfloating-pointnumber

AlldatatypekeywordsbeginwithalowercaseletterexceptString–whichisaspecialclass.

SpecializeddatatypesareusefulinadvancedJavaprograms–theexamplesinthisbookmostlyusethecommondatatypesdescribedinthetoptable.

FollowthesestepstocreateaJavaprogramthatcreates,initializes,andoutputsvariablesofallfivecommondatatypes:

Startanewprogramnamed“DataTypes”containingthestandardmainmethodclassDataTypes

{

publicstaticvoidmain(String[]args){}

}

DataTypes.java

Betweenthecurlybracketsofthemainmethod,insertthesedeclarationstocreateandinitializefivevariablescharletter=‘M’;Stringtitle=“Javaineasysteps”;intnumber=365;floatdecimal=98.6f;booleanresult=true;

AddtheselinestooutputanappropriatetextStringconcatenatedtothe

Page 30: Java in easy steps: Covers Java 9

valueofeachvariableSystem.out.println(“Initialis”+letter);System.out.println(“Bookis”+title);System.out.println(“Daysare”+number);System.out.println(“Temperatureis”+decimal);System.out.println(“Answeris”+result);

SavetheprogramasDataTypes.java,thencompileandruntheprogram

Noticehowthe+characterisusedheretojoin(concatenate)textstringsandstoredvariablevalues.

TheJavacompilerwillreportanerroriftheprogramattemptstoassignavalueofthewrongdatatypetoavariable–trychangingthevaluesinthisexample,thenattempttorecompiletheprogramtoseetheeffect.

.

Page 31: Java in easy steps: Covers Java 9

CreatingconstantsThe“final”keywordisamodifierthatcanbeusedwhendeclaringvariablestopreventanysubsequentchangestothevaluesthatareinitiallyassignedtothem.Thisisusefulwhenstoringafixedvalueinaprogramtoavoiditbecomingalteredaccidentally.

Variablescreatedtostorefixedvaluesinthiswayareknownas“constants”,anditisconventiontonameconstantswithalluppercasecharacters–todistinguishthemfromregularvariables.Programsthatattempttochangeaconstantvaluewillnotcompile,andthejavaccompilerwillgenerateanerrormessage.

FollowthesestepstocreateaJavaprogramfeaturingconstants:

Startanewprogramnamed“Constants”containingthestandardmainmethodclassConstants

{

publicstaticvoidmain(String[]args){}

}

Constants.java

Betweenthecurlybracketsofthemainmethod,insertthiscodetocreateandinitializethreeintegerconstantsfinalintTOUCHDOWN=6;finalintCONVERSION=1;finalintFIELDGOAL=3;

Now,declarefourregularintegervariablesinttd,pat,fg,total;

Initializetheregularvariables–usingmultiplesoftheconstantvaluestd=

Page 32: Java in easy steps: Covers Java 9

4*TOUCHDOWN;pat=3*CONVERSION;fg=2*FIELDGOAL;total=(td+pat+fg);

AddthislinetodisplaythetotalscoreSystem.out.println(“Score:”+total);

SavetheprogramasConstants.java,thencompileandruntheprogramtoseetheoutput,Score:33(4x6=24,3x1=3,2x3=6,so24+3+6=33).

The*asteriskcharacterisusedheretomultiplytheconstantvalues,andparenthesessurroundtheiradditionforclarity

Page 33: Java in easy steps: Covers Java 9

AddingcommentsWhenprogramminginanylanguage,itisgoodpracticetoaddcommentstoprogramcodetoexplaineachparticularsection.Thismakesthecodemoreeasilyunderstoodbyothers,andbyyourself,whenrevisitingapieceofcodeafteraperiodofabsence.

InJavaprogramming,commentscanbeaddedacrossmultiplelinesbetween/*and*/commentidentifiers,oronasinglelineaftera//commentidentifier.Anythingappearingbetween/*and*/,oronalineafter//,iscompletelyignoredbythejavaccompiler.

WhencommentshavebeenaddedtotheConstants.javaprogram,described

opposite,thesourcecodemightlooklikethis:

Constants.java(commented)

/*

Aprogramtodemonstrateconstantvariables.

*/

classConstants

{

publicstaticvoidmain(Stringargs[])

{

//Constantscorevalues.finalintTOUCHDOWN=6;finalintCONVERSION=1;finalintFIELDGOAL=3;

//Calculatepointsscored.

Page 34: Java in easy steps: Covers Java 9

inttd,pat,fg,total;td=4*TOUCHDOWN;//4x6=24pat=3*CONVERSION;//3x1=3fg=2*FIELDGOAL;//2x3=6total=(td+pat+fg);//24+3+6=33

//Outputcalculatedtotal.System.out.println(“Score:“+total);

}

}

Savedwithcomments,theprogramcompilesandrunsasnormal:

Youcanaddastatementthatattemptstochangethevalueofaconstant,thentrytorecompiletheprogramtoseetheresultingerrormessage.

Page 35: Java in easy steps: Covers Java 9

TroubleshootingproblemsSometimes,thejavaccompilerorjavainterpreterwillcomplainabouterrors,soit’susefultounderstandtheircauseandhowtoquicklyresolvetheproblem.Inordertodemonstratesomecommonerrorreports,thiscodecontainssomedeliberateerrors:

Test.java

classtest

{

publicstaticvoidmain(String[]args)

{

Stringtext;System.out.println(“Test”+text)

}

}

AfirstattempttocompileTest.javathrowsupthiserrorreport:

• Cause–thejavaccompilercannotbefound.

• Solution–editthesystemPATHvariable,asdescribedhere,oruseitsfull

Page 36: Java in easy steps: Covers Java 9

pathaddresstoinvokethecompiler.

Thepathaddressmustbeenclosedwithinquotationmarksifitcontainsanyspaces,suchasthepathaddress“C:\ProgramFiles\Java”.

• Cause–thefileTest.javacannotbefound.

• Solution–navigatetothedirectorywherethefileislocated,orusethefullpathaddresstothefileinthecommand.

• Cause–thestatementisnotterminatedcorrectly.

• Solution–inthesourcecodeaddasemicolonattheendofthestatement,thensavethefiletoapplythechange.

• Cause–theprogramnameandclassnamedonotmatch.

• Solution–inthesourcecodechangetheclassnamefromtesttoTest,thensavethefiletoapplythechange.

Page 37: Java in easy steps: Covers Java 9

• Cause–thevariabletexthasnovalue.

• Solution–inthevariabledeclarationassignthevariableavalidStringvalue,forinstance=“success”,thensavethefile.

Youmustruntheprogramfromwithinitsdirectory–youcannotuseapathaddressastheJavalauncherrequiresaprogramname,notafilename.

Page 38: Java in easy steps: Covers Java 9

Summary• Javaisbothaprogramminglanguageandaruntimeplatform.

• Javaprogramsarewrittenasplaintextfileswitha.javafileextension.

• TheJavacompilerjavaccreatescompiled.classprogramfilesfromoriginal.javasourcecodefiles.

• TheJavainterpreterjavaexecutescompiledprogramsusinganinstanceoftheJavaVirtualMachine.

• TheJavaVMisavailableonmanyoperatingsystemplatforms.

• AddingJava’sbinsub-directorytothesystemPATHvariableallowsthejavaccompilertobeinvokedfromanywhere.

• Javaisacase-sensitivelanguage.

• ThestandardmainmethodistheentrypointforJavaprograms.

• TheSystem.out.println()statementoutputstext.

• AJavaprogramfilenamemustexactlymatchitsclassname.

• Javavariablescanonlybenamedinaccordancewithspecifiednamingconventions,andmustavoidtheJavakeywords.

• InJavaprogramming,eachstatementmustbeterminatedbyasemicoloncharacter.

• ThemostcommonJavadatatypesareString,int,char,floatandboolean.

• Stringvaluesmustbeenclosedindoublequotes;charvaluesinsinglequotes;andfloatvaluesmusthavean“f”suffix.

• Thefinalkeywordcanbeusedtocreateaconstantvariable.

• CommentscanbeaddedtoJavasourcecodebetween/*and*/,ononeormorelines,orafter//onasingleline.

• Errorreportsidentifycompilerandruntimeproblems.

Page 39: Java in easy steps: Covers Java 9

2

Performingoperations

ThischapterdemonstratesthevariousoperatorsthatareusedtocreateexpressionsinJavaprograms.

DoingarithmeticAssigningvalues

ComparingvaluesAssessinglogicExaminingconditionsSettingprecedence

EscapingliteralsWorkingwithbitsSummary

Doingarithmetic

Arithmeticaloperators,listedinthetablebelow,areusedtocreateexpressionsinJavaprogramsthatreturnasingleresultingvalue.Forexample,theexpression4*2returnsthevalue8.

Operator: Operation:

+Addition(andconcatenatesStringvalues)

-Subtraction

Page 40: Java in easy steps: Covers Java 9

-

*Multiplication

/Division

%Modulus

++Increment

--Decrement

Divisionofintvalueswilltruncateanyfractionalpart.Forexample,11/4=2,whereasdivisionoffloatvalues11/4=2.75.

Theincrementoperator++anddecrementoperator--returntheresultofmodifyingasinglegivenoperandbyavalueofone.Forexample,4++returnsthevalue5,and4--returnsthevalue3.

Allotherarithmeticoperatorsreturntheresultofanoperationperformedontwogivenoperands,andactasyouwouldexpect.Forexample,theexpression5+2returns7.

Themodulusoperatordividesthefirstoperandbythesecondoperandandreturnstheremainderoftheoperation.Forexample,32%5returns2–fivedividesinto32sixtimes,with2remainder.

Theoperationperformedbytheadditionoperator+dependsonthetypeofitsgivenoperands.Wherebothoperandsarenumericvaluesitwillreturnthetotalsumvalueofthosenumbers,butwheretheoperandsareStringvaluesitwillreturnasingleconcatenatedString–combiningthetextineachStringoperand.

Page 41: Java in easy steps: Covers Java 9

Forexample,“Java”+“Arithmetic”returns“JavaArithmetic”.

Incrementanddecrementoperatorsaretypicallyusedtocounttheiterationsintheforloopconstructs,introducedhere.

FollowthesestepstoexploretheJavaarithmeticoperatorsintheJavashell:

Openacommand-linepromptwindow,thentypejshellandhittheEnterkeytolaunchtheJavashellNext,enterstatementstoinitializethreevariablesintnum=100;intfactor=20;intsum=0;

Next,separatelyenterstatementstoperformadditionandsubtractionoperations,displayingeachresultsum=num+factor;sum=num-factor;

Now,separatelyenterstatementstoperformmultiplicationanddivisionoperations,displayingeachresultsum=num*factor;sum=num/factor;

Page 42: Java in easy steps: Covers Java 9

JavamustbeinstalledonyoursystempathtolaunchtheJavashellfromanyprompt–seeInstallinghereandTroubleshootingherefordetails.

TheJavashelljshellisanewfeatureinJava9.Optionally,thesemicoloncharactermaybeomittedattheendofsinglestatementsenteredintotheshellbutthesearerequiredwhenwritingJavaprogramsforcompilation.Semicolonsareincludedintheshellexamplesinthischaptertoaidcodeconsistency.

Assigningvalues

Assignmentoperators,listedinthetablebelow,areusedtoassigntheresultofanexpression.Allexceptthesimple=operatoraretheshorthandformofalongerequivalentexpression:

Operator: Example: Equivalent:

=a=b a=b

+=a+=b a=a+b

Page 43: Java in easy steps: Covers Java 9

-= a-=b a=a-b

*=a*=b a=a*b

/=a/=b a=a/b

%=a%=b a=a%b

Itisimportanttoregardthe=operatortomean“assign”,ratherthan“equals”,toavoidconfusionwiththe==equalityoperator.

Intheexamplea=b,thevaluestoredinthevariablenamedbisassignedtothevariablenameda,sothatvaluebecomesthenewvaluestoredina–replacinganyvalueitpreviouslycontained.

The+=operatorisusefultoaddavalueontoanexistingvaluestoredinavariable–keepinga“runningtotal”.

Theexamplea+=bfirstcalculatesthesumtotalofthevaluesstoredinthevariablesnamedaandb,thenassignstheresultingtotaltovariablea.Aprogrammightthencontainafurtherassignmenta+=cthatcalculatesthetotalstoredinvariablesnamedaandc,thenassignsthatnewtotaltovariablea–addingthevalueofctothevalueitpreviouslycontained.

Alltheotherassignmentoperatorsworkinthesamewaybyfirstperformingthearithmeticalcalculationonthetwostoredvalues,thenassigningtheresulttothefirstvariable–tobecomeitsnewstoredvalue.

The==equalityoperatorcomparesvalues,andisfullyexplainedhere.

FollowthesestepstoexploretheJavaassignmentoperatorsintheJavashell:

Openacommand-linepromptwindow,thentypejshellandhittheEnterkeyto

Page 44: Java in easy steps: Covers Java 9

launchtheJavashellNext,enterstatementstoinitializetwoStringvariablesStringtxt=“Super”;Stringlang=“Java”;

Now,separatelyenterstatementstoaddandassignaStringvalue,thendisplaytheconcatenatedstringresulttxt+=lang;txt;

Then,enterstatementstoinitializetwointegervariablesintsum=10;intnum=20;

Separatelyenterstatementstoaddandassignanintvalue,thendisplaythetotaledintegerresultsum+=num;sum;

ThenewJavashellfeature,introducedinJava9,createsinternal$-prefixednumberedvariablescontainingtheresultofanevaluation.Here,internalvariables$3and$7containevaluationresults.

Page 45: Java in easy steps: Covers Java 9

Assignmentofthewrongdatatypetoavariablewillcauseanerror.

Comparingvalues

Comparisonoperators,listedinthetablebelow,areusedtocomparetwovaluesinanexpressionandreturnasingleBooleanvalueoftrueorfalse–describingtheresultofthatcomparison.

Operator: Comparison:

==Equality

!=Inequality

> Greaterthan

>= Greaterthan,orequalto

< Lessthan

<= Lessthan,orequalto

The==equalityoperatorcomparestwooperands,andwillreturntrueifbothareexactlyequalinvalue.Ifbotharethesamenumbertheyareequal,orifbothareStringvaluescontainingthesamecharactersinthesameordertheyareequal.Booleanoperandsthatarebothtrue,orthatarebothfalse,areequal.

Conversely,the!=inequalityoperatorreturnstrueiftwooperandsarenotequal–applyingthesamerulesastheequalityoperator.

Equalityandinequalityoperatorsareusefulintestingthestateoftwovariablestoperform“conditionalbranching”ofaprogram–proceedingindifferentdirectionsaccordingtothecondition.

The>“greaterthan”operatorcomparestwooperands,andwillreturntrueifthe

Page 46: Java in easy steps: Covers Java 9

firstisgreaterinvaluethanthesecond.

The<“lessthan”operatormakesthesamecomparison,butreturnstrueifthefirstoperandislessinvaluethanthesecond.

Addingthe=assignmentoperatorafterthe>“greaterthan”operator,orafterthe<“lessthan”operator,makesitalsoreturntruewhenthetwooperandsareexactlyequalinvalue.

The<lessthanoperatoristypicallyusedtotestacountervalueinaloop–anexampleofthiscanbefoundhere.

FollowthesestepstoexploretheJavacomparisonoperatorsintheJavashell:

Openacommand-linepromptwindow,thentypejshellandhittheEnterkeytolaunchtheJavashellNext,enterstatementstoinitializetwoStringvariablesStringtxt=“Super”;Stringlang=“Java”;

Now,separatelyenterstatementstoinitializeabooleanvariableanddisplaytheresultofStringvaluecomparisonsforequalityandinequalitybooleanstate=(txt==lang);state=(txt!=lang);

Inasimilarway,separatelyenterthesestatementstodisplaytheresultofintvaluecomparisonsforgreaterandlessnumericvalueintdozen=12;intscore=20;state=(dozen>score);state=(dozen<score);

Page 47: Java in easy steps: Covers Java 9

YoucandiscovermoreoptionswithintheJavashellbyenteringthe/helpcommand.

Hereit’suntrue(false)thattheStringvaluesareequal,butitistruethattheyareunequal.

Noticehowanexpressioncanbecontainedinparenthesesforbetterreadability.

Assessinglogic

Logicaloperators,listedinthetablebelow,areusedtocombinemultipleexpressionsthateachreturnaBooleanvalue–intoacomplexexpressionthatreturnsasingleBooleanvalue.

Page 48: Java in easy steps: Covers Java 9

Operator: Operation:

&& LogicalAND

||LogicalOR

! LogicalNOT

LogicaloperatorsareusedwithoperandsthathavetheBooleanvaluesoftrueorfalse,orvaluesthatcanconverttotrueorfalse.

Thelogical&&ANDoperatorwillevaluatetwooperandsandreturntrueonlyifbothoperandsarethemselvestrue.Otherwise,thelogical&&operatorwillreturnfalse.Thisevaluationcanbeusedinconditionalbranching,whereaprogramwillonlyperformacertainactionwhentwotestedconditionsarebothtrue.

Unlikethelogical&&operatorthatneedstwooperandstobetrue,thelogical||ORoperatorwillevaluateitstwooperandsandreturntrueifeitheroneoftheoperandsistrue–itwillonlyreturnfalsewhenneitheroperandistrue.ThisisusefulinJavaprogrammingtoperformacertainactionwheneitheroneoftwotestconditionshasbeenmet.

Thelogical!NOToperatorisa“unary”operatorthatisusedbeforeasingleoperand.ItreturnstheinverseBooleanvalueofthegivenoperand–reversingtruetofalse,andfalsetotrue.It’susefulinJavaprogramstotogglethevalueofavariableinsuccessiveloopiterationswithastatementlikegoState=!goState.Thisensuresthatoneachpassoftheloopthevalueischanged,likeflickingalightswitchonandoff.

Theterm“Boolean”referstoasystemoflogicalthoughtdevelopedbytheEnglishmathematicianGeorgeBoole(1815-1864).

Page 49: Java in easy steps: Covers Java 9

ThenewJavashellfeature,introducedinJava9,isalsoknownasa“REPL”–anacronymforRead,Evaluate,Print,Loopthatdescribesthistypeofinteractivetool.

FollowthesestepstoexplorelogicaloperatorsintheJavashell:

Openacommand-linepromptwindow,thentypejshellandhittheEnterkeytolaunchtheJavashellNext,enterstatementstoinitializetwobooleanvariablesbooleanyes=true;booleanno=false;

Enterstatementstotestifbothtwoconditionsaretruebooleanresult=(yes&&yes);result=(yes&&no);

Enterstatementstotestifeitheroftwoconditionsistrueresult=(yes||yes);result=(yes||no);

Page 50: Java in easy steps: Covers Java 9

result=(no||no);

Enterstatementstoshowanoriginalandinversevalueresult=yes;result=!yes;

Noticethatfalse&&falsereturnsfalse,nottrue–demonstratingthemaximthat“twowrongsdon’tmakearight”.

Thevaluereturnedbythe!NOTlogicaloperatoristheinverseofthestoredvalue–thestoredvalueitselfremainsunchanged.

Examiningconditions

Possiblytheall-timefavoriteoperatoroftheJavaprogrammeristhe?:conditionaloperatorthatmakesapowerfulstatementveryconcisely.Itsunusualsyntaxcanseemtrickytounderstandatfirst,butitiswellworthgettingtoknowthisusefuloperator.

Page 51: Java in easy steps: Covers Java 9

Theconditionaloperatorfirstevaluatesanexpressionforatrueorfalsevalue,thenreturnsoneoftwogivenoperandsdependingontheresultoftheevaluation.Itssyntaxlookslikethis:

(boolean-expression)?if-true-return-this:if-false-return-this;

Theconditionaloperatorisalsoknownasthe“ternary”operator.

EachspecifiedoperandalternativeallowstheprogramtoprogressaccordingtotheBooleanvaluereturnedbythetestedexpression.Forinstance,thealternativesmightreturnaStringvalue:status=(quit==true)?“Done!”:“Continuing...”;

Inthiscase,whenthequitvariableistruetheconditionaloperatorassignsthevalueofitsfirstoperandtothestatusvariable;otherwise,itassignsitssecondoperandvalueinstead.

AshorthandavailablewhencodingJavaprogramsallowsexpressionstooptionallyomit==truewhenevaluatingasimpleBooleanvalue,sotheexampleabovecanbewrittensimplyas:

status=(quit)?“Done!”:“Continuing...”;

Theconditionaloperatorcanreturnvaluesofanydatatypeandemployanyvalidtestexpression.Forinstance,theexpressionmightusethegreaterthan>operatortoevaluatetwonumericvaluesthenreturnaBooleanvaluedependingontheresult:

busted=(speed>speedLimit)?true:false;

Similarly,theconditionaloperatormightemploytheinequality!=operatortoevaluateaStringvaluethenreturnanumericvaluedependingontheresult:bodyTemperature=(scale!=“Celsius”)?98.6:37.0;

Page 52: Java in easy steps: Covers Java 9

YoucanalsostarttheJavashellwiththecommandjshell--feedbackverbosetoreceivedescriptiveoutputaftereachevaluation.

FollowthesestepstoexploretheJavaconditionaloperatorintheJavashell:

Openacommand-linepromptwindow,thentypejshellandhittheEnterkeytolaunchtheJavashellNext,enterstatementstoinitializetwointvariablesintnum1=1357;intnum2=2468;

DeclareafurthervariabletostoreatestresultStringStringresult;

Enterthisstatementtodeterminewhetherthefirstintegervalueisanoddorevennumberresult=(num1%2!=0)?“Odd”:“Even”;

Now,enterthisstatementtodeterminewhetherthesecondintegervalueisanoddorevennumberresult=(num2%2!=0)?“Odd”:“Even”;

Page 53: Java in easy steps: Covers Java 9

NoticethatanuninitializedStringvariablereturnsaspecialnullvalue–indicatingthatitcontainsnothingwhatsoever.

Here,theexpressionevaluatesastruewhenthereisanyremainder.

Settingprecedence

Complexexpressions,whichcontainmultipleoperatorsandoperands,canbeambiguousunlesstheorderinwhichtheoperationsshouldbeexecutedisclear.Thislackofclaritycaneasilycausedifferentresultstobeimpliedbythesameexpression.Forexample,considerthiscomplexexpression:num=8+4*2;

Workinglefttoright8+4=12,and12*2=24,sonum=24.Butworkingrighttoleft2*4=8,and8+8=16,sonum=16.

TheJavaprogrammercanexplicitlyspecifywhichoperationshouldbeexecutedfirstbyaddingparenthesestosignifywhichoperatorhasprecedence.Inthiscase,(8+4)*2ensuresthattheadditionisperformedbeforethemultiplication–sotheresultis24,not16.Conversely,8+(4*2)performsthemultiplicationfirst–sotheresultis16,not24.

WhereparenthesesdonotexplicitlyspecifyoperatorprecedenceJavafollowsthedefaultprecedenceorderlistedinthetablebelow,fromfirstatthetoptolastatthebottom:

Operator: Description:

++--! Increment,Decrement,LogicalNOT

*/%Multiplication,Division,Modulus

Page 54: Java in easy steps: Covers Java 9

+-Addition,Subtraction

>>=<<= Greaterthan,GreaterthanorequaltoLessthan,Lessthanorequalto

==!=Equality,Inequality

&& LogicalAND

||LogicalOR

?:Conditional

=+=-=*=/=%=Assignment

Operatorsofequalprecedencearehandledintheordertheyappearintheexpression–fromlefttoright.

FollowthesestepstoexploreoperatorprecedenceintheJavashell:

Openacommand-linepromptwindow,thentypejshellandhittheEnterkeytolaunchtheJavashellNext,enterastatementtodisplaytheresultofevaluatinganexpressionthatusesdefaultoperatorprecedenceintsum=32-8+16*2;

Page 55: Java in easy steps: Covers Java 9

Now,enterastatementtodisplaytheresultofevaluatingthesameexpression–butgivingadditionandsubtractionprecedenceovermultiplicationsum=(32-8+16)*2;

Finally,enterastatementtodisplaytheresultofevaluatingthesameexpressiononcemore–butnowwhereoperationprecedenceorderisfirstaddition,thensubtraction,andthenmultiplicationsum=(32-(8+16))*2;

Whereexpressionshavemultiplenestedparentheses,theinnermosttakesprecedence.

Page 56: Java in easy steps: Covers Java 9

Howitworks–Step2...

16x2=32,+24=56

Step3...

24+16=40,x2=80

Step4...

32-24=8,x2=16

ThischapterhassofarusedtheJavashelljshelltoexplorethevariousJavaoperatorsbyevaluatingcodesnippets.EnsuingexampleswillusetheJavacompilerjavacandJavaruntimejavatocreateandexecuteprograms.YoucanquittheJavashelltoreturntoaregularpromptwiththecommand/exit.

Escapingliterals

ThenumericalandtextvaluesinJavaprogramsareknownas“literals”–theyrepresentnothingbutare,literally,whatyousee.

LiteralsarenormallydetachedfromthekeywordsoftheJavalanguage,butwheredoublequotes,orsinglequotes,arerequiredwithinaStringvalueitisnecessarytoindicatethatthequotecharacteristobetreatedliterallytoavoidprematurelyterminatingtheString.Thisiseasilyachievedbyimmediatelyprefixingeachnestedquotecharacterwiththe\escapeoperator.Forexample,includingaquotewithinaStringvariable,likethis:Stringquote=“\”Fortunefavorsthebrave.\”saidVirgil”;

Additionally,the\escapeoperatoroffersavarietyofusefulescapesequencesfor

Page 57: Java in easy steps: Covers Java 9

simpleoutputformatting:

Escape: Description:

\n Newline

\t Tab

\b Backspace

\r Carriagereturn

\f Formfeed

\\Backslash

\’ Singlequotemark

\” Doublequotemark

Singlequotescanbenestedwithindoublequotesasanalternativetoescapingquotecharacters.

The\nnewlineescapesequenceisfrequentlyusedwithinlongStringvaluestodisplaytheoutputonmultiplelines.Similarly,the\ttabescapesequenceisfrequentlyusedtodisplaytheoutputincolumns.Usingacombinationof\nnewlineand\ttabescapesequencesallowstheoutputtobeformattedinbothrowsandcolumns–toresembleatable.

FollowthesestepstocreateaJavaprogramusingescapesequencestoformattheoutput:

Startanewprogramnamed“Escape”containingthestandardmainmethodclassEscape

{

publicstaticvoidmain(String[]args){}

Page 58: Java in easy steps: Covers Java 9

}

Escape.java

Betweenthecurlybracketsofthemainmethod,insertthiscodetobuildaStringcontainingaformattedtabletitleandcolumnheadingsStringheader=“\n\tNEWYORK3-DAYFORECAST:\n”;header+=“\n\tDay\t\tHigh\tLow\tConditions\n”;header+=“\t---\t\t----\t---\t----------\n”;

AddtheselinestobuildaStringcontainingformattedtablecelldataStringforecast=“\tSunday\t\t68F\t48F\tSunny\n”;forecast+=“\tMonday\t\t69F\t57F\tSunny\n”;forecast+=“\tTuesday\t\t71F\t50F\tCloudy\n”;

Now,addthislinetooutputbothformattedStringvaluesSystem.out.print(header+forecast);

SavetheprogramasEscape.java,thencompileandruntheprogram

Page 59: Java in easy steps: Covers Java 9

Inthiscase,escapesequencesaddnewlinessotheprint()methodisusedhere–ratherthantheprintln()methodthatautomaticallyaddsanewlineafteroutput.

Workingwithbits

Inadditiontotheregularoperatorsdescribedearlierinthischapter,Javaprovidesspecialoperatorsforbinaryarithmetic.Thesearelesscommonlyusedthanotheroperators,butarebrieflydiscussedheretosimplyprovideanawarenessoftheirexistence.

TheJava“bitwise”operatorscanbeusedwiththeintintegerdatatypetomanipulatethebitsofthebinaryrepresentationofavalue.Thisrequiresanunderstandingofbinarynumbering,whereeightbitsinabyterepresentdecimalvalueszeroto255.Forexample,53isbinary00110101(0x128,0x64,1x32,1x16,0x8,1x4,0x2,1x1).

Binaryadditionoperationsareperformedlikedecimalarithmetic:

53=

00110101

+7

=00000111

60=

00111100

Thebitwiseoperators,listedbelow,allowmorespecializedoperationstobeperformedinbinaryarithmetic.

Operator: Operation: Example: Result:

& AND a&b 1ifbothbitsare1

|OR a|b 1ifeitherbitis1

Page 60: Java in easy steps: Covers Java 9

^XOR a^b 1ifbothbitsdiffer

~NOT ~a Invertsthebits

<< Leftshift n<<p Movesnbitspleft

>> Rightshift n>>p Movesnbitspright

Forexample,usingthebitwise&operatorinbinaryarithmetic:

53=

00110101

& 7=

00000111

5=

00000101

Don’tconfusethelogicalANDoperator&&withthebitwise&operator,orthelogicalORoperator||withthebitwise|operator.

Acommonuseofbitwiseoperatorscombinesseveralvaluesinasinglevariableforefficiency.Forinstance,aprogramwitheight“flag”intvariables,withvaluesof1or0(representingonandoffstates),requires32bitsofmemoryforeachvariable–256bitsintotal.Thesevaluesonlyreallyrequireasinglebit,however,soeightflagscanbecombinedinasinglebytevariable–usingonebitperflag.Thestatusofeachflagcanberetrievedwithbitwiseoperations:

Startanewprogramnamed“Bitwise”containingthestandardmainmethodclassBitwise

Page 61: Java in easy steps: Covers Java 9

{

publicstaticvoidmain(String[]args){}

}

Bitwise.java

Betweenthecurlybracketsofthemainmethod,insertthiscodetodeclareandinitializeabytevariablewithavaluerepresentingthetotalstatusofuptoeightflagsbytefs=53;//Combinedflagstatusof00110101

AddtheselinestoretrievethestatusofeachflagSystem.out.println(“Flag1:“+(((fs&1)>0)?“ON”:“off”));System.out.println(“Flag2:“+(((fs&2)>0)?“ON”:“off”));System.out.println(“Flag3:“+(((fs&4)>0)?“ON”:“off”));System.out.println(“Flag4:“+(((fs&8)>0)?“ON”:“off”));System.out.println(“Flag5:“+(((fs&16)>0)?“ON”:“off”));System.out.println(“Flag6:“+(((fs&32)>0)?“ON”:“off”));System.out.println(“Flag7:“+(((fs&64)>0)?“ON”:“off”));System.out.println(“Flag8:“+(((fs&128)>0)?“ON”:“off”));

SavetheprogramasBitwise.javathencompileandruntheprogram:

Page 62: Java in easy steps: Covers Java 9

Howitworks–Thebinaryrepresentationof53is00110101sothesetbitsare...1+4+16+32=53

Here,thebitwise&operationreturnsoneorzerotodetermineeachflag’sstatus.

Summary

• Arithmeticaloperatorscanformexpressionswithtwooperandsforaddition+,subtraction–,multiplication*,division/,ormodulus%.

• Increment++anddecrement--operatorsmodifyasingleoperandbyavalueofone.

• Theassignment=operatorcanbecombinedwithanarithmeticaloperatortoperformanarithmeticalcalculationthenassignitsresult.

• Comparisonoperatorscanformexpressionscomparingtwooperandsforequality==,inequality!=,greater>,orlesser<values.

• Theassignment=operatorcanbecombinedwiththegreaterthan>orlesserthan<operatortoalsoreturntruewhenequal.

• Logical&&and||operatorsformexpressionsevaluatingtwooperandstoreturnaBooleanvalueofeithertrueorfalse.

• Thelogical!operatorreturnstheinverseBooleanvalueofasingleoperand.

• Aconditional?:operatorevaluatesagivenBooleanexpressionandreturnsoneoftwooperands,dependingonitsresult.

• ExpressionsevaluatingaBooleanexpressionforatruevaluemayoptionally

Page 63: Java in easy steps: Covers Java 9

omit==true.

• Itisimportanttoexplicitlysetoperatorprecedenceincomplexexpressionsbyaddingparentheses().

• Thebackslashescape\operatorcanbeusedtoprefixquotecharacterswithinStringvaluestopreventsyntaxerrors.

• Escapesequences\nnewlineand\ttabprovidesimpleoutputformatting.

• Bitwiseoperatorscanbeusefultoperformbinaryarithmeticinspecializedsituations.

Page 64: Java in easy steps: Covers Java 9

3

Makingstatements

ThischapterdemonstratesthevariouskeywordsthatareusedtocreatebranchinginJavaprograms.

BranchingwithifBranchingalternatives

SwitchingbranchesLoopingforLoopingwhiletrueDoingdo-whileloops

BreakingoutofloopsReturningcontrolSummary

Branchingwithif

TheifkeywordperformsaconditionaltesttoevaluateanexpressionforaBooleanvalue.Astatementfollowingtheexpressionwillonlybeexecutedwhentheevaluationistrue,otherwisetheprogramproceedsontosubsequentcode–pursuingthenext“branch”.Theifstatementsyntaxlookslikethis:

Page 65: Java in easy steps: Covers Java 9

if(test-expression)code-to-be-executed-when-true;Thecodetobeexecutedcancontainmultiplestatementsiftheyareenclosedwithincurlybracketstoforma“statementblock”:

Startanewprogramnamed“If”containingthestandardmainmethodclassIf

{

publicstaticvoidmain(String[]args){}

}

If.java

Betweenthecurlybracketsofthemainmethod,insertthissimpleconditionaltestthatexecutesasinglestatementwhenonenumberisgreaterthananotherif(5>1)System.out.println(“Fiveisgreaterthanone.”);

Addasecondconditionaltest,whichexecutesanentirestatementblockwhenonenumberislessthananotherif(2<4)

{

System.out.println(“Twoislessthanfour.”);System.out.println(“Testsucceeded.”);

}

SavetheprogramasIf.javathencompileandruntheprogramtoseeallstatementsgetexecuted–becausebothtestsevaluateastrueinthiscase:

Page 66: Java in easy steps: Covers Java 9

Expressionscanutilizethetrueandfalsekeywords.Thetestexpression(2<4)isshorthandfor(2<4==true).

AconditionaltestcanalsoevaluateacomplexexpressiontotestmultipleconditionsforaBooleanvalue.Parenthesesencloseeachtestconditiontoestablishprecedence–sotheygetevaluatedfirst.TheBoolean&&ANDoperatorensuresthecomplexexpressionwillonlyreturntruewhenbothtestedconditionsaretrue:if((test-condition1)&&(test-condition2))execute-this-code;TheBoolean||ORoperatorensuresacomplexexpressionwillonlyreturntruewheneitheroneofthetestedconditionsistrue:if((test-condition1)||(test-condition2))execute-this-code;Acombinationofthesecanformlongercomplexexpressions:

InsidethemainmethodofIf.javainsertthislinetodeclareandinitializeanintegervariablenamednumintnum=8;

Addathirdconditionaltestthatexecutesastatementwhenthevalueofthenumvariableiswithinaspecifiedrange,orwhenit’sexactlyequaltoaspecifiedvalueif(((num>5)&&(num<10))||(num==12))System.out.println(“Numberis6-9inclusive,or12”);

Recompiletheprogram,andrunitoncemoretoseethestatementafterthecomplexexpressiongetexecuted

Page 67: Java in easy steps: Covers Java 9

Changethevalueassignedtothenumvariablesoitisneitherwithinthespecifiedrange6-9,orexactly12.Recompiletheprogram,andrunitagaintonowseethestatementafterthecomplexexpressionisnotexecuted

Therangecanbeextendedtoincludetheupperandlowerlimitsusingthe>=and<=operators.

Thecomplexexpressionusesthe==equalityoperatortospecifyanexactmatch,notthe=assignmentoperator.

Branchingalternatives

Theelsekeywordisusedinconjunctionwiththeifkeywordtocreateifelsestatementsthatprovidealternativebranchesforaprogramtopursue–accordingtotheevaluationofatestedexpression.Initssimplestform,thismerelynominatesanalternativestatementforexecutionwhenthetestfails:if(test-expression)code-to-be-executed-when-true;

else

Page 68: Java in easy steps: Covers Java 9

code-to-be-executed-when-false;Eachalternativebranchmaybeasinglestatementorastatementblockofmultiplestatements–enclosedwithincurlybrackets.

Morepowerfulifelsestatementscanbeconstructedthatevaluateatestexpressionforeachalternativebranch.Theseemploynestedifstatementsaftereachelsekeywordtospecifyeachfurthertest.Whentheprogramdiscoversanexpressionthatevaluatesastrue,itexecutesthestatementsassociatedwithjustthattestthenexitstheifelsestatementwithoutexploringanyfurtherbranches:

Startanewprogramnamed“Else”containingthestandardmainmethodclassElse

{

publicstaticvoidmain(String[]args){}

}

Else.java

Insidethemainmethod,insertthislinetodeclareandinitializeanintegervariablenamedhrsinthrs=11;

Insertthissimpleconditionaltest,whichexecutesasinglestatementwhenthevalueofthehrsvariableisbelow13if(hrs<13)

{

System.out.println(“Goodmorning:”+hrs);

}

SavetheprogramasElse.javathencompileandruntheprogramtoseethestatementgetexecuted

Page 69: Java in easy steps: Covers Java 9

Noticethatthefirststatementisterminatedwithasemicolon,asusual,beforetheelsekeyword.

Changethevalueassignedtothehrsvariableto15,thenaddthisalternativebranchrightaftertheifstatementelseif(hrs<18)

{

System.out.println(“Goodafternoon:”+hrs);

}

Savethechanges,recompile,andruntheprogramagaintoseejustthealternativestatementgetexecuted

Itissometimesdesirabletoprovideafinalelsebranch,withoutanestedifstatement,tospecifya“default”statementtobeexecutedwhennotestedexpressionevaluatesastrue:

Changethevalueassignedtothehrsvariableto21,thenaddthisdefaultbranchtotheendoftheifelsestatementelseSystem.out.println(“Goodevening:”+hrs);

Savethechanges,recompile,andruntheprogramoncemoretoseejustthedefaultstatementgetexecuted

Page 70: Java in easy steps: Covers Java 9

Conditionalbranchingisthefundamentalprocessbywhichcomputerprogramsproceed.

Switchingbranches

Lengthyifelsestatements,whichoffermanyconditionalbranchesforaprogramtopursue,canbecomeunwieldy.Wherethetestexpressionsrepeatedlyevaluatethesamevariablevalue,amoreelegantsolutionisoftenprovidedbyaswitchstatement.

Thesyntaxofatypicalswitchstatementblocklookslikethis:switch(test-variable){

casevalue1:code-to-be-executed-when-true;break;casevalue2:code-to-be-executed-when-true;break;casevalue3:code-to-be-executed-when-true;break;default:code-to-be-executed-when-false;}

Theswitchstatementworksinanunusualway.Ittakesaspecifiedvariablethenseekstomatchitsassignedvaluefromamonganumberofcaseoptions.Statementsassociatedwiththeoptionwhosevaluematchesarethenexecuted.

Optionally,aswitchstatementcanincludeafinaloptionusingthedefaultkeywordtospecifystatementstoexecutewhennocaseoptionsmatchthevalueassignedtothespecifiedvariable.

Eachoptionbeginswiththecasekeywordandavaluetomatch.Thisisfollowedbya:coloncharacterandthestatements,ifany,tobeexecutedwhenthematchismade.

Page 71: Java in easy steps: Covers Java 9

Itisimportanttorecognizethatthestatement,orstatementblock,associatedwitheachcaseoptionmustbeterminatedbythebreakkeyword.Otherwise,theprogramwillcontinuetoexecutethestatementsofothercaseoptionsafterthematchedoption.Sometimes,thisisdesirabletospecifyanumberofcaseoptionsthatshouldeachexecutethesamestatementsifmatched.Forexample,onestatementforeachblockofthreeoptionslikethis:switch(test-variable){

casevalue1:casevalue2:casevalue3:code-A-to-be-executed-when-true;break;casevalue4:casevalue5:casevalue6:code-B-to-be-executed-when-true;break;}

Missingbreakkeywordsarenotsyntaxerrors–ensurethatallintendedbreaksarepresentinswitchblockstoavoidunexpectedresults.

Startanewprogramnamed“Switch”containingthestandardmainmethodclassSwitch

{

publicstaticvoidmain(String[]args){}

}

Switch.java

Insidethemainmethod,declareandinitializethreeintegervariablesintmonth=2,year=2018,num=31;

Addaswitchstatementblocktotestthevalueassignedtothemonthvariableswitch(month)

{

}

Page 72: Java in easy steps: Covers Java 9

}

Insidetheswitchblock,insertcaseoptionsassigninganewvaluetothenumvariableformonths4,6,9and11case4:case6:case9:case11:num=30;break;

Insertacaseoptionassigninganewvaluetothenumvariableformonth2,accordingtotheyearvaluecase2:num=(year%4==0)?29:28;break;

Aftertheswitchblock,attheendofthemainmethod,addthislinetooutputallthreeintegervaluesSystem.out.println(month+“/”+year+“:“+num+“days”);

SavetheprogramasSwitch.javathencompileandruntheprogramtoseetheoutput

Noticehowallthreeintegervariablesaredeclaredandinitializedinlinehereusingconvenientshorthand.

Theconditionaloperatorisusedtogoodeffectinstep5.Youcancheckbacktoheretoberemindedhowitworks.

Loopingfor

Aloopisablockofcodethatrepeatedlyexecutesthestatementsitcontainsuntil

Page 73: Java in easy steps: Covers Java 9

Aloopisablockofcodethatrepeatedlyexecutesthestatementsitcontainsuntilatestedconditionismet–thentheloopendsandtheprogramproceedsontoitsnexttask.

Themostfrequently-usedloopstructureinJavaprogrammingemploystheforkeywordandhasthissyntax:for(initializer;test-expression;updater){

statements-to-be-executed-on-each-iteration;}

Theparenthesesaftertheforkeywordmustcontainthreecontrolsthatestablishtheperformanceoftheloop:• Initializer–assignsaninitialvaluetoacountervariable,whichwillkeepcountofthenumberofiterationsmadebythisloop.Thevariableforthispurposemaybedeclaredhere,anditistraditionallya“trivial”integervariablenamedi.

• Testexpression–evaluatedatthestartofeachiterationoftheloopforaBooleantruevalue.Whentheevaluationreturnstruetheiterationproceedsbutwhenitreturnsfalsetheloopisimmediatelyterminated,withoutcompletingthatiteration.

• Updater–changesthecurrentvalueofthecountervariable,startedbytheinitializer,keepingtherunningtotalofthenumberofiterationsmadebythisloop.Typically,thiswillusei++forcountingup,ori--forcountingdown.

Thecodeexecutedoneachiterationoftheloopcanbeasinglestatement,astatementblock,orevenanother“nested”loop.

Everyloopmust,atsomepoint,enablethetestexpressiontoreturnfalse–otherwise,aninfiniteloopiscreatedthatwillrelentlesslyexecuteitsstatements.Commonly,thetestexpressionwillevaluatethecurrentvalueofthecountervariabletoperformaspecifiednumberofiterations.Forexample,withacounteriinitializedatoneandincrementedbyoneoneachiteration,atestexpressionofi<11becomesfalseafter10iterations–sothatloopwillexecuteitsstatements10timesbeforetheloopends.

Page 74: Java in easy steps: Covers Java 9

Theupdaterisoftenreferredtoasthe“incrementer”asitmoreoftenincrements,ratherthandecrements,thecountervariable

Startanewprogramnamed“For”containingthestandardmainmethodclassFor

{

publicstaticvoidmain(String[]args){}

}

For.java

Insidethemainmethod,declareandinitializeanintegervariabletocountthetotaloverallnumberofiterationsintnum=0;

Addaforlooptoperformthreeiterationsanddisplaythecurrentvalueofitscountervariableioneachiterationfor(inti=1;i<4;i++)

{

System.out.println(“OuterLoopi=”+i);

}

Insidetheforloopblockinsertanestedforlooptoalsoperformthreeiterations,displayingthecurrentvalueofitscountervariablejandtotaloverallnumberofiterationsfor(intj=1;j<4;j++)

{

System.out.print(“\tInnerLoopj=”+j);

Page 75: Java in easy steps: Covers Java 9

System.out.println(“\t\tTotalnum=”+(++num));

}

SavetheprogramasFor.javathencompileandruntheprogramtoseetheoutput

Theincrement++anddecrement--operatorscanprefixavariable,tochangeitsvalueimmediately,orpostfixthevariable–soitsvaluebecomeschangedwhennextreferenced.Trychangingtheincrementoperatorsinthisexampleto++iand++jtoseethedifference.

Loopingwhiletrue

Analternativeloopstructuretothatoftheforloop,describedhere,employsthewhilekeywordandhasthissyntax:while(test-expression){

statements-to-be-executed-on-each-iteration;}

Liketheforloop,awhilelooprepeatedlyexecutesthestatementsitcontainsuntilatestedconditionismet–thentheloopendsandtheprogramproceedsontoitsnexttask.

Unliketheforloop,theparenthesesafterthewhilekeyworddonotcontainaninitializerorupdaterforaniterationcountervariable.Thismeansthatthetest

Page 76: Java in easy steps: Covers Java 9

expressionmustevaluatesomevaluethatgetschangedintheloopstatementsastheloopproceeds–otherwise,aninfiniteloopiscreatedthatwillrelentlesslyexecuteitsstatements.

ThetestexpressionisevaluatedatthestartofeachiterationoftheloopforaBooleantruevalue.Whentheevaluationreturnstruetheiterationproceedsbutwhenitreturnsfalsetheloopisimmediatelyterminated,withoutcompletingthatiteration.

Notethatifthetestexpressionreturnsfalsewhenitisfirstevaluated,theloopstatementsareneverexecuted.

Awhileloopcanbemadetoresemblethestructureofaforloop,toevaluateacountervariableinitstestexpression,bycreatingacountervariableoutsidetheloopandchangingitsvaluewithinthestatementsitexecutesoneachiteration.Forexample,theouterforloopinthepreviousexamplecanberecreatedasawhileloop,likethis:inti=1;

while(i<4)

{

System.out.println(“OuterLoopi=”+i);i++;

}

Thispositionsthecounterinitializerexternally,beforethewhileloopstructure,anditsupdaterwithinthestatementblock.

Aninfiniteloopwilllocktheprogramasitcontinuestoperformiterations–onWindows,pressCtrl+Ctohalt.

Startanewprogramnamed“While”containingthestandardmainmethodclassWhile

{

Page 77: Java in easy steps: Covers Java 9

publicstaticvoidmain(String[]args){}

}

While.java

Insidethemainmethod,declareandinitializeanintegervariablenamednumintnum=100;

Addawhilelooptodisplaythenumvariable’scurrentvaluewhileitremainsabovezerowhile(num>0)

{

System.out.println(“WhileCountdown:”+num);

}

Insertanupdaterattheendofthewhileloopblocktodecreasethenumvariable’svalueby10oneachiteration–therebyavoidinganinfiniteloopnum-=10;

SavetheprogramasWhile.javathencompileandruntheprogramtoseetheoutput

Page 78: Java in easy steps: Covers Java 9

Theassignmentinthisupdaterisshorthandfornum=(num-10).

Page 79: Java in easy steps: Covers Java 9

Doingdo-whileloopsAvariationofthewhileloopstructure,describedhere,employsthedokeywordtocreatealoopwiththissyntax:

do

{

statements-to-be-executed-on-each-iteration;}

while(test-expression);Liketheforloopandwhileloop,adowhilelooprepeatedlyexecutesthestatementsitcontainsuntilatestedconditionismet–thentheloopendsandtheprogramproceedstoitsnexttask.

Unliketheforloopandwhileloop,thedowhiletestexpressionappearsaftertheblockcontainingthestatementstobeexecuted.ThetestexpressionisevaluatedattheendofeachiterationoftheloopforaBooleantruevalue.Whentheevaluationreturnstruethenextiterationproceedsbutwhenitreturnsfalsetheloopisimmediatelyterminated.Thismeansthatthestatementsinadowhilelooparealwaysexecutedatleastonce.

Notethatifthetestexpressionreturnsfalsewhenitisfirstevaluated,theloopstatementshavealreadybeenexecutedonce.

Adowhileloopcanbemadetoresemblethestructureofaforloop,toevaluateacountervariableinitstestexpression,bypositioningthecounterinitializeroutsidetheloopstructureanditsupdaterwithinthestatementblock–justaswithawhileloop.

Allfor,while,ordowhileloopstructurescontainingjustonestatementtoexecutemay,optionally,omitthecurlybracketsaroundthestatement.But,ifomitted,youwillneedtoaddcurlybracketsifadditionalstatementsareaddedtothelooplater.

Thechoiceoffor,while,ordowhileloopislargelyamatterofpersonalcodingpreferenceandpurpose.Aforloopstructureconvenientlylocatesthecounter

Page 80: Java in easy steps: Covers Java 9

initializer,testexpression,andupdaterintheparenthesesaftertheforkeyword.Awhileloopstructurecanbemoreconcise–butyoumustremembertoincludeanupdaterintheloop’sstatementstoavoidaninfiniteloop.Adowhileloopsimplyaddsthebenefitofexecutingitsstatementsoncebeforeevaluatingitstestexpression–demonstratedbythedowhileloopdescribedopposite.

Alwaysenclosethestatementstobeexecutedbyaloopwithincurlybrackets–forclarityandimprovedcodemaintainability.

Startanewprogramnamed“DoWhile”containingthestandardmainmethodclassDoWhile

{

publicstaticvoidmain(String[]args){}

}

DoWhile.java

Insidethemainmethod,declareandinitializeanintegervariablenamednumintnum=100;

Addadowhilelooptodisplaythenumvariable’scurrentvaluewhileitisbelow10

do

{

System.out.println(“DoWhileCountup:”+num);

}

Page 81: Java in easy steps: Covers Java 9

}

while(num<10);

Insertanupdaterattheendofthedowhileloopblocktochangethenumvariable’svalueoneachiteration–therebyavoidinganinfiniteloopnum+=10;

SavetheprogramasDoWhile.javathencompileandruntheprogram–seethatthenumvariablenevermeetsthetestcondition,butthestatementexecutesonceanyway

Theassignmentinthisupdaterisshorthandfornum=(num+10).

Breakingoutofloops

Thebreakkeywordcanbeusedtoprematurelyterminatealoopwhenaspecifiedconditionismet.Thebreakstatementissituatedinsidetheloopstatementblock,andisprecededbyatestexpression.Whenthetestreturnstrue,theloopendsimmediatelyandtheprogramproceedsontoitsnexttask.Forexample,inanestedloopitproceedstothenextiterationofitsouterloop.

Startanewprogramnamed“Break”containingthestandardmainmethodclassBreak

{

publicstaticvoidmain(String[]args){}

}

Page 82: Java in easy steps: Covers Java 9

}

Break.java

Insidethemainmethod,createtwonestedforloopsthatdisplaytheircountervaluesoneachofthreeiterationsfor(inti=1;i<4;i++)

{

for(intj=1;j<4;j++)

{

System.out.println(“Runningi=”+i+“j=”+j);

}

}

SavetheprogramasBreak.javathencompileandruntheprogramtoseetheoutput

Thisprogrammakesthreeiterationsoftheouterloop,whichexecutestheinnerlooponeachiteration.Abreakstatementcanbeaddedtostopthesecondexecutionoftheinnerloop.

Addthisbreakstatementtothebeginningoftheinnerloopstatementblock,tobreakoutoftheinnerloop–thenrecompileandre-runtheprogramif(i==2&&j==1)

{

Page 83: Java in easy steps: Covers Java 9

{

System.out.println(“BreaksinnerLoopwheni=”+i+“j=”+j);

break;

}

Here,thebreakstatementhaltsallthreeiterationsoftheinnerloopwhentheouterlooptriestorunitthesecondtime.

Thecontinuekeywordcanbeusedtoskipasingleiterationofaloopwhenaspecifiedconditionismet.Thecontinuestatementissituatedinsidetheloopstatementblockandisprecededbyatestexpression.Whenthetestreturnstrue,thatiterationends.

Addthiscontinuestatementtothebeginningoftheinnerloopstatementblock,toskipthefirstiterationoftheinnerloop–thenrecompileandre-runtheprogramif(i==1&&j==1)

{

System.out.println(“ContinuesinnerLoopwheni=”+i+“j=”+j);

continue;

}

Page 84: Java in easy steps: Covers Java 9

Here,thecontinuestatementskipsjustthefirstiterationoftheinnerloopwhentheouterlooptriestorunitforthefirsttime.

Returningcontrol

Thedefaultbehaviorofthebreakandcontinuekeywordscanbechangedtoexplicitlyspecifythatcontrolshouldreturntoalabeledouterloopbystatingitslabelname.

Startanewprogramnamed“Label”containingthestandardmainmethodclassLabel

{

publicstaticvoidmain(String[]args){}

}

Label.java

Insidethemainmethod,createtwonestedforloopsthatdisplaytheircountervaluesoneachofthreeiterationsfor(inti=1;i<4;i++)

{

Page 85: Java in easy steps: Covers Java 9

{

for(intj=1;j<4;j++)

{

System.out.println(“Runningi=”+i+“j=”+j);

}

}

SavetheprogramasLabel.javathencompileandruntheprogramtoseetheoutput

Thesyntaxtolabelalooprequiresalabelname,followedbya:coloncharacter,toprecedethestartoftheloopstructure

Editthestartoftheouterlooptolabelit“outerLoop”outerLoop:for(inti=1;i<4;i++)

Toexplicitlyspecifythattheprogramshouldproceedintheouterloop,statethatloop’slabelnameafterthecontinuekeyword

Addthiscontinuestatementtothebeginningoftheinnerloopstatementblock,toproceedatthenextiterationoftheouterloop–thenrecompileandre-runtheprogramif(i==1&&j==1)

{

System.out.println(“ContinuesouterLoopwheni=”+i+“j=”+j);continueouterLoop;

}

Page 86: Java in easy steps: Covers Java 9

}

Herethecontinuestatementhaltsallthreeiterationsoftheinnerloop‘sfirstrun–byreturningcontroltotheouterloop.

Toexplicitlyspecifythattheprogramshouldexitfromtheouterloop,statethatloop’slabelnameafterthebreakkeyword

Addthisbreakstatementtothebeginningoftheinnerloopstatementblock,toexittheouterloop–thenrecompileandre-runtheprogramif(i==2&&j==3)

{

System.out.println(“BreaksouterLoopwheni=”+i+“j=”+j);breakouterLoop;

}

Page 87: Java in easy steps: Covers Java 9

Herethebreakstatementhaltsallfurtheriterationsoftheentireloopstructure–byexitingfromtheouterloop.

Summary

• TheifkeywordperformsaconditionaltesttoevaluateanexpressionforaBooleanvalueoftrueorfalse.

• Anifstatementblockcancontainoneormorestatements,whichareonlyexecutedwhenthetestexpressionreturnstrue.

• Theelsekeywordspecifiesalternativestatementstoexecutewhenthetestperformedbytheifkeywordreturnsfalse.

• Combinedifelsestatementsenableaprogramtoproceedbytheprocessofconditionalbranching.

• Aswitchstatementcanoftenprovideanelegantsolutiontounwieldyifelsestatementsbyofferingcaseoptions.

• Eachcaseoptioncanbeterminatedbythebreakkeywordsoonlystatementsassociatedwiththatoptionwillbeexecuted.

• Thedefaultkeywordcanspecifystatementstobeexecutedwhenallcaseoptionsreturnfalse.

• Alooprepeatedlyexecutesthestatementsitcontainsuntilatestedexpressionreturnsfalse.

• Theparenthesesthatfollowtheforkeywordspecifytheloop’scounterinitializer,testexpression,andcounterupdater.

• Statementsinawhileloopandadowhileloopmustchangeavalueusedintheirtestexpressiontoavoidaninfiniteloop.

• Thetestexpressionisevaluatedatthestartofforloopsandwhileloops–beforethefirstiterationoftheloop.

• Thetestexpressionisevaluatedattheendofdowhileloops–afterthefirst

Page 88: Java in easy steps: Covers Java 9

iterationoftheloop.

• Aloopiterationcanbeskippedusingthecontinuekeyword.

• Aloopcanbeterminatedusingthebreakkeyword.

• Nestedinnerloopscanuselabelswiththebreakandcontinuekeywordstoreferencetheouterloop.

Page 89: Java in easy steps: Covers Java 9

4

Directingvalues

ThischapterdemonstrateshowtodirectdatavaluesusingvariousJavaprogrammingconstructs.

CastingtypevaluesCreatingvariablearrays

PassinganargumentPassingmultipleargumentsLoopingthroughelementsChangingelementvalues

AddingarraydimensionsCatchingexceptionsSummary

Castingtypevalues

HandlingvaluesinJavaprogrammingrequirescorrectdatatypingtobecloselyobservedtoavoidcompilererrors.Forexample,sendingafloattypevaluetoamethodthatrequiresaninttypevaluewillproduceacompilererror.Thismeansitisoftennecessarytoconvertavaluetoanotherdatatypebeforeitcanbeprocessed.

Numericvaluescanbeeasily“cast”(converted)intoanothernumericdatatypeusingthissyntax:

(data-type)valueSomelossofprecisionwilloccurwhencastingfloatfloating

Page 90: Java in easy steps: Covers Java 9

pointvaluesintoanintdatatype,asthenumberwillbetruncatedatthedecimalpoint.Forexample,castingafloatvalueof9.9intoanintvariableproducesanintegervalueofnine.

Interestingly,charactervaluesofthechardatatypecanautomaticallybeusedasintvaluesbecausetheyeachhaveauniqueintegerrepresentation.ThisistheirnumericcodevalueintheASCIIcharacterset,whichissupportedbyJava.TheuppercaseletterA,forinstance,hasthecodevalueof65.

NumericvaluescanbeconvertedtotheStringdatatypeusingthetoString()methodofthatvalue’sdatatypeclass.Thistakesthenumericvalueasitsargument,withintheparentheses.Forexample,convertanintnumvariabletoaStringwithInteger.toString(num).Similarly,convertafloatnumvariabletoaStringwithFloat.toString(num).Inpractice,thistechniqueisnotalwaysrequiredbecauseJavaautomaticallyconvertsconcatenatedvariablestoaStringifanyoneofthevariableshasaStringvalue.

Morefrequently,youwillwanttoconvertaStringvaluetoanumericdatatypesotheprogramcanusethatvaluearithmetically.AStringvaluecanbeconvertedtoanintvalueusingtheInteger.parseInt()method.ThistakestheStringvalueasitsargument,withintheparentheses.Forexample,convertaStringmsgvariabletoanintwithInteger.parseInt(msg).Similarly,convertaStringmsgvariabletoafloatwithFloat.parseFloat(msg).WhenconvertingaStringvaluetoanumericdatatype,theStringmayonlycontainavalidnumericvalue,orthecompilerwillreportanerror.

Allnumericclasseshaveaparse...methodandatoStringmethodallowingconversionbetweenStringvaluesandnumericdatatypes.

Startanewprogramnamed“Convert”containingthestandardmainmethodclassConvert

{

publicstaticvoidmain(String[]args){}

}

Page 91: Java in easy steps: Covers Java 9

}

Convert.java

Insidethemainmethod,declareandinitializeafloatvariableandaStringvariablefloatdaysFloat=365.25f;StringweeksString=“52”;

CastthefloatvalueintoanintvariableintdaysInt=(int)daysFloat;

ConverttheStringvalueintoanintvariableintweeksInt=Integer.parseInt(weeksString);

Performarithmeticontheconvertedvaluesanddisplaytheresultintweek=(daysInt/weeksInt);System.out.println(“Daysperweek:“+week);

SavetheprogramasConvert.javathencompileandruntheprogramtoseetheoutput

Creatingvariablearrays

Anarrayissimplyavariablethatcancontainmultiplevalues–unlikearegularvariablethatcanonlycontainasinglevalue.

Thedeclarationofanarrayfirststatesitsdatatype,usingoneofthedatatypekeywords,followedbysquarebrackets[]todenotethatitwillbeanarray

Page 92: Java in easy steps: Covers Java 9

keywords,followedbysquarebrackets[]todenotethatitwillbeanarrayvariable.Next,thedeclarationstatesthearrayvariablename,adheringtothenormalnamingconventions.

Anarraycanbeinitializedinitsdeclarationbyassigningvaluesoftheappropriatedatatypeasacomma-delimitedlist,enclosedwithincurlybrackets.Forexample,thedeclarationofanintegerarrayvariableinitializedwiththreevaluesmightlooklikethis:

int[]numbersArray={1,2,3};

Thearrayiscreatedofthelengthoftheassignedlist,allowingone“element”pervalue–inthiscase,anarrayofthreeelements.

Storedvaluesareindexedstartingatzero,andeachvaluecanbeaddressedbyitselementindexposition.Thesyntaxtodosorequiresthearraynametobefollowedbysquarebracketscontainingtheelementindex.Forinstance,numbersArray[0]wouldaddressthefirstvaluestoredintheexampleabove(1).

Althoughthevaluesstoredineachelementcanbechangedassimplyasthoseofregularvariables,thesizeofanarrayisdeterminedbyitsdeclarationandcannotbechangedlater.Usefully,thetotalnumberofelementsinanarrayisstoredasanintegerinthelengthpropertyofthatarray.Thesyntaxtoaddressthisfigurejusttacksaperiodand“length”ontothearrayname.Forexample,numbersArray.lengthwouldreturnthesizeofthearrayintheexampleabove–inthiscase,theinteger3.

Arrayscanalsobedeclaredwithoutassigningalistofinitialvaluesbyusingthenewkeywordtocreateanemptyarray“object”ofaspecifiedsize.Thenumberofrequiredemptyelementsisstatedintheassignmentwithinsquarebracketsaftertheappropriatedatatype.Forexample,thedeclarationofanemptyintegerarrayvariablewiththreeelementsmightlooklikethis:int[]numbersArray=newint[3];

Page 93: Java in easy steps: Covers Java 9

Theelementsareassigneddefaultvaluesofzeroforintandfloatdatatypes,nullforStringdatatypes,\0forchardatatypes,andfalseforbooleandatatypes.

Rememberthatarrayindexingstartsatzero.Thismeansthatindex[2]addressesthethirdelementinthearray,notitssecondelement.

Startanewprogramnamed“Array”containingthestandardmainmethodclassArray

{

publicstaticvoidmain(String[]args){}

}

Array.java

Insidethemainmethod,declareandinitializeaStringarraywiththreeelementsString[]str={“Much”,“More”,“Java”};

Declareanemptyintegerarraywiththreeelementsint[]num=newint[3];

Assignvaluestothefirsttwointegerarrayelementsnum[0]=100;

num[1]=200;

AssignanewvaluetothesecondStringarrayelementstr[1]=“Better”;

OutputthelengthofeacharrayandthecontentofallelementsineacharraySystem.out.println(“Stringarraylengthis“+str.length);System.out.println(“Integerarraylengthis“+num.length);System.out.println(num[0]+”,”+num[1]+”,”+num[2]);System.out.println(str[0]+str[1]+str[2]);

SavetheprogramasArray.javathencompileandruntheprogramtoseetheoutput

Page 94: Java in easy steps: Covers Java 9

Stringvaluesneedtobeenclosedwithinquotes.

Passinganargument

ThestandardJavacodethatdeclarestheprogram’smainmethodincludesanargumentwithinitsparenthesesthatcreatesaStringarray,traditionallynamed“args”:publicstaticvoidmain(String[]args){}

Thepurposeoftheargs[]arrayistoallowvaluestobepassedtotheprogramwhenitiscalledupontorun.Atthecommandline,avaluetobepassedtotheprogramisaddedafterasinglespacefollowingtheprogramname.Forexample,thecommandtopasstheString“Java”toaprogramnamed“Run”wouldbeRunJava.

Asinglevaluepassedtoaprogramisautomaticallyplacedintothefirstelementoftheargs[]array,soitcanbeaddressedbytheprogramasargs[0].

Itisimportanttorecognizethattheargs[]arrayisoftheStringdatatype–soanumericvaluepassedtoaprogramwillbestoredasaStringrepresentationofthatnumber.Thismeansthattheprogramcannotusethatvaluearithmeticallyuntilithasbeenconvertedtoanumericaldatatype,suchasanintvalue.Forexample,Run4passesthenumberfourtotheprogram,whichstoresitastheString“4”,notastheint4.Consequently,outputofargs[0]+3producestheconcatenatedString“43”,notthesum7.TheargumentcanbeconvertedwiththeInteger.parseInt()methodsothatInteger.parseInt(args[0])+3doesproducethesum7.

Page 95: Java in easy steps: Covers Java 9

AStringcontainingspacescanbepassedtoaprogramasasingleStringvaluebyenclosingtheentireStringwithindoublequotesonthecommandline.Forexample,Run“JavaInEasySteps”.

Passinganargumenttoaprogramismostusefultodeterminehowtheprogramshouldrunbyindicatinganexecutionoption.TheoptionispassedtotheprogramasaStringvalueinargs[0]andcanbeevaluatedusingtheString.equals()method.Thesyntaxforthisjusttacksaperiodand“equals()”ontothearrayname,withacomparisonStringwithintheparentheses.Forexample,args[0].equals(“b”)evaluatestheargumentfortheStringvalue“b”.

Startanewprogramnamed“Option”containingthestandardmainmethodclassOption

{

publicstaticvoidmain(String[]args){}

}

Option.java

Insidethemainmethod,writeanifstatementtoseekanargumentof“-en”if(args[0].equals(“-en”))

{

System.out.println(“Englishoption”);

}

Addanelsealternativeontotheifstatementtoseekanargumentof“-es”elseif(args[0].equals(“-es”))

{

System.out.println(“Spanishoption”);

}

Page 96: Java in easy steps: Covers Java 9

}

AddanotherelsealternativeontotheifstatementtoprovideadefaultresponseelseSystem.out.println(“Unrecognizedoption”);

SavetheprogramasOption.javathencompileandruntheprogramtoseetheoutput

ThisexamplewillthrowanArrayIndexOutOfBoundsexceptionifyouattempttoexecutetheprogramwithoutanyargument.Seeherefordetailsonhowtocatchexceptions.

Passingmultiplearguments

Multipleargumentscanbepassedtoaprogramatthecommandline,followingtheprogramnameandaspace.Theargumentsmustbeseparatedbyatleastonespaceandtheirvaluesareplaced,inorder,intotheelementsoftheargs[]array.Eachvaluecanthenbeaddressedbyitsindexnumberaswithanyotherarray–args[0]forthefirstargument,args[1]forthesecondargument,andsoon.

Theprogramcantestthelengthpropertyoftheargs[]arraytoensuretheuserhasenteredtheappropriatenumberofarguments.Whenthetestfails,thereturnkeywordcanbeusedtoexitthemainmethod,therebyexitingtheprogram:

Page 97: Java in easy steps: Covers Java 9

Startanewprogramnamed“Args”containingthestandardmainmethodclassArgs

{

publicstaticvoidmain(String[]args){}

}

Args.java

Insidethemainmethod,writeanifstatementtooutputadviceandexittheprogramwhentherearenottherequirednumberofarguments–inthiscase,threeif(args.length!=3)

{

System.out.println(“Wrongnumberofarguments”);return;

}

Belowtheifstatement,createtwointvariables–initializedwiththevaluesofthefirstargumentandthirdargumentrespectivelyintnum1=Integer.parseInt(args[0]);intnum2=Integer.parseInt(args[2]);

AddaStringvariable,initializedwithaconcatenationofallthreeargumentsStringmsg=args[0]+args[1]+args[2]+“=”;

Thereturnkeywordexitsthecurrentmethod.Itcanalsoreturnavaluetothepointwherethemethodwascalled.Seehereformoredetails.

Page 98: Java in easy steps: Covers Java 9

AddthisifelsestatementtoperformarithmeticontheargumentsandappendtheresulttotheStringvariableif(args[1].equals(“+”))msg+=(num1+num2);elseif(args[1].equals(“-”))msg+=(num1-num2);elseif(args[1].equals(“x”))msg+=(num1*num2);elseif(args[1].equals(“/”))msg+=(num1/num2);elsemsg=“Incorrectoperator”;

InsertthislineattheendofthemainmethodtodisplaytheappendedStringSystem.out.println(msg);

SavetheprogramasArgs.javathencompileandruntheprogramwiththreearguments–aninteger,anyarithmeticalsymbol+-x/,andanotherinteger

Now,runtheprogramwithanincorrectsecondargumentandwiththewrongnumberofarguments

Page 99: Java in easy steps: Covers Java 9

Thisprogramwillreportanerrorifnon-numericvaluesareentered.Seeherefordetailsonhowtocatcherrors.

Loopingthroughelements

Alltypesofloopcanbeusedtoeasilyreadallthevaluesstoredinsidetheelementsofanarray.Theloopcountershouldstartwiththeindexnumberofthefirstelementthenproceedonuptothefinalindexnumber.Theindexnumberofthelastelementinanarraywillalwaysbeonelessthanthearraylength–becausetheindexstartsatzero.

Itisusefultosetthearraylengthpropertyastheloop’sconditionaltestdeterminingwhentheloopshouldend.Thismeansthattheloopwillcontinueuntilthecountervalueexceedstheindexnumberofthearray’sfinalelement.

Startanewprogramnamed“Loops”containingthestandardmainmethodclassLoops

{

publicstaticvoidmain(String[]args){}

}

Page 100: Java in easy steps: Covers Java 9

Loops.java

Insidethemainmethod,writeanifstatementtotestwhetheranyargumentvalueshavebeenenteredintotheargs[]arrayfromthecommandlineif(args.length>0){}

Insertaforloopinsidethecurlybracketsoftheifstatementtooutputthevaluestoredineachelementfor(inti=0;i<args.length;i++)

{

System.out.println(“args[“+i+“]is|“+args[i]);

}

SavetheprogramasLoops.javathencompiletheprogramandrunitwiththeargumentsJavaineasysteps

EditLoops.javatoaddaStringarrayandawhilelooptooutputthevaluestoredineachelementString[]htm={“HTML5”,“in”,“easy”,“steps”};

intj=0;while(j<htm.length)

{

System.out.println(“htm[“+j+“]is|“+htm[j]);j++;

}

Page 101: Java in easy steps: Covers Java 9

Savethechanges,thenrecompileandre-runtheprogram

EditLoops.javatoaddanotherStringarrayandadowhilelooptooutputthevaluestoredineachelementString[]xml={“XML”,“in”,“easy”,“steps”};

intk=0;if(xml.length>0)do

{

System.out.println(“\t\txml[“+k+“]is|“+xml[k]);k++;

}while(k<xml.length);

Savethechanges,thenrecompileandre-runtheprogram

Noticethatthedostatementisprecededbyaconditionaltesttoensurethearrayisnotemptybeforeattemptingtooutputthevalueofthefirstelement.

Page 102: Java in easy steps: Covers Java 9

Changingelementvalues

Thevaluestoredinanarrayelementcanbechangedbyassigninganewvaluetothatparticularelementusingitsindexnumber.Additionally,anytypeofloopcanbeusedtoefficientlypopulatealltheelementsinanarrayfromvaluesstoredinotherarrays.Thisisespeciallyusefultocombinedatafrommultiplearraysintoasinglearrayoftotaleddata.

Startanewprogramnamed“Elements”containingthestandardmainmethodclassElements

{

publicstaticvoidmain(String[]args){}

}

Elements.java

Inthemainmethod,addinitializedintarraysrepresentingmonthlykiosksalesfromallfourquartersofayearint[]kiosk_q1={42000,48000,50000};int[]kiosk_q2={52000,58000,60000};int[]kiosk_q3={46000,49000,58000};int[]kiosk_q4={50000,51000,61000};

Addinitializedintarraysrepresentingmonthlyoutletsalesfromallfourquartersofayearint[]outlet_q1={57000,63000,60000};int[]outlet_q2={70000,67000,73000};int[]outlet_q3={67000,65000,62000};int[]outlet_q4={72000,69000,75000};

Now,createanemptyintarrayof12elementsinwhichtocombineallthemonthlysalesfiguresandanintvariableinwhichtorecordtheirgrandtotalvalueint[]sum=newint[12];inttotal=0;

Addaforlooptopopulateeachelementoftheemptyarraywithcombinedvalues

Page 103: Java in easy steps: Covers Java 9

fromtheotherarraysfor(inti=0;i<kiosk_q1.length;i++)

{

sum[i]=kiosk_q1[i]+outlet_q1[i];sum[i+3]=kiosk_q2[i]+outlet_q2[i];sum[i+6]=kiosk_q3[i]+outlet_q3[i];sum[i+9]=kiosk_q4[i]+outlet_q4[i];

}

Next,addasecondforlooptooutputeachofthecombinedmonthlysalestotals,andtocalculatetheirgrandtotalfor(inti=0;i<sum.length;i++)

{

System.out.println(“Month“+(i+1)+”sales:\t”+sum[i]);total+=sum[i];

}

InsertafinalstatementattheendofthemainmethodtooutputthegrandtotalSystem.out.println(“TOTALYEARSALES\t”+total);

SavetheprogramasElements.javathencompiletheprogramandrunittoseetheoutput

Page 104: Java in easy steps: Covers Java 9

Thecounternumbergetsincreasedbyonetoproducethemonthnumbers1-12.

Addingarraydimensions

Arrayscanbecreatedtostoremultiplesetsofelementvalues,eachhavingtheirownindexdimension.Individualvaluesareaddressedinamulti-dimensionalarrayusingtheappropriateindexnumbersofeachdimension.Forexample,num[1][3].

Atwo-dimensionalarraymightbeusedtorecordanintegervalueforeachdayofabusinessyear,organizedbyweek.Thisrequiresanarrayof52elements(oneperweek)thateachhaveanarrayofsevenelements(oneperday).Itsdeclarationlookslikethis:

int[][]dailyRecord=newint[52][7];

Avoidusingmorethanthreedimensionsinarrays–itwillbeconfusing.

This“arrayofarrays”providesanelementforeachbusinessday.Valuesareassignedtoamulti-dimensionalarraybystatingtheappropriateindexnumbersofeachdimension.Withtheexampleabove,forinstance,avaluecanbeassignedtothefirstdayofthesixthweeklikethis:dailyRecord[5][0]=5000;

Eacharrayhasitsownlengthpropertythatcanbeaccessedbyspecifyingthedimensionrequired.Fortheexampleabove,thesyntaxdailyRecord.lengthreturnsavalue52–thesizeofthefirstdimension.Toaccessthesizeoftheseconddimension,thesyntaxdailyRecord[0].lengthreturnsthevalueofseven.

Page 105: Java in easy steps: Covers Java 9

Two-dimensionalarraysareoftenusedtostoregridcoordinates,whereonedimensionrepresentstheXaxisandtheotherdimensionrepresentstheYaxis.Forexample,point[3][5].

Three-dimensionalarrayscanbeusedtostoreXYZcoordinatesinasimilarway,butitcanbedifficulttovisualizepoint[4][8][2].

Nestedloopsareperfectlysuitedtomulti-dimensionalarrays,aseachlooplevelcanaddresstheelementsofeacharraydimension.

Startanewprogramnamed“Dimensions”containingthestandardmainmethodclassDimensions

{

publicstaticvoidmain(String[]args){}

}

Dimensions.java

Inthemainmethod,createatwo-dimensionalarraytostoreBooleanflatsrelatingtoXYcoordinatesboolean[][]points=newboolean[5][20];

DefineoneYpointoneachXaxispoints[0][5]=true;points[1][6]=true;points[2][7]=true;points[3][8]=true;points[4][9]=true;

Page 106: Java in easy steps: Covers Java 9

Addaforlooptoiteratethroughthefirstarrayindex,addinganewlinecharacterattheendofeachiterationfor(inti=0;i<points.length;i++)

{

System.out.print(“\n”);

}

Withinthecurlybracketsoftheforloop,insertasecondforlooptoiteratethroughthesecondarrayindexfor(intj=0;j<points[0].length;j++){}

Withinthecurlybracketsofthesecondforloop,insertastatementtooutputacharacterforeachelementaccordingtothatelement’sBooleanvaluecharmark=(points[i][j])?‘X’:‘-’;System.out.print(mark);

SavetheprogramasDimensions.javathencompileandruntheprogramtoseetheoutput

Booleanvariablesarefalsebydefault.

Catchingexceptions

Aprogrammayencounteraruntimeproblemthatcausesan“exception”error,

Page 107: Java in easy steps: Covers Java 9

Aprogrammayencounteraruntimeproblemthatcausesan“exception”error,whichhaltsitsexecution.Often,thiswillbecreatedbyunexpecteduserinput.Awell-writtenprogramshould,therefore,attempttoanticipateallpossiblewaystheusermightcauseexceptionsatruntime.

Codewhereexceptionsmightarisecanbeidentifiedandenclosedwithinatrycatchstatementblock.Thisallowstheprogramtohandleexceptionswithouthaltingexecutionandlookslikethis:

try

{

statementswhereanexceptionmayarise}catch(Exceptione)

{

statementsrespondingtoanexception}

Theparenthesesfollowingthecatchkeywordspecifytheclassofexceptiontobecaughtandassignittothevariable“e”.Thetop-levelExceptionclasscatchesallexceptions.Responsescanbeprovidedforspecificexceptions,however,usingmultiplecatchstatementstoidentifydifferentlower-levelexceptionclasses.

ThemostcommonexceptionsaretheNumberFormatException,whichariseswhentheprogramencountersavaluethatisnotoftheexpectednumerictype,andtheArrayIndexOutOfBoundsException,whichariseswhentheprogramattemptstoaddressanarrayelementnumberthatisoutsidetheindexsize.Itishelpfultocreateaseparateresponseforeachoftheseexceptionstoreadilynotifytheuseraboutthenatureoftheproblem.

Optionally,atrycatchstatementblockcanbeextendedwithafinallystatementblock,containingcodethatwillalwaysbeexecuted–irrespectiveofwhethertheprogramhasencounteredexceptions.

Page 108: Java in easy steps: Covers Java 9

Thee.getMessage()methodreturnsfurtherinformationaboutsomecapturedexceptions.

Startanewprogramnamed“Exceptions”containingthestandardmainmethodclassExceptions

{

publicstaticvoidmain(String[]args){}

}

Exceptions.java

Insidethemainmethod,writeatrystatementtooutputasingleintegerargument

try

{

intnum=Integer.parseInt(args[0]);System.out.println(“Youentered:“+num);

}

Addacatchstatementtohandletheexceptionthatariseswhentheprogramisrunwithoutanargumentcatch(ArrayIndexOutOfBoundsExceptione){System.out.println(“Integerargumentrequired.”);}

Addacatchstatementtohandletheexceptionthatariseswhentheprogramisrunwithanon-integerargumentcatch(NumberFormatExceptione){System.out.println(“Argumentiswrongformat.”);}

Addafinallystatementattheendoftheprogramfinally{System.out.println(“Programends.”);}

Page 109: Java in easy steps: Covers Java 9

SavetheprogramasExceptions.javathencompileandruntheprogram,tryingtocauseexceptions

Summary

• Numericvaluescanbeconvertedtoothernumericdatatypesbycasting,andtotheStringtypeusingthetoString()method.

• AStringvaluecanbeconvertedtoanintvalueusingtheInteger.parseInt()method,andtoafloatusingFloat.parseFloat().

• Anarrayisavariablethatcancontainmultiplevalues,initializedasalistwithincurlybracketsinitsdeclaration.

• Anemptyarrayobjectcanbecreatedusingthenewkeyword.

• Thelengthpropertyofanarraystoresaninteger,whichisthenumberofelementsinthatarray.

• Eachelementofanarraycanbeaddressedbyitsindexnumber.

• Aprogram’smainmethodcreatesaStringarray,traditionallynamed“args”,tostorecommandlinearguments.

• Thefirstcommandlineargumentgetsautomaticallystoredintheargs[0]element–asaStringdatatype.

• Multipleargumentsbeingpassedtoaprogramfromthecommandlinemusteachbeseparatedbyaspace.

• Loopsareanidealwaytoreadallthevaluesstoredwithinarrayelements.

• Datafrommultiplearrayscanbecombinedtoformanewarrayoftotaleddataineachelement.

Page 110: Java in easy steps: Covers Java 9

• Multi-dimensionalarrayscanstoremultiplesetsofelementvalues,eachhavingtheirownindexdimension.

• Atrycatchstatementblockisusedtoanticipateandhandleruntimeexceptionsthatmayarise.

• TheExceptionclasscatchesallexceptionerrors,includingNumberFormatExceptionandArrayIndexOutOfBoundsException.

• Atrycatchstatementcanbeextendedwithafinallystatementblock,containingcodethatwillalwaysbeexecuted.

Page 111: Java in easy steps: Covers Java 9

5

Manipulatingdata

ThischapterdemonstrateshowtomanipulateprogramdatausingvariousJavalibrarymethods.

ExploringJavaclassesDoingmathematics

RoundingnumbersGeneratingrandomnumbersManagingstringsComparingstrings

SearchingstringsManipulatingcharactersSummary

ExploringJavaclasses

Javahasavastlibraryofpre-testedcodepackages,whicharearrangedinmodules.ThoseprovidingfunctionalitythatisfundamentaltotheJavalanguageitselfarecontainedinthejava.langpackage,withinthejava.basemodule.TheseareautomaticallyaccessibletotheJavaAPI(ApplicationProgrammingInterface).Thismeansthatthepropertiesandmethodsprovidedbythejava.langpackagearereadilyavailablewhencreatingprograms.Forexample,themathematicfunctionalityprovidedbytheabs()methodoftheMathclass,whichispartofthejava.langpackage,inthejava.basemodule.

Page 112: Java in easy steps: Covers Java 9

ModulesareanewfeatureintroducedinJava9toimprovescalabilityandincreaseperformance.

Packagecontentsarearrangedinhierarchicalorder,allowinganyitemtobeaddressedusingdotnotation.Forexample,theSystemclasscontainsanoutproperty(field),whichinturncontainsaprintln()method–socanbeaddressedasSystem.out.println().

TheJavadocumentationprovidesinformationabouteveryitemavailable,andcanbeusedtoexploretheJavaclasses.Itisavailableonlineatdocs.oracle.com/javase/9/docs/apiorcanbedownloadedforofflinereference.Thedocumentationisunderstandablylarge,butfamiliaritywithitisvaluable.AgoodstartingpointistheAPIOverviewpagecontainingalistofeverymoduleineachofthreesections,togetherwithabriefdescriptionofeachmodule:

StartawebbrowserandopentheAPIOverviewpageatdocs.oracle.com/javase/9/docs/api

SeetheModuleslistedalphabeticallyineachsection–scrolldownthepagetothe“JavaSE”sectionandfindthejava.basemodule,thenclickitshyperlink

YoucanclickontheFrameslinktoseeamulti-paneviewofthedocumentation.

Page 113: Java in easy steps: Covers Java 9

Seethemodule’sPackageslistedalphabeticallyineachsection–scrolldownthepagetothe“Exports”sectionandfindthejava.langpackage,thenclickitshyperlink

Seethepackage’sClasseslistedalphabeticallyineachsection–scrolldownthepagetothe“ClassSummary”sectiontofindtheMathclass,thenclickitshyperlink

Seetheclass’sMethodslistedalphabeticallyinthe“MethodSummary”section–clickonanyhyperlinktodiscoverthepurposeofthatmethodanditssyntax

Page 114: Java in easy steps: Covers Java 9

YoucanalsousetheSearchboxtofindinformationonanyitem.

Examinetheinformationavailableviaotheritemsonthepagemenutobecomemorefamiliarwiththedocumentation.

Doingmathematics

TheMathclasswithinthejava.langpackageprovidestwoconstantvaluesthatareoftenusefultoperformmathematicalcalculations.Math.PIstoresthevalueofPi,andMath.Estoresthevaluethatisthebaseofnaturallogarithms.Boththeseconstantvaluesarestoredasdoubleprecisiondatatypeswith15decimalplaces.

Startanewprogramnamed“Pi”containingthestandardmainmethodclassPi

{

publicstaticvoidmain(String[]args){}

}

Pi.java

Insidethemainmethod,declareandinitializeafloatvariablefromacommandlineargument,andcastthedoubleMath.PIconstantintoasecondfloatvariablefloatradius=Float.parseFloat(args[0]);floatshortPi=(float)Math.PI;

Page 115: Java in easy steps: Covers Java 9

Performmathematicalcalculationsusingthecastvalue,assigningtheresultstomorefloatvariablesfloatcirc=shortPi*(radius+radius);floatarea=shortPi*(radius*radius);

OutputthevalueofMath.PIanditscastfloatequivalent,followedbytheresultsofthecalculationsSystem.out.print(“WithPicommutedfrom“+Math.PI);System.out.println(“to“+shortPi+“...”);System.out.println(“Acircleofradius“+radius+“cm”);System.out.printIn(“hasacircumferenceof“+circ+“cm”);System.out.println(“andanareaof“+area+“sq.cm”);

SavetheprogramasPi.javathencompileandruntheprogramtoseetheoutput

ThecommutedvalueofPiusuallyprovidessufficientprecision.

TheMathclasswithinthejava.langpackageprovidesmanymethodsthatareusefultoperformmathematicalcalculations.UsingMath.pow(),agivennumbercanberaisedtoaspecifiedpower.Theparenthesesrequirethenumberasitsfirstargumentandthepowerbywhichitistoberaisedasitssecondargument.TheMath.sqrt()methodreturnsthesquarerootofthenumberspecifiedasitssoleargument.Bothmethodsreturnadoubletype.

Startanewprogramnamed“Power”containingthestandardmainmethodclassPower

{

Page 116: Java in easy steps: Covers Java 9

publicstaticvoidmain(String[]args){}

}

Power.java

Insidethemainmethod,declareandinitializeanintvariablefromapassedcommandlineargumentintnum=Integer.parseInt(args[0]);

Performmathematicalcalculations,castingtheresultsintomoreintvariablesintsquare=(int)Math.pow(num,2);intcube=(int)Math.pow(num,3);intsqrt=(int)Math.sqrt(num);

OutputtheresultsofthecalculationsSystem.out.println(num+”squaredis“+square);System.out.println(num+”cubedis“+cube);System.out.println(“Squarerootof“+num+”is“+sqrt);

SavetheprogramasPower.javathencompileandruntheprogramtoseetheoutput

Boththeseexamplescouldbeimprovedbyaddingtrycatchstatement

Page 117: Java in easy steps: Covers Java 9

blockstoanticipateusererrors–seeherefordetails.

Roundingnumbers

TheMathclasswithinthejava.langpackageprovidesthreemethodstoroundfloating-pointnumberstothenearestinteger.SimplestoftheseistheMath.round()methodthatroundsanumberstatedasitsargumentup,ordown,totheclosestinteger.

TheMath.floor()methodroundsdowntotheclosestintegerbelow,andMath.ceil()roundsuptotheclosestintegerabove.

WhiletheMath.round()methodreturnsanintdatatype,bothMath.floor()andMath.ceil()methodsreturnadoubledatatype.

Startanewprogramnamed“Round”containingthestandardmainmethodclassRound

{

publicstaticvoidmain(String[]args){}

}

Round.java

Insidethemainmethod,declareandinitializeafloatvariablefloatnum=7.25f;

OutputtheroundedfloatvalueasanintvalueSystem.out.println(num+”roundedis“+Math.round(num));

OutputtheroundedfloatvalueasdoublevaluesSystem.out.println(num+”flooredis“+Math.floor(num));System.out.println(num+“ceilingis“+Math.ceil(num));

SavetheprogramasRound.javathencompileandruntheprogramtoseetheoutput

Page 118: Java in easy steps: Covers Java 9

Bydefault,Math.round()willroundup–so7.5wouldberoundedupto8.

TheMathclasswithinthejava.langpackageprovidestwomethodstocomparetwonumericalvalues.TheMath.max()methodandtheMath.min()methodeachrequiretwonumberstobestatedastheirarguments.Math.max()willreturnthegreaternumberandMath.min()willreturnthesmallernumber.

Thenumberstobecomparedcanbeofanynumericaldatatype,buttheresultwillbereturnedasadoubledatatype.

Startanewprogramnamed“Compare”containingthestandardmainmethodclassCompare

{

publicstaticvoidmain(String[]args){}

}

Compare.java

Insidethemainmethod,declareandinitializeafloatvariableandanintvariable

Page 119: Java in easy steps: Covers Java 9

floatnum1=24.75f;intnum2=25;

OutputthegreatervalueSystem.out.println(“Mostis“+Math.max(num1,num2));

OutputthelesservalueSystem.out.println(“Leastis“+Math.min(num1,num2));

SavetheprogramasCompare.javathencompileandruntheprogramtoseetheoutput

Generatingrandomnumbers

TheMathclasswithinthejava.langpackageprovidestheabilitytogeneraterandomnumberswithitsMath.random()method,whichreturnsadoubleprecisionrandomnumberbetween0.0and0.999.Multiplyingtherandomnumberwillspecifyawiderrange.Forexample,multiplyingby10willcreatearandomnumberintherangeof0.0to9.999.NowroundingtherandomnumberupwithMath.ceil()willensureitfallswithintherangeof1-10inclusive.

Startanewprogramnamed“Random”containingthestandardmainmethodclassRandom

{

publicstaticvoidmain(String[]args){}

}

Page 120: Java in easy steps: Covers Java 9

Random.java

Insidethemainmethod,assignarandomnumbertoafloatvariable,andoutputitsvaluefloatrandom=(float)Math.random();System.out.println(“Randomnumber:“+random);

Assignamultiplicationoftherandomnumbertoasecondfloatvariable,andoutputitsvaluefloatmultiplied=random*10;System.out.println(“Multipliednumber:“+multiplied);

Assignaroundedintegerofthemultipliedrandomnumbertoanintvariable,andoutputitsvalueintrandomInt=(int)Math.ceil(multiplied);System.out.println(“RandomInteger:“+randomInt);

SavetheprogramasRandom.javathencompileandruntheprogramtoseetheoutput

TheLotteryprogramdescribedoppositecombinesallthreestepsfromthisexampleintoasinglestatement.

Asequenceofsixnon-repeatingrandomnumberswithintherange1-59inclusivecanbegeneratedusingMath.random()toproducearandomlotteryselection.

Startanewprogramnamed“Lottery”containingthestandardmainmethodclassLottery

Page 121: Java in easy steps: Covers Java 9

{

publicstaticvoidmain(String[]args){}

}

Lottery.java

Insidethemainmethod,createanintarrayof60elements,thenfillelements1-59withintegers1-59int[]nums=newint[60];for(inti=1;i<60;i++){nums[i]=i;}

Shufflethevaluesinelements1-59for(inti=1;i<60;i++)

{

intr=(int)Math.ceil(Math.random()*59);inttemp=nums[i];nums[i]=nums[r];nums[r]=temp;}

Outputonlythosevaluescontainedinelements1-6for(inti=1;i<7;i++)

{

System.out.print(Integer.toString(nums[i])+““);

}

SavetheprogramasLottery.javathencompileitandruntheprogramthreetimestoseethreedifferentsequences

Page 122: Java in easy steps: Covers Java 9

ThisprogramisrevisitedwithagraphicaluserinterfaceinChapter10.

Managingstrings

InJavaprogramming,aStringiszeroormorecharactersenclosedwithinquotationmarks.So,theseareallvalidStringvalues:Stringtxt1=“MyFirstString”;

Stringtxt2=“”;

Stringtxt3=“2”;

Stringtxt4=“null”;

Array.lengthisapropertybutString.length()isamethod–soitmusthavetrailingparentheses.

Theemptyquotesoftxt2initializethevariableasanemptyStringvalue.Thenumericvalueassignedtotxt3isaStringrepresentationofthenumber.TheJavanullkeyword,whichnormallyrepresentstheabsenceofanyvalue,issimplyaStringliteralwhenitisenclosedwithinquotes.

Page 123: Java in easy steps: Covers Java 9

Essentially,aStringisacollectionofcharacters;eachcharactercontainingitsowndata–justlikeelementsinadefinedarray.Itis,therefore,logicaltoregardaStringasanarrayofcharactersandapplyarraycharacteristicswhendealingwithStringvalues.

TheStringclassispartofthefundamentaljava.langpackageandprovidesalength()methodthatwillreturnthesizeofaString,muchlikethelengthpropertyofanarray.EachStringvariableiscreatedasan“instance”oftheStringclasssoitsmethodscanbeusedbytackingtheirnameontothevariablenameusingdotnotation.Forexample,thesyntaxtoreturnthesizeofaStringvariablenamedtxtistxt.length().

TheStringclasswithinthejava.langpackagealsoprovidesanalternativetothe+concatenationoperatorforjoiningStringvaluestogether.Itsconcat()methodrequiresasingleargumentspecifyingthesecondStringtobeappended.InuseitistackedontothevariablenameofthefirstStringusingdotnotation.Forexample,appendtxt2ontotxt1usingtxt1.concat(txt2).

Startanewprogramnamed“StringLength”containingthestandardmainmethodclassStringLength

{

publicstaticvoidmain(String[]args){}

}

StringLength.java

Insidethemainmethod,createandinitializetwoStringvariablesStringlang=“Java”;Stringseries=“ineasysteps”;

AddanotherStringvariableandassignittheconcatenatedvalueoftheothertwoStringvariablesStringtitle=lang.concat(series);

OutputtheconcatenatedStringwithinquotationmarks,togetherwithitssizeSystem.out.print(“\””+title+“\”has“);

Page 124: Java in easy steps: Covers Java 9

System.out.println(title.length()+“characters”);

SavetheprogramasStringLength.javathencompileandruntheprogramtoseetheoutput

SpacesarepartoftheStringsoareincludedinthecharactercount–butthequotationmarksarenotincluded.

Comparingstrings

TheStringclasswithinthejava.langpackageprovidestheusefulequals()methodthatwasintroducedheretoevaluateacommandlineargumentintheargs[0]element.ThiscanalsobeusedtocompareanytwoStringvaluesbytackingthemethodnameontothefirstStringvariableusingdotnotation,andspecifyingtheStringtobecomparedasitsargument.Forexample,thesyntaxtocomparetxt2totxt1istxt1.equals(txt2).WhenbothStringvalueshaveidenticalcharacters,inthesameorder,themethodreturnstrue–otherwise,itreturnsfalse.

Besuretoobservecorrectcapitalizationusingacapital“C”inthe

Page 125: Java in easy steps: Covers Java 9

toUpperCaseandtoLowerCasemethods.

Stringvaluesthatusedifferentlettercase,suchas“Java”and“JAVA”,arenotconsideredequalbecausetheASCIIcodevaluesofthecharactersdiffer.Forinstance,thevalueofuppercase“A”is65,whereaslowercase“a”is97.

TocompareaninputStringvalue,wherethelettercaseenteredbytheuserisuncertain,againstaStringvalueintheprogramitisoftenusefultotransformtheinputintoaparticularcase.Forthispurpose,theStringclassprovidesatoUpperCase()methodandatoLowerCase()method.TheinputStringisspecifiedastheargument,andthemethodreturnsthetransformedString.

Atypicalexamplemightforceauser-inputpasswordStringtolowercasebeforecomparingittothecorrectpasswordstoredinalllowercaseinaStringvariablewithintheprogram.Thiswouldallowtheusertoentertheirpasswordinuppercase,lowercase,oramixtureofbothcaseswherecase-insensitivepasswordsarepermissible.

Dotnotationallowsmethodstobetackedontoothermethodssotheiroperationscanbeperformedinsequence.ThismeansthattoLowerCase().equals()canbeusedtotransformaStringvaluetolowercaseandthencomparethatlowercaseversionagainstaspecifiedargument.

Startanewprogramnamed“StringComparison”containingthestandardmainmethodclassStringComparison

{

publicstaticvoidmain(String[]args){}

}

StringComparison.java

Insidethemainmethod,createandinitializeaStringvariablewithacorrectlowercasepasswordStringpassword=“bingo”;

Addatrycatchstatementtocatchtheexceptionthatoccurswhennopassword

Page 126: Java in easy steps: Covers Java 9

argumentisenteredtry{}catch(Exceptione)

{

System.out.println(“Passwordrequired.”);

}

Insertthisifelsestatementintothetrystatementblocktoevaluatethepasswordargumententeredbytheuserif(args[0].toLowerCase().equals(password))

{

System.out.println(“Passwordaccepted.”);

}

else

{

System.out.println(“Incorrectpassword.”);

}

SavetheprogramasStringComparison.javathencompileandruntheprogramwithvariousarguments

Searchingstrings

Page 127: Java in easy steps: Covers Java 9

TheStringclasswithinthejava.langpackageprovidesstartsWith()andendsWith()methodstocompareportionsofaStringvalue.TheseareespeciallyusefultocompareanumberofStringvaluesandselectthosewithcommonbeginningsorcommonendings.WhentheStringsectionmatchesthespecifiedargument,themethodreturnstrue–otherwise,itreturnsfalse.

AportionofaStringvaluecanbecopiedbystatingthepositionnumberofthefirstcharactertobecopiedastheargumenttoitssubstring()method.ThiswillreturnasubstringoftheoriginalStringvalue,startingatthespecifiedstartpositionandendingattheendoftheoriginalString.

Optionally,thesubstring()methodcantakeasecondargumenttospecifythepositionnumberofthefinalcharactertobecopied.ThiswillreturnasubstringoftheoriginalStringvalue,startingatthespecifiedstartpositionandendingatthespecifiedendposition.

AStringvaluecanbesearchedtofindacharacterorsubstringspecifiedastheargumenttoitsindexOf()method.Unusually,thismethodreturnsthenumericpositionofthefirstoccurrenceofthematchedcharacterorsubstringwithinthesearchedStringvalue.Wherenomatchisfound,themethodreturnsthenegativeintegervalueof-1.

Startanewprogramnamed“StringSearch”containingthestandardmainmethodclassStringSearch

{

publicstaticvoidmain(String[]args){}

}

StringSearch.java

Insidethemainmethod,createaninitializedStringarrayofbooktitlesString[]books={“Javaineasysteps”,“XMLineasysteps”,“SQLineasysteps”,”CSSineasysteps”,“GoneWiththeWind”,“DroptheDefense”};

Page 128: Java in easy steps: Covers Java 9

Createandinitializethreeintcountervariablesintcounter1=0,counter2=0,counter3=0;

AddaforlooptoiteratethroughtheStringarray,listingasoutputthefirstfourcharactersofeachtitlefor(inti=0;i<books.length;i++)

{

System.out.print(books[i].substring(0,4)+“|“);

}

Insertastatementintheforloopblocktocountthetitlesfoundwithaspecifiedendingif(books[i].endsWith(“ineasysteps”))counter1++;

Insertastatementintheforloopblocktocountthetitlesfoundwithaspecifiedbeginningif(books[i].startsWith(“Java”))counter2++;

Insertastatementintheforloopblocktocountthetitlesfoundnotcontainingaspecifiedsubstringif(books[i].indexOf(“easy”)==-1)counter3++;

Attheendofthemainmethod,addthesestatementstooutputtheresultsofeachsearchSystem.out.println(“\nFound“+counter1+“titlesfromthisseries”);System.out.println(“Found“+counter2+“Javatitle”);System.out.println(“Found“+counter3+“othertitles”);

SavetheprogramasStringSearch.javathencompileandruntheprogramtoseetheoutput

Page 129: Java in easy steps: Covers Java 9

The!NOToperatorcannotbeusedtotestiftheindexOf()methodhasfailed–becauseitreturnsanintegervalue,notaBooleanvalue.

Manipulatingcharacters

TheStringclasswithinthejava.langpackageprovidesthetrim()methodthatisusedtoremoveanywhitespacefromthebeginningandendoftheStringspecifiedasitsargument.Thismethodwillremoveallextremespaces,newlines,andtabs,returningthetrimmedversionofthatString.

AnindividualcharacterinaStringcanbeaddressedbystatingitsindexpositionwithinthatStringastheargumenttoitscharAt()method.ThismethodtreatstheStringasanarrayofcharacterswherethefirstcharacterisatpositionzero–justlikeotherarrayswhoseelementsareindexedstartingatzero.ThefirstcharacterinaStringcanbeaddressedascharAt(0),thesecondcharacterascharAt(1),andsoon.

Ascharacterindexingbeginsatzero,thefinalcharacterinaStringwillalwayshaveanindexnumberthatisonelessthanthetotalnumberofcharactersintheString.ThismeansthatthefinalcharacterinanyStringhastheindexnumberequivalenttolength()-1.ThefinalcharacterinaStringnamed“str”can,therefore,beaddressedasstr.charAt(str.length()-1).

AlloccurrencesofaparticularcharacterinaStringcanbereplacedbyanothercharacterusingitsreplace()method.Thismethodrequirestwoargumentsthatspecifythecharactertobereplacedandthecharacterthatistotakeitsplace.Forexample,toreplacealloccurrencesoftheletter“a”withtheletter“z”,thesyntaxwouldbereplace(‘a’,‘z’).

TheisEmpty()methodcanbeusedtodiscoverifaStringcontainsnocharacters.ThismethodwillreturntrueiftheStringisabsolutelyempty,otherwiseitwillreturnfalse.

Startanewprogramnamed“CharacterSwap”containingthestandardmainmethodclassCharacterSwap

Page 130: Java in easy steps: Covers Java 9

{

publicstaticvoidmain(String[]args){}

}

CharacterSwap.java

Insidethemainmethod,declareandinitializeanemptyStringvariableStringtxt=““;

AssignsomecharacterstotheStringvariable,ifitisindeedempty,withbothleadingandtrailingspacesif(txt.isEmpty())txt=“Borrocudo“;

OutputtheStringvalueandthenumberofcharactersitcontainsSystem.out.println(“String:“+txt);System.out.println(“OriginalStringLength:“+txt.length());

Removetheleadingandtrailingspaces,thenoutputtheStringvalueanditssizeagaintxt=txt.trim();System.out.println(“String:“+txt);System.out.println(“StringLength:“+txt.length());

OutputthefirstcharacterintheStringcharinitial=txt.charAt(0);System.out.println(“FirstLetter:“+initial);

Now,outputthelastcharacterintheStringinitial=txt.charAt((txt.length()-1));System.out.println(“LastLetter:“+initial);

Replacealloccurrencesoftheletter“o”withletter“a”txt=txt.replace(‘o’,’a’);System.out.println(“String:“+txt);

SavetheprogramasCharacterSwap.javathencompileandruntheprogramtoseetheoutput

Page 131: Java in easy steps: Covers Java 9

Summary

• TheJavadocumentationprovidesinformationaboutthemethodsandpropertiesineachJavaclass.

• JavaclassesthatarefundamentaltotheJavalanguagearecontainedinthejava.langpackage,inthejava.basemodule.

• TheMathclassprovidesMath.PIandMath.Econstants.

• Math.pow()raisestoaspecifiedpowerandMath.sqrt()returnsthesquarerootofaspecifiednumber.

• NumberscanberoundedtoanintegervaluewithMath.round(),Math.floor(),andMath.ceil().

• NumberscanbecomparedwithMath.max()andMath.min().

• Math.random()returnsadoubleprecisionrandomnumberbetween0.0and0.999999999999999.

• AStringiszeroormorecharactersenclosedinquotemarks.

• Thelength()methodreturnsthesizeofitsString,muchlikethelengthpropertyofanarray.

• Theconcat()methodofaStringappendsanotherStringvalue.

• Theequals()methodofaStringonlyreturnstruewhentwoStringvalueshaveidenticalcharacters,inthesameorder.

Page 132: Java in easy steps: Covers Java 9

• CharactercaseofaStringcanbechangedusingitstoUpperCase()methodandtoLowerCase()method.

• StringvaluescanbecomparedusingthestartsWith()andendsWith()methodsofaString.

• AsubstringcanbesoughtinaStringusingitsindexOf()andsubstring()methods.

• TheisEmpty()methodonlyreturnstruewhentheStringcontainsabsolutelynothing.

• CharacterscanbemanipulatedwithinaStringvalueusingitstrim(),charAt(),andreplace()methods.

Page 133: Java in easy steps: Covers Java 9

6

Creatingclasses

ThischapterdemonstrateshowtocreateJavaprogramsthatemploymultiplemethodsandclasses.

FormingmultiplemethodsUnderstandingprogramscope

FormingmultipleclassesExtendinganexistingclassCreatinganobjectclassProducinganobjectinstance

EncapsulatingpropertiesConstructingobjectvaluesSummary

Formingmultiplemethods

Programsaretypicallysplitintoseparatemethodsinordertocreatemodulesofcodethateachperformtasks,andthatcanbecalledrepeatedlythroughouttheprogramasrequired.Splittingtheprogramintomultiplemethodsalsomakesiteasiertotrackdownbugs,aseachmethodcanbetestedindividually.Furthermethodsmaybedeclared,insidethecurlybracketsthatfollowtheclassdeclaration,usingthesamekeywordsthatareusedtodeclarethemainmethod.Eachnewmethodmustbegivenaname,followingtheusualnamingconventions,andmayoptionallyspecifyargumentsintheparenthesesafteritsname.

Page 134: Java in easy steps: Covers Java 9

Startanewprogramnamed“Methods”containingthestandardmainmethodclassMethods

{

publicstaticvoidmain(String[]args){}

}

Methods.java

Betweenthecurlybracketsofthemainmethod,insertstatementstooutputamessageandtocallasecondmethodnamed“sub”System.out.println(“Messagefromthemainmethod.”);sub();

Afterthemainmethod,beforethefinalcurlybracketoftheclass,addthesecondmethodtooutputamessagepublicstaticvoidsub()

{

System.out.println(“Messagefromthesubmethod.”);

}

SavetheprogramasMethods.javathencompileandruntheprogramtoseetheoutput

Page 135: Java in easy steps: Covers Java 9

Thesyntaxtocallamethodwithoutargumentsjustneedsthemethodname,followedbyparentheses.

Aclassmayevencontainmultiplemethodsofthesamenameprovidingtheyeachhavedifferentarguments–requiringadifferentnumberofarguments,orargumentsofdifferentdatatypes.Thisusefulfeatureisknownasmethod“overloading”.

Startanewprogramnamed“Overload”containingthestandardmainmethodclassOverload

{

publicstaticvoidmain(String[]args){}

}

Overload.java

Betweenthecurlybracketsofthemainmethod,insertthreestatementscallingdifferentoverloadedmethodsandpassingthemargumentvaluesSystem.out.println(write(12));System.out.println(write(“Twelve”));System.out.println(write(4,16));

Afterthemainmethod,beforethefinalcurlybracketoftheclass,addthethreeoverloadedmethodstoeachreturnaStringtothecallerpublicstaticStringwrite(intnum){return(“Integerpassedis“+num);}publicstaticStringwrite(Stringnum){return(“Stringpassedis“+num);}publicstaticStringwrite(intnum1,intnum2){return(“SumTotalis“+(num1*num2));}

Page 136: Java in easy steps: Covers Java 9

SavetheprogramasOverload.javathencompileandruntheprogramtoseetheoutput

ThedeclarationforeachoftheoverloadedmethodsmustindicatethatthemethodreturnsaStringvalue,notvoid.

Understandingprogramscope

Avariablethatisdeclaredinsideamethodisonlyaccessiblefrominsidethatmethod–its“scope”ofaccessibilityisonlylocaltothemethodinwhichitisdeclared.Thismeansthatavariableofthesamenamecanbedeclaredinanothermethodwithoutconflict.

Startanewprogramnamed“Scope”containingthestandardmainmethodclassScope

{

publicstaticvoidmain(String[]args){}

}

Scope.java

Page 137: Java in easy steps: Covers Java 9

BetweenthecurlybracketsofthemainmethoddeclareandinitializealocalStringvariable,thenoutputitsvalueStringtxt=“Thisisalocalvariableinthemainmethod”;System.out.println(txt);

Afterthemainmethod,beforethefinalcurlybracketoftheclass,addanothermethodnamed“sub”publicstaticvoidsub(){}

Betweenthecurlybracketsofthesubmethod,declareandinitializealocalStringvariableofthesamenameasthevariableinthemainmethodStringtxt=“Thisisalocalvariableinthesubmethod”;System.out.println(txt);

Insertacalltothesubmethodattheendofthemainmethodsub();

SavetheprogramasScope.javathencompileandruntheprogramtoseetheoutput

Acountervariabledeclaredinaforloopcannotbeaccessedoutsidetheloop–itsscopeislimitedtotheforstatementblock.

Thestatickeywordthatisusedinmethoddeclarationsensuresthatthemethodisa“classmethod”–globallyaccessiblefromanyothermethodintheclass.

Similarly,a“classvariable”canbedeclaredwiththestatickeywordtoensureitisgloballyaccessiblethroughouttheclass.Itsdeclarationshouldbemadebeforethemainmethoddeclaration,rightafterthecurlybracketfollowingtheclassdeclaration.

Aprogrammayhaveaglobalclassvariableandlocalmethodvariableofthe

Page 138: Java in easy steps: Covers Java 9

Aprogrammayhaveaglobalclassvariableandlocalmethodvariableofthesamename.Thelocalmethodvariabletakesprecedenceunlesstheglobalclassvariableisexplicitlyaddressedbytheclassnameprefixusingdotnotation,orifalocalvariableofthatnamehasnotbeendeclared.

EditScope.javabyinsertingaglobalclassStringvariableconstantofthesamenameasthelocalmethodvariablesfinalstaticStringtxt=“ThisisaglobalvariableoftheScopeclass”;

AddastatementattheendofthemainmethodtooutputthevalueoftheglobalclassvariableSystem.out.println(Scope.txt);

Commentoutthelinethatdeclaresthelocalvariableinthesubmethod–sotheoutputstatementwillnowaddresstheglobalvariableofthesamename//Stringtxt=“Thisisalocalvariableinthesubmethod”;

Savethechanges,thenrecompiletheprogramandrunitoncemoretoseetherevisedoutput

Uselocalmethodvariableswhereverpossibletoavoidconflicts–globalclassvariablesaretypicallyonlyusedforconstants.

Formingmultipleclasses

Inthesamewaythataprogrammayhavemultiplemethods,largerprogramsmayconsistofseveralclasses–whereeachclassprovidesspecificfunctionality.Thismodularformatisgenerallypreferabletowritingtheentireprogramina

Page 139: Java in easy steps: Covers Java 9

Thismodularformatisgenerallypreferabletowritingtheentireprograminasingleclassasitmakesdebuggingeasierandprovidesbetterflexibility.

Thepublickeywordthatappearsindeclarationsisan“accessmodifier”thatdetermineshowvisibleanitemwillbetootherclasses.Itcanbeusedintheclassdeclarationtoexplicitlyensurethatclasswillbevisibletoanyotherclass.Ifitisomitted,thedefaultaccesscontrollevelallowsaccessfromotherlocalclasses.Thepublickeywordmustalwaysbeusedwiththeprogram’smainmethod,however,sothatmethodwillbevisibletothecompiler.

Startanewprogramnamed“Multi”containingthestandardmainmethod–includingthepublickeywordasusualclassMulti

{

publicstaticvoidmain(String[]args){}

}

Multi.java

Betweenthecurlybracketsofthemainmethod,declareandinitializeaStringvariable,thenoutputitscontentsStringmsg=“ThisisalocalvariableintheMulticlass”;System.out.println(msg);

OutputthecontentsofaclassStringvariableconstantnamed“txt”fromaclassnamed“Data”System.out.println(Data.txt);

Callamethodnamed“greeting”fromtheDataclassData.greeting();

Callamethodnamed“line”fromaclassnamed“Draw”Draw.line();

SavetheprogramasMulti.java

Page 140: Java in easy steps: Covers Java 9

Thecompilerwillautomaticallyfindclassesinadjacentexternal.javafiles–andcreatecompiled.classfilesforeachone.

StartanewfilecreatingtheDataclassclassData

{

}

Data.java

DeclareandinitializeapublicclassvariableconstantpublicfinalstaticStringtxt=“ThisisaglobalvariableintheDataclass”;

Addapublic“greeting”classmethodpublicstaticvoidgreeting()

{

System.out.print(“Thisisaglobalmethod“);System.out.println(“oftheDataclass”);

}

SavethefileasData.javainthesamedirectoryastheMulti.javaprogramStartanewfilecreatingaDrawclassandaclass“line”methodfordefaultaccess–withoutthepublickeywordclassDraw

{

staticvoidline()

{

Page 141: Java in easy steps: Covers Java 9

System.out.println(“”);

}

}

Draw.java

SavethefileasDraw.javainthesamedirectoryastheMulti.javaprogram,thencompileandruntheprogramtoseetheoutput

Thepublickeywordallowsaccessfromanyotherclass,butdefaultaccessonlyallowsaccessfromclassesinthesamepackage.

Extendinganexistingclass

Aclasscaninheritthefeaturesofanotherclassbyusingtheextendskeywordintheclassdeclarationtospecifythenameoftheclassfromwhichitshouldinherit.Forexample,thedeclarationclassExtraextendsBaseinheritsfromtheBaseclass.

Theinheritingclassisdescribedasthe“sub”class,andtheclassfromwhichit

Page 142: Java in easy steps: Covers Java 9

inheritsisdescribedasthe“super”class.Intheexampledeclarationabove,theBaseclassisthesuperclassandtheExtraclassisthesubclass.

Methodsandvariablescreatedinasuperclasscangenerallybetreatedasiftheyexistedinthesubclassprovidingtheyhavenotbeendeclaredwiththeprivatekeyword,whichdeniesaccessfromoutsidetheoriginalclass.

Amethodinasubclasswilloverrideamethodofthesamenamethatexistsinitssuperclassunlesstheirargumentsdiffer.Themethodinthesuperclassmaybeexplicitlyaddressedusingitsclassnameanddotnotation.Forexample,SuperClass.run().

Itshouldbenotedthatatrycatchstatementinamethodwithinasuperclassdoesnotcatchexceptionsthatoccurinasubclass–thecallingstatementmustbeenclosedwithinitsowntrycatchstatementtocatchthoseexceptions.

Startanewclassnamed“SuperClass”classSuperClass{}

SuperClass.java

Betweenthecurlybracketsoftheclass,addamethodthatoutputsanidentifyingStringpublicstaticvoidhello()

{

System.out.println(“HellofromtheSuperClass”);

}

Addasecondmethodthatattemptstooutputapassedargument,thensavethefileasSuperClass.javapublicstaticvoidecho(Stringarg)

{

Page 143: Java in easy steps: Covers Java 9

try{System.out.println(“Youentered:“+arg);}catch(Exceptione){System.out.println(“Argumentrequired”);}

}

Startanewprogramnamed“SubClass”thatextendstheSuperClassclassclassSubClassextendsSuperClass

{

publicstaticvoidmain(String[]args){}

}

SubClass.java

Afterthemainmethod,addamethodthatoutputsanidentifyingString,overridingtheinheritedmethodofthesamenamepublicstaticvoidhello()

{

System.out.println(“HellofromtheSubClass”);

}

Betweenthecurlybracketsofthemainmethod,insertacalltotheoverridingmethodandthenexplicitlycallthemethodofthesamenameinthesuperclasshello();SuperClass.hello();

Addacalltotheotherinheritedmethodecho(args[0]);

SavetheprogramasSubClass.javathencompileandruntheprogramwithoutacommandlineargument

Page 144: Java in easy steps: Covers Java 9

EditSubClass.javatoenclosethemethodcallinStep7,toplaceitwithinitsowntrycatchstatementtocatchexceptions,thenrecompileandre-runtheprogramtoseetheproblemresolved

Youcanfindmoreinformationaboutcatchingexceptionshere.

Creatinganobjectclass

Real-worldobjectsareallaroundus,andtheyeachhaveattributesandbehaviorsthatwecandescribe:

• Attributesdescribethefeaturesthatanobjecthas• BehaviorsdescribeactionsthatanobjectcanperformForexample,acarmightbedescribedwithattributesof“red”and“coupe”,alongwithan“accelerates”behavior.

ThesefeaturescouldberepresentedinJavaprogrammingwithaCarclasscontainingvariablepropertiesofcolorandbodyType,alongwithanaccelerate()method.

JavaissaidtobeanObjectOrientedProgramming(OOP)languagebecauseit

Page 145: Java in easy steps: Covers Java 9

JavaissaidtobeanObjectOrientedProgramming(OOP)languagebecauseitmakesextensiveuseofobjectattributesandbehaviorstoperformprogramtasks.

ObjectsarecreatedinJavabydefiningaclassasatemplatefromwhichdifferentcopies,or“instances”,canbemade.

Eachinstanceoftheclasscanbecustomizedbyassigningattributevaluesandbehaviorstodescribethatobject.

TheCarclassiscreatedasaclasstemplateinthestepsdescribedopposite–withthedefaultattributesandbehavioroutlinedabove.AninstanceoftheCarclassiscreatedinthestepsdescribedhere,inheritingthesamedefaultattributesandbehavior.

Startanewtemplateclassnamed“Car”classCar

{

}

FirstObject.java

BetweenthecurlybracketsoftheCarclass,declareandinitializetwoglobalStringconstantsdescribingattributespublicfinalstaticStringcolor=“Red”;publicfinalstaticStringbodyType=“Coupe”;

AddaglobalmethoddescribingabehaviorpublicstaticStringaccelerate()

{

Stringmotion=“Accelerating...”;returnmotion;

}

AftertheCarclass,startanewprogramclassnamed“FirstObject”containingthestandardmainmethod

Page 146: Java in easy steps: Covers Java 9

classFirstObject

{

publicstaticvoidmain(String[]args){}

}

Betweenthecurlybracketsofthemainmethod,insertstatementstooutputthevalueofeachCarattributeandcallitsbehaviormethodSystem.out.println(“Paintis“+Car.color);System.out.println(“Styleis“+Car.bodyType);System.out.println(Car.accelerate());

SavetheprogramasFirstObject.javathencompileandruntheprogramtoseetheoutput

Thestatickeyworddeclaresclassvariablesandclassmethods–inthiscase,asmembersoftheCarclass.

Objectclassesarenormallycreatedbeforetheprogramclasscontainingthemainmethod.

Page 147: Java in easy steps: Covers Java 9

Producinganobjectinstance

Eachclasshasabuilt-in“constructor”methodthatcanbeusedtocreateanewinstanceofthatclass.Theconstructormethodhasthesamenameastheclass,andisinvokedwiththenewkeyword.

Eachinstanceofaclassinheritstheobject’sattributesandbehaviors.TheprincipleofinheritanceisusedthroughoutJavasothatprogramscanuseready-madeproperties.

Tobemoreflexible,objectclasstemplatescanbedefinedinafileotherthanthatcontainingtheprogram.Thismeanstheycanbereadilyusedbymultipleprograms.

Startanewfile,repeatingtheCarclassobjecttemplatefromthepreviousexamplehereclassCar

{

publicfinalstaticStringcolor=“Red”;publicfinalstaticStringbodyType=“Coupe”;publicstaticStringaccelerate()

{

Stringmotion=“Accelerating...”;returnmotion;

}

}

Car.java

SavethefileasCar.java

Page 148: Java in easy steps: Covers Java 9

Startanewprogramnamed“FirstInstance”containingthestandardmainmethodclassFirstInstance

{

publicstaticvoidmain(String[]args){}

}

FirstInstance.java

Betweenthecurlybracketsofthemainmethod,insertstatementstooutputthevalueofeachattributeoftheCarclassandcallitsbehaviormethodSystem.out.println(“Carpaintis“+Car.color);System.out.println(“Carstyleis“+Car.bodyType);System.out.println(Car.accelerate());

Now,addastatementtocreateaPorscheinstanceoftheCarclassCarPorsche=newCar();

AddstatementstooutputtheinheritedvalueofeachPorscheattributeandcallitsbehaviormethodSystem.out.println(“Porschepaintis“+Porsche.color);System.out.println(“Porschestyleis“+Porsche.bodyType);System.out.println(Porsche.accelerate());

SavetheprogramasFirstInstance.javaalongsidetheCar.javatemplatefile,thencompileandruntheprogramtoseetheoutput

Page 149: Java in easy steps: Covers Java 9

Youcannotaddressthemotionvariabledirectly–itisoutofscopewithinthemethoddeclaration.

AvirtualclassiscreatedforthenewPorscheobjectthatreplicatestheoriginalCarclass.Boththeseobjectscontainstatic“classvariables”anda“classmethod”,whichareaddressedusingtheclassnameanddotnotation–asthesemembersaregloballyaccessible,thisisnotconsideredgoodprogrammingpractice.

Whilstthisexampledemonstrateshowinstancesofanobjectinheritpropertiesoftheoriginalclass,itisimprovedinthenextexampleherethatusesnon-staticmemberstocreate“instancevariables”andan“instancemethod”,whichcannotbeaddressedfromoutsidethatclass–asthesemembersarenotgloballyaccessible,thisisconsideredgoodprogrammingpractice.

ThecompilerautomaticallyfindstheCarclassintheexternal.javafile–andcreatesacompiled.classfileforit.

Encapsulatingproperties

Theprivatekeywordcanbeusedwhendeclaringobjectvariablesandmethodstoprotectthemfrommanipulationbyexternalprogramcode.Theobjectshouldthenincludepublicmethodstoretrievethevaluesandcallthemethods.Thistechniqueneatlyencapsulatesthevariablesandmethodswithintheobjectstructure.Itisdemonstratedinthefollowingstepsthatreproducethepreviousexample–butwithencapsulatedattributesandmethod:

Startanewclassnamed“Car”classCar

{

Page 150: Java in easy steps: Covers Java 9

{

}

SafeInstance.java

Betweenthecurlybracketsoftheclass,declarethreeprivateStringvariablestostoreobjectattributesprivateStringmaker;privateStringcolor;privateStringbodyType;

AddaprivatemethoddescribingabehaviorprivateStringaccelerate()

{

Stringmotion=“Accelerating...”;returnmotion;

}

AddapublicmethodtoassignpassedargumentvaluestoeachprivatevariablepublicvoidsetCar(Stringbrand,Stringpaint,Stringstyle)

{

maker=brand;color=paint;bodyType=style;

}

AddanotherpublicmethodtoretrievetheprivatevariablevaluesandtocalltheprivatemethodpublicvoidgetCar()

{

System.out.println(maker+”paintis“+color);

Page 151: Java in easy steps: Covers Java 9

System.out.println(maker+“styleis“+bodyType);System.out.println(maker+“is“+accelerate()+”\n”);

}

AftertheendoftheCarclass,startanotherclassnamed“SafeInstance”containingthestandardmainmethodclassSafeInstance

{

publicstaticvoidmain(String[]args){}

}

Betweenthecurlybracketsofthemainmethod,insertastatementtocreateaninstanceoftheCarclassCarPorsche=newCar();

AddastatementthatcallsapublicmethodoftheCarclasstoassignvaluestoitsprivatevariablesPorsche.setCar(“Porsche”,”Red”,”Coupe”);

NowaddastatementtocalltheotherpublicmethodoftheCarclasstoretrievethestoredattributevaluesandcalltheprivatebehaviormethodPorsche.getCar();

Createanotherinstance,assigningandretrievingvaluesCarBentley=newCar();Bentley.setCar(“Bentley”,”Green”,”Saloon”);Bentley.getCar();

SavetheprogramasSafeInstance.javathencompileandruntheprogramtoseetheoutput

Page 152: Java in easy steps: Covers Java 9

AnuninitializedStringvariablehasanullvalue–socallingthegetCar()methodbeforesetCar()willreturnanullfromeachvariable.

Constructingobjectvalues

Anobject’sconstructormethodcanbecalleddirectlyintheobjectclasstoinitializeobjectvariables.Thishelpstokeepthedeclarationsandassignmentsseparate,andisconsideredtobegoodprogrammingstyle.Itisdemonstratedinthefollowingstepsthatreproducethepreviousexampleherewithencapsulatedattributesandmethod–togetherwithinitializationbytheconstructor:

Startanewclassnamed“Car”classCar

{

}

Constructor.java

Betweenthecurlybracketsoftheclass,declarethreeprivateStringvariablestostoreobjectattributesprivateStringmaker;privateStringcolor;privateStringbodyType;

AddaconstructormethodthatinitializesallthreevariableswithattributevaluespublicCar()

{

maker=“Porsche”;

Page 153: Java in easy steps: Covers Java 9

color=“Silver”;bodyType=“Coupe”;

}

AddaprivatemethoddescribingabehaviorprivateStringaccelerate()

{

Stringmotion=“Accelerating...”;returnmotion;

}

AddapublicmethodtoassignpassedargumentvaluestoeachprivatevariablepublicvoidsetCar(Stringbrand,Stringpaint,Stringstyle)

{

maker=brand;color=paint;bodyType=style;

}

Constructormethoddeclarationsdonotstateanyreturndatatype.

AddanotherpublicmethodtoretrievetheprivatevariablevaluesandtocalltheprivatemethodpublicvoidgetCar()

{

System.out.println(maker+”paintis“+color);System.out.println(maker+“styleis“+bodyType);System.out.println(maker+“is“+accelerate()+”\n”);

}

Page 154: Java in easy steps: Covers Java 9

}

AftertheendoftheCarclass,startanotherclassnamed“Constructor”containingthestandardmainmethodclassConstructor

{

publicstaticvoidmain(String[]args){}

}

Betweenthecurlybracketsofthemainmethod,insertstatementstocreateaninstanceoftheCarclassandretrievetheinitialdefaultvaluesCarPorsche=newCar();Porsche.getCar();

Createanotherinstance,assigningandretrievingvaluesCarFerrari=newCar();Ferrari.setCar(“Ferrari”,”Red”,”Sport”);Ferrari.getCar();

SavetheprogramasConstructor.javathencompileandruntheprogramtoseetheoutput

Summary

• Splittingprogramsintomultiplemethods,whichcanbecalleduponwhenrequired,increasesflexibilityandmakesiteasiertotrackdownbugs.

• Overloadedmethodshavethesamenamebuttakedifferentarguments.

• Variablesdeclaredwithinamethodhavelocalscope,butclassvariableshave

Page 155: Java in easy steps: Covers Java 9

globalscopethroughoutthatclass.

• Thestatickeywordisusedtodeclareclassmethodsandclassvariables–havingglobalscopethroughoutthatclass.

• Thepublickeywordexplicitlyallowsaccessfromanyclass.

• Aclassdeclarationcanincludetheextendskeywordtonominateasuperclassfromwhichitwillinherit.

• Theclassnameanddotnotationcanbeusedtoexplicitlyaddressaparticularclassmethodorclassvariable.

• Real-worldobjectshaveattributesandbehaviorsthatcanberepresentedinprogramsbyvariablesandmethods.

• Javaobjectsarecreatedasatemplateclassfromwhichinstancecopiescanbemade.

• Eachclasshasaconstructormethodthatcanbeinvokedusingthenewkeywordtocreateaninstancecopyofthatclass.

• Instancesinherittheattributesandbehaviorsoftheclassfromwhichtheyarederived.

• Encapsulationprotectsinstancevariablesandinstancemethodsfrommanipulationbyexternalclasses.

• Theprivatekeyworddeniesaccessfromoutsidetheclasswherethedeclarationismade.

• Anobject’sconstructormethodcanbecalledtoinitializevariableattributesofthatobject.

Page 156: Java in easy steps: Covers Java 9

7

Importingfunctions

ThischapterdemonstrateshowtoimportadditionalprogramfunctionalityfromspecializedJavaclasses.

HandlingfilesReadingconsoleinput

ReadingfilesWritingfilesSortingarrayelementsMakingarraylists

ManagingdatesFormattingnumbersSummary

Handlingfiles

Javacontainsapackagenamedjava.iothatisdesignedtohandlefileinputandoutputprocedures.Thepackagecanbemadeavailabletoaprogrambyincludinganimportstatementattheverybeginningofthe.javafile.Thiscanusethe*wildcardcharactertomean“allclasses”inthestatementimportjava.io.*;.

Thejava.iopackagehasaclassnamed“File”thatcanbeusedtoaccessfilesorcompletedirectories.AFileobjectmustfirstbecreatedusingthenewkeywordandspecifyingthefilename,ordirectoryname,astheconstructor’sargument.Forexample,thesyntaxtocreateaFileobjectnamed“info”torepresentalocal

Page 157: Java in easy steps: Covers Java 9

filenamed“info.dat”lookslikethis:Fileinfo=newFile(“info.dat”);

Thisfilewouldbelocatedinthesamedirectoryastheprogram,buttheargumentcouldstatethepathtoafilelocatedelsewhere.NotethatthecreationofaFileobjectdoesnotactuallycreateafile,butmerelythemeanstorepresentafile.

OnceaFileobjecthasbeencreatedtorepresentafile,itsmethodscanbecalledtomanipulatethefile.ThemostusefulFileobjectmethodsarelistedinthistable,togetherwithabriefdescription:

Method: Returns:

exists() trueifthefileexists–falseifitdoesnot

getName() thefilenameasaString

length() numberofbytesinthefile,asalongtype

createNewFile() trueifabletocreatethenewuniquefile

delete() trueifabletosuccessfullydeletethefile

renameTo(File) trueifabletosuccessfullyrenamethefile

list() anarrayoffileorfoldernamesasStrings

Thefilenamespecifiedastheconstructorargumentmustbeenclosedwithinquotes.

Startanewprogramthatimportsthefunctionalityofallthejava.ioclassesimportjava.io.*;

ListFiles.java

Page 158: Java in easy steps: Covers Java 9

Addaclassnamed“ListFiles”containingthestandardmainmethodclassListFiles

{

publicstaticvoidmain(String[]args){}

}

Betweenthecurlybracketsofthemainmethod,insertastatementtocreateaFileobjectforadirectoryfoldernamed“data”Filedir=newFile(“data”);

Addanifstatementtooutputthenamesofallfilesinthatfolder,oramessageifthefolderisemptyif(dir.exists())

{

String[]files=dir.list();System.out.println(files.length+“filesfound...”);for(inti=0;i<files.length;i++)

{

System.out.println(files[i]);

}

}

else{System.out.println(“Foldernotfound.”);}

SavetheprogramasListFiles.javaalongsidea“data”foldercontainingsomefiles,thencompileandruntheprogramtoseethefilenameslistedasoutput

Page 159: Java in easy steps: Covers Java 9

Readingconsoleinput

Thejava.iopackageallowsaprogramtoreadinputfromthecommandline–interactingwiththeuser.JustastheSystem.outfieldcansendoutputtothecommandline,theSystem.infieldcanbeusedtoreadfromitwithanInputStreamReaderobject.Thisreadstheinputasbytes,whichitconvertsintointegervaluesthatrepresentUnicodecharactervalues.

Inordertoreadanentirelineofinputtext,thereadLine()methodofaBufferedReaderobjectreadsthecharactersdecodedbytheInputStreamReader.ThismethodmustbecalledfromwithinatrycatchstatementtocatchanyIOExceptionproblems.

Typically,thereadLine()methodwillassigntheinputtoaStringvariableformanipulationbytheprogram.

Startanewprogramthatimportsthefunctionalityofallthejava.ioclassesimportjava.io.*;

ReadString.java

Addaclassnamed“ReadString”containingthestandardmainmethodclassReadString

{

publicstaticvoidmain(String[]args){}

Page 160: Java in easy steps: Covers Java 9

}

Betweenthecurlybracketsofthemainmethod,insertastatementtooutputamessagepromptingtheuserforinputSystem.out.print(“Enterthetitleofthisbook:“);

AddastatementcreatinganInputStreamReaderobject,enablinginputtobereadfromthecommandlineInputStreamReaderisr=newInputStreamReader(System.in);

CreateaBufferedReaderobjecttoreadthedecodedinputBufferedReaderbuffer=newBufferedReader(isr);

DeclareandinitializeanemptyStringvariableinwhichtostoretheinputStringinput=““;

Addatrycatchstatementtoreadtheinputfromthecommandlineandstoreitinthevariable

try

{

input=buffer.readLine();buffer.close();

}

catch(IOExceptione)

{

System.out.println(“Aninputerrorhasoccurred”);

}

OutputamessagethatincludesthestoredvalueSystem.out.println(“\nThanks,youarereading“+input);

SavetheprogramasReadString.javathencompileandruntheprogram

Page 161: Java in easy steps: Covers Java 9

Entertextasprompted,thenhitReturntoseetheoutputmessagecontainingyourinputtext

Itisgoodpracticetocalltheclose()methodoftheBufferedReaderobjectwhenitisnolongerneeded.

Readingfiles

Thejava.iopackagecontainsaclassnamedFileReaderthatisespeciallydesignedtoreadtextfiles.ThisclassisasubclassoftheInputStreamReaderclassthatcanbeusedtoreadconsoleinputbyconvertingabytestreamintointegersthatrepresentUnicodecharactervalues.

AFileReaderobjectiscreatedusingthenewkeyword,andtakesthenameofthefiletobereadasitsargument.Optionally,theargumentcanincludethefullpath

Page 162: Java in easy steps: Covers Java 9

toafileoutsidethedirectorywheretheprogramislocated.

Inordertoefficientlyreadthetextfileline-by-line,thereadLine()methodofaBufferedReaderobjectcanbeemployedtoreadthecharactersdecodedbytheFileReaderobject.ThismethodmustbecalledfromwithinatrycatchstatementtocatchanyIOExceptionproblemsthatmayarise.

ReadingalllinesinatextfilecontainingmultiplelinesoftextisaccomplishedbymakingrepeatedcallstothereadLine()methodinaloop.Attheendofthefilethecallwillreturnanullvalue,whichcanbeusedtoterminatetheloop.

Openaplaintexteditor,suchasWindowsNotepad,andwriteafewlinesoftext–forexample,afamousversefrom“TheBalladofReadingGaol”byOscarWilde

SavethetextfileasOscar.txtthenstartanewprogramthatimportsthefunctionalityofallthejava.ioclassesimportjava.io.*;

ReadFile.java

Addaclassnamed“ReadFile”containingthestandardmainmethodclassReadFile{publicstaticvoidmain(String[]args){}}

Betweenthecurlybracketsofthemainmethod,insertatrycatchstatementtry{}catch(IOExceptione)

{

System.out.println(“Areaderrorhasoccurred”);

}

Page 163: Java in easy steps: Covers Java 9

}

Betweenthecurlybracketsofthetryblock,insertastatementtocreateaFileReaderobjectFileReaderfile=newFileReader(“Oscar.txt”);

CreateaBufferedReaderobjecttoreadthefileBufferedReaderbuffer=newBufferedReader(file);

DeclareandinitializeanemptyStringvariableinwhichtostorealineoftextStringline=““;

Addalooptoreadthetextfilecontentsintothevariableandoutputeachlineoftextwhile((line=buffer.readLine())!=null){System.out.println(line);}

RemembertoclosetheBufferedReaderobjectwhenitisnolongerneededbuffer.close();

SavetheprogramasReadFile.javaalongsidethetextfile,thencompileandruntheprogramtoseetheoutput

ThetextfilespecifiedastheFileReaderargumentmustbeenclosedwithinquotationmarks.

Writingfiles

Page 164: Java in easy steps: Covers Java 9

Inthejava.iopackagetheFileReaderandBufferedReaderclasses,whichareusedtoreadtextfiles,havecounterpartsnamedFileWriterandBufferedWriterthatcanbeusedtowritetextfiles.

AFileWriterobjectiscreatedusingthenewkeyword,andtakesthenameofthefiletobewrittenasitsargument.Optionally,theargumentcanincludethefullpathtoafiletobewritteninadirectoryoutsidethatinwhichtheprogramislocated.

TheBufferedWriterobjectiscreatedwiththenewkeyword,andtakesthenameoftheFileWriterobjectasitsargument.Textcanthenbewrittenwiththewrite()methodoftheBufferedWriterobject,andlinesseparatedbycallingitsnewLine()method.ThesemethodsshouldbecalledfromwithinatrycatchstatementtocatchanyIOExceptionproblemsthatmayarise.

Ifafileofthespecifiednamealreadyexists,itscontentswillbeoverwrittenbythewrite()method,otherwiseanewfileofthatnamewillbecreatedanditscontentswritten.

Startanewprogramthatimportsthefunctionalityofallthejava.ioclassesimportjava.io.*;

WriteFile.java

Addaclassnamed“WriteFile”containingthestandardmainmethodclassWriteFile

{

publicstaticvoidmain(String[]args){}

}

Betweenthecurlybracketsofthemainmethod,insertatrycatchstatementtry{}catch(IOExceptione)

{

Page 165: Java in easy steps: Covers Java 9

System.out.println(“Awriteerrorhasoccurred”);

}

Betweenthecurlybracketsofthetryblock,insertastatementtocreateaFileWriter

objectforatextfilenamed“Tam.txt”FileWriterfile=newFileWriter(“Tam.txt”);

CreateaBufferedWriterobjecttowritethefileBufferedWriterbuffer=newBufferedWriter(file);

Addstatementstowritelinesoftextandnewlinecharactersintothetextfile–forexample,atranslatedversefrom“TamO’Shanter”byRobertBurnsbuffer.write(“Thewindblewasifithadblownitslast”);

buffer.newLine();buffer.write(“Therattlingshowersroseonitsblast”);

buffer.newLine();buffer.write(“Thespeedygleamsthedarknessswallowed”);

buffer.newLine();buffer.write(“Loud,deepandlongthethunderbellowed”);

buffer.newLine();buffer.write(“Thatnightachildmightunderstand”);

buffer.newLine();buffer.write(“Thedevilhadbusinessonhishand.”);

RemembertoclosetheBufferedWriterobjectwhenitisnolongerneededbuffer.close();

SavetheprogramasWriteFile.javathencompileandruntheprogramtowritethetextfilealongsidetheprogram

Page 166: Java in easy steps: Covers Java 9

Youcancalltheappend()methodoftheBufferedWriterobjecttoaddtext–ratherthanoverwritingtextwiththewrite()method.

Sortingarrayelements

Javacontainsapackagenamedjava.utilthatprovidesusefulutilitiesforhandlingcollectionsofdata.Thepackagecanbemadeavailabletoaprogrambyincludinganimportstatementattheverybeginningofthe.javafile.Thiscanusethe*wildcardcharactertomean“allclasses”inthestatementimportjava.util.*;.

Thejava.utilpackagehasaclassnamed“Arrays”thathasmethodswhichcanbeusedtomanipulatearrays.Itsfunctionalitycanbemadeavailabletotheprogrambyimportingallclassesfromthejava.utilpackageor,wheretheprogramonlyrequiresasingleclass,theimportstatementcanimportjustthatspecificclass.Forexample,theprogramcanimporttheArraysclasswiththestatementimportjava.util.Arrays;.

TheArraysclasshasasort()methodthatcanrearrangethecontentsofarrayelementsalphabeticallyandnumerically.

Startanewprogramthatimportsthefunctionalityofallmethodsinthejava.util.Arraysclassimportjava.util.Arrays;

Page 167: Java in easy steps: Covers Java 9

Sort.java

Addaclassnamed“Sort”containingthestandardmainmethodclassSort{publicstaticvoidmain(String[]args){}}

Afterthemainmethod,insertamethodtodisplayallelementcontentsofapassedStringarraypublicstaticvoiddisplay(String[]elems)

{

System.out.println(“\nStringArray:”);for(inti=0;i<elems.length;i++)System.out.println(“Element”+i+“is”+elems[i]);

}

Addanoverloadedversionofthedisplay()methodtodisplayallelementcontentsofapassedintarraypublicstaticvoiddisplay(int[]elems)

{

System.out.println(“\nIntegerArray:”);for(inti=0;i<elems.length;i++)System.out.println(“Element”+i+“is”+elems[i]);

}

Seehereformoreonoverloadingmethods.

Betweenthecurlybracketsofthemainmethod,declareandinitializeaStringarrayandanintarrayString[]names={“Mike”,“Dave”,“Andy”};int[]nums={200,300,100};

Outputthecontentsofallelementsineacharraydisplay(names);

display(nums);

SorttheelementcontentsofbotharraysArrays.sort(names);

Page 168: Java in easy steps: Covers Java 9

Arrays.sort(nums);

Outputthecontentsofallelementsineacharrayagaindisplay(names);

display(nums);

SavetheprogramasSort.javathencompileandruntheprogramtoseetheoutput

Theforloopsinthisexampleeachexecuteasinglestatementsonocurlybracketsarerequired–buttheycouldbeaddedforclarity.

Makingarraylists

Thejava.utilpackagecontainsaclassnamedArrayListthatstoresdatainanordered“Collection”(resizablesequence)oflistelements.Thiscanbemadeavailabletoaprogrambyimportingthespecificclasswithimportjava.util.ArrayList;.Alistmaycontainduplicateelements,andanArrayListobjecthasusefulmethodsthatallowmanipulationofstoredvaluesbyspecifyingtheir

Page 169: Java in easy steps: Covers Java 9

elementindexnumber.Forexample,thelist’smethodcallget(0)willretrievethevaluestoredinthefirstelementwhereasremove(1)willremovethesecondlistelement.

Elementvaluescanbemodifiedbyspecifyingtheindexnumberandnewvalueasargumentstothelist’sset()method.Elementscanbeaddedtothelistataparticularpositionbyspecifyingtheindexnumberandvalueasargumentstothelist’sadd()method.Thelistexpandstoaccommodateadditionalelementsbymovingtheelementvaluesalongtheindex.

Youcandiscoverhowmanyelementsalistcurrentlyhasbycallingitssize()method.

AnArrayListobjectissimplycreatedusingthenewkeywordbut,likeotherJavacollections,thestatementmustspecifywhichgenerictypeofitemthelistmaycontain.Typically,alistmaycontainStringitems,soArrayListmusthavea<String>suffix.

Collections,suchasArrayList,haveaforEach()methodthatiteratesovereachelementinthelist.Thismakesiteasytoloopthroughallitemscontainedinthelist.

Eachstoredlistitemcanbeconvenientlyreferencedinturnbyspecifyinga“lambdaexpression”astheargumenttotheforEach()method.Lambdaexpressionsaresimplyshort,anonymous(un-named)methodsthatcanbespecifiedinthelocationtheyaretobeexecuted.Theybeginwithparentheses,tocontainanyarguments,thenhavea->charactersequencefollowedbythestatementblock,withthissyntax:(argument/s)->{statement/s}

Thedatatypeoftheargumentscanbeexplicitlydeclared,oritcanbeinferredfromthecontext–(Stringx)canbesimply(x).Additionally,thecurlybracketscanbeomittedifthelambdaexpressionstatementblockcontainsonlyonestatement.

Withalist’sforEach()methodthevalueofthecurrentelementintheiterationcanbepassedtothelambdaexpressionasitsargument,thendisplayedinoutputby

Page 170: Java in easy steps: Covers Java 9

itsstatement.

LambdaexpressionswereintroducedinJava8toenablesuccinctanonymousmethods.

Startanewprogramthatimportsthefunctionalityofallmethodsinthejava.util.ArrayListclassimportjava.util.ArrayList;

Lists.java

Addaclassnamed“Lists”containingthestandardmainmethodclassLists{publicstaticvoidmain(String[]args){}}

Betweenthecurlybracketsofthemainmethod,insertastatementtocreateaStringArrayListobjectnamed“list”ArrayList<String>list=newArrayList<String>();

Next,addstatementstopopulatethelistelementswithStringvaluesthendisplaytheentirelistlist.add(“Alpha”);list.add(“Delta”);list.add(“Charlie”);System.out.println(“List:”+list);

Now,identifythecurrentvalueinthesecondelementthenreplaceitwithanewStringSystem.out.println(“Replacing:”+list.get(1)+“\n”);list.set(1,“Bravo”);

Finally,iteratethroughthelistanddisplaytheStringvaluenowstoredineachelementlist.forEach((x)->System.out.println(“Item:“+x));

SavetheprogramasLists.javathencompileandruntheprogramtoseetheoutput

Page 171: Java in easy steps: Covers Java 9

Aswithregulararrays,elementsinanArrayListhaveazero-basedindex.

ThegraphicalJavaSwingJComboBoxcomponentthatisintroducedhereholdsadrop-downlistofoptions,somustalsospecifyitsgenericdatatypewhenthatobjectgetscreated.

Managingdates

Thejava.timepackagecontainsaclassnamedLocalDateTimethathasusefulmethodstoextractspecificfieldsfromaLocalDateTimeobjectthatdescribeaparticularpointintime.Thesecanbemadeavailabletoaprogrambyimportingthespecificclasswithimportjava.time.LocalDateTime;orbyimportingallclassesinthispackageusingthewildcardwithimportjava.time.*;.

Page 172: Java in easy steps: Covers Java 9

Thejava.timepackagewasintroducedinJava8tomakeiteasiertoworkwithdatesandtimes.

AnewLocalDateTimeobjectcanbecreatedwithfieldsdescribingthecurrentdateandtimeusingitsnow()method.Thefieldsareinitializedfromthesystemclockforthecurrentlocale.

ThevaluewithinanindividualfieldcanberetrievedusinganappropriatemethodoftheLocalDateTimeobject.Forexample,thevalueoftheyearfieldcanberetrievedusingitsgetYear()method.Similarly,anyfieldcanbechangedusinganappropriatemethodoftheLocalDateTimeobjecttospecifyareplacementvalue.Forexample,thevalueoftheyearfieldcanbechangedbyspecifyinganewyearvalueasanargumenttoitswithYear()method.

Startanewprogramthatimportsthefunctionalityofallmethodsinthejava.time.LocalDateTimeclassimportjava.time.LocalDateTime;

DateTime.java

Addaclassnamed“DateTime”containingthestandardmainmethodclassDateTime

{

publicstaticvoidmain(String[]args){}

}

Betweenthecurlybracketsofthemainmethod,insertastatementtocreateacurrentLocalDateTimeobjectLocalDateTimedate=LocalDateTime.now();

OutputthecurrentdateandtimedetailsSystem.out.println(“\nItisnow”+date);

Incrementtheyear,andoutputthereviseddateandtimedate=date.withYear(2019);System.out.println(“\nDateisnow”+date);

OutputindividualLocalDateTimefieldsofthereviseddateStringfields=

Page 173: Java in easy steps: Covers Java 9

“\nYear:\t\t\t”+date.getYear();

fields+=“\nMonth:\t\t\t”+date.getMonth();

fields+=“\nMonthNumber:\t\t”+date.getMonthValue();

fields+=“\nDay:\t\t\t”+date.getDayOfWeek();

fields+=“\nDayNumber:\t\t”+date.getDayOfMonth();

fields+=“\nDayNumberOfYear:\t”+date.getDayOfYear();

fields+=“\nHour(0-23):\t\t”+date.getHour();

fields+=“\nMinute:\t\t\t”+date.getMinute();

fields+=“\nSecond:\t\t\t”+date.getSecond();

System.out.println(fields);

SavetheprogramasDateTime.javathencompileandruntheprogramtoseetheoutput

ConcatenatingaStringlikethismeanstheprogrammakesjustonecall

Page 174: Java in easy steps: Covers Java 9

toprintln()tooutputfielddetails–thisismoreefficientthancallingprintln()manytimestooutputeachindividualfieldseparately.

YoucanalternativelyusetheZonedDateTimeclassinsteadofLocalDateTimeifyoualsorequireatimezonefield.

Formattingnumbers

Javacontainsapackagenamedjava.textthatprovidesusefulclassesforformattingnumbersandcurrency.Thepackagecanbemadeavailabletoaprogrambyincludinganimportstatementattheverybeginningofthe.javafile.Thiscanusethe*wildcardcharactertomean“allclasses”inthestatementimportjava.text.*;.Alternatively,specificclassescanbeimportedbyname.

Thejava.textpackagehasaclassnamed“NumberFormat”,whichhasmethodsthatcanbeusedtoformatnumericalvaluesforoutput–addinggroupseparators,currencysigns,andpercentagesigns.

ThemethodusedtocreateanewNumberFormatobjectdeterminesitsformattingtype–getNumberInstance()forgroupseparators,getCurrencyInstance()forcurrencysigns,andgetPercentInstance()forpercentagesigns.Formattingisappliedbyspecifyingthenumericalvaluetobeformattedastheargumenttotheformat()methodoftheNumberFormatobject.

Thejava.time.formatpackagewasintroducedinJava8tomakeiteasiertospecifydateformatpatterns.

Thejava.time.formatpackagehasaDateTimeFormatterclassthatcanbeusedtoformatjava.timedatesandtimeobjects.ADateTimeFormatterobjectcontainsaformatterpatternthatisspecifiedasastringargumenttoitsofPattern()method.

Page 175: Java in easy steps: Covers Java 9

Theformattercomprisesletters,definedintheJavadocumentation,andyourchoiceofseparators.Forexample,“M/d/y”specifiesthemonth,day,andyear,separatedbyslashes.Theformatisappliedbyspecifyingtheformatterastheargumenttotheformat()methodofajava.timedateandtimeobject.

StartanewprogramthatimportsthefunctionalityofallmethodsoftheNumberFormatclassinthejava.textpackageandallmethodsoftheDateTimeFormatterclassinthejava.time.formatpackageimportjava.text.NumberFormat;importjava.time.format.DateTimeFormatter;

Formats.java

Addaclassnamed“Formats”containingthestandardmainmethodclassFormats

{

publicstaticvoidmain(String[]args)

{

}

}

Betweenthecurlybracketsofthemainmethod,insertstatementstooutputanumberwithgroupseparatorsNumberFormatnf=NumberFormat.getNumberInstance();System.out.println(“\nNumber:“+nf.format(123456789));

AddstatementstooutputanumberwithacurrencysignNumberFormatcf=NumberFormat.getCurrencyInstance();System.out.println(“\nCurrency:“+cf.format(1234.50f));

AddstatementstooutputanumberwithapercentsignNumberFormatpf=NumberFormat.getPercentInstance();System.out.println(“\nPercent:“+pf.format(0.75f));

AddastatementcreatingacurrentLocalDateTimeobject

Page 176: Java in easy steps: Covers Java 9

java.time.LocalDateTimenow=java.time.LocalDateTime.now();

AddstatementstooutputaformattednumericaldateDateTimeFormatterdf=DateTimeFormatter.ofPattern(“MMMd,yyy”);System.out.println(“\nDate:“+now.format(df));

AddstatementstooutputaformattednumericaltimeDateTimeFormattertf=DateTimeFormatter.ofPattern(“h:ma”);System.out.println(“\nTime:“+now.format(tf));

SavetheprogramasFormats.javathencompileandruntheprogramtoseetheformattedoutput

Astatementcanaddressaclassthathasnotbeenimportedbyusingitsfullpackageaddress–asseenhereinthestatementcreatingaLocalDateTimeobject.

Patternlettersarecasesensitive–refertothedocumentationtodiscover

Page 177: Java in easy steps: Covers Java 9

thefulldetailsofpossiblepatterns.

Summary

• Oneormoreimportstatementscanbeincludedatthestartofaprogramtomakethefunctionalityofotherclassesavailable.

• Animportstatementcanimportallclassesinapackagewitha*wildcardcharacter,orindividualclassesbyname.

• Thejava.iopackagehasclassesthataredesignedtohandleinputandoutputprocedures.

• AFileobjectcanbeusedtoaccessfilesanddirectories.

• TheInputStreamReaderobjectdecodesinputbytesintocharacters,andtheBufferedReaderreadsitsdecodedcharacters.

• AFileReaderobjectcanbeusedtodecodetextfilebytesintocharactersforreadingbyaBufferedReaderobject.

• AFileWriterobjectandBufferedWriterobjectcancreateandupdatetextfiles.

• Thejava.utilpackagecontainsutilitiesforhandlingcollectionsofdata,suchasarraymanipulationwithitsArraysclass.

• Thejava.utilpackagealsocontainsanArrayListclassthathasmethodstoeasilymanipulatesequencedlistitems.

• AnArrayListobjectisaCollectionthatmustspecifythegenerictypeofitemthatlistmaycontain,suchas<String>.

• Alambdaexpressionisananonymousmethodthatcanbespecifiedwhereitistobeexecuted.

• Thejava.timepackagecontainsaLocalDateTimeclassthatprovidesfieldsfordateandtimecomponents.

• Thejava.textpackagecontainsaNumberFormatclassthatcanformatnumbersandcurrency.

• Thejava.time.formatpackagecontainsaDateTimeFormatterclassthatcanspecifypatternstoformatdatesandtimes.

Page 178: Java in easy steps: Covers Java 9

8

Buildinginterfaces

ThischapterdemonstrateshowtouseJavaSwingcomponentstocreateagraphicalprograminterface.

CreatingawindowAddingpushbuttons

AddinglabelsAddingtextfieldsAddingitemselectorsAddingradiobuttons

ArrangingcomponentsChangingappearanceSummary

Creatingawindow

Programscanprovideagraphicaluserinterface(GUI)usingthe“Swing”componentsoftheJavalibrary.Thejavax.swingpackagecontainsclassestocreateavarietyofcomponentsusingthestyleofthenativeoperatingsystem.Thesecanbemadeavailabletoaprogrambyincludingtheinitialstatementimportjavax.swing.*;.

AclassmustbecreatedtorepresenttheGUItowhichcomponentscanbeaddedtobuildtheinterface.ThisiseasilyachievedbydeclaringitasubclassofSwing’sJFrameclassusingtheextendskeyword–therebyinheritingattributes

Page 179: Java in easy steps: Covers Java 9

andbehaviorsthatallowtheusertomove,resize,andclosethewindow.

Remembertheletterxinjavax.swingbythinkingofJAVAeXtra.

Theclassconstructorshouldincludestatementstosettheseminimumrequirements:• Thetitleofthewindow–specifiedasaStringargumenttotheinheritedsuper()methodoftheJFrameclass.

• Thesizeofthewindow–specifiedaswidthandheightinpixelsasargumentstoitssetSize()method.

• Whattodowhentheuserclosesthewindow–specifiedasaconstantargumenttoitssetDefaultCloseOperation()method.

• Displaythewindow–specifiedasaBooleanargumenttoitssetVisible()method.

Additionally,theconstructorcanaddaJPanelcontainercomponenttothewindow,inwhichsmallercomponentscanbeadded,usingtheinheritedadd()methodoftheJFrameclass.

Bydefault,aJPanelcontaineremploysaFlowLayoutlayoutmanagerthatlaysoutcomponentsinleft-to-rightlines,wrappingattherightedgeofthewindow.

ThestepsoppositedescribehowtocreateabasicwindowcontainingaJPanelcontainerwithaFlowLayoutlayoutmanager.ThiswindowisfeaturedinsubsequentexamplesinthisbookthatdemonstratehowtoaddvariouscomponentstotheJPanelcontainer.

Layoutmanagersaredescribedinmoredetailhere.

StartanewprogramthatimportsallSwingcomponentsimportjavax.swing.*;

Page 180: Java in easy steps: Covers Java 9

Window.java

CreateasubclassoftheJFrameclassnamed“Window”containingthestandardmainmethodclassWindowextendsJFrame

{

publicstaticvoidmain(String[]args){}

}

Beforethemainmethod,createaJPanelcontainerobjectJPanelpnl=newJPanel();

Next,insertthisconstructormethodtospecifywindowrequirementsandtoaddtheJPanelobjecttotheJFramepublicWindow()

{

super(“SwingWindow”);setSize(500,200);setDefaultCloseOperation(EXIT_ON_CLOSE);add(pnl);setVisible(true);

}

CreateaninstanceoftheWindowclassbyinsertingthislineintothemainmethodWindowgui=newWindow();

SavetheprogramasWindow.javathencompileandruntheprogramtoseethebasicwindowappear

Page 181: Java in easy steps: Covers Java 9

TheEXIT_ON_CLOSEoperationisaconstantmemberoftheJFrameclass.Itexitstheprogramwhenthewindowgetsclosed.

Noticehowtheadd()methodisusedheretoaddtheJPanelobjecttotheJFramewindow.

Addingpushbuttons

TheSwingJButtonclasscreatesapush-buttoncomponentthatcanbeaddedtoagraphicalinterface.Thisletstheuserinteractwiththeprogrambyclickingonabuttontoperformanaction.

TheJButtonobjectiscreatedwiththenewkeyword,anditsconstructortakesaStringargumentspecifyingtexttobedisplayedonthatbutton.

Page 182: Java in easy steps: Covers Java 9

Imagescanappearonbuttonstoo.AnImageIconobjectmustfirstbecreatedtorepresenttheimage,specifyingtheimagefilenameastheargumenttoitsconstructor.Typically,theimagewillbelocatedalongsidetheprogrambuttheargumentcanincludethepathforimagesoutsidethelocaldirectory.

Detailsofhowtocreateevent-handlermethodstorespondtouseractions,suchasabuttonclick,canbefoundinthenextchapter.

SpecifythenameoftheImageIconobjectastheargumenttotheJButtonconstructortodisplaythatimageonthebutton,orspecifyaStringandImageIconasitstwoargumentstodisplaybothtextandtheimage.

EditacopyofWindow.javafromhere,changingtheclassnameinthedeclaration,theconstructor,andtheinstancestatementfrom“Window”to“Buttons”

Buttons.java

BeforetheButtons()constructor,createtwoImageIconobjectsImageIcontick=newImageIcon(“Tick.png”);ImageIconcross=newImageIcon(“Cross.png”);

Next,createthreeJButtonobjectstodisplaytext,animage,andbothtextandanimagerespectivelyJButtonbtn=newJButton(“ClickMe”);JButtontickBtn=newJButton(tick);JButtoncrossBtn=newJButton(“STOP”,cross);

InsidetheButtons()constructor,insertthreestatementstoaddtheJButtoncomponentstotheJPanelcontainerpnl.add(btn);pnl.add(tickBtn);pnl.add(crossBtn);

Page 183: Java in easy steps: Covers Java 9

SavetheprogramasButtons.javathencompileandruntheprogramtoseepushbuttonsappearinthewindow

TheJPanelobjecthasanadd()method–toaddcomponentstothatpanel.

DetailsofhowtocreateaJavaArchive(JAR)canbefoundhere.

Thebuttonsrespondgraphicallywhentheyareclicked,butwillnotperformanactionuntiltheprogramprovidesanevent-handlermethodtorespondtoeachclickevent.

WheretheprogramisintendedfordeploymentinasingleJavaarchive(JAR),imageresourcesmustbeloadedbyaClassLoaderobjectbeforecreatingtheImageIconobjectstorepresentthem.

Page 184: Java in easy steps: Covers Java 9

SpecifyingtheresourcefilenameorpathtothegetResource()methodofaClassLoaderreturnsaURL,whichcanbeusedastheargumenttotheImageIconconstructor.Thejava.netpackageprovidesausefulURLclasstowhichthesemayfirstbeassigned.

BeforetheButtons()constructor,createaClassLoaderobjectClassLoaderldr=this.getClass().getClassLoader();

LoadtheURLsoftheimageresourcesjava.net.URLtickURL=ldr.getResource(“Tick.png”);java.net.URLcrossURL=ldr.getResource(“Cross.png”);

EdittheImageIcon()constructorsinStep2oppositetouseURLsImageIcontick=newImageIcon(tickURL);ImageIconcross=newImageIcon(crossURL);

Savethechangesthenrecompileandre-runtheprogram–itwillrunasbeforebutcannowbedeployedinaJAR

NoticehowthegetClass()methodandthiskeywordareusedheretoreferencethisclassobject.

Addinglabels

TheSwingJLabelclasscreatesalabelcomponentthatcanbeaddedtoagraphicalinterface.Thiscanbeusedtodisplaynon-interactivetextorimage,orbothtextandanimage.

TheJLabelobjectiscreatedwiththenewkeyword,anditsconstructortakesaStringargumentspecifyingtexttobedisplayedonthatlabel,orthenameofanImageIconobjectrepresentinganimagetodisplay.Itcanalsotakethreeargumentstospecifytext,image,andhorizontalalignmentasaJLabelconstantvalue.Forexample,JLabel(“text”,img,JLabel.CENTER)alignscentrally.

WhereaJLabelobjectcontainsbothtextandanimage,therelativepositionofthetextcanbedeterminedbyspecifyingaJLabelconstantastheargumentto

Page 185: Java in easy steps: Covers Java 9

setVerticalPosition()andsetHorizontalPosition()methodsoftheJLabelobject.

Additionally,aJLabelobjectcanbemadetodisplayaToolTipwhenthecursorhoversover,byspecifyingatextStringastheargumenttothatobject’ssetToolTipText()method.

EditacopyofWindow.javafromhere,changingtheclassnameinthedeclaration,theconstructor,andtheinstancestatementfrom“Window”to“Labels”

Labels.java

BeforetheLabels()constructor,createanImageIconobjectImageIconduke=newImageIcon(“Duke.png”);

Next,createthreeJLabelobjectstodisplayanimage,text,andbothtextandanimagerespectivelyJLabellbl1=newJLabel(duke);JLabellbl2=newJLabel(“DukeisthefriendlymascotofJavatechnology.”);JLabellbl3=newJLabel(“Duke”,duke,JLabel.CENTER);

InsidetheLabels()constructor,insertthisstatementtocreateaToolTipforthefirstlabellbl1.setToolTipText(“Duke-theJavaMascot”);

Addthesetwostatementstoalignthetextcentrallybelowthethirdlabellbl3.setHorizontalTextPosition(JLabel.CENTER);lbl3.setVerticalTextPosition(JLabel.BOTTOM);

Now,addthreestatementstoaddtheJLabelcomponentstotheJPanelcontainerpnl.add(lbl1);pnl.add(lbl2);pnl.add(lbl3);

SavetheprogramasLabels.javathencompileandruntheprogram,placingthecursoroverthefirstlabel

Page 186: Java in easy steps: Covers Java 9

JLabelalignmentconstantsincludeLEFT,CENTER,RIGHT,TOPandBOTTOM.

WheretheprogramisintendedfordeploymentinasingleJavaarchive(JAR),theimageresourcemustbeloadedbyaClassLoaderobjectbeforecreatingtheImageIconobjecttorepresentit.

SpecifyingtheresourcefilenameorpathtothegetResource()methodofaClassLoaderreturnsaURL,whichcanbeusedastheargumenttotheImageIconconstructor.

BeforetheLabels()constructor,createaClassLoaderobjectClassLoaderldr=this.getClass().getClassLoader();

EdittheImageIcon()constructorinStep2oppositetoloadtheURLoftheimageresourceusingtheClassLoaderobjectImageIconduke=newImageIcon(ldr.getResource(“Duke.png”));

Savethechanges,thenrecompileandre-runtheprogram–itwillrunasbefore,butcannowbedeployedinaJAR

Page 187: Java in easy steps: Covers Java 9

DetailsofhowtocreateaJavaArchive(JAR)canbefoundhere.

Addingtextfields

TheSwingJTextFieldclasscreatesasingle-linetextfieldcomponentthatcanbeaddedtoagraphicalinterface.Thiscanbeusedtodisplayeditabletext,andallowstheusertoentertexttointeractwiththeprogram.

TheJTextFieldobjectiscreatedwiththenewkeyword,anditsconstructorcantakeaStringargumentspecifyingdefaulttexttobedisplayedinthatfield.Inthiscase,thecomponentwillbesizedtoaccommodatethelengthoftheString.Alternatively,theargumentmaybeanumericvaluetospecifythetextfieldsize.Theconstructorcanalsotaketwoarguments,specifyingbothdefaulttextandthetextfieldsize.

UsetheJPasswordFieldclassinsteadoftheJTextFieldclasswhereinputcharactersareneededtobenotvisible.

Amultiple-linetextfieldcanbecreatedwiththeJTextAreaclass,whoseconstructortakestwonumericalargumentsspecifyingitsnumberoflinesanditswidth.Alternatively,threeargumentscanbesuppliedspecifyingdefaulttext,linenumber,andwidth.TextcanbemadetowrapatwordendingswithinthisfieldbyspecifyingtrueastheargumenttothesetLineWrap()methodandsetWrapStyleWord()methodoftheJTextAreaobject.

WheretextenteredintoaJTextAreacomponentexceedsitsinitialsize,thecomponentwillexpandtoaccommodatethetext.Tomakethecomponentafixedsizewithscrollingcapability,itcanbeplacedinaJScrollPanecontainer.Thisiscreatedwiththenewkeyword,andtakesthenameoftheJTextAreaasitsargument.

Page 188: Java in easy steps: Covers Java 9

Scrollbarswill,bydefault,onlyappearwhenthefieldcontainstextthatexceedsitsinitialsize–buttheycanbemadetoappearconstantlybyspecifyingaJScrollPaneconstantastheargumenttothesnappily-namedsetVerticalScrollBarPolicy()orsetHorizontalScrollBarPolicy()methodsoftheJScrollPaneobject.Forexample,toalwaysdisplayaverticalscrollbarusetheJScrollPane.VERTICAL_SCROLLBAR_ALWAYSconstantastheargument.

EditacopyofWindow.javafromhere,changingtheclassnameinthedeclaration,theconstructor,andtheinstancestatementfrom“Window”to“TextFields”

TextFields.java

BeforetheTextFields()constructor,createtwoJTextFieldobjectsJTextFieldtxt1=newJTextField(38);JTextFieldtxt2=newJTextField(“DefaultText”,38);

CreateaJTextAreaobjectfivelineshighJTextAreatxtArea=newJTextArea(5,37);

AddaJScrollPaneobject–tocontaintheJTextAreacreatedinStep3,aboveJScrollPanepane=newJScrollPane(txtArea);

IntheTextFields()constructormethod,insertstatementstoenabletheJTextAreaobjecttowrapatwordendingstxtArea.setLineWrap(true);txtArea.setWrapStyleWord(true);

InsertastatementtoalwaysdisplayaverticalscrollbarfortheJTextAreaobjectpane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

InserttwostatementstoaddtheJTextFieldcomponentstotheJPanelcontainerpnl.add(txt1);pnl.add(txt2);

InsertanotherstatementtoaddtheJScrollPanecontainer,(containingtheJTextAreafield)totheJPanelcontainerpnl.add(pane);

Page 189: Java in easy steps: Covers Java 9

SavetheprogramasTextFields.javathencompileandruntheprogram,enteringsometextintothetextarea

AJTextAreacomponenthasnoscrollingabilityunlessitiscontainedwithinaJScrollPanecomponent.

Addingitemselectors

TheSwingJCheckBoxclasscreatesacheckboxcomponentthatcanbeaddedtoagraphicalinterface.Thiscanbeusedtoallowtheusertoselectordeselectindividualitemsinaprogram.TheJCheckBoxobjectiscreatedwiththenewkeyword,anditsconstructortakesaStringargumentspecifyingtexttobedisplayedalongsidethatcheckbox.Itcanalsotakeasecondtrueargumenttomakethecheckboxbeselectedbydefault.

AchoiceofitemscanbeofferedbytheJComboBoxclassthatcreatesadrop-downlistfromwhichtheusercanselectanysingleitem.Thisobjectiscreatedwiththenewkeyword,anditsconstructortypicallytakesthenameofaStringarrayasitsargument.Eachelementinthearrayprovidesanitemforselectioninthedrop-downlist.Similarly,achoiceofitemscanbeofferedbytheJListclass

Page 190: Java in easy steps: Covers Java 9

thatcreatesafixed-sizelistfromwhichtheusercanselectoneormoreitems.Itiscreatedwiththenewkeyword,anditsconstructoralsotakesanarrayasitsargument,witheachelementprovidinganitemforselection.AsbothJListandJComboBoxare“Collections”theymustspecifythegenerictypetheymaycontainwhentheygetcreated,suchas<String>.

EditacopyofWindow.javafromhere,changingtheclassnameinthedeclaration,theconstructor,andtheinstancestatementfrom“Window”to“Items”

Items.java

BeforetheItems()constructor,createaStringarrayofitemsforselectionString[]toppings={“Pepperoni”,“Mushroom”,“Ham”,“Tomato”};

Next,createfourJCheckBoxobjectstopresenteacharrayitemforselection–withoneselectedbydefaultJCheckBoxchk1=newJCheckBox(toppings[0]);JCheckBoxchk2=newJCheckBox(toppings[1],true);JCheckBoxchk3=newJCheckBox(toppings[2]);JCheckBoxchk4=newJCheckBox(toppings[3]);

AddasecondStringarrayofitemsforselectionString[]styles={“DeepDish”,“GourmetStyle”,“Thin&Crispy”};

CreateaJComboBoxobjecttopresenteachiteminthesecondarrayforselectionJComboBox<String>box1=newJComboBox<String>(styles);

AddaJListobjecttopresenteachiteminthefirstarrayforselectionfromalistJList<String>lst1=newJList<String>(toppings);

IntheItems()constructormethod,insertstatementstoaddeachJCheckBoxcomponenttotheJPanelcontainerpnl.add(chk1);pnl.add(chk2);pnl.add(chk3);pnl.add(chk4);

InsertstatementstomakeadefaultselectionandtoaddtheJComboBox

componenttotheJPanelcontainerbox1.setSelectedIndex(0);

Page 191: Java in easy steps: Covers Java 9

pnl.add(box1);

Now,insertastatementtoaddtheJListcomponenttotheJPanelcontainerpnl.add(lst1);

SavetheprogramasItems.javathencompileandruntheprogram,selectingitemsfromthelists

OnlyoneitemcanbeselectedfromaJComboBoxcomponent–multipleitemscanbeselectedfromaJListcomponent.

Detailsofhowtocreateevent-handlermethodstorespondtouseractions,suchasanitemselection,canbefoundinChapter9.

Addingradiobuttons

Page 192: Java in easy steps: Covers Java 9

TheSwingJRadioButtonclasscreatesaradiobuttoncomponentthatcanbeaddedtoagraphicalinterface.Thiscanbeusedtoallowtheusertoselectanitemfromagroupofradiobuttons.

TheJRadioButtonobjectiscreatedwiththenewkeyword,anditsconstructortakesaStringargumentspecifyingtexttobedisplayedalongsidethatradiobutton.Itcanalsotakeasecondtrueargumenttomakearadiobuttonbeselectedbydefault.

AButtonGroupobjectlogicallygroupsanumberofradiobuttonssothatonlyonebuttoninthatgroupcanbeselectedatanytime.EachradiobuttonisaddedtotheButtonGroupobjectbyspecifyingitsnameastheargumenttothegroup’sadd()method.

EditacopyofWindow.javafromhere,changingtheclassnameinthedeclaration,theconstructor,andtheinstancestatementfrom“Window”to“Radios”

Radios.java

BeforetheRadios()constructor,createthreeJRadioButtonobjects–withoneselectedbydefaultJRadioButtonrad1=newJRadioButton(“Red”,true);JRadioButtonrad2=newJRadioButton(“Rosé”);JRadioButtonrad3=newJRadioButton(“White”);

Next,createaButtonGroupobjectwithwhichtogrouptheradiobuttonsButtonGroupwines=newButtonGroup();

IntheRadios()constructormethod,insertstatementstoaddeachJRadioButtoncomponenttotheJButtonGroupwines.add(rad1);wines.add(rad2);wines.add(rad3);

InsertstatementstoaddtheJRadioButtoncomponentstotheJPanelcontainerpnl.add(rad1);pnl.add(rad2);pnl.add(rad3);

Page 193: Java in easy steps: Covers Java 9

SavetheprogramasRadios.javathencompileandruntheprogram,selectinganyoneradiobuttonafterthedefault

TheButtonGroupobjectonlygroupsthebuttonslogically,notphysically.

Detailsofhowtocreateevent-handlermethodstorespondtouseractionscanbefoundinthenextchapter.

TheexamplesonthepreviouspageshavedemonstratedthemostcommonSwingcomponents–JButton,JLabel,JTextField,JCheckBox,JComboBox,JListandJRadioButton.Therearemanymorespecializedcomponentsavailableinthejavax.swingpackage,whosedetailscanbefoundintheJavadocumentation.Forexample,theJSlider,JProgressBar,andJMenuBarcomponentsbelow:

Page 194: Java in easy steps: Covers Java 9

TryusingtheJavadocumentationtoaddaJSlidercomponenttotheRadiosprogram–seeherefordetailsonhowtousethedocumentation.

Arrangingcomponents

Thejava.awtpackage(AbstractWindowToolkit)containsanumberoflayoutmanagerclassesthatcanbeusedtoplacecomponentsinacontainerindifferentways.

Alayoutmanagerobjectiscreatedusingthenewkeyword,andcanthenbespecifiedastheargumenttoaJPanelconstructortohavethepanelusethatlayout.Whencomponentsgetaddedtothepaneltheywillbeplacedaccordingtotherulesofthespecifiedlayoutmanager.

LayoutManager: Rules:

BorderLayoutPlacesNorth,South,East,WestandCenter(thecontentpanedefault)

Page 195: Java in easy steps: Covers Java 9

BoxLayoutPlacesinasingleroworcolumn

CardLayoutPlacesdifferentcomponentsinaspecifiedareaatdifferenttimes

FlowLayoutPlaceslefttorightinawrappingline(theJPaneldefault)

GridBagLayoutPlacesinagridofcells,allowingcomponentstospancells

GridLayoutPlacesinagridofrowsandcolumns

GroupLayoutPlaceshorizontallyandvertically

SpringLayoutPlacesbyrelativespacing

ThetoplevelJFrameobjecthasa“contentpane”containerthatplacescomponentsusingtheBorderLayoutlayoutmanagerbydefault.ThiscanbeusedtoplaceuptofiveJPanelcontainers,whichmayeachusetheirdefaultFlowLayoutlayoutmanager,oranyofthelayoutmanagersinthetableabove.Usingavarietyoflayoutmanagersaccommodatesmostlayoutrequirements.

Thecontentpanecanberepresentedbyajava.awt.Containerobject,whoseadd()methodcanspecifythepositionandnameofacomponenttobeplacedwithinthecontentpane.

Page 196: Java in easy steps: Covers Java 9

Youcanfindfurtherdetailsofeachlayoutmanagerinthejava.awtsectionoftheJavadocumentation.

EditacopyofWindow.javafromhere,changingtheclassdeclaration,constructor,andinstancefrom“Window”to“Layout”,thenaddastatementatthestartoftheprogramtoimportthefunctionalityofthejava.awtpackageimportjava.awt.*;

Layout.java

BeforetheLayout()constructor,createaContainerobjectrepresentingtheJFrame

contentpanecontainerContainercontentPane=getContentPane();

CreateasecondJPanelobjectusingaGridLayoutlayoutmanagerina2x2gridJPanelgrid=newJPanel(newGridLayout(2,2));

IntheLayout()constructormethod,insertstatementsaddingJButtoncomponentstobothJPanelobjectspnl.add(newJButton(“Yes”));pnl.add(newJButton(“No”));pnl.add(newJButton(“Cancel”));grid.add(newJButton(“1”));grid.add(newJButton(“2”));grid.add(newJButton(“3”));grid.add(newJButton(“4”));

Now,insertstatementsaddingbothpanelsandabuttontothecontentpanecontentPane.add(“North”,pnl);contentPane.add(“Center”,grid);contentPane.add(“West”,newJButton(“West”));

SavetheprogramasLayout.javathencompileandruntheprogramtoseethecomponentlayout

Page 197: Java in easy steps: Covers Java 9

WhiletheFlowLayoutmaintainstheJButtonsize,otherlayoutmanagersexpandthecomponentstofilltheirlayoutdesign.

Changingappearance

Thejava.awtpackage(AbstractWindowToolkit)contains“painting”classesthatcanbeusedtocolorinterfacecomponents.Thesecanbemadeavailabletoaprogrambyincludingtheinitialstatementimportjava.awt.*;.

Includedinthejava.awtpackageisaColorclassthathasconstantsrepresentingafewbasiccolors,suchasColor.RED.Additionally,instancesoftheColorclasscanbecreatedusingthenewkeywordtorepresentcustomcolors.Theconstructorcantakethreeintegerargumentsbetweenzeroand255torepresentred,green,andblue(RGB)valuestoformthecustomcolor.

EachcomponenthasasetBackground()methodandasetForeground()methodthattakeaColorobjectastheirargumenttopaintthatcomponentwiththespecifiedcolor.

NotethatthebackgroundofJLabelcomponentsaretransparentbydefault,soitisrecommendedthattheirsetOpaque()methodshouldbecalledtosettheopacitytotruebeforetheyarepainted.

Alsointhejava.awtpackageisaFontclassthatcanbeusedtomodifythefontdisplayingtext.AFontobjectrepresentsafont,anditsconstructorcantakethreeargumentstospecifyname,styleandsize:

Page 198: Java in easy steps: Covers Java 9

• Thespecifiednameshouldbeoneofthethreeplatform-independentnames“Serif”,“SansSerif”or“Monospaced”.

• Thespecifiedstyleshouldbeoneofthefollowingthreeconstants:Font.PLAIN,Font.BOLDorFont.ITALIC

• Thespecifiedsizeshouldbeanintegerofthepointsize.

EachcomponenthasasetFont()methodthattakesaFontobjectasitsargumenttopaintthatcomponentwiththespecifiedfont.

EditacopyofWindow.javafromhere,changingtheclassnameinthedeclaration,theconstructor,andtheinstancestatementfrom“Window”to“Custom”

Custom.java

Addastatementattheverystartoftheprogramtoimportthefunctionalityofallclassesinthejava.awtpackageimportjava.awt.*;

BeforetheCustom()constructor,createthreeJLabelobjectsJLabellbl1=newJLabel(“CustomBackground”);JLabellbl2=newJLabel(“CustomForeground”);JLabellbl3=newJLabel(“CustomFont”);

Next,createColor,Font,andBoxlayoutobjectsColorcustomColor=newColor(255,0,0);FontcustomFont=newFont(“Serif”,Font.PLAIN,64);Boxbox=Box.createVerticalBox();

IntheCustom()constructormethod,insertstatementstocoloraJLabelbackgroundusingaColorconstantlbl1.setOpaque(true);lbl1.setBackground(Color.YELLOW);

InsertastatementtocoloraJLabelforegroundusingacustomColorobjectlbl2.setForeground(customColor);

InsertastatementtopainttextonaJLabelcomponentusingacustomfontlbl3.setFont(customFont);

Page 199: Java in easy steps: Covers Java 9

Addeachlabeltothelayoutcontainerbox.add(lbl1);box.add(lbl2);box.add(lbl3);

Then,addthelayoutcontainertotheJPanelcontainerpnl.add(box);

SavetheprogramasCustom.javathencompileandruntheprogramtoseetheeffect

Inthiscase,thecustomcolorisequivalenttoColor.REDastheRGBvaluespecifiesthemaximumredvaluewithnogreenorblue.

ABoxobjectisahandylightweightcontainerthatusesBoxLayoutasitslayoutmanager.TheBoxobject’screateVerticalBox()methodindividuallydisplaysitscomponentsfromtoptobottom.

Summary

• Thejavax.swingpackagecontainstheJavaSwingclassesthatareusedtocreateGUIcomponents.

• Awindowiscreatedasatop-levelJFramecontainer.

• TheJFrameconstructorshouldspecifythewindow’stitle,size,defaultclose

Page 200: Java in easy steps: Covers Java 9

operationandvisibility.

• AJPanelcontainerdisplayssmallercomponentsinawrappinglineusingitsdefaultFlowLayoutlayoutmanager.

• TheJButtonconstructorcanspecifytextandimagestobedisplayedonapushbuttoncomponent.

• AnImageIconobjectrepresentsanimagetouseintheprogram.

• ProgramsthataretobedeployedasasingleJavaarchive(JAR)shoulduseaClassLoaderobjecttospecifyanimagesource.

• AJLabelobjectdisplaysnon-interactivetextandimagecontent.

• EditabletextcanbedisplayedinJTextFieldandJTextAreafields.

• AJScrollPaneobjectprovidesscrollbarsforaJTextAreafield.

• ItemsforselectioncanbedisplayedwithJCheckBox,JComboBoxandJListcomponents.

• AButtonGroupobjectlogicallygroupsanumberofJRadioButtoncomponentssoonlyonecanbeselected.

• SpecificRGBcolorscanberepresentedbytheColorclassofthejava.awtpackage.

• Thejava.awtpackagehasaFontclassthatcanbeusedtocreateobjectsrepresentingaparticularfontname,style,andsize.

• MultipleJPanelcontainerscanbeaddedtoaJFramecontainerbyusingtheContainerclassofthejava.awtpackagetorepresentthecontentpaneoftheJFrame.

• WhencreatingaJPanelcontainerobject,itsargumentmayoptionallyspecifyalayoutmanager.

Page 201: Java in easy steps: Covers Java 9

9

Recognizingevents

ThischapterdemonstrateshowtocreateJavaprogramevent-handlersthatrespondtouserinterface

actions.

ListeningforeventsGeneratingevents

HandlingbuttoneventsHandlingitemeventsReactingtokeyboardeventsRespondingtomouseevents

AnnouncingmessagesRequestinginputSummary

Listeningforevents

Ausercaninteractwithaprogramthatprovidesagraphicaluserinterface(GUI)byperformingactionswithamouse,keyboard,orotherinputdevice.Theseactionscause“events”tooccurintheinterface,andmakingaprogramrespondtothemisknownas“event-handling”.

ForaprogramtorecognizeusereventsitneedstohaveoneormoreEventListenerinterfacesaddedfromthejava.awt.eventpackage.Thesecanbemadeavailabletotheprogrambyaddinganinitialstatementtoimportjava.awt.event.*;.

Page 202: Java in easy steps: Covers Java 9

ThedesiredEventListenerinterfacecanbeincludedintheclassdeclarationusingtheimplementskeyword.Forexample,aclassdeclarationtolistenforbuttonclicksmightlooklikethis:classClickextendsJFrameimplementsActionListener{}

TheJavadocumentationdescribesmanyEventListenerinterfacesthatcanlistenoutfordifferentevents,butthemostcommononesarelistedinthetablebelow,togetherwithabriefdescription:

EventListener: Description:

ActionListenerRecognizesactioneventsthatoccurwhenapushbuttonispushedorreleased

ItemListenerRecognizesitemeventsthatoccurwhenalistitemgetsselectedordeselected

KeyListenerRecognizeskeyboardeventsthatoccurwhentheuserpressesorreleasesakey

MouseListenerRecognizesmousebuttonactionsthatoccurwhentheuserpressesorreleasesamousebutton,andwhenthemouseentersorexitsacomponent

MouseMotionListenerRecognizesmotioneventsthatoccurwhentheusermovesthemouse

MultipleEventListenerscanbeincludedaftertheimplementskeywordasacomma-separatedlist.

Page 203: Java in easy steps: Covers Java 9

Generatingevents

ComponentsneedtogenerateeventsthattheEventListenerinterfacescanrecognizeiftheyaretobeuseful.HavingaddedtheappropriateEventListenertotheprogram,asdescribedopposite,aneventgeneratormustbeaddedtothecomponent.

Forexample,inordertohavetheprogramrespondtoabuttonclick,theActionListenerinterfaceisaddedtotheprogramandthebutton’saddActionListener()methodmustbecalled,specifyingthethiskeywordasitsargument.Thismakesthebuttongenerateaneventwhenitgetsclicked,whichcanberecognizedbytheActionListenerinterface.

Statementscreatingabuttonthatgenerateseventslooklikethis:JButtonbtn=newJButton(“ClickMe”);btn.addActionListener(this);

Whentheuserclicksabuttonthatgeneratesanevent,theActionListenerinterfacerecognizestheeventandseeksanevent-handlermethodwithintheprogramtoexecutearesponse.

EachEventListenerinterfacehasanassociatedevent-handlermethodthatiscalledwhenaneventisrecognized.Forexample,whenabuttongetsclicked,theActionListenerinterfacecallsanassociatedmethodnamedactionPerformed()andpassesanActionEventobjectasitsargument.

AnActionEventobjectcontainsinformationabouttheeventandthesourcecomponentfromwhereitoriginated.Mostusefully,ithasagetSource()methodthatidentifiestheobjectthatgeneratedtheevent.Thiscanbeusedtocreateanappropriateresponseforthatcomponent.

Anevent-handlermethodtocreatearesponseforaspecificbuttonclickcouldlooklikethis:

publicvoidactionPerformed(ActionEventevent)

{

if(event.getSource()==btn)

{

Page 204: Java in easy steps: Covers Java 9

Statementstobeexecutedforthisbuttonclickevent}

}

Handlingbuttonevents

ASwingJButtoncomponentthatissettogenerateanActionEventeventwhenitgetsclickedcanberecognizedbytheActionListenerinterface,whichwillpasstheeventtoitsactionPerformed()event-handlermethod.TheActionEventobjecthasagetSource()methodthatidentifiestheoriginatingcomponent,andagetActionCommand()methodthatreturnsaString.Thiswillbethetextlabelforabuttoncomponent,orthecontentforatextfieldcomponent.

OneresponsetoabuttonmightbetodisableacomponentbycallingitssetEnabled()methodwithafalseargument.Conversely,thecomponentcanbeenabledoncemorebyspecifyingatrueargumenttoitssetEnabled()method.

EditacopyofWindow.javafromhere,changingtheclassnameinthedeclaration,theconstructor,andtheinstancestatementfrom“Window”to“Actions”

Actions.java

Addastatementattheverystartoftheprogramtoimportthefunctionalityofallclassesinthejava.awt.eventpackageimportjava.awt.event.*;

EdittheclassdeclarationtoaddanActionListenerinterfacetotheprogramclassActionsextendsJFrameimplementsActionListener

BeforetheActions()constructor,createtwoJButtonpushbuttonsandaJTextAreatextfieldJButtonbtn1=newJButton(“Button1”);JButtonbtn2=newJButton(“Button2”);JTextAreatxtArea=newJTextArea(5,38);

AddthebuttonsandtextareatotheJPanelcontainerpnl.add(btn1);pnl.add(btn2);

Page 205: Java in easy steps: Covers Java 9

pnl.add(txtArea);

Insertstatementstosettheinitialstateoftwocomponentsbtn2.setEnabled(false);txtArea.setText(“Button2isDisabled”);

IntheActions()constructor,insertstatementstomakeeachbuttongenerateanActionEventeventwhenclickedbtn1.addActionListener(this);btn2.addActionListener(this);

Aftertheconstructormethod,addanevent-handlermethodfortheActionListenerinterface–todisplaytextidentifyingwhichbuttonhasbeenclickedpublicvoidactionPerformed(ActionEventevent)

{

txtArea.setText(event.getActionCommand()+“ClickedandDisabled”);

}

Insertifstatementsintheevent-handlermethod–executingaspecificresponsetoeachbuttonclickif(event.getSource()==btn1){btn2.setEnabled(true);btn1.setEnabled(false);}

if(event.getSource()==btn2){btn1.setEnabled(true);btn2.setEnabled(false);}

SavetheprogramasActions.javathencompileandruntheprogram,clickingthepushbuttons

Page 206: Java in easy steps: Covers Java 9

Thecomponentsaredeclaredbeforetheconstructorsotheyaregloballyaccessibletotheevent-handlermethod.

It’ssometimesusefultodisableacomponentuntiltheuserhasperformedarequiredaction.

Handlingitemevents

SwingJRadioButton,JCheckBoxandJComboBoxcomponentsmaintainstateswhosechangecanberecognizedbytheItemListenerinterface,whichwillpasstheItemEventtoitsitemStateChanged()event-handlermethod.TheItemEventobjecthasagetItemSelectable()methodthatidentifiestheoriginatingcomponentandagetStateChange()methodthatreturnsitsstatus.Thiswilldetermineifthechangeisselectingordeselectinganitem,andcanbecomparedtoanItemEvent.SELECTEDconstant.

EditacopyofWindow.javafromhere,changingtheclassnameinthedeclaration,theconstructor,andtheinstancestatementfrom“Window”to“States”.Then,addastatementattheverystartoftheprogramtoimportthefunctionalityofthejava.awt.eventpackageimportjava.awt.event.*;

Page 207: Java in easy steps: Covers Java 9

States.java

EdittheclassdeclarationtoaddanItemListenerinterfacetotheprogramclassStatesextendsJFrameimplementsItemListener

BeforetheStates()constructor,createthesecomponentsString[]styles={“DeepDish”,“GourmetStyle”,“Thin&Crispy”};JComboBox<String>box=newJComboBox<String>(styles);JRadioButtonrad1=newJRadioButton(“White”);JRadioButtonrad2=newJRadioButton(“Red”);ButtonGroupwines=newButtonGroup();JCheckBoxchk=newJCheckBox(“Pepperoni”);JTextAreatxtArea=newJTextArea(5,38);

IntheStates()constructor,insertstatementstogroupthetwoJRadioButtoncomponentswines.add(rad1);wines.add(rad2);

InsertstatementstoaddthecomponentstotheJPanelcontainerpnl.add(rad1);pnl.add(rad2);pnl.add(chk);pnl.add(box);pnl.add(txtArea);

Notehowthisexampleusestheappend()methodtoaddfurthertexttothetextarea.

InsertstatementstomakeselectablecomponentsgenerateanItemEvent

eventwhenanitemisselectedordeselectedrad1.addItemListener(this);rad2.addItemListener(this);chk.addItemListener(this);box.addItemListener(this);

Aftertheconstructormethod,addanevent-handlermethodforthe

Page 208: Java in easy steps: Covers Java 9

ItemListenerinterface–identifyingitemsselectedbytheJRadioButtoncomponentspublicvoiditemStateChanged(ItemEventevent)

{

if(event.getItemSelectable()==rad1)txtArea.setText(“Whitewineselected”);

if(event.getItemSelectable()==rad2)txtArea.setText(“Redwineselected”);

}

Addanifstatementtotheevent-handlermethodtoindicatethestatusoftheJCheckBoxcomponentif((event.getItemSelectable()==chk)&&

(event.getStateChange()==ItemEvent.SELECTED))txtArea.append(“\nPepperoniselected\n”);

Addanifstatementtotheevent-handlermethodtoindicatethestatusoftheJComboBoxcomponentif((event.getItemSelectable()==box)&&

(event.getStateChange()==ItemEvent.SELECTED))txtArea.append(event.getItem().toString()+“selected”);

SavetheprogramasStates.javathencompileandruntheprogram,selectingvariousitemsfromlefttoright

TheJComboBoxfirestwoItemEventswhenanitemgetsselected–one

Page 209: Java in easy steps: Covers Java 9

selectingtheitemandonedeselectingthepreviouslyselecteditem.Thatiswhysteps8&9mustidentifyboththeoriginatingcomponentandthetypeofItemEvent.

NoticethatthegetItem()methodreturnstheitemaffectedbythechange.

Reactingtokeyboardevents

SwingcomponentsthatallowtheusertoinputtextcanrecognizeuserkeystrokeswiththeKeyListenerinterface,whichwillpasstheKeyEventeventtothesethreeevent-handlermethods:

Event-handler: Description:

keyPressed(KeyEvent) Calledwhenakeyispressed

keyTyped(KeyEvent) Calledafterakeyispressed

keyReleased(KeyEvent) Calledwhenakeyisreleased

WhenaprogramimplementstheKeyListenerinterfaceitmustdeclarethesethreemethods–evenifnotallareactuallyused.

TheKeyEventobjecthasagetKeyChar()method,whichreturnsthecharacterforthatkey,andagetKeyCode()method,whichreturnsanintegerUnicodevaluerepresentingthatkey.Additionally,agetKeyText()methodtakesthekeycodevalueasitsargumentandreturnsadescriptionofthatkey.

EditacopyofWindow.javafromhere,changingtheclassnameinthedeclaration,theconstructor,andtheinstancestatementfrom“Window”to“Keystrokes”.Then,addaninitialstatementtoimportthefunctionalityofthejava.awt.eventpackageimportjava.awt.event.*;

Page 210: Java in easy steps: Covers Java 9

Keystrokes.java

EdittheclassdeclarationtoaddaKeyListenerinterfacetotheprogramclassKeystrokesextendsJFrameimplementsKeyListener

BeforetheKeystrokes()constructor,createaJTextFieldcomponentandaJTextAreacomponentJTextFieldfield=newJTextField(38);JTextAreatxtArea=newJTextArea(5,38);

InsertstatementstoaddthesetwocomponentstotheJPanelcontainerpnl.add(field);pnl.add(txtArea);

IntheKeystrokes()constructor,insertastatementtomaketheJTextFieldcomponentgenerateKeyEventeventsfield.addKeyListener(this);

Aftertheconstructormethod,addanevent-handlerthatacknowledgeswhenakeygetspressedpublicvoidkeyPressed(KeyEventevent)

{

txtArea.setText(“KeyPressed”);

}

Addasecondevent-handlerthatdisplaysthekeycharacterafterthekeyhasbeenpressedpublicvoidkeyTyped(KeyEventevent)

{

txtArea.append(“\nCharacter:”+event.getKeyChar());

}

Addathirdevent-handlerthatdisplaysthekeycodeandkeytextwhenthekeygetsreleasedpublicvoidkeyReleased(KeyEventevent)

Page 211: Java in easy steps: Covers Java 9

{

intkeyCode=event.getKeyCode();txtArea.append(“\nKeyCode:”+keyCode);txtArea.append(“\nKeyText:”+event.getKeyText(keyCode));

}

SavetheprogramasKeystrokes.javathencompileandruntheprogram,typinginthetoptextfield

ThegetKeyCode()methodonlyreturnsthekeycodeifcalledfromwithinthekeyPressed()orkeyReleased()event-handlers–notfromthekeyTyped()event-handler.

Runthisprogramandpressanon-characterkey,suchasBackspace,toseeitskeytextname.

Respondingtomouseevents

Page 212: Java in easy steps: Covers Java 9

SwingcomponentscanrecognizeusermouseactionswiththeMouseListenerinterface,whichwillpasstheMouseEventeventtothesefiveevent-handlermethods:

Event-handler: Description:

mousePressed(MouseEvent) Buttonispressed

mouseReleased(MouseEvent) Buttonisreleased

mouseClicked(MouseEvent) Buttonhasbeenreleased

mouseEntered(MouseEvent) Mousemoveson

mouseExited(MouseEvent) Mousemovesoff

MousemovementscanberecognizedbytheMouseMotionListenerinterface,whichpassesMouseEventeventstotwoevent-handlers:

Event-handler: Description:

mouseMoved(MouseEvent) Mouseismoved

mouseDragged(MouseEvent) Mouseisdragged

WhenaprogramimplementstheMouseListenerorMouseMotionListenerinterface,itmustdeclareallitsassociatedevent-handlermethods–evenifnotallareactuallyused.

TheMouseEventobjectpassedbytheMouseMotionListenerinterfacehasgetX()andgetY()methods,whichreturnthecurrentmousecoordinatesrelativetothecomponentgeneratingtheevent.

EditacopyofWindow.javafromhere,changingtheclassnameinthedeclaration,theconstructor,andtheinstancestatementfrom“Window”to“Mouse”.Then,addaninitialstatementtoimportthefunctionalityofthejava.awt.eventpackageimportjava.awt.event.*;

Mouse.java

Page 213: Java in easy steps: Covers Java 9

EdittheclassdeclarationtoaddaMouseListenerinterfaceandMouseMotionListenerinterfacetotheprogramclassMouseextendsJFrameimplementsMouseListener,MouseMotionListener

BeforetheMouse()constructor,createaJTextAreacomponentandtwointegervariablestostorecoordinatesJTextAreatxtArea=newJTextArea(8,38);intx,y;

IntheMouse()constructor,insertstatementstoaddtheJTextAreacomponenttotheJPanelcontainerandtomakeitgenerateMouseEventeventspnl.add(txtArea);txtArea.addMouseMotionListener(this);txtArea.addMouseListener(this);

Aftertheconstructormethod,addthetwoevent-handlersfortheMouseMotionListenerinterfacepublicvoidmouseMoved(MouseEventevent){x=event.getX();y=event.getY();}publicvoidmouseDragged(MouseEventevent){}

Addfiveevent-handlersfortheMouseListenerinterfacepublicvoidmouseEntered(MouseEventevent){txtArea.setText(“\nMouseEntered”);}

publicvoidmousePressed(MouseEventevent){txtArea.append(“\nMousePressedatX:“+x+“Y:“+y);}

publicvoidmouseReleased(MouseEventevent){txtArea.append(“\nMouseReleased”);}

publicvoidmouseClicked(MouseEventevent){}publicvoidmouseExited(MouseEventevent){}

SavetheprogramasMouse.java,thencompileandruntheprogram,clickingontheJTextAreacomponent

Page 214: Java in easy steps: Covers Java 9

RollovereffectscanbecreatedbyswappingimageswiththemouseEntered()andmouseExited()event-handlermethods.

Announcingmessages

TheSwingJOptionPaneclassisdesignedtocreateastandarddialogboxcenteredonitsparentwindow.ItsshowMessageDialog()methoddisplaysamessagetotheuserprovidinginformation,warning,orerrordescription.

TheshowMessageDialog()methodcantakefourarguments:• Parentobject–typicallyreferencedbythethiskeyword• MessageStringtobedisplayed• DialogtitleString

• OneoftheJOptionPaneconstants:

INFORMATION_MESSAGE

WARNING_MESSAGEorERROR_MESSAGE

ThedialogboxwilldisplayanappropriateiconaccordingtowhichJOptionPaneconstantisspecified.

EditacopyofWindow.javafromhere,changingtheclassnameinthedeclaration,theconstructor,andtheinstancestatementfrom“Window”to“Messages”

Messages.java

Addaninitialstatementtoimportthefunctionalityofthejava.awt.eventpackageimportjava.awt.event.*;

EdittheclassdeclarationtoaddanActionListenerinterfacetotheprogramclass

Page 215: Java in easy steps: Covers Java 9

MessagesextendsJFrameimplementsActionListener

BeforetheMessages()constructor,createthreeJButtoncomponentsJButtonbtn1=newJButton(“ShowInformationMessage”);JButtonbtn2=newJButton(“ShowWarningMessage”);JButtonbtn3=newJButton(“ShowErrorMessage”);

InsertstatementstoaddthebuttoncomponentstotheJPanelcontainerpnl.add(btn1);pnl.add(btn2);pnl.add(btn3);

IntheMessages()constructor,insertstatementstomakeeachbuttongenerateanActionEventeventbtn1.addActionListener(this);btn2.addActionListener(this);btn3.addActionListener(this);

Aftertheconstructormethod,addanevent-handlermethodfortheActionListenerinterfacepublicvoidactionPerformed(ActionEventevent){}

Betweenthecurlybracketsoftheevent-handler,insertifstatementstodisplayadialogwhenabuttongetsclickedif(event.getSource()==btn1)JOptionPane.showMessageDialog(this,“Information...”,“MessageDialog”,JOptionPane.INFORMATION_MESSAGE);

if(event.getSource()==btn2)JOptionPane.showMessageDialog(this,“Warning...”,“MessageDialog”,JOptionPane.WARNING_MESSAGE);

if(event.getSource()==btn3)JOptionPane.showMessageDialog(this,“Error...”,“MessageDialog”,JOptionPane.ERROR_MESSAGE);

SavetheprogramasMessages.javathencompileandruntheprogram,clickingoneachbutton

Page 216: Java in easy steps: Covers Java 9

Youcanalsosimplyspecifytheparentandmessageastwoargumentstocreateadialogwiththedefaultinformationiconandthedefault“Message”title.

Requestinginput

TheSwingJOptionPaneclasscanrequestinformationfromtheuserbyopeningadialogboxwithitsshowConfirmationDialog()method,requestingadecision,orwithitsshowInputDialog()method,requestinguserinput.

Boththesemethodscantakefourarguments:• Parentobject–typicallyreferencedbythethiskeyword• RequestStringtobedisplayed• DialogtitleString

• OneoftheJOptionPaneconstantssuchasPLAIN_MESSAGEortospecifydialogdecisionbuttonsasYES_NO_CANCEL_OPTION

Page 217: Java in easy steps: Covers Java 9

ThedialogboxwillreturntheinputStringfromaninputdialogoranintegerfromadecisionbutton–zeroforyes,1forno,or2forcancel.

EditacopyofWindow.javafromhere,changingtheclassnameinthedeclaration,theconstructor,andtheinstancestatementfrom“Window”to“Request”.Then,addaninitialstatementtoimportthefunctionalityofthejava.awt.eventpackageimportjava.awt.event.*;

Request.java

EdittheclassdeclarationtoaddanActionListenerinterfacetotheprogramclassRequestextendsJFrameimplementsActionListener

BeforetheRequest()constructor,createaJTextFieldandtwoJButtoncomponentsJTextFieldfield=newJTextField(38);JButtonbtn1=newJButton(“RequestDecision”);JButtonbtn2=newJButton(“RequestInput”);

AddeachcomponenttotheJPanelcontainerpnl.add(field);pnl.add(btn1);pnl.add(btn2);

IntheRequest()constructor,insertstatementstomakeeachbuttongenerateanActionEventeventbtn1.addActionListener(this);btn2.addActionListener(this);

Aftertheconstructormethod,addanevent-handlermethodfortheActionListenerinterfacepublicvoidactionPerformed(ActionEventevent){}

Betweenthecurlybracketsoftheevent-handler,insertanifstatementtorespondtoadecisionbuttonclickif(event.getSource()==btn1)

{

intn=JOptionPane.showConfirmDialog(this,“Doyouagree?”,“ConfirmationDialog”,JOptionPane.YES_NO_CANCEL_OPTION);

switch(n)

{

Page 218: Java in easy steps: Covers Java 9

case0:field.setText(“Agreed”);break;case1:field.setText(“Disagreed”);break;case2:field.setText(“Canceled”);break;

}

}

Insertanifstatementtohandleuserinputif(event.getSource()==btn2)field.setText(JOptionPane.showInputDialog(this,

“Enteryourcomment”,“InputDialog”,JOptionPane.PLAIN_MESSAGE));

SavetheprogramasRequest.javathencompileandruntheprogram,clickingoneachbutton

Page 219: Java in easy steps: Covers Java 9

TheOK_CANCELconstantprovidestwodecisionbuttons–OKreturnszeroandCANCELreturns2.Refertothedocumentationforthefullrangeofconstants.

Summary

• TheimplementskeywordcanbeusedinaclassdeclarationtoaddoneormoreEventListenerinterfaces.

• Acomponent’saddActionListener()methodtakesthethiskeywordasitsargument–tomakethatcomponentgenerateanActionEventeventwhenitisactivated.

• TheActionListenerinterfacepassesageneratedActionEventeventastheargumenttoitsactionPerformed()event-handler,whichcanrespondtoapushbuttonclickmadebytheuser.

• ThegetSource()methodofanActionEventeventcanbeusedtoidentifytheoriginatingcomponentthatgeneratedtheevent.

• AnItemListenerinterfacepassesageneratedItemEventeventastheargumenttoitsitemStateChanged()event-handler,whichcanrespondtoanitemselectionmadebytheuser.

• ThegetItemSelectable()methodofanItemEventeventcanbeusedtoidentifythecomponentthatgeneratedtheevent.

• AKeyListenerinterfacepassesageneratedKeyEventeventastheargumenttothreerequiredevent-handlermethods,whichcanrespondtoakeypressandrevealthatkey’scharacter.

Page 220: Java in easy steps: Covers Java 9

• AMouseListenerinterfacepassesageneratedMouseEventeventastheargumenttofiverequiredevent-handlermethods,whichcanrespondtomouseactionsmadebytheuser.

• AMouseMotionListenerinterfacepassesageneratedMouseEventeventastheargumenttotworequiredevent-handlers,whichcanrespondtomousemovement.

• TheshowMessageDialog()methodoftheJOptionPaneclasscreatesadialogdisplayingamessagetotheuser,anditsshowInputDialog()andshowConfirmationDialog()methodscanbeusedtorequestuserinput.

• AudioresourcescanberepresentedbytheAudioClipclassofthejava.appletpackage,andplayedusingitsplay()method.

Page 221: Java in easy steps: Covers Java 9

10

Deployingprograms

ThischapterdemonstrateshowtodeployJavaprograms–bothasJavaarchives(JAR)andAndroid

applicationpackages(APK).

ProducinganapplicationDistributingprograms

BuildingJavaarchivesDeployingapplicationsCreatingAndroidprojectsExploringprojectfiles

Addingresources&controlsInsertingJavacodeTestingtheapplicationDeployingAndroidapps

Summary

Producinganapplication

Javaapplicationsforbothdesktopandhandhelddevicescanbecreatedfromcommoncode–liketheLotto.javaprogrambelow:importjavax.swing.*;importjava.awt.event.*;

ComponentspublicclassLottoextendsJFrameimplementsActionListener

Page 222: Java in easy steps: Covers Java 9

{

ClassLoaderldr=this.getClass().getClassLoader();java.net.URLiconURL=ldr.getResource(“Lotto.png”);ImageIconicon=newImageIcon(iconURL);JLabelimg=newJLabel(icon);JTextFieldtxt=newJTextField(“”,18);JButtonbtn=newJButton(“GetMyLuckyNumbers”);JPanelpnl=newJPanel();

ConstructorpublicLotto(){

super(“LottoApp”);setSize(260,210);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);pnl.add(img);pnl.add(txt);pnl.add(btn);btn.addActionListener(this);add(pnl);setVisible(true);

}

Event-handlerpublicvoidactionPerformed(ActionEventevent)

{

if(event.getSource()==btn)

{

int[]nums=newint[60];Stringstr=“”;for(inti=1;i<60;i++){nums[i]=i;}for(inti=1;i<60;i++){intr=(int)(59*Math.random())+1;intt=nums[i];nums[i]=nums[r];nums[r]=t;

}

for(inti=1;i<7;i++){str+=“”+Integer.toString(nums[i])+“”;}txt.setText(str);

}

}

Entry-pointpublicstaticvoidmain(String[]args){Lottolotto=newLotto();}

}

Page 223: Java in easy steps: Covers Java 9

}

Lotto.java

Thealgorithminthisevent-handlershufflesintegers1-59inanarray,thenassignsthoseintegersinthefirstsixelementstoastring.

TheLottoprogrambeginswithimportstatementstomakeSwingcomponentsandtheActionListenerinterfaceavailable.

Lotto.png–Checkeredareasaretransparent

Components

Theprogramcomprisesasinglepanelcomponentcontainingalabelcomponenttodisplayanimage,atextfieldcomponenttodisplayoutput,andabuttoncomponentforuserinteraction.

Constructor

TheLotto()constructorbuildsasimpleSwinginterfacethatloadsthepanelintoawindowframemeasuring260x210.

Event-handlerThebutton’sevent-handlermethodexecutesanalgorithmtoselectasequenceofsixuniquerandomnumbersintherangeof1-59fordisplayinthetextfieldcomponent.

Page 224: Java in easy steps: Covers Java 9

Entry-pointThemain()methodcreatesaninstanceoftheapp,andcallsuponClassLoader()toseektheimagefileresourceLotto.pnginthesamedirectoryastheprogramfile.Thefilesmustbearrangedinthiswaybeforeattemptingtocompiletheprogram.

TheLottoprogramisusedthroughoutthischaptertocreateappsfordesktopandhandhelddevices.

Observingtherequiredfilearrangement,thejavaccompilercanbeemployedintheusualwaytocreateaLotto.classfile,thenthejavainterpretercanbeemployedtoexecutetheprogram:

Distributingprograms

TheLottoprogramopensanewwindowofthespecifiedsizecontainingtheSwinginterfacecomponents.Eachtimetheuserclicksthepushbutton,itsevent-handlerdisplayssixnewrandomnumbersintherange1-59withinthetextfield

Page 225: Java in easy steps: Covers Java 9

component:

Aswithallotherexamplesinthisbook,theexampleLottoprogramhasbeencompiledhereforJava9andcanbedistributedforexecutiononothercomputerswheretheJava9RuntimeEnvironmentispresent–regardlessoftheiroperatingsystem.Forexample,inthescreenshotsbelow,Lotto.classandLotto.pngfileshavebeencopiedtothedesktopofacomputerrunningtheLinuxoperatingsystemwiththeJava9runtimeinstalled.TheLottoprogramcan,therefore,beexecutedbythejavainterpreterinthesamewayasontheoriginatingWindowssystem.

The.javasourcecodefileneednotbeincludedwhendistributingaprogram–only.classandresourcefilesareneeded.

Thereis,however,adangerindistributingJavaprogramsthiswayastheprogramwillfailtoexecuteifresourcefilesbecomeunavailable–inthiscase,

Page 226: Java in easy steps: Covers Java 9

removingLotto.pngproducesthiserror:

TheJDKcontainsajarutilitytoolthatallowsprogramclassandresourcefilestobebundledintoasingleJavaARchive(JAR)file.Thiscompressesallprogramfiles,usingthepopularZIPformat,intoasinglefilewitha.jarfileextension.AJARfilestorestheprogramefficientlyandhelpsensurethatresourcefilesdonotbecomeaccidentallyisolated.ThejavainterpreterfullysupportsJARfilessoJavaapplicationscanbeexecutedwithoutextractingtheindividualfiles.Likethejavainterpreterandjavaccompiler,thejartoolislocatedinJava’sbindirectoryandrunsfromthecommandlinetoperformthesecommonjaroperations:

Commandsyntax: Operation:

jarcfjar-fileinput-file/s CreateaJARfile

jarcfejar-fileentry-pointinput-file/s CreateaJARfilewithaspecifiedentrypointinastand-aloneapplication

jartfjar-file ViewcontentsofaJARfile

jarufjar-file UpdatecontentsofJARfile

jarufmjar-fileattribute-file UpdatecontentsofJARfilemanifest,addingattribute/s

jarxfjar-file ExtractallcontentsofJAR

jarxfjar-filearchived-file/s ExtractspecificfilesfromJAR

Largerprogramsmayusemanyresourcefileswhoselocationcaneasilybedisruptedbyauser–thesolutionistopackagetheprogramandallits

Page 227: Java in easy steps: Covers Java 9

resourcesintoasingleexecutablearchivefile.

Forlargerprograms,the*wildcardcharactercanbeusedtoarchivemultiplefileswithinthedirectory–forinstance,jarcfProgram.jar*.classarchivesallclassfilesinthecurrentdirectory.

BuildingJavaarchives

FollowthesestepstocreateaJARfilefortheLottoprogramdescribedatthestartofthischapter:

Openacommand-line/terminalwindow,thennavigatetothedirectorywheretheLottoprogramfilesarelocated–Lotto.classandLotto.png

Lotto.jar

EnterjarcfeLotto.jarLottoLotto.classLotto.png,thenhittheEnterkeytocreateaLotto.jararchiveNext,enterjartfLotto.jartoseeallcontentsoftheJAR

NoticethatthejartoolautomaticallycreatesaMETA-INFdirectoryalongsidethearchivedfiles.Thiscontainsatext-basedmanifestmetafilenamedMANIFEST.MFthatyoucanexamine:

Page 228: Java in easy steps: Covers Java 9

Now,enterjarxfLotto.jarMETA-INFtoextractacopyoftheMETA-INFdirectoryFinally,entertypeMETA-INF\MANIFEST.MFtoseethetextcontainedwithinthearchivemanifest

TheJARmanifestcanbemodifiedforadvancedpurposes,suchastheadditionofpermissionstousesystemresources.

Deployingapplications

JavaJARfilesareexecutableonanysystemonwhichtheappropriateversionoftheJavaRuntimeisinstalled:

Atthecommandline,navigatetothedirectorywheretheLotto.jarfileislocated,thentypejava-jarLotto.jarandhittheEnterkeytoruntheLottoapplication

Page 229: Java in easy steps: Covers Java 9

Alternatively,double-clickorright-clicktheLotto.jarfileicon,andchooseto“OpenWith”theJavaRuntime

Page 230: Java in easy steps: Covers Java 9

The.jarfileextensionisrequiredwhenexecutingJARfilesfromaprompt.

SettheJREasthedefaultJARfilehandleronyoursystemforpermanentdouble-clickexecution.

CreatingAndroidprojects

TheAndroidoperatingsystem,prevalentonhandhelddevices,includesasetofcorelibrariesthatprovidemostofthefunctionalityofthoseintheJavaprogramminglanguage.ThismeansthatJavaprogramscanbereadilyconvertedforAndroid.

AndroidStudioisavailablefreefromdeveloper.android.com/studioThisexampledescribesversion2.3.3–instructionsmayvaryforotherversions.AndroidStudioisasizeabledownloadofaround1.9GB,andmayrequireadditionaldownloadstocompletesetup.CheckthesystemrequirementstoensureyourcomputercanrunAndroidStudiobeforedownloading.

AndroidappdevelopmentisbestundertakenusingtheofficialAndroidStudioIntegratedDevelopmentEnvironment(IDE).ThisprovidesaunifiedenvironmentwhereyoucandevelopappsforallAndroiddevices,andprovides

Page 231: Java in easy steps: Covers Java 9

extensivetestingtools.CompletedappsaredistributedasanAndroidApplicationPackage(APK)archivefile,whichissimilartoaJavaarchive(JAR)file.Thiscompressesallprogramfiles,usingthepopularZIPformat,intoasinglefilewitha.apkfileextension.EachappisfirstcreatedinAndroidStudioasa“project”,towhichthedeveloperaddscodeandresources:

LaunchAndroidStudio,thenchoosetoStartanewAndroidStudioprojectinthe“Welcome”dialogoptions–toopenthe“NewProject”dialogEnteranApplicationname(forexample,“Lotto”)andaCompanyDomain,thenchooseyourpreferredProjectlocationatwhichtosavetheprojectonyourcomputer

ClickNexttoopenthe“TargetAndroidDevices”dialogSelectthedevicetypeandplatformlevel(forexample,“PhoneandTablet”running“IceCreamSandwich”)

ThePackagenameisanautomaticallyassigneduniqueidentifierfortheapp,comprisedofcom.domain.appname

Page 232: Java in easy steps: Covers Java 9

ClickNexttoopenthe“AddanActivitytoMobile”dialog,andsimplyselecttheEmptyActivityoptionClickNexttoopenthe“CustomizetheActivity”dialog

ClickFinishtoacceptthesuggestedconfiguration–AndroidStudiowillnowgenerateseveralfilesandfoldersforthenewproject(thiscantakeawhile)theneventuallyopentheIDEinterface

ChooseAPI15ifyouwouldliketheapptorunon100%ofdevicesactiveontheGooglePlayStore.

Page 233: Java in easy steps: Covers Java 9

Youcanchangethesuggestednameshere,butbesuretoleavetheGenerateLayoutFileandBackwardsCompatibilityboxeschecked.

Exploringprojectfiles

TheAndroidStudioIDEprovidesaProjectwindowthatdisplaysanexpandabletreeviewofallfilesandfolderswithintheproject.YoucanclickanyarrowintheProjectwindowtoexpandafolder,anddouble-clickonanyfileintheProjectwindowtoopenitinthetabbedEditorwindow.

Despiteitsinitialappearanceofcomplexity,onlytwofilesneedmodificationbythedevelopertocreateacustomizedapplication:• MainActivity.java–theJavafilethatloadscontrolsintotheappinterfaceandcancontainevent-handlercodetorespondtouseractionswithintheappinterface.

• activity_main.xml–theXMLfilethatdefineseachcontroltoappearintheappinterfaceandtheirlayout.

Page 234: Java in easy steps: Covers Java 9

IftheProjectwindowisnotimmediatelyvisibleclicktheProjectbuttonintheleftsidebar,oropenitusingtheshortcutkeysAlt+F1.

Selectingtheactivity_main.xmlfileintheProjectwindowpresentsitintheEditorwindowinoneoftwopossibleviews–visuallyinDesignvieworprogrammaticallyinTextview.Therearetabsatthebottomofthewindowtoswitchbetweenviews.

DesignviewprovidesaPaletteofcontrolsthatcanbedraggedontoagraphicalrepresentationoftheapp,aComponentTreetoselectanyaddedcontrol,andaPropertieswindowinwhichtomodifytheappearanceofaselectedcontrol.

Textviewprovidesa“code-behind”versionofthelayoutthatdescribeseachaspectofaddedcontrolsusingXMLattributes.

Page 235: Java in easy steps: Covers Java 9

ControlscanbeaddedtotheappinterfaceandmodifiedeithervisuallyinDesignvieworprogrammaticallyinTextview.

Page 236: Java in easy steps: Covers Java 9

Addingresources&controlsImageResources

TobegincustomizingthedefaultAndroidStudioemptyappfortheLottoprogram,theimagecanfirstbeaddedasa“resource”:

Right-clickontheLotto.pngimage,andchooseCopyNext,right-clickontheapp>res>drawablefolderandchoosePaste–toseea“Copy”dialogappearRenamethefiletolowercaseLotto.png

ClickOKtoseethefilenowappearinthedrawablefolder

Androidonlysupportslowercasefilenamesforresourceitems.

InterfaceControls

TheLottoappwillrequirethreeinterfacecontrolsalignedoneabovetheotherinaverticallayout.AnImageViewcontrolisrequiredforthelogo,aTextView

Page 237: Java in easy steps: Covers Java 9

averticallayout.AnImageViewcontrolisrequiredforthelogo,aTextViewcontrolisrequiredfortheoutput,andaButtoncontrolisrequiredforuserinteraction:

Opentheactivity_main.xmlfileintheEditor’sTextview

activity_main.xml

InsertthisImageViewcontrolelementimmediatelybeforetheexistingdefaultTextViewelement

<ImageViewandroid:layout_width=”match_parent”android:layout_height=”wrap_content”app:srcCompat=”@drawable/lotto”android:id=”@+id/imageView”app:layout_constraintTop_toTopOf=”parent”/>

Theapp:srcCompatattributereferencestheimageresourceaddedtothedrawablefolder.

Theattributesinthiselementfitthecontroltothewidthofthelayoutcontainer,andpositionthecontrolatthetopofthecontainer.Theimageresourceisdefinedasthecontentsource,andtheelementisgivenanidforreferencebyotherelements.

EdittheexistingTextViewelementtolooklikethis<TextViewandroid:layout_width=”match_parent”android:layout_height=”wrap_content”android:id=”@+id/textViewandroid:height=”60dp”android:textSize=”36sp”android:gravity=”center_horizontal”app:layout_constraintTop_toBottomOf=”@+id/imageView”/>

InsertthiselementrightaftertheTextViewelement<Button

Page 238: Java in easy steps: Covers Java 9

android:layout_width=”match_parent”android:layout_height=”wrap_content”android:id=”@+id/button”android:textSize=”24sp”android:onClick=”lotto”android:text=”GETMYLUCKYNUMBERS”app:layout_constraintTop_toBottomOf=”@+id/textView”/>

Theandroid:idattributeineachelementspecifiesauniquenamebywhichtheelementcanbereferencedinJavacode.

Theandroid:onClickattributespecifiesthenameofanevent-handlertobecalled.

StringResources

Thestringsassignedtodescribetheimagecontentandtospecifythebuttontextshouldeachbeconvertedtoastringresource:

Clickwithinthe“LottoLogo”stringassignmenttogiveitfocus,thenpressAlt+EntertoseeaQuickFixdialog

ChooseExtractstringresource,thenprovidearesourcenameinthe“ExtractResource”dialogthatnowappears

Page 239: Java in easy steps: Covers Java 9

ClickOKtoclosethedialog,andseetheassignedstringgetreplacedbyareferencetothenewstringresource

Repeatthisforthe“GETMYLUCKYNUMBERS”string

InsertingJavacode

Afteraddingresourcesandcontrolshere,theappinterfaceshouldnowresemble

thatoftheLotto.jarapplication:

Ifthecontrolsdonotlooklikethisscreenshot,youshouldreturntohere

Page 240: Java in easy steps: Covers Java 9

andcarefullycheckeachelement’sattributes.

Functionalitycannextbeaddedtotheappbyinsertinganevent-handlerintotheMainActivity.javafilethatwillrespondtothebutton’sonClickeventwhentheuserpushesthebutton.Thiseventautomaticallypassesoneargumenttotheevent-handler,whichisanidentifyingreferencetothecontrolthathasbeenclicked.Consequently,theevent-handlersignaturemustaccommodatetheargumentbyincludingaparameterfortheViewclass–thebaseclassofallwidgets.Themethodmustalsohaveavoidreturntype:

Insertthisevent-handlersignatureintotheMainActivityclass,immediatelyafteritsonCreate()methodblockpublicvoidlotto(Viewvue){}

MainActivity.javaInterfacecontrolscanbereferencedincodebyspecifyingtheiridentityastheargumenttoafindViewById()method.Thisisthenameassignedtotheirandroid:idattributeinactivity_main.xmlprefixedbyR.id.:

Insidetheevent-handlerblock,assignareferencetothe<TextView>controlelementtoavariableTextViewtxt=(TextView)findViewById(R.id.textView);

Finally,insidetheevent-handlerblock,copythecodefromtheevent-handlerintheLotto.javaprogram(listedhere)thatoutputssixuniquerandomnumbersint[]nums=newint[60];Stringstr=“”;for(inti=1;i<60;i++){nums[i]=i;}for(inti=1;i<60;i++)

{

intr=(int)(59*Math.random())+1;intt=nums[i];nums[i]=nums[r];nums[r]=t;

}

for(inti=1;i<7;i++){str+=“”+Integer.toString(nums[i])+“”;}txt.setText(str);

Page 241: Java in easy steps: Covers Java 9

Inthiscase,thereisnoneedforthecodetocheckthesourceofthecallastheevent-handlerisexplicitlyassignedtothebuttonbytheandroid:onClickattributeinactivity_main.xml

NowthattheLottoapphasallresources,controls,andfunctionalcodeinplace,anattemptcanbemadetobuildtheproject:

OntheAndroidStudiomaintoolbar,clickView,ToolWindows,Messages–toopenthe“Messages”windowThen,clickBuild,MakeProject(orpresstheCtrl+F9shortcut)tostartbuildingThe“Messages”windowwillsoondisplayaconfirmationofsuccess,orreportanyerrorsthatneedfixing

Fixanyreportederrorsifnecessary,thenbuildagainuntilyouseeaconfirmationofsuccess

Ifthebuildattemptfails,lookforredlightbulbiconsinthecode–AndroidStudioaddsthesesoyoucaneasilyfindandcorrecterrors.

Testingtheapplication

Onceanapplicationprojecthasbuiltsuccessfully,itisreadytobetested.

Page 242: Java in easy steps: Covers Java 9

Onceanapplicationprojecthasbuiltsuccessfully,itisreadytobetested.TestingcanbeperformedonarealAndroiddevice,connectedtoyourcomputerviaaUSBsocket,oronanAndroidVirtualDevice(AVD)emulator.AVDsallowyoutotesthowtheappwillperformonarangeofdevices,buttheydousemoresystemresourcesandcanbepainfullyslow.Applicationsshouldbetestedonatleastonephonedeviceandonetabletdevice:

ClickRun,Run‘app’(orpresstheShift+F10shortcut)toopenthe“SelectDeploymentTarget”dialog

SelectanAVDphoneemulatortoconnect,thenclickOKtoinstalltheLottoappontheemulator

PushtheappbuttontoseetheTextViewcontentunhappilywraponthissmalldevicescreen

Editactivity_main.xmltoreducethetextsizeandroid:textSize=”32sp”

ClickBuild,RebuildProjecttoapplythechange,thenruntheappintheemulatoroncemoretoseethesolution

Page 243: Java in easy steps: Covers Java 9

CreationofeachAVDemulatormayrequirealargesystemimagefiletobedownloaded.YoumayprefertotestonarealAndroiddevice.AlsonotethatacceleratedemulatorswillonlyrunifyourcomputerhasaCPUthatsupportshardwarevirtualization(IntelVT-xorAMDSVM).

AndroidStudiohasanInstantRunfeaturethatautomaticallyupdateschangestotheappsotheyappearinthetestdevicemorequickly.

Page 244: Java in easy steps: Covers Java 9

Itisbettertotestonrealdevicesratherthantheemulators.Ideally,youshouldtestonasmanydifferentdevicesaspossiblebeforefinaldeploymentofapps.

TakeanAndroidtabletandenable“USBDebugging”ontheSettings,DeveloperOptionsmenuConnectthetablettoyourcomputerviaaUSBporttoseethisnotification

ClickRun,Run‘app’(orpresstheShift+F10shortcut)toopenthe“SelectDeploymentTarget”dialog

Selecttheconnectedtabletdevice,thenclickOKtoinstalltheLottoapponthetabletPushtheappbuttontoseetheLottoapphappilyperformasexpected–asuccessfultest

Page 245: Java in easy steps: Covers Java 9

Thetestprocessesprovideanapplicationlaunchersothetabletcanbedisconnectedandtheapplaunchedbytappingthelaunchericon–butremember,thisisaDebugbuildoftheapp.

IfyoucannotseeDeveloperOptionsontheAndroidSettingsyoucanenableitbytappingontheBuildNumberseventimes–typicallyfoundatSettings,About,SoftwareInformation,BuildNumber.

AndroidStudioprovidesadefaultimagelaunchericon,butyoucanuse

Page 246: Java in easy steps: Covers Java 9

yourownimage.IntheProjectwindow,right-clickontheresfolderthenchooseNew,ImageAssettoopentheAssetStudio,thenselectImageandbrowsetoanimageyouwishtoimportintotheproject.

DeployingAndroidapps

Aftersuccessfultesting,thedevelopmentDebugversionofanappshouldbechangedtoaReleaseversionbeforedeploymentasanAndroidApplicationPackage(APK).AndroidrequiresthatallAPKsmustbedigitallysignedwithacertificate,andAndroidStudioallowsyoutoeasilygenerateasignedAPK:

ClickBuild,SelectBuildVariant,thenchoosethereleaseversionoption

Next,clickBuild,GenerateSignedAPK

EnterexistingkeystoredetailsorclickCreatenew...

Choosealocationatwhichtosavethekeystore,thenenterpasswords

Selectyourpreferredvalidityperiod,thenentercertificateinformation

Page 247: Java in easy steps: Covers Java 9

ClickOKtocreatethenewkeystore

ClickNexttousethenewkeystoretogenerateasignedAPKfortheapp

AdditionalstepsarerequiredifyouwishtodistributeyourappsviatheGooglePlayStore.Youcandiscoverwhatisneededonlineatdeveloper.android.com/distribute/tools/launch-checklist.html

Akeystoreholdsoneormorecorrespondingpublic/privatekeypairs.You,astheownerofthecertificate,retaintheprivatekeywhiletheAndroidStudiosigningtoolattachesthepublickeycertificatetotheAPK.ThisuniquelyassociatestheAPKtoyouandyourcorrespondingprivatekeytoensurethatanyfutureupdatestotheAPKcomefromtheoriginaldeveloper.

ChoosealocationatwhichtosavetheAPKandbesuretheBuildTypeis“release”,thenclickFinishtogenerateasignedAPKnamedapp-release.apk

Page 248: Java in easy steps: Covers Java 9

Uponsuccess,changetheAPKnametoamoremeaningfulLotto.apk

Aproductflavorcanbespecifiedtodefinedifferentcustomizedbuildsoftheapp.Forexample,thebuttontextonaSpanishlanguageflavoras“Consiguemisnúmerosdelasuerte”.

TheAndroidappAPKcannowbedeployedinseveralways:• AppMarketplace–publishonGooglePlayStore• Email–senddirectasanattachment• Website–hostonlinefordownloadInstallationofAPKsfromsourcesotherthanGooglePlayisblockedunlesstheuseroptstoallowthem:

OnanAndroiddevice,gotoSettings,Securityandoptto“Allowinstallationofappsfromunknownsources”

Next,downloadLotto.apktotheAndroiddeviceNavigatetothedownloadfolderandclickInstall,thentapthe launchericontoruntheapp

Page 249: Java in easy steps: Covers Java 9

Summary

• Javaprogramscanbedeployedasstand-alonedesktopapplicationsrunningonanappropriateversionoftheJRE.

• Applicationfilescanbedistributedforexecutiononotheroperatingsystemsusingtheappropriatejavainterpreter.

• BundlingallprogramfilesintoasingleJARarchivefilehelpsensureresourcefilesdonotbecomeaccidentallyisolated.

• ExecutableJARapplicationscanbeexecutedfromapromptwiththejava-jarcommandorbyclickingontheirfileicon.

• JavaprogramscanbereadilyconvertedfortheAndroidoperatingsystemasitincludessimilarcorelibraries.

• AndroidStudioistheofficialIDEforthedevelopmentofAndroidapplications.

• APKandJARarchivefilesarebothcompressedinZIPformat.

• EachAndroidappisfirstcreatedasaprojecttowhichthedeveloperaddscodeandresources.

• ThemostusedwindowsintheAndroidStudiointerfacearetheProjectwindowandtheEditorwindow.

• FunctionalcodecanbeaddedtotheMainActivity.javafileandinterfacecomponentsaddedtotheactivity_main.xmlfile.

Page 250: Java in easy steps: Covers Java 9

• AnAndroidappcanstoreimagesandstringsasresources.

• Thesignatureofabutton’sonClickevent-handlermustincludeaparameterforaViewclassobject.

• InterfacecomponentscanbereferencedincodebyspecifyingtheiridentityastheargumenttofindViewById().

• AndroidStudioprovidesAVDemulatorsfortestingandalsoallowstestingtobeperformedonrealconnecteddevices.

• TheReleaseversionofanAndroidappmustbedigitallysignedwithapublickeycertificate.

Page 251: Java in easy steps: Covers Java 9
Page 252: Java in easy steps: Covers Java 9
Page 253: Java in easy steps: Covers Java 9