Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Q3 G12 Programming M1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 32

Republic of the Philippines

Department of Education

NAME: ________________________________________ DATE: ________________

GRADE & SECTION: ___________________________ TEACHER: _____________

MODULE IN PROGRAMMING NC III


GRADE 12
THIRD QUARTER
WEEK 1

MOST ESSENTIAL LEARNING COMPETENCY

Define fundamental object-oriented terminology in accordance with Java


framework. TLE_ICTJAVA11-12POAD-IIId-g-31

t OBJECTIVES
1. Define math functions in accordance with Java framework.
2. Define character data type in accordance with Java framework.

PRE-TEST IDENTIFICATION (10 Points)

Directions: Read each item carefully and identify concept/terms on every


item. Write your answer on the space provided.

1. What method returns 𝑒 raised to power of 𝑥 (𝑒 𝑥 )?


_________________________________________________________________________________

2. What method returns 𝑎 raised to the power of 𝑏(𝑎𝑏 )?

_________________________________________________________________________________

3. What method returns the square root of 𝑥 (√𝑥 )𝑓𝑜𝑟 𝑥 ≥ 0?

_________________________________________________________________________________

2
4. What data type is used to represent a single character?

_________________________________________________________________________________

5. What supports the interchange, processing, and display of written texts in


the world’s diverse languages?

_________________________________________________________________________________

MATH FUNCTIONS AND CHARACTER DATA TYPE

The Java Math Functions

The Java Math class has many methods that allows performing mathematical
tasks on numbers. Math class provides two useful double constants, PI and E
(the base of natural logarithms) and used as Math.PI and Math.E in any
program. The Math class is used in the program, but not imported, because it is
in the java.lang package. All the classes in the java.lang package are implicitly
imported in a Java program.

Exponent Methods in Math Class

Method Description

exp(𝑥) Returns 𝑒 raised to power of 𝑥 (𝑒 𝑥 ).


log(𝑥) Returns the natural logarithm of 𝑥 (𝑙𝑛(𝑥) = 𝑙𝑜𝑔𝑒 (𝑥)).
log10(𝑥) Returns the base 10 logarithm of 𝑥 (𝑙𝑜𝑔10 (𝑥)).
pow(𝑎, 𝑏) Returns 𝑎 raised to the power of 𝑏(𝑎𝑏 ).
sqrt(𝑥) Returns the square root of 𝑥 (√𝑥 ) 𝑓𝑜𝑟 𝑥 ≥ 0

For example:

Math.exp(1) returns 2.71828


Math.log(Math.E) returns 1.0
Math.log10(10) returns 1.0
Math.pow(2, 3) returns 8.0
Math.pow(3, 2) returns 9.0
Math.pow(4.5, 2.5) returns 42.95673

3
Math.sqrt(4) returns 2.0
Math.sqrt(10.5) returns 3.24

Rounding Methods in Math Class

Method Description

ceil(x) x is rounded up to its nearest integer. This integer is returned as a


double value.

floor(x) x is rounded down to its nearest integer. This integer is returned as a


double value.

rint(x) x is rounded up to its nearest integer. If x is equally close to two


integers, the even one is returned as a double value.

round(x) Returns (int)Math.floor(x+0.5) if x is a float and returns


(long)Math.floor(x+0.5) if x is a double.

For example:

Math.ceil(2.1) returns 3.0


Math.ceil(2.0) returns 2.0
Math.ceil(-2.0) returns -2.0
Math.ceil(-2.1) returns -2.0
Math.floor(2.1) returns 2.0
Math.floor(2.0) returns 2.0
Math.floor(-2.0) returns –2.0
Math.floor(-2.1) returns -3.0
Math.rint(2.1) returns 2.0
Math.rint(-2.0) returns –2.0
Math.rint(-2.1) returns -2.0
Math.rint(2.5) returns 2.0
Math.rint(4.5) returns 4.0
Math.rint(-2.5) returns -2.0

