0% found this document useful (0 votes)
16 views

5 User Defined Methods

Uploaded by

Vedant Utekar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

5 User Defined Methods

Uploaded by

Vedant Utekar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 67

Chapter 5

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.

Lorven public school, chandapura 2


Example
int m=5,n=6, i;
int f1=1, f2=1;
for (i=1; i<=m; i++)
{
f1=f1 * i;
}
System.out.println(“Factorial of” +m+“ is” + f1);
for (i=1; i<=n; i++)
{
f2=f2 * I;
}
System.out.println(“Factorial of” +n+“ is” + f2);

Lorven public school, chandapura 3


Example
int m=5, n=6, fact1=0,fact2=0;
fact ( int x)
{
f=1;
for(i=1; i<=x ; i++)
f=f * i;
System.out.println(“factorial of” +x+“ is” + f);
}
fact(m);
fact(n);

Lorven public school, chandapura 4


Advantages of a method
◦ It reuses the segment of operations, as and when necessary, by simply using the
method name.
◦ It divides the complex computational task into a collection of smaller method so that
problem solving becomes easier, object-specific and modular.
◦ A program that uses a method occupies less memory space and executes faster.

Lorven public school, chandapura 5


Defining a method
◦ The general form:
<access specifier> <Return type> <method name> (parameter list)
{
statement;
_____________
_____________
return(value)
}

Example:
public int add(int x, int y) Method header
{
int sum;
Sum=x+y;
return (sum); Body of method
}

Lorven public school, chandapura 6


Lorven public school, chandapura 7
Components of a method
◦ Modifier-: Defines access type of the method i.e. from where it can be accessed in
your application. In Java, there 4 type of the access specifiers.
◦ public: accessible in all class in your application.

◦ 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.

Lorven public school, chandapura 8


Components of a method
◦ Method name : Every method has a name by it is identified. It should be preferably
related to the process it is being carried out.

◦ The parameter list in parenthesis : a comma-delimited list of input parameters,


preceded by their data types, enclosed by parentheses, (). If
there are no parameters, you must use empty parentheses.

◦ The method body, enclosed between braces : the method's code, including the
declaration of local variables.

Lorven public school, chandapura 9


Components of a method
◦ The method signature : Method signature is the identification of a method. it signifies a
method to be invoked for a specific task. A method signature is
written using its name along with its parameters to be passed to
the method.

ex: add (a , b);

◦ Return statement : The statement that send back the value (result) from a method
to its caller program is known as return statement.

Syntax: return <value>

ex : return(sum)

Lorven public school, chandapura 10


Features of return statement.
◦ It is always used at the end of the method.
◦ No statement will be executed after return statement.
◦ It can return return a single value to its caller.
◦ If a function has more than one termination points, then it can have more than one
return statements.
if (a>b)
return a;
else
return b;
◦ Even if there multiple return statements are implied in the method any one of return
statement will be executed.

Lorven public school, chandapura 11


Features of return statement.
◦ Once the control exits from the method , it can not return back unless the method is
called again.
{
for(I =1; i<=10; i++)
{
if (i>5)
return(i);
System.out.println(i);
}
}

Lorven public school, chandapura 12


Invoking a method
◦ A process of using a method in a program is referred to as ‘Calling a method’ or
‘Invoking a method’
◦ To invoke a method, first a object of the class has be created.
◦ Using the object name the method can be invoked.
example:
ob. add(x, y)

Lorven public school, chandapura 13


E
X
A
M
P
L
E
Lorven public school, chandapura 14
Static method
◦ https://www.geeksforgeeks.org/static-methods-vs-instance-methods-java/
◦ Static methods are the methods in Java that can be called without creating an object
of class. They are referenced by the class name itself or reference to the Object of that
class.
◦ Static method(s) are associated to the class in which they reside i.e. they can be called
even without creating an instance of the class i.e ClassName. methodName(args).
◦ They are designed with aim to be shared among all Objects created from the same
class.
◦ Static methods can not be overridden. But can be overloaded since they are resolved
using static binding by compiler at compile time.

Lorven public school, chandapura 15


