0% found this document useful (0 votes)
32 views38 pages

Computer PDF

Uploaded by

knandithareddy7
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views38 pages

Computer PDF

Uploaded by

knandithareddy7
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

User-defined Method

• The method written by the user or programmer is known as a


user-defined method. These methods are modified according
to the requirement.

Need/Advantages of Methods:
• It is used to achieve the reusability of code. We write a
method once and use it many times. We do not require to
write code again and again.
• It also provides the easy modification and readability of code,
just by adding or removing a chunk of code. The method is
executed only when we call or invoke it.
• The most important method in Java is the main() method.
Method Declaration/Method Definition
• The method declaration provides information about method
attributes, such as visibility, return-type, name, and arguments. It
has six components that are known as method header or method
prototype, as shown in the following figure.
The method definition can be divided into five main parts:
1. Access Specifier: Access specifier or modifier is the access
type of the method. It specifies the visibility of the method.
Java provides four types of access specifier:
i. Public: The method is accessible by all classes when we use
public specifier in our application.
ii. Private: When we use a private access specifier, the method
is accessible only in the classes in which it is defined.
iii. Protected: When we use protected access specifier, the
method is accessible within the same package or subclasses
in a different package.
iv. Default: When we do not use any access specifier in the
method declaration, Java uses default access specifier by
default. It is visible only from the same package only.
2. Return Type: Return type is a data type that the method
returns. It may have a primitive data type, object,
collection, void, etc. If the method does not return
anything, we use void keyword.
3. Method Name: It is a unique name that is used to define
the name of a method. It must be corresponding to the
functionality of the method. Suppose, if we are creating a
method for subtraction of two numbers, the method name
must be subtraction(). A method is invoked by its name.
4. Parameter List: It is the list of parameters separated by a
comma and enclosed in the pair of parentheses. It contains
the data type and variable name. If the method has no
parameter, left the parentheses blank.
5. Method Body: It is a part of the method declaration. It
contains all the actions to be performed. It is enclosed
within the pair of curly braces.
• Method Signature:
Every method has a method signature. It is a part of the
method declaration. It includes the method
name and parameter list.
Some examples:
Naming a Method
• While defining a method, remember that the method name
must be a verb and start with a lowercase letter.
• If the method name has more than two words, the first
name must be a verb followed by adjective or noun.
• In the multi-word method name, the first letter of each
word must be in uppercase except the first word. For
example:
• Single-word method name: sum(), area()
• Multi-word method name: areaOfCircle(),
stringComparision()
• Method Parameters:
Parameters are given in round brackets after the method
name in the heading of a method definition. A parameter
provides a mechanism for passing information to the method.
Within the body of the method , the parameter can be used in
the same way as a variable.
public int findCube(int x)
Notice that there is nothing in the method definition that
gives a value to the parameter. The parameter gets its initial
value from outside of the method. When the method is
invoked, a value must be provided for the parameter in the
method call statement. The corresponding argument in the
method definition is then initialised with the parameter value.
The parameter in the method invocation can be literal , a
variable, or any expression that yields a value of the
appropriate type.
Invoking Methods/Calling Methods:
• Once we have defined a method, it should be called. When we call
or invoke a user-defined method, the program control transfer to
the called method.
import java.util.Scanner;
public class EvenOdd
{
public static void main (String args[])
{
//creating Scanner class object
Scanner scan=new Scanner(System.in);
System.out.print("Enter the number: ");
//reading value from user
int num=scan.nextInt();
//method calling
findEvenOdd(num);
}
public static void findEvenOdd(int num)
{
//method body
if(num%2==0)
System.out.println(num+" is even");
else
System.out.println(num+" is odd");
}
}
Output 1:
Enter the number: 12
12 is even
Output 2:
Enter the number: 99
99 is odd
When a method is invoked:

• The invoke statement must provide all the parameter values.