4
Math.round(2.6f) returns 3
Math.round(2.0) returns 2
Math.round(-2.0f) returns -2
Math.round(-2.6) returns -3
Math.round(-2.4) returns -2

Min, Max and Abs Methods in Math Class

The min and max methods return the minimum and maximum numbers of two
numbers (int, long, float, or double).

For example: max(4.4, 5.0) returns 5.0, and min(3, 2) returns 2.

The abs method returns the absolute value of the number (int, long, float, or
double).

For example:

Math.max(2, 3) returns 3
Math.max(2.5, 3) returns 3.0
Math.min(2.5, 4.6) returns 2.5
Math.abs(-2) returns 2
Math.abs(-2.1) returns 2.1

Character Data Type and Operations

The character data type, char, is used to represent a single character. A


character literal is enclosed in single quotation marks.

char letter = 'A';


char numChar = '4';

The first statement assigns character A to the char variable letter. The second
statement assigns digit character 4 to the char variable numChar.

5
A string literal must be enclosed in quotation marks (" "). A character literal is a
single character enclosed in single quotation marks (' '). Therefore, "A" is a string,
but 'A' is a character.

Unicode and ASCII Code

A character is stored in a computer as a sequence of 0s and 1s. Mapping a


character to its binary representation is called encoding. Encoding scheme
determines how characters are encoded. Java supports Unicode, to support the
interchange, processing, and display of written texts in the world’s diverse
languages.

Most computers use ASCII (American Standard Code for Information


Interchange), an 8-bit encoding scheme for representing all uppercase and
lowercase letters, digits, punctuation marks, and control characters. Unicode
includes ASCII code, with \u0000 to \u007F corresponding to the 128 ASCII
characters.

ASCII Code for Commonly Used Characters

Characters Code Value in Decimal Unicode Value

'0' to '9' 48 to 57 \u0030 to \u0039


'A' to 'Z' 65 to 90 \u0041 to \u005A
'a' to 'z' 97 to 122 \u0061 to \u007A

Comparing and Testing Characters

Two characters can be compared using the relational operators the same way as
comparing two numbers. This is done by comparing the Unicodes of the two
characters.

'a' < 'b' is true because the Unicode for 'a' (97) is less than the Unicode for 'b'
(98).

'a' < 'A' is false because the Unicode for 'a' (97) is greater than the Unicode for 'A'
(65).

'1' < '8' is true because the Unicode for '1' (49) is less than the Unicode for '8'
(56).

6
In programming, we may need to test whether a character is a number, a letter,
an uppercase letter, or a lowercase letter. The following code tests whether a
character ch is an uppercase letter, a lowercase letter, or a digital character.

if (ch >= 'A' && ch <= 'Z')


System.out.println(ch + " is an uppercase letter");

else if (ch >= 'a' && ch <= 'z')


System.out.println(ch + " is a lowercase letter");

else if (ch >= '0' && ch <= '9')


System.out.println(ch + " is a numeric character");

Methods in the Character Class

Method Description

isDigit(ch) Returns true if the specified character is a digit.


isLetter(ch) Returns true if the specified character is a letter.
isLetterOfDigit(ch) Returns true if the specified character is a letter or digit.
isLowerCase(ch) Returns true if the specified character is a lowercase letter.
isUpperCase(ch) Returns true if the specified character is an uppercase letter.
toLowerCase(ch) Returns the lowercase of the specified character.
toUpperCase(ch) Returns the uppercase of the specified character.

For example:

System.out.println("isDigit('a') is " + Character.isDigit('a'));


System.out.println("isLetter('a') is " + Character.isLetter('a'));
System.out.println("isLowerCase('a') is " + Character.isLowerCase('a'));
System.out.println("isUpperCase('a') is " + Character.isUpperCase('a'));
System.out.println("toLowerCase('T') is " + Character.toLowerCase('T'));
System.out.println("toUpperCase('q') is " + Character.toUpperCase('q'));

7
Displays:

isDigit('a') is false
isLetter('a') is true
isLowerCase('a') is true
isUpperCase('a') is false
toLowerCase('T') is t
toUpperCase('q') is Q

Reading a Character from the Console

To read a character from the console, we use the nextLine() method to read a
string and then invoke the charAt(0) method on the string to return a character.

For example, the following code reads a character from the keyboard:

Scanner input = new Scanner(System.in);

System.out.print("Enter a character: ");


String s = input.nextLine();

char ch = s.charAt(0);

System.out.println("The character entered is " + ch);

POST-TEST IDENTIFICATION (10 Points)

Direction: Read each item carefully and identify concept/terms on every


item. Write your answer on the space provided. (10 points)

1. What method returns the minimum and maximum numbers of two


numbers?

_________________________________________________________________________________

8
2. What method returns the absolute value of the number?

3. What method returns the natural logarithm of 𝑥 (𝑙𝑛(𝑥) = 𝑙𝑜𝑔𝑒 (𝑥))?

4. What method returns true if the specified character is a digit?

_________________________________________________________________________________

5. What is an 8-bit encoding scheme for representing all uppercase and


lowercase letters, digits, punctuation marks, and control characters?

_________________________________________________________________________________

9
NAME: ________________________________________ DATE: ________________

GRADE & SECTION: ___________________________ TEACHER: _____________

MODULE IN PROGRAMMING NC III


GRADE 12
THIRD QUARTER
WEEK 2

MOST ESSENTIAL LEARNING COMPETENCY

• Describe object-oriented concepts in accordance with Java framework.


TLE_ICTJAVA11-12POAD-IIId-g-31

OBJECTIVES

1. Describe defining a method in accordance with Java framework.


2. Describe calling a method in accordance with Java framework.

PRE-TEST IDENTIFICATION (10 Points)

Direction: Read each item carefully and identify concept/terms on every


item. Write your answer on the space provided.

1. What can be used to define reusable code, organize and simplify coding?

_________________________________________________________________________________

2. What method returns true if the specified character is a letter?

_________________________________________________________________________________

3. What returns the uppercase of the specified character??

_________________________________________________________________________________

4. What method returns true if the specified character is an uppercase letter?

_________________________________________________________________________________

10
5. What returns the lowercase of the specified character?

_________________________________________________________________________________

METHODS

Methods can be used to define reusable codes, organize and simplify codes.

In the following examples, we need to find the sum of integers from 1 to 10, from
20 to 34, and from 35 to 50, respectively. We may write the code as follows:

int sum = 0;
for (int i = 1; i <= 10; i++)

sum += i;
System.out.println("Sum from 1 to 10 is " + sum);

sum = 0;
for (int i = 20; i <= 34; i++)

sum += i;
System.out.println("Sum from 20 to 34 is " + sum);

sum = 0;
for (int i = 35; i <= 50; i++)

sum += i;
System.out.println("Sum from 35 to 50 is " + sum);

We have observed that computing these sums from 1 to 10, from 20 to 34, and
from 35 to 50 are very similar except that the starting and ending integers are
different. We can write a common code once and reuse it by defining a method
and invoking it. The preceding code can be simplified as follows:

1 public static int sum(int i1, int i2)


2 {
3 int result = 0;
4 for (int i = i1; i <= i2; i++)
5 result = result + i;

11
6 return result;
7 }
8
9 public static void main(String[] args)
10 {
11 System.out.println("Sum from 1 to 10 is " + sum(1, 10));
12 System.out.println("Sum from 20 to 34 is " + sum(20, 34));
13 System.out.println("Sum from 35 to 50 is " + sum(35, 50));
14 }

Lines 1–7 define the method named sum with two parameters i1 and i2. The
statements in the main method invoke sum(1, 10) to compute the sum from 1
to 10, sum(20, 34) to compute the sum from 20 to 34, and sum(35, 50) to
compute the sum from 35 to 50.

A method is a collection of statements grouped together to perform an operation.