Lorven public school, chandapura 16
Actual and formal parameters
Formal parameters
Class Addition System.out.println(“Enter two numbers to be added”);
{ a=in.nextInt();
int Add( int m, int n)
b=in.nextInt();
{
Addition obj=new Addition();
int sum=0;
sum=m+n;
Actual parameters
p=obj.Add(a,b);
return(sum);
System.out.println(“Sum=“+p);
}
public static void main(String args[])throws IOException }
{
int a, b, p;
Scanner in =new Scanner();

Lorven public school, chandapura 17


Different ways of defining a function
1. Receiving value and returning outcome to the caller.(parameterized method)

public static void main(String args[])


class Factorial
{
{
Public int fact(int x) Factorial ob=new Factorial();
{ Int n=5, m=8,p,q;
Int i,f=1; P=ob.fact(n);
for(i=0 ; i<=x ; i++) Q=ob.fact(m);
f*=I; System.out.println(“Factorial of “+n+”is”+p);
return(f);
System.out.println(“Factorial of “+m+”is”+q);
}
}}
Lorven public school, chandapura 18
Different ways of defining a function
2. Receiving values but not returning outcome to the caller.

class Factorial public static void main(String args[])


{ {
Public void fact(int x) Factorial ob=new Factorial();
{
int n=5, m=8;
int i,f=1;
for(i=0 ; i<=x ; i++) ob.fact(n);
f*=I; ob.fact(m);
System.out.println(“Factorial of “+x+”is”+f); }
}
}

Lorven public school, chandapura 19


Different ways of defining a function
3. Neither receiving values nor returning outcome to the caller.(non-parameterized)

class Factorial public static void main(String args[])


{
{
Public void fact()
{ Factorial ob=new Factorial();
Int n=5, f=1,i; ob.fact();
for(i=0 ; i<=n ; i++) }
f*=i;
}
System.out.println(“Factorial of “+n+”is”+f);

Lorven public school, chandapura 20


Ways of passing values to a function
◦ Java allows you to pass the value to function in two ways;
◦ Pass by value
◦ Pass by reference public static void main(String args[])

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
}

Lorven public school, chandapura 21


Lorven public school, chandapura 22
call

Lorven public school, chandapura 23


Pass by reference
◦ Call by Reference means calling a method with a parameter as a reference. Through
this, the argument reference is passed to the parameter.
◦ It creates a copy of references and passes them as valuable to the methods. As
reference points to same address of object, creating a copy of reference is of no harm.
But if new object is assigned to reference it will not be reflected.

Lorven public school, chandapura 24


Lorven public school, chandapura 25
Lorven public school, chandapura 26
Side effects of call by Reference

Lorven public school, chandapura 27


Pure Functions
◦ Functions are mostly used to perform some computational operations.
◦ A function is called pure function if it always returns the same result for same argument
values and it has no side effects like modifying an argument (or global variable) or
outputting something.
◦ The pure function is a returnable function.
◦ It does not cause in the state of any object.
◦ Examples of pure functions are strlen(), pow(), sqrt() etc.
◦ Thus A function which returns a value to its caller module is called a ‘Pure function’.
◦ It is also called accessor method, as it doesn’t change the states of an object.

Lorven public school, chandapura 28


Pure function demonstration
Class sample System.out.println(“The actual arguments before

{ performing task : “ +p);

int Show(int a) System.out.println(“The actual arguments after


{ performing task : “ +k);
a=2*a+5;
}
return(a);
}
}
Public static void main(String args[])
{

Sample ob=new Sample();


int p=5,k;
k=ob.Show(p);

Lorven public school, chandapura 29


Impure functions
◦ Impure functions area called mutater methods or simply mutators.
◦ They cause change to the state of an object.
◦ That means, values of the object’s instance variables get modified or changed depen
ding on the current state of the object on which the function operates.
◦ Examples of impure functions are random(), time(), etc.
◦ https://www.learnsteps.com/pure-impure-functions/

Lorven public school, chandapura 30


Impure functions demonstration
Class sample Public static void main(String args[])
{ {
void Add(int x[]) int a[]={3,6,8,9};
{ int j,q;

int i,p; q=a.length;


p=x.length; Sample ob=new Sample();
for(i=0; i<p ; i++) Ob.Add(a);
x[i]=x[i]+2; System.out.println(“The arguments after function call:”);
System.out.println(“The change during For (i=0; j<q;j++)
function call:”);
System.out.print(a[j]+” “);
for(i=0; i<p ; i++)
System.out.println();
{
}
System.out.println(x[i]+” “);
}
System.out.println();
}
}
}

Lorven public school, chandapura 31


Lorven public school, chandapura 32
Function overloading
◦ Designing the functions with same name and different parametric types are called
overloaded functions.
◦ The process is said to be function overloading.
◦ It implements polymorphism.
◦ On invoking the function it finds the best match of the function parameters to ensure
which of the overloaded function us called.
◦ This phenomenon is known as early binding or static binding.
◦ The methods with same name are treated as same if the number of arguments and
type of arguments are same.
◦ Hence the functions must have different type or number of arguments.

Lorven public school, chandapura 33


Example
➢Valid overloaded function protypes
int area(int a, int b);
Double area (double a, double b);
Double area (int a, double b);
➢Invalid function prototypes
int area( int a, int b);
int area (int x, int y);

Lorven public school, chandapura 34


Program to find the area of

the following geometrical

figures to illustrate function

overloading where

• Area of circle 𝐴 = 𝜋𝑟 2

• Area of square = a2

• Area of rectangle = L * B

Lorven public school, chandapura 35


Recursive
functions
➢ Some time a function is required to be
called in the body of the same function in
order to encourage the recitative operations
of a number of times.
➢ A function designed in such a way that it
calls itself in its body is called a Recursive
function.

Lorven public school, chandapura 36


Lorven public school, chandapura 37
Lorven public school, chandapura 38
Lorven public school, chandapura 39
Lorven public school, chandapura 40
Lorven public school, chandapura 41
Lorven public school, chandapura 42
Lorven public school, chandapura 43
Lorven public school, chandapura 44
Lorven public school, chandapura 45
Lorven public school, chandapura 46
Lorven public school, chandapura 47
Lorven public school, chandapura 48
Lorven public school, chandapura 49
Lorven public school, chandapura 50
Lorven public school, chandapura 51
Lorven public school, chandapura 52
Lorven public school, chandapura 53
Lorven public school, chandapura 54
Lorven public school, chandapura 55
Lorven public school, chandapura 56
Lorven public school, chandapura 57
Lorven public school, chandapura 58
Lorven public school, chandapura 59
Lorven public school, chandapura 60
Lorven public school, chandapura 61
Lorven public school, chandapura 62
Lorven public school, chandapura 63
Lorven public school, chandapura 64
Lorven public school, chandapura 65
Lorven public school, chandapura 66
Lorven public school, chandapura 67

You might also like