free webinars, videos, and live trainingtisten.ir/.../12/java-4-selenium-webdriverpart-2.pdf ·...

177

Upload: others

Post on 29-May-2020

3 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming
Page 2: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming
Page 3: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

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

Page 4: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

RexJones’ContactInformationEmailAddress:[email protected]:https://www.linkedin.com/in/rexjones34Books:http://tinyurl.com/Rex-Allen-Jones-BooksTwitter:@RexJonesIISkype:rex.jones34

Page 5: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

TableofContentsFREEWEBINARS,VIDEOS,ANDLIVETRAINING

REXJONES’CONTACTINFORMATION

TABLEOFCONTENTS

PREFACE

ABOUTTHEAUTHOR

COPYRIGHT,LEGALNOTICE,ANDDISCLAIMER

ACKNOWLEDGEMENTS

CHAPTER1INTRODUCTIONTOOBJECT-ORIENTEDPROGRAMMING

CLASSES,OBJECTS,ANDMETHODS

ARRAYSANDSTRINGS

INHERITANCE

PACKAGES

INTERFACES

ERRORS,EXCEPTIONS,ANDDEBUGGING

UTILIZINGINPUTANDOUTPUT

CHAPTER2CLASSES,OBJECTS,ANDMETHODS

CLASSES

OBJECTS

METHODS

THISKEYWORD

ANNOTATIONS

ACCESSMODIFIERS

STATICKEYWORD

CHAPTER3ARRAYSANDSTRINGS

SINGLE-DIMENSIONALARRAYS

MULTI-DIMENSIONALARRAYS

FOR-EACHLOOP

STRINGS

CHAPTER4INHERITANCE

FUNDAMENTALSOFINHERITANCE

SUPERCLASSOBJECT

INHERITINGPRIVATEMEMBERS

SUPERCLASSANDSUBCLASSCONSTRUCTORS

POLYMORPHISM

Page 6: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

ABSTRACTION

KEYWORDFINAL

CHAPTER5PACKAGES

CREATEAPACKAGE

IMPORTAPACKAGE

JAVACLASSLIBRARY

CHAPTER6INTERFACES

INTERFACEIMPLEMENTATION

INTERFACEVARIABLES

MULTIPLEINHERITANCE

DEFAULTINTERFACEMETHOD

CHAPTER7ERRORS,EXCEPTIONS,ANDDEBUGGING

ERRORTYPES

THROWABLEEXCEPTIONPARENTCLASS

JAVA’SBUILT-INEXCEPTIONS

COMMONEXCEPTIONS

PRINCIPLESOFHANDLINGEXCEPTIONS

TRY/CATCHBLOCK

FINALLYBLOCK

CATCHATHROWABLEEXCEPTION

METHODSDEFINEDBYTHROWABLE

THROWVSTHROWS

DEBUGGING

CHAPTER8UTILIZINGINPUTANDOUTPUT

STREAMS

FILEINPUT/OUTPUT

CONCLUSION

RESOURCES

BOOKSBYREXJONESII

SIGNUPTORECEIVE

Page 7: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

PrefaceAccordingtoTIOBE,Javaisthemostpopularprogramminglanguagewithintheprogrammingcommunity.ThereforeJavaisagreatlanguagetolearnintheworldofautomatingapplications.AcoresetofJavaisnecessarytobeeffectiveonautomationprojects.Part2–Java4SeleniumWebDriverprovidesacoresetofJavaplusconceptsinvolvinginheritance,packages,andmuchmore.

TargetAudience

Thetargetaudienceisprogrammerswithknowledgeofvariables,datatypes,operators,branches,andloops.ItisrecommendedtoreadPart1–Java4SeleniumWebDriver,ifanindividualneedstogainafoundationinJava.

Purpose

Thepurposeofthisbookistonotoverwhelmyouwithhundredsandhundredsofpages(knownasinformationoverload)regardingJava.Howeveritwillprovidevaluableinformationthatisconcisewithstraightforwarddefinitions,examples,andfigures.AfterreadingPart2–Java4SeleniumWebDriver,athoroughunderstandingofJavaandobject-orientedprogrammingwillbeinyourpossession.

Page 8: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

AbouttheAuthor

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

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

Mr.Jones’adviceforpeopleinterestedinFunctionalAutomationTestingistolearntheprogramminglanguage.Thisadviceledhimtowritebooksfourprogrammingbooks“(Part1&Part2)YouMustLearnVBScriptforQTP/UFT”and“(Part1&Part2)Java4SeleniumWebDriver”.VBScriptistheprogramminglanguageforUnifiedFunctionalTesting(UFT)formerlyknownasQuickTestProfessional(QTP)andJavaisoneoftheprogramminglanguagesforSeleniumWebDriver.

Page 9: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

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

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

Anytrademarks,servicemarks,productnamesornamedfeaturesareassumedtobethepropertyoftheirrespectiveownersandusedonlyforreference.

Copyright©2016Test4Success,LLC.Allrightsreservedworldwide.

Page 10: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

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

ThankYou,

RexAllenJonesII

Page 11: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

Chapter1IntroductiontoObject-Oriented

ProgrammingObject-OrientedProgramming(OOP)isthemostpopularparadigminprogramming.Itisanapproachtoprogrammingthatcentersaroundobjects.Asaresult,identifyingobjectsisoneofthemostessentialprinciplesinOOP.Accordingtodictionary.com,anobjectisanythingvisibleortangible.Thereforeobjectscanbeaperson,place,orthingwherebyitisrecognizedinprogrammingliketherealworld.Allobjectshavetwocharacteristics:stateandbehavior.Stateidentifiestheobjectandbehaviorrepresenttheactionsoftheobject.

Chapter1underlinesobject-orientedprogramming(OOP)byprovidinganoverviewofthisbook“Part2–Java4SeleniumWebDriver”:

Classes,Objects,andMethods

ArraysandStrings

Inheritance

Packages

Interfaces

Errors,Exceptions,andDebugging

UtilizingInputandOutput

Page 12: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

Classes,Objects,andMethodsJavaisanobject-orientedprogramming(OOP)languagecontainingclasses,objects,andmethods(seeClasses,Objects,andMethodsinChapter2).Aclassisablueprintforcreatinganobjectandamethodexecuteajobfortheobject.Classesincludedataandcodethatoperateonthedata.ObjectsserveasthefoundationforOOPwhilemethodsperformactions.Amethod’sresponsibilityistoinstructtheprogramwhatactiontoperformandhowtoperformtheaction.

Page 13: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

ArraysandStringsInJava,arraysandstringsareobjects(seeArraysandStringsinChapter3).Anarrayisagroupofrelatedvariableswiththesamedatatype,samename,andfixednumberofvalues.Allitemsinthearrayareaccessedbyanindexwhichstartsatzero.Ontheotherhand,astringisagroupofunchangeablecharacters.Manymethodsareavailableforstringsthatfacilitateanoperationontheobject.

Page 14: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

InheritanceInheritanceisahierarchicalconceptwhichallowscodeandobjectstobereused(seeInheritanceinChapter4).Eachclassallowsotherclassestoinherititscode.Asaresult,therelationshipbetweentheclassesaresuperclassandsubclass.Superclassistheparentclassandsubclassisthechildclass.Theclassesmaintainacertainamountdataincommonwhileholdinguniquecharacteristics.

Page 15: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

PackagesApackageisacollectionofrelatedclasses(seePackagesinChapter5).Thepackageiscomparabletoafolderandtheclassesaresimilartofileswithinthefolder.Eachclasswithinthepackagecanbeaccessedbythepackagename.Itisimportanttoknowthatapackagemustbeimportedifaclasswantstousemembersfromadifferentclass.

Page 16: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

InterfacesAninterfaceisacollectionofrelatedmethods(seeInterfacesinChapter6).Generally,mostinterfacesdonotincludethebodyofamethod.Thereforeaninterfacemethodrevealswhatactiontoperformbutnothowtoperformtheaction.Thisconceptallowsaclasstoimplementtheinterfacemethodanddecidehowtoperformtheaction.Eachclasshastheabilitytoimplementadifferentactionforthesameinterfacemethod.

Page 17: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

Errors,Exceptions,andDebuggingErrorsareunavoidableproblemsinaprogram.Newprogrammersaswellasexperiencedprogrammerswillfaceerrors.Syntax,runtime,andlogicalarethreetypesoferrorsinJava.Syntaxerrorsstopthecodefromexecutingwhileruntimeerrorsallowcodetoexecutethengenerateanerror.Logicalerrorsarethemostdifficulterrorstodetectduetonoerrormessageduringexecution.Theprogrammermustknowwhattoexpectinordertofindandresolvealogicalerror.

Anexceptionisanerrorthatisoccursatruntime.Thistypeoferrorcanbemanagedbyablockofcodecalledanexceptionhandler.Exceptionhandlersallowtheprogramtogenerateanerrorbutcontinueexecutingaftertheerror.Debuggingisaprocessthatallowsaprogrammertoobservethencorrectanerrorand/orexception.Atoolcalleddebuggersimplifiesthetaskofresolvingerrorsduetobreakpointsanditsstep-by-stepfeatures.

Note:SeeErrors,Exceptions,andDebugginginChapter7formoreinformation

Page 18: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

UtilizingInputandOutputJava’sInputandOutput(I/O)isaverylargesystemconsistingofmanyclasses,interfaces,andmethods(seeUtilizingInputandOutputinChapter8).Informationisreadfromaninputsourceandwrittentoanoutputdestination.Theprogramsperforminputandoutputthroughstreamswherebystreamsrepresentdata.FilesinJavaarestoredandorganizedforconvenience.Mostofthefilesarestructuredinahierarchyknownasatree.Atthetopofeverytreeistherootnodewhichcontainsfoldersandfiles.Allfoldersandfileshaveadistinctivepathwithinthetree.Thefilescanbecreated,deleted,moved,copied,andverifiedforexistence.

Chapter1providedanoverviewoftheupcomingchapters.Thesubsequentchaptersexploreclasses,objects,methods,arrays,strings,inheritance,packages,interfaces,errors,exceptions,debugging,andJava’sinput/outputsystem.Chapter2willthoroughlyexplainclasses,objects,andmethodswhichisthecornerstoneofobject-orientedprogramming.

Page 19: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

Chapter2Classes,Objects,andMethods

Object-orientedprogramming(OOP)isaprogramminglanguagestructuredaroundobjects.Classes,objects,andmethodsareinterrelatedfundamentalswithinOOP.Anobjectisanythingthatcanbeseenorperceived.However,aclassisatemplateforobjectswhileamethodsprovideinteractionwithaclassfromvariouscomponentsoftheprogram.

Thedataandthecode(knownasstatements)thatoperateonthedataaretwomergednotionsofanobject.Asaresult,thetwomergednotionsallowaconceptcalledinformationhidingwherebydatacanbehidden.Thereforebydefaultanobject’sdatacanbeaccessedonlybymethodsholdingtheobject.Thelimitedaccesspreventotherprogramcomponentsfrominterferingandcausingerrors.Ifanothercomponentwantstochangeanobject’sdatathenthecomponentmustcallapubliclyaccessiblemethod.Thefollowingarefourtypesofmethods:

1. Instance–Amethodthatcanbeaccessedbyobjects2. Class–Amethodsharedbetweenallobjectsinaclass3. Main–Aspecialmethodusedtorunanapplication.Thistypeofmethodisnot

neededforSeleniumWebDriver.4. Constructor–Aspecialmethodusedtoinitializeobjectsofaparticularclass

Methodsandvariablesarelabeledmembersofaclasssincetheyformtheclass.Accesstobothmembersarecontrolledbyfourmodifiers:

1. public–Amodifierthatallowsaccesstocodedefinedoutsideofitsclass2. private–Amodifierthatallowsaccesstoothermemberswithinitsclass3. nomodifier–Amodifierthatallowsaccesstoallclasseswithinitspackage4. protected–Amodifierthatallowsaccesswithinitspackageandtoallsubclasses

Usually,membersofaclassareaccessedbyobjectswithinitsownclass.However,thekeyword“static”permitsamembertobeaccessedbeforeanyobjectiscreatedwithinitsclass.Methodsandvariablesaredeclaredstaticwhenthekeywordisplacedinfrontofthemember.

Chaptertwowillexplainthefollowingregardingclasses,objects,andmethods:

Page 20: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

Classes

Objects

Methods

ThisKeyword

Annotations

AccessModifiers

StaticKeyword

Page 21: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

ClassesClassesdefinedataandcodethatoperatesonthedata.Thedataisrepresentedbyvariableswhilethecodeisrepresentedbymethods.Bothvariablesandmethodsaremembersofaclass.Henceaclassisatemplatethatdefinesthestructureofanobject.Thereforethestructureofaclassmustbeprecise.Classesformedwithonelogicalentitymakestheclasscomplete.Itisimportanttodefineclasseswithinformationthatislogicallyconnected.Forexample,aclassthatcontainsinformationaboutanEnglishclasswouldnotcontainunrelatedinformationabouttheschoolzonespeedlimit.

Mostreal-worldclassesincludeaninstancevariableandamethodtooperateontheinstancevariable.Rememberfromthefirstbook“(Part1)AbsoluteBeginner:Java4SeleniumWebDriver”aninstancevariableisdeclaredinsideaclassbutoutsideofamethod.Asaresult,valuesofaninstancevariableareuniquetoeachobject.Thistypeofvariablecanbeusedbeforeorafteritisinitializedwithvisibilitytoallmethodswithinaclass.Thefollowingisthesyntaxfordefiningaclass:

SyntaxclassClassName

{

//DeclareInstanceVariable

variableTypevariableName1;

variableTypevariableName2;

variableTypevariableNameN;

//DeclareMethods

methodTypemethodName1()

{

//BodyoftheMethod

}

methodTypemethodName2()

{

//BodyoftheMethod

}

methodTypemethodNameN()

{

//BodyoftheMethod

Page 22: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

}

}

ThefollowingisanexampleofadataonlyclasscalledEnglishwhichstoresthreeinstancevariables:students,weeks,anddays.

classEnglish

{

intstudents;

intweeks;

intdays;

}

Figure2.1–DataOnlyClass

Line1definestheEnglishclassandlines3–5declaretheinstancevariables.Englishisaschoolcoursewhileinstancevariablestudentsrepresentthenumberofstudentsintheclass,weeksrepresentthenumberofweeksfortheEnglishcourse,anddaysrepresentthenumberofdaysperweek.Wheneveraclassisdefined,itisconsideredanewdatatype.Inthiscase,thenewdatatype“English”istheclassname.

Note:AconventionfornamingclassesistouseanUpperCamelCasewhereeachwordintheclassnamebeginswithacapitalletter(i.e.,EnglishCourse).

Page 23: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

ObjectsObject-Orientedprogramming(OOP)isbuiltuponobjects.Thereforeitiscrucialtounderstandhowobjectsareformedandutilized.Anobjectcanbeanything.Allobjectssharetwocharacteristics:stateandbehavior.Stateidentifiestheobjectandbehaviorrepresenttheactionsoftheobject.Forexample,adoghasastate(name,breed,color)whichidentifiesthedogandbehavior(bark,jump,fetch)whichrepresentthedog’sactions.Thestateofanobjectissupportedbyvariableswhilebehaviorisimplementedthroughmethods.Objectsarecreatedusingthekeyword“new”.Thefollowingexampleillustrateshowtocreateanobjectandhowtoaccessinstancevariables:

classEnglish

{

intstudents;

intweeks;

intdays;

}

classOneEnglishCourse

{

publicstaticvoidmain(Stringargs[])

{

EnglishENG101=newEnglish();

inttotalDays;

ENG101.students=10;

ENG101.weeks=4;

ENG101.days=3;

totalDays=ENG101.weeks*ENG101.days;

System.out.println(“TheEnglish101courseisatotalof“+totalDays+”days”);

}

}

Page 24: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

Figure2.2–CreateNewObjectandAccessInstanceVariables

ProgramOutput:TheEnglish101courseisatotalof12days

Line12createsanewobject( EnglishENG101=newEnglish(); )bycombiningtwosteps.AccordingtoJavaABeginner’sGuideSixthEdition(2014),thetwostepscombinedcanberewrittenlikethefollowingtoshoweachstepindividually(page106):

1. EnglishENG101;-TheleftsideoftheassignmentwhichdeclaresavariablecalledENG101ofclasstypeEnglish

2. ENG101=newEnglish();-TherightsideoftheassignmentwhichcreatesacopyoftheobjectandgiveENG101areferencetotheobject

ENG101isacreation(knownasinstance)ofEnglishaftercreatingthenewobject.Lines15–17assignvaluestotheinstancevariablesbyaccessingthevariablesusingthedot(.)operator.Thefollowingisthesyntaxforutilizingthedotoperator:

SyntaxobjectName.MemberName;

Thedotoperatorconnectsanobjectwithamember(instancevariableormethod).Inthisexample,anobjectname(ENG101)islocatedontheleftandtheinstancevariables(students,weeks,days)arelocatedontheright.Anobjectholditsowninstancevariablecopydefinedbytheclass.Therefore,ifmultipleobjectsexist,eachobjectcanholda

Page 25: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

differentvaluethantheotherobject.Thefollowingexampleillustrateacreationoftwoobjects(ENG101andENG202):

classEnglish

{

intstudents;

intweeks;

intdays;

}

classTwoEnglishCourses

{

publicstaticvoidmain(Stringargs[])

{

EnglishENG101=newEnglish();

EnglishENG202=newEnglish();

inttotalDays101;

inttotalDays202;

ENG101.students=10;

ENG101.weeks=4;

ENG101.days=3;

ENG202.students=12;

ENG202.weeks=6;

ENG202.days=3;

totalDays101=ENG101.weeks*ENG101.days;

System.out.println(“TheEnglish101coursehas“+ENG101.students+”studentsandthecourselast“+totalDays101+”days”);

totalDays202=ENG202.weeks*ENG202.days;

System.out.println(“TheEnglish202coursehas“+ENG202.students+”studentsandthecourselast“+totalDays202+”days”);

}

}

Page 26: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

Figure2.3–TwoObjectsCreated

ProgramOutput:TheEnglish101coursehas10studentsandthecourselast12days

TheEnglish202coursehas12studentsandthecourselast18days

Lines12and13createtwoobjects(ENG101andENG202)thenassignvaluestobothobjectsinlines18–24.Recall,ifmultipleobjectsexisttheneachobjectcanholdadifferentvaluethantheotherobject.Inthisexample,adifferentvalueisassignedtovariables“studentsandweeks”butvariable“days”containsthesamevalue“3”forbothobjects.