We have used predefined methods in java before such as System.out.println,
System.out.print, Math.pow, and Math.random. These methods are defined in
the Java library.

Defining a Method

A method definition consists of its method name, parameters, return value


type, and body.

The syntax for defining a method is as follows:

modifier returnValueType methodName(list of parameters)


{
// Method body;
}

Here is a method defined to find the larger between two integers. This method,
named max, has two int parameters, num1 and num2, the larger of which is
returned by the method.

12
Define a method

A method definition consists of a method header and a method body.

Invoke a method

The method header specifies the modifiers, return value type, method name,
and parameters of the method. The static modifier is used in the example. A
method may return a value. The returnValueType is the data type of the value
the method returns. Some methods perform operations without returning a
value. In this case, the returnValueType is the keyword void. For example, the
returnValueType is void in the main method, as well as in System.exit, and
System.out.println. If a method returns a value, it is called a value-returning
method; otherwise, it is called a void method.

Some programming languages refer to methods as procedures and functions. In


these languages, a value-returning method is called a function and a void
method is called a procedure.

13
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. The parameter list refers to the method’s
type, order, and number of the parameters. The method name and the
parameter list together constitute the method signature. Parameters are optional
as a method may contain no parameters. For example, the Math.random()
method has no parameters.

In the method header, we need to declare each parameter separately. For


instance, max(int num1, int num2) is correct, but max(int num1, num2) is
wrong.

The method body contains a collection of statements that implement the method.
The method body of the max method uses an if statement to determine which
number is larger and return the value of that number. For a value-returning
method to return a result, a return statement using the keyword return is
required. The method terminates when a return statement is executed.

When we say, “define a method” and “declare a variable”, we make a distinction.


A definition defines what the defined item is, but a declaration usually involves
allocating memory to store data for the declared item.

Calling a Method

Calling a method executes the code in the method. In a method definition, we


define what the method is to do. To execute the method, we 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.

14
Another example of a call that is treated as a value is

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

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. The following is a program to test the max method.

1 public class TestMaximum


2 {
3 /** Main method */
4 public static void main(String[] args)
5 {
6 int i = 5;
7 int j = 2;
8 int k = max(i, j);
9 System.out.println("The maximum of " + i + " and " + j + " is " + k);
10 }
11
12 /** Return the max of two numbers */
13 public static int max(int num1, int num2)
14 {
15 int result;
16
17 if (num1 > num2)
18 result = num1;
19 else
20 result = num2;
21
22 return result;
23 }
24 }

15
This program contains the main method and the max method. The main method
is like any other method except that it is invoked by the JVM to start the
program. The main method’s header is always the same. It includes the modifiers
public and static, return value type void, method name main, and a parameter
of the String [] type. String [] indicates that the parameter is an array of String.

The statements in main may invoke other methods that are defined in the class
that contains the main method or in other classes. In this example, the main
method invokes max(i, j), which is defined in the same class with the main
method.

When the max method is invoked (line 8), variable i’s value 5 is passed to num1,
and variable j’s value 2 is passed to num2 in the max method. The flow of control
transfers to the max method, and the max method is executed. When the return
statement in the max method is executed, the max method returns the control
to its caller (in this case the caller is the main method).

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.

16
POST-TEST IDENTIFICATION (10 Points)

Direction: Read each item carefully and identify concept/terms on every


item. Write your answer on the space provided.

1. What is a collection of statements grouped together to perform an


operation?

_________________________________________________________________________________

2. What specifies the modifiers, return value type, method name, and
parameters of the method?

_________________________________________________________________________________

3. What is the value passed to the parameter when a method is invoked?

_________________________________________________________________________________

4. What is the keyword used for a value-returning method to return a result?

_________________________________________________________________________________

5. What is called a method that returns a value?

_________________________________________________________________________________

17
NAME: _________________________________________ DATE: ________________

GRADE & SECTION: ___________________________ TEACHER: _____________

MODULE IN PROGRAMMING NC III


