Sei sulla pagina 1di 8

Computer Programming 2

1
Methods

Methods
Java Methods
In this module, we are going to discuss the concept of the method. We will also
explain the importance of methods and how to implement it in Java programs.

At the end of the lesson, the student should be able to:


Explain what is method and how to use it
Define a method in a Java program
To call and pass parameter on method in a Java program
Explain and implement an overloading method in a Java program

Introduction
In the previous lesson, all the sample program contains one method only and it is
the main method, in one Java program (class) we are allowed to define one or methods.
Why do we need more methods in a program where we can solve the problem in one
method? The reason is, the method is used to simplify and organize coding and define
reusable codes. The method can help to have clean, organize and readable codes. It could
also, eliminate redundant codes defined in a class.
A method contains a collection of statements that are grouped together, and it is
called by another method (such as main) to perform a specific task or operation. An
example of the method call is when you use the System.out.println() in main method.
Executing println(), the compiler actually executes several statements in order to display a
message on the console. The following are characteristics of methods:
It can return one or no values.
It can accept any values.
After the method finished the execution, it goes back to the method that called it.

Defining Method
Below is an example of the method declaration:
public double computeOperation(int param2, int param2){
//statements that performs calculation
}

Course Module
As you can see from the example above, method has the following components:
Modifier (public) - It defines the access type of the method and it is optional to use. Other
modifiers that can used are private, protected and default, modifiers will be discussed
further later. Modifier is optional, therefore, you can define method without modifier.
Return type (double) The data type of the value that the method returns. If the method
defined as void it will not return any value.
Method name (computeOperation) Specifies the name that identifies the method, we
apply here the coding guidelines for the valid identifier.
Parameter List ((int param1, intparam2))- A list of parameters, preceded by their data types
and enclosed by parentheses, (). If your method does not have any parameters, you must
use empty parenthesis.
Method body ({ //statements }) - The Method body is enclosed in curly brackets. It defines
what the method does with the statements.

Naming a method
Method name should follow the rules of valid identifier, and it should be a verb in
lowercase or a multi-word name that begins with a verb in lowercase, followed by adjectives,
nouns, etc. In multi-word names, the first letter of each of the second and following words
should be capitalized. Here are some examples:
compute
computeGrade
execute
getAge
setAge
compareTo
setValue
isEmpty

Method Calling
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 the return statement is executed or when it reaches the
method ending closing brace.
The methods returning void is considered as call to a statement. For example,
System.out.println("Hello World!");
Here's an example of method call that returns value,
int result = sum(8, 6);
Computer Programming 2
3
Methods

Below is the example that demonstrates on how to define and call methods:

Below is output of the sample program above:

From the example above, we defined two methods the getMin and getMax. They are
expected to return int value and they were called inside the main method. The two methods
have both static keyword, we use this keyword because the caller (main) is also defined as
static, we will discuss more on static keyword later.
The getMin method has two parameters the int num1 and int num2, and returns which
of these two parameters have the minimum value. The getMax method has also two parameters
and returns which of them has the maximum value. In getMax method, we defined return
keyword twice, we placed the them inside the if condition, so whatever the result of condition
it will automatically return the value to the caller method (main), unlike the getMin method we
defined min variable that will contain the minimum value and return it after the if condition.
Course Module
Heres an example that calls method that does not return value,

Below is output of the sample program above:

From the example above, we defined two methods the displayMin and displayMax,
this time they will not return any value. The two methods used void keyword as the return
type. The void keyword allows us to create methods which do not return a value. The two
methods were called inside the main method, they will just display minimum and maximum
value respectively.
Computer Programming 2
5
Methods

Passing Arguments in Method


In the previous example, we have already tried passing arguments (value or variable
that we specified when calling a method) to methods. Now, we are going to discuss the two
ways of passing arguments to method, the first one is pass-by-value and the other one is
pass-by-reference.
We have to be cautious when passing arguments, they must match the parameters
in order, number, and compatible data type, as defined in the method. Compatible data type
means that you can pass an argument to a parameter even if they do not have the exact type
as long as they are compatible, such as passing an int value argument to a double value
parameter.
Pass-by-value
When a pass-by-value occurs, the method makes a copy of the value of the variable
passed to the method. The variable will not be affected even if there are changes made to
the parameter inside the method. For example,

The sample program above will have the output below:

As you can see from the output above, the value of variable x and y remain
unchanged even if they were passed as arguments in the method swap and change their
value inside the method.

Course Module
Pass-by-reference
In pass-by-value, it makes a copy of the variable that will be passed to method,
while pass-by-reference, it passed the actual argument. In pass by reference, the parameter
specified in the method is just an alias to the actual parameter and it refers to the actual
argument. Any changes made to the parameter inside the method will reflect in the actual
argument. For example,

The sample program above will have the output below:

Method Overloading
Typically, a method has a unique name within its class. However, a method might
have the same name as other methods due to method overloading. Method overloading
allows you to define multiple method with the same name in a class, provided their
parameter lists are different.
Two ways to overload the method in Java:
Method should have different number of parameters. For example,
public int add(int num1, int num2){
..
}
Computer Programming 2
7
Methods

public int add(int num1, int num2, int num3){


..
}
Different data type of parameters.
public void swap(int num1, int num2){
..
}
public void swap(String num1, String num2){
..
}
Method Overloading Sample Program
Below is the example of overloading method with different number of parameter:

Below is the output of the sample program above:

From this example, we have created two overloaded methods. The first sum method
has two int parameters and performs addition of the two parameters. The second one has
three parameters and performs the addition of the three parameters.

Course Module
Another example of overloading method but differs in data type of the parameters:

Below is the output of the sample program above:

From the example above, we have created two overloaded methods that differ in
data type. The first displaySum method has two int parameters, the method display the sum
of two parameters. The second method has two double parameters and also displays the
sum of two parameters.

Potrebbero piacerti anche