0% found this document useful (0 votes)
8 views

IT 201 Module 3

This document discusses methods in Java programming. It explains that methods can define reusable code and simplify organization. Methods consist of a method header that specifies the name, parameters, return type, and modifiers, as well as a method body. The document provides examples of defining methods to calculate the sum of integers and find the maximum of two numbers. It demonstrates how to call methods by passing arguments and using the return value. The objectives are to learn how to define, invoke, pass parameters to and return values from methods in Java.

Uploaded by

lanilyn mongado
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)
8 views

IT 201 Module 3

This document discusses methods in Java programming. It explains that methods can define reusable code and simplify organization. Methods consist of a method header that specifies the name, parameters, return type, and modifiers, as well as a method body. The document provides examples of defining methods to calculate the sum of integers and find the maximum of two numbers. It demonstrates how to call methods by passing arguments and using the return value. The objectives are to learn how to define, invoke, pass parameters to and return values from methods in Java.

Uploaded by

lanilyn mongado
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/ 6

Introduction to Java Programming Module 3

PAG
E
SUBJECT : IT 201 \*
ME
DESCRIPTION : Fundamentals of Programming RGE
FOR
PREPARED BY : MR. ALEX B. GUIRIGAY
MA
T2
Module 3
TITLE: Methods

OVERVIEW
This module focuses on the applicability of methods in java. It discusses on how to define, invoke and to pass methods
with parameters and return values. It also tackles on how to develop reusable code, apply the concept of method and
design and implement methods using stepwise refinement.

OBJECTIVES
After the students read this module, they should be able:

• To define methods with formal parameters;


• To invoke methods with actual parameters (i.e., arguments);
• To define methods with a return value;
• To define methods without a return value;
• To pass arguments by value;
• To develop reusable code that is modular, easy to read, easy to debug, and easy to maintain;
• To write a method that converts hexadecimals to decimals;
• To use method overloading and understand ambiguous overloading;
• To determine the scope of variables;
• To apply the concept of method abstraction in software development; and
• To design and implement methods using stepwise refinement.

DISCUSSION
Introduction
Methods can be used to define reusable code and organize and simplify coding.

Suppose that you need to find the sum of integers from 1 to 10, from 20 to 37, and from 35 to 49, respectively. You 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 <= 37; i++)
sum += i;
System.out.println("Sum from 20 to 37 is " + sum);

sum = 0;
for (int i = 35; i <= 49; i++)
sum += i;
System.out.println("Sum from 35 to 49 is " + sum);

You may have observed that computing these sums from 1 to 10, from 20 to 37, and from 35 to 49 are very similar
except that the starting and ending integers are different. Wouldn’t it be nice if we could write the common code once
and reuse it? We can do so by defining a method and invoking it.
Introduction to Java Programming Module 3
PAG
E
The preceding code can be simplified as follows: \*
ME
RGE
FOR
Sample Program # 1: SummingIntegers.java MA
Description: A program that sums up three different sets of numbers using Method. T2
Code:

Line Code
No.
1 package Module3;

2 public class SummingIntegers {


3 public static int sum(int num1, int num2) {
4 int result = 0;
5 for (int num = num1; num <= num2; num++)
6 result += num;
7 return result;
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 }
14 }

Output:
Sum from 1 to 10 is 55
Sum from 20 to 37 is 513
Sum from 35 to 49 is 630

Lines 3–8 define the method named sum with two parameters num1 and num2. The statements in the main method
invoke sum(1, 10) to compute the sum from 1 to 10, sum(20, 37) to compute the sum from 20 to 37, and sum(35, 49) to
compute the sum from 35 to 49.

A method is a collection of statements grouped together to perform an operation. Some of the predefined methods
such as System.out.println, System.exit, Math.pow, and Math.random. These methods are defined in the Java library.
In this module, you will learn how to define your own methods and apply method abstraction to solve complex
problems.

Defining a Method
A method definition consists of its method name, parameters, return value type, and body.

Syntax:
modifier returnValueType methodName(list of parameters) {
// Method body;
}

Let’s look at 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. Figure 1 illustrates the components of this
method.
Introduction to Java Programming Module 3
PAG
E
Figure 1: A method definition consists of a method header and a method body. \*
Define a Method ME
RGE
modifier Method name FOR
MA
Return value type Formal parameters T2

public static int sum(int num1, int num2) { Method header


int result = 0;
for (int num = num1; num <= num2; num++)
result += num; Method body
return result;
}
The method header specifies the modifiers, return value type, method name, and parameters of the method. The static
modifier is used for all the methods in this module.

A method may return a value. The returnValueType is the data type of the value the method returns. Some methods
perform desired 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.

The variables defined in the method header are known as formal parameters or simply parameters.

Calling a Method
Calling a method executes the code in the method. To execute the method, you have to call or invoke it.

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

Sample Program # 2: TestMax.java