GRADE 12
THIRD QUARTER
WEEK 3

MOST ESSENTIAL LEARNING COMPETENCY

• Describe object-oriented concepts in accordance with Java framework.


TLE_ICTJAVA11-12POAD-IIId-g-31

OBJECTIVES

1. Describe defining a method in accordance with Java framework.


2. Describe calling a method in accordance with Java framework.

PRE-TEST IDENTIFICATION (10 Points)

Direction: Read each item carefully and identify concept/terms on every


item. Write your answer on the space provided.

1. What method does not return a value?

_________________________________________________________________________________

2. What statement can be used for terminating a method and returning to a


method’s caller?

_________________________________________________________________________________

3. What is a variable in the method with its own memory space?

_________________________________________________________________________________

4. What is the term used to provide arguments with the same order as their
respective parameters in the method signature?

_________________________________________________________________________________

18
5. What is the term used when a method with an argument is invoked, the
value of the argument is passed to the parameter?

_________________________________________________________________________________

METHODS

VOID Method

A void method does not return a value. The example below shows how to define
and invoke a void method. The program defines a method named printGrade and
invokes it to print the grade for a given score.
1 public class TestVoidMethod
2 {
3 public static void main(String[] args)
4 {
5 System.out.print("The grade is ");
6 printGrade(78.5);
7
8 System.out.print("The grade is ");
9 printGrade(59.5);
10 }
11
12 public static void printGrade(double score)
13 {
14 if (score >= 90.0)
15 {
16 System.out.println('A');
17 }
18 else if (score >= 80.0)
19 {
20 System.out.println('B');
21 }
22 else if (score >= 70.0)
23 {
24 System.out.println('C');
25 }
26 else if (score >= 60.0)
27 {
28 System.out.println('D');

19
29 }
30 else
31 {
32 System.out.println('F');
33 }
34 }
35 }

Program Output:

The grade is C
The grade is F

The printGrade method is a void method because it does not return any value.
A call to a void method must be a statement. Therefore, it is invoked as a
statement in line 6 in the main method, terminated with a semicolon. To see the
difference between a void and value-returning method, the following printGrade
method is redesigned to return a value. The new method, getGrade, returns the
grade.

1 public class TestReturnGradeMethod


2 {
3 public static void main(String[] args)
4 {
5 System.out.print("The grade is " + getGrade(78.5));
6 System.out.print("\nThe grade is " + getGrade(59.5));
7 }
8
9 public static char getGrade(double score)
10 {
11 if (score >= 90.0)
12 return 'A';
13 else if (score >= 80.0)
11 return 'B';
12 else if (score >= 70.0)
13 return 'C';
14 else if (score >= 60.0)
15 return 'D';
16 else
17 return 'F';
18 }
19 }

20
The getGrade method defined in lines 9–18 returns a character grade based on
the numeric score value. The caller invokes this method in lines 5-6. The
getGrade method can be invoked by a caller wherever a character may appear.
The printGrade method does not return any value, so it must be invoked as a
statement.

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. The syntax is
simply: return;

public static void printGrade(double score)


{
if (score < 0 || score > 100)
{
System.out.println("Invalid score");
return;
}

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

21
Passing Arguments by Values

The arguments are passed by value to parameters when invoking a method. We


can use println to print any string and max to find the maximum of any two int
values. When calling a method, we 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 example, 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);
}

We 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 parameter, message, nor does the second argument, Hello, match the
second parameter, n.

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.

When we 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. As shown in the following sample problem, the
value of x (1) is passed to the parameter n to invoke the increment method (line
7). The parameter n is incremented by 1 in the method (line 11), but x is not
changed no matter what the method does.

1 public class Increment


2 {
3 public static void main(String[] args)
4 {

22
5 int x = 1;
6 System.out.println("Before the call, x is " + x);
7 increment(x);
8 System.out.println("After the call, x is " + x);
9 }
10
11 public static void increment(int n)
12 {
13 n++;
14 System.out.println("n inside the method is " + n);
15 }
16 }