• The type and number of parameters in the invoke statement must
match with those of the method prototype.
• The order of parameters in the invoke statement must match with
that of the method prototype.
For example:
The method prototype is:
public int samp(char c, int a, float b)
The invoke statement should be:
samp(‘a’,35,22.22);
When the method call statement is encountered:
1. The program control is transferred to the method definition.
2. The statements in the method body are executed.
3. The control transfers back to the calling statement.
Actual and Formal Parameters
The Parameters that appear in the method invocation are
called Actual Parameters. The Parameters that appear
in the method definition are called Formal Parameters.
public class Addition
{
public static void main(String[] args)
{
int a = 19;
int b = 5;
//method calling
int c = add(a, b); //a and b are actual parameters
System.out.println("The sum = " + c);
}
//user defined method
public static int add(int n1, int n2)
//n1 and n2 are formal parameters
{
int s;
s=n1+n2;
return s; //returning the sum
}
}
Output:
The sum = 24
Returning from Methods:
Just as invoking a method is important, returning
from a method is equally important. By invoking a
method, the program control transfers to the
invoked method. Once the method execution
finishes, the control transfers back to the invoking
statement. There are two ways in which the
control can transfer back to the invoking
statement:
1. The return statement is encountered in the
invoked method.
2. The last statement in the invoked method is
executed.
The Return Statement:
The method processes some data and give a value
that remains within the method unless it is returned
back to the invoking method.
Such methods specify the return value via return
statement.
Syntax: return expression;
The return statement can only be used inside the method
body. The data type of the return value must match the
type specified in the method header.
The return statement fulfills two purposes:
1. It returns a value to the calling statement.
2. It causes an exit from the method and transfers
control back to the calling method.
• return is a reserved keyword in Java i.e, we can’t
use it as an identifier. It is used to exit from a
method, with or without a value.
return can be used with methods in two ways:
• Methods returning a value : For methods
that define a return type, return statement must
be immediately followed by return value.
(Example Program)
• Methods not returning a value : For methods
that don’t return a value, return statement can
be skipped.
• Example 1: Method NOT using return
statement in void function:
void samp(int a, int b)
{
int sum = 0;
sum = (a + b) / 10;
System.out.println(sum);
// no return statement in this method
}
• Example 2 : Methods with return type void : return statement not
required (but can be used) for methods with return type void. We can use
“return;” which means not return anything.
void samp(double j)
{
if (j < 9)
return;
}
If the statement if(j<9) is true then control exits from the method and
hence come back again to main method.
• Note: return statement need not to be last statement in a method, but it
must be last statement to execute in a method.

void samp(double i)
{
if (i < 9)
return;
else
++I;
}
Returning Values:
All methods must return a value except the
methods defined as void. This returned value
must be of the same data type as defined in
the method prototype.
Passing Values to Methods:
Two types of arguments can be passed to the
java method:
1. Any primitive data types ie., int ,char, float etc
2. Reference data types i.e., objects or arrays
In Java we can pass values to a method in two
ways:
1. Pass by Value or Call by Value
2. Pass by Reference or Call by Reference
Pass by Value:
It is a process in which the function parameter values are copied to another
variable i.e., values of actual parameters are copied too the formal
parameters. By doing so, any changes in the formal parameters values
does not reflect in the actual parameters.
class Operation
{
int data=50;
void change(int data)
{
data=data+100;//changes will be in the local variable only
}
public static void main(String args[])
{
Operation op=new Operation();
System.out.println("before change "+op.data);
op.change(500);
System.out.println("after change "+op.data);
}
}
Pass by Reference:

It is a process in which the actual copy of reference is passed to the function. This
is called by Reference.
Both the actual and formal parameters represent the same memory location. Thus,
any changes made to the value of the formal parameters also get reflected in the
actual parameter.
class Operation2
{
int data=50;
void change(Operation2 op)
{
op.data=op.data+100;//changes will be in the instance variable
}
public static void main(String args[])
{
Operation2 op=new Operation2();
System.out.println("before change "+op.data);
op.change(op);//passing object
System.out.println("after change "+op.data);
}
}
Classification of Methods
On the basis of Functionality, methods can be classified into two types.
• Pure Methods
• Impure Methods
Pure Methods :
A method is pure which :
➢ Does not modify the original state of object (or) simply access the values that are passed to
them.
➢ Is without side effect.

The only result of invoking a pure method is the return value.


Can be called any number of times in any order, value does not change. Pure methods are also
called Accessor methods.
Pure functions are functions which will give exact result when the same arguments are passed.
For example the mathematical function sin (0) always results 0. This means that every time you
call the function with the same arguments, you will always get the same result. A function
can be a pure function provided it should not have any external variable which will alter the
behaviour of that variable.
Example:
square (x)
{
return: x * x }
Impure Methods:
A method is impure that
➢ Modify the original state of object
➢ may or may not return result.
➢ May cause side effects

When a function depends on variables or functions outside of its definition block, you
can never be sure that the function will behave the same every time it’s called. For
example the mathematical function random() will give different outputs for the same
function call.

Random number
a = random()
if (a > 10 )
return a;
else
return 10;

Here the function Random is impure as it is not sure what will be the result when we call
the function.
class pure
{
public static int large(int x,int y)
{
if(x>y)
return x;
else
return y;
}
}
class impure
{
public static int main()
{
int x=-5;
if(x>0)
return - - x;
else
return ++x;
}
}
Static and Non-static Methods
• A static method is a method that belongs to a
class, but it does not belong to an instance of
that class and this method can be called
without the instance or object of that class.

• Every method in java defaults to a non-static


