Methods in Java | Types, Method Signature, Example

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

Learn types of methods in java with example program, method declaration, method signature in java, instance, static method, predefined, user-defined ... Skiptocontent Menu MethodsinJavaarethebuildingblockofaJavaapplication.InJava, amethodisasetofcodeusedtowritethelogicoftheapplicationswhichperformsomespecifictasksoroperations. InJavaprogramming,amethodisexecutedwhenitiscalledfromanothermethod.Themain()methodisthefirstmethodthatisexecutedbyJVM(JavaVirtualMachine)injavaprogram.Ifwewanttowanttoexecuteanyothermethod,weshouldcallitfromthemain()method.Whenamethodiscalled,itreturnsavaluetothecallingmethod.Itcanalsoperformataskwithoutreturninganyvaluetothecallingmethod.AmethodcanbecalledfromanywhereinJavaprogram.Eachmethodhasasingleentrypointandasingleexit.WhydoweusemethodsinJava?ThepurposeofusingmethodsintheJavaprogramistowritethelogicoftheapplications.Let’stakeanexampleprogramtounderstandtheconceptofusingmethodsinjavaprogramming.Programsourcecode1:Inthisexampleprogram,weareperformingtheadditionoftwonumbers.classAddition { //Declaretwoinstancevariables. inta=10; intb=20; System.out.println(a+b);//Itisinvalidsyntaxbecauseinsidetheclass,wecannotwritedirectlythebusinesslogicoftheapplication.Therefore,wedeclarethemethodinsidetheclassandwritethelogicinsidethemethods. //Declarationofaninstancemethod. voidadd() { //Writelogicofaddingtwonumberandprintitontheconsole. System.out.println(a+b); } publicstaticvoidmain(String[]args) { Additiona=newAddition();//Objectcreation. a.add();//Callingmethod. } }Output: 30Fromtheaboveprogram,itisclearthatmethodsareusedtowritethebusinesslogicoftheapplicationorprogram.MethoddeclarationinJavawithExampleAmethodmustbedeclaredinsidetheclass.Ingeneral,amethodhassixfundamentalpartssuchasmodifiers,methodname,returntype,parameterlist,exceptionlist,andbody.Thebasicsyntaxtodeclareamethodisasfollows:Syntax:  method_modifier  return_type  method_name(Parameter_list)throwsExceptions  {   //Methodbody   }Let’sdiscusssomeimportantpointsaboutthesyntaxofmethod.1.Themethodmodifierdefinestheaccesstypeofamethodbutitisoptionaltouse.Itmaybedeclaredasstatic,final,abstract,synchronized,oroneoftheaccessspecifiersprivate,default,protected,andpublic.Thepublicistheleastrestrictiveaccessmodifierandtheprivateisthemost.2.Ifthemethodisabstract,theimplementationisomittedandthemethodbodyisreplacedwithasinglesemicolon.3.Thereturntypedefinesthetypeofdatathatcomesbackfromthemethodaftercallingit.MethodSignatureinJavaThemethodnamewithparameterlist(numberofparameters,typeofparameters,andorderofparameters)iscalledmethodsignatureinjava. Lookatsomeexamplesofmethodssignatureare:1.add(inta,intb):Numberofparametersis2,Typeofparameterisint. 2.m1(Stringname):Numberofparametersis1,TypeofparameterisString. 3.sub():Noparameter.Parameterlist:Theparameterlistisacomma-separatedlistofzeroormoreparameterdeclaration.Thebasicformtodeclaretheparameterlistis:Syntax:   parameter-modifier  data-type parameter-nameTheparameter-modifiermaybefinal.Iftheparameterisfinal,itcannotbemodifiedinsidethemethod.Thedata-typemaybeint,float,char,double,etc.Eachparameter-namemustbeadistinctname.Ifthereismorethanoneparameter,theyareseparatedbycommas.Iftherearenoparameters,youincludeanemptypairofparentheses().Themethodparameterlistmakesitpossibletopassthevaluetothemethod.Itisdeclaredinsidetheparenthesesafterthemethodname.Thescopeoftheparameterlistisinsidethemethodbodybuttheseareoptional.Themethodmayalsocontainzeroparameters.Methodbody:Themethodbodyisablock-statementthatcontainsstatementsaswellasthedeclarationofthelocalvariablesandlocalclasses.Themethodbodymayalsocontainreturnstatements.Ifthereturntypeisvoid,themethodcanperformataskwithoutreturninganyvalue.Suchamethodiscalledvoidmethod.Therewillbenoreturnstatementinsidethemethodbody.Ifthereturntypeisnon-voidbutadata-typelikeint,float,double,etc,themethodwillreturnavalue.Itwillnotbepossibleforexecutiontoreachtheendofthemethodbodywithoutexecutingareturnstatement.KeyPoints:1.Thereturntypeandexceptionsarenotpartofthemethodsignature.2.Themethodnameshouldbefunctionalitynamerelatedtologic.3.Theexceptionsmaybethrownbythemethods.Inthiscase,youcanspecifytheexceptions.Herearesomeexamplesofdifferenttypesofmethoddeclarationinjava.1.publicvoidadd(inta,intb); //Here,addisthefunctionality/methodname.Itwillexecutewheneverwewillpassinputvaluesofaandb.Oncethefunctionalityiscompleted,voidrepresentsdon’treturnanyvalue.Thepublicisaccessmodifierswhichrepresentthatthismethodcanbeaccessedfromanywhere.2.privateintm2();//m2isfunctionality/methodnamewithnoargument.Oncethefunctionalityiscompleted,itmustreturnanintegervalue.Theprivateaccessmodifierrepresentsthatitcanbeaccessedonlywithintheclass.3.protectedintsub(inta)throwsException.TypesofMethodsinJavaGenerally,therearetwobasictypesofmethodsinJavabutprogrammerscandevelopanykindofmethoddependingonthescenario.1.Predefinedmethods 2.User-definedmethods(Programmer-definedmethods)PredefinedmethodsinJavawithExampleProgramPredefinedmethodsinJavaarethosemethodsthatarealreadydefinedintheJavaAPI(ApplicationProgrammingInterface)touseinanapplication. JavaProgramminglanguagecontainspredefinedclassesthatareorganizedindifferentpredefinedpackages.Withinthesepredefinedclasses,therearelocatedpredefinedmethods.Infact,Javahasover160predefinedpackagesthatcontainmorethan3000predefinedclasses.Theseclasseshavemanymorethousandsofindividualpredefinedmethods.AllareavailabletotheprogrammersviaJavaAPI.Lookatsomeexamplesbelow:1.print()isapredefinedmethodpresentinthepackagejava.io.PrintSteam.Theprint(“….”)printsthestringinsidethequotationmarks.2.sqrt()isamethodofMathclasswhichispresentinpackagejava.lang.Itcalculatesthesquarerootofanumber.Let’takeanexampleprogrambasedonjavapredefinedmethods.Let’stakeanexampleprogramwherewewillusesqrt()methodofMathclasstofindoutthesquarerootofnumber16.Programsourcecode2: packagepredefinedMethods; publicclassSquareRoot { publicstaticvoidmain(String[]args) { System.out.println("Squarerootof16:"+Math.sqrt(16)); } }Whenyouruntheaboveprogram,theoutputwillbe:Output: Squarerootof16:4.03.max()predefinedmethodreturnsthegreateroftwovalues.Let’sunderstanditwithanexampleprogram.Programsourcecode3:packagepredefinedMethods; publicclassMaxValue { publicstaticvoidmain(String[]args) { intnum1=20,num2=50,maxValue; maxValue=Math.max(num1,num2); System.out.println("Maxvalue:"+maxValue); } }Output: Maxvalue:50User-definedmethodsinJavawithExampleProgramUser-definedmethodsinJavaarethosemethodsthataredefinedinsideaclasstoperformaspecialtaskorfunctioninanapplication.Suchmethodsarecalleduser-definedmethods.Auser-definedmethodisalsoknownasprogrammer-definedmethod.Wecandeclaretwotypesofuser-definedmethodsinanapplication.1.InstanceMethod 2.StaticMethodInstanceMethodinJavaAninstancemethodisusedtoimplementbehaviorsofeachobject/instanceoftheclass.Sincetheinstancemethodrepresentsbehaviorsoftheobjects.Therefore,instancemethodislinkedwithanobject.Aninstancemethodisalsoknownasnon-staticmethod.So,withoutcreatinganobjectoftheclass,themethodscannotexisttoperformtheirdesiredbehaviorsortask.Itisallocatedintheheapmemoryduringtheobjectcreation.Hereisanexampleofaninstancemethoddeclaration:voidm1() {  //Thisareaiscalledaninstancedarea/Non-staticarea.  //logichere. }StaticMethodinJavaWhenyoudeclareanymethodwithastaticmodifier,itiscalledstaticmethodinjava.Astaticmethodislinkedwithclass.Therefore,itisalsoknownasaclassmethod.Itisusedtoimplementthebehavioroftheclassitself.Staticmethodsloadintothememoryduringclassloadingandbeforeobjectcreation.Anexampleofastaticmethoddeclarationisasfollows:staticvoidm2() { //Thisareaiscalledastaticarea. //logichere. }KeyPoints: 1.Aninstancemethodcanrefertostaticvariables(classvariables)aswellasforinstancevariablesoftheclass. 2.Astaticmethodcanrefertoonlystaticvariables.HowtoCallaMethodinJavaExecutingcodeinsidethebodyofamethodiscalledcallingamethod(orinvokingamethod)injava.Instancemethodsandstaticmethodsbotharecalleddifferentlyinaprogram.Let’sunderstandonebyone.CallingInstanceMethodinJava:Therearetwostepstocallaninstancemethodinjava.1.First,createanobjectofaclassbeforecallinganinstancemethodofthatclass. 2.Second,callthemethodwithareferencevariableusingthedotoperator.Thesyntaxtocallaninstancemethodisasfollows:Syntax:   instance_reference.instance_method_name(actualparameters);  Forexample: Youcanwritethefollowingcodetocallmsg()instancemethodofTestclass. //CreateanobjectofTestclassandstoresitsreferencein't'referencevariable.   Testt=newTest(); //Callmsg()byusingreferencevariable"t".   t.msg();CallingStaticMethodinJava: Tocallastaticmethod,weusedotoperatorwiththeclassname.Forexample: Thefollowingcodecallsm1()staticmethodofTestclass.Test.m1();KeyPoints: 1.Instancemethodusesdynamicbinding(latebinding). 2.Classmethodusesstaticbinding(earlybinding).Nowjustrememberthebelowpracticalconceptasshowninthefollowingfigure.Youcanmakethemethodscallingconcepteasy.Asshownintheabovefigure,therearetwotypesofareasinJava.Firstisinstanceareaandsecondisstaticarea.1.Ifyoucallinstancemembers(variablesormethods)frominstanceareawithinaninstancearea(i.e,samearea),youdon’tneedtouseobjectreferencevariableforcallinginstancevariablesormethods.Youcallitdirectly.2.Ifyoucallinstancevariablesormethodsfromtheinstanceareawithinthestaticarea(i.e,differentarea),youcannotcalldirectlythem.Youwillhavetouseobjectreferencevariablesforcallingthem.3.Ifyoucallstaticmembers(variablesormethods)fromthestaticareaorinstancearea,wedon’tneedtousetheclassnameforcallingthestaticmembers.Youcaninvokethemdirectly.4.Whenyouwanttocallstaticmembersfromoutsidetheclass,staticmemberscanbeaccessedbyusingtheclassnameonly.5.Whenamethodiscalledintheprogram,thecontrolofexecutiongetstransferredtothecalledmethod.HowtocallInstanceMethodinJavafromMainTocallaninstancemethodfromthemainmethodisverysimple.Justcreateanobjectoftheclassandcallthemethodusingthereferencevariable.Let’sunderstandasimpleexampleprogramtocallaninstancemethodfrommaininjava.Programsourcecode4:packagemethodProgram; publicclassAddition { //Instancearea/Non-staticarea. //Declarationofinstancevariables. inta=10; intb=20; //Declarationofinstancemethod. voidadd() { //Instancearea/Non-staticarea. //Withininstancearea,wecandirectlycalltheinstancevariablesfrominstancearea(Samearea)withoutusingobjectreferencevariable. System.out.println("Firstnumbera="+a); System.out.println("Secondnumberb="+b); //logicofaddition. intx=a+b; System.out.println("Additionoftwonumbersx="+x);//directlycalled. } publicstaticvoidmain(String[]args) { //Staticarea. //Createanobjectoftheclass. Additionad=newAddition(); //Sincewearecallinganinstancemethodfrominstanceareawithinthestaticarea.So,Objectreferencevariablewillbeused. ad.add(); } } Output: Firstnumbera=10 Secondnumberb=20 Additionoftwonumbersx=30HowtocallStaticMethodfromMaininJavaUsingclassname,wecandirectlycallastaticmethodfromthemainmethod.Let’stakeanexampleprogramwherewewillcallstaticmethodusingclassname.Programsourcecode5:packagemethodProgram; publicclassMultiplication { inta=20;//Instancevariable. //Declarestaticvariables. staticintc=40; staticintd=50; voidm1() { //Wecancalldirectlystaticvariablesfrominstancearea(Samearea)withoutusingclassname. System.out.println("Thirdnumberc="+c); System.out.println("Fourthnumberc="+d); } staticvoidmultiply() { //Staticarea. //Wecannotcalldirectlyinstancemembers/Non-staticmembersinthestaticarea. //System.out.println(x);//Invalidsyntax. intmNum=c*d; System.out.println("Multiplication:"+mNum); } publicstaticvoidmain(String[]args) { //Callstaticmethodusingclassname. Multiplication.multiply(); } }Output: Multiplication:2000Fromtheaboveprogram,Onequestionariseswhichisaskedbytheinterviewerintheinterview.WhycannotStaticmethoddirectlyaccessnon-staticmembers?Wecannotdirectlyaccessnon-staticmembersfromastaticmethod.Thatis,wecannotdirectlycallinstancememberswithinastaticareabecausethereisalogicalconceptbehindsuchrestriction.Staticmemberssuchasstaticvariables,methods,orblocksarelinkedwiththeclass.Therefore,theygetmemoryonlyoncewhentheclassisloadedinthememory.Butnon-staticmemberslikeinstancevariables,method,orblockgetmemoryaftertheobjectcreationoftheclass.Therefore,Ifwecallanynon-staticmembersfromthestaticarea,itmeansthatwhentheclassisloadedinthememory,thestaticmembersalsoloadedanditwilllookfornon-staticmemberswhicharenotinexistencebecausewehavenotcreatedaninstancetillnow.Hencethereisambiguity.That’swhywecannotcallthenon-staticmemberfromthestaticarea. Anon-staticmethodcanaccessstaticmembersinJava.wewilldiscussinthestatictutorial.Sincestaticmethodcannotaccessdirectlythenon-staticmembersbutifwecreatetheobjectoftheclasswithinthestaticmethod,Inthiscase,wecanaccessnon-staticmemberswithinthestaticmethod.Let’sseeanexampleprogrambasedonthestaticmethod.Programsourcecode6:packagemethodProgram; publicclassSubtraction { inta=40; intb=50; voidsub() { inty=a-b; System.out.println("Subtractionoftwonumbery="+y); } staticvoidsubtract() { //creatingtheobjectoftheclasswithinastaticareatocalltheinstancemembers. Subtractionst=newSubtraction(); st.sub(); } publicstaticvoidmain(String[]args) { subtract(); } }Output: Subtractionoftwonumbery=-10Programsourcecode7:packagecallingMethodExample; publicclassTest { voidm1() { m2();//Instancemethodcalling. System.out.println("m1iscalling"); } voidm2() { m3();//Staticmethodcalling. System.out.println("m2iscalling"); } staticvoidm3() { System.out.println("m3iscalling"); } staticvoidm4() { System.out.println("m4iscalling"); } publicstaticvoidmain(String[]args) { Testt=newTest(); t.m1(); m4(); Addition.sum();//here,wearecallingstaticmethodusingtheclassnamefromoutsidetheclassAdditionofprogramsourcecode2. } }Output: m3iscalling m2iscalling m1iscalling m4iscalling Fourthnumberd=50Let’sunderstandtheflowofexecutiondiagramofthisprogramasshowninthebelowfigure.Asyoucanseeintheabovefigureforprogram7,wearecallingm1()methodbutm1()methodiscallingm2().So,thecontrolofexecutionwillgotom2()butm2()iscallingstaticm3()method.Aftercompletingofm3(),onceagainthecontrolofexecutiongoestom2().Aftercompletionofm2(),thecontrolofexecutionagaingoestom1().Afterthat,staticm4()methodiscalledandprintingthemessageontheconsole.NowthecontrolofexecutiongoestoclassAdditionofprogramsourcecode2forcallingthestaticmethod.Hopethatthistutorialhascoveredthemostimportanttopicsrelatedtomethodsinjavawithexampleprograms.Ihopethatyouwillhaveunderstoodthistopicandenjoyedprogramming. Thanksforreading!!!Next⇒MainmethodinJava⇐ PrevNext⇒ LeaveaCommentCancelreplyYoumustbeloggedintopostacomment. JavaTutorialsJavaIntroduction1.WhatisJava|Creation,History2.FeaturesofJava|JavaBuzzwords3.WhatisJDK|JavaPlatform(Ecosystem)4.BytecodeinJava|BytecodevsMachinecode5.WhatisJRE,JavaAPI,ClassLoader6.WhatisJVMinJava,JVMArchitecture,JITCompiler7.JavaCompiler|Howworksit8.InterpreterinJava|InterpretervsCompiler9.DownloadJDK(JavaDevelopmentKit)inWindows10.FirstSimpleJavaProgram:HelloWorld11.DownloadEclipseIDEforJavaDevelopers12.SimpleJavaPrograminEclipse,Compile,Run13.CvsJava|26VitalDifferences14.22VitalDifferencebetweenC++andJava BasicsofJava1.JavaTokens|TypesofTokens2.JavaCharacterSet3.KeywordsinJava4.IdentifiersinJava|RulesofIdentifiers5.CommentsinJava|Types,Example6.EscapeSequenceinJava JavaClassandObject1.ClassesandObjectsinJava2.HowtocreateObjectsinJava3.ObjectDeclarationandInitialization4.LifeCycleofObject5.AnonymousObjectinJava6.TypesofClassesinJava JavaDatatypesandVariables1.DatatypesinJava2.Non-primitivedatatypes3.MemoryAllocationofDatatypes4.JavaVariables5.ScopeofVariablesinJava6.ConstantsinJava JavaOperators1.JavaOperators2.RelationalOperators3.LogicalOperators4.AssignmentOperators5.UnaryOperators6.ConditionalOperators7.BitwiseOperators8.ShiftOperators DecisionMaking,Branching,Looping1.ConditionalControlStatementsinJava2.IfStatementinJava|ExampleProgram3.IfelseinJava|Nestedif-else,Example4.LoopsinJava|Types:Nested,Infinite5.WhileLoopinJava6.JavaDoWhileLoop7.ForLoopinJava8.NestedForLoopinJava9.ForEachLoop(Enhancedforloop)10.SwitchStatementinJava|UseExample11.JavaBreakStatement,ExampleProgram12.ContinueStatementinJava,ExampleProgram13.LabelledLoopinJava|ExampleProgram JavaPackages1.JavaPackages JavaMethods1.MethodsinJava2.JavaMainMethod3.ArgumentsandParameters4.CallbyValueandCallbyReference5.HowtocallMethodswithParametersinJava6.JavaReturntype JavaConstructor1.ConstructorinJava2.ConstructorOverloading3.ConstructorChaining4.CopyConstructor5.PrivateConstructorinJava|Use,Example JavaModifiers1.AccessModifiers2.Non-accessModifiers3.AccessModifiersInterviewQuestionsAnswers BlocksinJava1.JavaBlocks JavaStaticandFinalKeywords1.StaticVariable2.StaticMethods3.CanweoverrideStaticmethodinJava4.StaticBlock5.FinalKeyword InnerClassesinJava1.JavaInnerClass2.NormalInnerClass3.MethodLocalInnerClass4.AnonymousInnerClass5.StaticNestedClass OOPsConceptsinJava1.OOPsConcepts2.Top32+OOPsInterviewQuestions JavaEncapsulation1.JavaGetterandSetter2.Encapsulation3.Top5EncapsulationProgramsinJavaforPractice4.12JavaEncapsulationInterviewQuestionsAnswers InheritanceinJava1.Inheritance2.SuperclassandSubclasses3.BehaviorofAccessmodifiersincaseofInheritance4.TypesofInheritance5.10JavaInheritanceInterviewProgramsforPractice6.Top50JavaInheritanceInterviewQuestionsAnswers7.ClassRelationshipsinJava8.Has-ARelationshipinJava9.AssociationinJava10.AggregationinJava11.CompositioninJava12.AssociationvsAggregationvsComposition JavaSuperandThiskeywords1.Superkeyword2.Thiskeyword3.DifferencebetweenSuperandThis JavaOverloading1.MethodOverloadinginJava2.WhentouseMethodoverloadinginJavaProject3.TypeConversionandCasting4.AutomatictypePromotioninMethodoverloading5.ClassCastinginJava6.JavaUpcastingandDowncastingwithExample7.JavaMethodOverloadingInterviewProgramsforPractice JavaOverriding1.MethodOverridinginJava2.CovariantReturntypeinJava3.RulesofExceptionHandlingwithMethodOverriding4.DifferencebetweenMethodOverloadingandMethodOverriding5.MethodHidinginJava6.DynamicMethodDispatchinJava7.Top15JavaMethodOverridingInterviewProgramsforPractice JavaAbstraction1.JavaAbstraction|AbstractClass2.ExtendingandImplementingInterfaceinJava3.RealtimeUseofInterfaceinJavaApplicationinJava4.NestedInterfaceinJava5.12DifferencebetweenAbstractclassandInterface6.JavaClassvsInterface7.40JavaAbstractClassInterviewQuestionsAnswers8.50JavaInterfaceInterviewProgrammingQuestions9.DefaultMethodinJava8Interface10.InterfaceStaticMethodinJava8 JavaPolymorphism1.Compiletime,RuntimePolymorphisminJava2.StaticandDynamicBindinginJava3.Top32InterviewQuestionsonPolymorphism



請為這篇文章評分?