Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Absolute-Beginner-Java-4-Selenium... ·...

Preview:

Citation preview

FreeWebinars,Videos,andLiveTrainingMr.Jonesplanstohavefreestep-by-stepdemonstrationwebinars,videos,andlivetrainingswalkingpeoplethroughconceptsofSeleniumandQTP/UFTfromA-Z.Thematerialwillteach/trainindividualsthefundamentalsoftheprogramminglanguage,fundamentalsofSeleniumandQTP/UFT,andimportantconceptsofSeleniumandQTP/UFT.Allofthewebinars,videos,andlivetrainingwillbedirectedtowardbeginnersaswellasmid-levelautomationengineers.

SignUptoReceive

1. 3TipsToMasterSeleniumWithin30Dayshttp://tinyurl.com/3-Tips-For-Selenium

2. 3TipsToMasterQTP/UFTWithin30Dayshttp://tinyurl.com/3-Tips-For-QTP-UFT

3. FreeWebinars,Videos,andLiveTrainingshttp://tinyurl.com/Free-QTP-UFT-Selenium

RexJones’ContactInformationEmailAddress:Rex.Jones@Test4Success.orgLinkedIn:https://www.linkedin.com/in/rexjones34Books:http://tinyurl.com/Rex-Allen-Jones-BooksTwitter:@RexJonesIISkype:rex.jones34

TableofContentsFREEWEBINARS,VIDEOS,ANDLIVETRAINING

REXJONES’CONTACTINFORMATION

TABLEOFCONTENTS

PREFACE

ABOUTTHEAUTHOR

ABOUTTHEEDITOR

COPYRIGHT,LEGALNOTICE,ANDDISCLAIMER

ACKNOWLEDGEMENTS

CHAPTER1INTRODUCTIONTOJAVA

OVERVIEW

VARIABLESANDDATATYPES

OPERATORS

CONTROLSTRUCTURES

OBJECT-ORIENTEDPROGRAMMING(OOP)

CHAPTER2VARIABLESANDDATATYPES

VARIABLENAMES

VARIABLEDECLARATION

VARIABLEINITIALIZATION

VARIABLETYPE,SCOPE,ANDLIFETIME

PRIMITIVEDATATYPES

CONSTANTS

CHAPTER3OPERATORS

ARITHMETICOPERATORS

BITWISEOPERATORS

LOGICALOPERATORS

RELATIONALOPERATORS

ASSIGNMENTOPERATOR

TERNARYOPERATOR

OPERATORPRECEDENCE

DATATYPECASTING

EXPRESSIONS

CHAPTER4CONTROLSTRUCTURES

IFBRANCH

SWITCHBRANCH

FORLOOP

WHILELOOP

DOWHILELOOP

BREAKTOEXIT

CONTINUETONEXTSTATEMENT

CONCLUSION

RESOURCES

BOOKSBYREXJONESII

SIGNUPTORECEIVE

PrefaceIamenthusedtowriteaninstructionalbookonJavabecauseIhavetalkedwithmanytesterswhocanrelatetothefrustrationcausedbythelackofinformationtolearnJavaforautomationtesting.JavaisoneoftheprogramminglanguagesforSelenium.Acommonchallengewithnewautomationtestersislearninghowtoprogram.Therefore,thisbookisdesignedtohelpanabsolutebeginnerlearnJava.Thepurposeofthisbookistofillaneedofautomationtesterswhoareforcedtohurrypasttheprogrammingcomponentofautomation,leadingtoastrugglewithworkinginSelenium.

TargetAudience

ThetargetaudienceisbeginnerswithlittletonoknowledgeofJava.BeginnersarepeoplenewtoSeleniumandJava,andhaveadesiretoestablishadeepfoundationofJavaprinciples.

WhylearnJava?

JavaisapowerfulprogramminglanguagethatisfrequentlyandcommonlyimplementedintheInformationTechnology(IT)industry.JavaprogrammersareinhighdemandintheITfieldandbeingabletocodeautomationscriptsinJavawillmakeyouacommoditytoanyqualityassurancetestingteam.TherearemanyJavaforums(messageboards)onlinethatsupportJavaprogrammersinneedofasolutionforaproblem.LearningJavaandSeleniumisagreatcombinationthatwillmakeanyqualityassurancetestereffectiveonanautomationproject.

AbouttheAuthor

RexAllenJonesIIisaQA/SoftwareTesterwithapassionforsharingknowledgeabouttestingsoftware.Hehasbeenwatchingwebinars,attendingseminars,andtestingapplicationssinceFebruary2005.Mr.JonesgraduatedfromDeVryUniversityinJune1999withaBachelor’sofSciencedegreeinComputerInformationSystems(CIS).

Currently,RexisaConsultantandformerBoardofDirectorforUserGroup:Dallas/FortWorthMercuryUserGroup(DFWMUG)andmemberofUserGroup:Dallas/FortWorthQualityAssuranceAssociation(DFWQAA).InadditiontohisUserGroupmemberships,heisaCertifiedSoftwareTesterEngineer(CSTE)andhasaTestManagementApproach(TMap)certification.

Mr.Jones’adviceforpeopleinterestedinFunctionalAutomationTestingistolearntheprogramminglanguage.Thisadviceledhimtowritetwobooks“(Part1&Part2)YouMustLearnVBScriptforQTP/UFT”gearedtowardsVBScriptwhichistheprogramminglanguageforUnifiedFunctionalTesting(UFT)formerlyknownasQuickTestProfessional(QTP).Inaddition,onebook“Part1–Java4SeleniumWebDriver”andanupcomingbook“Part2–Java4SeleniumWebDriver”gearedtowardJavawhichisoneoftheprogramminglanguagesforSelenium.

AbouttheEditor

WhenSamanthaMannisnotimprovingthecontentsofadocumentthroughconstructiveeditingmarksandremarks,sheisenjoyinglifeasaprofessionalinDallas,Texas.SamanthaisaUserExperienceguruintherealmsofresearchanddesign,andworksasanInformationTechnologyconsultant.Outsideofworkherhobbiesincludethetypicalnerd-typefunoffreelanceediting,reading,writing,andbingewatchingNetflixwithherpitbull.

ConnectwithSamantha:

Samantha.danae.mann@gmail.com

https://www.linkedin.com/pub/samantha-mann/84/9b7/100

Copyright,LegalNotice,andDisclaimerThispublicationisprotectedundertheUSCopyrightActof1976.Allrightsarereservedincludingresalerightswhichappliestointernational,federal,state,andlocallaws.Thepurchaserisnotallowedtoshareorsellthisbooktoanyone.

Pleasenotethatmuchofthispublicationisbasedonpersonalexperienceandanecdotalevidence.Theauthorhasmadeeveryreasonableattempttoproduceaccuratecontentinthisbook.Heassumesnoresponsibilityforunknownerrorsoromissions.Therefore,thepurchasershouldusethisinformationashe/sheseesfit.

Anytrademarks,servicemarks,productnamesornamedfeaturesareassumedtobethepropertyoftheirrespectiveownersandusedonlyforreference.

Copyright©2016Test4Success,LLC.Allrightsreservedworldwide.

ASIN:B01CO4E000

AcknowledgementsIwouldliketoexpressmygratitudetomywifeTiffany,childrenOliviaRexe’andRexIII,editorSamanthaMann,family,friends,andthemanypeoplewhoprovidedencouragement.Writingthisbooktooktimeandyoursupporthelpedpushedthisbookforward.

ThankYou,

RexAllenJonesII

Chapter1IntroductiontoJava

OverviewJavaisapowerfulprogramminglanguagedevelopedbySunMicrosystems.Itisawidelyusedobject-orientedlanguagethatrevolutionizedtheweb.Inadditiontorevolutionizingtheweb,Javaisusedinmanydevices,suchascellphones.TheJavaDevelopmentKit(JDK)andoneoftheIntegratedDevelopmentEnvironments(IDE),suchasEclipse,mustbedownloadedandinstalledinordertouseJava.

ThefollowinglinksarevalidfordownloadingJavaDevelopmentKit(JDK)andEclipseIDEatthetimeofwritingthisbook:

DownloadJavaDevelopmentKit(JDK)http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html

DownloadEclipseIDEhttps://eclipse.org/downloads/

OncetheJDKandEclipseIDEhavebeendownloadedandinstalled,statementscanbewrittenandcompiled.Statementsarereferredtoascode—alineorlinesofinformationwritteninaparticularsyntax. Thekeytoallprogramminglanguagesisthesyntax.Syntaxisasetofrulesthatspecifiesastructuredcombinationofwordsandsymbols.Ifnotstructuredcorrectly,anerroroccurstopreventthestatementsfromcompiling.

Compilingstatementsisperformedviaacompiler.Acompiledlanguagereferstoaspecialprogramthatretrievesthestatementsdevelopedbyaprogrammerandthentranslatesthestatementsintoanunderstandablemachinelanguage.Acomputerprocessoristhenabletousethemachinelanguageoncethestatementsaretranslated. Itisimportanttoknowthatcommentsarestatementsbutignoredandnevercausesanerror.Commentsarenotesthathelpprogrammersunderstandtheprogramand/orotherstatements.Thefollowingaretwotypesofcomments:

1. Singleline–commentonelineatatime2. Multi-line–commentmultiplelines

Usually,multi-linecommentsarelocatedatthetopofaprogramwithinformationdescribingtheentireprogram.Singlelinecommentsareusedtoexplainstatementswithintheprogram.Thepurposeofbothtypesofcommentsistoself-documentcontentwrittenintheprogram.Commentsprovideanswerstotwoquestions:

1. Whatisthepurposeoftheprogram,statements,etc.?2. Whydidtheprogrammerwritetheprogram,statements,etc.?

Thefollowingisanexampleofasingleandmulti-linecomment:

/*

Programmer:RexJonesII

Description:Showbothtypesofcomments

Purpose:

Date:

*/

publicclassMain

{

publicstaticvoidmain(String[]args)

{

//Thisisasinglelinecommentexample

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

}

}

Figure1.1–SingleandMulti-LineExamples

ProgramOutput:HelloWorld!!!

Lineonebeginsthemulti-linecommentwithaforwardslash(/)andanasterisk(*)whilelinesixendsthemulti-linecommentwithanasteriskandforwardslash(*/).Line12