method without static keyword preceding it
Non-static methods can access
any static method and static variable, without
creating an instance of the object.
Below are the various important differences

• Accessing members and methods:


– In static method, the method can only access static
data members and static methods of another class or
same class but cannot access non-static methods and
variables. Also a static method can rewrite the values
of any static data member.

– In non-static method, the method can access static


data members and static methods as well as non-
static members and method of another class or same
class, also can change the values of any static data
member.
• Calling process:
– In static method, The memory of a static method
is fixed in the ram, for this reason we don’t need
the object of a class in which the static method is
defined to call the static method. To call the
method we need to write the name of the method
followed by the class name.

• In non-static method, the memory of non-static


method is not fixed in the ram, so we need class
object to call a non-static method. To call the method
we need to write the name of the method followed
by the class object name.
class Demo {

// static method
public static int sum(int a, int b)
{
return a + b;
}
}

class Samp {
public static void main(String[] args)
{
int n = 3, m = 6;

// call the static method


int s = Demo.sum(n, m);

System.out.print("sum is = " + s);


}
}
• Binding process:
– In static method, the method use compile time or
early binding. For this reason we can access static
method without creation a instance.
– In non-static method, the method use runtime or
dynamic binding. So that we cannot access a non-
static method without creation a instance.

• Overriding:
– In static method, we cannot override a static method,
because of early binding.
• In non-static method, we can override a non-static
method. Because for override we need runtime
polymorphism, which is happens only in runtime
binding.
• Memory allocation: In static method, memory
allocation happens only once, because the static
keyword fixed a particular memory for that
method in ram. So when the method is called
every time in a program, each time that particular
memory is used. For that reason the less memory
is allocated.

• In non-static method, here memory allocation


happens when the method is invoked and the
memory is allocated every time when the
method is called. So much memory is used here.
Method Overloading(Polymorphism)
• Method overloading is a feature of Java in which
a class has more than one methods of the same
name and their parameters are different.
• In other words, we can say that Method
overloading is a concept of Java in which we can
create multiple methods of the same name in the
same class, and all methods work in different
ways. When more than one method of the same
name is created in a Class, this type of method is
called Overloaded Methods.
• Suppose we have to write a method to find the
square of an integer number. We can write this
method as follows:
public void intSquare ( int number )
{
int square = number * number;
System.out.printIn("Method with Integer Argument Called:"+square);
}
public void doubleSquare(double number)
{
double square = number * number;
System.out.printIn("Method with double Argument Called:"+square);
}
public void longSquare(long number)
{
long square = number * number;
System.out.printIn("Method with long Argument Called:"+square);
}
If it is possible that a programmer has to take only one name and the program
itself decides which method to use for which type of value, then it will be
easier for the programmer.
public void square ( int number )
{
int square = number * number;
System.out.printIn(“Method with Integer Argument Called:“+square);
}
public void square(double number)
{
double square = number * number;
System.out.printIn(“Method with double Argument Called:“+square);
}
public void square(long number)
{
long square = number * number;
System.out.printIn(“Method with long Argument Called:“+square);
}
If we define these three methods in a class, then these methods can
be called Overloaded Methods as they have the same name.
Need for Method Overloading /Benefits of using
Method Overloading

• Method overloading increases the readability of the


program.
• This provides flexibility to programmers so that they
can call the same method for different types of data.
• This makes the code look clean.
• This reduces the execution time because the binding
is done in compilation time itself.
• Method overloading minimizes the complexity of the
code.
• With this, we can use the code again, which saves
memory.
• Some points to remember about method
overloading: –

• Method overloading cannot be done by changing


the return type of methods.
• The most important rule of method overloading
is that two overloaded methods must have
different parameters.
If there are two methods of the same signature
within a class in the program, then Ambiguity
Error comes, whether their return-type is
different or not. This means that method
overloading has no relation with return-type.
• Defining Overloaded Methods:

• A method name along with the list of


parameters used in the method prototype is
known as method signature.
• In Java, you can overload a method , provided
the methods with the same name have
different signatures. The signatures can differ
in the type of parameters or in the number of
parameters or both.
• Signatures do not include return types.
• When a method has been declared more than
once in a class :
• Redeclaration
max(int x, int y)
max(int a, int b)
• Syntax error
int max(int x, int y)
double max(int x, int y)
• Overloaded
max(int x, int y)
max(double a, double b)
• Invoking Overloaded Methods:
Overloaded Methods can be invoked just like
any other methods. Java uses the type and /or
number of parameters as its guide to determine
which version of the overloaded method to call.
Consider
max(int num1, int num2)
max(double num1, double num2)
max() method with int type parameters will be
invoked if the method is called with int
parameters. Similarly for max() method with
double type parameters.

You might also like