Note:TheconventionforvariablesarelowerCamelCasewhereeachwordinthevariablenamebeginswithacapitalletterexceptthefirstword.However,ENG101andENG202isanexceptionwhichcontainsallcapitallettersbecauseschoolcoursesnormallyhaveallcapitallettersbeforeanumberintheircoursename.

Page 27: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

MethodsAmethodisablockofcodesurroundedbycurlybracketsthatperformaspecificaction/task.Thepurposeistomanipulateandprovideaccesstodatadefinedbytheclass.Inotherwords,amethodperformsactionsonthedata.Itisbestforallmethodstocarryoutasingletask.Forexample,agoodmethodwillonlyperformasingletaskofaddingnumbersbutnotaddingnumbersandsavingdatatoafile.Theprogrammaybecomedifficulttoreadandunderstandifamethodcarriesoutmorethanonetask.

Methodsconsistofaheaderandbody.Themethodheaderincludesamethodtypeandamethodname.TheconventionformethodnameissimilartoavariablenamewhichconsistofalowerCamelCasestyle.Eachwordbeginswithacapitalletterexceptthefirstword.Succeedingthemethodnameisarequiredpairofparenthesiswhichsetsapartvariablesfrommethods.Thefollowingisthesyntaxformethod:

SyntaxmethodTypemethodName(parameter-list)

{

//MethodBody

}

ThemethodType(knownasreturntype)determinesthedatatypereturnedbythemethod.Aprogrammerisforcedtousekeyword“void”forthemethodTypeifnovaluesarereturned.ThemethodNamecanbeanynameexceptaJavakeyword.Agoodtechniquetoemployfornamingamethodisverb-nouncombinations,suchas“getOrderoraddNumbers”.Methodbodyiswherecodewillbeexecutedtocarryoutatask.Theparameterlistarevariablesthatreceiveargumentspassedtothemethod.Ifthemethodhasnoparametersthentheparameterlistmustremainempty.

Note:AmethodsignatureisthemethodNameandparameterlist.

Page 28: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

MethodReturns

Methodreturnsareconceptsthatreturnavaluefromamethodortransfercontroloutofamethod.Bothconceptsareachievedbyusingthereturnkeyword.Executionisterminatedandsubsequentstatementswithinthemethodareskippednomatterwherethereturnkeywordislocated.Thefollowingaretwomethodreturntypes:

1. Methodsthatreturnavalue2. Methodsthatcannotreturnavalue

AccordingtoORACLE,amethodreturnstothecodethatinvokeditwhenit

completesallthestatementsinthemethod,reachesareturnstatementorthrowsanexception

whicheveroccursfirst.

Note:Usually,thereturnkeyword(alsoknownasreturnstatement)isnotusedformethodsthatcannotreturnavalue.Itisnotusedbecauseallofthecodewithinthemethodiscompletedbeforeexecutingthereturnkeyword.However,ifthereturnkeywordisused,thenitwillbeimplementedattheendofthemethodtotransfercontrol.

ReturnAValue

Mostmethodsreturnavaluewhichspecifiestheoutcomeofacalculationorresult(pass,fail,etc.)Thereturnvalueisrequiredtobethesamedatatypeasthemethodtype.Forinstance,ifthemethodtypeisan“int”datatypethenthereturntypemustbean“int”datatype.Thefollowingisasyntaxandexampleforamethodreturn:

Syntaxreturnvalue;

classEnglish

{

intstudents,weeks,days;

inttotalDays()

{

Page 29: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

returnweeks*days;

}

}

classTwoEnglishCourses

{

publicstaticvoidmain(Stringargs[])

{

EnglishENG101=newEnglish();

EnglishENG202=newEnglish();

ENG101.students=10;

ENG101.weeks=4;

ENG101.days=3;

ENG202.students=12;

ENG202.weeks=6;

ENG202.days=3;

System.out.println(“TheEnglish101coursehas“+ENG101.students+”studentsandthecourselast“+ENG101.totalDays()+”days”);

System.out.println(“TheEnglish202coursehas“+ENG202.students+”studentsandthecourselast“+ENG202.totalDays()+”days”);

}

}

Page 30: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

Figure2.4–ReturnaValue

ProgramOutput:TheEnglish101coursehas10studentsandthecourselast12days

TheEnglish202coursehas12studentsandthecourselast18days

Methodsreturnavaluetothecodethatcalledthemethod.Inthisexample,lines26and27makecallstothemethod( inttotalDays() )atline5.Thenthemethodreturnstheoutcomefromcalculation( weeks*days )backtolines26and27.Thedot(.)operatorconnectsbothobjects(ENG101andENG202)toamember(totalDays())whichisamethod.Themethodisplacedontherightsideofthedotoperatorwhiletheobjectsarelocatedontheleft:

ENG101.totalDays();ENG202.totalDays();

Line3declaresallinstancevariablesasan“int”datatype.Thereforetheinstancevariables(weeksanddays)usedforcalculationatline7isautomaticallydeclaredwithan“int”datatype.Thiswillnotcauseareturnerrorbecausethereturntype(line7)andmethodtype(line5)possessthesamedatatype.Thevaluesforeachinstancevariablearecalculatedbasedonlines19,20,23,and24.Lines19and23containvaluesforvariable“weeks”whilelines20and24containvaluesforvariable“days”.

ReturnNoValue

Methodsthatcannotreturnavaluearecalledvoidmethods.Thekeyword“void“isimplementedasthemethodTyperatherthanadatatypesuchas“int”.Anerroroccursifthereisanattempttoreturnavaluefromthevoidmethod.Thefollowingisavoidmethodexample:

classEnglish

{

intstudents,weeks,days;

voidtotalDays()

{

System.out.println(weeks*days);

Page 31: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

}

}

classTwoEnglishCourses

{

publicstaticvoidmain(Stringargs[])

{

EnglishENG101=newEnglish();

EnglishENG202=newEnglish();

ENG101.students=10;

ENG101.weeks=4;

ENG101.days=3;

ENG202.students=12;

ENG202.weeks=6;

ENG202.days=3;

System.out.println(“HowmanystudentsareintheEnglish101course?“+ENG101.students);

System.out.println(“Thecourseis“+ENG101.days+”daysfor“+ENG101.weeks+”weeks.”);

System.out.print(“Thereforethecourselastthefollowingtotalnumberofdays:”);

ENG101.totalDays();

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

System.out.println(“HowmanystudentsareintheEnglish202course?“+ENG202.students);

System.out.println(“Thecourseis“+ENG202.days+”daysfor“+ENG202.weeks+”weeks.”);

System.out.print(“Thereforethecourselastthefollowingtotalnumberofdays:”);

ENG202.totalDays();

}

}

Page 32: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

Figure2.5–VoidMethod

ProgramOutput:HowmanystudentsareintheEnglish101course?10

Thecourseis3daysfor4weeks.

Thereforethecourselastthefollowingtotalnumberofdays:12

HowmanystudentsareintheEnglish202course?12

Thecourseis3daysfor6weeks.

Thereforethecourselastthefollowingtotalnumberofdays:18

Line5displayskeyword“void”whichindicatesthemethodwillnotreturnanyvalues.Nevertheless,thevoidmethodonlyperformsataskofcalculatingthetotalofnumberofdays.Line7printsthetotaldaysaftermultiplyingweeksanddays.Thefollowingdisplaysanerrorwhenthevoidmethodimplementsthereturnkeywordwithavalue:

classEnglish

{

intstudents,weeks,days;

//Avoidmethodcannotreturnavalue

voidtotalDays()

{

returnweeks*days

Page 33: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

}

}

Figure2.6–VoidMethodError

Page 34: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

PassArgumentsToParameters

Argumentsarevaluespassedtoamethodwhileparametersreceivesthevalues.Inotherwords,parametersreceivearguments.Parametervariablesaredeclaredwithinamethod’sparenthesisandoperatelikealocalvariable.Localvariablesandparametervariablesareonlyvisibletothemethodwhereisdeclared.Itisimportanttoknowthatoneormoreargumentscanbepassedtoindividualparameters.Thefollowingisanexampleofpassingtwoargumentstotwoparameters:

classEnglish

{

inttotalDays(intwk,intd)

{

returnwk*d;

}

}

classTwoEnglishCourses

{

publicstaticvoidmain(Stringargs[])

{

EnglishENG101=newEnglish();

EnglishENG202=newEnglish();

System.out.println(“TheEnglish101courseisatotalof“+ENG101.totalDays(4,3)+”days”);

System.out.println(“TheEnglish202courseisatotalof“+ENG202.totalDays(6,3)+”days”);

}

}

Page 35: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

Figure2.7–PassArgumentsToParameters

ProgramOutput:TheEnglish101courseisatotalof12days

TheEnglish202courseisatotalof18days

Line3definestwoparameters“wk,d”formethodtotalDays().MethodscanhavemorethanoneparameterbyseparatingeachparameterwithacommaLines16and17indicatesthearguments“4,3”forobject“ENG101”and“6,3”forobject“ENG202”arepassedtoparameters“wk,d”

Note:Objectscanbepassedtoamethodandreturnedfromamethod.

Page 36: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

MethodTypes

Thefollowingarethefourtypesofmethods:

1. InstanceMethods2. ClassMethods3. MainMethod4. Constructors

InstanceMethods

Instancemethodsarecalled(knownasinvoked)byusinganobject.Thereforeaninstancemethodissimilartoaninstancevariablewherebybothmemberscanbeaccessedthroughinitializedobjects.However,instancevariablescanbeaccessedwithanobjectreferenceorwithoutanobjectreference.Thefollowingisaninstancemethodexample:

publicclassLion

{

voidsound()

{

System.out.println(“ROAR”);

}

publicstaticvoidmain(Stringargs[])

{

LionmaleLion=newLion();

maleLion.sound();

}

}

Page 37: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

Figure2.8–InstanceMethod

ProgramOutput:ROAR

Lines3–6startsandcompletestheinstancemethod“sound”Line10createsanobject“maleLion”usingkeyword“new”Line11callstheinstancemethod“sound”throughinitializedobject“maleLion”

ClassMethods

Aclassmethod(knownasstaticmethod)issimilartoaclassvariablewherebytheyaredeclaredwithastatickeyword.Thestatickeywordmeansthememberbelongstotheclassandsharedbetweenallobjects.Classmethodscanbeaccessedviatheobjectnameorclassname.However,awarningappearswhenaccessingthemethodbyanobject.Thereforethefavoredwaytoaccessclassedmethodsisthroughclassname.Thefollowingisaclassmethodexample:classStaticAddNumbers

{

staticinta,b;

staticintaddNumbers()

{

returna+b;

}

}

classStaticExample

{

Page 38: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

publicstaticvoidmain(String[]args)

{

StaticAddNumbersobjAdd=newStaticAddNumbers();

objAdd.a=20;

StaticAddNumbers.b=30;

System.out.println(“Theadditionofvariables‘a+b’is“+objAdd.addNumbers()+”andaccessedbyanobject”);

System.out.println(“Theadditionofvariables‘a+b’is“+StaticAddNumbers.addNumbers()+”andaccessedbyaclassname”);

}

}

Figure2.9–ClassMethod

ProgramOutput:Theadditionofvariables‘a+b’is50andaccessedbyanobject

Theadditionofvariables‘a+b’is50andaccessedbyaclassname

Line3declarestwoclass/staticvariables“a,b”Lines5–7definestheclass/staticmethod“addNumbers”Line17assigns20toclassvariable“a”.Notice,thewarningnexttoline17thatstates“ThestaticfieldStaticAddNumbers.ashouldbeaccessedinastaticway”.Thiswarningmeanstheclassvariable(knownasstaticvariable)ispreferredtobeaccessedbyclassname.Line18doesnothaveawarningbecauseclassnameprecedesthevariablename“b”Line20issimilartoline18.Awarningmessageappearsbecausethestaticmethodisaccessedviaobjectnameratherthanclassname“i.e.,line21”

Page 39: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

Note:Classmethodscanonlyaccessclassvariablesandonlycallotherclassmethods.

MainMethod

Themainmethodisuniqueandmandatoryifaparticularclassbeginstheprogram.Thismethodisrequiredbecauseitexecutestheprogram.Thefollowingisthesyntaxformainmethod:

Syntaxpublicstaticvoidmain(String[]args)

{

//MethodBody

}

Thereareseveralexamplesofthemainmethodbutthefollowingexplainseachcomponent:

public-themethodcanbeaccessedbyallclassesstatic–themethodissharedbetweenallobjectsvoid–themethoddoesnotreturnanyvaluesString[]args–themethodreceivesaStringargumentandpasstheargumenttotheprogram

Note:ThemainmethodisexplainedinthischapterbecausePart2–Java4SeleniumWebDriverfocusesonJavaprogramming.However,SeleniumWebDriverwritesimplechecksusesatestingframeworksuchasJUnitandTestNGthatwillnotrequirethemainmethod.Thenextbook“SeleniumWebDriverforFunctionalAutomationTesting”willfocusonSeleniumanddiveintoJUnit.

Constructors

Aconstructorisaspecialmethodthathasthesamenameastheclass.Ifaconstructorisnotdefinedthenablankconstructorisautomaticallycreated.Consequentlyallclassescontainaconstructorwhichinitializeobjectsofaspecificclass.Anewobjectcallsaconstructoreverytimetheobjectiscreated.Bydefault,theinstancevariablesare

Page 40: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

initializedtozerofornumerictypes,nullforreferencetypes,andfalseforbooleantypes.

Constructorshavetheabilitytosettheinitialvalueforaninstancevariable.Recallaninstancevariablecanbeaccessedandassignedavalueusingthedotoperator.InFigure2.4–ReturnAValue,thefollowinginstancevariableswereassignedvalues:

ENG101.students=10;

ENG101.weeks=4;

ENG101.days=3;

ENG202.students=12;

ENG202.weeks=6;

ENG202.days=3;

Constructorscontainparameterswhichreceiveargumentswhenanobjectiscreated.Thefollowingexampleillustrateshowtopassargumentstoaconstructor:

classEnglish

{

intstudents,weeks,days;

English(ints,intw,intd)

{

students=s;

weeks=w;

days=d;

}

inttotalDays()

{

returnweeks*days;

}

}

classTwoEnglishCourses

{

publicstaticvoidmain(Stringargs[])

{

Page 41: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

EnglishENG101=newEnglish(10,4,3);

EnglishENG202=newEnglish(12,6,3);

System.out.println(“TheEnglish101coursehas“+ENG101.students+”studentsandthecourselast“+ENG101.totalDays()+”days”);

System.out.println(“TheEnglish202coursehas“+ENG202.students+”studentsandthecourselast“+ENG202.totalDays()+”days”);

}

}

Figure2.10–ParameterizedConstructor

ProgramOutput:TheEnglish101coursehas10studentsandthecourselast12days

TheEnglish202coursehas12studentsandthecourselast18days

Line5–10createaconstructorwhichdefinesthreeparameters“s,w,d”online5.Eachparameterisusedtoinitializetheinstancevariables“students,weeks,days”onlines7-9.Afterlines22and23areexecuted,thevalues“10,4,3”forENG101andvalues“12,6,3”forENG202areassignedtotheparameters“s,w,d”.Asaresult,thevaluesarepassedtotheEnglish()constructorwhenthekeyword“new”createseachobject“ENG101andENG202”.

Note:Constructorsarenotdefinedwithamethodtypesuchasintorvoid.Noticehowline5beginswithEnglishthendefinetheparameters.Javaallowsaclasstocontainmultiple

Page 42: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

constructors.Thefeatureiscalledconstructoroverloadingiftheconstructorscontainadifferentparameterlist.

Page 43: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

AccessorMethods

Accessormethodsaremethodsusedtogetandsetvaluesofprivatevariables.Privatevariablescanonlybeaccessedbycodewithinitsownclass.Thereforetheaccessormethodsaretwomethodsknownasgettersandsettersdefinedinthesameclassastheprivatevariables.

Bothmethodsaredefinedwithaprefixthatbeginswith“get”and“set”beforethemethodname.Forexample,getDays()andsetDays()areregardedasaccessormethodstogetthenumberofdaysthensetthenumberofdays.Thefollowingisanexampleofbothaccessormethods:

classEnglish

{

privateintstudents,weeks,days;

English(ints,intw,intd)

{

students=s;

weeks=w;

days=d;

}

intgetStudents()

{

returnstudents;

}

intgetWeeks()

{

returnweeks;

}

intgetDays()

{

returndays;

}

voidsetStudents(ints)

{

students=s;

}

Page 44: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

voidsetWeeks(intw)

{

weeks=w;

}

voidsetDays(intd)

{

days=d;

}

inttotalDays()

{

returnweeks*days;

}

}

Figure2.11–AccessorMethods

Line3declaresalloftheinstancevariables“students,weeks,anddays”asprivateLines5–10istheconstructormethod

Page 45: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

Lines12–25arethegetaccessormethods.Eachmethodonlyget/returnthenumberofstudents,weeks,anddaysLines27–40arethesetaccessmethods.Eachmethodsets/modifiesthenumberstudents,weeks,anddays

Page 46: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

ThisKeywordTheword“this”isakeywordwhichoperatesasareferenceinsideinstancemethodsand/orconstructors.Itreferstothecurrentobjectormemberofthecurrentobjectwhosemethodisbeingcalled.Thekeyword“this”isoptionalbutusefulwhenaprogrammerdecidestohideinformation.Inaddition,thekeyword“this”preventsuncertaintyinaprogramwhenalocalvariableandinstancevariablecontainthesamename.Awarningmessagestates“Theassignmenttovariablenamehasnoeffect”ifbothvariableshavethesamename.Thefollowingexampleshowshowtousekeyword“this”whenthelocalvariableandinstancevariablecontainthesamename:

publicclassThisKeyword

{

inttestVariable=34;

voidhideInstanceVariable()

{

inttestVariable=15;

System.out.println(“WhatisthevalueofthelocalvariableNOTusingthekeyword‘this’?“+testVariable);

System.out.println(“Whatisthevalueoftheinstancevariableusingthekeyword‘this’?“+this.testVariable);

}

publicstaticvoidmain(String[]args)

{

ThisKeywordobjHide=newThisKeyword();

objHide.hideInstanceVariable();

}

}

Page 47: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

Figure2.12–ThisKeyword

ProgramOutput:WhatisthevalueofthelocalvariableNOTusingthekeyword‘this’?15

Whatisthevalueoftheinstancevariableusingthekeyword‘this’?34

