Lecture 6
Lecture 6
Unit 1
Lecture 6
Syntax of Method
<access_modifier> <return_type>
<method_name>( list_of_parameters)
{
//body
}
Advantage of Method
• Code Reusability
• Code Optimization
Method Declaration
Method Declaration
In general, method declarations have 6 components:
1.Modifier: It defines the access type of the method i.e.
from where it can be accessed in your application. In Java,
there 4 types of access specifiers.
• public: It is accessible in all classes in your application.
• protected: It is accessible within the class in which it is
defined and in its subclass/es
• private: It is accessible only within the class in which it is
defined.
• default: It is declared/defined without using any modifier. It
is accessible within the same class and package within which
its class is defined.
Note: It is Optional in syntax.
2. The return type: The data type of the value
returned by the method or void if does not return a
value. It is Mandatory in syntax.
3. Method Name: the rules for field names apply to
method names as well, but the convention is a little
different. It is Mandatory in syntax.
4. Parameter list: Comma-separated list of the input
parameters is defined, preceded by their data type,
within the enclosed parenthesis. If there are no
parameters, you must use empty parentheses (). It is
Optional in syntax.
5. Exception list: The exceptions you expect by the
method can throw, you can specify these
exception(s). It is Optional in syntax.
6. Method body: it is enclosed between braces.
The code you need to be executed to perform
your intended operations. It is Optional in
syntax.
Example
class Addition {
// Initially taking sum as 0
// as we have not started computation
int sum = 0;
// Method
// To add two numbers
public int addTwoInt(int a, int b)
{
// Adding two integer value
sum = a + b;