Page 225 - CA_Blue( J )_Class10
P. 225
For example,
Scanner sc = new Scanner (System.in); // Defining the object "sc"
String s = sc.next(); // Using the function next()
10.2.2 User-defined Methods
A method written by the programmer according to his requirements is known as a user-defined method. It helps a
programmer to write customised code according to the needs of a program. An example of a user-defined function is
fact(), which is written by the programmer to calculate the factorial of a number.
10.3 DEFINING A METHOD
A programmer can define a function anywhere inside a class after declaring the data members. Following is the general
syntax to define a function:
<Access_Specifier> <Return_Type> <Method_Name> (parameters)
{
Block of statements;
}
Let us take an example:
Access Specifier
Method name
Return type
Parameters
public void sum (int i, int j)
{ Statement in the body
Method body System.out.println(i + j);
of the method
}
Here, sum is the name of the method. The keyword void specifies that the method does not return any value. The
public keyword specifies that the method can be accessed from anywhere inside the class and outside the class. In the
body of the method, the sum of the values in i and j is printed.
10.3.1 Different Components of a Method
The various components of a method are:
• Header
• Method Signature
• Access Specifier
• Return Type and Return Statement
• Method Name
• Parameters
• Body of the Method
Let us study these in details.
Header of Method
When a method is declared, the first line is known as the method header or method prototype. This line contains the
access specifier, return type, method name and a list of parameters. Let us consider the following example:
public int sum (int i, int j)
Parameter List
Method Name
Return Type
Access Specifier
223
User-defined Methods 223