Line3declaresandinitializesaninstancevariable“testVariable”toavalueof34Line7declaresandinitializesalocalvariable“testVariable”toavalueof15Line9printamessagewhichincludesthelocalvariable“testVariable”Line10printsamessagewhichincludestheinstancevariable“this.testVariable”usingthekeyword“this”

Page 48: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

AnnotationsAccordingtodictionary.com,annotationmeans,“acriticalorexplanatorynote.”RecallfromPart1–Java4SeleniumWebDriver,commentsarenotesthathelpprogrammersunderstandtheprogram.Anannotationissimilartoacommentwherebytheybothprovideinformation.However,commentsareignoredbythecompilerwhileannotationssupplydatatothecompiler.Annotationsprovidemetadatawhichisdatathatdescribesdata.

Allannotationsstartwithanat“@”symbolandspecifythepurposeofamethod.Someannotationscanbecustomizedtoreplacecommentsandpredefinedannotationssuchas@Override.ThefollowingareexamplesofthreeJUnitannotationsusedinSeleniumWebDriver:

1. @Before–allocateresourcesandexecuteonetimebeforeeachtest2. @Test–executesatestscript3. @After–releaseallocatedresourcesandexecuteonetimeaftereachtest

Note:DetailsoftheJUnitannotationsareusedandexplainedinthe“SeleniumWebDriver”books.

Page 49: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

AccessModifiersAccessmodifiersarehelpfulfeaturesofobject-orientedprogramming.Theyarehelpfulbecauseoftheaccesslimitationitplacesoneveryclassandclassmembers(variablesandmethods).InJava,therearefourkindsofaccessmodifiers:

1. public–indicatesamembercanbeaccessedbyallclasses2. protected–indicatesamembercanbeaccessedbyallclassesandsubclasses(see

InheritanceinChapter4)withinitsownpackage(seePackagesinChapter5)3. nomodifier–indicatesamembercanbeaccessedbyallclasseswithinitsown

package4. private–indicatesamembercanbeaccessedwithinitsownclass

Theaccessmodifierprecedesaclass,variable,andmethoddeclaration.Classescanonlyusethepublicmodifierornomodifier.Therefore,anerroroccursifaclassmakesuseofaprivateorprotectedaccessmodifier.Thefollowingisanexampleofaclass,method,andvariablesusingapublicmodifier:

publicclassEnglish

{

publicintstudents,weeks,days;

publicinttotalDays()

{

returnweeks*days;

}

}

classTwoEnglishCourses

{

publicstaticvoidmain(Stringargs[])

{

EnglishENG101=newEnglish();

EnglishENG202=newEnglish();

ENG101.students=10;

ENG101.weeks=4;

ENG101.days=3;

ENG202.students=12;

Page 50: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

ENG202.weeks=6;

ENG202.days=3;

System.out.println(“TheEnglish101coursehas“+ENG101.students+”studentsandthecourselast“+ENG101.totalDays()+”days”);

System.out.println(“TheEnglish202coursehas“+ENG202.students+”studentsandthecourselast“+ENG202.totalDays()+”days”);

}

}

Figure2.13–PublicClass,Variables,andMethod

Theclass(line1),allofthevariables(line3),andmethod(lines5-8)aredeclaredwithapublicaccessmodifier.Consequently,therearenoerrorsandthememberswithintheEnglishclasscanbeaccessedbycodefromtheclass“TwoEnglishCourses”.

Thefollowingisanexampleofaprivatemethod:

publicclassEnglish

{

publicintstudents,weeks,days;

privateinttotalDays()

{

returnweeks*days;

Page 51: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

}

}

classTwoEnglishCourses

{

publicstaticvoidmain(Stringargs[])

{

EnglishENG101=newEnglish();

EnglishENG202=newEnglish();

ENG101.students=10;

ENG101.weeks=4;

ENG101.days=3;

ENG202.students=12;

ENG202.weeks=6;

ENG202.days=3;

System.out.println(“TheEnglish101coursehas“+ENG101.students+”studentsandthecourselast“+ENG101.totalDays()+”days”);

System.out.println(“TheEnglish202coursehas“+ENG202.students+”studentsandthecourselast“+ENG202.totalDays()+”days”);

}

}

Page 52: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

Figure2.14–PrivateMethod

Line5declaresthemethodtotalDays()withaprivateaccessmodifier.Thatmeansonlymemberswithinitsclass“English”canaccessthemethod.Lines26and27attemptstocallmethod“totalDays()”butcannotbecausetheyarelocatedinadifferentclass“TwoEnglishCourses”.Asaresult,anerrormessagestates“ThemethodtotalDays()”fromTypeEnglishisnotvisible.Thefollowingisanexampleofoneprivatevariableandtwopublicvariables:

Figure2.15–PrivateandPublicInstanceVariables

Line3declaresinstancevariable“students”asprivatewhileline4declaresinstancevariables“weeksanddays”aspublic.Noticelines19–25,twoerrors“lines19and23”occurfortheprivatevariable“students”.Inaddition,thereisanerroronlines27and28whichstates“ThefieldEnglish.studentsisnotvisible”.TheprivatevariableisonlyvisibletotheEnglishclassbutnotvisibletotheclass“TwoEnglishCourses”.However,thepublicvariablesarevisibletobothclasses.Thefollowingareaccesslevelsforeachmodifier:

public protected nomodifier private

Class Yes Yes Yes Yes

Package Yes Yes Yes No

Subclass Yes Yes No No

Page 53: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

World Yes No No No

Figure2.16–AccessModifierLevels

Page 54: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

StaticKeywordThestatickeywordcanbeappliedtovariables,methods,blocks,andnestedclasses.Usually,themembersofaclassareaccessedthroughanobjectoftheclassviathedotoperator.Whenamemberisdeclaredasstatic,themembercanbeaccessedpriortocreatinganobject.Howevertoaccessastaticmember,itisbesttoprecedethestaticmemberwithaclassnameanddotoperatorratherthantheobjectnameanddotoperator.Awarningmessageappearsifthestaticmemberisprecededbyanobjectnameanddotoperator.Thefollowingisthesyntaxandexampleofastaticvariable:

SyntaxClassName.variableName;classStaticAddNumbers

{

staticinta;

intb;

intaddNumbers()

{

returna+b;

}

}

classStaticExample

{

publicstaticvoidmain(String[]args)

{

StaticAddNumbersobjAdd=newStaticAddNumbers();

objAdd.b=50;

StaticAddNumbers.a=25;

System.out.println(“Thevalueof‘objAdd.b’is“+objAdd.b);

System.out.println(“Thevalueof‘a’is“+StaticAddNumbers.a);

System.out.println(“Thetotalof‘a+b’is“+objAdd.addNumbers()+“\n”);

StaticAddNumbers.a=30;

System.out.println(“Thevalueof‘a’changedto“+StaticAddNumbers.a+”butthevalueof‘objAdd.b’remains“+objAdd.b);

System.out.println(“Thetotalof‘a+b’is“++objAdd.addNumbers());

Page 55: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

}

}

Figure2.17–StaticVariable

ProgramOutput:Thevalueof‘objAdd.b’is50

Thevalueof‘a’is25

Thetotalof‘a+b’is75

Thevalueof‘a’changedto30butthevalueof‘objAdd.b’remains50

Thetotalof‘a+b’is80

Line3declaresastaticvariablenamed“a”withinclass“StaticAddNumbers”.Thevariable“a”isaccessedinlines19,22,25,and26byusingtheclassname,dotoperator,andstaticvariablename.Lines19and25setthevaluewhilelines22and26displaysthevalue.Staticvariablesaretreatedlikeglobalvariablesandinitializedatthestartofexecution.

Chapter2describedclasses,objects,methods,annotations,accessmodifiers,andkeywords“thisandstatic”.Aclassincorporatesdataandcodethatoperatesonthedata.Inaddition,classesprovideatemplateforobjectswhichisthefoundationforobject-orientedprogramming.Methodscarryoutaspecifictaskwhileprovidingaccesstodatadefinedbytheclass.Chapter3willdiscussarraysandstringswhichareregardedasobjectsinJava.

Page 56: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

Chapter3ArraysandStrings

Anarrayisacollectionofvariableswiththesamedatatype,samenameandfixednumberofvalues.Thevaluesareaccessedviaanindexwhichidentifiesanitemandstartsatzero.Eachiteminthearrayiscalledanelement.Abenefitofarraysisthecapacitytodealwithalargenumberofrelatedvaluesinoneentity.Forinstance,asinglearrayhastheabilitytoholdeveryemployee’ssalary.

InJava,arraysandstringsareconsideredobjects.Astringisadatatypecontaininganimmutablesequenceofcharacters.Immutablemeansthestringcannotbemodifiedafteraninitializationstatement.However,therearemanymethodsthatcanperformactionsonthestrings.

Chapterthreewilldiscussthefollowingconcerningarraysandstrings:

Single-DimensionalArrays

Multi-DimensionalArrays

For-EachLoop

Strings

Page 57: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

Single-DimensionalArraysSingle-Dimensionalarraysarethemostusedtypeofarrays.Itstoresalistofrelatedvaluessuchasdailytemperaturesforaspecificmonth.Inreturn,thelistofvaluescanleadtoamonthlytemperatureaverage.Alloftheinformationstoredinanarrayiseasilyaccessiblebyanindex.Thefollowingaretwosyntaxesfordefiningasingle-dimensionalarray:

SyntaxarrTypearrName[]=newarrType[arrSize];

or

arrTypearrName[];arrName=newarrType[arrSize];

Parameter Description

arrType Determinesthedatatypeofeachvalueinthearray

arrName Nameofthearray

new Allocatesmemoryforthearray

arrSize Numberofvaluesinthearray

Figure3.1–SingleDimensionSyntaxDetails

Thefollowingisanexampleofasingle-dimensionalarray:

publicclassOneDimensionalArray

{

publicstaticvoidmain(String[]args)

{

int[]tempMay=newint[3];

tempMay[0]=105;

tempMay[1]=102;

tempMay[2]=98;

Page 58: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

System.out.println(“ThehighesttemperatureinMaywas“+tempMay[0]+”degrees”);

System.out.println(“The2ndhighesttemperatureinMaywas“+tempMay[1]+”degrees”);

System.out.println(“The3rdhighesttemperatureinMaywas“+tempMay[2]+”degrees”);

}

}

Figure3.2–Single-DimensionalArrayExample

ProgramOutput:ThehighesttemperatureinMaywas105degrees

The2ndhighesttemperatureinMaywas102degrees

The3rdhighesttemperatureinMaywas98degrees

Line5initializesthearray“tempMay”byusingthekeyword“new”.Thenumber3inbrackets[3]indicatethearraycontain3elementsLines7–9assignvaluestoeachofthearray.Thefirstvalueisstoredatindexposition0.Zeroisalwaysthestartingpositionforarrays.Inthisexample,thelastindexpositionis2.Elements0–2holdsatotalof3elements.

Arrayscanbeassignedvaluesononelinewithoutthekeyword“new”.Thefollowingisanotherwaytoassignvaluestoanarray:

publicclassOneDimensionalArray

{

publicstaticvoidmain(String[]args)

{

Page 59: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

int[]tempMay={105,102,98};

System.out.println(“ThehighesttemperatureinMaywas“+tempMay[0]+”degrees”);

System.out.println(“The2ndhighesttemperatureinMaywas“+tempMay[1]+”degrees”);

System.out.println(“The3rdhighesttemperatureinMaywas“+tempMay[2]+”degrees”);

}

}

Figure3.3–AlternateSingle-DimensionalArrayExample

ProgramOutput:ThehighesttemperatureinMaywas105degrees

The2ndhighesttemperatureinMaywas102degrees

The3rdhighesttemperatureinMaywas98degrees

Line5initializesthearray“tempMay”andassignsthreevaluestothearray.Noticethekeyword“new”isnotusedtoinitializethearray.However,thedatatype“int”isspecifiedalongwiththearraynameandvalues.Squarebracketsindicatesanarraywhilethenumberofvalueswithinthecurlybracketsdictatethearraysize.ThefollowingisadiagramdisplayingthearrayvaluesfromFigure3.2andFigure3.3:

Page 60: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

Figure3.4–ArrayName,Values,andIndexes

Page 61: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

Multi-DimensionalArraysMulti-Dimensionalarraysareregardedasanarrayofarrays.Thereforetwoormorebracketsmustbeusedtodeclareamulti-dimensionalarray.Themostcommontypeofmulti-dimensionalarrayisatwo-dimensionalarray.Eachdimensioncontainsitsownsetofbrackets.Aspreadsheetwithrowsandcolumnsisagoodwaytoimagineatwo-dimensionalarray.Thefirstpairofbracketsarerowsandsecondpairofbracketsarecolumns.Thefollowingisthesyntaxandexampleforatwo-dimensionalarray:

SyntaxarrTypearrName[][]=newarrType[arrSize1][arrSize2];

publicclassTwoDimensionalArray

{

publicstaticvoidmain(String[]args)

{

introw,column;

inttestTwoDimension[][]=newint[2][3];

for(row=0;row<2;row++)

{

for(column=0;column<3;column++)

{

testTwoDimension[row][column]=(row*3)+column+1;

System.out.print(testTwoDimension[row][column]+”“);

}

System.out.println();

}

}

}

Page 62: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

Figure3.5–Two-DimensionalArrayExample

ProgramOutput:123

456

Line7initializesthetwo-dimensionalarray“testTwoDimension”byusingthekeyword“new”.Twobracketsindicatetherearetwodimensionssimilartorowsandcolumns.Noticetheoutputproducesatotaloftworowsandthreecolumns.Line9representsthecountforrowswhileline11representsthecountforcolumnLine13calculatesthevaluesonethroughsixLine14printsthevaluesonethroughsix

Comparabletosingle-dimensionalarrays,atwo-dimensionalarraycanbedeclaredandinitializedwithoutthekeyword“new”.Thefollowingisanexampleofatwo-dimensionalarraywithoutbeinginitializedusingkeyword“new”.

publicclassTwoDimensionalArray

{

publicstaticvoidmain(String[]args)

{

introw,column;

inttestTwoDimension[][]=

{

{1,2,3},

Page 63: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

{4,5,6}

};

for(row=0;row<2;row++)

{

for(column=0;column<3;column++)

System.out.print(testTwoDimension[row][column]+”“);

System.out.println();

}

}

}

Figure3.6–AlternateTwo-DimensionalArrayExample

ProgramOutput:123

456

Lines7–11initializethearraybysurroundingeachdimension’slistwithinaseparatesetofbrackets.Noticehoweachelementisdividedbyacommaandeachsetofbracketsrepresentarow.Theprevioustwoexamplesoutputthesameinformation.Aspecificvaluecanbeprintedbyindicatingaspecificrowandcolumn.Thefollowingexampleprintsaspecificvalueaccordingtoadefinedrowandcolumn:

publicclassTwoDimensionalArray

Page 64: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

{

publicstaticvoidmain(String[]args)

{

introw,column;

inttestTwoDimension[][]=

{

{1,2,3},

{4,5,6}

};

for(row=0;row<2;row++)

{

for(column=0;column<3;column++)

System.out.print(testTwoDimension[row][column]+”“);

System.out.println();

}

System.out.println(“\n”+“Whatvalueislocatedinrow1-column2?“+testTwoDimension[1][2]);

}

}

Figure3.7–PrintASpecificValueFromATwo-DimensionalArray

ProgramOutput:123

Page 65: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

456

Whatvalueislocatedinrow1-column2?6

Thefollowingillustratestheoutputinaspreadsheetformat:

Figure3.8–SpecificIndexForATwo-DimensionalArray

Page 66: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

For-EachLoopThefor-eachloop(knownasenhancedforloop)wasestablishedtocyclethroughacollectionofobjectssuchasanarray.Thistypeofcontrolstructurepresentsthesamefunctionalityastheforloop(seeChapter4-ControlStructuresin(Part1)Java4SeleniumWebDriver)whichexecutesablockofcodeacertainnumberofiterations.However,thefor-eachloopexecutesablockofcodewhilecyclingthrougheachelementinthecollection.Thefollowingisthefor-eachloopsyntax:

Syntaxfor(collTypeitrVariable:collection){statement(s)}

SyntaxDetails

Argument Description

collType Referstothetypeofdataforthecollection

itrVariable Referstothenameoftheiterationvariablethatreceiveseachelementaftereveryiteration

collection Thecollectionsuchasarraythatwillbeiteratedorcycledthrough

statement(s) Theblockedofthatwillbeexecuted

{…} Theopeningandclosingcurlybrackets

Figure3.9–For-EachLoopSyntaxDetails

Allelementsinthefor-eachloopareretrievedandstoredintheitrVariable.Thelooprepeatsuntilallelementsarereadinindexorder.Itisimportanttoknowthatthecolltypemustbethesametypeastheobject.Inthecaseofarrays,thecollTypemustbethesametypeasthearrType.Thefollowingisanexampleoffor-eachloop:

publicclassForEachLoop

{

publicstaticvoidmain(String[]args)

Page 67: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

{

double[]costPerItem={12.34,56.78,99.99};

doubletotalCost=0;

for(doublei:costPerItem)

{

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

totalCost=totalCost+i;

}

System.out.println(“\n”+“Thetotalcostofallitemsis“+totalCost);

}

}

Figure3.10–ForEachLoopExample

ProgramOutput:Thecostis12.34

Thecostis56.78

Thecostis99.99

Thetotalcostofallitemsis169.11

Line5and6initializeandassignvaluestothearray“costPerItem”and“totalCost”Line8retrieveseachelement(12.34,56.78,99.99)inarray“costPerItem”Line10printseachelementLine11calculatesthetotalofallelements

Note:Lines8–11canbereadas”Foreachdoubledatatypeinthe“costPerItem”array,printeachelementandcalculatethetotalofallelements”.

Page 68: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming
Page 69: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

Two-DimensionalArrayIteration

Iterationsfortwo-dimensionalarraysoperatesimilartosingle-dimensionalarrays.Theiterationvariableforatwo-dimensionalarraymustreferencethesingle-dimensionalarray.Itmustreferencethesingle-dimensionalarraybecausetwo-dimensionalarraysareconsideredarraysofarrays.Thereforeeachtwo-dimensionalarrayiterationretrievesthenextarray.Thefollowingisanexampleofatwo-dimensionalarrayiteration:

publicclassForEachLoop

{

publicstaticvoidmain(String[]args)

{

inttotalCost=0;

int[][]costPerItem=

{

{5,10},

{15,20},

{25,30}

};

for(inti[]:costPerItem)

{

for(intj:i)

{

System.out.println(“Thecostis“+j);

totalCost=totalCost+j;

}

}

System.out.println(“\n”+“Thetotalcostofallitemsis“+totalCost);

}

}

