Computer Science  ·  Level 6
Fundamentals Of Programming
Chapter 5: Use methods
📚 1 Topics
⚑ What you will be able to do

By the end of this chapter, you will be able to:

  • correctly apply procedures, functions, and methods in your programming projects
  • implement methods accurately while following proper programming standards
  • develop programs that use methods to organize and simplify your code effectively

Mastering these skills will help you write cleaner, more efficient programs that are easier to understand and maintain in your future work as a programmer.

Use of methods in programming is fundamental to creating organized, reusable, and maintainable code. In Kenya's growing software development sector, from fintech startups in Nairobi to e-governance projects in county offices, mastering methods enhances productivity and collaboration among computer science professionals. This chapter focuses on Java methods, a cornerstone of Java programming, providing a foundation for writing modular programs that are easier to debug and extend.

5.1 Java Methods

Java methods encapsulate blocks of code designed to perform specific tasks within a program. Understanding methods is crucial for Kenyan developers working on complex applications such as hospital management systems or SACCO financial software, where modularity and clarity are paramount.

5.1.1 Definition

The concept of a method in Java is central to procedural and object-oriented programming paradigms. It allows programmers to define a set of instructions that can be executed repeatedly without rewriting code.

What is a Java Method

A Java method is a named block of code that performs a particular operation and can be invoked when needed. It may accept input parameters, perform computations or actions, and return a result. Methods help reduce code duplication by encapsulating logic that can be reused across different parts of a program.

Role of Methods in Software Development

Methods enable programmers to break down complex problems into manageable pieces. This modular approach is essential in environments such as Kenya’s banking sector, where software systems like those used by Equity Bank require clear, maintainable, and testable code modules.

Difference Between Methods and Functions

In Java, methods are associated with classes and objects, unlike functions in some other languages which can exist independently. This association supports encapsulation and inheritance, key principles in building robust systems such as county government e-services.

Parameters and Return Types

Methods can accept zero or more parameters, which act as inputs, and can return a value of a specified type. For instance, a method calculating loan interest in a SACCO application would accept parameters like principal amount and interest rate and return the computed interest.

Importance of Method Naming Conventions

Clear and descriptive method names improve code readability and maintainability. Kenyan software developers working collaboratively benefit from adhering to conventions such as camelCase, which is widely accepted in Java development practices.

5.1.2 Structure

The structure of a Java method defines its components and syntax, which must be understood to write effective code. Kenyan programmers developing applications for educational institutions or healthcare providers rely on well-structured methods to ensure clarity and functionality.

Method Signature

The method signature includes the method name and parameter list. It uniquely identifies the method within a class and is critical for method overloading, allowing multiple methods with the same name but different parameters in systems like university management software.

Access Modifiers

Access modifiers such as public, private, and protected control the visibility of methods. For example, a method marked private in a hospital management system restricts access to sensitive operations like patient data processing, enhancing security.

Return Type Declaration

Every Java method declares the type of value it returns, or void if it returns nothing. This specification informs the compiler and developers about the kind of result to expect, such as an integer representing the number of items processed in inventory management software for retail shops.

Method Body

The method body contains the executable code enclosed in braces. It defines the specific actions the method performs, such as calculating totals or updating records in a county revenue collection system.

Example of a Java Method Structure

public int calculateTotal(int quantity, int price) {
    int total = quantity * price;
    return total;
}

This example demonstrates a method named calculateTotal that takes two integer parameters, multiplies them, and returns the result as an integer. Such methods are common in financial applications used by Kenyan cooperatives.

Practice Questions

  1. Define a Java method and explain its significance in software development. (6 marks)
  2. Describe the components of a Java method’s structure with examples. (8 marks)
  3. Explain how access modifiers affect method visibility in Java. Provide examples relevant to Kenyan public sector software. (6 marks)
  4. Write a Java method that calculates the area of a rectangle given its length and width. Include parameters and return type in your method signature. (5 marks)

Chapter Summary

