Page 115 - 2617_JSSPS_C-7
P. 115
Predefined Methods
The methods that are already defined in the packages of Java and available to use in the form of class
library are called predefined methods. They are also known as built-in methods. To use these methods,
we first have to import the package in which the class exists that contains the desired methods.
Examples of predefined methods are CharAt() and next(). To use the predefined methods, we need to
create an object of the class under which the function is defined.
For example,
Scanner sc = new Scanner (System.in); // Defining the object "sc"
String s = sc.next(); // Using the function next()
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.
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
Method body System.out.println(i + j);
body 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.
Different Components of a Method
The various components of a method are:
Header of Method
Method Signature
Access Specifier
Return Type and Return Statement
Java Programming 113

