Java in easy steps: Covers Java 9
Transcript of Java in easy steps: Covers Java 9
IneasystepsisanimprintofInEasyStepsLimited16HamiltonTerrace·HollyWalk·LeamingtonSpaWarwickshire·CV324LYwww.ineasysteps.com
SixthEdition
Copyright©2017byInEasyStepsLimited.Allrightsreserved.Nopartofthisbookmaybereproducedortransmittedinanyformorbyanymeans,electronicormechanical,includingphotocopying,recording,orbyanyinformationstorageorretrievalsystem,withoutpriorwrittenpermissionfromthepublisher.
NoticeofLiabilityEveryefforthasbeenmadetoensurethatthisbookcontainsaccurateandcurrentinformation.However,InEasyStepsLimitedandtheauthorshallnotbeliableforanylossordamagesufferedbyreadersasaresultofanyinformationcontainedherein.
TrademarksAlltrademarksareacknowledgedasbelongingtotheirrespectivecompanies.
Contents
1GettingstartedIntroductionInstallingtheJDKWritingafirstJavaprogramCompiling&runningprogramsCreatingavariableRecognizingdatatypesCreatingconstantsAddingcommentsTroubleshootingproblemsSummary
2PerformingoperationsDoingarithmeticAssigningvaluesComparingvaluesAssessinglogicExaminingconditionsSettingprecedenceEscapingliteralsWorkingwithbitsSummary
3MakingstatementsBranchingwithifBranchingalternativesSwitchingbranchesLoopingforLoopingwhiletrueDoingdo-whileloopsBreakingoutofloopsReturningcontrolSummary
4DirectingvaluesCastingtypevaluesCreatingvariablearrays
PassinganargumentPassingmultipleargumentsLoopingthroughelementsChangingelementvaluesAddingarraydimensionsCatchingexceptionsSummary
5ManipulatingdataExploringJavaclassesDoingmathematicsRoundingnumbersGeneratingrandomnumbersManagingstringsComparingstringsSearchingstringsManipulatingcharactersSummary
6CreatingclassesFormingmultiplemethodsUnderstandingprogramscopeFormingmultipleclassesExtendinganexistingclassCreatinganobjectclassProducinganobjectinstanceEncapsulatingpropertiesConstructingobjectvaluesSummary
7ImportingfunctionsHandlingfilesReadingconsoleinputReadingfilesWritingfilesSortingarrayelementsMakingarraylistsManagingdatesFormattingnumbersSummary
8BuildinginterfacesCreatingawindowAddingpushbuttonsAddinglabels
AddingtextfieldsAddingitemselectorsAddingradiobuttonsArrangingcomponentsChangingappearanceSummary
9RecognizingeventsListeningforeventsGeneratingeventsHandlingbuttoneventsHandlingitemeventsReactingtokeyboardeventsRespondingtomouseeventsAnnouncingmessagesRequestinginputSummary
10DeployingprogramsProducinganapplicationDistributingprogramsBuildingJavaarchivesDeployingapplicationsCreatingAndroidprojectsExploringprojectfilesAddingresources&controlsInsertingJavacodeTestingtheapplicationDeployingAndroidappsSummary
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
App.xml
Grabbingthesourcecode
Forconvenience,IhaveplacedsourcecodefilesfromtheexamplesfeaturedinthisbookintoasingleZIParchive.Youcanobtainthecompletearchivebyfollowingtheseeasysteps:
Browsetowww.ineasysteps.comthennavigatetoFreeResourcesandchoosetheDownloadssectionFindJavaineasysteps,6thEditioninthelist,thenclickonthehyperlinkentitledAllCodeExamplestodownloadthearchiveNow,extractthearchivecontentstoanyconvenientlocationonyourcomputer
IsincerelyhopeyouenjoydiscoveringtheprogrammingpossibilitiesofJavaandhaveasmuchfunwithitasIdidinwritingthisbook.
MikeMcGrath
1
Gettingstarted
WelcometotheexcitingworldofJavaprogramming.Thischaptershowshowtocreateandexecute
simpleJavaprograms,anddemonstrateshowtostoredatawithinprograms.
IntroductionInstallingtheJDKWritingafirstJavaprogramCompiling&runningprograms
CreatingavariableRecognizingdatatypesCreatingconstantsAddingcomments
TroubleshootingproblemsSummary
Introduction
TheJava™programminglanguagewasfirstdevelopedin1990byanengineeratSunMicrosystemsnamedJamesGosling.HewasunhappyusingtheC++programminglanguagesohecreatedanewlanguagethathenamed“Oak”,aftertheoaktreethathecouldseefromhisofficewindow.
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):
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
TheOracledownloadpagealsofeaturesotherpackages,butonlytheJDK9packageisrequiredtogetstartedwithJavaprogramming.
TheJDK9packageisavailableinversionsfor32-bitand64-bitvariantsoftheLinux,Mac,SolarisandWindowsplatforms–accepttheOracleLicenseAgreement,thenselecttheappropriateversionforyourcomputertodownloadtheJavaDevelopmentKit.
ThereisnotruthintherumorthatJAVAstandsfor“JustAnotherVagueAcronym”.
InstallingtheJDKSelecttheappropriateJavaDevelopmentKit(JDK)packageforyoursystemfromtheOracle®downloadspage,andthenfollowthesestepstoinstallJavaonyourcomputer:
UninstallanypreviousversionsoftheJDKand/orJavaRuntimeEnvironment(JRE)fromyoursystem
StarttheinstallationandaccepttheLicenseAgreementWhenthe“CustomSetup”dialogappears,eitheracceptthesuggestedinstallationlocationorclicktheChangebuttontochooseyourpreferredlocation–suchasC:\JavaforWindowssystemsorusrJavaforLinuxsystems
EnsurethatthePublicJREandDevelopmentToolsfeaturesareselectedfromthelist.Optionally,youmaydeselecttheotherfeaturesastheyarenotrequiredtostartprogrammingwiththisbook
ClicktheNextbuttontoinstallallthenecessaryJavaclasslibrariesandtoolsatthechosenlocation
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:
Youarenowabletotesttheenvironment:
Openacommand-linepromptwindow,suchasWindowsPowerShellorLinuxTerminalTypethecommandjava-versionthenhittheEnterkeytoseetheJavainterpreter’sversionnumberNext,typethecommandjavac-versionthenhittheEnterkeytoseetheJavacompiler’sversionnumberNow,typethecommandjshell-versionthenhittheEnterkeytoseetheJavashellversionnumberEnsurethatallversionnumbersmatch(9),andyou’rereadytobeginJavaprogramming
Ifthe.bashrcfileisnotvisibleinyourLinuxhomedirectorychooseView,ShowHiddenFilestorevealit.
TheJavashelljshellisanewfeatureinJava9.Thisinteractivetoolletsyouquicklytestsnippetsofcode,withouttheneedtofirstcompilethecode.Itisusedinthenextchaptertodemonstratethevarious“operators”availableinJavaprogramming.
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:
Javaisacase-sensitivelanguagewhere“Hello”and“hello”aredistinctlydifferent–traditionally,Javaprogramnamesshouldalwaysbeginwithanuppercaseletter.
Javaprogramsarealwayssavedastheirexactprogramnamefollowedbythe“.java”extension.
Theseparatepartsoftheprogramcodeontheoppositepagecanbeexaminedindividuallytounderstandeachpartmoreclearly:
TheProgramContainer
classHello{}
Theprogramnameisdeclaredfollowingtheclasskeyword,andfollowedbyapairofcurlybrackets.AlloftheprogramcodethatdefinestheHelloclasswillbecontainedwithinthesecurlybrackets.
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
Compiling&runningprogramsBeforeaJavaprogramcanrun,itmustfirstbecompiledintoaclassfilebytheJavacompiler.ThisislocatedinJava’sbinsub-directory,andisanapplicationnamedjavac.Theinstructionsheredescribedhowtoaddthebinsub-directorytothesystempathsothatjavaccanbeinvokedfromanysystemlocation.
Followthesestepstocompiletheprogramhere:
Openacommand-linewindow,thennavigatetothedirectorywhereyousavedtheHello.javasourcecodefileTypejavacfollowedbyaspacethenthefullnameofthesourcecodefileHello.javaandhittheEnterkey
OnWindowsusetheWindowsPowerShellapportheolderCommandPromptapptoprovideacommand-lineprompt,andonLinuxuseaTerminalwindow.
AtaprompttypejavacandhitReturntorevealtheJavacompileroptions.
Ifthejavaccompilerdiscoverserrorsinthecodeitwillhaltanddisplayahelpful
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
Donotincludethe.classextensionwhenrunningaprogram–onlyusetheprogramname.
TheHelloprogramrunsandexecutesthetaskdefinedinthestatementwithinitsmainmethod–tooutput“HelloWorld!”.Uponcompletion,focusreturnstothepromptoncemore.
TheprocessofcompilingandrunningaJavaprogramistypicallycombinedinsequentialsteps,andisthesameregardlessofplatform.ThescreenshotbelowillustratestheHelloprogrambeingcompiledandrunincombinedstepsonaLinuxsystem:
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
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
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
helpfromTroubleshootingproblemshere.
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
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
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.
.
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=
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
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.
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.
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
pathaddresstoinvokethecompiler.
Thepathaddressmustbeenclosedwithinquotationmarksifitcontainsanyspaces,suchasthepathaddress“C:\ProgramFiles\Java”.
• Cause–thefileTest.javacannotbefound.
• Solution–navigatetothedirectorywherethefileislocated,orusethefullpathaddresstothefileinthecommand.
• Cause–thestatementisnotterminatedcorrectly.
• Solution–inthesourcecodeaddasemicolonattheendofthestatement,thensavethefiletoapplythechange.
• Cause–theprogramnameandclassnamedonotmatch.
• Solution–inthesourcecodechangetheclassnamefromtesttoTest,thensavethefiletoapplythechange.
• Cause–thevariabletexthasnovalue.
• Solution–inthevariabledeclarationassignthevariableavalidStringvalue,forinstance=“success”,thensavethefile.
Youmustruntheprogramfromwithinitsdirectory–youcannotuseapathaddressastheJavalauncherrequiresaprogramname,notafilename.
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.
2
Performingoperations
ThischapterdemonstratesthevariousoperatorsthatareusedtocreateexpressionsinJavaprograms.
DoingarithmeticAssigningvalues
ComparingvaluesAssessinglogicExaminingconditionsSettingprecedence
EscapingliteralsWorkingwithbitsSummary
Doingarithmetic
Arithmeticaloperators,listedinthetablebelow,areusedtocreateexpressionsinJavaprogramsthatreturnasingleresultingvalue.Forexample,theexpression4*2returnsthevalue8.
Operator: Operation:
+Addition(andconcatenatesStringvalues)
-Subtraction
-
*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.
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;
JavamustbeinstalledonyoursystempathtolaunchtheJavashellfromanyprompt–seeInstallinghereandTroubleshootingherefordetails.
TheJavashelljshellisanewfeatureinJava9.Optionally,thesemicoloncharactermaybeomittedattheendofsinglestatementsenteredintotheshellbutthesearerequiredwhenwritingJavaprogramsforcompilation.Semicolonsareincludedintheshellexamplesinthischaptertoaidcodeconsistency.
Assigningvalues
Assignmentoperators,listedinthetablebelow,areusedtoassigntheresultofanexpression.Allexceptthesimple=operatoraretheshorthandformofalongerequivalentexpression:
Operator: Example: Equivalent:
=a=b a=b
+=a+=b a=a+b
-= 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
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.
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
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);
YoucandiscovermoreoptionswithintheJavashellbyenteringthe/helpcommand.
Hereit’suntrue(false)thattheStringvaluesareequal,butitistruethattheyareunequal.
Noticehowanexpressioncanbecontainedinparenthesesforbetterreadability.
Assessinglogic
Logicaloperators,listedinthetablebelow,areusedtocombinemultipleexpressionsthateachreturnaBooleanvalue–intoacomplexexpressionthatreturnsasingleBooleanvalue.
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).
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);
result=(no||no);
Enterstatementstoshowanoriginalandinversevalueresult=yes;result=!yes;
Noticethatfalse&&falsereturnsfalse,nottrue–demonstratingthemaximthat“twowrongsdon’tmakearight”.
Thevaluereturnedbythe!NOTlogicaloperatoristheinverseofthestoredvalue–thestoredvalueitselfremainsunchanged.
Examiningconditions
Possiblytheall-timefavoriteoperatoroftheJavaprogrammeristhe?:conditionaloperatorthatmakesapowerfulstatementveryconcisely.Itsunusualsyntaxcanseemtrickytounderstandatfirst,butitiswellworthgettingtoknowthisusefuloperator.
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;
YoucanalsostarttheJavashellwiththecommandjshell--feedbackverbosetoreceivedescriptiveoutputaftereachevaluation.
FollowthesestepstoexploretheJavaconditionaloperatorintheJavashell:
Openacommand-linepromptwindow,thentypejshellandhittheEnterkeytolaunchtheJavashellNext,enterstatementstoinitializetwointvariablesintnum1=1357;intnum2=2468;
DeclareafurthervariabletostoreatestresultStringStringresult;
Enterthisstatementtodeterminewhetherthefirstintegervalueisanoddorevennumberresult=(num1%2!=0)?“Odd”:“Even”;
Now,enterthisstatementtodeterminewhetherthesecondintegervalueisanoddorevennumberresult=(num2%2!=0)?“Odd”:“Even”;
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
+-Addition,Subtraction
>>=<<= Greaterthan,GreaterthanorequaltoLessthan,Lessthanorequalto
==!=Equality,Inequality
&& LogicalAND
||LogicalOR
?:Conditional
=+=-=*=/=%=Assignment
Operatorsofequalprecedencearehandledintheordertheyappearintheexpression–fromlefttoright.
FollowthesestepstoexploreoperatorprecedenceintheJavashell:
Openacommand-linepromptwindow,thentypejshellandhittheEnterkeytolaunchtheJavashellNext,enterastatementtodisplaytheresultofevaluatinganexpressionthatusesdefaultoperatorprecedenceintsum=32-8+16*2;
Now,enterastatementtodisplaytheresultofevaluatingthesameexpression–butgivingadditionandsubtractionprecedenceovermultiplicationsum=(32-8+16)*2;
Finally,enterastatementtodisplaytheresultofevaluatingthesameexpressiononcemore–butnowwhereoperationprecedenceorderisfirstaddition,thensubtraction,andthenmultiplicationsum=(32-(8+16))*2;
Whereexpressionshavemultiplenestedparentheses,theinnermosttakesprecedence.
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
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){}
}
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
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
^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
{
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:
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
omit==true.
• Itisimportanttoexplicitlysetoperatorprecedenceincomplexexpressionsbyaddingparentheses().
• Thebackslashescape\operatorcanbeusedtoprefixquotecharacterswithinStringvaluestopreventsyntaxerrors.
• Escapesequences\nnewlineand\ttabprovidesimpleoutputformatting.
• Bitwiseoperatorscanbeusefultoperformbinaryarithmeticinspecializedsituations.
3
Makingstatements
ThischapterdemonstratesthevariouskeywordsthatareusedtocreatebranchinginJavaprograms.
BranchingwithifBranchingalternatives
SwitchingbranchesLoopingforLoopingwhiletrueDoingdo-whileloops
BreakingoutofloopsReturningcontrolSummary
Branchingwithif
TheifkeywordperformsaconditionaltesttoevaluateanexpressionforaBooleanvalue.Astatementfollowingtheexpressionwillonlybeexecutedwhentheevaluationistrue,otherwisetheprogramproceedsontosubsequentcode–pursuingthenext“branch”.Theifstatementsyntaxlookslikethis:
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:
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
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
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
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
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.
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)
{
}
}
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
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.
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);
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
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
{
publicstaticvoidmain(String[]args){}
}
While.java
Insidethemainmethod,declareandinitializeanintegervariablenamednumintnum=100;
Addawhilelooptodisplaythenumvariable’scurrentvaluewhileitremainsabovezerowhile(num>0)
{
System.out.println(“WhileCountdown:”+num);
}
Insertanupdaterattheendofthewhileloopblocktodecreasethenumvariable’svalueby10oneachiteration–therebyavoidinganinfiniteloopnum-=10;
SavetheprogramasWhile.javathencompileandruntheprogramtoseetheoutput
Theassignmentinthisupdaterisshorthandfornum=(num-10).
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
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);
}
}
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){}
}
}
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)
{
{
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;
}
Here,thecontinuestatementskipsjustthefirstiterationoftheinnerloopwhentheouterlooptriestorunitforthefirsttime.
Returningcontrol
Thedefaultbehaviorofthebreakandcontinuekeywordscanbechangedtoexplicitlyspecifythatcontrolshouldreturntoalabeledouterloopbystatingitslabelname.
Startanewprogramnamed“Label”containingthestandardmainmethodclassLabel
{
publicstaticvoidmain(String[]args){}
}
Label.java
Insidethemainmethod,createtwonestedforloopsthatdisplaytheircountervaluesoneachofthreeiterationsfor(inti=1;i<4;i++)
{
{
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;
}
}
Herethecontinuestatementhaltsallthreeiterationsoftheinnerloop‘sfirstrun–byreturningcontroltotheouterloop.
Toexplicitlyspecifythattheprogramshouldexitfromtheouterloop,statethatloop’slabelnameafterthebreakkeyword
Addthisbreakstatementtothebeginningoftheinnerloopstatementblock,toexittheouterloop–thenrecompileandre-runtheprogramif(i==2&&j==3)
{
System.out.println(“BreaksouterLoopwheni=”+i+“j=”+j);breakouterLoop;
}
Herethebreakstatementhaltsallfurtheriterationsoftheentireloopstructure–byexitingfromtheouterloop.
Summary
• TheifkeywordperformsaconditionaltesttoevaluateanexpressionforaBooleanvalueoftrueorfalse.
• Anifstatementblockcancontainoneormorestatements,whichareonlyexecutedwhenthetestexpressionreturnstrue.
• Theelsekeywordspecifiesalternativestatementstoexecutewhenthetestperformedbytheifkeywordreturnsfalse.
• Combinedifelsestatementsenableaprogramtoproceedbytheprocessofconditionalbranching.
• Aswitchstatementcanoftenprovideanelegantsolutiontounwieldyifelsestatementsbyofferingcaseoptions.
• Eachcaseoptioncanbeterminatedbythebreakkeywordsoonlystatementsassociatedwiththatoptionwillbeexecuted.
• Thedefaultkeywordcanspecifystatementstobeexecutedwhenallcaseoptionsreturnfalse.
• Alooprepeatedlyexecutesthestatementsitcontainsuntilatestedexpressionreturnsfalse.
• Theparenthesesthatfollowtheforkeywordspecifytheloop’scounterinitializer,testexpression,andcounterupdater.
• Statementsinawhileloopandadowhileloopmustchangeavalueusedintheirtestexpressiontoavoidaninfiniteloop.
• Thetestexpressionisevaluatedatthestartofforloopsandwhileloops–beforethefirstiterationoftheloop.
• Thetestexpressionisevaluatedattheendofdowhileloops–afterthefirst
iterationoftheloop.
• Aloopiterationcanbeskippedusingthecontinuekeyword.
• Aloopcanbeterminatedusingthebreakkeyword.
• Nestedinnerloopscanuselabelswiththebreakandcontinuekeywordstoreferencetheouterloop.
4
Directingvalues
ThischapterdemonstrateshowtodirectdatavaluesusingvariousJavaprogrammingconstructs.
CastingtypevaluesCreatingvariablearrays
PassinganargumentPassingmultipleargumentsLoopingthroughelementsChangingelementvalues
AddingarraydimensionsCatchingexceptionsSummary
Castingtypevalues
HandlingvaluesinJavaprogrammingrequirescorrectdatatypingtobecloselyobservedtoavoidcompilererrors.Forexample,sendingafloattypevaluetoamethodthatrequiresaninttypevaluewillproduceacompilererror.Thismeansitisoftennecessarytoconvertavaluetoanotherdatatypebeforeitcanbeprocessed.
Numericvaluescanbeeasily“cast”(converted)intoanothernumericdatatypeusingthissyntax:
(data-type)valueSomelossofprecisionwilloccurwhencastingfloatfloating
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){}
}
}
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
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];
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
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.
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”);
}
}
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:
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.
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
Thisprogramwillreportanerrorifnon-numericvaluesareentered.Seeherefordetailsonhowtocatcherrors.
Loopingthroughelements
Alltypesofloopcanbeusedtoeasilyreadallthevaluesstoredinsidetheelementsofanarray.Theloopcountershouldstartwiththeindexnumberofthefirstelementthenproceedonuptothefinalindexnumber.Theindexnumberofthelastelementinanarraywillalwaysbeonelessthanthearraylength–becausetheindexstartsatzero.
Itisusefultosetthearraylengthpropertyastheloop’sconditionaltestdeterminingwhentheloopshouldend.Thismeansthattheloopwillcontinueuntilthecountervalueexceedstheindexnumberofthearray’sfinalelement.
Startanewprogramnamed“Loops”containingthestandardmainmethodclassLoops
{
publicstaticvoidmain(String[]args){}
}
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++;
}
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.
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
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
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.
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;
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,
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.
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.”);}
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.
• Multi-dimensionalarrayscanstoremultiplesetsofelementvalues,eachhavingtheirownindexdimension.
• Atrycatchstatementblockisusedtoanticipateandhandleruntimeexceptionsthatmayarise.
• TheExceptionclasscatchesallexceptionerrors,includingNumberFormatExceptionandArrayIndexOutOfBoundsException.
• Atrycatchstatementcanbeextendedwithafinallystatementblock,containingcodethatwillalwaysbeexecuted.
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.
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.
Seethemodule’sPackageslistedalphabeticallyineachsection–scrolldownthepagetothe“Exports”sectionandfindthejava.langpackage,thenclickitshyperlink
Seethepackage’sClasseslistedalphabeticallyineachsection–scrolldownthepagetothe“ClassSummary”sectiontofindtheMathclass,thenclickitshyperlink
Seetheclass’sMethodslistedalphabeticallyinthe“MethodSummary”section–clickonanyhyperlinktodiscoverthepurposeofthatmethodanditssyntax
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;
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
{
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
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
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
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){}
}
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
{
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
ThisprogramisrevisitedwithagraphicaluserinterfaceinChapter10.
Managingstrings
InJavaprogramming,aStringiszeroormorecharactersenclosedwithinquotationmarks.So,theseareallvalidStringvalues:Stringtxt1=“MyFirstString”;
Stringtxt2=“”;
Stringtxt3=“2”;
Stringtxt4=“null”;
Array.lengthisapropertybutString.length()isamethod–soitmusthavetrailingparentheses.
Theemptyquotesoftxt2initializethevariableasanemptyStringvalue.Thenumericvalueassignedtotxt3isaStringrepresentationofthenumber.TheJavanullkeyword,whichnormallyrepresentstheabsenceofanyvalue,issimplyaStringliteralwhenitisenclosedwithinquotes.
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“);
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
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
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
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”};
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
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
{
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
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.
• CharactercaseofaStringcanbechangedusingitstoUpperCase()methodandtoLowerCase()method.
• StringvaluescanbecomparedusingthestartsWith()andendsWith()methodsofaString.
• AsubstringcanbesoughtinaStringusingitsindexOf()andsubstring()methods.
• TheisEmpty()methodonlyreturnstruewhentheStringcontainsabsolutelynothing.
• CharacterscanbemanipulatedwithinaStringvalueusingitstrim(),charAt(),andreplace()methods.
6
Creatingclasses
ThischapterdemonstrateshowtocreateJavaprogramsthatemploymultiplemethodsandclasses.
FormingmultiplemethodsUnderstandingprogramscope
FormingmultipleclassesExtendinganexistingclassCreatinganobjectclassProducinganobjectinstance
EncapsulatingpropertiesConstructingobjectvaluesSummary
Formingmultiplemethods
Programsaretypicallysplitintoseparatemethodsinordertocreatemodulesofcodethateachperformtasks,andthatcanbecalledrepeatedlythroughouttheprogramasrequired.Splittingtheprogramintomultiplemethodsalsomakesiteasiertotrackdownbugs,aseachmethodcanbetestedindividually.Furthermethodsmaybedeclared,insidethecurlybracketsthatfollowtheclassdeclaration,usingthesamekeywordsthatareusedtodeclarethemainmethod.Eachnewmethodmustbegivenaname,followingtheusualnamingconventions,andmayoptionallyspecifyargumentsintheparenthesesafteritsname.
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
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));}
SavetheprogramasOverload.javathencompileandruntheprogramtoseetheoutput
ThedeclarationforeachoftheoverloadedmethodsmustindicatethatthemethodreturnsaStringvalue,notvoid.
Understandingprogramscope
Avariablethatisdeclaredinsideamethodisonlyaccessiblefrominsidethatmethod–its“scope”ofaccessibilityisonlylocaltothemethodinwhichitisdeclared.Thismeansthatavariableofthesamenamecanbedeclaredinanothermethodwithoutconflict.
Startanewprogramnamed“Scope”containingthestandardmainmethodclassScope
{
publicstaticvoidmain(String[]args){}
}
Scope.java
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
Aprogrammayhaveaglobalclassvariableandlocalmethodvariableofthesamename.Thelocalmethodvariabletakesprecedenceunlesstheglobalclassvariableisexplicitlyaddressedbytheclassnameprefixusingdotnotation,orifalocalvariableofthatnamehasnotbeendeclared.
EditScope.javabyinsertingaglobalclassStringvariableconstantofthesamenameasthelocalmethodvariablesfinalstaticStringtxt=“ThisisaglobalvariableoftheScopeclass”;
AddastatementattheendofthemainmethodtooutputthevalueoftheglobalclassvariableSystem.out.println(Scope.txt);
Commentoutthelinethatdeclaresthelocalvariableinthesubmethod–sotheoutputstatementwillnowaddresstheglobalvariableofthesamename//Stringtxt=“Thisisalocalvariableinthesubmethod”;
Savethechanges,thenrecompiletheprogramandrunitoncemoretoseetherevisedoutput
Uselocalmethodvariableswhereverpossibletoavoidconflicts–globalclassvariablesaretypicallyonlyusedforconstants.
Formingmultipleclasses
Inthesamewaythataprogrammayhavemultiplemethods,largerprogramsmayconsistofseveralclasses–whereeachclassprovidesspecificfunctionality.Thismodularformatisgenerallypreferabletowritingtheentireprogramina
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
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()
{
System.out.println(“”);
}
}
Draw.java
SavethefileasDraw.javainthesamedirectoryastheMulti.javaprogram,thencompileandruntheprogramtoseetheoutput
Thepublickeywordallowsaccessfromanyotherclass,butdefaultaccessonlyallowsaccessfromclassesinthesamepackage.
Extendinganexistingclass
Aclasscaninheritthefeaturesofanotherclassbyusingtheextendskeywordintheclassdeclarationtospecifythenameoftheclassfromwhichitshouldinherit.Forexample,thedeclarationclassExtraextendsBaseinheritsfromtheBaseclass.
Theinheritingclassisdescribedasthe“sub”class,andtheclassfromwhichit
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)
{
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
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
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
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.
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
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
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
{
{
}
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);
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
AnuninitializedStringvariablehasanullvalue–socallingthegetCar()methodbeforesetCar()willreturnanullfromeachvariable.
Constructingobjectvalues
Anobject’sconstructormethodcanbecalleddirectlyintheobjectclasstoinitializeobjectvariables.Thishelpstokeepthedeclarationsandassignmentsseparate,andisconsideredtobegoodprogrammingstyle.Itisdemonstratedinthefollowingstepsthatreproducethepreviousexampleherewithencapsulatedattributesandmethod–togetherwithinitializationbytheconstructor:
Startanewclassnamed“Car”classCar
{
}
Constructor.java
Betweenthecurlybracketsoftheclass,declarethreeprivateStringvariablestostoreobjectattributesprivateStringmaker;privateStringcolor;privateStringbodyType;
AddaconstructormethodthatinitializesallthreevariableswithattributevaluespublicCar()
{
maker=“Porsche”;
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”);
}
}
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
globalscopethroughoutthatclass.
• Thestatickeywordisusedtodeclareclassmethodsandclassvariables–havingglobalscopethroughoutthatclass.
• Thepublickeywordexplicitlyallowsaccessfromanyclass.
• Aclassdeclarationcanincludetheextendskeywordtonominateasuperclassfromwhichitwillinherit.
• Theclassnameanddotnotationcanbeusedtoexplicitlyaddressaparticularclassmethodorclassvariable.
• Real-worldobjectshaveattributesandbehaviorsthatcanberepresentedinprogramsbyvariablesandmethods.
• Javaobjectsarecreatedasatemplateclassfromwhichinstancecopiescanbemade.
• Eachclasshasaconstructormethodthatcanbeinvokedusingthenewkeywordtocreateaninstancecopyofthatclass.
• Instancesinherittheattributesandbehaviorsoftheclassfromwhichtheyarederived.
• Encapsulationprotectsinstancevariablesandinstancemethodsfrommanipulationbyexternalclasses.
• Theprivatekeyworddeniesaccessfromoutsidetheclasswherethedeclarationismade.
• Anobject’sconstructormethodcanbecalledtoinitializevariableattributesofthatobject.
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
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
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
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){}
}
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
Entertextasprompted,thenhitReturntoseetheoutputmessagecontainingyourinputtext
Itisgoodpracticetocalltheclose()methodoftheBufferedReaderobjectwhenitisnolongerneeded.
Readingfiles
Thejava.iopackagecontainsaclassnamedFileReaderthatisespeciallydesignedtoreadtextfiles.ThisclassisasubclassoftheInputStreamReaderclassthatcanbeusedtoreadconsoleinputbyconvertingabytestreamintointegersthatrepresentUnicodecharactervalues.
AFileReaderobjectiscreatedusingthenewkeyword,andtakesthenameofthefiletobereadasitsargument.Optionally,theargumentcanincludethefullpath
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”);
}
}
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
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)
{
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
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;
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);
Arrays.sort(nums);
Outputthecontentsofallelementsineacharrayagaindisplay(names);
display(nums);
SavetheprogramasSort.javathencompileandruntheprogramtoseetheoutput
Theforloopsinthisexampleeachexecuteasinglestatementsonocurlybracketsarerequired–buttheycouldbeaddedforclarity.
Makingarraylists
Thejava.utilpackagecontainsaclassnamedArrayListthatstoresdatainanordered“Collection”(resizablesequence)oflistelements.Thiscanbemadeavailabletoaprogrambyimportingthespecificclasswithimportjava.util.ArrayList;.Alistmaycontainduplicateelements,andanArrayListobjecthasusefulmethodsthatallowmanipulationofstoredvaluesbyspecifyingtheir
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
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
Aswithregulararrays,elementsinanArrayListhaveazero-basedindex.
ThegraphicalJavaSwingJComboBoxcomponentthatisintroducedhereholdsadrop-downlistofoptions,somustalsospecifyitsgenericdatatypewhenthatobjectgetscreated.
Managingdates
Thejava.timepackagecontainsaclassnamedLocalDateTimethathasusefulmethodstoextractspecificfieldsfromaLocalDateTimeobjectthatdescribeaparticularpointintime.Thesecanbemadeavailabletoaprogrambyimportingthespecificclasswithimportjava.time.LocalDateTime;orbyimportingallclassesinthispackageusingthewildcardwithimportjava.time.*;.
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=
“\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
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.
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
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
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.
8
Buildinginterfaces
ThischapterdemonstrateshowtouseJavaSwingcomponentstocreateagraphicalprograminterface.
CreatingawindowAddingpushbuttons
AddinglabelsAddingtextfieldsAddingitemselectorsAddingradiobuttons
ArrangingcomponentsChangingappearanceSummary
Creatingawindow
Programscanprovideagraphicaluserinterface(GUI)usingthe“Swing”componentsoftheJavalibrary.Thejavax.swingpackagecontainsclassestocreateavarietyofcomponentsusingthestyleofthenativeoperatingsystem.Thesecanbemadeavailabletoaprogrambyincludingtheinitialstatementimportjavax.swing.*;.
AclassmustbecreatedtorepresenttheGUItowhichcomponentscanbeaddedtobuildtheinterface.ThisiseasilyachievedbydeclaringitasubclassofSwing’sJFrameclassusingtheextendskeyword–therebyinheritingattributes
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.*;
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
TheEXIT_ON_CLOSEoperationisaconstantmemberoftheJFrameclass.Itexitstheprogramwhenthewindowgetsclosed.
Noticehowtheadd()methodisusedheretoaddtheJPanelobjecttotheJFramewindow.
Addingpushbuttons
TheSwingJButtonclasscreatesapush-buttoncomponentthatcanbeaddedtoagraphicalinterface.Thisletstheuserinteractwiththeprogrambyclickingonabuttontoperformanaction.
TheJButtonobjectiscreatedwiththenewkeyword,anditsconstructortakesaStringargumentspecifyingtexttobedisplayedonthatbutton.
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);
SavetheprogramasButtons.javathencompileandruntheprogramtoseepushbuttonsappearinthewindow
TheJPanelobjecthasanadd()method–toaddcomponentstothatpanel.
DetailsofhowtocreateaJavaArchive(JAR)canbefoundhere.
Thebuttonsrespondgraphicallywhentheyareclicked,butwillnotperformanactionuntiltheprogramprovidesanevent-handlermethodtorespondtoeachclickevent.
WheretheprogramisintendedfordeploymentinasingleJavaarchive(JAR),imageresourcesmustbeloadedbyaClassLoaderobjectbeforecreatingtheImageIconobjectstorepresentthem.
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
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
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
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.
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);
SavetheprogramasTextFields.javathencompileandruntheprogram,enteringsometextintothetextarea
AJTextAreacomponenthasnoscrollingabilityunlessitiscontainedwithinaJScrollPanecomponent.
Addingitemselectors
TheSwingJCheckBoxclasscreatesacheckboxcomponentthatcanbeaddedtoagraphicalinterface.Thiscanbeusedtoallowtheusertoselectordeselectindividualitemsinaprogram.TheJCheckBoxobjectiscreatedwiththenewkeyword,anditsconstructortakesaStringargumentspecifyingtexttobedisplayedalongsidethatcheckbox.Itcanalsotakeasecondtrueargumenttomakethecheckboxbeselectedbydefault.
AchoiceofitemscanbeofferedbytheJComboBoxclassthatcreatesadrop-downlistfromwhichtheusercanselectanysingleitem.Thisobjectiscreatedwiththenewkeyword,anditsconstructortypicallytakesthenameofaStringarrayasitsargument.Eachelementinthearrayprovidesanitemforselectioninthedrop-downlist.Similarly,achoiceofitemscanbeofferedbytheJListclass
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);
pnl.add(box1);
Now,insertastatementtoaddtheJListcomponenttotheJPanelcontainerpnl.add(lst1);
SavetheprogramasItems.javathencompileandruntheprogram,selectingitemsfromthelists
OnlyoneitemcanbeselectedfromaJComboBoxcomponent–multipleitemscanbeselectedfromaJListcomponent.
Detailsofhowtocreateevent-handlermethodstorespondtouseractions,suchasanitemselection,canbefoundinChapter9.
Addingradiobuttons
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);
SavetheprogramasRadios.javathencompileandruntheprogram,selectinganyoneradiobuttonafterthedefault
TheButtonGroupobjectonlygroupsthebuttonslogically,notphysically.
Detailsofhowtocreateevent-handlermethodstorespondtouseractionscanbefoundinthenextchapter.
TheexamplesonthepreviouspageshavedemonstratedthemostcommonSwingcomponents–JButton,JLabel,JTextField,JCheckBox,JComboBox,JListandJRadioButton.Therearemanymorespecializedcomponentsavailableinthejavax.swingpackage,whosedetailscanbefoundintheJavadocumentation.Forexample,theJSlider,JProgressBar,andJMenuBarcomponentsbelow:
TryusingtheJavadocumentationtoaddaJSlidercomponenttotheRadiosprogram–seeherefordetailsonhowtousethedocumentation.
Arrangingcomponents
Thejava.awtpackage(AbstractWindowToolkit)containsanumberoflayoutmanagerclassesthatcanbeusedtoplacecomponentsinacontainerindifferentways.
Alayoutmanagerobjectiscreatedusingthenewkeyword,andcanthenbespecifiedastheargumenttoaJPanelconstructortohavethepanelusethatlayout.Whencomponentsgetaddedtothepaneltheywillbeplacedaccordingtotherulesofthespecifiedlayoutmanager.
LayoutManager: Rules:
BorderLayoutPlacesNorth,South,East,WestandCenter(thecontentpanedefault)
BoxLayoutPlacesinasingleroworcolumn
CardLayoutPlacesdifferentcomponentsinaspecifiedareaatdifferenttimes
FlowLayoutPlaceslefttorightinawrappingline(theJPaneldefault)
GridBagLayoutPlacesinagridofcells,allowingcomponentstospancells
GridLayoutPlacesinagridofrowsandcolumns
GroupLayoutPlaceshorizontallyandvertically
SpringLayoutPlacesbyrelativespacing
ThetoplevelJFrameobjecthasa“contentpane”containerthatplacescomponentsusingtheBorderLayoutlayoutmanagerbydefault.ThiscanbeusedtoplaceuptofiveJPanelcontainers,whichmayeachusetheirdefaultFlowLayoutlayoutmanager,oranyofthelayoutmanagersinthetableabove.Usingavarietyoflayoutmanagersaccommodatesmostlayoutrequirements.
Thecontentpanecanberepresentedbyajava.awt.Containerobject,whoseadd()methodcanspecifythepositionandnameofacomponenttobeplacedwithinthecontentpane.
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
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:
• 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);
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
operationandvisibility.
• AJPanelcontainerdisplayssmallercomponentsinawrappinglineusingitsdefaultFlowLayoutlayoutmanager.
• TheJButtonconstructorcanspecifytextandimagestobedisplayedonapushbuttoncomponent.
• AnImageIconobjectrepresentsanimagetouseintheprogram.
• ProgramsthataretobedeployedasasingleJavaarchive(JAR)shoulduseaClassLoaderobjecttospecifyanimagesource.
• AJLabelobjectdisplaysnon-interactivetextandimagecontent.
• EditabletextcanbedisplayedinJTextFieldandJTextAreafields.
• AJScrollPaneobjectprovidesscrollbarsforaJTextAreafield.
• ItemsforselectioncanbedisplayedwithJCheckBox,JComboBoxandJListcomponents.
• AButtonGroupobjectlogicallygroupsanumberofJRadioButtoncomponentssoonlyonecanbeselected.
• SpecificRGBcolorscanberepresentedbytheColorclassofthejava.awtpackage.
• Thejava.awtpackagehasaFontclassthatcanbeusedtocreateobjectsrepresentingaparticularfontname,style,andsize.
• MultipleJPanelcontainerscanbeaddedtoaJFramecontainerbyusingtheContainerclassofthejava.awtpackagetorepresentthecontentpaneoftheJFrame.
• WhencreatingaJPanelcontainerobject,itsargumentmayoptionallyspecifyalayoutmanager.
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.*;.
ThedesiredEventListenerinterfacecanbeincludedintheclassdeclarationusingtheimplementskeyword.Forexample,aclassdeclarationtolistenforbuttonclicksmightlooklikethis:classClickextendsJFrameimplementsActionListener{}
TheJavadocumentationdescribesmanyEventListenerinterfacesthatcanlistenoutfordifferentevents,butthemostcommononesarelistedinthetablebelow,togetherwithabriefdescription:
EventListener: Description:
ActionListenerRecognizesactioneventsthatoccurwhenapushbuttonispushedorreleased
ItemListenerRecognizesitemeventsthatoccurwhenalistitemgetsselectedordeselected
KeyListenerRecognizeskeyboardeventsthatoccurwhentheuserpressesorreleasesakey
MouseListenerRecognizesmousebuttonactionsthatoccurwhentheuserpressesorreleasesamousebutton,andwhenthemouseentersorexitsacomponent
MouseMotionListenerRecognizesmotioneventsthatoccurwhentheusermovesthemouse
MultipleEventListenerscanbeincludedaftertheimplementskeywordasacomma-separatedlist.
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)
{
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);
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
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.*;
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
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
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.*;
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)
{
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
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
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
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
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
Youcanalsosimplyspecifytheparentandmessageastwoargumentstocreateadialogwiththedefaultinformationiconandthedefault“Message”title.
Requestinginput
TheSwingJOptionPaneclasscanrequestinformationfromtheuserbyopeningadialogboxwithitsshowConfirmationDialog()method,requestingadecision,orwithitsshowInputDialog()method,requestinguserinput.
Boththesemethodscantakefourarguments:• Parentobject–typicallyreferencedbythethiskeyword• RequestStringtobedisplayed• DialogtitleString
• OneoftheJOptionPaneconstantssuchasPLAIN_MESSAGEortospecifydialogdecisionbuttonsasYES_NO_CANCEL_OPTION
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)
{
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
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.
• AMouseListenerinterfacepassesageneratedMouseEventeventastheargumenttofiverequiredevent-handlermethods,whichcanrespondtomouseactionsmadebytheuser.
• AMouseMotionListenerinterfacepassesageneratedMouseEventeventastheargumenttotworequiredevent-handlers,whichcanrespondtomousemovement.
• TheshowMessageDialog()methodoftheJOptionPaneclasscreatesadialogdisplayingamessagetotheuser,anditsshowInputDialog()andshowConfirmationDialog()methodscanbeusedtorequestuserinput.
• AudioresourcescanberepresentedbytheAudioClipclassofthejava.appletpackage,andplayedusingitsplay()method.
10
Deployingprograms
ThischapterdemonstrateshowtodeployJavaprograms–bothasJavaarchives(JAR)andAndroid
applicationpackages(APK).
ProducinganapplicationDistributingprograms
BuildingJavaarchivesDeployingapplicationsCreatingAndroidprojectsExploringprojectfiles
Addingresources&controlsInsertingJavacodeTestingtheapplicationDeployingAndroidapps
Summary
Producinganapplication
Javaapplicationsforbothdesktopandhandhelddevicescanbecreatedfromcommoncode–liketheLotto.javaprogrambelow:importjavax.swing.*;importjava.awt.event.*;
ComponentspublicclassLottoextendsJFrameimplementsActionListener
{
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();}
}
}
Lotto.java
Thealgorithminthisevent-handlershufflesintegers1-59inanarray,thenassignsthoseintegersinthefirstsixelementstoastring.
TheLottoprogrambeginswithimportstatementstomakeSwingcomponentsandtheActionListenerinterfaceavailable.
Lotto.png–Checkeredareasaretransparent
Components
Theprogramcomprisesasinglepanelcomponentcontainingalabelcomponenttodisplayanimage,atextfieldcomponenttodisplayoutput,andabuttoncomponentforuserinteraction.
Constructor
TheLotto()constructorbuildsasimpleSwinginterfacethatloadsthepanelintoawindowframemeasuring260x210.
Event-handlerThebutton’sevent-handlermethodexecutesanalgorithmtoselectasequenceofsixuniquerandomnumbersintherangeof1-59fordisplayinthetextfieldcomponent.
Entry-pointThemain()methodcreatesaninstanceoftheapp,andcallsuponClassLoader()toseektheimagefileresourceLotto.pnginthesamedirectoryastheprogramfile.Thefilesmustbearrangedinthiswaybeforeattemptingtocompiletheprogram.
TheLottoprogramisusedthroughoutthischaptertocreateappsfordesktopandhandhelddevices.
Observingtherequiredfilearrangement,thejavaccompilercanbeemployedintheusualwaytocreateaLotto.classfile,thenthejavainterpretercanbeemployedtoexecutetheprogram:
Distributingprograms
TheLottoprogramopensanewwindowofthespecifiedsizecontainingtheSwinginterfacecomponents.Eachtimetheuserclicksthepushbutton,itsevent-handlerdisplayssixnewrandomnumbersintherange1-59withinthetextfield
component:
Aswithallotherexamplesinthisbook,theexampleLottoprogramhasbeencompiledhereforJava9andcanbedistributedforexecutiononothercomputerswheretheJava9RuntimeEnvironmentispresent–regardlessoftheiroperatingsystem.Forexample,inthescreenshotsbelow,Lotto.classandLotto.pngfileshavebeencopiedtothedesktopofacomputerrunningtheLinuxoperatingsystemwiththeJava9runtimeinstalled.TheLottoprogramcan,therefore,beexecutedbythejavainterpreterinthesamewayasontheoriginatingWindowssystem.
The.javasourcecodefileneednotbeincludedwhendistributingaprogram–only.classandresourcefilesareneeded.
Thereis,however,adangerindistributingJavaprogramsthiswayastheprogramwillfailtoexecuteifresourcefilesbecomeunavailable–inthiscase,
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
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:
Now,enterjarxfLotto.jarMETA-INFtoextractacopyoftheMETA-INFdirectoryFinally,entertypeMETA-INF\MANIFEST.MFtoseethetextcontainedwithinthearchivemanifest
TheJARmanifestcanbemodifiedforadvancedpurposes,suchastheadditionofpermissionstousesystemresources.
Deployingapplications
JavaJARfilesareexecutableonanysystemonwhichtheappropriateversionoftheJavaRuntimeisinstalled:
Atthecommandline,navigatetothedirectorywheretheLotto.jarfileislocated,thentypejava-jarLotto.jarandhittheEnterkeytoruntheLottoapplication
Alternatively,double-clickorright-clicktheLotto.jarfileicon,andchooseto“OpenWith”theJavaRuntime
The.jarfileextensionisrequiredwhenexecutingJARfilesfromaprompt.
SettheJREasthedefaultJARfilehandleronyoursystemforpermanentdouble-clickexecution.
CreatingAndroidprojects
TheAndroidoperatingsystem,prevalentonhandhelddevices,includesasetofcorelibrariesthatprovidemostofthefunctionalityofthoseintheJavaprogramminglanguage.ThismeansthatJavaprogramscanbereadilyconvertedforAndroid.
AndroidStudioisavailablefreefromdeveloper.android.com/studioThisexampledescribesversion2.3.3–instructionsmayvaryforotherversions.AndroidStudioisasizeabledownloadofaround1.9GB,andmayrequireadditionaldownloadstocompletesetup.CheckthesystemrequirementstoensureyourcomputercanrunAndroidStudiobeforedownloading.
AndroidappdevelopmentisbestundertakenusingtheofficialAndroidStudioIntegratedDevelopmentEnvironment(IDE).ThisprovidesaunifiedenvironmentwhereyoucandevelopappsforallAndroiddevices,andprovides
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
ClickNexttoopenthe“AddanActivitytoMobile”dialog,andsimplyselecttheEmptyActivityoptionClickNexttoopenthe“CustomizetheActivity”dialog
ClickFinishtoacceptthesuggestedconfiguration–AndroidStudiowillnowgenerateseveralfilesandfoldersforthenewproject(thiscantakeawhile)theneventuallyopentheIDEinterface
ChooseAPI15ifyouwouldliketheapptorunon100%ofdevicesactiveontheGooglePlayStore.
Youcanchangethesuggestednameshere,butbesuretoleavetheGenerateLayoutFileandBackwardsCompatibilityboxeschecked.
Exploringprojectfiles
TheAndroidStudioIDEprovidesaProjectwindowthatdisplaysanexpandabletreeviewofallfilesandfolderswithintheproject.YoucanclickanyarrowintheProjectwindowtoexpandafolder,anddouble-clickonanyfileintheProjectwindowtoopenitinthetabbedEditorwindow.
Despiteitsinitialappearanceofcomplexity,onlytwofilesneedmodificationbythedevelopertocreateacustomizedapplication:• MainActivity.java–theJavafilethatloadscontrolsintotheappinterfaceandcancontainevent-handlercodetorespondtouseractionswithintheappinterface.
• activity_main.xml–theXMLfilethatdefineseachcontroltoappearintheappinterfaceandtheirlayout.
IftheProjectwindowisnotimmediatelyvisibleclicktheProjectbuttonintheleftsidebar,oropenitusingtheshortcutkeysAlt+F1.
Selectingtheactivity_main.xmlfileintheProjectwindowpresentsitintheEditorwindowinoneoftwopossibleviews–visuallyinDesignvieworprogrammaticallyinTextview.Therearetabsatthebottomofthewindowtoswitchbetweenviews.
DesignviewprovidesaPaletteofcontrolsthatcanbedraggedontoagraphicalrepresentationoftheapp,aComponentTreetoselectanyaddedcontrol,andaPropertieswindowinwhichtomodifytheappearanceofaselectedcontrol.
Textviewprovidesa“code-behind”versionofthelayoutthatdescribeseachaspectofaddedcontrolsusingXMLattributes.
ControlscanbeaddedtotheappinterfaceandmodifiedeithervisuallyinDesignvieworprogrammaticallyinTextview.
Addingresources&controlsImageResources
TobegincustomizingthedefaultAndroidStudioemptyappfortheLottoprogram,theimagecanfirstbeaddedasa“resource”:
Right-clickontheLotto.pngimage,andchooseCopyNext,right-clickontheapp>res>drawablefolderandchoosePaste–toseea“Copy”dialogappearRenamethefiletolowercaseLotto.png
ClickOKtoseethefilenowappearinthedrawablefolder
Androidonlysupportslowercasefilenamesforresourceitems.
InterfaceControls
TheLottoappwillrequirethreeinterfacecontrolsalignedoneabovetheotherinaverticallayout.AnImageViewcontrolisrequiredforthelogo,aTextView
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
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
ClickOKtoclosethedialog,andseetheassignedstringgetreplacedbyareferencetothenewstringresource
Repeatthisforthe“GETMYLUCKYNUMBERS”string
InsertingJavacode
Afteraddingresourcesandcontrolshere,theappinterfaceshouldnowresemble
thatoftheLotto.jarapplication:
Ifthecontrolsdonotlooklikethisscreenshot,youshouldreturntohere
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);
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.
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
CreationofeachAVDemulatormayrequirealargesystemimagefiletobedownloaded.YoumayprefertotestonarealAndroiddevice.AlsonotethatacceleratedemulatorswillonlyrunifyourcomputerhasaCPUthatsupportshardwarevirtualization(IntelVT-xorAMDSVM).
AndroidStudiohasanInstantRunfeaturethatautomaticallyupdateschangestotheappsotheyappearinthetestdevicemorequickly.
Itisbettertotestonrealdevicesratherthantheemulators.Ideally,youshouldtestonasmanydifferentdevicesaspossiblebeforefinaldeploymentofapps.
TakeanAndroidtabletandenable“USBDebugging”ontheSettings,DeveloperOptionsmenuConnectthetablettoyourcomputerviaaUSBporttoseethisnotification
ClickRun,Run‘app’(orpresstheShift+F10shortcut)toopenthe“SelectDeploymentTarget”dialog
Selecttheconnectedtabletdevice,thenclickOKtoinstalltheLottoapponthetabletPushtheappbuttontoseetheLottoapphappilyperformasexpected–asuccessfultest
Thetestprocessesprovideanapplicationlaunchersothetabletcanbedisconnectedandtheapplaunchedbytappingthelaunchericon–butremember,thisisaDebugbuildoftheapp.
IfyoucannotseeDeveloperOptionsontheAndroidSettingsyoucanenableitbytappingontheBuildNumberseventimes–typicallyfoundatSettings,About,SoftwareInformation,BuildNumber.
AndroidStudioprovidesadefaultimagelaunchericon,butyoucanuse
yourownimage.IntheProjectwindow,right-clickontheresfolderthenchooseNew,ImageAssettoopentheAssetStudio,thenselectImageandbrowsetoanimageyouwishtoimportintotheproject.
DeployingAndroidapps
Aftersuccessfultesting,thedevelopmentDebugversionofanappshouldbechangedtoaReleaseversionbeforedeploymentasanAndroidApplicationPackage(APK).AndroidrequiresthatallAPKsmustbedigitallysignedwithacertificate,andAndroidStudioallowsyoutoeasilygenerateasignedAPK:
ClickBuild,SelectBuildVariant,thenchoosethereleaseversionoption
Next,clickBuild,GenerateSignedAPK
EnterexistingkeystoredetailsorclickCreatenew...
Choosealocationatwhichtosavethekeystore,thenenterpasswords
Selectyourpreferredvalidityperiod,thenentercertificateinformation
ClickOKtocreatethenewkeystore
ClickNexttousethenewkeystoretogenerateasignedAPKfortheapp
AdditionalstepsarerequiredifyouwishtodistributeyourappsviatheGooglePlayStore.Youcandiscoverwhatisneededonlineatdeveloper.android.com/distribute/tools/launch-checklist.html
Akeystoreholdsoneormorecorrespondingpublic/privatekeypairs.You,astheownerofthecertificate,retaintheprivatekeywhiletheAndroidStudiosigningtoolattachesthepublickeycertificatetotheAPK.ThisuniquelyassociatestheAPKtoyouandyourcorrespondingprivatekeytoensurethatanyfutureupdatestotheAPKcomefromtheoriginaldeveloper.
ChoosealocationatwhichtosavetheAPKandbesuretheBuildTypeis“release”,thenclickFinishtogenerateasignedAPKnamedapp-release.apk
Uponsuccess,changetheAPKnametoamoremeaningfulLotto.apk
Aproductflavorcanbespecifiedtodefinedifferentcustomizedbuildsoftheapp.Forexample,thebuttontextonaSpanishlanguageflavoras“Consiguemisnúmerosdelasuerte”.
TheAndroidappAPKcannowbedeployedinseveralways:• AppMarketplace–publishonGooglePlayStore• Email–senddirectasanattachment• Website–hostonlinefordownloadInstallationofAPKsfromsourcesotherthanGooglePlayisblockedunlesstheuseroptstoallowthem:
OnanAndroiddevice,gotoSettings,Securityandoptto“Allowinstallationofappsfromunknownsources”
Next,downloadLotto.apktotheAndroiddeviceNavigatetothedownloadfolderandclickInstall,thentapthe launchericontoruntheapp
Summary
• Javaprogramscanbedeployedasstand-alonedesktopapplicationsrunningonanappropriateversionoftheJRE.
• Applicationfilescanbedistributedforexecutiononotheroperatingsystemsusingtheappropriatejavainterpreter.
• BundlingallprogramfilesintoasingleJARarchivefilehelpsensureresourcefilesdonotbecomeaccidentallyisolated.
• ExecutableJARapplicationscanbeexecutedfromapromptwiththejava-jarcommandorbyclickingontheirfileicon.
• JavaprogramscanbereadilyconvertedfortheAndroidoperatingsystemasitincludessimilarcorelibraries.
• AndroidStudioistheofficialIDEforthedevelopmentofAndroidapplications.
• APKandJARarchivefilesarebothcompressedinZIPformat.
• EachAndroidappisfirstcreatedasaprojecttowhichthedeveloperaddscodeandresources.
• ThemostusedwindowsintheAndroidStudiointerfacearetheProjectwindowandtheEditorwindow.
• FunctionalcodecanbeaddedtotheMainActivity.javafileandinterfacecomponentsaddedtotheactivity_main.xmlfile.
• AnAndroidappcanstoreimagesandstringsasresources.
• Thesignatureofabutton’sonClickevent-handlermustincludeaparameterforaViewclassobject.
• InterfacecomponentscanbereferencedincodebyspecifyingtheiridentityastheargumenttofindViewById().
• AndroidStudioprovidesAVDemulatorsfortestingandalsoallowstestingtobeperformedonrealconnecteddevices.
• TheReleaseversionofanAndroidappmustbedigitallysignedwithapublickeycertificate.