This chapter focused on the concept of Java methods, starting with a clear definition that explained methods as reusable blocks of code designed to perform specific tasks within a program. The discussion highlighted how methods help organize code, making it more modular and easier to maintain. The structure of Java methods was then examined, detailing the essential components such as the method signature, return type, method name, parameters, and the body of the method enclosed in braces. Understanding this structure is crucial for writing effective methods that can be called upon to execute particular functions. The chapter emphasized the importance of method declarations and how they define the behavior and interaction within Java programs. Overall, the chapter provided foundational knowledge necessary for creating, using, and managing methods in Java programming.

Self-Assessment

🔒 PDFDownload this self-assessment, with answers

A. Written Assessment

  1. What is a method in Java? (2 marks)
  2. Identify the correct syntax for defining a method that returns an integer and takes two integer parameters. (2 marks)
  3. Which keyword is used to specify that a method does not return any value? (1 mark)
  4. Explain the role of the method header in Java. (3 marks)
  5. True or False: A Java method can have multiple return statements. Justify your answer. (3 marks)
  6. List the main components of a Java method structure. (5 marks)
  7. How does method overloading differ from method overriding in Java? (3 marks)
  8. Describe how methods improve code reusability in software development. Give an example related to a banking application. (4 marks)
  9. What is the significance of the method body in Java? (2 marks)
  10. In the context of the Kenya Revenue Authority (KRA) tax calculation system, how might methods be used to modularize the program? (4 marks)
Show Answers
  1. A method in Java is a block of code designed to perform a specific task and can be called to execute that task whenever needed.
  2. public int methodName(int param1, int param2)
  3. void
  4. The method header defines the method’s name, return type, and parameters; it specifies how the method can be called and what data it requires.
  5. True. A method can have multiple return statements to exit the method at different points depending on conditions, but only one is executed during a call.
  6. Method header, parameter list, return type, method body, access modifiers.
  7. Method overloading involves defining multiple methods with the same name but different parameters within the same class, while method overriding involves redefining a method inherited from a superclass to provide specific behavior.
  8. Methods allow programmers to write reusable code blocks; for example, in a banking app, a method to calculate interest can be reused for different account types without rewriting the logic.
  9. The method body contains the executable statements that define the task the method performs when called.
  10. In KRA’s tax system, methods can be used to separate tasks such as calculating income tax, VAT, and penalties, making the program clearer and easier to maintain.

B. Oral Assessment

  1. Discuss how the use of methods in Java enhances program modularity and maintenance, providing examples from software used in Kenyan universities.
  2. Explain the importance of parameter passing in Java methods and how it affects method functionality, using an example from a mobile banking application.
Answer Guide

Question 1 key points:

  • Methods break down programs into manageable, logical units that simplify debugging and updating.
  • For instance, university management systems use methods to handle student registration, fee payment, and course allocation separately.
  • This separation allows teams to work on different modules without conflict and facilitates easier updates.

Question 2 key points:

  • Parameter passing allows methods to receive input values, making them flexible and reusable for different data.
  • In mobile banking, passing account numbers and transaction amounts as parameters lets a single method handle various transactions like deposits or withdrawals.
  • Pass-by-value in Java ensures the original data remains unchanged unless explicitly modified.

C. Case Study

The Safaricom M-Pesa development team is creating a new feature to calculate transaction fees dynamically based on transaction amount and user type.

Tasks:
a) Define a Java method signature suitable for calculating transaction fees, including appropriate parameters and return type. (4 marks)
b) Outline the structure of this method, describing each component clearly. (5 marks)
c) Explain how using this method would improve the maintainability of the M-Pesa codebase. (3 marks)

Suggested Approach

a) A suitable method signature could be:
public double calculateTransactionFee(double amount, String userType)

  • public for accessibility, double as return type to allow decimal fees, parameters for amount and user category.

