0% found this document useful (0 votes)
22 views44 pages

Day 04 - Methods

Uploaded by

Thảo Phương
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)
22 views44 pages

Day 04 - Methods

Uploaded by

Thảo Phương
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/ 44

Introduction to Method

Faculty of Information Technology, Hanoi University


What You Are About To Achieve 2
❖ By the end of this lecture, we are going to:
❑ Define what a method is in Java.
❑ Explain the structure of a method.
❑ Differentiate between void methods and methods that return values.
❑ Demonstrate how to create and use methods with parameters.
❑ Illustrate how to modularize code using methods.
❑ Apply method overloading in Java programs.
❑ Understand the scope of variables within methods.
❑ Explore method abstraction and stepwise refinement techniques.
3
❖ Introduction to Method
❖ Types of Methods
❑ Void Methods
❑ Methods Returning Values
❖ Method Features
❖ Final Touches
Introduction to Method 4
❖ Suppose that you need to find the sum of integers from 1 to 10, from 20 to 37, and from 35
to 49, respectively. Using the knowledge you’ve learned, you may write something like:
int sum = 0;
for (int i = 1; i <= 10; i++)
sum += i;
System.out.println("Sum from 1 to 10 is " + sum);
Can you see that? Computing these
sum = 0; sums from 1 to 10, from 20 to 37, and
for (int i = 20; i <= 37; i++) from 35 to 49 are very similar except
that the starting and ending integers
sum += i;
are different. Wouldn’t it be nice if we
System.out.println("Sum from 20 to 37 is " + sum);
could write the common code once
and reuse it, right?
sum = 0;
for (int i = 35; i <= 49; i++)
sum += i;
System.out.println("Sum from 35 to 49 is " + sum);
Introduction to Method 5
❖ Fortunately, in Java, we can achieve this by using methods. A method allows us to
encapsulate a block of code that performs a specific task, so we can reuse it with
different inputs. For example, the preceding code can be simplified as follows:
1 public static int sum(int i1, int i2) { Proposition
2 int result = 0; ❑ Lines 1–7 define the method named sum with two
parameters i1 and i2.
3 for (int i = i1; i <= i2; i++)
4 result += i;
5 Proposition
❑ The statements in the main method invoke
6 return result; sum(1, 10) to compute the sum from 1 to 10
7 } sum(20, 37) to compute the sum from 20 to 37
sum(35, 49) to compute the sum from 35 to 49.
8
9 public static void main(String[] args) {
10 System.out.println("Sum from 1 to 10 is " + sum(1, 10));
11 System.out.println("Sum from 20 to 37 is " + sum(20, 37));
12 System.out.println("Sum from 35 to 49 is " + sum(35, 49));
13 }
“Sound interesting? But unsure
how to define a method?
Let’s embark on the journey of understanding how to create one!
6
Introduction to Method – Method Structure 7
❖ Before we dive into writing methods, let’s first understand how to define one. Defining a
method involves specifying its name, the task it performs, and the input it requires.
Think of it like creating a recipe: you give it a name, list the ingredients (inputs), and
outline the steps (code) to achieve the result.
❖ The syntax for defining a method is as follows:
modifier returnValueType methodName(list of parameters) {
// Method body;
}
Let’s look at a method
defined to find the larger
between two integers.
Introduction to Method – Method Structure 8
❖ The method, named max, has two int parameters, num1 and num2, the larger of which is
returned by the method.
Introduction to Method – Method Structure 9
❖ As can be seen from the figure, the
method header specifies the modifiers,
return value type, method name, and
parameters of the method. The following
paragraphs describe method declarations
piece-by-piece:

Proposition
❑ public: This keyword indicates that the method’s existence should be publicized to the world,
and that any Java program that knows about your program (or, more accurately, the class
defined for your Java program) should be able to use your method. That’s not very meaningful
for the types of programs you’re dealing with at this point in the course, but it will become
more meaningful later on.
Introduction to Method – Method Structure 10
❖ As can be seen from the figure, the
method header specifies the modifiers,
return value type, method name, and
parameters of the method. The following
paragraphs describe method declarations
piece-by-piece:

Proposition
❑ static: The static modifier might be used for all the methods in this course. The reason for
using it will be discussed in Programming 02 (PR2).
Introduction to Method – Method Structure 11
❖ As can be seen from the figure, the
method header specifies the modifiers,
return value type, method name, and
parameters of the method. The following
paragraphs describe method declarations
piece-by-piece:

Proposition
❑ return-value-type: After the word static comes the return value type, which indicates whether
the method returns a value when it is called and, if so, what type the value is. If the method
doesn’t return a value, specify void.
Introduction to Method – Method Structure 12
❖ As can be seen from the figure, the
method header specifies the modifiers,
return value type, method name, and
parameters of the method. The following
paragraphs describe method declarations
piece-by-piece:

Proposition
❑ method-name: The name of the method. This name should follow the naming conventions
mentioned a few week ago.
Fun fact: We say “define a method” and “declare a variable.” We are making a subtle distinction here. A definition defines what the defined item is, but a declaration usually
involves allocating memory to store data for the declared item.
Introduction to Method – Method Structure 13
❖ As can be seen from the figure, the
method header specifies the modifiers,
return value type, method name, and
parameters of the method. The following
paragraphs describe method declarations
piece-by-piece:

Proposition
❑ parameter-list: You can pass one or more values to a method by listing the values in
parentheses following the method name. The parameter list in the method declaration lets
Java know what types of parameters a method should expect to receive and provides names
so that the statements in the method’s body can access the parameters as local variables. If
the method doesn’t accept parameters, you must still code the parentheses that surround the
parameter list. You just leave the parentheses empty.
Introduction to Method – Method Structure 14
❖ As can be seen from the figure, the
method header specifies the modifiers,
return value type, method name, and
parameters of the method. The following
paragraphs describe method declarations
piece-by-piece:

Proposition
❑ method-body: The method body consists of one or more Java statements enclosed in a set of
braces. Unlike Java statements such as if, while, and for, you still have to use the braces even
if the body of your method consists of only one statement.
Facts
❑ Some programming languages refer to methods as procedures and functions. In those languages, a value-returning
method is called a function and a void method is called a procedure.
Need to know how to use this?
It's time to see how it works.

15
Introduction to Method – Calling a Method 16
❖ In a method definition, you define what the method is to do. 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.

System.out.println(max(3, 4)); - which prints the return value of the method call max(3, 4).
❖ If a method returns void, a call to the method must be a statement. For example, the
method println returns void. The following call is a statement:
System.out.println("Welcome to Java!");
Introduction to Method – Calling a Method 17
❖ When a program calls a method, program control is transferred to the called method. A
called method returns control to the caller when its return statement is executed or when
its method-ending closing brace is reached.

Figure A. When the max method is invoked, the flow of control transfers to it. Once the max method is
finished, it returns control back to the caller.
Introduction to Method – Calling a Method 18
❖ Each time a method is invoked, the system creates an activation record (also called an activation frame)
that stores parameters and variables for the method and places the activation record in an area of memory
known as a call stack. A call stack is also known as an execution stack, runtime stack, or machine stack,
and it is often shortened to just “the stack.” When a method calls another method, the caller’s activation
record is kept intact, and a new activation record is created for the new method called. When a method
finishes its work and returns to its caller, its activation record is removed from the call stack.
19
I was just thinking... I understand how
methods are structured and executed,
but are there different types of methods
in Java? How can I create one?

Good question! Yes, Java has different types of methods, but the
one we'll focus on today is the static method. There’s also another
distinction between void methods and returning methods,
methods with and without parameters. Each serves a different
purpose. Let me explain what makes them distinct. Then you will
see how to define a method based on your demand.
20
❖ Introduction to Method
❖ Types of Methods
❑ Void Methods
❑ Methods Returning Values
❖ Method Features
❖ Final Touches
21

So far we’ve only written short


