File 2. Functions
File 2. Functions
Syntax :
[access specifier] [access modifier] <return type>
<function name>(parameter list)
{
Body of the function
}
Example :
public static void main(int a, int b)
{
int c = a+b;
System.out.println(“Sum = “+c);
}
class C1
{
int x;//data member
//No argument(parameter) No return function
void display()//called fn
{
x=53; //data member accessed in function
System.out.println("My first oop");
System.out.println("Value of x = "+x);
}// return - go back to calling function
//argument, no return
void add(int a, int b)//called fn
{
int c=a+b;
1
System.out.println("Sum="+c);
} // -implicit return
//Argument, return
int product(int a, int b) //called fn
{
int c=a*b;
return c; //return statement is compulsory here
}
}
class C2
{
public static void main() //calling fn
{
C1 ob = new C1();
ob.display();//fn call stmt
int x,y,z;
x=12;
y=10;
ob.add(x,y);//fn call stmt
z=ob.product(x,y);
System.out.println("Product = "+z);
}
}
Signature
2
Practice Question 1 :
Write a prototype for a function check which checks the equality
between two integers received and returns 0 or 1.
Practice Question 2 :
Specify the function signature of the above check function.
Keyword void
When a function does not return a value, keyword(data type) void is
used as a return type of a function. It indicates that the function
returns to the calling function without a value.
3
Types of Functions:
5
Pure and impure functions
Functions that does not change the state of the received parameters
are pure functions. They are also called accessor or getter methods.
Generally, call by value functions are pure functions.
Functions that change the state of the received parameters are impure
functions. They are also called mutators or setter methods. Generally,
call by reference functions are impure functions.
Function Overloading :
More than one function in a class having the same name but differ in
signature is function overloading. It implements polymorphism.
Example:
class CalcArea
{
int area(int s)
{
return s*s;
}
double area(int l, int b)
{
return l*b;
}
double area(int b, double h)
{
return 0.5*b*h;
}
double area(double r)
{
return 3.14*r*r;
}
}