We can also create methods of our own choice to perform some task. Such methods are called user-defined methods.As we know that methods is a block of codes or set of statements which when execute it perform a particular task.
Syntax
<Access specifier> <returnType> <nameOfMethod> <(Parameter List)> {
// method body (block of codes)
}
The syntax shown above includes −
Access specifier − It defines the access type of the method and it is optional to use.
returnType − Method may return a value.
nameOfMethod − This is the method name. The method signature consists of the method name and the parameter list.
Parameter List − The list of parameters, it is the type, order, and number of parameters of a method. These are optional, method may contain zero parameters.
method body − The method body defines what the method does with the statements.
//to find minimum of two numbers
public static int minFunction(int n1, int n2) {
int min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}
For using a method, it should be called.It is very simple to call a method, for calling a method we need to create object of class if method is non static otherwise simply we can call bye name.
//to find minimum of two numbers
class demo
{
public int minFunction(int n1, int n2) {
int min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}
public static void main(String [] args)
{
demo obj=new demo(); //no need of object if function will be static.
int min=obj.minFunction(20,30);
System.out.println("min="+min);
}
For complete details must watch this video lecture.
For Complete details must watch.
In this system the value from the actual parameters are copied to the formal parameters. Hence, any changes made in the formal parameter does not reflect actual parameters. The actual parameter remains unchanged.
In this system the reference from the actual parameters are copied to the formal parameters. Hence, any changes made in the formal parameter it reflect to actual parameters.
Must Watch this video lecture.