Program Output:

Before the call, x is 1


n inside the method is 2
After the call, x is 1

This problem gives another program that demonstrates the effect of passing by
value. The program creates a method for swapping two variables. The swap
method is invoked by passing two arguments. Interestingly, the values of the
arguments are not changed after the method is invoked.

1 public class TestPassByValue


2 {
3 public static void main(String[] args)
4 {
5 //Declare and initialize variables
6 int num1 = 1;
7 int num2 = 2;
8
9 System.out.println("Before invoking the swap method, num1 is " +
10 num1 + " and num2 is " + num2);
11
12 //Invoke the swap method to attempt to swap two variables
13 swap(num1, num2);
14
15 System.out.println("After invoking the swap method, num1 is " +
16 num1 + " and num2 is " + num2);

23
17 }
18
19 /** Swap two variables */
20 public static void swap(int n1, int n2)
21 {
22 System.out.println("\tInside the swap method");
23 System.out.println("\t\tBefore swapping, n1 is " + n1
24 + " and n2 is " + n2);
25
26 //Swap n1 with n2
26 int temp = n1;
27 n1 = n2;
28 n2 = temp;
29
30 System.out.println("\t\tAfter swapping, n1 is " + n1
31 + " and n2 is " + n2);
32 }
33 }

Program Output:

Before invoking the swap method, num1 is 1 and num2 is 2


Inside the swap method
Before swapping, n1 is 1 and n2 is 2
After swapping, n1 is 2 and n2 is 1
After invoking the swap method, num1 is 1 and num2 is 2

Before the swap method is invoked (line 13), num1 is 1 and num2 is 2. After the
swap method is invoked, num1 is still 1 and num2 is still 2. Their values have
not been swapped. As shown above, the values of the arguments num1 and
num2 are passed to n1 and n2, but n1 and n2 have their own memory locations
independent of num1 and num2. Therefore, changes in n1 and n2 do not affect
the contents of num1 and num2. The parameter is a variable in the method with
its own memory space. The variable is allocated when the method is invoked,
and it disappears when the method is returned to its caller.

24
POST-TEST IDENTIFICATION (10 Points)

Direction: Read each item carefully and identify concept/terms on every


item. Write your answer on the space provided.

1. What is part of a method declaration that accepts values from the method
call?

_________________________________________________________________________________

2. What is the value or variable passed to a method?

_________________________________________________________________________________

3. What is passing the value of an argument to a method?

_________________________________________________________________________________

4. What is a statement used to send a value from a method back to the calling
statement?

_________________________________________________________________________________

5. What is a keyword used in the declaration of a method to indicate that


the method will not return a value?

_________________________________________________________________________________

25
NAME: _________________________________________ DATE: ________________

GRADE & SECTION: ___________________________ TEACHER: _____________

MODULE IN PROGRAMMING NC III


GRADE 12
THIRD QUARTER
WEEK 4

MOST ESSENTIAL LEARNING COMPETENCY

• Describe object-oriented concepts in accordance with Java framework.


TLE_ICTJAVA11-12POAD-IIId-g-31

OBJECTIVES

1. Describe defining a method in accordance with Java framework.


2. Describe calling a method in accordance with Java framework.

PRE-TEST IDENTIFICATION (10 Points)

Direction: Read each item carefully and identify concept/terms on every


item. Write your answer on the space provided.

1. What is a statement that contains method name followed by parentheses?

_________________________________________________________________________________

2. What is writing more than one method of the same name in a class?

_________________________________________________________________________________

3. What is an access modifier used in the declaration of a method to indicate


that the method is visible to any other class?

_________________________________________________________________________________

4. What is called a value or variable passed to a method?

_________________________________________________________________________________

26
5. What is called a statement used to send a value from a method back to
the calling statement?

_________________________________________________________________________________

Modularizing Code