b) The method structure includes:

  • Method header specifying access modifier, return type, method name, and parameters.
  • Parameter list accepting transaction amount and user type.
  • Method body containing logic to compute fee based on rules (e.g., different rates for regular and premium users).
  • Return statement that outputs the calculated fee.

c) Using this method modularizes fee calculation, enabling updates to fee logic without affecting other parts of the system. It promotes code reuse across multiple transaction types and reduces errors by centralizing the fee logic.

Chapter Examination Questions

🔒 PDFDownload these examination questions, with worked answers

SECTION A (40 Marks) - Answer ALL Questions

  1. Explain the concept of a method in Java and its role in modular programming within software development projects at institutions such as Kenya Revenue Authority. (4 marks)
  2. Identify and describe the main components that make up the structure of a Java method. (4 marks)
  3. How does the use of methods improve code reusability and maintenance in a banking software system like KCB's mobile application? (4 marks)
  4. Differentiate between a method header and method body in Java, providing examples relevant to educational software development. (4 marks)
  5. What is the significance of the return type in a Java method and how does it affect method functionality? Illustrate with an example from a healthcare management system. (4 marks)
  6. Describe the purpose of method parameters and how they facilitate data handling in Java programs used by county government offices. (4 marks)
  7. Explain the difference between void and non-void methods with practical examples from a retail inventory management system. (4 marks)
  8. What are the naming conventions for methods in Java and why are they important in collaborative programming environments such as software teams at Safaricom? (4 marks)
  9. How do access modifiers influence the usability of methods in Java classes, especially in secure systems like banking or insurance? (4 marks)
  10. Illustrate how method overloading can be applied in a Java program designed for managing student records at a university. (4 marks)
Section A - Answers
  1. A method in Java is a block of code designed to perform a specific task; it promotes modular programming by allowing developers to divide complex problems into manageable units. For instance, at Kenya Revenue Authority, methods help encapsulate tax calculation logic separately, making the system easier to maintain and update.
  2. The main components of a Java method are the method header (which includes access modifier, return type, method name, and parameters) and the method body (which contains the code statements to execute).
  3. Methods enable code reusability by allowing the same logic to be called multiple times without duplication. In KCB’s mobile app, methods for validating user input can be reused across different modules, simplifying maintenance.
  4. The method header declares the method’s signature, such as public int calculateSum(int a, int b), while the method body contains the executable code within braces {}. For example, an educational software might have a method header defining a function to compute grades, with the body implementing the calculation.
  5. The return type specifies the data type of the value the method will return to the caller. For example, in a healthcare system, a method returning a patient’s age would have int as return type, enabling the program to use this value elsewhere.
  6. Method parameters act as inputs that allow passing data into methods. County government systems use parameters to send details like employee ID and leave days to methods that process leave applications.
  7. Void methods do not return any value and are used for operations like displaying information, while non-void methods return data after execution, such as a method that calculates total sales and returns the amount in a retail system.
  8. Java method names should start with a lowercase letter and use camelCase for readability. This convention is important in teams at Safaricom to maintain code consistency and facilitate collaboration.
  9. Access modifiers like public and private control method visibility; in secure banking systems, sensitive methods are often private to restrict access and protect data integrity.
  10. Method overloading allows multiple methods with the same name but different parameters. In university student management, a registerStudent() method could be overloaded to accept different sets of student information depending on context.

SECTION B (60 Marks) - Answer any TWO Questions

Question 11 (Compulsory - 20 marks)
At a county government IT department, a Java program is being developed to manage employee attendance and leave records.

a) Design a Java method named calculateLeaveBalance that takes two integer parameters: total leave days and leave taken, and returns the remaining leave balance. Include method header and body. (10 marks)
b) Explain how this method can improve the efficiency of the leave management system and suggest two ways to enhance it using method overloading or access modifiers. (10 marks)

Question 12 (20 marks)
Discuss the advantages of using methods in Java programming with reference to a healthcare management system such as Kenyatta National Hospital’s patient records software. Include at least five points with explanations.

