Methods In Java - Tutorial With Programming Examples

文章推薦指數: 80 %
投票人數:10人

Java Method Types Skiptocontent Menu MENUMENUHomeResourcesFREEeBooksQATesting FreeQATrainingTestCasesSDLCTestLink SoftwareTestingBugZillaMobileTestingJIRA AgileMethodologyDatabaseTestingETLTesting QualityAssuranceTestManagementSAPERPTesting Courses SoftwareTesting(LIVECourse)Selenium(LIVECourse) SoftwareTestingSeleniumQTP/UFTJIRAVideosRubyCucumber Automation AutomationTestingSoapUIJIRAAppiumKarateFramework SeleniumQTP/UFTALMQCPostman JMeterLoadRunnerAPITestingRobotFramework TestNGJUnitEclipseMaven TypesOfTesting AllTestingTypesRegressionTestingUnitTestingSmokeTesting FunctionalTestingIntegrationTestingSystemTestingUsabilityTesting UATTestingBetaTestingBlackBoxTestingWhiteBoxtesting LoadTestingStressTestingSecurityTestingPerformanceTesting Tutorials C++C#DevOpsVBScriptTeamManagementComputerNetworkingJest PythonJAVAUNIXSVNAngularJSSpockLaravel SpecFlowJSONFlaskSOAtestMockitoKarma MachineLearningBlockchainGitHubGatlingWiremock Data OraclePL/SQL DataWarehouseExcelVBA BigDataJDBC MongoDB Menu MENUMENUHomeResourcesFREEeBooksQATesting FreeQATrainingTestCasesSDLCTestLink SoftwareTestingBugZillaMobileTestingJIRA AgileMethodologyDatabaseTestingETLTesting QualityAssuranceTestManagementSAPERPTesting Courses SoftwareTesting(LIVECourse)Selenium(LIVECourse) SoftwareTestingSeleniumQTP/UFTJIRAVideosRubyCucumber Automation AutomationTestingSoapUIJIRAAppiumKarateFramework SeleniumQTP/UFTALMQCPostman JMeterLoadRunnerAPITestingRobotFramework TestNGJUnitEclipseMaven TypesOfTesting AllTestingTypesRegressionTestingUnitTestingSmokeTesting FunctionalTestingIntegrationTestingSystemTestingUsabilityTesting UATTestingBetaTestingBlackBoxTestingWhiteBoxtesting LoadTestingStressTestingSecurityTestingPerformanceTesting Tutorials C++C#DevOpsVBScriptTeamManagementComputerNetworkingJest PythonJAVAUNIXSVNAngularJSSpockLaravel SpecFlowJSONFlaskSOAtestMockitoKarma MachineLearningBlockchainGitHubGatlingWiremock Data OraclePL/SQL DataWarehouseExcelVBA BigDataJDBC MongoDB LastUpdated:August7,2022 Inthistutorial,wewilllearntheconceptofMethodsinJavadetail.WewilllearnthefollowingconceptsrelatedtoJavamethods:  Javamethodtypes MethodSyntax Howtocallthemethod Parameters,Arguments,andReturnValues AccessModifiers MemoryallocationforMethodcalls MethodOverloading Simpleprogrammingexamplesarealsoincludedforclarity. =>CheckOutThePerfectJavaTrainingGuideHere. WhatYouWillLearn:JavaMethodTypesMethodsProvidedByStandardJavaLibraryMethodsDefinedByUsersJavaMethodSyntaxHowToCallAMethodByInvokingMethodOnTheClassByInvokingMethodOnTheClassInstanceMultipleMethodCallsParametersAndArgumentsReturnValuesWhenAMethodReturnsAnyValueWhenAMethodDoesNotReturnAnyValue(VoidMethod)AccessModifiersMemoryAllocationForMethodCallsMethodOverloadingFAQConclusionRecommendedReading JavaMethodTypes Let’shavealookatthefollowingsampleJavaprogram: packagecom.softwaretestinghelp; publicclassDemoClass{ publicstaticvoidmain(String[]args){ System.out.println("Hello,thisissampleprogram"); doubled=Math.random(); System.out.println("RandomNumber:"+d); } } Asseeninthesamplecode,thisprogramjustretrievesarandomnumberandprintsit,that’sit!Ifwehaveacloserlook,wehaveused2methodsinthemain()methodasshownbelow. System.out.println() Math.random() WehavenotdefinedthesemethodsintheclassDemoClass;wearejustusingthealreadyavailablemethodsthatarecalledasStandardlibrarymethods. Javamethodscanbeclassifiedintotwodifferentcategories: MethodsprovidedbyStandardJavalibrary MethodsdefinedbyUsers MethodsProvidedByStandardJavaLibrary JavaprovidesmanyreadilyavailablemethodsintheJavastandardlibrary.TheselibrariesareprovidedbytheclasslibraryofJava.ThislibraryexistsinaJavaarchivefilethatbecomesavailablealongwiththeJavaRuntimeEnvironment(JRE)andJavaVirtualMachine(JVM). ToconsumetheselibrariesinourJavacode,ajarfilecalledstdlib.jarneedstobeaddedtotheJavaclasspath.SomeofthestandardlibrarymethodswecommonlyuseareMathlibrarymethodslikeMath.random(),Math.sqrt(),orStringmethodslikeequals()tocomparetwostringsorconcat()tojointwostrings. MethodsDefinedByUsers Alongwiththereadymadestandardlibrarymethods,adevelopercancreatehis/hermethodaswelltoperformacertaintask.ThesemethodsarecalledasUserDefinedmethods.Tocreateourmethods,wefirstneedtounderstandtheconceptsandrulestocreatemethods. So,let’sunderstandtheJavamethodsyntaxtodefineourownJavamethod. JavaMethodSyntax WhileconsideringthedefinitionofthetermMethod,Methodsareconsideredasproceduresassociatedwithaclass. Insimpleterms,themethodisacodeblockhavingacollectionofstatementstoperformcertainactions.Thisblockofcoderunswhenthemethodisinvoked.Dataknownasparameterscanbepassedtothemethod. Herethebasicquestioncouldbe,whatisthepurposeofusingmethods?theanswertothisis,toreusethecodei.e.whenacodeisdefinedonceinamethoditcanbeusedmanytimes. Let’sseethesyntaxofthemethod.Beforethat,let’sseethefollowingsamplemethod. }publicstaticvoidsampleMethod(inta,intb)throwsArithmeticException{ System.out.println("Hello,thisissamplemethod");//<-Methodbody intc=a/b; System.out.println("c:"+c); } Givenbelowisthesyntaxofthemethod: modifiernon-access_modifierreturnTypemethodName(parameters)throwsExceptionexceptionName{ //methodbody } #1)Modifiers:Thesearetheaccesstype.ForExample,public,private,etc.Also,wecanspecifya non-accessmodifierlike‘static’. #2)Returntype:Whenthemethodreturnsanyvalue,itsdatatypeisspecified.Ifthemethoddoesnotreturnanyvalue,thenthemethodisspecifiedas‘void’. #3)Methodname:ThisisthenameofthemethodwhichfollowsconventionssomewhatsimilartotheJavafieldnames. #4)Parameters:Thisisalistofinputparameternameswithdatatypesseparatedbyacomma.Thisisenclosedbyparentheses().Itisanemptyparenthesesifnoparametersaretobespecified. #5)Anexceptionlist:Thisisacomma-separatedlistofexceptionsthatcanbethrownbythemethod. #6)Themethodbody:Thisistheplacewherethemethodcodegoes.Itisenclosedbetweenbraces.i.e.{} Withthisunderstanding,let’shavearelookatthesamplemethodtomapthesewiththesamplemethodthatwesaw: HowToCallAMethod Now,aswehaveseenthesyntaxofthemethod,let’sseehowwecanusethemethod. ByInvokingMethodOnTheClass packagecom.softwaretestinghelp; publicclassDemoClass{ publicstaticvoidsampleMethod(inta,intb)throwsArithmeticException{ System.out.println("Hello,thisissamplemethod"); intc=a/b; System.out.println("c:"+c); } publicstaticvoidmain(String[]args){ DemoClass.sampleMethod(4,2); } } HereistheprogramOutput: Hello,thisissamplemethod c:2 Here,themethodisdefinedasstatic.Hence,thismethodcanbecalledwithoutcreatinganinstanceofaclass.So,itisdirectlyinvokedontheclassi.e.DemoClass.sampleMethod(4,2) ByInvokingMethodOnTheClassInstance packagecom.softwaretestinghelp; publicclassDemoClass{ publicvoidsampleMethod(inta,intb)throwsArithmeticException{ System.out.println("Hello,thisissamplemethod"); intc=a/b; System.out.println("c:"+c); } publicstaticvoidmain(String[]args){ newDemoClass().sampleMethod(4,2); } } HereistheprogramOutput: Hello,thisissamplemethod c:2 Here,themethodisnotdefinedasstatic.Hence,tocallthismethod,aclassinstancehasbeencreatedfirstandthemethodisinvokedonaninstanceofaclassi.e.newDemoClass().sampleMethod(4,2) MultipleMethodCalls Wecaninvokethesamemethodmultipletimesasseeninthebelowsampleprogram: packagecom.softwaretestinghelp; publicclassDemoClass{ publicstaticvoidsampleMethod(inta,intb)throwsArithmeticException{ System.out.println("Hello,thisissamplemethod"); intc=a/b; System.out.println("c:"+c); } publicstaticvoidmain(String[]args){ DemoClass.sampleMethod(4,2); DemoClass.sampleMethod(4,2); DemoClass.sampleMethod(6,2); } } HereistheprogramOutput: Hello,thisissamplemethod c:2 Hello,thisissamplemethod c:2 Hello,thisissamplemethod c:3 ParametersAndArguments Parameters Asseenintheabovesamplemethod,whilecallingthemethod,wearepassinginformationtothemethod.Thisinformationiscalledasparameters.ForExample, asseeninsampleMethod(inta,intb),aandbarecalledasparameters.Theseparametersworkasvariablesinsidethemethod. packagecom.softwaretestinghelp; publicclassDemoClass{ publicstaticvoidsampleMethod(inta,intb)throwsArithmeticException{ System.out.println("Hello,thisissamplemethod"); intc=a/b; System.out.println("c:"+c); } publicstaticvoidmain(String[]args){ DemoClass.sampleMethod(4,2); } } Inthemethodsyntax,wehaveseenthatparametersarespecifiedinsideparenthesesi.e.().AsseeninsampleMethod(inta,intb),aandbaretheparametersspecifiedinsidetheparenthesis. Theseparameter’sdatatypehastobespecifiedwiththeparametername.ForExample,thedatatypeofparameteraisspecifiedasint.ThisdatatypecanbeanyvalidJavadatatypeasString,double,etc.,andalsoanyobjecttype. Wecanspecifyanynumberofparameters,theseparametershavetobeseparatedbycomma.ForExample,(inta,intb,doublec,Stringd),etc. Arguments Whenwecallamethod,theactualvaluesarepassedforparameterswhicharecalledArguments.ForExample,whenweareinvokingsampleMethod(),wearepassingactualvaluesi.e.4and2toDemoClass.sampleMethod(4,2); Here,alistofactualvalueswearepassingi.e.ArgumentsshouldhaveanexactmatchtotheParameterlisti.e.anumberofparametersandtheirdatatype. ForExample, So,Value4getsassignedtoparametera Value2getsassignedtoparameterb ActionsonaandbinsidesampleMethod()takeplaceaccordingly publicstaticvoidsampleMethod(inta,intb)throwsArithmeticException{ System.out.println("Hello,thisissamplemethod"); intc=a/b;//intc=4/2whichgetscalculatedas2 System.out.println("c:"+c);//c:2 } ReturnValues EverymethodexecutesJavastatementswritteninthemethodbodytoperformintendedactionstogettheintendedresultandthenthemethodcanalsoreturntheresultvaluetotheinvokingmethod. WhenAMethodReturnsAnyValue [1]Datatypeofreturnvalueneedstobespecifiedinthemethod. [2]returnstatementneedstobewrittenattheendofthemethod. packagecom.softwaretestinghelp; publicclassDemoClass{ publicstaticintsampleMethod(inta,intb)throwsArithmeticException{ //[1]intasdatatypeofreturnvalue System.out.println("Hello,thisissamplemethod"); intc=a/b;//intc=4/2getscalculatedas2 System.out.println("c:"+c);//c:2 returnc;//returnstatement } publicstaticvoidmain(String[]args){ intx=DemoClass.sampleMethod(4,2);//returnvalueisassignedtovariablex System.out.println("x:"+x);//x:2 } } HereistheprogramOutput: Hello,thisissamplemethod c:2 x:2 Aswehaveseenhere,therehastobeonereturnstatement.However,insomemethods,youwillfindmultiplereturnstatementsi.e.intheif-elseloop,likeif-elseifloopasseenbelow. packagecom.softwaretestinghelp; publicclassDemoClass{ publicstaticStringgetGrade(intpercentage){ if(percentage>=60){ System.out.println("Agrade"); return"Agrade";//Returnstatement }elseif(percentage>=40){ System.out.println("Bgrade"); return"Bgrade";//Returnstatement }else{ System.out.println("NotEligible"); return"NotEligible";//Returnstatement } } publicstaticvoidmain(String[]args){ System.out.println("Hello,thisissampleprogram"); Stringgrade=DemoClass.getGrade(70); System.out.println("Grade:"+grade); } } WhenAMethodDoesNotReturnAnyValue(VoidMethod) Whenthemethoddoesnotreturnanyvaluebacktoitscallingmethod,thenthereturndatatypeofthemethodisspecifiedasvoid. packagecom.softwaretestinghelp; publicclassDemoClass{ publicstaticvoidsampleMethod(inta,intb)throwsArithmeticException{ //[1]voidasmethoddoesnotreturnanyvalue System.out.println("Hello,thisissamplemethod"); intc=a/b;//intc=4/2whichcomesas2 System.out.println("c:"+c);//c:2//Noreturnstatement } publicstaticvoidmain(String[]args){ DemoClass.sampleMethod(4,2);//Noresultvalueisreturnedfromthemethod } } HereistheprogramOutput: Hello,thisissamplemethod c:2 AccessModifiers WehavealreadyseenamethodthatcanbedeclaredasstaticwhereweinvokeamethodontheclassitselflikeDemoClass.sampleMethod().Also,whenamethodisnotdeclaredasstatic,thenitiscalledaninstancemethodi.e.methodhastobeinvokedfromaninstanceofaclass,ForExample,newDemoClass().sampleMethod(). Also,themethodcanbedeclaredasprivate,public,protected,anddefaultsimilartoaJavafield. MemoryAllocationForMethodCalls InJava,memorymanagementisdonethroughHeapandStacks.HeapisaplacewheretheJavaobjectsarestored.Inthecaseofmethods,themethodcallsaremanagedbyStacks. Whenamethodisinvoked,thestackframeiscreated,andargumentsarepassed,andthemethod’sreturnedvalueisstored.Onmethodexecutioncompletion,thatallocatedstackframegetsdeleted. MethodOverloading InoursampleJavaprogram,wesawhowasampleMethod(inta,intb)canbedefinedandused.So,canwehavemorethanonemethodwiththesamenamei.e.canwedefinemultiplemethodswiththenamesampleMethod()inthesameclassDemoClass? TheanswertothisisYes.Considerascenario,ifwewanttodefineamethodtoaddtwonumbers.Butthesevaluescouldbe2integernumbersor2doublenumbers.Insuchascenario,wehave2differentmethodswiththesamenameasaddNumbers(). ThisbehavioriscalledMethodOverloadingi.e.definingmultiplemethodsintheclasswiththesamenameprovidedthesemethodshaveadifferentnumberofparametersand/ordifferenttypesofparameters. Let’shavealookatthebelowsampleprogram: packagecom.softwaretestinghelp; publicclassMethodsDemoClass{ publicstaticvoidadd(inta,intb){ System.out.println("Hello,thisisaddmethod"); intc=a+b; System.out.println("c:"+c); } publicstaticvoidadd(doublea,doubleb){ System.out.println("Hello,thisisaddmethod"); doublec=a+b; System.out.println("c:"+c); } publicstaticvoidmain(String[]args){ MethodsDemoClass.add(4,2); MethodsDemoClass.add(4.2,2.3); } } HereistheprogramOutput: Hello,thisisaddmethod c:6 Hello,thisisaddmethod c:6.5 FAQ Q#1)HowdoyoucreateaMethodinJava? Answer:User-definedmethodsarecreatedaspertheJavamethodsyntaxi.e.methoddeclarationwithmethodbodyisasfollows: modifiernon-access_modifierreturnTypemethodName(parameters)throwsExceptionexceptionName{ //methodbody } ForExample: publicstaticvoidsomeCalculation(intx,inty)throwsArithmeticException{ intz=x/y; } Q#2)WhatarethetypesofMethodsinJava? Answer:TherearetwotypesofmethodsinJava: MethodsprovidedbyStandardJavalibrary MethodsdefinedbyUsers Q#3)WhatisthemainMethodinJava? Answer:Themain()methodisconsideredasastartingpointtoanapplicationasthisispredefinedandconfiguredintoJVM.ToexecuteaJavaprogram,JVMlooksforthemain()methodandexecutesstatementsinsidethemain()method. Hereisthesyntaxofthemain()method: publicstaticvoid main(String[]args){} argsisanarrayofStringclass.Command-lineargumentsarepassedthroughtheargsparameter. Q#4)IsMethodandFunctionthesameinJava? Answer:TheconceptofMethod anda functionisthesame.AspertheOOPSprogrammingconcept,itisaprocedurethatisareusableblockofcodethatcanbecalledfromanywhereintheprogram.InJava,thetermusedforthisreusablecodeisMethod. Q#5)WhyaremethodsusedinJava? Answer:MethodsarewrittenintheJavaclasstoperformsomespecifictask.Usually,methodsarewrittenforsometasksthatmayberequiredtobeperformedmultipletimesintheJavaapplication.Methodssavetimeandefforttowritethesameblockofcodeeverytimewhenitisrequiredtoperformthesametask. ForExample, publicintadd(inta,intb){ returna+b; } Thus,themainpurposeofusingamethodisitsreusabilitytosavetime,effort,andimprovethereadabilityandmaintainabilityoftheJavaprogram. Q#6)Whatisprint()inJava? Answer:Javaprint()methodisusedtoprinttextontheconsoleandkeepthecursorattheendofthetext.i.e.whenthenextprint()methodisinvoked,textprintingstartsfromtheendofthislocation. AnyoftheprimitiveJavadatatypeorobjectcanbepassedasanargumentwhichgetsdisplayedontheconsoleastext. ForExample,void print(Strings):methodprintsastring. voidprint(ints):methodprintsintegervalue Javaalsohastheprintln()methodwhichfunctionsthesameastheprint()methodexceptforitscursorposition.Everytimewhentheprintln()methodiscalled,itprintsthetextandthecursorismovedtothestartofthenextline. Conclusion Inthistutorial,weexploredtheconceptofJavaMethodsindetail.Wesawthesyntaxofthemethodalongwiththeconceptofparameters-arguments,returntype,accessmodifiers,typeofmethods,andmethodoverloading. =>VisitHereForTheExclusiveJavaTrainingTutorialSeries. RecommendedReading JavaFloatTutorialWithProgrammingExamples JavaStringMethodsTutorialWithExamples JavaDouble-TutorialWithProgrammingExamples JavaStringcontains()MethodTutorialWithExamples JavaReverseString:TutorialWithProgrammingExamples JavaStringlength()MethodWithExamples JavaStringcompareToMethodWithProgrammingExamples TreeSetInJava:TutorialWithProgrammingExamples AboutSoftwareTestingHelpHelpingourcommunitysince2006! MostpopularportalforSoftwareprofessionalswith240million+visitsand300,000+followers!YouwillabsolutelyloveourcreativecontentonSoftwareToolsandServicesReviews! RecommendedReading JavaFloatTutorialWithProgrammingExamples JavaStringMethodsTutorialWithExamples JavaDouble–TutorialWithProgrammingExamples JavaStringcontains()MethodTutorialWithExamples JavaReverseString:TutorialWithProgrammingExamples JavaStringlength()MethodWithExamples JavaStringcompareToMethodWithProgrammingExamples TreeSetInJava:TutorialWithProgrammingExamples JOINOurTeam!



請為這篇文章評分?