Modularizing makes the code easy to maintain and debug and enables the code
to be reused. 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. The following program prompts the user to enter two integers and
displays their greatest common divisor.
1 import java.util.Scanner;
2 public class GreatestCommonDivisorMethod
3 {
4 /** Main method */
5 public static void main(String[] args)
6 {
7 Scanner input = new Scanner(System.in);
8
9 System.out.print("Enter first integer: ");
10 int n1 = input.nextInt();
11 System.out.print("Enter second integer: ");
12 int n2 = input.nextInt();
13
14 System.out.println("The greatest common divisor for " + n1 +
15 " and " + n2 + " is " + gcd(n1, n2));
16 }
17
18 /** Return the gcd of two integers */
19 public static int gcd(int n1, int n2)
20 {
21 int gcd = 1; // Initial gcd is 1
22 int k = 2; // Possible gcd
23 while (k <= n1 && k <= n2)
24 {
25 if (n1 % k == 0 && n2 % k == 0)
26 gcd = k; // Update gcd
27 k++; Program Output:
28 }
29 Enter first integer: 45
Enter second integer: 75
30 return gcd; // Return gcd The greatest common divisor for 45 and 75 is 15
31 }
32 }

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

Concept of code modularization to improve program


1 public class PrimeNumberMethod
2 {
3 public static void main(String[] args)
4 {
5 System.out.println("The first 50 prime numbers are \n");
6 printPrimeNumbers(50);
7 }
8
9 public static void printPrimeNumbers(int numberOfPrimes)
10 {
11 final int NUMBER_OF_PRIMES_PER_LINE = 10;
12 int count = 0; //Count the number of prime numbers
13 int number = 2; //A number to be tested for primeness
14 // Repeatedly find prime numbers
15 while (count < numberOfPrimes)
16 {
17 //Print the prime number and increase the count
18 if (isPrime(number))
19 {
20 count++; //Increase the count
21
22 if (count % NUMBER_OF_PRIMES_PER_LINE == 0)
23 {
24 //Print the number and advance to the new line
25 System.out.printf("%-5s\n", number);
26 }
27 else
28 System.out.printf("%-5s", number);
29 }
30
31 // Check whether the next number is prime
32 number++;
33 }
34 }
35
36 /** Check whether number is prime */
37 public static boolean isPrime(int number)
38 {

28
39 for (int divisor = 2; divisor <= number / 2; divisor++)
40 {
41 if (number % divisor == 0)
42 {
43 //If true, number is not prime
44 return false; // Number is not a prime
45 }
46 }
47 return true; // Number is prime
40 }
41 } Program Output:
The first 50 prime numbers are
2 3 5 7 11 13 17 19 23 29
31 37 41 43 47 53 59 61 67 71
73 79 83 89 97 101 103 107 109 113
127 131 137 139 149 151 157 163 167 173
179 181 191 193 197 199 211 223 227 229

The large program was divided 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.

Overloading Methods

Overloading methods enables us to define the methods with the same name as
long as their signatures are different. The max method that was used earlier
works only with the int data type. How 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, as shown in the following:

public static double max(double num1, double num2)


{
if (num1 > num2)
return num1;
else
return num2;
}
If we call max with int parameters, the max method that expects int parameters
will be invoked; if we 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

29
lists within one class. The Java compiler determines which method to use based
on the method signature.

The following program creates three methods. The first finds the maximum
integer, the second finds the maximum double, and the third finds the maximum
among three double values. All three methods are named max.
1 public class TestMethodOverloading
2 {
3 /** Main method */
4 public static void main(String[] args)
5 {
6 // Invoke the max method with int parameters
7 System.out.println("The maximum of 3 and 4 is " + max(3, 4));
8
9 // Invoke the max method with the double parameters
10 System.out.println("The maximum of 3.0 and 5.4 is "
11 + max(3.0, 5.4));
12
13 // Invoke the max method with three double parameters
14 System.out.println("The maximum of 3.0, 5.4, and 10.14 is "
15 + max(3.0, 5.4, 10.14));
16 }
17
18 /** Return the max of two int values */
19 public static int max(int num1, int num2)
20 {
21 if (num1 > num2) Program Output:
22 return num1;
23 else The maximum of 3 and 4 is 4
24 return num2; The maximum of 3.0 and 5.4 is 5.4
25 } The maximum of 3.0, 5.4, and 10.14 is 10.14
26
27 /** Find the max of two double values */
28 public static double max(double num1, double num2)
29 {
30 if (num1 > num2)
31 return num1;
32 else
33 return num2;
34 }
35
36 /** Return the max of three double values */
37 public static double max(double num1, double num2, double num3)
38 {
39 return max(max(num1, num2), num3);
40 }
41 }