Page 70: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

Figure3.11–Two-DimensionArrayIterationExample

ProgramOutput:Thecostis5

Thecostis10

Thecostis15

Thecostis20

Thecostis25

Thecostis30

Thetotalcostofallitemsis105

Line5initializesandassignszero“0”tototalCostLines6–11initializeandassignvaluestothetwo-dimensionalarray“costPerItem”Line13“ for(inti[]:costPerItem) ”referencesasingle-dimensionalarraywherebyeachiterationretrievesthenextarrayincostPerItemfromstarttofinish“index0toindex5”Line15“ for(intj:i) ”cyclesthrougheachelement

Page 71: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

SearchAnArray

Arrayscanbesearchedtoretrievespecificvalues.Therearetimeswhenonlyacertainvalueisneededfromacollectionofvalues.Thefollowingexampleillustrateshowtoretrieveaspecificvaluefromanarray:

publicclassForEachLoop

{

publicstaticvoidmain(String[]args)

{

intspecificCost=20;

int[][]costPerItem=

{

{5,10},

{15,20},

{25,30}

};

for(inti[]:costPerItem)

{

for(intj:i)

{

if(j==specificCost)

{

System.out.println(“Thespecificcostof“+”’”+specificCost+”’”+”waslocatedinthecollectionofvalues”);

}

}

}

}

}

Page 72: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

Figure3.12–SearchATwo-DimensionalArray

ProgramOutput:Thespecificcostof‘20’waslocatedinthecollectionofvalues

Line5initializesandassigns20tovariable“specificCost”Lines6–11initializeandassignvaluestothetwo-dimensionalarray“costPerItem”Line13“ for(inti[]:costPerItem) ”referencesasingle-dimensionalarraywherebyeachiterationretrievesthenextarrayincostPerItemfromstarttofinish“index0toindex5”Line15“ for(intj:i) ”cyclesthrougheachelementLine17searchesthetwo-dimensionalarrayforaspecificelement“20”viavariablespecificCost

Page 73: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

StringsAstringisadatatypecontaininganimmutablesequenceofcharacters.Thisdatatypeisconsideredanobjectsoitwasnotdiscussedin(Part1)Java4SeleniumWebDriverwiththeotherdatatypes.Therearetwowaystocreateastring:

1. StringLiteral2. Stringusingthekeyword“new”

Thefollowingisanexampleofastringliteral:

publicclassStringObject

{

publicstaticvoidmain(String[]args)

{

StringfirstName=“Rex”;

StringlastName=“Jones”;

System.out.println(“Stringsareplacedwithinquotationmarks”);

System.out.print(“Thefirstnameis“+firstName+”andlastnameis“+lastName+“.”);

System.out.println(”Bothnamesweredeclaredandinitializedasstrings.Asequenceofcharacters”);

}

}

Figure3.13–StringExample

Page 74: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

ProgramOutput:Stringsareplacedwithinquotationmarks

ThefirstnameisRexandlastnameisJones.Bothnamesweredeclaredandinitializedasstrings.Asequenceofcharacters

Lines5and6declareandinitializeastringdatatypeLines8–10displaysthestringliteralwithintheprintlnmethod()

Stringscanbecreatedlikeotherobjectsbyusingthekeyword“new”whichcallstheStringconstructor.ThefollowingisanexampleofaStringwiththekeyword“new”:

Stringname=newString(“RexJones”);

Page 75: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

StringOperations

InJava,thereisaStringclasswhichcontainsmanymethodsforoperations.ThefollowingisascreenshotofseveralStringmethodsperEclipse:

Figure3.14–StringMethods

Line7displaysalistofmethodsaftertypingaperiodafterthevariable“name”Adescriptionofaspecificmethod“equals”appearswhenitishighlighted

ThefollowingarepopularStringmethods,theirdatatype,anddescription:

1. charAt(intindex):char-Returnsthecharacteratthespecifiedindex2. compareTo(str):int-Returnslessthanzeroifthecallingstringislessthanstr,

greaterthanzeroifthecallingstringisgreaterthanstr,andzeroifthestringsareequal

3. concat(Stringstr):String-Concatenatesthegivenstringattheendofthestring4. equals(ObjectanObject):boolean–Comparesthestringtoaspecificobject5. equalsIgnoreCase(Stringstring):boolean-Comparestringsandignorethecases6. indexOf(Stringstr):int-Returnstheindexofthefirstoccurrenceofaspecified

substring7. lastindexOf(Stringstr):int-Returnstheindexofthelastoccurrenceofastring8. length():int-Returnsthelengthofastring9. replace(charoldChar,charnewChar):String-Returnsthenewstringafter

changingalloccurrencesoftheoldstring10.split(Stringregex):String[]-Splitsthestringandreturnsastringarray

Page 76: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

thatmatchesthegivenregularexpression11.toLowerCase():String-ConvertsallofthecharactersinaStringtolowercase12.toUpperCase():String-ConvertsallofthecharactersinaStringtouppercase13.trim():String-Returnsacopyofthestring,afterdeletingleadingandtrailingwhitespacesfromtheoriginalstring

Astringdatatypecannotbecombinedwithadifferentdatatypeforanoperationsuchasmultiplication,subtraction,ordivision.Forexample,astringvalueof“534000.00”appearstobeanumericvaluebutstringdoesnotallowmathematicaloperationsunlessatypewrapperconvertsthestring.Thevalue“534000.00”resemblesadoubledatatype.However,anerroroccursifcombinedwithadoubledatatype.Thefollowingexampledisplaysanerrorifastringdatatypeiscombinedwithasubtractionoperator:

publicclassStringObject

{

publicstaticvoidmain(String[]args)

{

StringgrossIncome=“534000.00”;

doublegross=534000.00;

doubletaxes=225000.00;

doublenetIncome;

netIncome=grossIncome-taxes;

netIncome=gross-taxes;

System.out.println(“Thenetincomeis“+netIncome);

}

}

Page 77: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

Figure3.15–StringErrorDueToMathematicalOperations

Line5declaresandinitializesaStingvalue“534000.00”Line10displaysanerrorbecauseStringsdonotallowmathematicaloperations.However,noticeline11doesnotdisplayanerrorbecausebothvariables“grossandtaxes”aredeclaredasadoubledatatype“lines6and7”

Page 78: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

TypeWrappers

Typewrappersareusedtoconvertstringsintoprimitivetypes(byte,double,float,integer,long,short).Thereforethepreviousexamplewhichdisplayedanerrorforstringvalue“534000.00”canbeconvertedintoanumber.Typewrappersareusedtowraptheprimitivetype.Thefollowingisanexampleofhowtoreturnadoublewhenthevalue“534000”isspecifiedasastring:

publicclassStringObject

{

publicstaticvoidmain(String[]args)

{

StringgrossIncome=“534000.00”;

doubletaxes=225000.00;

doublenetIncome;

netIncome=Double.parseDouble(grossIncome)-taxes;

System.out.println(“Thenetincomeis“+netIncome);

}

}

Figure3.16–ReturnsADoubleAfterReadingAStringValue

ProgramOutput:Thenetincomeis309000.00

Page 79: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

Line5declaresandinitializesaStingvalue“534000.00”Line9parses(knownasreads)thestring“grossIncome”thenreturnadoubledatatype.Afterwards,thevariabletaxes“225000”issubtractedfromvariablegrossIncome“534000”andthevalueisassignedtovariable“netIncome”

Thefollowingisalistoftypewrappersthatconvertastringdatatype:

Wrapper ConversionMethod

Double Double.parseDouble(string)

Float Float.parseFloat(string)

Long Long.parseLong(string)

Integer Integer.parseInteger(string)

Short String.parseString(string)

Byte Byte.parseByte(string)

Figure3.17–TypeWrappers

Chapter3explainedarraysandstringswhichareobjects.Anarrayisacollectionofvariableswiththesamedatatype,samenameandfixednumberofvalues.Astringisadatatypecontaininganimmutablesequenceofcharacters.Chapter4willdefineinheritancewhichisahierarchicalconcept.Theconceptallowscodeandobjectstobereused.

Page 80: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

Chapter4Inheritance

Inheritanceisahierarchicalconceptwhichallowsreusablecodeandobjectstobeextended.Aclassknownassuperclasscanbecreatedwithvariablesandmethodstheninheritedbyotherclasses.Theinheritedclassesarecalledsubclasses.Eachsubclassthatinheritsthesuperclassmembersarepermittedtoaddtheirownclassmembers.Forexample,adogisananimal,sotheclass“Dog”,wouldbeasubclassofAnimal.Acatisananimalandtheclass“Cat”wouldalsobeasubclassofAnimal.Inbothexamples,class“Animal”isthesuperclass.

ChapterfourwillexplainthefollowingregardingInheritance:

FundamentalofInheritance

SuperclassObject

InheritingPrivateMembers

SuperclassandSubclassConstructors

Polymorphism

Abstraction

KeywordFinal

Page 81: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

FundamentalsofInheritanceTheconceptofinheritingclassesisanimportantfoundationwithinobject-orientedprogramming.Functionalitiesareaddedtoanexistingclasswhichpreventsthesamecodefrombeingwrittenmultipletimes.Thesubclassinheritsallclassmembersfromthesuperclass.Anotherwaytoviewsuperclassandsubclass,istothinkofsuperclassastheparentandsubclassasthechild.

Inorderforthesubclasstoinheritthesuperclass,thekeyword“extends”mustbeusedintheclassdeclaration.Keyword“extends”meansthesubclasswilladdtothesuperclass.Subclassesarenotallowedtoinheritmultiplesuperclasses.However,asubclassisallowedtobecomeasuperclassforanadditionalsubclass.Asaresult,theadditionalsubclassinheritsallclassmembersfromeachsuperclass.Thefollowingisthesyntaxforasubclassinheritingasuperclass:

SyntaxclassSubClassNameextendsSuperClassName

{

//ClassBody

}

Thefollowingisanexampleforasubclassinheritingasuperclass:

classSchool

{

intnumTeachers;

intnumStudents;

voidshowNumberOfPeople()

{

System.out.println(“Thereare“+numTeachers+”teachersand“+numStudents+”students”);

}

}

classElementarySchoolextendsSchool

{

StringprincipalName;

inttotalTeacherStudents()

{

returnnumTeachers+numStudents;

Page 82: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

}

voiddisplayPrincipal()

{

System.out.println(“Theprincipalnameis“+principalName);

}

}

classSchoolDistrict

{

publicstaticvoidmain(String[]args)

{

ElementarySchoolBishopHeights=newElementarySchool();

ElementarySchoolAltaMesa=newElementarySchool();

BishopHeights.numTeachers=10;

BishopHeights.numStudents=130;

BishopHeights.principalName=“JoeDoe”;

System.out.println(“MyelementaryschoolisBishopHeights\n”);

BishopHeights.displayPrincipal();

BishopHeights.showNumberOfPeople();

System.out.println(“Thereforethetotalofteachersandstudentsis“+BishopHeights.totalTeacherStudents());

}

}

Page 83: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

Figure4.1–SubclassExtendsSuperclassExample

ProgramOutput:MyelementaryschoolisBishopHeights

TheprincipalnameisJoeDoe

Thereare10teachersand130students

Thereforethetotalofteachersandstudentsis140

Line1displayssuperclass“School”Line11usesthekeyword“extends”tocreatesubclass“ElementarySchool”whichinheritssuperclass“School”Line17utilizevariables“numTeachersandnumStudents”ofthesuperclassLines29and30displaytwoobjects“BishopHeightsandAltaMesa”Lines32and33assignvalues“10and130”tovariables“numTeachersandnumStudents”whichareinheritedfromsuperclass“School”Line34assignavalue“JoeDoe”tovariable“principalName”whichisamemberofsubclass“ElementarySchool”

Thesubclass“ElementarySchool”isauniquetypeofsuperclass“School”.MoresubclassessuchasHighSchool,University,etc.caninheritsuperclass“School”.The“ElementarySchool“classinheritsallofthe“School“classmembersthenaddavariable

Page 84: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

“principalName”andtwomethods“totalTeacherStudentsanddisplayPrincipal”.Noticehowline30createsanobjectthatwasnotutilized.ThisshowsthatmoreElementarySchoolobjectscanbecreatedtoaccessmembersofthesuperclass“School”.

Note:Objectsfromthesuperclassdonothaveknowledgeofthesubclass.Therefore,thesuperclassobjectscannotaccessthesubclass.

Page 85: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

SuperclassObjectThesuperclass“Object”isthehighestsuperclassofallclasses.Inotherwords,thereisnoparentclassabovethe“Object”superclass.Bydefault,the“Object”superclassincludesmethodsthatareinheritedbyallsubclasses.ThefollowingisascreenshotwhichshowsObject“java.lang.Object”bydefaultastheSuperclasswhencreatinganewclass:

Figure4.2–EclipseNewClassCreationModal

Page 86: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

InheritingPrivateMembersPrivatemembersthatareinheritedfromthesuperclassremainprivateinthesubclass.Thereforethesubclasscannotaccesstheprivatemembers.Variablesandmethodsareonlyaccessiblebycodewithinitsownclasswhichdoesnotincludesubclasses.Nevertheless,theprivatememberscanbeaccessedbyusingaccessormethods.

Page 87: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

SuperclassandSubclassConstructorsSuperclassesandsubclassescontaintheirownconstructorswhichinitializeobjectsofitsclass.Asaresult,theconstructorsareindependentofeachother.Thesuperclassdoesnothaveaccesstothesubclassconstructorsbutthesubclasshasaccesstothesuperclassconstructors.Subclassescallasuperclass’sconstructorbyutilizingthekeyword“super”.Thefollowingisthesyntaxforasubclasscallingasuperclassconstructor:

Syntaxsuper(parameter-list)

Thefollowingisanexampleofasubclassinheritingasuperclass:

classSchool

{

privateintnumTeachers,numStudents;

School(intt,ints)

{

numTeachers=t;

numStudents=s;

}

intgetTeachers(){returnnumTeachers;}

intgetStudents(){returnnumStudents;}

voidsetTeachers(intt){numTeachers=t;}

voidsetStudents(ints){numStudents=s;}

voidshowNumberOfPeople()

{

System.out.println(“Thereare“+numTeachers+”teachersand“+numStudents+”students”);

}

}

classElementarySchoolextendsSchool

{

privateStringprincipalName;

ElementarySchool(Stringp,intt,ints)

{

super(t,s);

principalName=p;

}

Page 88: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

inttotalTeacherStudents()

{

returngetTeachers()+getStudents();

}

voiddisplayPrincipal()

{

System.out.println(“Theprincipalnameis“+principalName);

}

}

classSchoolDistrict

{

publicstaticvoidmain(String[]args)

{

ElementarySchoolBishopHeights=newElementarySchool(“JoeDoe”,10,130);

System.out.println(“MyelementaryschoolisBishopHeights\n”);

BishopHeights.displayPrincipal();

BishopHeights.showNumberOfPeople();

System.out.println(“Thereforethetotalofteachersandstudentsis“+BishopHeights.totalTeacherStudents());

}

}

Page 89: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

Figure4.3–SubclassInheritsSuperclassExample

ProgramOutput:MyelementaryschoolisBishopHeights

TheprincipalnameisJoeDoe

Thereare10teachersand130students

Thereforethetotalofteachersandstudentsis140

Line3declaresallofthevariables“numTeachersandnumStudents”asprivateLines5–9istheconstructorforsuperclass“School”Lines11–14aretheaccessormethods“getandset”Lines25–29isthesubclassconstructorfor“ElementarySchool”whichcallsthesuperclassconstructor“School”.Thestatement“super(t,s);”online27referstothesuperclassconstructorviakeyword“super”

Note:Asuperclassconstructorisexecutedfirstiftheprogramincludesasuperclassconstructorandsubclassconstructor.

Page 90: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

PolymorphismPolymorphismisasignificantconceptinobject-orientedprogramming.Thisconceptallowsoneinterfacetobeutilizedbymultiplemethods.Inthecaseofsuperclassandsubclass,asuperclassprovideastructurewherebyasubclasscandefineitsownmethodoperation.Themethodsareinheritedautomaticallywhenthesubclassextendsthesuperclass.

Page 91: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

MethodOverridingvsMethodOverloading

Methodoverridingisafeaturewhenthesubclassmethodoverridesthesuperclassmethod.Bothmethodsmusthavethesamemethoddatatypeandsignature.Amethod’ssignatureconsistsofamethod’snameandparameterlist.Thesuperclassmethodcanbecalledalthoughitisoverriddenbyasubclassmethod.Itisoverriddenifthekeyword“super”anddot(.)operatorisfollowedbythemethodname:super.methodName();

Methodoverloadingistwoormoremethodsinthesameclasswiththesamenamebutadifferentparameterlist.Theparameterlistdetermineswhichoverloadedmethodisexecutedifacallismadetothemethodname.Howeveraduplicatemethoderroroccursifmultiplemethodshavethesamesignature.Thefollowingshowsthedifferencesbetweenmethodoverridingandmethodoverloading:

MethodOverriding MethodOverloading

Definition Thesuperclassandsubclasshasamethodwiththesamemethodtypeandsignature

Aclasshasmultiplemethodswiththesamenameanddifferentparameterlist

MethodType

Thesuperclassandsubclassmethodtypesmustbecompatible

Thetypecanbethesameordifferent

Signature Thesuperclassandsubclassmusthavethesamesignature

Thesignaturesaredifferentregardingnumberofparameters,typeofparameters,andorderofparameters

Figure4.4–DifferencesBetweenMethodOverridingandOverloading

Note:An“@Override”annotationcanbeusedtoinstructthecompilerofasubclassoverridingasuperclass.Annotationsmaketheprogrameasiertoreadandletsthecompilerverifyiftheoverrideisvalid.

Page 92: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

StaticBinding

Bindingistheconnectionbetweenamethodcallandthemethoddefinition.Staticbinding(knownasearlybinding)iswhenbindingoccursatcompiletime.Thereforebindinghappensbeforeaprogramexecutes.Thefollowingisanexampleofstaticbinding:

classBinding

{

voidprintClassName()

{

System.out.println(“ThisclassiscalledBinding”);

}

}

classBindingExtendextendsBinding

{

@Override

voidprintClassName()

{

System.out.println(“ThisclassiscalledBindingExtend”);

}

}

classBindingExamples

{

publicstaticvoidmain(String[]args)

{

BindingExtendobjBindingExtend=newBindingExtend();

objBindingExtend.printClassName();

}

}

