In Java
Function & advantages
A program module which can be called at different
instances in a program to perform a specific task.
Advantages:
Reuse of code
Memory optimisation
Divides complex task into small methods-modular
approach
Components
public static void main(String args[])
public int add(int a,int b,int c)//formal parameters
{//method block
} inbuilt, user defined functions
protected double add(int a,double b)//header or
prototype
add(int a,double b)-Method signature
Access specifier, return, method block.
type,name,parameter list
return statement
Used at the end of the function
Returns only one value
Methods, types and invoking
The process of using a method in a program is referred
to as calling or invoking
Static and non static
Actual and Formal parameters
Pass by value
Pass by reference
Pure and Impure methods
Pass by reference/call by reference
import java.util.*;
public class passbyreference
{
public void ref(int a[])
{
int i,l;
l=a.length;
for(i=0;i<l;i++)
a[i]=a[i]+10;
System.out.println("array after adding 10");
for(i=0;i<l;i++)
System.out.print("formal"+a[i]+"\t");
}
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int a[]={10,20,30,40,45};
int i;
int l=a.length;
passbyreference ob=new passbyreference();
ob.ref(a);
for(i=0;i<l;i++)
System.out.print("actual"+a[i]+"\t");
}
}
Output- change in formal parameters effect
actual parameters as both refer to same address
array after adding 10
formal20 formal30 formal40 formal50 formal55
actual20 actual30 actual40 actual50 actual55
Function Overloading
int area(int l,int b)
int area(int s)
int area(double r)
Methods with same name but having different
parameter list( difference in number of parameters or
data type of parameters), compiler checks for the best
match at the compile time and invoke the respective
function.