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

Lecture 7 Methods in Java

Methods in Java

Uploaded by

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

Lecture 7 Methods in Java

Methods in Java

Uploaded by

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

IN2203

Fundamentals of
Programming (Java)

Instructor
Dr. Muhammad Waqar
[email protected]
2

Methods
• Methods can be used to define reusable code and organize
and simplify coding. Tests
• A method is a collection of statements grouped together to
perform an operation.
• Previously you have used predefined methods such as
System.out.println, Math.pow, and Math.random. These
methods are defined in the Java library.
3

Defining Methods
• A method definition consists of its method name,
parameters, return value type, and body.
Tests
• The syntax for defining a method is as follows:

modifier returnValueType methodName(list of parameters) {


// Method body;
}
4

Different parts of a method


• The method header specifies the modifiers, return value
type, method name, and parameters of the method. The
static modifier is used for all the Tests
methods in this
• A method may return a value. The returnValueType is the
data type of the value the method returns.
• Some methods perform desired operations without returning
a value. In this case, the returnValueType is the keyword
void. For example, the returnValueType is void in the main
method.
• The variables defined in the method header are known as
formal parameters or simply parameters.
• A parameter is like a placeholder: when a method is invoked,
you pass a value to the parameter. This value is referred to
as an actual parameter or argument. Parameters are
optional; that is, a method may contain no parameters.
5

Example of a method

Tests
6

Calling a method
• Calling a method executes the code in the method.
• In a method definition, you define what the method is to do.
Tests
• To execute the method, you have to call or invoke it.
• There are two ways to call a method, depending on whether
the method
returns a value or not.
• If a method returns a value, a call to the method is usually
treated as a value. For example,
int larger = max(3, 4);
calls max(3, 4) and assigns the result of the method to the
variable larger
• If a method returns void, a call to the method must be a
statement. For example, the method println returns void.
7

Calling a method
• When a program calls a method, program control is
transferred to the called method.
• A called method returns control Tests
to the caller when its return
statement is executed or when its method ending closing
brace is reached.
• Methods enable code sharing and reuse. The max method
can be invoked from any class.
• If you call a method in the same class where it has been
defined, it can be used directly by name e.g. max(i,j)
• If you create a new class, you can invoke the max method
using ClassName.methodName (i.e., TestMax.max(i,j)).
8

Example
public class TestMax {
public static void main(String[] args) {
int i = 5;
Tests
int j = 2;
int k = max(i, j);
System.out.println("The maximum of " + i +
" and " + j + " is " + k);
}

public static int max(int num1, int num2) {


int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;}}
9

An example of void method


• A void method does not have a return type as it does not
return a value
Tests
public class TestVoidMethod {

public static void main(String[] args) {

System.out.print("The grade is ");


printGrade(78.5);
System.out.print("The grade is ");
printGrade(59.5);
}
}
10

An example of void method


public static void printGrade(double score) {
if (score >= 90.0) {
System.out.println('A');} Tests
else if (score >= 80.0) {
System.out.println('B');}
else if (score >= 70.0) {
System.out.println('C');}
else if (score >= 60.0) {
System.out.println('D');}
else {
System.out.println('F');
}
}
}
11

return statement in void method


• A return statement is not needed for a void method, but it
can be used for terminating the method and returning to the
method’s caller. Tests
• The syntax is simply
return;
• This is not often done, but sometimes it is useful for
circumventing the normal flow of control in a void method.
An example is given on next slide.
12

Example of return statement in void method


public static void printGrade(double score) {
if (score < 0 || score > 100) {
System.out.println("Invalid score");
return;} Tests
if (score >= 90.0) {
System.out.println('A');}
else if (score >= 80.0) {
System.out.println('B');}
else if (score >= 70.0) {
System.out.println('C');}
else if (score >= 60.0) {
System.out.println('D');}
else {
System.out.println('F');
}}
13

Argument passing by values


• When calling a method, you need to provide arguments,
which must be given in the same order as their respective
parameters in the method signature. This is known as
parameter order association. For
Testsexample, the following
method prints a message n times:

public static void nPrintln(String message, int n) {


for (int i = 0; i < n; i++)
System.out.println(message);}

• You can use nPrintln("Hello", 3) to print Hello three times.


• The nPrintln("Hello", 3) statement passes the actual string
parameter Hello to the parameter message, passes 3 to n,
and prints Hello three times.
• However, the statement nPrintln(3, "Hello") would be wrong.
The data type of 3 does not match the data type for the first
14

Argument passing by values


• The arguments must match the parameters in order,
number, and compatible type, as defined in the method
signature.
• Compatible type means that youTestscan pass an argument to a
parameter without explicit casting, such as passing an int
value argument to a double value parameter.
• When you invoke a method with an argument, the value of
the argument is passed to the parameter. This is referred to
as pass-by-value.
• If the argument is a variable rather than a literal value, the
value of the variable is passed to the parameter.
• The variable is not affected, regardless of the changes made
to the parameter inside the method.
15

Argument passing by values example


public class Increment {
public static void main(String[] args) {
int x = 1; Tests
System.out.println("Before the call, x is " + x);
increment(x);
System.out.println("After the call, x is " + x);
}
public static void increment(int n) {
n++;
System.out.println("n inside the method is " + n);
}
}
16

Practice Problem
• Write a program which defines two methods, max and min.

• Both these methods should accept two integers as input and


Tests
should return, maximum and minimum value in a return
statement.

• Call these methods in main() method and print out outputs


returned by these methods.
17

Method Overloading

• Overloading methods enables you to define the methods


Testssignatures are different.
with the same name as long as their
• The max method that was used earlier works only with the
int data type. But what if you need to determine which of
two floating-point numbers has the maximum value?
• The solution is to create another method with the same
name but different parameters
18

Method Overloading
public static double max(double num1, double num2) {
if (num1 > num2)
return num1; Tests
else
return num2;}

• If you call max with int parameters, the max method that
expects int parameters will be invoked;
• if you call max with double parameters, the max method
that expects double parameters will be invoked.
• This is referred to as method overloading; that is, two
methods have the same name but different parameter lists
within one class.
• The Java compiler determines which method to use based on
the method signature.
19

Method Overloading Example (Part I)


public class TestMethodOverloading {
public static void main(String[] args) {
System.out.println("The maximum of 3 and 4 is “ + max(3, 4));
Tests
System.out.println("The maximum of 3.0 and 5.4 is "+ max(3.0,
5.4));
System.out.println("The maximum of 3.0, 5.4, and 10.14 is "
+ max(3.0, 5.4, 10.14));}

public static int max(int num1, int num2) {


if (num1 > num2)
return num1;
else
return num2;
}
20

Method Overloading Example (Part I)


public static double max(double num1, double num2) {
if (num1 > num2)
Tests
return num1;
else
return num2;
}

public static double max(double num1, double num2, double num3) {


return max(max(num1, num2), num3);
}
}
21

Practice Problem I
Write a program which defines a method to calculate
multiplication of two numbers e.g. multiplyInteger.
Tests
Call this method in the main method and calculate
multiplication of two numbers.
22

Practice Problem II
Write a program which defines three overloaded methods to
calculate multiplication of numbers.
Tests
First method should accept two values and should return
multiplication of two numbers.

Second and third method should have three and four numbers
and should give the multiplication result at output respectively.
23

Practice Problem III


Write a Java method to count all vowels in a string.

Define a method which counts vowels in any string.


Tests

Ask the user to enter a string in main() method.

Call countvowels method in main() method and return value to


main()

Print out the number of vowels in string.


Thank You

You might also like