beginsthesinglelinecommentwithtwoforwardslashes(//)anddoesnotincludesymbolstoendthecomment.

ThischapterprovidesgeneralconceptsregardingJavaandwillexplainthefollowing:

VariablesandDataTypes

Operators

ControlStructures

Object-OrientedProgramming(OOP)

Note:Detailsoftheconceptsarecoveredinsubsequentchapters.

VariablesandDataTypesAvariableisamemorylocationwithanamethatcontainsavalue(seeVariablesandDataTypesinChapter2).Inordertousethevariable,itmustbedeclaredandinitialized.Declaringavariableisstatingclearlythatavariableexistsbyprovidingadatatypeandvariablename.Datatypereferstothetypeofdatathatcanbestoredinavariablewhilevariablenameidentifiesthevariable.InJava,therearetwokindsofdatatypes:primitiveandreference.Primitivedatatypesupportseightbasicdatatypesandreferencedatatypeisbasedonaclass.Initializingavariableiswhenthevariableisassignedavaluethatcanchangeduringprogramexecution.Thefollowingisavariabledeclarationandinitializationexample:

publicclassDeclare_Initialize_Variable

{

publicstaticvoidmain(String[]args)

{

intsum;

sum=3+4;

System.out.println(“Whatisthesumof3+4?“+sum);

}

}

Figure1.2–VariableDeclarationandInitialization

ProgramOutput:Whatisthesumof3+4?7

Linefivedeclaresthevariablewithadatatype“int”andvariablename“sum”whilelineseveninitializes“3+4”tothevariable“sum”.InJava,allvariablespossessadatatype,variablename,andvalue.

OperatorsOperatorsaresymbolssuchasplus(+)andminus(-)thatperformmathematicaloperations(seeOperatorsinChapter3).Theoperatorsareexecutedonoperandswhichisanythingthatcanbechanged.Avariableisacommonoperandwhichchangesduringexecution.InJava,therearefourtypesofoperators:

1. Arithmetic–implementmathematicaloperationsonnumericalvalues2. Bitwise–workonoperandsutilizingbits3. Logical–returnsabooleanvalue(trueorfalse)basedononeormoreexpressions4. Relational–returnsabooleanvalue(trueorfalse)aftercomparingoperands

ThefollowingisanArithmeticOperatorexample:

publicclassSubtraction_Operator

{

publicstaticvoidmain(String[]args)

{

//SubtractionOperator

intx,y,answer;

x=100;

y=80;

answer=x-y;

System.out.println(“Whatis100-80?“+answer);

}

}

Figure1.3–SubtractionArithmeticOperator

ProgramOutput:Whatis100-80?20

Linesevendeclaresthevariables“x,y,answer”withanintdatatype.However,linesnineand10assignthevalues(x=100andy=80)totwoofthevariables.The–Subtractionoperatorisimplementedatline12andsubtractstherightoperand“y”fromtheleftoperand“x”thenassignsthevalue“20”tovariable“answer”.

ControlStructuresControlstructuresprovidewaystoregulatetheflowofaprogram(seeControlStructuresinChapter4).Theflowisdirectedbybranchesandloops.Branchesallowcertainstatementstobeskippedafterevaluatingaconditionorvariable.Loopspermitspecificstatementstoberepeatedaccordingtoabooleanexpression.Thefollowingisalistoftwobranchesandthreeloops:

Branches1. IfBranch–executesastatementwhenaconditionistrue2. SwitchBranch–evaluatesavariablethenexecuteastatementaccordingtothe

variable’svalue

Loops1. ForLoop–executesablockofcodeacertainnumberofiterations2. WhileLoop–repeatsastatementwhileabooleanexpressionistrue3. DoWhileLoop–executeastatementatleastoneiterationandcontinuewhilethe

booleanexpressionistrue

Thefollowingisanifbranchexample:

publicclassIf_Branch

{

publicstaticvoidmain(String[]args)

{

//IfBranch

booleanstudy;

study=true;

if(study==true)

{

System.out.println(“YoucanlearnJava/Seleniumwithin30days”);

}

else

{

System.out.println(“Maytakealittlelongerthan30daysbutremainpatient”);

}

}

}

Figure1.4–IfBranchExample

ProgramOutput:YoucanlearnJava/Seleniumwithin30days

Lineeightassignsvariable“study”thevalueoftrue.Asaresult,thecondition“if(study==true)”evaluatestotrue.Therefore,theprogramexecutesline12andskiptheremaininglines(line14–17).Ontheotherhand,theprogramwouldhaveexecutedlines14–17andskippedlines11–13iftheconditionwasfalse.

Object-OrientedProgramming(OOP)Javaisanobject-orientedprogramming(OOP)languagethatisstructuredaroundobjects.Anobjectisanythingthatcanbeseenorperceived.Allobjectshavetwocharacteristics:stateandbehavior.Stateidentifiestheobjectandbehaviorrepresenttheactionsoftheobject.Forexample,acustomercanbeidentifiedbytheirname(state)whiletalking(behavior)istheactionofthecustomer.

Bothcharacteristics“stateandbehavior”aredefinedbyaclass.Aclassisatemplateforobjectsandformsthefoundationforobject-orientedprogramming.Dataandstatementsthatoperateonthedataarespecifiedbyclasses.Inaddition,accesstothedatabywayofclassesarecarriedoutthroughmethods.Amethodmanipulatesdataandprovideinteractionwithclassesfromothercomponentsoftheprogram.Thefollowingisanexampleillustratingaclass,object,andmethod:

classCustomer

{

Stringname;

intage;

publicstaticvoidmain(String[]args)

{

CustomerfirstCustomer=newCustomer();

firstCustomer.name=“JoeDoe”;

System.out.println(“Thecustomer’snameis“+firstCustomer.name);

}

}

Figure1.5–Class,Object,andMethodExample

ProgramOutput:Thecustomer’snameisJoeDoe

Lineonedisplaysthekeyword“class”andclassname“Customer”LinesixisamethodlabeledmainLineeightdeclaresfirstCustomerasthevariableforclasstype“Customer”.Keyword“new”allocatesmemoryandcreatesanewCustomerobject

Chapter1outlinedgeneralconceptsregardingvariables,datatypes,operators,controlstructures,andobject-orientedprogramming.Thedetailsofvariables,datatypes,operators,andcontrolstructuresarepresentedinthisbook.Also,thelinkstodownloadJavaDevelopmentKit(JDK)andEclipseIDEwereprovided.Thenextbook“Part2–Java4SeleniumWebDriver”thoroughlyexplainsobject-orientedprogramming,whichincludesclasses,objects,andmethods.Chapter2willdefinethefourtypesofvariableslocal,parameter,instance,andclassaswellasprimitivedatatypes:boolean,byte,char,double,float,int,long,andshort.

Chapter2VariablesandDataTypes

Avariableisanamedcontainerormemorylocationthatholdsavalue.Thevalueofthecontainerormemorylocationcanchangeduringexecutionoftheprogram.Eachvariablehastheabilitytocontainanykindofinformation,suchastextornumbers.Asaresult,automationengineersareempoweredtocreateflexibleprograms.Variablesareutilizedtorepresentchangeabledata,ratherthanhard-codingdata(enteringunchangeabledatadirectlyintoaprogram).

Allvariablespossessaname,datatype,andvalue.Avariablenameisusedtouniquelyidentifythevariable.Datatypereferstothetypeofvariable,suchasint,double,orbooleanthatcanbestoredinavariable.Therefore,datatypedeterminesavariable’svalue.InJava,therearetwokindsofdatatypes:primitiveandreference.Primitivedatatypesupportseightbasicdatatypes(explainedinthischapter)andreferencedatatypeisbasedonaclass(explainedinPart2–Java4SeleniumWebDriver).

Chaptertwocoversthefollowingregardingvariablesanddatatypes:

VariableNames

VariableDeclaration

VariableInitialization

VariableType,Scope,andLifetime

PrimitiveDataTypes

Constants

VariableNamesThenameofavariableissignificantwhenidentifyingthevariableinmemory.Hence,variablesarereferredtoasidentifiers.Inadditiontovariables,anidentifierrepresentsmethodsalongwithotheruser-defineditems.Allvariablenamescanrangeanywherefromonecharactertoanunlimitednumberofcharacters.Thefollowingisavariablenameexample:

publicclassVariableExample

{

publicstaticvoidmain(String[]args)

{

intcustOrder;

custOrder=123;

System.out.println(“Thecustomer’sordernumberis“+custOrder);

}

}

Figure2.1–VariableNameExample

ProgramOutput:Thecustomer’sordernumberis123

VariableNamingRulesJavahasrulestonamingvariables.Oneoftherulesistoensureeachvariablehasauniquename.Uniquenamespreventerrorsfromoccurring,suchas“Duplicatelocalvariable”—meaningthesamevariablenamehasbeenenteredmorethanonetime.Thefollowingisalistofmorerulesfornamingavariable:

Cancontaincasesensitiveletters,numbers,dollarsign“$,”andunderscore“_”Canbeginwithaletter,dollarsign“$,”orunderscore“_”CannotbeginwithanumberCannotcontainaspaceorspecialcharacterexceptdollarsign“$,”andunderscore“_”Cannotcontainareservekeyword

Thefollowingisalistof50Javareservekeywords:

abstract continue for new switch

assert default goto package synchronized

boolean do if private this

break double implements protected throw

byte else import public throws

case enum instanceof return transient

catch extends int short try

char final interface static void

class finally long strictfp volatile

const float native super while

Figure2.2-ReserveKeywords

VariableNamingConventionsConventionisageneralagreementorpracticewhenestablishingastandard.Suitablefornamingvariables,aconventionisimportantwhileworkingwithateamofautomationengineers.Allidentifiernames(e.g.,variable,method,etc.)arecriticalforreading,understanding,andmaintainingcode.Thefollowingisalistofsuggestedconventionsfornamingavariable:

Constructdescriptivenamesthatdescribethevariable’spurposeComposenamesutilizingmixedcaseletters,unlessthenameisoneword

Ifoneword,thenusealllowercaselettersIfmultiplewords,thenbeginthefirstwordwithalowercaseletterandeachconsecutivewordwithanuppercaseletter(e.g.,custFirstName)

Createanamethatbeginswithaletterandnotadollarsign“$”orunderscore“_”Chooseloopcontrolvariablesthatbeginwithasinglelowercaseletter(e.g.,i,x,y)

VariableDeclarationDeclaringavariableisstatingclearlythatavariableexists.Allvariablesareassociatedwithadatatypeintheeventofdeclaringavariable.Datatypesguaranteethecorrectdataisassignedtoavariable.Inaddition,thesizeofavariableisdeterminedbyadatatype.Variablesmustbedeclaredbeforetheyareutilizedinanyprogram.Thefollowingisthesyntaxfordeclaringavariable:

SyntaxvariableTypevariableName;

SyntaxDetails

Argument Description

variableType Datatypeofvariablebeingdeclared

variableName Nameofvariablebeingdeclared

; Semi-coloncompletesthedeclarationstatement

Figure2.3–VariableDeclarationSyntaxDetails

Thefollowingisavariabledeclarationexample:

publicclassVariableExample

{

publicstaticvoidmain(String[]args)

{

intx;

inty;

x=5;

y=7;

System.out.println(“Thevaluesofxandyare“+x+”and“+y);

}

}

Figure2.4–VariableDeclaration

ProgramOutput:Thevaluesofxandyare:5and7

Linesfiveandsixdeclarevariablesxandywithanintdatatype.Noticehoweachdeclarationendswithasemi-colon.Thesemi-coloncompletesthedeclarationstatement.

Note:Multiplevariablescanbedeclaredonthesamelineifthevariablehasthesamedatatype.Thefollowingisadeclarationexampleofmultiplevariablesseparatedbyacomma:

intx,y;

VariableInitializationIngeneral,variablesaregivenaninitialvaluebeforethevariablesareused.TheAssignmentOperatorseparatestwosidesofanequation.Thereisaleftandrightsideofeveryequation.Theleftsidedisplaysavariablenamewhiletherightsidedisplaysavalue.Variablescanbeinitializedthefollowingways:

1. InitializebyValue2. InitializebyDynamics

InitializebyValueInitializingavariablebyvaluesrequiresavaluetobesetforthevariable.Thefollowingaretwowaystoinitializeavariablebyvalue:

1. Atdeclaration2. Afterdeclaration

AtdeclarationAtdeclarationiswhenthedatatype,variablename,andvalueareplacedonthesameline.Inotherwords,thevariableisdeclaredandinitializedsimultaneously.Multiplevariablescanbeinitializedatdeclarationbyusingacommaseparatedlist.Thefollowingisanexampleof“atdeclaration”initializebyvalue:

publicclassVariableExample

{

publicstaticvoidmain(String[]args)

{

intnum1=100,num2=200,total;

total=num1+num2;

System.out.println(“Thetotalofnum1andnum2is“+total);

}

}

Figure2.5–VariableInitializationAtDeclaration

ProgramOutput:Thetotalofnum1andnum2is300

Linefivedeclaresthreevariables“num1,num2,andtotal”withanintdatatype.Twoofthevariables“num1andnum2”areinitializedwithavaluethatrepresentsvariableinitializationatdeclaration.Therefore,thevariablesareinitializedwhentheyaredeclared.

AfterdeclarationAfterdeclarationiswhenthedatatype,variablename,andvalueareplacedontwoseparatelines.Thedatatypeandvariablenamearedeclaredonthesamelinewhilethevariablenameisassignedavalueonasubsequentline.Thefollowingisanexampleof“afterdeclaration”initializebyvalue:

publicclassVariableExample

{

publicstaticvoidmain(String[]args)

{

intnum1,num2,total;

num1=100;

num2=200;

total=num1+num2;

System.out.println(“Thetotalofnum1andnum2is“+total);

}

}

Figure2.6–VariableInitializationAfterDeclaration

ProgramOutput:Thetotalofnum1andnum2is300

Linefivedeclaresthreevariables“num1,num2,andtotal”withanintdatatype.Twoofthevariables“num1andnum2”areinitializedwithavalueonlinessevenandeightthatrepresentsvariableinitializationafterdeclaration.Therefore,thevariablesaredeclaredonlinefiveandinitializedaftertheyaredeclaredonlinessevenandeight.

InitializebyDynamicsInitializingavariablebydynamicsdoesnotassignaspecificvaluetoavariable.Instead,valuessubjecttochangeareassignedtothevariables.Occasionally,valuesthatchangearevaluesfromanApplicationUnderTest(AUT)orothervariables.Thefollowingisavariableinitializationbydynamicsexample:

publicclassVariableExample

{

publicstaticvoidmain(String[]args)

{

intnum1,num2;

num1=100;

num2=200;

inttotal=num1+num2;

System.out.println(“Thetotalofnum1andnum2is“+total);

}

}

Figure2.7–InitializebyDynamics

ProgramOutput:Thetotalofnum1andnum2is300

Line10declaresandinitializesvariable“total”withanintdatatype.Thevariableisnot

initializedwithaspecificvalue.However,thevariableisinitializedwithinformation“num1andnum2”thatcanpossiblychangeduringexecution.Forexample,anautomationengineercanenterstatementstoincreasethevalueofbothvariables“num1andnum2”duringexecution.Ifvariablesnum1andnum2change,thenthevariable“total”willdynamicallychange.

Note:Line10requiresadatatypeintwheninitializingavariablebydynamics.

VariableType,Scope,andLifetimeJavaallowsavariabletobedeclaredanywhereinaprogram.Forthatreason,avariablecanbedefinedwithinaclass,withinamethod,orwithinamethodasaparameter.Avariable’sscopeisrelatedtowherethevariableisdeclaredinsidetheprogram.Lifetimeishowlongthevariableexistsintheprogram.Thefollowingarefourtypesofvariablesthathavetheirownscopeandlifetime:

1. LocalVariables2. ParameterVariables3. InstanceVariables4. ClassVariables

LocalVariablesLocalvariablesaredeclaredinsideamethod.Individualmethodscanhavethesamevariablenameasanothermethodwithinaprogram.Localvariablesareonlyvisibleinsideitsindividualmethod.Therefore,eachvariableisuniquetoaspecificmethod.Beforeusingalocalvariable,itmustbedeclaredandinitializedavaluewithoutneedingaspecialkeyword.Hence,therearenodefaultvaluesforlocalvariables.Localvariablesarecreatedwhenthemethodisconstructedanddestroyedwhenthemethodisterminated.Thefollowingisalocalvariableexample:

publicclassVariableExample

{

publicvoidAutomationEngineers()

{

intyearsEmployed;

yearsEmployed=5;

System.out.println(“JoeDoe‘Automation’hasbeenattheorganization“+yearsEmployed+”years”);

}

publicvoidDevelopers()

{

intyearsEmployed;

yearsEmployed=3;

System.out.println(“JaneDoe‘Dev’hasbeenattheorganization“+yearsEmployed+”years”);

}

publicstaticvoidmain(String[]args)

{

VariableExampleyears=newVariableExample();

years.AutomationEngineers();

years.Developers();

}

}

Figure2.8–LocalVariable

ProgramOutput:JoeDoe‘Automation’hasbeenattheorganization5years

JaneDoe‘Dev’hasbeenattheorganization3years

Linesfiveandthirteendisplayavariable“yearsEmployed”thatislocaltomethods“AutomationEngineersandDevelopers.”Anerrorwillnotoccurbecauseeachvariableisuniquetoitsmethod.However,thesamevariablenamecannotbedeclaredmultipletimeswithinthesamemethod.Thescopeandlifetimeofalocalvariableislimitedtotheblock/curlybracesinwhichitisdeclared.

ParameterVariablesParametervariablesaredeclaredandpassedintomethods.Afteraparametervariableisdeclared,itisimplementedlikealocalvariable.Therefore,alocalvariableandparametervariablecannothavethesamename.Keywordsarenotrequiredforaparametervariable.However,thedatatypeandvariablenamemustbesurroundedbyaparenthesisafterthemethodname.Thefollowingisaparametervariableexample:

publicclassVariableExample

{

publicvoidsetMtgAmount(doublemtgAmount)

{

System.out.println(“Themortgagepaymentamountis“+mtgAmount);

}

publicstaticvoidmain(String[]args)

{

VariableExamplepayment=newVariableExample();

payment.setMtgAmount(99000);

}

}

Figure2.9–ParameterVariables

ProgramOutput:Themortgagepaymentamountis99000.0

Linesthreeandeightpassparametervariables“doublemtgAmountandString[]args”intomethods“setMtgAmountandmain.”Thevalue“99000”ispassedfromthemethodcall“payment.setMtgAmount”line11intothemethod“setMtgAmount”linethreethatiscalled.Thescopeofaparametervariableisamethod’sheaderinsidetheparenthesiswhile

thelifetimeisamethod’sbodywithinthecurlybrackets.

InstanceVariablesInstancevariablesaredeclaredinsideaclass,outsideofamethod,andaccessedusingkeywordnew.Thevaluesofaninstancevariableareuniquetoeachobject.Thistypeofvariablecanbeusedbeforeorafteritisinitializedwithvisibilitytoallmethodsinaclass.Defaultvaluesforanumberiszero,forbooleanthedefaultisfalse,andanobjectreferencedefaultisnull.Instancevariablesarecreatedwhenanobjectisformedandterminatedwhentheobjectisdestroyed.Thefollowingisaninstancevariableexample:

publicclassVariableExample

{

intyearsExist=34;

publicstaticvoidmain(String[]args)

{

VariableExampleyears=newVariableExample();

System.out.println(“Thisorganizationhasexistedfor“+years.yearsExist+”years”);

}

}

Figure2.10–InstanceVariable

ProgramOutput:Thisorganizationhasexistedfor34years

Linethreedeclarestheinstancevariable“yearsExist”withintheclass“VariableExample,”butoutsideofthemethod“main”.Theinstancevariableisaccessedinlineeight“years.yearsExist”aftercreatingkeywordnewvialineseven.

Note:AninstancevariablecanbeaccessedviaObjectReference.Lineeightprintsthevariable’svaluebyusingtheObjectReference.InstanceVariable“years.yearsExist”.

ClassVariablesClassVariables(knownasStaticVariables)aredeclaredinaclass,butnotinamethod.Thistypeofvariableisdeclaredusingkeywordstatic.Thekeywordstaticannouncestothecompilerthatonlyonecopyofaparticularvariableexists,butissharedbyallinstancesofanobject.Defaultvaluesforanumberiszero,thedefaultforbooleanisfalse,andanobjectreferencedefaultisnull.Usually,ClassVariablesaredeclaredasConstants.ClassVariablesarecreatedwhentheprogrambeginsanddestroyedwhentheprogramends.Thefollowingisaclassvariableexample:

publicclassVariableExample

{

staticintnumDays=30;

publicstaticvoidmain(String[]args)

{

VariableExampledays=newVariableExample();

System.out.println(“Javacanbemasteredin“+VariableExample.numDays+”days”);

System.out.println(“Seleniumcanbemasteredin“+days.numDays+”days”);

System.out.println(“DoyouthinkyoucanmasterJava/Seleniumin“+numDays+”days”);

}

}

Figure2.11–ClassVariable

ProgramOutput:Javacanbemasteredin30days

Seleniumcanbemasteredin30days

LinethreedeclarestheClassVariable“numDays”withintheclass“VariableExample,”butoutsideofthemethod“main.”Thescopeofaclassvariableisinsidetheblock/curlybracesofclassandoutsidetheblock/curlybracesofallmethods.Therefore,thelifetimeofthevariablecontinuesthroughoutexecutionoftheprogram.

Note:AclassvariablecanbeaccessedviaClassName,ObjectReference,orClassVariableName.IfaccessedbywayofObjectReferencethenkeyword“new”mustbecreated.Lineseight,nine,andtenaccesstheclassvariablebyusingtheClassName.ClassVariable“VariableExample.numDays”,ObjectReference.ClassVariable“days.numDays”,andClassVariableName“numDays”.

PrimitiveDataTypesTheprimitivedatatypesgiveanaccountforthetypeofdatathatisstoredinavariable.Eachdatatypehasapreciserangeandbehavior.Consequently,adatatypeofintcanstorenumericaldata,butatypemismatcherrorwilloccurifbooleanattemptstostorenumericaldata.Inaddition,certainoperationsarepermittedonvaluesdependingonthedatatype.Asanexample,amathcalculationcannotbeperformedonabooleandatatypebecauseabooleancannotcontainnumbers.Thefollowingisalistofalleightprimitivedatatypes:

Type WidthinBits(Bytes)

Description/Range

boolean TrueorFalsevalues

byte 8-bit(1-byte) -128to127

char 16-bit Standardcharactersetthatcanbealetter,controlcharacter,number,punctuation,orsymbolrepresentingalllanguagesintheworld

double 64-bit(8-byte) -1.7976931348623157E+308to1.7976931348623157E+308

float 32-bit(4-byte) -3.4028235E+38to3.4028235E+38

int 32-bit(4-byte) −2,147,483,648to2,147,483,647

long 64-bit(8-byte) -9,223,372,036,854,775,808to9,223,372,036,854,755,807

short 16-bit(2-byte) -32,768to32,767

Figure2.12–EightPrimitiveDataTypes

Thefollowingdividestheprimitivedatatypesinto4categories:

1. IntegerType2. FloatingPointType3. CharacterType4. BooleanType

IntegerTypeTheintegertypesupportsnumericalvalueswithoutafractionalcomponent.Amajordifferencewithintheintegertypeistherangeofvalues.Thefollowingshoweachdatatypeforintegertype:

byteshortintlong

Datatypeintisusedthemostbecauseitisusedforcontrollingloopsandindexingarrays.Thefollowingisanintdatatypeexample:

publicclassVariableExample

{

publicstaticvoidmain(String[]args)

{

//Calculate2integervalues

inti,j;

inttotal;

i=10;

j=20;

total=i+j;

System.out.println(“Totalofi+jis“+total);

}

}

Figure2.13–DataTypeint

ProgramOutput: Totalofi+jis30

Linessixandsevendeclareanintdatatypefornames“i,”“j,”and“total.”Linesnine,ten,andeleveninitializethevariables.

FloatingPointTypeThefloatingpointtypesupportsnumericalvalueswithafractionalcomponent.Datatypesfloatanddoublemakeupthefloatingpointtypecategory.DuetoJava’sstandardMathclass,thedoubledatatypeisusedthemostwhenanumericalvalueincludesafraction.Thefollowingisadoubledatatypeexample:

publicclassVariableExample

{

publicstaticvoidmain(String[]args)

{

doubled;

doublecalc;

d=200;

calc=Math.sqrt(d);

System.out.println(“Squarerootof200is“+calc);

}

}

Figure2.14–DataTypedouble

ProgramOutput: Squarerootof200is14.142135623730951

Linesfiveandsixdeclareadoubledatatypefornames“d”and“calc.”Lineeightassigns

200tovariable“d”,whilelinenineassignsasquarerootmethodtovariable“calc.”The“sqrt()”methodisamethodwithinthestandardMathclasswhichreturnsadoubledatatype.

CharacterTypeThecharactertypesupportsaUnicodesystemthatdisplaysallcharactersforeveryhumanlanguage.Inordertorepresentallcharacters,thechardatatypeholdsa16-bittypethathasarangeof0to65,535.TherangehelpsUnicodeassigneveryletter,number,andsymbolanexclusivenumericalvalue.Thefollowingisachardatatypeexample:

publicclassVariableExample

{

publicstaticvoidmain(String[]args)

{

charcha1,cha2;

cha1=‘C’;

cha2=67;

System.out.println(“Valueassignedtocha1is“+cha1);

System.out.println(“67istheUnicodefor“+cha2);

}

}

Figure2.15–DataTypechar

ProgramOutput:Valueassignedtocha1isC

67istheUnicodeforC

Linefivedeclaresachardatatypefornames“cha1”and“cha2.”Linessevenassignstheletter‘C’,utilizingsinglequoteswhilelineeightassignsavalueof67.Constantssuchaslinesevendeclaredwithachardatatypealwaysuseasinglequote(‘)foraletter.Value67istheAmericanStandardCodeforInformationInterchange(ASCII)fortheletter‘C’.

Note:Accordingtowebopedia,“ASCIIisacodeforrepresentingEnglishcharactersasnumbers,witheachletterassignedanumberfrom0to127”.

BooleanTypeThebooleantypesupportsaprogramwhentheprograminvolveslogic.Thus,thebooleandatatypereturnsavalueafterevaluatingalogical/conditionalstatement.Conditionalstatementsrequireananswer(trueorfalse)regardingaspecificstatement.Aconditionalstatementconsistsofvariablesand/orexpressions.Thefollowingisabooleandatatypeexample:

publicclassVariableExample

{

publicstaticvoidmain(String[]args)

{

booleanresult;

result=false;

System.out.println(“Booleanvariable‘result’wasinitializedto“+result);

System.out.println(“Isthisatrueorfalsestatement‘100greaterthan99’?“+(100>99));

}

}

Figure2.16–DataTypeboolean

ProgramOutput:Booleanvariable‘result’wasinitializedtofalse

Isthisatrueorfalsestatement‘100greaterthan99’?true

Linefivedeclaresabooleandatatypeforvariable“result.”Lineseveninitializesfalsetothevariable.Linenineprintsthedefaultvalueoffalse,butlinetenreturnatruevalueafterevaluatingcondition“100>99.”Trueisreturnedbecause100isgreaterthan99.

ConstantsConstants(alsoknownasLiterals)areunchangeablevaluesassignedtoavariablenameofaparticulardatatype.ThewayeachConstantisdefineddependsuponitsdatatype.DefiningaConstantisadefensemechanismtoprotectinformationsothatthevalueremainsfixed.Forinstance,thetotalhoursinadayis24,therefore,aConstantisdeclaredsothatthevalueof24doesnotchange.Thefollowingarefourtypesofconstants:

1. StringConstants2. CharacterConstants3. BooleanConstants4. NumericConstants

ConstantNamingConventionsAstandardnamingconventionforConstantsfacilitatetheprocessoflocatingtheConstants.ThefollowingareConstantnamingconventions:

ConstructdescriptivenamesthatdescribetheConstant’spurposeCreateanamethatincludesallcapitalletters(e.g.,CUSTOMER)Composeanameutilizingallcapitalletterswithanunderscoreifthenameconsistsofmultiplewords(e.g.,ORDER_NUM)

DeclareandInitializeConstantsConstantsaredeclaredandinitializedsimilartovariables.ThedistinguishingcharacteristicofdeclaringaConstantisthekeywordmodifierfinal.AdeclarationstatementutilizingfinalinformsJavathattheinitializationvaluewillnotbechanged.Thefollowingexampleshowsaconstantdeclarationandinitializationstatement:

publicclassVariableExample

{

publicstaticvoidmain(String[]args)

{

finalintDAYS_IN_WEEK=7;

finalintDAILY_MAX_HOURS=24;

inttotalHours;

totalHours=DAYS_IN_WEEK*DAILY_MAX_HOURS;

System.out.println(“Thetotalofhoursinaweekis“+totalHours);

}

}

Figure2.17–DeclareandInitializeConstants

ProgramOutput:Thetotalofhoursinaweekis168

LinessixandsevendeclareandinitializeConstantsusingkeywordmodifierfinal.ConstantnameDAYS_IN_WEEKassigned“7”,whileDAILY_MAX_HOURSassigned“24”.TheassignedConstantvalueswillnotchangeintheprogram.Anerrorstates“ThefinallocalvariableNAME_OF_CONSTANTcannotbeassigned”ifthereisanattempttochangeaConstant.

DefaultConstantDataTypesDatatypesintanddoublearedefaultConstanttypesintheirrespectivecategory.However,thedefaulttypecanbemodifiedbyappendingaletterofthetargettype.Anintdatatypechangestoalongdatatypebyattachingtheletter“l”or“L.”Forexample,avalueof34indicatesanintdatatypebydefaultbut34lor34Lindicatesalongdatatype.Thesameistruewithadoubledatatype.Avalueof12.34specifiesadoubledatatypebydefault,but12.34for12.34Fspecifiesafloatdatatype.

Note:Thissectionpointsoutthedefaultconstantdatatypes.However,aconstantcanbedeclaredasanyprimitivedatatype.

EscapeCharactersEscapecharacters(knownasbackslashcharacterconstants)representagroupofcharactersandnon-graphicalcharacters.AccordingtoBeginningJava®Programming(2015),“escapecharactersareusedfordisplayingtextinspecificways,eitherforinsertingtabsorenterswheredesired,orbydisplayingacharacterthat’snormallyreservedforcodesyntax”(page29).

Characterssuchassinglequotes(‘’)haveadistinctmeaningandcannotbeuseddirectly.Therefore,abackslashcharacter(\)mustprecedethecharactersothatthecompilerinterpretsagivenstatementcorrectly.Thefollowingisalistofescapecharacters:

EscapeCharacter

Description Unicode

\b Insertsabackspaceinthetext \u0008

\f Insertsaformfeedinthetext \u000C

\n Insertsanewlinefeedinthetext \u000A

\r Insertsacarriagereturninthetext \u000D

\t Insertsahorizontaltabinthetext \u0009

\’ Insertsasinglequote(apostrophe)inthetext

\u0027

\” Insertsadoublequoteinthetext \u0022

\ Insertsabackslashinthetext \u005C

Figure2.18–EscapeCharacters

StringConstantsStringConstantsareenclosedindoublequotes(“”)representingasequenceofcharacters.Regularcharacters(e.g.,numbers,letters,etc.),aswellasescapecharacters,canbeprocessedinaStringConstant.ThefollowingisaStingConstantexample:

publicclassMiscExamples

{

publicstaticvoidmain(String[]args)

{

System.out.print(“Thefollowingdisplaysnumbers1-10ontwolines:\n”);

System.out.println(“1\t2\t3\t4\t5”);

System.out.println(“6\t7\t8\t9\t10”);

}

}

Figure2.19–StringConstantExample

ProgramOutput:Thefollowingdisplaysnumbers1-10ontwolines:

12345

678910

Linesfive,six,andsevendisplayStringConstantswithinthedoublequotes.Noticehowlinefivehasaprint()statementratherprintln()statementlikelinessixandseven.Theescapecharacter(\n)insertsanewlinefeedsoprintln()isnotneeded.Inaddition,escapecharacter(\t)isusedinlinessixandseventoinsertatabbetweennumbers1through10.

CharacterConstantsCharacterConstantsarealwaysinitializedinsinglequotes(‘’)andholdonlyonecharacter.Figure2.15ischarexampleinitializingtheletter‘C’toavariablenamedcha1inlineseven.ThesinglequotesapplytolettersandnotnumbersassignedtoCharacterConstants.

BooleanConstantsBooleanConstantsinitializesTrueandFalsevalues.Figure2.16isabooleanexampleinitializingaTruevaluetoavariablenamed“result”inlineseven.

NumericConstantsNumericConstantscontainintegertypeorfloatingpointtypevalues.Thesevaluesallowunderscores(_)tobeusedlikeapunctuationmark.Usually,acomma,hyphen(-),etc.dividesanumericalvaluecontainingseveraldigits.Forinstance,onehundredmillioniswrittenas100,000,000.ThecommasimprovereadabilityofhundredmillionsimilartoanunderscoreimprovingaNumericConstant.ThefollowingisaNumericConstantexampledisplayingmultipleunderscoresforasimilarvalue:

publicclassMiscExamples

{

publicstaticvoidmain(String[]args)

{

finallongFIRST_AMOUNT,SECOND_AMOUNT,TOTAL_AMOUNT;

FIRST_AMOUNT=111_111_111;

SECOND_AMOUNT=222222222;

TOTAL_AMOUNT=FIRST_AMOUNT+SECOND_AMOUNT;

System.out.println(“Thefirstamountis“+FIRST_AMOUNT);

System.out.println(“Thesecondamountis“+SECOND_AMOUNT);

System.out.println(“Thetotalofbothamountsis“+TOTAL_AMOUNT);

}

}

Figure2.20–NumericConstantExample

ProgramOutput:

Thefirstamountis111111111

Thesecondamountis222222222

Thetotalofbothamountsis333333333

Linessevenandeightdisplayalongdatatypecontainingninedigitsintheirvalue.However,linesevendisplaystwounderscorestomakethevalue111_111_111morereadablethanlineeightdisplayingvalue222222222.Tothesameextent,anunderscorecanbeusedforcreditcardnumbers,socialsecuritynumbers,etc.andcanonlybeplacedbetweendigits.

Chapter2describedhowtodeclareandinitializevariables.Inaddition,thefourtypesofvariables(local,parameter,instance,andclass)andprimitivedatatypeswerediscussed.Chapter3willexplorethefourtypesofJavaoperators:Arithmetic,Bitwise,Logical,andRelational.

Chapter3Operators

Operatorsaresymbolsthatperformmathematicalorlogicalmanipulationsononeormoreoperands.Anoperandisanythingthatcanbechangedormanipulated.Themostcommontypeofoperandisavariable.InJava,therearefourtypesofoperators:Arithmetic,Bitwise,Logical,andRelational.Arithmetic,Logical,andRelationaloperatorsarethemostusedoperators.ThefollowingexampledemonstratesaMultiplication(*)Operatorandoperands(threeandfour):

publicclassOperators

{

publicstaticvoidmain(String[]args)

{

intanswer;

answer=3*4;

System.out.println(“Whatis3times4?“+answer);

}

}

Figure3.1–OperatorandOperands

ProgramOutput:Whatis3times4?12

Thischapterprovidesthefollowinginformationregardingoperators:

ArithmeticOperators

BitwiseOperators

LogicalOperators

RelationalOperators

AssignmentOperator

TernaryOperator

OperatorPrecedence

DataTypeCasting

Expressions

ArithmeticOperatorsArithmeticoperatorsimplementmathematicaloperationsonnumericalvalues.Therefore,thearithmeticoperatorscanbeappliedtoanydatatypeinvolvingnumbers.Thefollowingisalistofarithmeticoperators:

1. +(Addition)operator2. -(Subtraction)operator3. *(Multiplication)operator4. /(Division)operator5. %(Modulus)operator6. ++(Increment)operator7. —(Decrement)operator

Operator Description

+ Addsavalueonbothsidesofthe(+)operatorUsedforjoiningstringswhichisknownasstringconcatenation

- Subtractsrightoperandfromleftoperand

* Multipliesvaluesonbothsidesofthe(*)operand

/ Dividesleftoperandbyrightoperand

% Dividesleftoperandbyrightoperandthenreturnstheremainder

++ Increasestheoperand’svaluebyone

— Decreasestheoperand’svaluebyone

Figure3.2–ArithmeticOperators

Note:TheDivisionOperator(/)truncatestheremainderwhiletheModulusOperator(%)returnstheremainder.Forinstance,10/3onlyreturnsthreeandtruncatestheremainder,whichisone.Ontheotherhand,10%3onlyreturnstheremainderofone.

IncrementArithmeticOperatorTheIncrementOperatoraddsonetoanoperand.Thisoperatorhasaprefixandpostfixform.Thebelowsyntaxesshowbothincrementoperatorformswhichisthesameasthefollowingexpression:

i=i+1;

PrefixFormSyntax++i;

PostfixFormSyntaxi++;

DecrementArithmeticOperatorTheDecrementOperatorsubtractsonefromanoperand.Thisoperatorhasaprefixandpostfixform.Thebelowsyntaxesshowbothdecrementoperatorformswhichisthesameasthefollowingexpression:

i=i-1;

PrefixFormSyntax—i;

PostfixFormSyntaxi—;

Thefollowingareexamplesofeacharithmeticoperator:

publicclassOperators

{

publicstaticvoidmain(String[]args)

{

intresult,x=10,y=3;

result=x+y;//Addition

System.out.println(“Whatis10plus3?“+result);

result=x-y;//Subtraction

System.out.println(“Whatis10minus3?“+result);

result=x*y;//Multiplication

System.out.println(“Whatis10times3?“+result);

result=x/y;//Division

System.out.println(“Whatis10divided3?“+result);

result=x%y;//Modulus

System.out.println(“Whatistheremainderof10divided3?“+result);

result=++x;//PrefixIncrement

System.out.println(“Whatistheprefixincrementvalueof10?“+result);

result=x++;//PostfixIncrement

System.out.println(“Whatisthepostfixincrementvalueof10?“+result);

result=—y;//PrefixDecrement

System.out.println(“Whatistheprefixdecrementvalueof3?“+result);

result=y—;//PostfixDecrement

System.out.println(“Whatisthepostfixdecrementvalueof3?“+result);

}

}

Figure3.3–ArithmeticOperatorExamples

ProgramOutput:Whatis10plus3?13

Whatis10minus3?7

Whatis10times3?30

Whatis10divided3?3

Whatistheremainderof10divided3?1

Whatistheprefixincrementvalueof10?11

Whatisthepostfixincrementvalueof10?11

Whatistheprefixdecrementvalueof3?2

Whatisthepostfixdecrementvalueof3?2

Inthisexample,linefivedeclaresandinitializesthevariables.Variable“x”isassigned10while“y”isassignedthree.An+(Addition)operatoraddsbothvariablesinlineseven.Variable“result”isassignedthesumofvariables“x”and“y”whichresultsin13.AsimilarprocessisperformedforallexamplesinFigure3.3usingadifferentArithmeticOperatoraccordingtoFigure3.2.

BitwiseOperatorsTheBitwiseOperatorworkonoperandsutilizingbits.Thereforethisoperatorhaveafoundationthatfunctionsonabit-by-bitbasis.Valuesaremadeavailableafterthebitsareset,shifted,andtested.Primarily,theBitwiseOperatorsareusedondatatypesbyte,char,int,long,andshort.Thefollowingisalistofbitwiseoperatorsandexamples:

1. &(BitwiseAND)operator2. |(BitwiseOR)operator3. ^(BitwiseexclusiveOR(XOR))operator4. >>(Signedshiftright)operator5. >>>(Unsignedshiftright)operator6. <<(Signedshiftleft)operator7. ~(One’sCompliment)operator

Operator Description Example

& Places1bitintheresultifabitexistsinbothoperands.Canbeusedonabooleandatatype

x&y;

| Places1bitintheresultifabitexistsinoneofbothoperands.Canbeusedonabooleandatatype

x|y;

^ Places1bitintheresultifabitexistsinoneoftheoperands(notboth)

x^y:

>> Shiftstheleftoperand’svaluetotherightbythenumberofbitsspecifiedbytherightoperand

x>>2

>>> Shiftstheleftoperand’svaluetotherightbythenumberofbitsspecifiedbytherightoperandwhileshiftedvaluearefilledwithzeros(0)

x>>>2

<< Shiftstheleftoperand’svaluetotheleftbythenumberofbitsspecifiedbytherightoperand

x<<2

~ Changeseverybittotheoppositebit.Forexample,every1bitchangesto0andevery0bitchangesto1

~2

Figure3.4–BitwiseOperators

LogicalOperatorsLogicalOperators(knownasConditionalOperators)returnabooleanvaluebasedononeormoreexpressions.Therefore,theLogicalOperator’sdatatypemustbeboolean.Thefollowingisalistoflogicaloperators:

&&(LogicalAND)operator||(LogicalOR)operator^(LogicalexclusiveOR(XOR))operator!(LogicalNOT)operator

Operator Description

&& ReturnstrueifbothoperandsaretrueReturnsfalseifoneoperandorbothoperandsarefalse

|| ReturnstrueifoneoperandorbothoperandsaretrueReturnsfalseifbothoperandsarefalse

^ ReturnstrueifonlyoneoperandistrueReturnsfalseifbothoperandsarefalseandifbothoperandsaretrue

! ReturnstheoppositevalueoftheoperandReturnstrueiftheoperandisfalseandreturnfalseiftheoperandistrue

Figure3.5–LogicalOperators

Note:TheBitwiseOperatorsandLogicalOperatorsperformsomeofthesamefunctions.Thefollowingareexamplesofeachlogicaloperatorandtwobitwiseoperators:

publicclassOperators

{

publicstaticvoidmain(String[]args)

{

booleanx=100>99,y=99>100;

//LogicalAND‘&&’operator

System.out.println(“Whatistheresultof100>99&&99>100?“+(x&&y));

//BitwiseAND‘&’operator

System.out.println(“Whatistheresultof100>99&99>100?“+(x&y));

//LogicalOR‘||’operator

System.out.println(“Whatistheresultof100>99||99>100?“+(x||y));

//BitwiseOR‘|’operator

System.out.println(“Whatistheresultof100>99|99>100?“+(x|y));

//LogicalXOR‘^’operator

System.out.println(“Whatistheresultof100>99^99>100?“+(x^y));

//LogicalNOT‘!’operator

System.out.println(“WhatistheresultofNot100>99?“+(!x));

//LogicalNOT‘!’operator(parenthesisisoptionalsurroundingthisoperatorandoperand)

System.out.println(“WhatistheresultofNot99>100?“+!y);

}

}

Figure3.6–LogicalandBitwiseOperatorExamples

ProgramOutput:Whatistheresultof100>99&&99>100?false

Whatistheresultof100>99&99>100?false

Whatistheresultof100>99||99>100?true

Whatistheresultof100>99|99>100?true

Whatistheresultof100>99^99>100?true

WhatistheresultofNot100>99?false

WhatistheresultofNot99>100?True

Inthisexample,linefivedeclaresandinitializesthevariables.Bothvariables“xandy”areassignedbooleanexpressions.Variable“x”isassignedatrueexpression(100>99)while“y”isassignedafalseexpression(99>100).A&&(LogicalAND)operatorinlineeightand&(BitwiseAND)operatorinline11comparestheoperands“xandy”thenreturnsa“false”value.Falseisreturnedbecauseoneoperand“x”istruewhiletheotheroperand“y”isfalse.AsimilarprocessisperformedforallexamplesinFigure3.6usingdifferentBitwiseandLogicalOperatorsaccordingtoFigure3.4andFigure3.5.

Short-CircuitBehaviorOperatorsShort-circuitbehavioroperatorsare||(LogicalOR)and&&(LogicalAND)operators.NoticefromFigure3.6,||(LogicalOR)and&&(LogicalAND)operatorsreturnthesameresultas|(BitwiseOR)and&(BitwiseAND)operators.However,thedistinguishingcharacteristicreliesonevaluatingtheoperands.

Ifthefirstoperandreturnsfalsethenthe&&(LogicalAND)Operatorwillnotevaluatethesecondoperator.Yet,the&(BitwiseAND)Operatoralwaysevaluatebothoperands.Likewise,the||(LogicalOR)Operatorwillnotevaluatethesecondoperandifthefirstoperandreturnstrue.Contrarytothe||(LogicalOR)Operator,the|(BitwiseOR)Operatorwillalwaysevaluatebothoperands.

Note:Theshort-circuitbehavioroperatorsdonotevaluatethesecondoperatorbecauseitknowstheresultregardlessofthesecondoperand.

RelationalOperatorsRelationalOperatorsreturnabooleanvalueaftercomparingoperands.Normally,alloftheRelationalOperatorsareappliedtooperandsthatarenumbers.IftherelationshipbetweentwooperandsisYes,thenTrueisreturned.Forexample,if34isequalto34,thenTrueisreturned.ThefollowingisalistofRelationalOperators:

1. ==(EqualTo)operator2. !=(NotEqualTo)operator3. >(GreaterThan)operator4. >=(GreaterThanorEqualTo)operator5. <(LessThan)operator6. <=(LessThanorEqualTo)operator

Operator Description

== Verifiesifbothoperandsareequal.

!= Verifiesifbothoperandsarenotequal.

> Verifiesiftheleftoperandisgreaterthantherightoperand

>= Verifiesiftheleftoperandisgreaterthanorequaltotherightoperand

< Verifiesiftheleftoperandislessthantherightoperand

<= Verifiesiftheleftoperandislessthanorequaltotherightoperand

Figure3.7–RelationalOperators

Thefollowingareexamplesofeachrelationaloperator:

publicclassOperators

{

publicstaticvoidmain(String[]args)

{

intx=25,y=50;

//==EqualTooperator

System.out.println(“Is25equalto50?“+(x==y));

//!=NotEqualTooperator

System.out.println(“Is25notequalto50?“+(x!=y));

//>GreaterThanoperator

System.out.println(“Is25greaterthan50?“+(x>y));

//>=GreaterThanorEqualTooperator

System.out.println(“Is25greaterthanorequalto50?“+(x>=y));

//<LessThanoperator

System.out.println(“Is25lessthan50?“+(x<y));

//<=LessThanorEqualTooperator

System.out.println(“Is25lessthanorequalto50?“+(x<=y));

}

}

Figure3.8–RelationalOperatorExamples

ProgramOutput:Is25equalto50?false

Is25notequalto50?true

Is25greaterthan50?false

Is25greaterthanorequalto50?false

Is25lessthan50?true

Is25lessthanorequalto50?True

Inthisexample,linefivedeclaresandinitializesthevariables.Variable“x”isassigned25while“y”isassigned50.An==(EqualTo)operatordeterminesifbothvariables(x==y)equalseachotheronlineeight.Thevalues25and50arenotequalsofalseisreturned.AsimilarprocessisperformedforallexamplesinFigure3.8usingadifferentRelationalOperatoraccordingtoFigure3.7.

AssignmentOperatorAnAssignmentOperator(=)ispositionedbetweenavariableandvalue.Thepurposeistoassignvaluestovariables.Therefore,thevalueontherightsideistransferredintothevariablenamewhichisontheleftside.Thefollowingisanassignmentoperatorsyntax:

SyntaxvariableName=expression;

SyntaxDetails

Argument Description

variableName Nameofvariablethatwasdeclared

Expression Valuethatisassignedtothevariablename

; Semi-coloncompletestheinitializationstatement

Figure3.9–AssignmentOperatorSyntaxDetails

Note:TheAssignmentOperatorcangenerateachainofassignments.Anassignmentchainisagoodwaytoinitializemultiplevariablesthesamevalue.Inaddition,avalueisoverwrittenifthevariablehasanexistingvalue.ThefollowingisanAssignmentOperatorexample:

publicclassOperators

{

publicstaticvoidmain(String[]args)

{

inti,j,k;

i=j=k=34;

System.out.println(“Thevalueofiis:“+i);

System.out.println(“Thevalueofjis:“+j);

System.out.println(“Thevalueofkis:“+k);

j=38;

System.out.println(“Thevalueofjhasbeenoverwrittento:“+j);

}

}

Figure3.10–AssignmentOperatorExample

ProgramOutput:Thevalueofiis:34

Thevalueofjis:34

Thevalueofkis:34

Thevalueofjhasbeenoverwrittento:38

Linefivedeclareseachvariable“i,j,k”withanintdatatype.Linesevenutilizesachainassignmenttheninitializeeachvariablethesamevalue34withonestatement.Line12overwritevariable“j”byassigningavalueof38.

CompoundAssignmentsCompoundAssignments(knownasShorthandAssignments)joinArithmeticandBitwiseOperatorswiththeAssignmentOperator.Thefollowingoperatorsareexcludedfromthejoiningfeature:increment,decrement,andone’scompliment.Thisprocessshortenstheassignmentstatement.Forexample,thefollowingtwostatementsproducethesameoutput:

y=y+3;

y=+3;

Bothstatementsassigntovariable“y”thevalueof“y”plusthree.Thefollowingisalistofcompoundassignments:

1. +=(AddandAssignment)operator2. -=(SubtractandAssignment)operator3. *=(MultiplyandAssignment)operator4. /=(DivideandAssignment)operator5. %=(ModulusandAssignment)operator6. &=(BitwiseAndandAssignment)operator7. |=(BitwiseORandAssignment)operator8. ^=(BitwiseexclusiveOR(XOR)andAssignment)operator9. <<=(LeftshiftandAssignment)operator

10.>>=(RightshiftandAssignment)operator11.>>>=(UnsignedrightshiftandAssignment)operator

CompoundAssignment

Description

+= Assignstheadditionoutcome

-= Assignsthesubtractionoutcome

*= Assignsthemultiplicationoutcome

/= Assignsthedivisionoutcome

%= Assignsthedivisionremainderoutcome

&= AssignsthebitwiseANDoutcome

|= AssignsthebitwiseORoutcome

^= AssignsthebitwiseexclusiveOR(XOR)outcome

<<= Assignsthesignedleftbitshiftoutcome

>>= Assignsthesignedrightbitshiftoutcome

>>>= Assignstheunsignedrightbitshiftoutcome

Figure3.11–CompoundAssignments

TernaryOperatorAccordingtodictionary.com,ternarymeans,“consistingoforinvolvingthree.”Therefore,theTernaryOperator(?)requiresthreeoperands.Thisoperatorisusedtoevaluatebooleanexpressionsanddeterminewhichvalueisassignedtothevariable.Thefollowingistheternaryoperatorsyntax:

SyntaxvariableTypevariableName=expression1?expression2:expression3;

SyntaxDetails

Argument Description

variableType Datatypeofvariable

variableName Nameofvariablethatwillreceiveavalue

expression1 Booleanexpression

expression2 Valueifthebooleanexpressionistrue

: Colonseparatesthevaluesofexpression2andexpression3

expression3 Valueifthebooleanexpressionisfalse

; Semi-coloncompletestheternaryoperatorstatement

Figure3.12–TernaryOperatorSyntaxDetails

Thefollowingisaternaryoperatorexample:

publicclassOperators

{

publicstaticvoidmain(String[]args)

{

intx,y;

x=5;

System.out.println(“Whatisthevalueofx?“+x);

y=(x==5)?7:1;

System.out.println(“xequals5sothebooleanexpressionistrue:Valueis“+y);

y=(x==3)?7:1;

System.out.println(“xdoesnotequal3sothebooleanexpressionisfalse:Valueis“+y);

}

}

Figure3.13–TernaryOperatorExample

ProgramOutput:Whatisthevalueofx?5

xequals5sothebooleanexpressionistrue:Valueis7

xdoesnotequal3sothebooleanexpressionisfalse:Valueis1

Line10displaysexpression1as(x==5)whileline13displaysexpression1as(x==3).Bothlinesdisplayexpression2as7andexpression3as1.IfthebooleanexpressionsareTruethenvariable“y”isassigned7,otherwise“y”isassigned1.

OperatorPrecedenceTheoperatorprecedenceisrankingJava’soperatorsfromhightolow.Rankingsbecomeimportantwhenagivenexpressionhasmultipleoperators.Anexpressionisevaluatedfromlefttorightandtheoperatorwithahigherprecedencereceivesthefirstevaluation.Tochangetheprecedenceorder,aparenthesisshouldbeimplementedtopointoutwhichexpressionisevaluatedfirst.Thefollowingexampleshowstwoexpressionswhichexcludeandincludeaparenthesis:

publicclassOperators

{

publicstaticvoidmain(String[]args)

{

inttotal;

total=2+3*4;

System.out.println(“Whatisthetotalwithoutaparenthesis?“+total);

total=(2+3)*4;

System.out.println(“Whatisthetotalwithaparenthesis?“+total);

}

}

Figure3.14–OperatorPrecedenceExample

ProgramOutput:Whatisthetotalwithoutaparenthesis?14

Whatisthetotalwithaparenthesis?20

Typically,aMultiplication(*)OperatorisevaluatedbeforeanAddition(+)Operator.The

variable“total”isassignedthesamevaluesinlinesevenandline10.However,thestatementinline7donotcontainparenthesiswhileline10containparenthesis.Inline7,theMultiplication(*)Operatorisevaluatedfirstforvalues3*4thenvalue2isaddedviaAddition(+)Operator.Therefore,thevalue14(3*4=12and12+2=14)isassignedtovariable“total”inline7.Inline10,theparenthesisrankshigherthantheMultiplication(*)Operator.Asaresult,values2+3isevaluatedfirstwithintheparenthesisthentheMultiplication(*)Operatorisevaluated.Hence,thevalue20(2+3=5and5*4=20)isassignedtovariable“total”inline10.AccordingtoTheJavaTMTutorials,thefollowingisanoperatorprecedencelist:

Operator Precedence

Postfix expr++expr—

Unary ++expr—expr+expr-expr~!

multiplicative */%

additive +-

shift <<>>>>>

relational <><=>=instanceof

equality ==!=

bitwiseAND &

bitwiseexclusiveOR ^

bitwiseinclusiveOR |

logicalAND &&

logicalOR ||

ternary ?:

assignment =+=-=*=/=%=&=^=|=<<=>>=>>>=

Figure3.15–OperatorPrecedence

DataTypeCastingDatatypecastingiswhenthevalueofadatatypeisconvertedintoadifferentdatatype.Forinstance,thevalueofonenumericdatatype“float”canbeconvertedtoanothernumericdatatype“double.”However,thevalueofabooleandatatypecanneverbeconvertedtoanumerictype.Therearetwotypesofcasts/conversions:

1. ImplicitCasting2. ExplicitCasting

Note:Theprimitivedatatypehierarchyfromhightolowisdouble,float,long,int,short,thenbyte.

ImplicitCastingImplicitcastingiswhenaconversiontakesplacewithoutaninstructiontothecompilertoconvertonedatatypeintoanotherdatatype.Thistypeofcastingonlyhappensforawideningconversion.Wideningconversionsoccurautomaticallywhenthevalueofaspecificdatatypeisconvertedtoahigherdatatype.Therefore,basedontheprimitivedatatypehierarchy,anintcanbeconvertedtoafloat,butanerrorariseswhentryingtoconvertafloattoanint.Thefollowingisanimplicitcastingexample:

publicclassOperators

{

publicstaticvoidmain(String[]args)

{

inti;

floatf;

i=78;

System.out.println(“Thevalueofint‘i’is:“+i);

f=i;

System.out.println(“Thevalueoffloat‘f’is:“+f);

}

}

Figure3.16-AssignmentTypeConversionExample

ProgramOutput:Thevalueofint‘i’is:78

Thevalueoffloat‘f’is:78.0

Linefivedeclaresvariable“i”withanintdatatypewhilelinesixdeclaresvariable“f”asafloatdatatype.Initially,lineeightassignsavalueof78tovariable“i”.However,aconversionhappensonline11whichconvertsthedatatypefrominttofloat.Thevalue“78.0”remainsthesamebutdisplaysdifferentlyasafloatdatatype.Noticethevaluedidnotlosedatawhenconvertingfrom78to78.0.Thefollowingtwoprinciplesarenecessaryforanimplicitcasting:

1. Bothdatatypesmustbecompatible2. Destinationdatatype(leftside)musthaveahigherrangethanthesourcedatatype

(rightside)

Thefollowingisalistofwideningconversionsaccordingtotheprimitivedatatypehierarchy:

byteconvertstoshort,int,long,float,ordoubleshortconvertsint,long,float,ordoublecharconvertstoint,long,float,ordoubleintconvertstolong,float,ordoublelongconvertsfloatordoublefloatconvertstodouble

ExplicitCastingExplicitcastingiswhenaconversiontakesplacewithaninstructiontothecompilertoconvertonedatatypeintoanotherdatatype.Thistypeofcastingcanhappenforawideningandnarrowingconversion.Narrowingconversionoccurswhenthevalueofaspecificdatatypeisconvertedtoalowerdatatype.Consequently,anerrorwillnotbegeneratedwhenconvertingafloattoanint.Thefollowingisanexplicitcastingsyntax:

Syntax(targetDataType)expression;

SyntaxDetails

Argument Description

targetDataType Desireddatatypetoconverttheexpression

expression Valuethatwillbeconverted

; Semi-coloncompletestheexplicitcastingstatement

Figure3.17–ExplicitCastingSyntaxDetails

Thefollowingisanexplicitcastingexample:

publicclassOperators

{

publicstaticvoidmain(String[]args)

{

inti=8;

doubled=(double)i;

System.out.println(“Whatisthevalueofint‘i’?“+i);

System.out.println(“Whatisthevalueofdouble‘d’?“+d);

floatf=12.34f;

shorts=(short)f;

System.out.println(“Whatisthevalueoffloat‘f’?“+f);

System.out.println(“Whatisthevalueofshort‘s’?“+s);

}

}

Figure3.18–ExplicitCastingExample

ProgramOutput:Whatisthevalueofint‘i’?8

Whatisthevalueofdouble‘d’?8.0

Whatisthevalueoffloat‘f’?12.34

Whatisthevalueofshort‘s’?12

Linefiveassigns“8”todatatypeint,whichisnamed“i.”Anexplicitwideningconversionensuesatlinesixwhenvariable“i”—anintdatatype—convertstoadoubledatatype.Line11assigns12.34(adefaultdatatypeofdouble),butconvertsittoafloatdatatype12.34f.Variable“f”holdsa12.34value,thenconvertstoashortdatatypeinline12.Noticethatthevaluelosesdataonline15,whenthenarrowingconversiontakesplaceandconvertsafloatvalue“12.34”toashortvalueof“12.”Thefollowingisalistofnarrowingconversionsaccordingtotheprimitivedatatypehierarchy:

byteconvertstocharshortconvertstobyteorcharcharconvertsbyteorshortintconvertstobyte,short,orcharlongconvertstobyte,short,char,orintfloatconvertstobyte,short,char,int,orlongdoubleconvertsbyte,short,char,int,long,orfloat

ExpressionsOperators,variables,constants,andmethods(callsandreturns)arecomponentsofanexpression.Acomponentjoinedwithanoperatorformsanexpression.Itispossibletocreateacompoundexpressionbycombiningmultipleexpressions.However,thedatatypesmustbecompatibletoconstructavalidcompoundexpression.Forexample,anintdatatypecanbemixedwithalongdatatypebecausebotharenumeric.

Throughtheuseoftypepromotionrules,themixtureofdatatypesisconvertedtothesamedatatype.Valuesthatarereturnedfromanexpressiondependonthedatatype.Datatypeschar,byte,andshortareadvancedtoint.Anexpressionispromotedtolongifoneoftheoperandsisalongdatatype.Thesamegoesforfloatdatatypes,ifoneoftheoperandsisafloatthenthewholeexpressionisafloat.Likewise,anexpressionispromotedtoadoubledatatypeifoneoftheoperandsisadouble.Thefollowingisanexpressionexamplewithmixdatatypesbyteandfloat:

publicclassOperators

{

publicstaticvoidmain(String[]args)

{

byteb=7;

floatf=34.56f;

floattotal=(b*f);

System.out.println(“Thetotalofbyte‘b’timesfloat‘f’(7*34.56)is:“+total);

}

}

Figure3.19–ExpressionExample

ProgramOutput:Thetotalofbyte‘b’timesfloat‘f’(7*34.56)is:241.92001

Linefivedeclaresandassignsabytedatatypewhilelinesevendeclaresandassignsafloatdatatype.Onlineeight,the*(Multiplication)operatormultipliesbothdatatypes(byteandfloat)eventhoughthetypesaremixed.However,theexpressionispromotedasafloatsinceoneoftheoperandsisafloat.

Chapter3gaveanaccountforthefourtypesofJavaoperators:Arithmetic,Bitwise,Logical,andRelational.TheAssignmentOperatorandTernaryOperatorwereexaminedalongwithrankingsofeachoperator.Chapter4willexplainthetwotypesofcontrolstructures:branchesandloops.Therearetwotypesofbranches:theifbranchandtheswitchbranch.Therearethreetypesofloops:forloop,whileloop,anddowhileloop.

Chapter4ControlStructures

Controlstructuresaretheprocessofusinglogictoforcetheprogramtoskipstatementswhileloopingotherstatements.Forcingtheprogramtoskipstatementsisknownasbranchingandloopingspecificstatementsiscarriedoutvialoops.

Thetwotypesofbranchesareifbranchandswitchbranch.Thethreetypesofloopsareforloop,whileloop,anddowhileloop.Inadditiontothebranchesandloopsarejumpstatements.Jumpstatementsallowexecutiontobypassunnecessarycomponentsoftheprogram.Thejumpstatementsutilizekeywordsbreakandcontinue.Bothkeywordscanbeincludedwithinallbranchesandloops.

Chapterfourwillcoverthefollowingregardingcontrolstructures:

IfBranch

SwitchBranch

ForLoop

WhileLoop

DoWhileLoop

BreakToExit

ContinueToNextStatement

IfBranchTheifbranchexecutesastatementwhenaconditionistrue.Inotherwords,aspecificstatementisexecutedifaconditionismet.Anifbranchisagreatlyutilizedandindispensablecontrolstructure.Thefollowingisthesyntaxfortheifbranch:

Syntaxif(condition){statement(s);}

SyntaxDetails

Argument Description

if Keywordthatstartstheifbranch

condition Booleanexpressionwhichresultsinatrueorfalseresult

{ Anopeningcurlybracket

statement(s) Statementthatwillbeexecutediftheconditionistrue

; Semi-coloncompletesthetruestatement

} Aclosingcurlybracket

Figure4.1–IfBranchSyntaxDetails

Thefollowingexampledisplaysamessageifthecustomerbringsthreeextracustomerstoasportingevent:

publicclassControlStructures

{

publicstaticvoidmain(String[]args)

{

intextraCustomers=4;

if(extraCustomers>=3)

{

System.out.println(“Customerreceivesadiscount”);

}

}

}

Figure4.2–IfBranch

ProgramOutput:Customerreceivesadiscount

Linefiveassigns“4”tothevariable“extraCustomers”.Linesevendisplayskeyword“if”followedbyaparenthesis.Insidetheparenthesisisacondition(extraCustomers>=3)thatreturnstrue.Trueisreturnedbecausefourisgreaterthanthree.Thestatementatlinenine(insidethecurlybrackets)isexecutedafterthetrueevaluation.

Note:Theprogramwouldnotexecutethestatementiftheconditionreturnedfalse.However,therearetwovariationsoftheifbranchthatcanbeexecutedwhenaconditionisfalse:

1. IfElse2. IfElse-If

IfElseBranchAnoptionalelsekeywordextendstheifbranchjustincasetheconditionreturnsfalse.Therefore,thestatementsfollowingkeyword“if”andtheconditionisexecutedwhenaconditionistrue.Otherwise,thestatementfollowingkeywordelse,isexecutedwhenaconditionisfalse.Thefollowingisthesyntaxfortheif-elsebranch:

Syntaxif(condition){statement(s);}else{statement(s);}

Thefollowingexampledisplaysamessagewhenthecustomerdoesnotbringthreeextracustomerstoasportingevent:

publicclassControlStructures

{

publicstaticvoidmain(String[]args)

{

intextraCustomers=2;

if(extraCustomers>=3)

{

System.out.println(“Customerreceivesadiscount”);

}

else

{

System.out.println(“Customerdoesnotreceiveadiscount”);

}

}

}

Figure4.3–IfElseBranch

ProgramOutput:Customerdoesnotreceiveadiscount

Linefiveassigns“2”tothevariable“extraCustomers”.Linesevendisplayskeyword“if”followedbyaparenthesis.Insidetheparenthesisisacondition(extraCustomers>=3)thatreturnsfalse.Falseisreturnedbecausetwoisnotgreaterthanorequaltothree.Therefore,theprogrambypassesthestatementatlinenineandexecutesthestatementatline13.

Note:Curlybracketsareoptionalifthereisasinglestatementfollowingkeywords“if”and“else”.However,thecurlybracketsarerequiredifmultiplestatementsexist.Itisrecommendedtoalwaysusecurlybracketstoimprovereadability.Thefollowingisanexamplethatdoesnotusecurlybrackets:

publicclassControlStructures

{

publicstaticvoidmain(String[]args)

{

intextraCustomers=2;

if(extraCustomers>=3)

System.out.println(“Customerreceivesadiscount”);

System.out.println(“Congratulations”);

else

System.out.println(“Customerdoesnotreceiveadiscount”);

}

}

Figure4.4–NoCurlyBrackets

Lineeightandninearemultiplestatementsfortheifbranchandrequirethecurlybrackets.NoticetheredXatline10.TheredXindicatesanerrorforthepreviousstatements.However,anerrordoesnotexistforline11becauseitisasinglestatementanddoesnotrequirethecurlybrackets.

IfElse-ifBranchThefirstifkeywordcanoptionallybefollowedbyoneormoreifkeywords.However,eachsubsequentifkeywordmustbeprecededbyarequiredelsekeyword.Theelse-ifbranchisonlyexecutedwhenthefirstifbranchisfalse.Allelse-ifbranchesarefollowedbyaconditionandoneormorestatements.Thefollowingisthesyntaxfortheelseifbranch:

Syntaxif(condition){statement(s);}elseif(condition){statement(s);}elseif(condition){statement(s);}else{statement(s);}

Thefollowingexampledisplaysamessagewhenthecustomerbringslessthanthreeextracustomerstoasportingevent:

publicclassControlStructures

{

publicstaticvoidmain(String[]args)

{

intextraCustomers=2;

if(extraCustomers>=3)

{

System.out.println(“Customerreceivesadiscount”);

}

elseif(extraCustomers<=3)

{

System.out.println(“NoDiscount:Customercountlessthanorequalto3”);

}

else

{

System.out.println(“Error:Notavalidcustomercount”);

}

}

}

Figure4.5–ElseIfBranch

ProgramOutput:NoDiscount:Customercountlessthanorequalto3

Linefiveassigns“2”tothevariable“extraCustomers”.Line11displaykeywords“else”and“if”followedbyaparenthesis.Insidetheparenthesisisacondition(extraCustomers<=3)thatreturnstrue.Trueisreturnedbecausetwoislessthanorequaltothree.Thesecondcondition(line11)isonlyexecutedafterthefirstcondition(lineseven)isfalse.

Note:Severalelse-ifbranchescanbeaddedtotheifbranch:

NestedIfBranchThenestedifbranchconsistsofaniforelse-ifbranchinsideanif,else,orelse-ifbranch.Aparticularouterifbranchservesasanestfortheinnerbranch.Thefollowingisanestedifbranchexample:

publicclassControlStructures

{

publicstaticvoidmain(String[]args)

{

intextraCustomers=15;

if(extraCustomers>=3)

{

System.out.println(“Customerreceivesadiscount”);

if(extraCustomers>=10)

{

System.out.println(“25%offtheprice”);

}

else

{

System.out.println(“10%offtheprice”);

}

}

else

{

System.out.println(“Customerdoesnotreceiveadiscount”);

}

}

}

Figure4.6–NestedIfBranch

ProgramOutput:Customerreceivesadiscount

25%offtheprice

Thenestedifbranchstartsatline11andendsatline18.Acondition(extraCustomers>=10)determinesifthecustomerreceives10or25percentoff.Inthiscase,thevariable“extraCustomers”isassigned15atlinefive.Therefore,theconditionatline11evaluatestotrueandexecutesthefirststatement“25%offtheprice.”Thesecondstatementwouldexecuteifthevariable“extraCustomers”islessthan10.

SwitchBranchTheswitchbranchevaluatesasinglevariablethenexecutesastatementaccordingtothevariable’svalue.Primitivedatatypesbyte,short,char,andintcanbeevaluatedalongwithString.Theswitchandifbranchesaresimilarinfunctionality.Therearesituationswhereeitherbranchissuitable.However,theswitchbranchismostefficientwhendealingwithaspecificnumberofvalues,suchasdaysoftheweek.Otherwise,itisbesttoimplementanifbranchwhenhandlinganinfinitenumberofvalues.Thefollowingisthesyntaxfortheswitchbranch:

Syntaxswitch(variableName){caseconstant1:statement(s);break;caseconstant2:statement(s);break;caseconstant3:statement(s);break;...default:statement;}

SyntaxDetails

Argument Description

switch Checksthevariable’svalue

variableName Nameofthevariable

{ Anopeningcurlybracket

caseconstant1,2,3… Containsapossiblematchforthevariable’svalue

statement(s) Statementtobeexecutedifthevariable’svaluematchagivencase

; Semi-coloncompletesastatement

break Anoptionalkeywordthatexitsoutoftheswitchbranch

; Semi-coloncompletesthebreak

default Anoptionalkeywordthatwillexecuteifthevariable’svaluedoesnotmatchacase

statement Defaultstatementtobeexecutedifthevariable’svaluedoesnotmatchacase

} Aclosingcurlybracket

Figure4.7–SwitchBranchSyntaxDetails

Thefollowingisaswitchbranchexample:

publicclassControlStructures

{

publicstaticvoidmain(String[]args)

{

intday=6;

switch(day)

{

case1:

System.out.println(“Sundayisthe1stdayoftheweek”);

break;

case2:

System.out.println(“Mondayisthe2nddayoftheweek”);

break;

case3:

System.out.println(“Tuesdayisthe3rddayoftheweek”);

break;

case4:

System.out.println(“Wednesdayisthe4thdayoftheweek”);

break;

case5:

System.out.println(“Thursdayisthe5thdayoftheweek”);

break;

case6:

System.out.println(“Fridayisthe6thdayoftheweek”);

break;

case7:

System.out.println(“Saturdayisthe7thdayoftheweek”);

break;

default:

System.out.println(“Notvalid:Thereareonly7daysinaweek”);

}

}

}

Figure4.8–SwitchBranchExample

ProgramOutput:Fridayisthe6thdayoftheweek

Linefiveassignsthevariable“day”thevalueof“6.”Thenthekeyword“switch”startsthebranchatlinesevenbycheckingthevariable’svalue.Keyword“case”atline24matches

thevariable’svalue“6”,thenexecutesthestatementatline25.Thekeyword“break”atline26isnecessarytopreventcase7(line27)anddefault(line30)fromexecuting.

Note:Allstatementsfollowingamatchwillexecuteduetoswitchbranchesexecutingsequentiallyutilizingatop-downapproach.Therefore,thekeyword“break”mustbeusedtojumpoutoftheswitchbranchafteramatchisfound.

NestedSwitchBranchThenestedswitchbranchconsistsofaswitchbranchinsideanotherswitchbranch.Inaddition,anifbranchcanbenestedinsideofaswitchbranch.Theouterswitchbranchservesasanestfortheinnerbranch.Valuesareuniquetotheirrespectiveouterandinnerbranch.Forinstance,aconstantcancontainthesamevalueinmultipleswitchbranches.Thefollowingisaswitchbranchexample:

publicclassControlStructures

{

publicstaticvoidmain(String[]args)

{

intday=2,numHours=4;

switch(day)

{

case1:

System.out.println(“Sundayisthe1stdayoftheweek”);

break;

case2:

System.out.println(“Mondayisthe2nddayoftheweek”);

switch(numHours)

{

case4:

System.out.println(“Plantowork4hours(halfaday)duetoanappointment”);

break;

case8:

System.out.println(“Plantowork8hourstoday”);

break;

default:

System.out.println(“NotsurehowmanyhoursIwillworktoday”);

break;

}

break;

case3:

System.out.println(“Tuesdayisthe3rddayoftheweek”);

break;

case4:

System.out.println(“Wednesdayisthe4thdayoftheweek”);

break;

case5:

System.out.println(“Thursdayisthe5thdayoftheweek”);

break;

case6:

System.out.println(“Fridayisthe6thdayoftheweek”);

break;

case7:

System.out.println(“Saturdayisthe7thdayoftheweek”);

break;

default:

System.out.println(“Notvalid:Thereareonly7daysinaweek”);

}

}

}

Figure4.9–NestedSwitchBranch

ProgramOutput:Mondayisthe2nddayoftheweek

Plantowork4hours(halfaday)duetoanappointment

Linefiveassignsthevariable“numHours”thevalueof“4.”Thenthekeyword“switch”startsthenestedswitchbranchatline14bycheckingthevariable’svalue.Thenestedswitchbranchencompassestwocasesandonedefault.Oneofthecasesatline16holdthesameconstant,“4”,asanoutercaseatline30.

ForLoopTheforloopexecutesablockofcodeforacertainnumberofiterations.Inotherwords,astatementisexecutedaslongasaconditionismet.Oneoftheforloopbenefitsistoallowstatementstobeexecutedwithoutwritingcoderepeatedly.Thefollowingistheforloopsyntax:

Syntaxfor(initialization;condition;iteration){statement(s)}

SyntaxDetails

Argument Description

for Keywordthatstartstheforloop

initialization Assignmentthatsetstheloopcontrolinitialvalue

; Semi-coloncompletestheinitialization

condition Abooleanexpressionthatdeterminesiftheloopwillorwillnotrepeat

; Semi-coloncompletesthecondition

iteration Indicateshowtheloopcontrolvariablewillchangeaftereachvariation

{ Anopeningcurlybracket

statement(s) Statement(s)thatwillexecuteaftertheconditionismet

; Semi-coloncompletesthestatement

} Aclosingcurlybracket

Figure4.10–ForLoopSyntaxDetails

Theinitializationcomponentdeclaresadatatypeandassignsaninitialvaluevialoopcontrolvariable.Usually,theloopcontrolvariableisasinglecharactervariablename

(e.g.,i)thatcontrolstheentireloop.Theconditionisabooleanexpressionthatspecifiesamaximumvaluefortheloopcontrolvariable.Allforloopscontinueexecutingwhiletheconditionistrue.Executionbeginsonthestatementimmediatelyfollowingtheforloopwhentheconditionbecomesfalse.Mostautomationengineersuseanincrement(++)ordecrement(—)operatorastheiterationexpression.Theincrementoperatorincreasestheloopcontrolvariablebyone,whilethedecrementoperatordecreasesthevaluebyone.Anexecutablestatementisplacedbetweentheoptionalcurlybrackets.Although,thecurlybracketsareoptional,itisrecommendedtousethebracketstoimprovereadability.Thefollowingisaforloopexample:

publicclassControlStructures

{

publicstaticvoidmain(String[]args)

{

for(inti=0;i<5;i++)

{

System.out.println(“Theloopcontrolvariablevalueis“+i);

}

}

}

Figure4.11–ForLoopExample

ProgramOutput:Theloopcontrolvariablevalueis0

Theloopcontrolvariablevalueis1

Theloopcontrolvariablevalueis2

Theloopcontrolvariablevalueis3

Theloopcontrolvariablevalueis4

Linefivestartstheforloopwithkeyword“for”followedbyargumentsinitialization,condition,anditeration.Initialization(inti=0;)assignszeroasthestartingvalue.

Condition(i<5)setsfiveasthestoppingpointfortheloopcontrolvariable.Increment(i++)increasestheloopcontrolvariablebyone.Thestatementprintstheloopcontrolvariablevialineseven.

Itisimportanttouseharmoniousvaluesintheforloop.Thevaluescanleadtoaninfiniteloopiftheyarenotcreatedinagreement.Aninfiniteloopisaloopthatneverstops.Forexample,thefollowingforloopwillrepeatindefinitelybecauseoftheinitialvalue,maximumvalue,anditerationexpression:

for(inti=3;i>1;i++)

Theinitialvalue“3”startsatagreatervaluethanthemaximumvalueof“1,”whiletheiterator“++”increasesaftereachloop.Tocorrectthisinfiniteloop,theinitializationvalue“3”mustdecreasetolessthantheconditionalvalue“1”;theconditionalvalue“1”mustincreasetomorethantheinitialization“3”;ortheiteratormustchangefromincreasing“++”todecreasing“—”aftereachloop.

Note:Routinely,aconditionusingagreaterthanoperator(>)implementsadecrementoperator(—),whileaconditionusingalessthanoperator(<)implementsanincrementoperator(++).

NestedForLoopThenestedforloopconsistofaforloopinsideanotherforloop.Anouterforloopservesasanestfortheinnerloop.Statementswithintheinnerloopcanutilizetheloopcontrolvariablesfromtheouterloop.Asaresult,itisbesttousedifferentloopcontrolvariablesforeachloop.Thefollowingisanestedforloopexample:

publicclassControlStructures

{

publicstaticvoidmain(String[]args)

{

for(intx=0;x<3;x++)

{

System.out.println(“OuterLoopvalueis“+x);

for(inty=0;y<3;y++)

{

System.out.println(“InnerLoopvalueis“+y);

}

}

}

}

Figure4.12–NestedForLoop

ProgramOutput:OuterLoopvalueis0

InnerLoopvalueis0

InnerLoopvalueis1

InnerLoopvalueis2

OuterLoopvalueis1

InnerLoopvalueis0

InnerLoopvalueis1

InnerLoopvalueis2

OuterLoopvalueis2

InnerLoopvalueis0

InnerLoopvalueis1

InnerLoopvalueis2

Lineeightstartsthenestedforloopwithkeyword“for”followedbyargumentsinitialization,condition,anditeration.Initialization(inty=0;)assignszeroasthestartingvalue.Condition(y<3)setsthreeasthestoppingpointfortheloopcontrolvariable.Increment(y++)increasestheloopcontrolvariablebyone.Thestatementprintstheloopcontrolvariablevialine10.

WhileLoopThewhilelooprepeatsastatementwhileaconditionistrue.Conditionsarebooleanexpressionsthatischeckedpriortoexecutingthestatement.Inaddition,thevariablenameisinitializedbeforetheloopandevaluatedaspartofthecondition.Whenexecutingthestatement,thewhileloopcontinuesuntiltheconditionbecomesfalse.Thefollowingisthesyntaxofawhileloop.

Syntaxwhile(condition){statement(s);}

SyntaxDetails

Argument Description

while Keywordthatstartstheloop

condition Abooleanexpressionthatdeterminesiftheloopwillorwillnotrepeat

{ Anopeningcurlybracket

statement(s) Statement(s)thatwillexecuteaftertheconditionismet

; Semi-colonthatcompletesthestatement

} Aclosingcurlybracket

Figure4.13–WhileLoopSyntaxDetails

Thefollowingisawhileloopexample:

publicclassControlStructures

{

publicstaticvoidmain(String[]args)

{

inti=0;

while(i<5)

{

System.out.println(“Thevariablesvalueis“+i);

i++;

}

}

}

Figure4.14–WhileLoopExample

ProgramOutput:Thevariablesvalueis0

Thevariablesvalueis1

Thevariablesvalueis2

Thevariablesvalueis3

Thevariablesvalueis4

Linefiveinitializesthevariable“i”tozero“0”.Thevariablewillbeevaluatedatlinesevenaspartofthecondition(i<5)afterkeyword“while”.Avalueforthevariable“i”isrepeatedlyprintedvialineninewhiletheconditionistrue.Noticetheincrementoperatoratline10.Itisimportanttoknowthatthewhileloopneverstopsiftheincrementoperatorisnotadded.Therefore,theloopwouldcontinueindefinitely,generatinganinfiniteloop.Inaddition,thewhileloopbecomesindefiniteiftheinitializationandconditionalvariablevaluesarenotsetinagreement.

DoWhileLoopThedowhileloopevaluatesaconditionatthebottomoftheloop.Therefore,theloopwillexecutethestatementwithintheloopthenevaluatethecondition.Asaresult,thedowhileloopalwaysexecutesastatementforatleastoneiterationandcontinuesaslongastheconditionistrue.Thefollowingisthesyntaxforadowhileloop:

Syntaxdo{statement(s);}while(condition);

SyntaxDetails

Argument Description

do Keywordthatstartstheloop

{ Anopeningcurlybracket

statement(s) Statement(s)thatwillexecuteatleastonce

; Semi-colonthatcompletesthestatement

} Aclosingcurlybracket

while Keywordthatdeterminesiftheloop’sconditionwillrepeat

condition Abooleanexpressionthatdeterminesiftheloopwillorwillnotrepeat

; Semi-colonthatcompletesthecondition

Figure4.15–DoWhileLoopSyntaxDetails

Thefollowingisadowhileloopexample:

publicclassControlStructures

{

publicstaticvoidmain(String[]args)

{

inti=0;

do

{

System.out.println(“Thevariablesvalueis“+i);

i++;

}

while(i>5);

}

}

Figure4.16–DoWhileLoopExample

ProgramOutput:Thevariablesvalueis0

Thevariablesvalueis1

Thevariablesvalueis2

Thevariablesvalueis3

Thevariablesvalueis4

Linefiveinitializesthevariable“i”tozero“0”.Thekeyword“do”startsthedowhileloopfollowedbytwostatementssurroundedbycurlybrackets.Avalueforthevariable“i”isrepeatedlyprintedvialineninewhilethecondition(i<5)istrue.Coincidentally,theconditionisevaluatedafterthestatementatline12.Likethewhileloop,aninfiniteloopwouldhaveoccurrediftheincrementoperator(++)wasnotaddedatline10.Also,theinitializationandconditionalvaluescancreateaninfiniteloopifnotsetcorrectly.Inthisexample,thestatementswererepeatedmultipleiterationsbecausetheconditionstartedwithatrueresult.Thefollowingshowswhathappenswhentheconditionstartswithafalseresult:

publicclassControlStructures

{

publicstaticvoidmain(String[]args)

{

inti=0;

do

{

System.out.println(“Thevariablesvalueis“+i);

i++;

}

while(i>5);

}

}

Figure4.17–DoWhileLoopExample(StartWithFalseCondition)

ProgramOutput:Thevariablesvalueis0

Linefiveinitializesthevariable“i”tozero“0”.Therefore,thecondition(i>5)atline12isfalseduetozerobeinglessthanfive.Thedowhileloopexecutedthestatementbecausestatementsareexecutedfirst,thentheconditionisevaluated.

Note:Theloops(for,while,anddowhile)aresimilarinfunctionality.Aruleofthumbtousewhendecidingwhichlooptoimplementis:

ImplementaforloopwhenexecutingaspecificnumberofiterationsImplementawhileloopwhentheloopwillrepeatanuncertainnumberofiterationsImplementadowhileloopwhenaloopneedstobeexecutedatleastoneiteration

BreakToExitThe“break”keywordisoptionalandusedtoforceanexitfromabranchorloop.Ifabreakoccurswithinanestedbranchorloopthentheinnermostbranchorloopdiscontinues.However,executionresumesatthestatementimmediatelyfollowingthecurrentbranchorloop.ThefollowingisabreakkeywordexampleusingstatementsfromFigure4.8(SwitchBranch).

publicclassControlStructures

{

publicstaticvoidmain(String[]args)

{

intday=6;

switch(day)

{

case1:

System.out.println(“Sundayisthe1stdayoftheweek”);

break;

case2:

System.out.println(“Mondayisthe2nddayoftheweek”);

break;

case3:

System.out.println(“Tuesdayisthe3rddayoftheweek”);

break;

case4:

System.out.println(“Wednesdayisthe4thdayoftheweek”);

break;

case5:

System.out.println(“Thursdayisthe5thdayoftheweek”);

break;

case6:

System.out.println(“Fridayisthe6thdayoftheweek”);

break;

case7:

System.out.println(“Saturdayisthe7thdayoftheweek”);

break;

default:

System.out.println(“Notvalid:Thereareonly7daysinaweek”);

}

}

}

Figure4.18–BreakKeywordExample

Inthisexample,the“break”keywordisusedtoexitacaseifamatchislocated.Amatchhappensforcasesixatline24.Thebreakkeywordpreventscaseseven(line27)andthedefault(line30)fromexecuting.

Note:Morethanonebreakkeywordcanappearinabranchorloop.Thereisabreakkeywordaftereverycase.

ContinueToNextStatementThe“continue”keywordforcesthecurrentloopiterationtostopandimmediatelyexecutethenextloopiteration.Asaresult,theconditionandstatementbetweenbothintervalsareskipped.Thefollowingisanexampleusingthe“continue”keywordtoskipalloddnumbers:

publicclassControlStructures

{

publicstaticvoidmain(String[]args)

{

for(intx=2;x<=10;x++)

{

if(x%2!=0)continue;

System.out.println(“Evennumbers“+x);

}

}

}

Figure4.19–ContinueKeyword

ProgramOutput:Evennumbers2

Evennumbers4

Evennumbers6

Evennumbers8

Evennumbers10

Linesevenimplementsthe“continue”keywordtobypassalloddnumbers.Therefore,theconditionandstatementsareskippedwhentheloopcontrolvariable“i”equalsone,three,

five,seven,andnine.

ConclusionThepurposeof“Part1–Java4SeleniumWebDriver”wastoprovideagoodfoundationalknowledgeofJava.AnunderstandingofJavafacilitatestheprocessoftestinganApplicationUnderTesting(AUT)viaSelenium.ThekeytoverifyingdatawithinanAUT,isknowinghowtoaccessandmanipulatedata.Dataisrepresentedbyvariables,whichcanbetextornumbers.Allvariablesmusthaveadatatypetoindicatetherangeandbehavior.Thedatatypeissignificantwhendealingwithoperatorsbecausecertainfunctionsareperformedaccordingtothedatatype.Inaddition,someoftheoperatorsarecontributorstoformingcontrolstructures.Thefollowingitemsaretake–awaytopicsfromthebook:

Variables:Alocationthatholdsdata

DataTypes:Refertoavariable’stype

Operators:Asymbolthatperformsmathematicalorlogicaloperations

ControlStructures:Referstotheprocessofusinglogictoforcetheprogramtoskiporloopstatements

ThesecondJavabookistitled“Part2–Java4SeleniumWebDriver.”ItexaminesClasses,Objects,Methods,Inheritance,Packages,Interfaces,ExceptionHandling,andhowtouseInput/Output.Thereleasedatefor“Part2–Java4SeleniumWebDriver”isApril2016.

Resources1.BeginningJava®ProgrammingTheObject-OrientedApproachBartBaesens,AiméeBackiel,SeppevandenBroucke

2.JavaABeginner’sGuideSixthEditionCreate,Compile,andRunJavaProgramsTodayHerbertSchildt

3.Webopediahttp://www.webopedia.com/TERM/A/ASCII.html4.Dictionary.Reference.comhttp://dictionary.reference.com/browse/ternary?s=t

5.ORACLEJavaDocumentationTheJavaTMTutorialshttps://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html

BooksbyRexJonesII1. FreeBook(Part1)AbsoluteBeginner

YouMustLearnVBScriptforQTP/UFTDon’tIgnoreTheLanguageForFunctionalAutomationTesting

2. (Part2)YouMustLearnVBScriptforQTP/UFTDon’tIgnoreTheLanguageForFunctionalAutomationTesting

3. FreeBook(Part1)AbsoluteBeginnerJava4SeleniumWebDriverComeLearnHowToProgramForAutomationTesting

ComingSoon

4. (Part2)Java4SeleniumWebDriverComeLearnHowToProgramForAutomationTesting

5. TestDesignTechniquesAnImportantSkillSetforQA/SoftwareTesters

Note:ThefreebooksareavailableviaeBookEdition.

SignUpToReceive1. 3TipsToMasterSeleniumWithin30Days

http://tinyurl.com/3-Tips-For-Selenium

2. 3TipsToMasterQTP/UFTWithin30Dayshttp://tinyurl.com/3-Tips-For-QTP-UFT

3. FreeWebinars,Videos,andLiveTrainingshttp://tinyurl.com/Free-QTP-UFT-Selenium

Recommended