Q3 G12 Programming M1
Q3 G12 Programming M1
Q3 G12 Programming M1
Department of Education
t OBJECTIVES
1. Define math functions in accordance with Java framework.
2. Define character data type in accordance with Java framework.
_________________________________________________________________________________
_________________________________________________________________________________
2
4. What data type is used to represent a single character?
_________________________________________________________________________________
_________________________________________________________________________________
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.
Method Description
For example:
3
Math.sqrt(4) returns 2.0
Math.sqrt(10.5) returns 3.24
Method Description
For example:
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
The min and max methods return the minimum and maximum numbers of two
numbers (int, long, float, or double).
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
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.
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.
Method Description
For example:
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
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:
char ch = s.charAt(0);
_________________________________________________________________________________
8
2. What method returns the absolute value of the number?
_________________________________________________________________________________
_________________________________________________________________________________
9
NAME: ________________________________________ DATE: ________________
OBJECTIVES
1. What can be used to define reusable code, organize and simplify coding?
_________________________________________________________________________________
_________________________________________________________________________________
_________________________________________________________________________________
_________________________________________________________________________________
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:
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.
Defining a Method
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
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.
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.
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.
Calling a Method
For example:
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!");
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)
_________________________________________________________________________________
2. What specifies the modifiers, return value type, method name, and
parameters of the method?
_________________________________________________________________________________
_________________________________________________________________________________
_________________________________________________________________________________
_________________________________________________________________________________
17
NAME: _________________________________________ DATE: ________________
OBJECTIVES
_________________________________________________________________________________
_________________________________________________________________________________
_________________________________________________________________________________
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.
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;
21
Passing Arguments by Values
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.
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:
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.
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 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)
1. What is part of a method declaration that accepts values from the method
call?
_________________________________________________________________________________
_________________________________________________________________________________
_________________________________________________________________________________
4. What is a statement used to send a value from a method back to the calling
statement?
_________________________________________________________________________________
_________________________________________________________________________________
25
NAME: _________________________________________ DATE: ________________
OBJECTIVES
_________________________________________________________________________________
2. What is writing more than one method of the same name in a class?
_________________________________________________________________________________
_________________________________________________________________________________
_________________________________________________________________________________
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.
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:
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.
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?
_________________________________________________________________________________
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:
32