Description:
Code:
Line Code
No.
//This program determines the maximum between two numbers
1 package Module3;

2 public class TestMax {

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


4 int i = 5;
5 int j = 12;
6 int k = max(i, j);
7 System.out.println("The maximum between " + i + " and " + j + " is " + k);
8 }

/** Return the max between two numbers */


9 public static int max(int num1, int num2) {
10 int result;
Introduction to Java Programming Module 3
PAG
E
\*
11 if (num1 > num2) ME
12 result = num1; RGE
13 else FOR
14 result = num2;
MA
15 return result; T2
16 }
17 }

Output:
The maximum between 5 and 2 is 5

Figure 2: 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.

Caution: A return statement is required for a value-returning method. The method shown below in (a) is logically
correct, but it has a compile error because the Java compiler thinks that this method might not return a value.

To fix this problem, delete if (n < 0) in (a), so the compiler will see a return statement to be reached regardless of
how the if statement is evaluated.

Note: Methods enable code sharing and reuse. The max method can be invoked from any class, not just TestMax. If you
create a new class, you can invoke the max method using ClassName.methodName (i.e., TestMax.max).

Sample Program # 3: Increment.java


Description:

Code:
Line Code
No.
Introduction to Java Programming Module 3
PAG
E
1 package Module3; \*
ME
2 public class Increment { RGE
3 FOR
4 public static void main(String[] args) {
MA
5 int x = 1;
6 System.out.println("Before the call, x is " + x); T2
7 increment(x);
8 System.out.println("after the call, x is " + x);
}
10
11 public static void increment(int n) {
12 n++;
13 System.out.println("n inside the method is " + n);
14 }
}

Output:
Before the call, x is 1
n inside the method is 2
after the call, x is 1

Sample Program # 4: TestPassByValue.java


Description:

Code:
Line Code
No.
1 package Module3;

2 public class TestPassByValue {


3 /** Main method */
4 public static void main(String[] args) {
5 // Declare and initialize variables
6 int num1 = 1;
7 int num2 = 2;

8 System.out.println("Before invoking the swap method, num1 is " +


10 num1 + " and num2 is " + num2);

11 // Invoke the swap method to attempt to swap two variables


12 swap(num1, num2);

13 System.out.println("After invoking the swap method, num1 is " +


14 num1 + " and num2 is " + num2);
15 }

/** Swap two variables */


16 public static void swap(int n1, int n2) {
17 System.out.println("\tInside the swap method");
18 System.out.println("\t\tBefore swapping n1 is " + n1
19 + " n2 is " + n2);

// Swap n1 with n2
20 int temp = n1;
21 n1 = n2;
22 n2 = temp;

23 System.out.println("\t\tAfter swapping n1 is " + n1


24 + " n2 is " + n2);
25 }
26 }

Output:
Before invoking the swap method, num1 is 1 and num2 is 2
Inside the swap method
Introduction to Java Programming Module 3
PAG
E
Before swapping n1 is 1 n2 is 2 \*
After swapping n1 is 2 n2 is 1 ME
After invoking the swap method, num1 is 1 and num2 is 2 RGE
FOR
MA
Modularizing Code T2
Modularizing makes the code easy to maintain and debug and enables the code to be reused.

Sample Program # 5: GreatestCommonDivisorMethod.java


Description:

Code:
Line Code
No.
1 package Module3;
2 import java.util.Scanner;

3 public class GreatestCommonDivisorMethod {

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


// Create a Scanner
5 Scanner input = new Scanner(System.in);

// Prompt the user to enter two integers


6 System.out.print("Enter first integer: ");
7 int n1 = input.nextInt();
8 System.out.print("Enter second integer: ");
10 int n2 = input.nextInt();

11 System.out.println("The greatest common divisor for " + n1 +


12 " and " + n2 + " is " + gcd(n1, n2));
13 }

/** Return the gcd of two integers */


14 public static int gcd(int n1, int n2) {
15 int gcd = 1; // Initial gcd is 1
16 int k = 2; // Possible gcd

17 while (k <= n1 && k <= n2) {


18 if (n1 % k == 0 && n2 % k == 0)
19 gcd = k; // Update gcd
20 k++;
21 }

22 return gcd; // Return gcd


23 }
24 }

Output:
Enter first integer: 45
Enter second integer: 75
The greatest common divisor for 45 and 75 is 15

EVALUATION

REFERENCES
1. Y. Daniel Liang: Intro to Java Programming, Comprehensive Version (10th Edition); Pearson Education, Inc.,: 2015
2. Barry Burd: Java for Dummies 5th Edition; Wiley Publishing Inc.,: 2011
3. J. Gosling, et. Al.: The Java Language Specification Java SE 7th Edition: Oracle America Inc.,: 2011
4. https://www.geeksforgeeks.org/understanding-public-static-void-mainstring-args-in-java/

You might also like