Page 93: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

Figure4.5–StaticBindingExample

ProgramOutput:ThisclassiscalledBindingExtend

Line11displaysanannotationwhichindicatesthesubclassmethod“printClassName()”willoverridethesuperclassmethod“printClassName()”Line12displaysaniconnexttothelinenumberwhichhasatooltipthatstates“overridesBinding.printClassName”Line22createsanobject“objBindingExtend”ofclass“BindingExtend”Line23callsthemethoddefinition“printClassName()”

Note:Forstaticbinding,thecompilerverifiesifamethoddefinition“printClassName”existinclass“BindingExtend”.

Page 94: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

DynamicBinding

Dynamicbindingiswhenbindingoccursatruntime.Thereforethistypeofbindinghappenswhentheprogramisrunning.Unlikestaticbinding,dynamicbindingallowspolymorphism.Thereforeamethodoverrideisgoodillustrationofdynamicbinding.Thefollowingisanexampleofdynamicbinding:

classBinding

{

voidprintClassName()

{

System.out.println(“ThisclassiscalledBinding”);

}

}

classBindingExtendextendsBinding

{

@Override

voidprintClassName()

{

System.out.println(“ThisclassiscalledBindingExtend”);

}

}

classBindingExamples

{

publicstaticvoidmain(String[]args)

{

BindingobjBinding=newBinding();

objBinding.printClassName();

BindingobjBindingExtend=newBindingExtend();

objBindingExtend.printClassName();

}

}

Page 95: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

Figure4.6–DynamicBindingExample

ProgramOutput:ThisclassiscalledBinding

ThisclassiscalledBindingExtend

Lines3and12definethesamemethodname“printClassName()”foreachclass“BindingandBindingExtend”Lines22and25createsbothobjects“objBinding”and“objBindingExtend”Lines23and26iswheredynamicbindingtakesplace.Bothcallsaremadetothesamemethodname“printClassName()”butindifferentclasses“superclassandsubclass”.Theobjects“objBinding”and“objBindingExtend”areusedforbindingatruntime.

Page 96: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

AbstractionAbstractionappliestoclassesaswellasmethods.Thekeyword“abstract”isusedtocreateabstractclassesandmethods.Anabstractclasscannotbeinstantiatedsoitisusedasasuperclass.Abstractmethodsaredeclaredwithoutanimplementationsoitdoesnotincludeabody.Abstractclassescanincludeabstractmethodsandimplementedmethods.However,anabstractclasscannotcontainobjectsduetoincompleteimplementationofitsmethods.

Thepurposeofabstractclassesistoonlydefineageneralizedmethodthenallowasubclasstodefinethedetailsofthemethod.Therearesituationswhenasuperclasscannotcreateameaningfulmethodimplementation.Aninstancemethodcanbedeclaredabstractbutstaticmethodsandconstructorscannotbedeclaredabstract.Thefollowingisthesyntaxforanabstractclassandmethod:

Syntax–AbstractClass

abstractclassClassName{

//AbstractClassescancontainabstractmethodsandimplementedmethods

//AbstractMethod

abstractmethodTypemethodName(parameter-list);

//ImplementedMethod

methodTypemethodName(parameter-list)

{

//MethodBody

}

}

Syntax–AbstractMethod

abstractmethodTypemethodName(parameter-list);

Note:Asubclassmustbedeclaredasabstractorimplementalloftheabstractmethodsfromthesuperclass.

Page 97: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

KeywordFinalThekeyword“final”preventsaclassormethodfrombeingoverwritten.Methodsareimplicitlydeclaredasfinaliftheclassisdeclaredfinal.RecallfromPart1–Java4SeleniumWebDriver,thekeyword“final”isusedtodeclareandinitializeconstants.Constantsareunchangeablevaluesassignedtoavariablename.Thebenefitofusingkeyword“final”istoconfirmaclassorclassmemberwillnotchangebecauseitiscriticaltotheprogram.Asaresult,anerroroccursifthereisanattempttoinheritaclassoroverrideaclassmember(methodorvariable)declaredasfinal.

Chapter4explainedinheritance,superclass,andsubclass.Inheritanceisahierarchicalconceptwhichallowsreusablecodeandobjectstobeextended.Superclassistheparentclasstosubclasswherebysubclassinheritstheclassmembers.Chapter5willdiveintopackageswhichisagroupofrelatedclasses.

Page 98: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

Chapter5Packages

Apackageisacollectionofrelatedclasseswherebythepackageoperateslikeafoldertoorganizecode.Theclasseswithinapackageareaccessedbythepackagename.RecallfromPart1–Java4SeleniumWebDriver,thatanerroroccursifaclassmakesuseoftheprivateaccessmodifier.However,aclasscanbemadeprivateandnotaccessedbycodeoutsideofthepackagebyusingnomodifier.Apackagedefinesauniquenamespacewhichpreventsmultipleclassesofhavingthesamenamewithinapackage.InJava,thereisnoproblemwithdifferentpackagesusingthesameclassname.

Chapter5willexplainthefollowingregardingpackages:

CreateAPackage

ImportAPackage

JavaClassLibrary

Page 99: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

CreateAPackageAprogrammercancreatetheirownpackagetogroupclasses.Allclasseshaveapackagethatisstoredinadirectory.Thefirstlineinmostsourcefilesincludesapackagestatement.However,apackagestatementisoptionalsothefirstlinecanremainblank.Ablankpackagestatementisthedefaultwhichcontainsnoname.Itisimportanttoknowthatdifferentsourcefilesareallowedtousethesamepackagestatement.Thefollowingisthesyntaxforapackagestatement:

Syntaxpackagepackagename;

Thenameofeachpackage“e.g.,packagename”iscasesensitive.InJava,itisconventionaltousealllowercaselettersforapackagename.Alllowercaselettersforapackageservesasacleardistinctionfromclassnames,methodnamesandmostvariablenames.EclipseIDEdisplaysawarningifthefirstletterwithinpackagenamebeginswithacapitalletter.Thefollowingisascreenshotwhichshowsawarningifthefirstletterisacapitalletter:

Figure5.1–PackageNamingConvention

Thefollowingisanexampleofapackagestatement:

packageexamplepackage;

classPackageTest

{

voidprintTest()

{

Page 100: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

System.out.println(“Thisisatest”);

}

}

publicclassPackage

{

publicstaticvoidmain(Stringargs[])

{

System.out.println(“Thisisanothertest”);

}

}

Figure5.2–PackageStatement

ProgramOutput:Thisisanothertest

Line1containsthepackagestatement“packageexamplepackage”Line3beginstheclassdefinitionforclass“PackageTest”.Thisclassisacomponentofapackage“examplepackage”Line11beginstheclassdefinitionforclass“Package”.Thisclassisacomponentofapackage“examplepackage”

Thefollowingisascreenshotoftheclassesgroupedtogetherinapackagedirectory:

Page 101: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

Figure5.3–PackageDirectoryScreenshot

Page 102: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

ImportAPackageAJavapackageisimportedbyusingthekeyword“import”.Importsareusefulwhenaclasswantstoaccessamemberinanotherclass.Theotherclasscanbeinthesamepackageordifferentpackage.Afterimportingapackage,themembersofthepackageareuseddirectlywithoutanyadditionalsyntax.Thefollowingisthesyntaxforimportingapackage:

Syntaximportpackagename.ClassName;

Toimportaclass,thedot(.)operatorisplacedbetweenthepackagenameandclassname.Theimportstatementsmustbeenteredafterthepackagestatementbutbeforetheclassesaredeclaredinthecurrentfile.Thefollowingisanexampleofapackagestatement,importstatement,andaclassdeclaration:

packageexamplepackage;

importexamplepackage.PackageTest;

publicclassPackageOne

{

publicstaticvoidmain(Stringargs[])

{

PackageTestobjPackage=newPackageTest();

objPackage.printTest();

}

}

Figure5.4–PackageImport

Page 103: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

ProgramOutput:Thisisatest

Line1containsthepackagestatement“packageexamplepackage;”Line2containstheimportstatement“importexamplepackage.PackageTest;”.Thepackagenameis“examplepackage”andclassnameis“PackageTest”whichislocatedinadifferentfile.Line4beginstheclassdeclaration“publicclassPackageOne”Line8createsanobject“objPackage”usingtheimportedclass“PackageTest”Line10callsthemethod“printTest();”whichislocatedinclass“PackageTest”.ViewFigure5.2-PackageStatement,toseedetailsofthemethod.

Note:Alloftheclassesfromaspecificpackagecanbeimportedbyusingthepackagenameandanasterisk:importpackagename.*;

Page 104: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

JavaClassLibraryTheJavaClassLibraryisknownasJavaApplicationProgrammingInterface(API)whichprovidesprogrammerswithacollectionofprewrittenclasses.Eachprewrittenclasshelpssupportthelogicofaprogrambysupplyingusefulfunctions.Oneofthepackagescalledjava.langisautomaticallyimportedintoallprograms.ThereforeclassessuchasSystemisemployedautomaticallywhenusingtheprint()andprintln()methodstodisplayinformation.AccordingtoOracle,thefollowingshowsfourofmanyJavaClassLibraries:

java.lang–ProvidesclassesthatarefundamentaltothedesignoftheJavaprogramminglanguage.

java.io-Providesforsysteminputandoutputthroughdatastreams,serializationandthefilesystem.

java.math-Providesclassesforperformingarbitrary-precisionintegerarithmetic(BigInteger)andarbitrary-precisiondecimalarithmetic(BigDecimal).

java.sql-ProvidestheAPIforaccessingandprocessingdatastoredinadatasource(usuallyarelationaldatabase)usingtheJavaTMprogramminglanguage.

Note:Packagejava.langcontainsamathclasswhichisdifferentfrompackagejava.math.Themathclasswithinjava.langcontainsmethodsthatperformsbasicnumericoperations.

Chapter5describedpackagesinJava.Eachpackagecontainsagroupofrelatedclasses.Theclassesareaccessedbythepackagename.Animportstatementmustbeplacedintheprograminorderforaclasstoutilizemembersofanotherclass.Chapter6willlookintointerfaceswhichisagroupofrelatedmethods.

Page 105: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

Chapter6Interfaces

Aninterfaceisacollectionofrelatedmethods.Interfacesarecomparabletoaclasswherebyitcontainsvariablesandmethods.Howeverbydefault,aninterface’svariableisdeclaredpublic,static,andfinalwhilethemethodisdeclaredabstract.Itispossibleforaninterfacetoperformataskbutusuallythereisnobehaviorimplementation.Inotherwords,mostmethodsinaninterfacedonotcontainabody.Thereforeaninterfacemethodwithoutabodyonlyincludesamethod’ssignature.Asaresult,theinterfacedefineswhattasktoperformbutnothowtoperformthetask.Theclasswhichimplementstheinterfacedecideshowtoperformthetask.Interfacescanextendoneormoreinterfacessimilartoasubclassextendingasuperclass.Thefollowingisthesyntaxforaninterface:

SyntaxaccessmodifierinterfaceinterfaceNameextendsinterfaceName1,interfaceName2,interfaceNameN

{

variableTypevariableName1;

variableTypevariableName2;

variableTypevariableNameN;

methodTypemethodName1(parameter-list);

methodTypemethodName2(parameter-list);

methodTypemethodNameN(parameter-list);

}

SyntaxDetails

Argument Description

accessmodifier Canbepublicornoaccessmodifier.Apublicdeclarationindicatestheinterfacecanbeusedbyanycode.Anoaccessmodifieristhedefaultwhichindicatestheinterfaceisonlyavailabletomembersofitspackage

Page 106: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

interface Akeywordusedtodeclareaninterface

interfaceName Thenameofaninterface

extends Anoptionalkeywordthatextendsoneormoreinterfaces

interfaceName1,2,N Oneormoreinterfacesseparatedbyacommathatwillbeextended

variableTypevariableName1,2,N; Oneormoreinterfacevariables

methodTypemethodName1(parameter-list);

Oneormoreinterfacemethods

Figure6.1–InterfaceSyntaxDetails

Thefollowingisaninterfaceexample:

publicinterfaceInterfaceTest

{

publicvoidmethodOne();

publicvoidmethodTwo();

}

Figure6.2–InterfaceExample

Line3declaresaninterfacebyusingthekeyword“interface”witha“public”accessmodifier.Thereforethecodecanbeimplementedbyanyclasswithinanypackage.ThenameoftheinterfaceiscalledInterfaceTest.Lines5and6arevoidabstractmethods“methodOneandmethodTwo”.Thekeyword“abstract”isnotneededwithinaninterface.Noticethesemi-colonatthe

Page 107: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

endofeachmethod.Thesemi-colonisplacedattheendofthemethodsbecausethereisnobody/implementation.

Chaptersixwilldiscussthefollowingregardinginterfaces:

InterfaceImplementation

InterfaceVariables

MultipleInheritance

DefaultInterfaceMethod

Page 108: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

InterfaceImplementationInterfacesareimplementedusingkeyword“implements”andoneormoreclassesprovideimplementationforthemethods.Ifaclassdoesnotimplementamethodbyprovidingabodythentheclassmustbedeclaredasabstract.Eachclassmayimplementthesameinterfacedifferentlywhilesupportingthesamemethods.Itisimportanttoknowthatoneclasscanimplementmultipleinterfaces.Thefollowingisthesyntaxforaclassimplementinganinterface:

SyntaxclassClassNameextendsSuperClassNameimplementsinterfaceName

{

//ClassBody

}

Thefollowingisanexampleofaclassimplementinganinterface.

packageInterfaceTesting;

publicclassInterfaceExamplesimplementsInterfaceTest

{

publicvoidmethodOne()

{

System.out.println(“ThisisthebodywhichimplementsmethodOne”);

}

publicvoidmethodTwo()

{

System.out.println(“ThisisthebodywhichimplementsmethodTwo”);

}

publicstaticvoidmain(String[]args)

{

InterfaceTestobjInterface=newInterfaceExamples();

objInterface.methodTwo();

}

}

Page 109: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

Figure6.3–ClassImplementsAnInterface

ProgramOutput:ThisisthebodywhichimplementsmethodTwo

Note:Thescreenshotdisplaysasplitimageduetotheinterfaceandclassbeinginseparatefiles.Eclipsedisplaysamessagewhichstates“interfacemustbedefinedinitsownfile”iftheinterfaceandclassislocatedinthesamefile.

Line3includesthe“implements”keywordwithintheclassdefinitionLines5–12aretheimplementedmethodswhichhasabody.Eachclassmethodmustmatchtheinterfacemethod.Thereforethemethodsaredeclared“public”,“void”methodtype,andsamesignature.Theclasswouldhavebeendeclaredasabstractifoneofthemethodswerenotimplemented.Anabstractclassresemblesthefollowingdeclaration:

abstractpublicclassInterfaceExamplesimplementsInterfaceTest

Page 110: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

InterfaceVariablesInterfaceconstants(knownasconstants)areimplicitlydeclaredaspublic,static,andfinal.Inotherwords,interfacevariablesarebydefaultconstantsinitializedwithavalue.Constantsareunchangeablevaluesassignedtoavariablename.Thevaluesareestablishedinaninterfacewithoutamethodandsharedacrossallfiles.Aclassimplementstheinterfacevariablesinthesamemannerasmethods.Thefollowingisanexampleofaninterfacevariable:

publicinterfaceInterfaceVariable

{

intDAYS_PER_WEEK=7;

intMAX_HOURS_PER_DAY=24;

}

Figure6.4–InterfaceVariableExample

Page 111: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

MultipleInheritanceMultipleinheritanceiswhenaninterfaceextendsanotherinterfaceoraclassimplementsmultipleinterfaces.Thekeyword“extends”isusedtoextendaninterface.Anextensionofinterfacesisbeneficialifaprogrammerelectstoaddmoremethods.Errorsaredisplayedifamethodisaddedtotheoriginalinterfaceandtheinterfacehasalreadybeenimplementedbyaclass.Alloftheclasseswhichusedtheoriginalinterfacewillbreakexistingcodebecausethereisnoimplementationofthenewlyaddedmethod.Howevertheoriginalinterfacecangetextendedtoaccommodatethenewmethodinaseparateinterface.Programmerscandecidetoeithercontinueusingtheoriginalinterfaceorstartusingtheextendedinterface.

Aclassinheritsmultipleinterfacesbyusingthekeyword“implements”followedbytheinterfaceswhichareseparatedusingacomma.Aclassmustprovideimplementationsforallmethodsiftheinterfaceinheritsanotherinterfaceortheclassimplementsmultipleinterfaces.Thefollowingisanexampleofmultipleinheritanceforaninterface:

publicinterfaceExtendInterfaceextendsInterfaceTest

{

publicvoidmethodThree();

publicvoidmethodFour();

}

Figure6.5–InterfaceExtendExample

Line3usesthe“extends”keywordtoextendsaninterface“InterfaceTest”.Theextendedinterfacecontainsabstractmethods“methodOneandmethodTwo”fromFigure6.2InterfaceExampleLines5and6displaypublicvoidabstractmethods“methodThreeandmethodFour”.Themethodsfromtheextendedinterfacearenotneededwheninheritinganinterface.Additionalinterfacescanbeextendedbyaddingtheinterfacenameandseparatingallinterfacingwithacomma

Page 112: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

Thefollowingisanexampleofaclassimplementingmultipleinterfaces:

publicclassMultipleInterfacesimplementsInterfaceTest,ExtendInterface

{

publicvoidmethodOne()

{

System.out.println(“ThisisthebodywhichimplementsmethodOne”);

}

publicvoidmethodTwo()

{

System.out.println(“ThisisthebodywhichimplementsmethodTwo”);

}

publicvoidmethodThree()

{

System.out.println(“ThisisthebodywhichimplementsmethodThree”);

}

publicvoidmethodFour()

{

System.out.println(“ThisisthebodywhichimplementsmethodFour”);

}

publicstaticvoidmain(String[]args)

{

InterfaceTestobjInterface1=newMultipleInterfaces();

objInterface1.methodOne();

ExtendInterfaceobjInterface3=newMultipleInterfaces();

objInterface3.methodThree();

}

}

Page 113: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

Figure6.6–ClassImplementingMultipleInterfaces

ProgramOutput:ThisisthebodywhichimplementsmethodOne

ThisisthebodywhichimplementsmethodThree

Line3usesthe“implements”keywordtoimplementmultipleinterfaces“InterfaceTestandExtendInterface”Lines5–21implementsabody/behaviorforeachmethoddefinedinbothinterfacesLines25–29createobjects“objInterface1andobjInterface3”thatisusedtocallmethods“methodOneandmethodThree”