Question 13 (20 marks)
Explain the structure of a Java method in detail, illustrating each component with code snippets relevant to a banking application scenario.

Question 14 (20 marks)
Write a Java method named calculateTotalSales that accepts an array of daily sales figures and returns the total sales. Explain each part of the method and how it would be utilized in a retail business software system.

Section B - Answers

Question 11
a)

public int calculateLeaveBalance(int totalLeave, int leaveTaken) {  
    int balance = totalLeave, leaveTaken;  
    return balance;  
}  

This method header includes the access modifier public, return type int, method name calculateLeaveBalance, and two integer parameters. The body calculates the difference and returns it.

b)
This method consolidates leave balance computation in one place, reducing code duplication and errors. It improves system efficiency by providing a reusable function for all leave-related computations. Enhancements include:

  • Method overloading to handle different leave types, e.g., calculateLeaveBalance(int totalLeave, int leaveTaken, int specialLeave)
  • Using private access modifier for helper methods that should not be accessible outside the class, enhancing security and encapsulation.

Question 12
Using methods in Java provides:

  • Modularity: Separates complex patient record operations into manageable units, easing debugging and updates.
  • Reusability: Common tasks such as calculating patient age or billing can be reused across modules, reducing redundancy.
  • Maintainability: Changes in one method do not affect others, facilitating updates in Kenyatta National Hospital’s system.
  • Readability: Method names describe their purpose, making the code easier for new developers to understand.
  • Testing: Individual methods can be tested independently, improving software reliability in critical healthcare applications.

Question 13
A Java method structure consists of:

  • Access Modifier: Defines method visibility (public, private, etc.).
  • Return Type: Specifies the data type returned (int, void, etc.).
  • Method Name: Identifier following naming conventions, e.g., processTransaction.
  • Parameter List: Input values in parentheses, e.g., (double amount, String accountNumber).
  • Method Body: Code block enclosed in braces {}, implementing the method’s logic.

Example:

public boolean processTransaction(double amount, String accountNumber) {  
    // Validate account and process payment  
    return true;  
}  

This method could be part of a banking app to process customer transactions.

Question 14

public double calculateTotalSales(double[] dailySales) {  
    double total = 0;  
    for (int i = 0; i < dailySales.length; i++) {  
        total += dailySales[i];  
    }  
    return total;  
}  

This method starts with a public access modifier and returns a double representing total sales. It takes an array of daily sales as input. Inside the body, a loop sums all sales values. In retail software, this method helps generate daily or monthly sales reports for decision-making.

References

  1. TVET CDACC - Fundamentals Of Programming Curriculum (Cycle 3, 2025)
  2. TVET CDACC - Fundamentals Of Programming Occupational Standards

Chapter Practical Activities

Practical 1: Define and Compile a Simple Java Method

Computer Science · Level 6
Fundamentals Of Programming
PRACTICAL ASSESSMENT
TIME: 4 HOURS
⬇ PDFCandidate Instructions (Candidate Tool)

Type: Individual

INSTRUCTIONS TO CANDIDATE:
1.  You are required to perform the following task:
i.  Write and compile a Java program defining a simple method named displayMessage that prints a welcome message, with the class named WelcomeClass.
2.  You have been provided with the following resources for the practical task:
Tools & EquipmentMaterials
Functional computer installed with Java IDE (NetBeans/Eclipse/IntelliJ)Plain paper
⬇ PDFResources Required (Cutting List)
S/NItemQuantity
1Functional computer installed with Java IDE (NetBeans/Eclipse/IntelliJ)1 Pc per Candidate
2Plain paper1 Pc per Candidate
⬇ PDFAssessor Guide
Items to be EvaluatedMarks AvailableMarks ObtainedComments
TASK 1: Define Java Method
Launched the Java IDE successfully
(Award 2 marks or zero)
2
Declared the class named WelcomeClass correctly
(Award 3 marks or zero)
3
Defined the method displayMessage with correct signature and no parameters
(Award 1 mark for method name, 2 marks for correct return type void, 2 marks for no parameters)
5
Implemented the method body to print the welcome message: "Welcome to Java Programming!"
(Award 5 marks or zero)
5
Declared the main method correctly
(Award 3 marks or zero)
3
Created an object of WelcomeClass inside main method
(Award 2 marks or zero)
2
Called the displayMessage method using the created object
(Award 3 marks or zero)
3
Compiled the Java program without errors
(Award 5 marks or zero)
5
Sub-Total28
PRODUCT CHECKLIST
Program runs and outputs the exact message: "Welcome to Java Programming!"
(Award 7 marks or zero)
7
Sub-Total7
GRAND TOTAL35
ASSESSMENT OUTCOME:   ☐ Competent    ☐ Not Yet Competent (competent if at least 50%)