programs that have a single class and a
single method (main). In this section,
we’ll show you how to organize longer
programs into multiple methods.
Types of Method – Void Methods 22
❖ The preceding section gives an example of a value-returning method. This section shows
how to define and invoke a void method. For a concrete example, we offer a version of
the Hello, World! program in which the message is displayed not by the main method,
but by a method named sayHello that’s called by the main method.
Types of Method – Void Methods 23
❖ As demonstrated in the sayHello method, the void keyword is used as the return type to
define methods that do not return any value.

❖ And to call this method, we need to invoke it from another method, such as the main
method in this case, by using a statement.

Is this too easy to


define a void method?
Types of Method – Value-Returning Methods 24
❖ Yeah, It’s too easy to create such methods. However, methods that just do work without
returning any data are useful only in limited situations. The real utility of methods comes
when they can perform some complicated task such as a calculation, and then return the
value of that calculation to the calling method so the calling method can do something
with the value. Here is another example of HelloWorld program:
Types of Method – Value-Returning Methods 25
❖ As can be seen, to create a method that returns a value, you simply indicate the type of
the value returned by the method on the declaration in place of the void keyword. For
example, here’s a method declaration that creates a method that returns a String value:

Proposition
❑ The return type of a method can be any of Java’s primitive return types, or the return type can
be a reference type, including a class defined by the API such as String or a class you create
yourself.
Types of Method – Value-Returning Methods 26
❖ As can be seen, to create a method that returns a value, you simply indicate the type of
the value returned by the method on the declaration in place of the void keyword. For
example, here’s a method declaration that creates a method that returns a String value:

Proposition
❑ When you specify a return type other than void in a method declaration, the body of the
method must include a return statement that specifies the value to be returned. The return
statement has this form:
return literals or expression;
❑ The expression must evaluate to a value that’s the same type as the type listed in the method
declaration. In other words, if the method returns a String, the expression in the return
statement must evaluate to a String.
Now that we know how to
define methods in Java, have
you ever wondered how we can
provide these methods with the
information they need to
perform their tasks?
Types of Method – Passing Arguments by Values 28
❖ You know, oftens, programmers write methods as if they were black boxes — the
programmer knows what is going on inside the box, but all of those implementation
details are hidden from the user. The user should be aware of the input of the black box,
and they should be able to predict an output given the input, but the details of how that
input gets transformed into the output can be hidden from the users.

Example
❑ Consider a television remote — we can give the remote some input, like pressing the “Volume Up” button, and we
can expect some output, like the volume increasing. But beyond that, all of the inner workings of the process is
hidden from us. We, as the television remote user, don’t really know how the remote communicates with the TV or
how the TV interfaces with its speakers. All we know is the format of the input and the expected output. Then we let
the black box do the rest.
Types of Method – Passing Arguments by Values 29
❖ It is the fact that the power of a method is its ability to work with those input (or formal
parameters). For example, you can use println to print any string and max to find the
maximum of any two int values. Remember that when calling a method, you need to
provide arguments (or actual parameters), which must be given in the same order as their
respective parameters in the method signature. This is known as parameter order
association.

Notice
❑ The arguments must match the parameters in order, number, and compatible type, as defined in the
method signature. Compatible type means that you can pass an argument to a parameter without
explicit casting, such as passing an int value argument to a double value parameter.
Types of Method – Passing Arguments by Values 30
❖ A parameter is a value that you can pass to a method. The method can then use the
parameter as if it were a local variable initialized with the value of the variable passed to
it by the calling method.
Formal Parameters

Scope of i1 and i2
Returned value
Actual Parameters
And please keep in
(Arguments)
mind that both types of
methods may require
parameters and use
them in a similar way.

Proposition
❑ When Java passes a variable to a method via a parameter, the method itself receives a copy of the variable’s value, not
the variable itself. This copy is called a pass-by-value, and it has an important consequence: If a method changes the
value it receives as a parameter, that change is not reflected in the original variable that was passed to the method.
31

Now that we've explored the