Page 114: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

DefaultInterfaceMethodAdefaultinterfacemethod(knownanextensionmethod)allowsaninterfacemethodtoprovideabody.Therefore,theinterfacemethodsarepermittedtoimplementabehavior.ThischangeoccurredinthereleaseofJDK8wherebyaninterfacehastheoptiontoremainabstractordefineadefaultimplementation.Defaultmethodscontaina“default”keywordwhichprecedesthemethodtype.Anadvantageofdefaultmethodsisaclassdoesnotrequireimplementation.Howeveraclassrequiresimplementationofadefaultmethodifadifferentvalueisreturned.Thefollowingisanexampleofadefaultmethodusingfigures“Figures6.2–InterfaceExampleandFigure6.5–InterfaceExtendExample”.

publicinterfaceDefaultMethod

{

publicvoidmethodOne();

publicvoidmethodTwo();

defaultpublicvoidmethodThree()

{

System.out.println(“ThisisthebodywhichimplementsmethodThree”);

}

defaultpublicvoidmethodFour()

{

System.out.println(“ThisisthebodywhichimplementsmethodFour”);

}

}

Figure6.7–DefaultMethodExample

Chapter6explainedinterfaceswhichisacollectionofrelatedmethods.Generally,the

Page 115: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

interfacemethodsdonotcontainabody.Thereforetheinterfacemethodsdefinewhattasktoperformbutnothowtoperformthetask.However,adefaultmethodallowsaninterfacemethodtoprovideabodywhichoccurredinthereleaseofJDK8.Chapter7willdiscusserrors,exceptions,anddebugging.

Page 116: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

Chapter7Errors,Exceptions,andDebugging

Allprogramswillincludesomekindoferror.Anerrorisanunwantedproblemintheprogram.Itcanbeanunexpectedproblemsuchasmisspellingakeyword.InJava,theerrorsaregroupedintothreetypes:

1. Syntax–preventscodefromexecuting2. Runtime–generatesanerrorwhentheprogramisexecuting3. Logical–doesnotgenerateanerrormessageduetoafaultinthecode’slogic

Logicalerrorsaredifficulttolocatebecauseanerrormessageisnotgenerated.Usually,logicalerrorsarehiddenuntilaprogrammerdebugstheirprogram.Althougherrorsareunavoidableproblems,someproblemscanbehandledatruntime.Problemshandledatruntimearecalledexceptions.Theprogrammercreatesablockofcodecalledanexceptionhandlerwhichhandleexceptionsinadisciplinedmanner.Abenefitofhandlingexceptionsistheprogramcontinuestorunaftercatchingtheexception.

Debuggingisaprocessthatallowsaprogrammertoobservethencorrectanerror.TheproblemsinaprogramcanbefoundbyusingSystem.out.print,System.out.printlnoradebugger.Adebuggerisatoolthatfollowsacode’slogic.Mostprogrammersprefertouseadebuggerinsteadofseveralprintstatementstoinvestigateaproblem.Ifprintstatementsareused,thentheprogrammermustaddtheprintstatementsandremovetheprintstatementafterresolvingtheproblem.

Chaptersevenwillexplainthefollowingregardingerrors,exceptions,anddebugging.

ErrorTypes

ThrowableExceptionParentClass

Java’sBuilt-InExceptions

CommonExceptions

PrinciplesofHandlingExceptions

Try/CatchBlock

FinallyBlock

Page 117: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

CatchAThrowableException

MethodsDefinedByThrowable

ThrowvsThrows

Debugging

Page 118: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

ErrorTypesInprogramming,errorsareproblemsthatresultfromamistakeinaprogrammer’scode.Theerrorsarefoundbeforeaprogramexecutes,whenaprogramexecutes,andsometimeshiddenwithinaprogram.Theerrorslocatedbeforeexecutionofaprogramarecalledsyntaxerrors.Errorsfoundduringexecutionofaprogramarecalledruntimeerrors.Thehardesterrorstodiscoverwhicharehiddeninaprogramarecalledlogicalerrors.Nevertheless,allerrorsmustberesolvedtohaveasuccessfulprogram.

Page 119: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

SyntaxErrors

Syntaxerrors(knownascompilererrors)stopprogramsfromexecuting.Recallfromthefirstbook“Part1–Java4SeleniumWebDriver”,syntaxisasetofrulesthatspecifiesastructuredcombinationofwordsandsymbols.Ifnotstructuredcorrectly,anerroroccurstopreventthestatementsfromcompiling.Asaresult,theerrorsarenotcompiledduetoaninaccuracyintheprogrammer’scode.

Syntaxerrorsaretheeasiesterrorstolocateandresolve.AnIntegratedDevelopmentEnvironment(IDE)suchasEclipsepointsouttheerrors.Theerrorsaredisclosedbyaredunderlinebeneaththecodeand/orredXtotheleftofalinenumber.Inaddition,atooltipdisplaysamessagethatrevealstheerrorafterhoveringovertheredX.AccordingtoBeginningJava®Programming(2015),syntaxerrorsincludethefollowingexamples(page172):

Misspelledclass,variable,ormethodnames

Misspelledkeywords

Missingsemicolons

Missingreturntypeformethods

Outofplaceormismatchedparenthesesandbrackets

Undeclaredoruninitializedvariables

Incorrectformatofloops,methods,orotherstructures

Thefollowingcodehassyntaxerrorsintheprogram:

publicclassSyntaxError

{

publicstaticvoidmain(String[]args)

{

intx,y,total;

x=10;

y=6,

Total=x+y;

System.out.println(“Thetotalof10+6is“+total);

Page 120: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

}

}

Figure7.1–SyntaxErrorExample

Line10displaysanerrorduetoacommaratherthanasemi-colonLine11displaysanerrorbecauseTotalisnotdeclared.Line7declarestotalbutthefirstletterbeginswithalowercase“t”ratherthananuppercase“T”.

ThefollowingisanexampleofEclipserevealingtheerrorafterhoveringovertheredXforline10:

Figure7.2–ErrorMessageAfterHoveringOverRedX

Theerrorstates“Syntaxerrorontoken“,”,;expected”whichmeansthecompilerexpectsasemi-colon.AgrayXwithacircleandwhitebackgroundappearsaftercorrectingthe

Page 121: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

error.Consequently,theredunderlineandredXdisappearafterreplacingthecommawithasemi-colontocompletethestatement.

SomeerrorsdisplayayellowcirclewithasmallerredXsimilartoline11.ThiserroruncoversmultiplesolutionsthatmayresolvetheproblemafterclickingtheredX.ThefollowingisascreenshotofEclipsedisplayingpossiblesolutionstofixtheerroronline11:

Figure7.3–PossibleSolutionsAfterClickingTheRedX

SeveralsolutionsunfoldafterclickingtheredXonline11.However,thecorrectsolutionisthefirstoption“Changeto‘total’”.Eclipseautomaticallyupdatesthecodetoreflecttheselectedproposedsolution.Thereforelines10and11displayagrayXwithacircleandwhitebackground.BothX’sareremovedaftersavingthefile.

Page 122: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

RuntimeErrors

Runtimeerrorsaredetectedwhenaprogramexecutesaninvalidaction.Invalidactionsareoperationssuchasdividebyzero.Thesyntaxiscorrectsotheprogramrunsbutaproblemoccursduringruntime.Thefollowingisanexampleofaruntimeerror:

publicclassRuntimeError

{

publicstaticvoidmain(String[]args)

{

inta,b,x,y;

intresult,sum;

a=x=10;

b=y=0;

result=a/b;

sum=x+y;

System.out.println(“Whatis10/0?”+result);

System.out.println(“Whatis10+0?”+sum);

}

}

Figure7.4–RuntimeErrorExample

Page 123: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

ProgramOutput:Exceptioninthread“main”java.lang.ArithmeticException:/byzero

atErrors.RuntimeError.main(RuntimeError.java:13)

Figure7.5–Console/ProgramOutputScreenshot

Line7declaresfourvariables“a,b,x,y”Line8declarestwovariables“result,sum”Line10initializetwoofthevariables“aandb”to10Line11initializetwoofthevariables“xandy”to0Line13initializevariable“result”todivide‘a’by‘b’Line14initializevariablesumtoadd‘x’plus‘y’

Theprogramexecutesbutaruntimeerroroccursduetoline13.Thereforeexecutionimmediatelystopsanddoesnotexecutelines14–17.Although,line14isavalidoperation,thecompilerwillnotexecutethestatement.TheProgramOutputdisplaysamessagewhichinformstheprogrammeroftheproblem.Firstlineindicatesaproblembyshowing“/byzero”meaninganumberwasdividedbyzero.Secondlinespecifieswheretheproblemoccurredbyshowingthepackagename“Errors”,classname“RuntimeError”,methodname“main”,andlinenumber“13”.

Page 124: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

LogicalErrors

Logicalerrorsexecutewithoutanerrorbutlogicallyperformsthewrongtask.Asaresult,thistypeoferrorischallengingunlessaprogrammerknowswhattoexpect.Theactualresultsarecomparedtotheexpectedresultstoverifywhatwentwrong.Logicalerrorssuchasusinganoperatorprecedenceincorrectlyormisplacingasemicolonwillexecuteandproduceimproperresults.Thefollowingareexamplesoflogicalerrors:

publicclassLogicalErrors

{

publicstaticvoidmain(String[]args)

{

inttotal1=(9+(8*7))/6;

inttotal2=(9+8)*(7/6);

inttotal3=9+8*7/6;

inttotal4=(9+8)*7/6;

System.out.println(“Whatistheresultoftotal1:“+total1);

System.out.println(“Whatistheresultoftotal2:“+total2);

System.out.println(“Whatistheresultoftotal3:“+total3);

System.out.println(“Whatistheresultoftotal4:“+total4);

}

}

Figure7.6–OperatorPrecedenceLogicalErrorExample

ProgramOutput:Whatistheresultoftotal1:10

Page 125: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

Whatistheresultoftotal2:17

Whatistheresultoftotal3:18

Whatistheresultoftotal4:19

Lines7–10initializeeachvariable“total1,total2,total3,total4”withadifferentoperatorprecedence.Eachvariableproduceadifferentvaluealthoughthevalues“9,8,7,6”arethesame.Thefollowingisanexampleofmisplacingasemicolon:

publicclassLogicalErrors2

{

publicstaticvoidmain(String[]args)

{

inti;

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

{

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

}

}

}

Figure7.7–MisplacedSemicolonLogicalErrorExample

ProgramOutput:Theloopcontrolvariableis5

Line9incorrectlyplacesasemicolonattheendoftheforloop.Thereforetheprogramoutputs5ratherthan0,1,2,3,4.

Page 126: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming
Page 127: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

ThrowableExceptionParentClassAnexceptionisaJavaclasswherebyjava.lang.Throwableistheparentclass.Therefore,theThrowableexceptionrepresentsallexceptionclasses.Anobjectofaparticularexceptionclassisgeneratedwhenanexceptionisthrowninaprogram.TherearetwomainsubclassesderivingfromtheThrowableparentclass:

1. Error–containsseriousexceptionsthatoccurintheJavaVirtualMachine(JVM).JVMisamachinewithinamachinewhichsolvesproblemsandhelpstheprogramremainsecure.AnErrorsubclassisnotmanagedbytheprogrammer.

2. Exception–containsexceptionsthatoccurintheprogram.AnExceptionsubclassismanagedbytheprogrammer.

Thisbook“Part2–Java4SeleniumWebDriver”willexplaintheExceptionsubclass.Exceptionsfromsubclass“Error”arebeyondaprogrammer’scontrol.ThefollowingisadiagramfromProgramCreekwhichshowsahierarchyofJavaExceptionclasses:

Page 128: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

Figure7.8–JavaExceptionClassHierarchy

Page 129: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

Java’sBuilt-InExceptionsInJava,thereisarespectableamountofexceptionclassesdefinedinsidethejava.langstandardpackage.Thereforesomeexceptionsareautomaticallyavailableduetoanimplicitimportofjava.langintoeveryprogram.MostoftheexceptionsaresubclassesthatoriginatefromastandardtypecalledRuntimeException.RuntimeExceptioncontainsexceptionsthatarenotcheckedbythecompiler.Allotherexceptionsarecheckedbythecompilerandmustbeincludedinamethod’sthrowslist.Thefollowingisalistofuncheckedandcheckedexceptionsdefinedinthejava.langpackage:

UncheckedExceptions Description

ArithmeticException Arithmeticerror,suchasdivide-by-zero.

ArrayIndexOutOfBoundsException Arrayindexisout-of-bounds.

ArrayStoreException Assignmenttoanarrayelementofanincompatibletype.

ClassCastException Invalidcast.

EnumConstantNotPresentException Anattemptismadetouseanundefinedenumerationvalue.

IllegalArgumentException Illegalargumentusedtoinvokeamethod.

IllegalMonitorStateException Illegalmonitoroperation,suchaswaitingonanunlockedthread.

IllegalStateException Environmentorapplicationisinincorrectstate.

IllegalThreadStateException Requestedoperationnotcompatiblewithcurrentthreadstate.

IndexOutOfBoundsException Sometypeofindexisout-of-bounds.

NegativeArraySizeException Arraycreatedwithanegativesize.

NullPointerException Invaliduseofanullreference.

NumberFormatException Invalidconversionofastringtoanumericformat.

Page 130: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

SecurityException Attempttoviolatesecurity.

StringIndexOutOfBoundsException Attempttoindexoutsidetheboundsofastring.

TypeNotPresentException Typenotfound.

UnsupportedOperationException Anunsupportedoperationwasencountered.

Figure7.9–JavaUncheckedExceptions

CheckedExceptions Description

ClassNotFoundException Classnotfound.

CloneNotSupportedException AttempttocloneanobjectthatdoesnotimplementtheCloneableinterface.

IllegalAccessException Accesstoaclassisdenied.

InstantiationException Attempttocreateanobjectofanabstractclassorinterface.

InterruptedException Onethreadhasbeeninterruptedbyanotherthread.

NoSuchFieldException Arequestedfielddoesnotexist.

NoSuchMethodException Arequestedmethoddoesnotexist.

ReflectiveOperationException Superclassofreflection-relatedexceptions.

Figure7.10–JavaCheckedExceptions

Note:Inadditiontojava.lang,thefollowingpackagesincludeexceptions:

java.awt java.net

Page 131: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

java.awt.color java.rmi

java.awt.datatransfer java.security

java.beans java.text

Figure7.11–PackagesThatIncludeExceptions

Page 132: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

CommonExceptionsCommonexceptionsareexceptionsthatoccurfrequentlyinaprogram.Thesetypeofexceptionhappenstonewprogrammersaswellasexperiencedprogrammers.Thefollowingisalistofcommonexceptionsinalphabeticalorder:

ArrayIndexOutOfBoundsExceptionClassCastExceptionIllegalArgumentExceptionIllegalStateExceptionNullPointerExceptionNumberFormatExceptionOutOfMemoryErrorStackOverFlowError

Arraysstartatindexpositionzerowhichstoresthefirstvalue.Thereforethelastindexpositionisonelessthesizeofthecompletearray.AnArrayIndexOutOfBoundsExceptionisthrownwhenaprogramattemptstoaccessanindexoutsidetheboundariesofthearray.ThefollowingisanArrayIndexOutOfBoundsException:

publicclassCommonException

{

publicstaticvoidmain(String[]args)

{

String[]continents=newString[7];

continents[0]=“Africa”;

continents[1]=“Antarctica”;

continents[2]=“Asia”;

continents[3]=“Australia”;

continents[4]=“Europe”;

continents[5]=“NorthAmerica”;

continents[6]=“SouthAmerica”;

continents[7]=“America”;

System.out.println(“Thereare“+continents.length+”countries”);

}

}

Page 133: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

Figure7.12–ArrayIndexOutOfBoundsException/CommonExceptionExample

Line8createsanarraywith7elements“String[]continents=newString[7];”Line17whichcontains“continents[7]=“America”;”isoutofboundsforthearray“continents”Line19isnotexecutedbecausetheerrorcausestheprogramtostop

ProgramOutput:Exceptioninthread“main”java.lang.ArrayIndexOutOfBoundsException:7

atExceptionHandling.CommonException.main(CommonException.java:17)

AccordingtotheProgramOutput,theoutofboundsindexis“7”locatedatline17.Thefirstlineindicatesthereisanexceptionthenshowstheexceptiontype“ java.lang.ArrayIndexOutOfBoundsException ”.Number7specifiestheindexwhichcausestheexception.Thesecondlinedisplayswheretheexceptionislocated” atExceptionHandling.CommonException.main(CommonException.java:17) ”.Thefollowingisatranslationofthesecondline:

Anexceptionoccurredinpackagename”ExceptionHandling”,classname“CommonException”,methodname“main”,atlinenumber17.

Page 134: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

PrinciplesofHandlingExceptionsItisunderstoodthatexceptionsareproblemsthatoccuratruntime(duringprogramexecution).Javaallowsanexceptionhandlertohandleexceptionswhichincludebenefits.RemembertheruntimeerrorexamplefromFigure7.4,whereexecutionstoppedduetoadivisionbyzero.Abenefitofhandlingexceptionsistheprogramwillcontinueexecutingafterrespondingtoanerror.Thereforeanerrordoesnotstopprogramexecutionbuttheexceptionhandlerpermitstheprogramtocontinuerunning.InJava,therearefiveinterrelatedkeywordsthatfacilitatethemanagementofhandlingexceptions.Thefollowingisadescriptionofeachkeyword:

1. try–monitorscodewhereanexceptionmightoccur2. catch–handlestheexceptionwhenanerroroccurs3. throw–manuallythrowsacustomexception4. throws–throwsanexceptionthatoccurredfromamethod5. finally–automaticallyexecutescodeafterexitingatryblock

TheJavaVirtualMachine(JVM)catchesallexceptionsiftheexceptionhandlerdoesnotcatchtheexception.JVMdisplaysanerrormessagewhichisgoodfordebuggingbutnotforhandlingexceptions.Itisnotgoodforhandlingexceptionsduetoterminationoftheprogram.

Page 135: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

Try/CatchBlockThetry/catchblockallowscodetobetriedtoverifywhetheranexceptionoccurs.Ifanexceptionoccursthentheexceptioniscaughttospecifywhatshouldhappen.Thekeywords“tryandcatch”operatetogetherwhenhandlingexceptions.Tryisusedtocontainthecodethatmaycauseanexceptionwhilecatchmanagestheexception.Bothkeywords“tryandcatch”arecentraltohandlingexceptions.Atryblockisprovidedalongwithoneormorecatchblocks.Itisimportanttoknowthatthetryblockandallcatchblocksarebypassedifnoexceptionoccurs.Thefollowingisthetry/catchblocksyntaxforhandlingexceptions:

Syntaxtry

{

//Codemonitoredbytryblock

}

catch(ExceptionType1excObject)

{

//ExceptionHandlerforExceptionType1

}catch(ExceptionType2excObject)

{

//ExceptionHandlerforExceptionType2

}

Thefollowingisthesyntaxdetailsfortryandcatchblock:

Arguments Description

try Monitorsablockofcodeforanexception

catch Handlesandprocessestheexception

ExceptionType1ExceptionType2

TypeofexceptionthatmustbethenameofaclassinheritedfromtheThrowableclass

excObject Receivesthevalueofanexceptioncaughtbythe

Page 136: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

handler.

Figure7.13–SyntaxDetails

Thefollowingisanexampleofatryandcatchexceptionhandler:

publicclassTryCatchBlock

{

publicstaticvoidmain(String[]args)

{

String[]continents=newString[7];

try

{

System.out.println(“Anexceptionhasnotbeenthrown”);

continents[0]=“Africa”;

continents[1]=“Antarctica”;

continents[2]=“Asia”;

continents[3]=“Australia”;

continents[4]=“Europe”;

continents[5]=“NorthAmerica”;

continents[6]=“SouthAmerica”;

continents[7]=“America”;

System.out.println(“Thereare“+continents.length+”continents”);

}

catch(ArrayIndexOutOfBoundsExceptionexc)

{

System.out.println(“Exception!!!-ArrayIndexOutofBounds.Notavalidcontinent”);

}

System.out.println(“Thislineexecutesautomaticallywhetheranexceptionoccursornot”);

}}

Page 137: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

Figure7.14–TryandCatchBlockExample

ProgramOutput:Anexceptionhasnotbeenthrown

Exception!!!-ArrayIndexOutofBounds.Notavalidcontinent

Thislineexecutesautomaticallywhetheranexceptionoccursornot

Line8startsthecodemonitoringprocessforerrorsusingthetryblockLine19forcesanexceptionwhendefiningindexposition7whichisoutsideofthearrayboundaries.ThereforethetryblockisterminatedandtheprogramtransferscontroltothecatchblockLine21doesnotexecuteduetotheexceptionatline19Line23startstheexceptionhandlingprocessbylistingtheexceptiontype“ArrayIndexOutOfBoundsException”withinthecatchblockLine25isexecutedwithinthecatchblockaftertheexceptioniscaughtLine27isexecutedfollowingthecatchblock.Thislineexecutesautomaticallywhetheranexceptionoccursornot.

AcommonpracticeinJavaistoassociatemultiplecatchblockswithatryblock.Eachcatchblockmustincludeauniqueexceptiontypesuchasarithmeticexception,arrayindexoutofboundsexception,etc.Theexceptiontypedetermineswhichcatchblockisexecutedaftercreatingmultiplecatchblocks.Thereforeifthearithmeticexceptiontypeisexecutedthenthearrayindexoutofboundsexceptiontypeisbypassed.Thefollowingisanexampleofatryblockwithmultiplecatchblocks:

Page 138: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

publicclassMultipleCatchBlocks

{

publicstaticvoidmain(String[]args)

{

intoddNumbers[]={11,33,55,77,99,111};

intevenNumbers[]={0,2,4,6,8};

for(inti=0;i<oddNumbers.length;i++)

{

try

{

System.out.println(“Whatis“+oddNumbers[i]+“/”+evenNumbers[i]+“?“

+””+oddNumbers[i]/evenNumbers[i]);

}

catch(ArithmeticExceptionexcept)

{

System.out.println(“Exception!!!-Cannotdivideanumberbyzero”);

}

catch(ArrayIndexOutOfBoundsExceptionexcept)

{

System.out.println(“Exception!!!-Cannotlocatetheindex”);

}

}

}

}

Page 139: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

Figure7.15–MultipleCatchBlocks

ProgramOutput:Exception!!!-Cannotdivideanumberbyzero

Whatis33/2?16

Whatis55/4?13

Whatis77/6?12

Whatis99/8?12

Exception!!!-Cannotlocatetheindex

Line17displaysthefirstcatchblockwhichcontainsanarithmeticexception.Catchblocksareevaluatedaccordingtotheirorderofassociationtothetryblock.Thereforethiscatchblockisevaluatedfirstsinceitoccursfirstintheprogram.Theothercatchblockisignoredwhenamatchisfoundforthisexceptiontype.Line19isexecutedwhenthecodereacheszero“0”inarray“evenNumbers[]”Line21displaysthesecondcatchblockwhichcontainsanarrayindexoutofboundsexceptionLine23isexecutedwhenthecodesearchesforanindexthatisnotavailableinarray“evenNumbers[]”.Theothercatchblockisignoredwhenamatchisfoundforthisexceptiontype.

Page 140: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

FinallyBlockThefinallyblockisanextensionoftry/catchblock.Thisblockconfirmscertainactionssuchaswritingdatatoafileisperformedwhetheranexceptionoccursornot.Javaallowsthesameactiontobeplacedwithinthetryblockandcatchblock.Ontheotherhand,placingthesamecodeinbothblocks“tryblockandcatchblock”createsduplicatecode.

Forexample,whathappensifthereisnoexceptionanddataneedstobewrittentoafile.Inthisscenario,thetryblockexecutesthecodewhilethecatchblockisbypassed.However,ifthereisanexception,thecatchblockexecutesthecodewhilethetryblockisbypassed.Therefore,aprogrammermustplacecodeinthetryandcatchblockforcertaintythatdataiswrittentoafile.Inprogramming,itisdifficulttoreadandmaintainduplicatecode.Afinallyblockisnotrequiredbutitwillcertainlywritedatatothefilewhenanexceptionisthrownandwhenitisnotthrown.Thefollowingisthesyntaxofatry/catch/finallyblock:

Syntaxtry

{

//Codemonitoredbytryblock

}

catch(ExceptionType1excObject)

{

//ExceptionHandlerforExceptionType1

}catch(ExceptionType2excObject)

{

//ExceptionHandlerforExceptionType2

}finally

{

//Executecodeifexceptionoccursornot

}

Thefollowingisanexampleusingthetry/catch/finallyblock:

Page 141: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

publicclassFinallyBlock

{

publicstaticvoidmain(String[]args)

{

intoddNumbers[]={11,33,55,77,99,111};

intevenNumbers[]={0,2,4,6,8};

for(inti=0;i<oddNumbers.length;i++)

{

try

{

System.out.println(“Whatis“+oddNumbers[i]+“/”+evenNumbers[i]+“?“

+””+oddNumbers[i]/evenNumbers[i]);

}

catch(ArithmeticExceptionexcept)

{

System.out.println(“Exception!!!-Cannotdivideanumberbyzero”);

}

catch(ArrayIndexOutOfBoundsExceptionexcept)

{

System.out.println(“Exception!!!-Cannotlocatetheindex”);

}

finally

{

System.out.println(“PerformanAction”);

}

}

}

}

Page 142: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

Figure7.16–FinallyBlock

ProgramOutput:Exception!!!-Cannotdivideanumberbyzero

PerformanAction

Whatis33/2?16

PerformanAction

Whatis55/4?13

PerformanAction

Whatis77/6?12

PerformanAction

Whatis99/8?12

PerformanAction

Exception!!!-Cannotlocatetheindex

PerformanAction

Line25startsthefinallyblockattheendofthetry/catchblockLine27isexecutedautomaticallywhenanexceptionisthrownandwhenanexceptionisnotthrown

Page 143: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

CatchAThrowableExceptionAThrowableexceptioncanbeutilizedtocatchallexceptionssinceitistheparentclass.ThesuperclassThrowablematchesallofitssubclasseswhichincludesRuntimeException.Inordertocatchexceptionsforbothclasses,thesuperclassandsubclassmustbeimplementedintheirrespectivecatchblock.ThefollowingisaThrowablesuperclassandArithmeticExceptionsubclassexampleusingcodefromFigure7.15:

publicclassSuperSubClassException

{

publicstaticvoidmain(String[]args)

{

intoddNumbers[]={11,33,55,77,99,111};

intevenNumbers[]={0,2,4,6,8};

for(inti=0;i<oddNumbers.length;i++)

{

try

{

System.out.println(“Whatis“+oddNumbers[i]+“/”+evenNumbers[i]+“?“

+””+oddNumbers[i]/evenNumbers[i]);

}

catch(ArithmeticExceptionexcept)

{

System.out.println(“Exception!!!-Cannotdivideanumberbyzero”);

}

catch(Throwableexcept)

{

System.out.println(“Exception!!!-TheThrowableExceptioncaughtanerror”);

}

}

}

}

Page 144: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

Figure7.17–ThrowableandArithmeticExceptionExample

ProgramOutput:Exception!!!-Cannotdivideanumberbyzero

Whatis33/2?16

Whatis55/4?13

Whatis77/6?12

Whatis99/8?12

Exception!!!-TheThrowableExceptioncaughtanerror

Line18implementsthesubclassexception“ArithmeticException”insidethefirstcatchblockLine20isexecutedwhenthecodereacheszero“0”inarray“evenNumbers[]”Line22implementstheThrowableexceptioninsidethesecondcatchblockLine24isexecutedwhenthecodesearchesforanindexthatisnotavailableinarray“evenNumbers[]”

TheThrowablesuperclassandsubclassareallowedtocatchexceptionsbyplacingthesubclassinthefirstcatchblock.AnerroroccursiftheThrowableexceptionisimplementedinthefirstblock.Theerrormessagestates“UnreachablecatchblockforArithmeticException.ItisalreadyhandledbythecatchblockforThrowable”.

Page 145: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

MethodsDefinedByThrowableAsmentioned,Throwableisasuperclassofeveryexceptionsubclass.ThereforeallexceptionssupportmethodsdefinedbyThrowable.AnexceptioncanbecaughtbyaThrowableexceptionbutitisagenericcatch.ItisbesttouseaspecificexceptionsuchasArithmeticExceptionwhenhandlingexceptions.However,someofthemethodsdefinedbyThrowablecanhelpthesuperclassbemorespecificwhenhandlingexceptions.ThefollowingisalistofThrowablemethods:

Method Description

fillInStackTrace() Fillsinthecompletedexecutionstacktrace

getLocalizedMessage() CreatesalocalizeddescriptionoftheThrowableexception

getMessage() ReturnsadetailmessageoftheThrowableexception

printStackTrace() Printsthestacktrace

printStackTrace(PrintStream) Printsthestacktracetothespecifiedprintstream

printStackTrace(PrintWriter) Printsthestacktracetothespecifiedprintwriter

toString() Returnsashortexceptiondescriptionafterbeingcalledbyprintln()method

Figure7.18–MethodsDefinedbyThrowable

OneofthemostcommonmethodsdefinedbyThrowableistheprintStackTrace()method.Thismethodprintsthestacktrace“standarderrormessage”.ThefollowingisanexampleofprintStackTrace()method:

publicclassThrowableMethod

{

publicstaticvoidmain(String[]args)

{

intoddNumbers[]={11,33,55,77,99,111};

Page 146: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

intevenNumbers[]={0,2,4,6,8};

for(inti=0;i<oddNumbers.length;i++)

{

try

{

System.out.println(“Whatis“+oddNumbers[i]+“/”+evenNumbers[i]+“?“

+””+oddNumbers[i]/evenNumbers[i]);

}

catch(ArithmeticExceptionexceptName)

{

System.out.println(“Exception!!!-Cannotdivideanumberbyzero”);

}

catch(ThrowableexceptName)

{

System.out.println(“Exception!!!-TheThrowableExceptioncaughtthefollowingerror:”+“\n”);

exceptName.printStackTrace();

}

}

}

}

Figure7.19–PrintStackTraceMethod

Page 147: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

ProgramOutput:Exception!!!-Cannotdivideanumberbyzero

Whatis33/2?16

Whatis55/4?13

Whatis77/6?12

Whatis99/8?12

Exception!!!-TheThrowableExceptioncaughtthefollowingerror:

java.lang.ArrayIndexOutOfBoundsException:5

atExceptionHandling.ThrowableMethod.main(ThrowableMethod.java:14)

Line21definesthesecondcatchblockwithanexceptionobject“exceptName”thatwillbeusedtodisplaytheexceptionvalueLine24createstheprintStackTrace()methodbyusingtheexceptionobjectfollowedbythedotoperator

Page 148: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

ThrowvsThrowsThekeyword“throw”isusedtoexplicitlythrowanexception.AnobjectoftheexceptionparentclassThrowablemustbecreatedtothrowanexception.Therearetwowaystomanuallythrowanexception:

1. Useaparameterinthecatchblock2. Createanobjectusingthenewoperator

Thefollowingisthesyntaxformanually/explicitlythrowinganexception:

SyntaxthrowexcObject

Thefollowingisanexampleofthrowinganexceptionusingthenewoperator:

publicclassThrowTest

{

intDivideByZero(intnum1,intnum2)

{

if(num2==0)

{

System.out.println(“Anerrorhasnotbeenthrown”);

thrownewArithmeticException(“Exception!!!-Cannotdivideanumberbyzero”);

}

else

{

returnnum1/num2;

}

}

publicstaticvoidmain(String[]args)

{

try

{

ThrowTestobjThrow=newThrowTest();

System.out.println(objThrow.DivideByZero(34,0));

}

Page 149: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

catch(Exceptionexc)

{

System.out.println(exc.getMessage());

}

finally

{

System.out.println(“Performanactionifexceptionthrownornot“);

}

}

}

Figure7.20–ThrowExceptionExample

ProgramOutput:Anerrorhasnotbeenthrown

Exception!!!-Cannotdivideanumberbyzero

Performanactionifexceptionthrownornot

Line10createsanexplicitexceptionusingkeywords“throw”and“new”.Thekeyword“new”isusedtoconstructaninstanceof“ArithmeticException”withaStringparameter.Line24passesthevalues“34and0”tomethod“DivideByZero”whichstartsatline5.Parametervariable“num2”receiveszero“0”whichcausestheexceptionLine28displaysthestringparameterfromline10bycallingmethod“getMessage”

Page 150: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

Thekeyword“throws”isusedtoexplicitlydefineexceptionsthatamethodmightthrow.Therefore,amethodcallmusthandlealloftheexceptionsifadeclaredmethodhasoneormoreexceptionsusingthekeyword“throws”.Thefollowingisanexampleusing“throws”todefineanexceptionlist:

SyntaxmethodTypemethodName(parameter-list)throwsexc-list{//MethodBody}

Thefollowingisanexampleusing“throws”todefineanexception:

publicclassThrowsKeywordTest

{

staticvoidthrowMethod()throwsNullPointerException

{

System.out.println(“Anerrorhasnotbeenthrown”);

thrownewNullPointerException(“Exception!!!-NullPointer”);

}

publicstaticvoidmain(String[]args)

{

try

{

throwMethod();

}

catch(NullPointerExceptionexc)

{

System.out.println(“ExceptionType“+exc);

}

}

}

Page 151: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

Figure7.21–ThrowsExceptionExample

Line5definesanexception“NullPointerException”usingthekeyword“throws”.Multipleexceptionscanbecreatedbywayofacomma-separatedlistofexceptionsthatthemethodmightthrow.Line15callsmethod“throwMethod”whichhasanexceptionLine19displaystheNullPointerException

Thefollowingdescribesthedifferencesbetweenthrowandthrows:

Throw Throws

Canthrowoneexception Candeclaremultipleexceptions

Followedbyaninstance Followedbyanexceptionclass

Usedwithinamethod’sbody Usedwithinamethod’ssignature

Figure7.22–ThrowvsThrows

Page 152: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

DebuggingAtsomepointwhiledevelopingaprogram,theprogramwillconsistoferrorsand/orexceptions.Thekeyforeveryprogrammeristolearnhowtodebugtheprogram.Debuggingistheprocessofdetectingandremovingunexpectedconditionsfromtheprogram.AnIDEsuchasEclipseprovidesadebuggertoolwhichfacilitatethedebuggingprocess.Thetoolallowsaprogrammertoexecutetheircodeline-by-linetoviewwhatishappeningoneachline.

Page 153: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

Breakpoints

Tostartthedebuggingprocess,abreakpointmustbeplacedintheprogram.Thepurposeofbreakpointsistopauseexecutionoftheprogram.Asaresult,theprogramrunsuptothebreakpointuntilthedebuggerreceivesadditionalinstructionsonwhattodonext.Aprogramcanhaveseveralbreakpointssetorclearedatanytime.Thefollowingisalistofwaystosetorclearabreakpoint:

1. Double-clicktheleftofthedesiredlinenumber2. Movethecursortotheleftofthedesiredlinenumber,right-clickthemouse,then

selectToggleBreakpoint3. Movethecursortothedesiredlineandpressshortcutkeys(Ctrl+Shift+B)

Abluedotislocatednexttothelinenumberaftersettingthebreakpoint.Next,theprogrammermustopentheDebugperspectivewhichprovidesacombinationofviewsandeditorstodebugaprogram.TheDebugperspectivecanbeopenedthefollowingways:

1. PressF112. Right-clickinsidetheprogram,selectDebugAs,thenJava3. ClickRunthenselectDebugAs,thenJavaApplication4. Shortcutkeys(Alt+Shift+D,J)

Note:SelectYeswhenEclipsedisplaysaConfirmPerspectiveSwitchdialogue.

Figure7.23–ConfirmPerspectiveSwitchScreenshot

Page 154: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

ThefollowingisascreenshotoftheDebugperspective:

Figure7.24–DebugPerspectiveScreenshot

Page 155: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

StepThroughTheProgram

Steppingthroughtheprogramiswhenthedebuggersteps/executesalineofcodeonelineatatime.Theprocessofsteppinghelpstheprogrammerunderstandhowthelogicworks.FunctionkeysF5,F6,F7,andF8controlexecutionofsteppingthroughtheprogram.

StepInto(F5)–Executesonlythecurrentcodeline.Thedebuggerpausesateverylineofcodethatissteppedintoincludingacalledmethod.StepOver(F6)–Executesthecurrentmethodwithoutdisplayingeverystep.Thedebuggerstaysinthemainroutinewhilethesubroutinesexecuteinthebackground.StepReturn(F7)–Executesthecurrentmethodinthebackgroundwhilereturningtothemethodthatwassteppedinto.Resume(F8)–Executesuntilthenextbreakpoint

Chapter7discussederrors,exceptions,anddebugging.Anerrorisaproblemintheprogram.Thethreetypesoferrorsaresyntax,runtime,andlogical.Exceptionsareerrorsthatoccuratruntime.However,anexceptionhandlerallowsablockofcodetomanagetheexceptions.Thereforetheexceptionallowsexecutiontocontinueafterrespondingtotheproblem.Debuggingisaprocessthatpermitsaprogrammertodetectandresolveallerrors.Chapter8isanintroductionJava’sinput/outputsystem.

Page 156: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

Chapter8UtilizingInputandOutput

Java’sInput/Output(I/O)package“java.io”containsmanyclasses,interfaces,andmethods.Thepackageprovidesinputandoutputstreamsthatreads/writesdata.Dataisreadfromaninputsourceandwrittentoanoutputdestination.Aninputsourceandoutputdestinationisanythingthatcontainsinformationsuchasafile,string,ormemory.Inputisdatareceivedbytheprogramandoutputisdatasentfromtheprogram.Aprogramcanbeawebbrowserwhichreceivesandsendsdata.

ChaptereightisanintroductionwhichcoversthefollowingregardingJava’slargeInput/Outputsystem:

Streams

FileInput/Output

Page 157: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

StreamsProgramsinJavaperforminputandoutputthroughstreams.Streamsrepresentasequenceofdatathatisreadorwritten.Thereforestreamshavetheabilitytopassdataorperformtransformationsondata.AccordingtoOracle,theInputStreamclassisanabstractsuperclassofallclassesrepresentinganinputstreamofbytes.TheOutputStreamclassisanabstractsuperclassofallclassesrepresentinganoutputstreamofbytes.ThereforetheI/Oclassesisanabstractionthatsuppliesorconsumesinformation.Streamsprovideavarietyofdataformats.

Page 158: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

ByteStreams

BytestreamclassesarederivedfromanInputStreamandOutputStream.Programsusingbytestreamsprovidefunctionalityandmanagedetailsofreading/writing.Thefollowingisalistofbytestreamclasses.

ByteStream Description

BufferedInputStream Addsfunctionalitytoanotherinputstream-namely,theabilitytobuffertheinputandtosupportthemarkandresetmethods

BufferedOutputStream Implementsabufferedoutputstream

ByteArrayInputStream Inputstreamthatreadsfromabytearray

ByteArrayOutputStream Outputstreamthatwritestoabytearray

DataInputStream AninputstreamthatincludesmethodsforreadingtheJavastandarddatatypes

DataOutputStream AnoutputstreamthatincludesmethodsforwritingtheJavastandarddatatypes

FileInputStream Inputstreamthatreadsfromafile

FileOutputStream Outputstreamthatwritestoafile

InputStream Abstractclassthatisthesuperclassofallclassesrepresentinganinputstreamofbytes

ObjectInputStream Inputstreamforobjects

ObjectOutputStream Outputstreamforobjects

OutputStream Abstractclassthatisthesuperclassofallclassesrepresentinganoutputstreamofbytes

PipedInputStream Providesdatabytesthatarewrittentothepipedoutputstream

PipedOutputStream Connectedtoapipedinputstreamtocreateacommunicationspipe

Page 159: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

PrintStream Outputstreamthatcontainsprint()andprintln()

PushbackInputStream Inputstreamthatallowsbytestobereturnedtothestream

SequenceInputStream Representsthelogicalconcatenationofotherinputstreams.

Figure8.1–ByteStream

ThefollowingisalistofInputStreammethods:

InputStreamMethod Description

abstractintread() Readsthenextbyteofdatafromtheinputstream

booleanmarkSupported() Testsifthisinputstreamsupportsthemarkandresetmethods

intavailable() Returnsanestimateofthenumberofbytesthatcanberead(orskippedover)fromthisinputstreamwithoutblockingbythenextinvocationofamethodforthisinputstream

intread(byte[]b) Readssomenumberofbytesfromtheinputstreamandstoresthemintothebufferarrayb

intread(byte[]b,intoff,intlen)

Readsuptolenbytesofdatafromtheinputstreamintoanarrayofbytes

longskip(longn) Skipsoveranddiscardsnbytesofdatafromthisinputstream

voidclose() Closesthisinputstreamandreleasesanysystemresourcesassociatedwiththestream

voidmark(intreadLimit) Marksthecurrentpositioninthisinputstream

Page 160: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

voidreset() Repositionsthisstreamtothepositionatthetimethemarkmethodwaslastcalledonthisinputstream

Figure8.2–InputStreamMethods

ThefollowingisalistofOutputStreammethods:

OutputStreamMethods

Description

abstractvoidwrite(intb)

Writesthespecifiedbytetothisoutputstream

voidclose() Closesthisoutputstreamandreleasesanysystemresourcesassociatedwiththisstream

voidflush() Flushesthisoutputstreamandforcesanybufferedoutputbytestobewrittenout

voidwrite(byte[]b) Writesb.lengthbytesfromthespecifiedbytearraytothisoutputstream

voidwrite(byte[]b,intoff,intlen)

Writeslenbytesfromthespecifiedbytearraystartingatoffsetofftothisoutputstream

Figure8.3–OutputStreamMethods

Page 161: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

CharacterStream

CharacterstreamclassesarederivedfromReaderandWriterwhichoffersimilarmethodsasInputStreamandOutputStream.ThecharacterstreamclassmanagesI/Oparallelingthebytestreamclass.Unicodecharactersaretranslatedfromcharacterstreamclasses.Thefollowingisalistofcharacterstreamclasses:

CharacterStream Description

BufferedReader Readstextfromacharacter-inputstream,bufferingcharacterssoastoprovidefortheefficientreadingofcharacters,arrays,andlines.

BufferedWriter Writestexttoacharacter-outputstream,bufferingcharacterssoastoprovidefortheefficientwritingofsinglecharacters,arrays,andstrings.

CharArrayReader Thisclassimplementsacharacterbufferthatcanbeusedasacharacter-inputstream.

CharArrayWriter ThisclassimplementsacharacterbufferthatcanbeusedasanWriter.

FileReader Convenienceclassforreadingcharacterfiles.

FileWriter Convenienceclassforwritingcharacterfiles.

FilterReader Abstractclassforreadingfilteredcharacterstreams

FilterWriter Abstractclassforwritingfilteredcharacterstreams

InputStreamReader AnInputStreamReaderisabridgefrombytestreamstocharacterstreams:Itreadsbytesanddecodesthemintocharactersusingaspecifiedcharset

LineNumberReader Abufferedcharacter-inputstreamthatkeepstrackoflinenumbers

OutputStreamWriter AnOutputStreamWriterisabridgefromcharacterstreamstobytestreams:Characterswrittentoitareencodedintobytesusinga

Page 162: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

specifiedcharset

PipedReader Pipedcharacter-inputstreams

PipedWriter Pipedcharacter-outputstreams.

PrintWriter Printsformattedrepresentationsofobjectstoatext-outputstream.

PushbackReader Acharacter-streamreaderthatallowscharacterstobepushedbackintothestream.

Reader Abstractclassforreadingcharacterstreams

StringReader Acharacterstreamwhosesourceisastring.

StringWriter Acharacterstreamthatcollectsitsoutputinastringbuffer,whichcanthenbeusedtoconstructastring

Writer Abstractclassforwritingtocharacterstreams

Figure8.4–CharacterStream

Page 163: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

BufferedStreams

Bufferedinputstreamsreaddatafromamemoryareaknownasabuffer.Ontheotherhand,bufferedoutputstreamswritedatatoabuffer.InJava,majorityofthestreamsareunbufferedmeaningeachreadorwriterequestismanageddirectlybytheoperatingsystem(OS).AmanagementrequestbyanOSmakeprogramslessefficientduetoarequesttriggeringanexpensiveoperation.

BufferedI/Ostreamsisimplementedtoreduceoverheadbyadministeringadedicatedspaceinmemory.Thededicatedspacestoresdatainanefficientmanner.Forinstance,thebufferedinputstreamisonlycalledwhenthebufferisemptyandbufferedoutputstreamsareonlycalledwhenthebufferisfull.Therefore,thefourfollowingbufferclassescanbeusedtowraparoundabyteorcharacterI/Ostream:

BufferClasses Description

BufferedInputStream Suppliesbufferingtooutputstreams

BufferedOutputStream Suppliesbufferingtoinputstreams

BufferedReader Readstextfromacharacterinputstream

BufferedWriter Writestexttoacharacteroutputstream

Figure8.5–BufferedStreams

Page 164: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

DataStreams

DatastreamsserveasafoundationforStringvalues,binaryinput,andoutputofprimitivedatatypessuchasboolean,byte,char,double,float,int,long,andshort.ADataInputorDataOutputinterfaceisimplementedbyallofthedatastreams.TheDataInputinterfaceprovidesmethodsforreadingwhileDataOutputinterfaceprovidesmethodsforwritingallofJava’sprimitivetypes.DataInputStreamimplementstheDataInputinterfaceandDataOutputStreamimplementstheDataOutputinterface.ThefollowingisalistofmethodsforDataInputStreamandDataOutputStream:

DataInputStreamMethod Description

booleanreadBoolean() Readsabooleaninputfromthefile

bytereadByte() Readsabyteinputfromthefile

charreadChar() Readsacharinputfromthefile

doublereadDouble() Readsadoubleinputfromthefile

floatreadFloat() Readsafloatinputfromthefile

intreadInt() Readsaintinputfromthefile

longreadLong() Readsalonginputfromthefile

shortreadShort() Readsashortinputfromthefile

Figure8.6–DataInputStreamMethods

DataOutputStreamMethod

Description

voidwriteBoolean(booleanv)

Writesabooleanoutputtothefile

voidwriteByte(intv) Writesabyteoutputtothefile

voidwriteChar(intv) Writesacharoutputtothefile

voidwriteDouble(doublev) Writesadoubleoutputtothefile

Page 165: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

voidwriteFloat(floatv) Writesafloatoutputtothefile

voidwriteInt(intv) Writesaintoutputtothefile

voidwriteLong(longv) Writesalongoutputtothefile

voidwriteShort(intv) Writesashortoutputtothefile

Figure8.7–DataOutputStreamMethods

Page 166: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

StandardStreams

JavaprovidessupportforstandardI/Osoaprogramreceivesinputfromakeyboardandproduceoutputontothecomputermonitor.AclasscalledSystemwithinthejava.langpackageincludesthreestandardstreamvariables:in,out,anderr.System.inisanInputStreamobjectwhileSystem.outandSystem.errarePrintStreamobjects.PrintStreamallowsformatteddatatobewrittentoanOutputStream.Thefollowingisadescriptionofthestandardstreams:

StandardStream Description

StandardInput (System.in)/BydefaultthekeyboardStandardInputcontrolswheretheprogramreceivesinput

StandardOutput (System.out)/BydefaulttheconsoleStandardOutputcontrolswheretheprogramsendsoutput

StandardError (System.err)/BydefaulttheconsoleStandardErrorusedtooutputanerrorsuppliedbytheprogram

Figure8.8–StandardStreams

Page 167: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

FileInput/OutputFilesarestoredandorganizedsotheycanberetrievedandaccessedinaconvenientmanner.InJava,therearetwopackages“java.io.fileandjava.nio.fio”setasideforfiles.Package“java.nio.file”isthenewerfilesystemlabeledNIO2meaning“NewInput/Output2”.NIO2identifiesinterfacesandclassestoaccessfiles,fileattributes,andfilesystems.

Page 168: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

Path

Mostfilesarearrangedinahierarchical(knownastree)structure.Therootnode(i.e.,C:\)islocatedatthetopofthehierarchyfollowedbyfoldersandfiles.Allfoldershavetheabilitytoincludeadditionalfoldersandfiles.Auniquepathidentifiesaspecificresource(fileorfolder)withinatree.Thereforethepath“C:\java4selenium\input_output\test.txt”indicatesafilenamed“test”islocatedinafoldernamed“input_output”withinanotherfoldernamed“java4selenium”.ThefollowingarecommonPathInterfacemethodsforJava’sfilesystem:

PathConversion

toAbsolutePath()ReturnsaPathobjectcharacterizingtheabsolutepathtoRealPath(LinkOption…options)ReturnstherealpathofanexistingfiletoUri()ReturnsaURItocharacterizethispath

RetrievePathInformation

getFileName()ReturnsthenameofthefileorlastelementinthePathobjectgetName(intindex)ReturnsthePathelementcorrespondingtothespecifiedindexgetNameCount()ReturnsthenumberofnameelementsinthepathgetParent()ReturnstheparentpathornullgetRoot()Returnsthepath’srootnormalize()Returnsapathwithredundantnameelementseliminated

Page 169: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

resolve(Pathother)Resolvethespecifiedpathagainstthispathrelativize(Pathother)ConstructsarelativepathbetweenthispathandaspecifiedpathsubPath(intbeginIndex,intendIndex)ReturnsthesubsequenceofthePathindicatedbystartingandendingindicestoStringReturnsthepath’sstringrepresentation

Page 170: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

Files

Filescanbecreated,deleted,moved,copied,andverifiedforexistence.Bothpackages“java.io.fileandjava.nio.fio”includemethodswhichread,write,andmanipulatefilesandfolders.ThefollowingarecommonmethodswithinbothpackagesforJava’sfilesystem:

CheckExistenceMethods

exists(Pathpath,LinkOption…options)TestsiftheresourceexistnotExists(Pathpath,LinkOption…options)Testsiftheresourcelocatedbythispathdoesnotexist

CheckStatusMethods

isDirectory(Pathpath,LinkOption…options)TestsiftheresourceisadirectoryisExecutable(Pathpath)TestsiftheresourceisexecutableisFile()TestsiftheresourceindicatedbythisabstractpathnameisanormalresourceisReadable(Pathpath)TestsiftheresourceisreadableisSameFile(Pathpath,Pathpath2)TestsiftworesourceslocatethesameresourceisWritable(Pathpath)Testsiftheresourceiswritable

CopyMethod

copy(Pathsource,Pathtarget,CopyOption…options)Copytheresourcetoaspecifiedtarget

Page 171: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

CreateMethod

createFile(Pathpath,FileAttribute<?>…attrs)Createsanewandemptyresource

DeleteMethod

Delete(Pathpath)Deletestheresource

Note:Foldersmustbeemptybeforeitcanbedeleted

DirectoryMethods

list()ReturnsanarrayofstringsnamingtheresourcesanddirectoriesinthedirectoryindicatedbythisabstractpathnamelistFiles()Returnsanarrayofabstractpathnamesindicatingthefilesinthedirectoryindicatedbythisabstractpathname

MoveMethod

move(Pathsource,Pathtarget,CopyOption…options)Moveorrenametheresourcetoatarget

ReadMethods

readAllBytes(Pathpath)ReadsallthebytesfromtheresourcereadAllLines(Pathpath,Charsetcs)Readalllinesfromtheresource

Page 172: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

SpaceMethods

length()ReturnsthelengthoftheresourceindicatedbythisabstractpathnamegetFreeSpace()ReturnsthenumberofunallocatedbytesinthepartitionnamedbythisabstractpathnamegetTotalSpace()ReturnsthesizeofthepartitionnamedbythisabstractpathnamegetUsableSpace()Returnsthenumberofbytesavailabletothisvirtualmachineonthepartitionnamedbythisabstractpathname

WriteMethods

write(Pathpath,byte[]bytes,OpenOption…options)Writesbytestotheresourcewrite(Pathpath,Iterable<?extendsCharSequence>linesCharsetcs,OpenOption…options)Writelinesoftexttotheresource

Page 173: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

ConclusionJavaisapopularobject-orientedprogramming(OOP)languagecenteredaroundobjects.Thegoalof“Part2–Java4SeleniumWebDriver”wastoprovidedeepconceptsofJava.OneofthebenefitsofJavaistheabilitytoreusecode.Thefollowingaretake-awaytopicsfromthisbook:

Classes:Aclassisatemplateforobjectswhichcontainsdataandcodethatoperatesonthedata.

Objects:Objectsarethefoundationtoobject-orientedprogramming.Itconsistsoftwocharacteristics:stateandbehavior.Stateidentifiestheobjectandbehaviorrepresenttheactionsoftheobject.

Methods:Amethodisablockofcodethatperformaspecifictask.

Inheritance:Inheritanceisahierarchicalconceptwhichallowsreusablecodeandobjectstobeextended.

Package:Apackageisacollectionofrelatedclasses.

Interface:Aninterfaceisacollectionofrelatedmethods.

Error:Anerrorisanunavoidableprobleminaprogram.

Exceptions:Anexceptionisanerrorthatoccursatruntime

Debugging:Debuggingistheprocessofdetectingandremovingunexpectedconditionsfromtheprogram.

Page 174: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

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

2.JavaABeginner’sGuideSixthEditionCreate,Compile,andRunJavaProgramsTodayHerbertSchildt

3.ORACLEJavaDocumentationTheJavaTMTutorialshttps://docs.oracle.com/javase/tutorial/java/javaOO/returnvalue.htmlhttps://docs.oracle.com/javase/7/docs/api/https://docs.oracle.com/javase/7/docs/api/java/io/package-summary.html#package_description

4.ProgramCreekhttp://www.programcreek.com/2009/02/diagram-for-hierarchy-of-exception-classes/

5.TIOBEhttp://www.tiobe.com/tiobe_index

6.Dictionary.comhttp://www.dictionary.com/browse/object?s=thttp://www.dictionary.com/browse/annotation?s=t

Page 175: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

BooksbyRexJonesII1. FreeBookAbsoluteBeginner

(Part1)YouMustLearnVBScriptforQTP/UFTDon’tIgnoreTheLanguageForFunctionalAutomationTesting

2. (Part2)YouMustLearnVBScriptforQTP/UFTDon’tIgnoreTheLanguageForFunctionalAutomationTesting

3. FreeBookAbsoluteBeginner(Part1)Java4SeleniumWebDriverComeLearnHowToProgramForAutomationTesting

4. (Part2)Java4SeleniumWebDriverComeLearnHowToProgramForAutomationTesting

ComingSoon

5. FreeBookAbsoluteBeginner(Part1)SeleniumWebDriverforFunctionalAutomationTestingYourBeginnersGuideToBecomeGood

6. (Part2)SeleniumWebDriverforFunctionalAutomationTestingYourGuideToStayEffective

Page 176: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming
Page 177: Free Webinars, Videos, and Live Trainingtisten.ir/.../12/Java-4-Selenium-WebDriverPart-2.pdf · According to TIOBE, Java is the most popular programming language within the programming

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