Practical 2: Create a Java method with parameters and return value

Computer Science · Level 6
Fundamentals Of Programming
PRACTICAL ASSESSMENT
TIME: 4 HOURS
⬇ PDFCandidate Instructions (Candidate Tool)

Type: Individual

INSTRUCTIONS TO CANDIDATE:
1.  You are required to perform the following task:
i.  Create a Java method named calculateArea that accepts two double parameters (length and width) and returns their product as a double value.
2.  You have been provided with the following resources for the practical task:
Tools & EquipmentMaterials
Functional computer installed with Java IDE (NetBeans/Eclipse/IntelliJ)Plain paper
⬇ PDFResources Required (Cutting List)
S/NItemQuantity
1Functional computer installed with Java IDE (NetBeans/Eclipse/IntelliJ)1 Pc per Candidate
2Plain paper1 Pc per Candidate
⬇ PDFAssessor Guide
Items to be EvaluatedMarks AvailableMarks ObtainedComments
TASK 1: Method Implementation
Launched the Java IDE
(Award 2 marks or 0)
2
Declared the calculateArea method with two double parameters
(Award 1 mark for method declaration, 2 marks for correct parameters, 2 marks for correct return type)
5
Implemented method logic to return the product of length and width
(Award 5 marks for correct calculation and return statement)
5
Called the calculateArea method from main with example arguments
(Award 3 marks for correct method invocation with arguments)
3
Displayed the returned area value on the console
(Award 3 marks for correct output display)
3
Used appropriate variable types and names
(Award 2 marks or 0)
2
Sub-Total20
PRODUCT CHECKLIST
Method calculateArea correctly accepts two double parameters and returns their product as double
(Award 10 marks for correct method signature, logic, and return type)
10
Sub-Total10
GRAND TOTAL30
ASSESSMENT OUTCOME:   ☐ Competent    ☐ Not Yet Competent (competent if at least 50%)
🔒

Free: practical guides, quick cards, workplace scenarios and more.

Create a free account
🔒Java Program Demonstrating Method OverloadingPractical 3
🔒Write and explain the structure of a Java methodPractical 4
🔒Implement and Run a Void Java Method to Display a Welcome MessagePractical 5
🔒Develop a Java method using return statement to calculate the square of a numberPractical 6
🔒Java Program Calling User-Defined Methods from Main MethodPractical 7
🔒Organize and Access Methods in a Java ClassPractical 8
🔒Java Methods Parameter Passing DemonstrationPractical 9
🔒Debug Java method syntax errors in a source code filePractical 10
Flashcards 20 cards Study deck ▾
Question
1

↻ Tap card to reveal answer
🔒

18 more in this section.

Create a free account
Test Yourself 11 questions Start quiz ▾
0%
0 / 2
🔒

9 more in this section.

Create a free account
Am I competent?

At the start of this chapter we promised you would be able to:

  • correctly apply procedures, functions, and methods in your programming projects
  • implement methods accurately while following proper programming standards
  • develop programs that use methods to organize and simplify your code effectively

Tick each one you can genuinely do.

So, are you there yet?

You're competent when you can confidently do 50% or more of what this chapter promised.

Sign in to record how you're doing.