different types of methods in Java,
it’s time to delve deeper into the
features that make these methods
effective and powerful.
32
❖ Introduction to Method
❖ Types of Methods
❑ Void Methods
❑ Methods Returning Values
❖ Method Features
❖ Final Touches
Methods Features 33
❖ In this section, we are going to:
❑ Explore how modularizing code can greatly enhance your code's structure and
readability.
❑ Discuss JavaDoc tags, which are essential for documenting your methods.
❑ Cover method overloading, a powerful feature that allows you to use the same
method name with different parameters.
❑ Delve into recursion, where a method calls itself to solve complex problems.
Methods Features – Modularizing Code 34
❖ Methods can be used to reduce redundant code and enable code reuse. Methods can also
be used to modularize code and improve the quality of the program. For example,

By encapsulating the code for obtaining the gcd in a


method, this program has several advantages:
1. It isolates the problem for computing the gcd from
the rest of the code in the main method. Thus, the
logic becomes clear and the program is easier to
read.
2. The errors on computing the gcd are confined in the
gcd method, which narrows the scope of debugging.
3. The gcd method now can be reused by other
programs.
Methods Features – Modularizing Code 35
❖ Here’s another example of code modularization for checking if a number is prime. Due
to length constraints, the source code provided here consists only of comments that
describe the logic.
Methods Features – Modularizing Code 36

Proposition
❑ As can be seen, we divided a large problem into two subproblems: determining whether a
number is a prime and printing the prime numbers. As a result, the new program is easier to
read and easier to debug. Moreover, the methods printPrimeNumbers and isPrime can be reused
by other programs.
Methods Features – Overloading Methods 37
❖ Modularization involves breaking down functionality into distinct methods. But what
happens when we need to use the same method name to handle different inputs? For
example, 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…
Proposition
❑ 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.
Methods Features – Overloading Methods 38
❖ Let’s see other “versions” of max method:
39
Nobita
We’ve just learned about method overloading, where a class can have multiple
methods with the same name but different parameters. But I've noticed
something interesting - some methods seem to call themselves. What’s going
on there?

Great observation! What you're seeing is actually a concept


called recursion. In recursion, a method calls itself in order to
solve a problem. It’s like when you’re trying to solve a puzzle
and keep breaking it down into smaller pieces until you reach a
base case.
Delivered
Nobita
So, it’s like the method is solving a smaller version of the
problem it was originally designed to solve?
40
Nobita
So, it’s like the method is solving a smaller version of the
problem it was originally designed to solve?

Exactly! Recursion is a powerful technique that can simplify


complex problems by breaking them down into simpler, more
manageable sub-problems. It’s a bit like method overloading but
with methods referring to themselves rather than just different
parameter lists.
Nobita
Delivered
Sounds interesting! When will we
dive into this more?

We’ll cover recursion in detail later in this course. For now, just
keep in mind that it’s a method calling itself to solve problems
more efficiently. We’ll explore how it works and see some
practical examples soon.
Delivered
That’s all about Methods,
do you have any question?
If not? Let’s summarize how to define and use methods…
41
Summary 42
❖ Methods in Java can be defined based on how they interact with the program's data and
the tasks they perform. We typically define methods in the following ways:
public static return-datatype methodName() {
public static void methodName() { // Method body
// Method body return result; // value that’s the same
} datatype as the return-datatype
}

void methods, without parameters Value-Returning methods, without parameters

public static return-datatype methodName(datatype


public static void methodName(datatype parameter1, parameter1, datatype parameter2) {
datatype parameter2) { // Method body
// Method body return result; // value that’s the same
} datatype as the return-datatype
}

void methods, with parameters Value-Returning methods, with parameters


Summary 43

How to call or invoke a method?


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

System.out.println(max(3, 4)); - which prints the return value of the method call max(3, 4).
❖ If a method returns void, a call to the method must be a statement. For example, the
method println returns void. The following call is a statement:
System.out.println("Welcome to Java!");
45

Thanks!
Any questions?
For an in-depth understanding of Java, I highly recommend
referring to the textbooks. This slide provides a brief overview
and may not cover all the details you're eager to explore!

You might also like