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

Lecture 5

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

Lecture 5

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

Lecture 5:

Methods (functions)

Object Oriented Programming


1
Introduction
• A method is a block of code or collection of statements or a set of
code grouped together to perform a certain task or operation. 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.

• In this lecture you will learn how to create a method, how to call a
method and function overloading.

2
Method Declaration
• Before using a method, we must create/declare it.

• 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, as we have
shown in the following figure.

3
Method Declaration
• Method Signature: Every method has a method signature. It is a part of
the method declaration. It includes the method name and parameter list.

• 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:
– Public: The method is accessible by all classes when we use public
specifier in our application.
– Private: When we use a private access specifier, the method is
accessible only in the classes in which it is defined.
– Protected: When we use protected access specifier, the method is
accessible within the same package or subclasses in a different
package.
– 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.

4
Method Declaration
• 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.

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

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

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

5
Naming a Method
• While defining a method, if possible 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()

• It is also possible that a method has the same name as another


method name in the same class, it is known as method
overloading.

6
Types of Method
• Methods are also known as Procedures or Functions:
– Procedures: They don't return any value.
– Functions: They return value.

• There are two types of methods in Java:


– Predefined Method
• In Java, predefined methods are the method that is already defined in the
Java class libraries is known as predefined methods. It is also known as
the standard library method or built-in method. We can directly use these
methods just by calling them in the program at any point. Some pre-
defined methods are length(), equals(), compareTo(), sqrt(), etc.

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

7
How to Create a User-defined Method
• Let's create a user defined method that checks the number is even
or odd. First, we will define the method.

//user defined method


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");
}

– We have defined the above method named findEvenOdd().


– It has a parameter num of type int.
– The method does not return any value that's why we have used void.
– The method body contains the steps to check the number is even or odd. If the
number is even, it prints the number is even, else prints the number is odd.
8
How to Call or Invoke a User-defined Method
• For using a method, it should be called. There are two ways in which a
method is called i.e. method returns a value or returning nothing (no return
value).

• The process of method calling is simple. When a program invokes a


method, the program control gets transferred to the called method. This
called method then returns control to the caller in two conditions, when:
– return statement is executed.
– reaches the method ending closing brace.

9
How to Call or Invoke a User-defined Method
import java.util.Scanner;
• Once we have defined a method, it should be
public class EvenOdd
called. The calling of a method in a program is
{ simple. When we call or invoke a user-defined
public static void main (String args[]) method, the program control transfer to the
{ called method.
//creating Scanner class object
Scanner scan=new Scanner(System.in); • In the code snippet, as soon as the compiler
System.out.print("Enter the number: "); reaches at line findEvenOdd(num), the control
transfer to the method and gives the output
//reading value from the user
accordingly.
int num=scan.nextInt();
//method calling
• The void keyword allows us to create methods
findEvenOdd(num); which do not return a value. This method is a
} void method which does not return any value.
public static void findEvenOdd(int num)
{ • Call to a void method must be a statement i.e.
//method body findEvenOdd(num); . It is a Java statement which
if(num%2==0) ends with a semicolon as shown below.
System.out.println(num+" is even");
else
System.out.println(num+" is odd");
}
10
}
Calling an function returning int data type
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 of a and b is= " + 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
}
}

11
Calling an function
• Note:
– In the above program in the function add, there are two parameters of
data type int
– The function will return a value of data type int

12
Calling an function returning double data type
public static void main(String[] args) {
double c = 7.3;
double d = 9.4;
double result2 = minFunction(c, d);
System.out.println("Minimum Value = " + result2);
}

// for double
public static double minFunction(double n1, double n2) {
double min;
if (n1 > n2)
min = n2;
else
min = n1;

return min;
}
}

13
void keyword
• The void keyword allows to create methods which do not return a
value. In the following example we're considering a void method
displayMarks. This method is a void method which does not return
any value. Call to a void method must be a statement i.e.
displayMarks(82);. It is a Java statement which ends with a
semicolon as shown below.

public static void main(String[] args) {


displayMarks(82);
}

public static void displayMarks(int mks) {


if (mks > 80)
System.out.println(“Grade A ");
else if( (mks > 50)&&(mks < 80))
System.out.println(“Grade B ");
else
System.out.println(“Grade C ");
} 14
}
Passing Parameters by Value
• While working under calling process, arguments is to be passed. These
should be in the same order as their respective parameters in the method
specification. Parameters can be passed by value or by reference.
• Passing Parameters by Value means calling a method with a parameter.
Through this the argument value is passed to the parameter.

• Example:
• The following program shows an example of passing parameter by value.
The values of the arguments remain the same even after the method
invocation.

15
Example of Passing Parameters by Value
public class swappingExample {

public static void main(String[] args) {


int a = 30;
int b = 45;
System.out.println("Before swapping, a = " + a + " and b = " + b);

// Invoke the swap method


swapFunction(a, b);
System.out.println("\n**Now, Before and After swapping values will be same here**:");
System.out.println("After swapping, a = " + a + " and b is " + b);
}

public static void swapFunction(int a, int b) {


System.out.println("Before swapping(Inside), a = " + a + " b = " + b);

// Swap n1 with n2
int c = a;
a = b;
b = c;
System.out.println("After swapping(Inside), a = " + a + " b = " + b);
} 16
}
Example of Passing Parameters by Value
• Output

Before swapping, a = 30 and b = 45


Before swapping(Inside), a = 30 b = 45
After swapping(Inside), a = 45 b = 30

**Now, Before and After swapping values will be same here**:


After swapping, a = 30 and b is 45

17

You might also like