5 User Defined Methods
5 User Defined Methods
USER DEFINED
METHODS
By,
Ashw ini K S
Lorven public school, chandapura 1
Introduction
◦ What is Method?
◦ A Java method is a set of statements that are grouped together to perform an
operation.
◦ Methods are also known as Functions
◦ In Structured programming (ex: C Language) we use Functions (Built in and User
defined)
◦ In Object Oriented Programming we use Methods (Built in and User defined)
◦ When we choose Methods?
◦ Whenever we want to perform any operation multiple times then choose methods.
Example:
public int add(int x, int y) Method header
{
int sum;
Sum=x+y;
return (sum); Body of method
}
◦ protected: accessible within the class in which it is defined and in its subclass(es)
◦ private: accessible only within the class in which it is defined.
◦ default (declared/defined without using any modifier) : accessible within same class and
package within which its class is defined.
◦ The return type : the data type of the value returned by the method, or void if the
method does not return a value.
◦ The method body, enclosed between braces : the method's code, including the
declaration of local variables.
◦ Return statement : The statement that send back the value (result) from a method
to its caller program is known as return statement.
ex : return(sum)
class Factorial {
{ Factorial ob=new Factorial();
Public int fact(int x) int n=5;
{ ob.fact(n);
int i,f=i;
}
for(i=0 ; i<=x ; i++)
f*=i; }
System.out.println(“Factorial of “+x+”is”+f); Output
Factorial of 5 is 120
}
overloading where
• Area of circle 𝐴 = 𝜋𝑟 2
• Area of square = a2
• Area of rectangle = L * B