NCP2210 LabAct4
NCP2210 LabAct4
LABORATORY ACTIVITY #4
METHODS
NAME: CRUZ, JOSH CLARENCE F. DR. JOAN P. LAZARO
SECTION: 1ME DATE: 5/4/22 GRADE:
Introduction to Methods
In a general sense, a method is a collection of statements that performs a specific task. So
far you have experienced methods in two ways: (1) You have created a method named main in
every program you’ve written, and (2) you have executed predefined methods from the Java API,
such as System.out.println, Integer.parseInt, and Math.pow. In this experiment, you will learn
how to create your own methods, other than main, that can be executed just as you execute the
API methods.
Methods are commonly used to break a problem into small, manageable pieces. Instead
of writing one long method that contains all of the statements necessary to solve a problem,
several small methods that each solve a specific part of the problem can be written. These small
methods can then be executed in the desired order to solve the problem. This approach is
sometimes called divide and conquer because a large problem is divided into several smaller
problems that are easily solved. The figure below illustrates this idea by comparing two
programs: one that uses a long, complex method containing all of the statements necessary to
solve a problem, and another that divides a problem into smaller problems, each of which is
handled by a separate method.
Another reason to write methods is that they simplify programs. If a specific task is
performed in several places in a program, a method can be written once to perform that task, and
then be executed any time it is needed. This benefit of using methods is known as code reuse
because you are writing the code to perform a task once and then reusing it each time you need
to perform the task. First, we will look at the general ways in which methods operate. At the end
of the experiment we will discuss in greater detail how methods can be used in problem solving.
1|Page
NCP 2210 (Computer Fundamentals & Programming)
As you already know, every complete Java program must have a main method. Java
programs can have other methods as well. Here is an example of a simple method that displays a
message on the screen:
public static void displayMessage() {
System.out.println("Hello from the displayMessage method.");
}
This method has a header and a body. The figure below shows the different parts of the
method header.
2|Page
NCP 2210 (Computer Fundamentals & Programming)
Let’s take a closer look at the parts identified in the figure as follows:
Method modifiers—The keywords public and static are modifiers. The word public
means that the method is publicly available to code outside the class. The word static
means that the method belongs to the class, not a specific object.
Return type—When the key word void appears here, it means that the method is a void
method, and does not return a value.
Method name—You should give each method a descriptive name. In general, the same
rules that apply to variable names also apply to method names. This method is named
displayMessage, so we can easily guess what the method does: It displays a message.
Parentheses—In the header, the method name is always followed by a set of
parentheses. Methods can be capable of receiving arguments. When this is the case, a list
of one or more variable declarations will appear inside the parentheses. The method in
this example does not receive any arguments, so the parentheses are empty.
Calling a Method
A method executes when it is called. The main method is automatically called when a
program starts, but other methods are executed by method call statements. When a method is
called, the JVM branches to that method and executes the statements in its body. Here is an
example of a method call statement that calls the displayMessage method we previously
examined:
displayMessage();
The statement is simply the name of the method followed by a set of parentheses.
Because it is a complete statement, it is terminated with a semicolon.
Example Program #1
/**
* @author Joan Lazaro
*/
public class Example1 {
public static void main(String[] args) {
System.out.println("Hello from the main method.");
displayMessage();
System.out.println("Back in the main method.");
}
/**
The displayMessage method displays a greeting.
*/
public static void displayMessage() {
System.out.println("Hello from the displayMessage method.");
}
}
3|Page
NCP 2210 (Computer Fundamentals & Programming)
Result:
Observation:
This example problem simply shows that it executes a display that you have inputted. It will
show the things that you wrote Inside the parenthesis.
Example Program #2
/**
* @author Joan Lazaro
*/
public class Example2 {
public static void main(String[] args) {
System.out.println("Hello from the main method.");
for (int i = 0; i < 5; i++)
displayMessage();
System.out.println("Back in the main method.");
}
/**
The displayMessage method displays a greeting.
*/
public static void displayMessage() {
System.out.println("Hello from the displayMessage method.");
}
}
Result:
Observation:
4|Page
NCP 2210 (Computer Fundamentals & Programming)
In this example problem it shows that you generate/produce an amount that you wish the
display would be. It needs to have an equation for it to work as well and the proper methods.
Example Program #3
import javax.swing.JOptionPane;
/**
* @author Joan Lazaro
*/
public class Example3 {
public static void main(String[] args) {
double salary; // Annual salary
int creditRating; // Credit rating
String input; // To hold the user’s input
// Get the user’s annual salary.
input = JOptionPane.showInputDialog("What is your annual salary?");
salary = Double.parseDouble(input);
// Get the user’s credit rating (1 through 10).
input = JOptionPane.showInputDialog("On a scale of 1 through 10, what
is your credit rating?\n(10 = excellent, 1 = very bad)");
creditRating = Integer.parseInt(input);
// Determine whether the user qualifies.
if (salary >= 20000 && creditRating >= 7)
qualify();
else
noQualify();
System.exit(0);
}
/**
The qualify method informs the user that he or she qualifies for the
credit card.
*/
public static void qualify(){
JOptionPane.showMessageDialog(null, "Congratulations! You qualify for
the credit card!");
}
/**
The noQualify method informs the user that he or she does not qualify for
the credit card.
*/
public static void noQualify() {
JOptionPane.showMessageDialog(null, "I'm sorry. You do not qualify for
the credit card.");
}
}
Result:
5|Page
NCP 2210 (Computer Fundamentals & Programming)
Observation:
It prompts a JOptionPane and it displays a question for gathering data. And it just simply shows
you if you are qualified or not if you have their specific requirements.
Example Program #4
/**
* @author Joan Lazaro
*/
public class Example4 {
public static void main(String[] args) {
System.out.println("I am starting in main.");
deep();
System.out.println("Now I am back in main.");
}
/**
The deep method displays a message and then calls the deeper method.
*/
public static void deep() {
System.out.println("I am now in deep.");
deeper();
System.out.println("Now I am back in deep.");
}
/**
The deeper method simply displays a message.
*/
public static void deeper() {
System.out.println("I am now in deeper.");
}
}
Result:
6|Page
NCP 2210 (Computer Fundamentals & Programming)
Observation:
In this example problem, it displays the control of the arrangement of the system prints and you
can arrange them however you want them to be displayed.
7|Page
NCP 2210 (Computer Fundamentals & Programming)
Inside the displayValue method, the variable num will contain the value of whatever
argument was passed into it. If we pass 5 as the argument, the method will display as follows:
The value is 5
You may also pass the contents of variables and the values of expressions as arguments.
For example, the following statements call the displayValue method with various arguments
passed:
displayValue(x);
displayValue(x * 4);
displayValue(Integer.parseInt("700"));
The first statement is simple. It passes the value in the variable x as the argument to the
displayValue method. The second statement is also simple, but it does a little more work: It
passes the result of the expression x * 4 as the argument to the displayValue method. The third
statement does even more work. It passes the value returned from the Integer.parseInt method as
the argument to the displayValue method. (The Integer.parseInt method is called first, and its
return value is passed to the displayValue method.) The program in Example #5 demonstrates
these method calls.
Example Program #5
/**
* @author Joan Lazaro
*/
public class Example5 {
public static void main(String[] args) {
int x = 10;
System.out.println("I am passing values to displayValue.");
displayValue(5); // Pass 5
displayValue(x); // Pass 10
displayValue(x * 4); // Pass 40
displayValue(Integer.parseInt("700")); // Pass 700
System.out.println("Now I am back in main.");
}
/**
The displayValue method displays the value of its integer parameter.
*/
public static void displayValue(int num) {
System.out.println("The value is " + num);
}
}
Result:
8|Page
NCP 2210 (Computer Fundamentals & Programming)
Observation:
In this example problem, it shows us how you input the data that is about to be displayed. It
shows us how we display it properly with the right methods.
9|Page
NCP 2210 (Computer Fundamentals & Programming)
Suppose we were to reverse the order in which the arguments are listed in the method
call, as shown here:
showSum(10, 5);
This would cause 10 to be passed into the num1 parameter and 5 to be passed into the
num2 parameter. The following code segment shows one more example. This time we are
passing variables as arguments.
double value1 = 2.5;
double value2 = 3.5;
showSum(value1, value2);
When the showSum methods executes as a result of this code, the num1 parameter will
contain 2.5 and the num2 parameter will contain 3.5.
10 | P a g e
NCP 2210 (Computer Fundamentals & Programming)
Result:
Observation:
In this example problem, it exhibits the way you can change the value of the first data to another
in a single run. And it displays the data at the same time without you even having a tool for
prompts to gather data.
11 | P a g e
NCP 2210 (Computer Fundamentals & Programming)
.
This might lead you to the conclusion that a method can change the contents of any
String object that has been passed to it as an argument. After all, the parameter variable
references the same object as the argument. However, String objects in Java are immutable,
which means that they cannot be changed. For example, look at the program in Example #7. It
passes a String object to a method, which appears to change the object. In reality, the object is
not changed.
Example Program #7
/**
* @author Joan Lazaro
*/
public class PassString {
public static void main(String[] args) {
// Create a String object containing "Shakespeare".
// The name variable references the object.
String name = "Shakespeare";
// Display the String referenced by the name variable.
System.out.println("In main, the name is " + name);
// Call the changeName method, passing the
// contents of the name variable as an argument.
changeName(name);
// Display the String referenced by the name variable.
System.out.println("Back in main, the name is " + name);
}
/**
The changeName method accepts a String as its argument
and assigns the str parameter to a new String.
*/
public static void changeName(String str) {
// Create a String object containing "Dickens".
// Assign its address to the str parameter variable.
str = "Dickens";
// Display the String referenced by str.
System.out.println("In changeName, the name is now " + str);
12 | P a g e
NCP 2210 (Computer Fundamentals & Programming)
}
}
13 | P a g e
NCP 2210 (Computer Fundamentals & Programming)
When a method’s documentation comments contain one or more @param tags, the
javadoc utility will create a Parameters section in the method’s documentation. This is where the
descriptions of the method’s parameters will be listed.
Result:
14 | P a g e
NCP 2210 (Computer Fundamentals & Programming)
Observation:
In this example problem it shows us to input the values of the given data and display it at the
same time.
Local Variable Lifetime
A method’s local variables exist only while the method is executing. This is known as the
lifetime of a local variable. When the method begins, its local variables and its parameter
variables are created in memory, and when the method ends, the local variables and parameter
variables are destroyed. This means that any value stored in a local variable is lost between calls
to the method in which the variable is declared.
15 | P a g e
NCP 2210 (Computer Fundamentals & Programming)
value. The value, which is 16.0, is assigned to the x variable by the = operator. In this section, we
will discuss how you can write your own value-returning methods.
This code defines a method named sum that accepts two int arguments. The arguments
are passed into the parameter variables num1 and num2. Inside the method, a local variable,
result, is declared. The parameter variables num1 and num2 are added, and their sum is assigned
to the result variable. The last statement in the method is as follows:
return result;
This is a return statement. You must have a return statement in a value-returning method.
It causes the method to end execution and it returns a value to the statement that called the
method. In a value-returning method, the general format of the return statement is as follows:
return Expression;
Expression is the value to be returned. It can be any expression that has a value, such as a
variable, literal, or mathematical expression. In this case, the sum method returns the value in the
result variable. However, we could have eliminated the result variable and returned the
expression num1 + num2, as shown in the following code:
public static int sum(int num1, int num2) {
return num1 + num2;
}
16 | P a g e
NCP 2210 (Computer Fundamentals & Programming)
@return tag inside a method’s documentation comments, it knows that a description of the
method’s return value appears next.
The general format of a @return tag comment is as follows:
@return Description
Description is a description of the return value. Remember the following points about
@return tag comments:
The @return tag in a method’s documentation comment must appear after the
general description of the method.
The description can span several lines. It ends at the end of the documentation
comment (the */ symbol), or at the beginning of another tag.
When a method’s documentation comments contain a @return tag, the javadoc utility
will create a Returns section in the method’s documentation. This is where the description of the
method’s return value will be listed.
Example Program #9
/**
* @author Joan Lazaro
*/
public class ValueReturn {
public static void main(String[] args) {
int total, value1 = 20, value2 = 40;
// Call the sum method, passing the contents of
// value1 and value2 as arguments. Assign the
// return value to the total variable.
total = sum(value1, value2);
// Display the contents of all these variables.
System.out.println("The sum of " + value1 + " and " + value2 + " is "
+ total);
}
/**
The sum method returns the sum of its two parameters.
@param num1 The first number to be added.
@param num2 The second number to be added.
@return The sum of num1 and num2.
*/
public static int sum(int num1, int num2) {
int result; // result is a local variable
// Assign the value of num1 + num2 to result.
result = num1 + num2;
// Return the value in the result variable.
return result;
}
}
Result:
17 | P a g e
NCP 2210 (Computer Fundamentals & Programming)
Observation:
In this sample problem it displays not only the answer but also a descriptive concept of where the
answer came from and how it is computed.
When you call a value-returning method, you usually want to do something meaningful
with the value it returns. The ValueReturn.java program shows a method’s return value being
assigned to a variable. This is commonly how return values are used, but you can do many other
things with them. For example, the following code shows a math expression that uses a call to
the sum method:
int x = 10, y = 15;
double average;
average = sum(x, y) / 2.0;
In the last statement, the sum method is called with x and y as its arguments. The
method’s return value, which is 25, is divided by 2.0. The result, 12.5, is assigned to average.
Here is another example:
int x = 10, y = 15;
System.out.println("The sum is " + sum(x, y));
This code sends the sum method’s return value to System.out.println, so it can be
displayed on the screen. The message “The sum is 25” will be displayed.
Remember, a value-returning method returns a value of a specific data type. You can use the
method’s return value anywhere that you can use a regular value of the same data type. This
means that anywhere an int value can be used, a call to an int value-returning method can be
used. Likewise, anywhere a double value can be used, a call to a double value-returning method
can be used. The same is true for all other data types.
18 | P a g e
NCP 2210 (Computer Fundamentals & Programming)
Frequently there is a need for a method that tests an argument and returns a true or false
value indicating whether or not a condition exists. Such a method would return a boolean value.
For example, the following method accepts an argument and returns true if the argument is
within the range of 1 through 100, or false otherwise:
public static boolean isValid(int number) {
boolean status;
if (number >= 1 && number <= 100)
status = true;
else
status = false;
return status;
}
The following code shows an if-else statement that uses a call to the method:
int value = 20;
if (isValid(value))
System.out.println("The value is within range.");
else
System.out.println("The value is out of range.");
When this code executes, the message “The value is within range.” will be displayed.
Result:
19 | P a g e
NCP 2210 (Computer Fundamentals & Programming)
Observation:
In problem 10, it just simply shows us the method of returning and it will display what you
inputted. It links 2 strings together.
20 | P a g e