1.

Java Methods

Answer»

A method is a collection of statements or a series of statements organised together to conduct a specific task or action. It’s a technique for making code more reusable. We create a method once and then use it repeatedly. We don’t have to write code over and over again. It also allows for easy code modification and readability by simply adding or removing code chunks. Only when we call or invoke the method is it executed.

Method Declaration:- Method properties such as visibility, return type, name, and parameters are all stated in the method declaration. As seen in the following diagram, it consists of six components known as method headers.

Method signature - A method signature is a statement that identifies a method. It’s included in the method declaration. It contains the method name as well as a list of parameters.

Access Specifier - The method’s access specifier, also known as a modifier, determines the method’s access type. It specifies the method’s visibility. There are four different types of access specifiers in Java:



  • public: When we utilise the public specifier in our application, all classes can access the method.


  • private: The method is only accessible in the classes in which it is declared when we use a private access specifier.


  • protected: The method is accessible within the same package or subclasses in a different package when we use the protected access specifier.


  • default: When no access specifier is specified in the method declaration, Java uses the default access specifier. It can only be seen from the same package.

Return Type - The data type that the method returns is known as the return type. It could be a primitive data type, an object, a collection, or void, for example. The void keyword is used when a method does not return anything.

Method name - The name of a method is defined by its method name, which is a unique name. It must be appropriate for the method’s functionality. If we’re making a method for subtracting two numbers, the name of the method must be subtraction (). The name of a method is used to call it.

Parameter List - The parameter list is a collection of parameters separated by a comma and wrapped in parentheses. It specifies the data type as well as the name of the variable. Leave the parenthesis blank if the method has no parameters.

Method body - The method declaration includes a section called the method body. It contains all of the actions that must be completed. It is protected by a pair of curly braces.




Discussion

No Comment Found