30
When calling max(3, 4) (line 7),the max method for finding the maximum of two
integers is invoked. When calling max(3.0, 5.4) (line 11), the max method for
finding the maximum of two doubles is invoked. When calling max(3.0, 5.4,
10.14) (line 15), the max method for finding the maximum of three double values
is invoked.

Can we invoke the max method with an int value and a double value, such as
max(2,2.5)? If so, which of the max methods is invoked? The answer is yes and
the max method for finding the maximum of two double values is invoked. The
argument value 2 is automatically converted into a double value and passed to
this method.

We may be wondering why the method max(double, double) is not invoked for
the call max(3, 4). Both max(double, double) and max(int, int) are possible
matches for max(3, 4). The Java compiler finds the method that best matches a
method invocation. Since the method max(int, int) is a better matches for
max(3, 4) than max(double, double), max(int, int) is used to invoke max(3, 4).

Overloading methods can make programs clearer and more readable. Methods
that perform the same function with different types of parameters should be
given the same name. Overloaded methods must have different parameter lists
and we cannot overload methods based on different modifiers or return types.

POST-TEST IDENTIFICATION (10 Points)

Direction: Read each item carefully and identify concept/terms on every


item. Write your answer on the space provided.

1. What keyword is used in the declaration of a method to indicate that the


method will not return a value?
_________________________________________________________________________________

2. What is writing more than one method of the same name in a class?
_________________________________________________________________________________
3. What is giving data to a method by enclosing the data in parentheses in
the method call?
_________________________________________________________________________________

4. What is part of a method declaration that accepts values from the method
call?
_________________________________________________________________________________

31
5. What is passing the value of an argument to a method. The type of data
passed depends on whether the argument is a primitive or an object?
_________________________________________________________________________________

ANSWER KEY TO PRE-TESTS AND POST-TESTS

Week 1 Week 2
Pretest Posttest Pretest Posttest
1. exp(𝑥) 1. Math.max() 1. method 1. method
Math.min()
2. pow(𝑎,𝑏) 2. Math.abs() 2. isLetter(ch) 2. method header
3. sqrt(𝑥) 3. log(x) 3. toUpperCase(ch) 3. argument
4. char 4. isDigit(ch) 4. isUpperCase(ch) 4. return
5. Unicode 5. ASCII 5. toLowerCase(ch) 5. value-returning
method

Week 3 Week 4
Pretest Posttest Pretest Posttest
1. void 1. method 1. call 1. void
parameter
2. return 2. argument 2. method 2. method
overloading overloading
3. parameter 3. pass by value 3. public 3. pass
4. parameter order 4. return 4. argument 4. method
association parameter
5. invoke a method 5. void 5. return 5. pass by value

REFERENCES:

Deitel, P. & Deitel, H. (2012). Java How to Program. 9th Edition

Brown, B. (2005). A Guide to Programming Java. 5 th Edition

Gaddis, T. (2015). Starting-Out with Java. 5 th Edition

Downey, A. & Mayfield, C. (2016). Think Java. 1st Edition

Hubbard, J. (2004). Programming with Java. 2 nd Edition

Liang, Y. Daniel (2011). Introduction to Java. 10 th Edition

W3Schools Online Web Tutorials. (2021). [online] Available at:


<https://www.w3schools.com/>

32

You might also like