Computer PDF
Computer PDF
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:
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.
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.
// 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;
• 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.