COS201 Programming
COS201 Programming
Faculty of Computing
COS 201:
COMPUTER PROGRAMMING I
Lecture Notes
Prepared By
Level: 200
Prepared By
Contents
2 Programming Paradigms 26
2.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
2.2 Functional Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
2.2.1 Characteristics of Functional Programming . . . . . . . . . . . . . 27
2.2.2 Advantages of Functional Programming . . . . . . . . . . . . . . . 28
2.2.3 Applications of Functional Programming . . . . . . . . . . . . . . 29
2.3 Declarative Programming . . . . . . . . . . . . . . . . . . . . . . . . . . 30
2.3.1 Characteristics . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
2.3.2 Types of Declarative Programming . . . . . . . . . . . . . . . . . 30
2.3.3 Advantages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
2.3.4 Disadvantages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
2.4 Logic Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
2.4.1 Characteristics . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
2.4.2 Components of Logic Programming . . . . . . . . . . . . . . . . . 32
1
COS 201: Computer Programming I Lecture Notes
2
COS 201: Computer Programming I Lecture Notes
5 Scanner Class 64
5.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
5.2 Importing the Scanner Class . . . . . . . . . . . . . . . . . . . . . . . . . 64
5.3 Creating a Scanner Object . . . . . . . . . . . . . . . . . . . . . . . . . . 64
5.4 Basic Input Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
5.4.1 Reading Integer Values . . . . . . . . . . . . . . . . . . . . . . . . 65
5.4.2 Reading Floating-Point Numbers . . . . . . . . . . . . . . . . . . 65
3
COS 201: Computer Programming I Lecture Notes
4
COS 201: Computer Programming I Lecture Notes
7 Type Conversion 81
7.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
7.2 What is Type Conversion? . . . . . . . . . . . . . . . . . . . . . . . . . . 81
7.3 Why Type Conversion is Necessary . . . . . . . . . . . . . . . . . . . . . 81
7.4 Types of Type Conversion . . . . . . . . . . . . . . . . . . . . . . . . . . 82
7.5 Implicit Type Conversion (Widening Conversion) . . . . . . . . . . . . . 82
7.5.1 Conversion Hierarchy . . . . . . . . . . . . . . . . . . . . . . . . . 82
7.5.2 Example 1: int to double . . . . . . . . . . . . . . . . . . . . . . . 82
7.5.3 Example 2: char to int . . . . . . . . . . . . . . . . . . . . . . . . 82
7.5.4 Advantages of Widening Conversion . . . . . . . . . . . . . . . . . 83
7.6 Explicit Type Conversion (Narrowing Conversion) . . . . . . . . . . . . . 83
7.6.1 Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
7.6.2 Example 1: double to int . . . . . . . . . . . . . . . . . . . . . . . 83
7.6.3 Example 2: long to int . . . . . . . . . . . . . . . . . . . . . . . . 84
7.6.4 Risks of Narrowing Conversion . . . . . . . . . . . . . . . . . . . 84
7.7 Casting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
7.7.1 Primitive Type Casting Example . . . . . . . . . . . . . . . . . . 84
7.8 Type Conversion in Arithmetic Expressions . . . . . . . . . . . . . . . . 85
7.9 Promotion in Arithmetic Operations . . . . . . . . . . . . . . . . . . . . 85
7.10 Conversion Between Characters and Integers . . . . . . . . . . . . . . . . 85
7.10.1 Character to Integer . . . . . . . . . . . . . . . . . . . . . . . . . 85
7.10.2 Integer to Character . . . . . . . . . . . . . . . . . . . . . . . . . 86
7.11 String Conversion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
7.11.1 String to Integer . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
7.11.2 String to Double . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
7.11.3 Number to String . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
7.12 Common Type Conversion Errors . . . . . . . . . . . . . . . . . . . . . . 87
7.12.1 Loss of Precision . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
7.12.2 Overflow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
7.12.3 Invalid String Conversion . . . . . . . . . . . . . . . . . . . . . . . 87
7.13 Best Practices for Type Conversion . . . . . . . . . . . . . . . . . . . . . 87
7.14 Applications of Type Conversion . . . . . . . . . . . . . . . . . . . . . . 87
7.15 Chapter Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
7.16 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
8 Control Structures 90
8.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
8.2 Sequential Control Structure . . . . . . . . . . . . . . . . . . . . . . . . . 90
8.3 Selection Control Structures . . . . . . . . . . . . . . . . . . . . . . . . . 91
5
COS 201: Computer Programming I Lecture Notes
6
COS 201: Computer Programming I Lecture Notes
7
COS 201: Computer Programming I Lecture Notes
8
COS 201: Computer Programming I Lecture Notes
9
COS 201: Computer Programming I Lecture Notes
10
COS 201: Computer Programming I Lecture Notes
10 Arrays 226
10.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226
10.2 Learning Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226
10.3 What is an Array? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227
10.3.1 Array Representation . . . . . . . . . . . . . . . . . . . . . . . . . 227
10.4 Advantages of Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227
10.5 Limitations of Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228
10.6 Declaring Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228
10.7 Creating Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228
10.8 Array Declaration and Creation in One Statement . . . . . . . . . . . . . 229
10.9 Default Values in Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . 229
10.10Initializing Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229
10.10.1 Method 1: Individual Assignment . . . . . . . . . . . . . . . . . . 229
10.10.2 Method 2: Array Initializer . . . . . . . . . . . . . . . . . . . . . 229
10.11Accessing Array Elements . . . . . . . . . . . . . . . . . . . . . . . . . . 230
10.12Modifying Array Elements . . . . . . . . . . . . . . . . . . . . . . . . . . 230
10.13Array Length . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230
10.14Traversing Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230
10.14.1 Using a for Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
10.15Enhanced for Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
10.15.1 Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
10.16Comparing and Enhanced for Loops . . . . . . . . . . . . . . . . . . . . . 231
10.17Calculating the Sum of Array Elements . . . . . . . . . . . . . . . . . . . 232
10.18Calculating the Average . . . . . . . . . . . . . . . . . . . . . . . . . . . 232
10.19Finding the Largest Element . . . . . . . . . . . . . . . . . . . . . . . . . 232
10.20Finding the Smallest Element . . . . . . . . . . . . . . . . . . . . . . . . 233
10.21Searching an Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233
10.21.1 Linear Search Example . . . . . . . . . . . . . . . . . . . . . . . . 234
10.22Sorting Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234
10.22.1 Import Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . 234
10.23Copying Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235
10.23.1 Using [Link]() . . . . . . . . . . . . . . . . . . . . . . . . 235
10.24Passing Arrays to Methods . . . . . . . . . . . . . . . . . . . . . . . . . . 235
10.25Returning Arrays from Methods . . . . . . . . . . . . . . . . . . . . . . . 235
10.26Multidimensional Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . 236
10.27Two-Dimensional Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . 236
10.27.1 Declaration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236
11
COS 201: Computer Programming I Lecture Notes
12
COS 201: Computer Programming I Lecture Notes
13
COS 201: Computer Programming I Lecture Notes
14
COS 201: Computer Programming I Lecture Notes
15 Recursion 295
15.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295
15.2 Concept of Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295
15.3 Structure of a Recursive Method . . . . . . . . . . . . . . . . . . . . . . . 295
15.4 How Recursion Works . . . . . . . . . . . . . . . . . . . . . . . . . . . . 296
15.4.1 Java Implementation . . . . . . . . . . . . . . . . . . . . . . . . . 296
15.4.2 Java Implementation . . . . . . . . . . . . . . . . . . . . . . . . . 297
15.5 Types of Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298
15.5.1 Direct Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . 298
15.5.2 Indirect Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . 298
15.5.3 Tail Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298
15.6 Base Case Importance . . . . . . . . . . . . . . . . . . . . . . . . . . . . 299
15.7 Recursion vs Iteration . . . . . . . . . . . . . . . . . . . . . . . . . . . . 299
15.8 Advantages of Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . 299
15.9 Disadvantages of Recursion . . . . . . . . . . . . . . . . . . . . . . . . . 300
15.10Common Applications of Recursion . . . . . . . . . . . . . . . . . . . . . 300
15.11Common Programming Errors . . . . . . . . . . . . . . . . . . . . . . . . 301
15.12Best Practices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 301
15.13Chapter Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 301
15.14Review Questions and Exercises . . . . . . . . . . . . . . . . . . . . . . . 303
15
COS 201: Computer Programming I Lecture Notes
References 321
16
Chapter 1
Introduction to Computer
Programming
17
COS 201: Computer Programming I Lecture Notes
18
COS 201: Computer Programming I Lecture Notes
records, generate statistics, and retrieve information much faster and more accu-
rately than manual methods. Efficient data processing supports informed decision-
making and enhances organizational performance.
4. Software Development
Programming is the primary tool used for developing software applications. These
applications may include desktop programs, mobile applications, web applications,
enterprise systems, embedded software, and intelligent systems. Through program-
ming, developers create software products that meet user requirements and provide
solutions to specific needs in both personal and professional environments.
5. Hardware Control
Programming enables computers to communicate with and control hardware de-
vices. Embedded systems, robotics, industrial automation systems, drones, sensors,
smart devices, and Internet of Things (IoT) applications all rely on programming
for their operation. By writing specialized programs, developers can instruct hard-
ware components to perform specific actions, monitor environmental conditions,
and respond intelligently to external events.
The objectives of programming extend beyond writing code; they focus on solving
problems, improving efficiency, automating operations, managing information, develop-
ing software solutions, and controlling hardware systems. These objectives make pro-
gramming an essential skill in today’s technology-driven world.
1.3.1 Correctness
Correctness refers to the ability of a program to produce accurate and expected results
for all valid inputs according to the problem specifications. A correct program performs
the intended task without producing erroneous outputs. Ensuring correctness requires
19
COS 201: Computer Programming I Lecture Notes
careful analysis of requirements, proper algorithm design, thorough testing, and debug-
ging. Regardless of how efficient or sophisticated a program may be, it is considered
useless if it fails to provide the correct solution to the problem it was designed to solve.
1.3.2 Efficiency
Efficiency refers to the optimal use of computer resources such as processor time, memory,
storage space, and network bandwidth. An efficient program executes tasks quickly while
consuming minimal resources. Efficient programming is particularly important in appli-
cations that process large volumes of data, perform complex computations, or operate in
resource-constrained environments. Efficiency can be achieved through the selection of
appropriate algorithms, data structures, and programming techniques.
1.3.3 Readability
Readability is the ease with which a program can be understood by programmers. A read-
able program uses meaningful variable names, proper indentation, consistent formatting,
and adequate comments to explain complex sections of code. Readability is important
because programs are often maintained and modified by different programmers over time.
Well-structured and readable code reduces the likelihood of errors and simplifies future
enhancements.
1.3.4 Maintainability
Maintainability refers to the ease with which a program can be modified, corrected,
updated, or enhanced after it has been developed. Software requirements frequently
change due to technological advancements, user needs, or organizational demands. A
maintainable program is organized into logical modules, follows coding standards, and
avoids unnecessary complexity, making future modifications easier and less costly.
1.3.5 Reliability
Reliability is the ability of a program to perform its intended functions consistently and
accurately under specified conditions for a given period of time. A reliable program
handles errors gracefully, recovers from unexpected situations, and continues to operate
correctly even when faced with unusual inputs or operating conditions. Reliability is
especially important in critical systems such as banking applications, healthcare systems,
aviation software, and industrial control systems.
20
COS 201: Computer Programming I Lecture Notes
1.3.6 Reusability
Reusability refers to the extent to which components of a program can be used in other
programs or projects with little or no modification. Reusable code reduces development
time, minimizes duplication of effort, improves consistency, and enhances software quality.
Techniques such as modular programming, object-oriented programming, and the use of
libraries and frameworks promote code reusability.
1.3.7 Portability
Portability is the ability of a program to run on different hardware platforms or operating
systems with minimal modifications. A portable program can be transferred from one
environment to another without significant changes to its code. Languages such as Java
promote portability through platform-independent execution environments.
1.3.8 Security
Security refers to the ability of a program to protect data and system resources from
unauthorized access, misuse, modification, or destruction. Secure programs implement
mechanisms such as authentication, authorization, encryption, and input validation to
safeguard sensitive information and maintain system integrity.
1.3.9 Scalability
Scalability is the capability of a program to accommodate increasing workloads, users,
or data volumes without significant degradation in performance. Scalable software can
grow and adapt to future demands while maintaining efficiency and reliability.
1.3.10 Robustness
Robustness refers to the ability of a program to continue functioning correctly even when
confronted with invalid inputs, unexpected conditions, or operational errors. Robust
programs include error detection and handling mechanisms that prevent system failures
and ensure stable operation.
A good program should be correct, efficient, readable, maintainable, reliable, reusable,
portable, secure, scalable, and robust. These characteristics contribute significantly to
the overall quality, usability, and longevity of software systems and are essential consid-
erations in professional software development.
21
COS 201: Computer Programming I Lecture Notes
1.5 Exercises
1. Define computer programming.
22
COS 201: Computer Programming I Lecture Notes
23
COS 201: Computer Programming I Lecture Notes
32. Why is portability important for organizations using multiple computing platforms?
3. Compare two software applications that you use regularly and evaluate them based
on correctness, efficiency, usability, and reliability.
4. Design a simple algorithm for calculating the average score of a student in five
courses.
5. Explain how poor program design can affect maintainability and scalability.
6. Research a software failure that occurred in the real world and identify which char-
acteristics of a good program were lacking.
24
COS 201: Computer Programming I Lecture Notes
10. Explain how the characteristics of a good program influence user satisfaction and
organizational success.
25
Chapter 2
Programming Paradigms
2.1 Introduction
Programming paradigms are fundamental styles, approaches, or models of programming
that provide programmers with different ways of thinking about and solving compu-
tational problems. A programming paradigm defines the structure, organization, and
methodology used in designing and implementing software systems. Rather than focus-
ing solely on the syntax of a programming language, programming paradigms emphasize
the principles and techniques used to develop programs.
Throughout the evolution of computer science, different programming paradigms have
emerged to address various challenges in software development. Each paradigm offers a
unique perspective on how programs should be written, how data should be represented,
and how computations should be performed. Some paradigms focus on procedures and
sequences of instructions, while others emphasize objects, functions, logical rules, or
declarative descriptions of desired outcomes.
The choice of a programming paradigm often depends on the nature of the problem
being solved, the programming language being used, and the preferences of the program-
mer. Modern programming languages frequently support multiple paradigms, allowing
developers to combine different approaches within the same application. For example,
Java primarily supports object-oriented programming but also incorporates features of
procedural and functional programming.
Programming paradigms provide several benefits in software development. They help
programmers organize code effectively, improve software maintainability, enhance read-
ability, encourage code reuse, and simplify problem-solving. Understanding different
programming paradigms enables programmers to select the most appropriate approach
for a particular task and develop more efficient and robust software solutions.
The major programming paradigms commonly studied in computer science include:
1. Functional Programming
26
COS 201: Computer Programming I Lecture Notes
2. Declarative Programming
3. Logic Programming
4. Scripting Programming
5. Procedural Programming
6. Object-Oriented Programming
27
COS 201: Computer Programming I Lecture Notes
In functional programming, functions are treated as first-class entities. This means that
functions can be assigned to variables, passed as arguments to other functions, returned as
values from functions, and stored in data structures. The ability to manipulate functions
like ordinary data provides flexibility and promotes code reuse.
Functional programming discourages modifying existing data after it has been created.
Instead of altering variables directly, new values are generated from existing ones. This
approach reduces unexpected side effects and makes program behavior more predictable.
Emphasizes Immutability
Immutability refers to the property that data cannot be modified after it has been cre-
ated. Whenever a change is required, a new data object is created rather than altering
the original one. Immutability improves program reliability, simplifies debugging, and
enhances support for concurrent and parallel processing.
Pure Functions
A pure function always produces the same output for the same input and does not modify
external data or produce side effects. Because pure functions are independent of external
states, they are easier to test and reason about.
Higher-Order Functions
A higher-order function is a function that can accept other functions as arguments or re-
turn functions as results. Higher-order functions enable abstraction and promote reusable
program components.
28
COS 201: Computer Programming I Lecture Notes
processing.
• Easier Debugging
Because functional programs minimize side effects and rely heavily on pure func-
tions, identifying and correcting errors becomes simpler. Each function can be ex-
amined independently without worrying about unintended interactions with other
parts of the program.
• Easier Testing
Pure functions are highly predictable because their outputs depend solely on their
inputs. This predictability simplifies unit testing and verification, allowing devel-
opers to test individual functions independently.
• Enhanced Maintainability
Programs written using functional principles are often shorter, clearer, and easier
to maintain because they emphasize modularity and abstraction.
• Financial Applications
29
COS 201: Computer Programming I Lecture Notes
• Distributed Systems
• Compiler Design
2.3.1 Characteristics
• Emphasizes what needs to be done, not how.
• Logic Programming: Programs are expressed in terms of logic rules and facts,
and computation is performed through inference (e.g., Prolog).
30
COS 201: Computer Programming I Lecture Notes
• Database Query Languages: Such as SQL, where users specify what data to
retrieve without describing the retrieval process.
2.3.3 Advantages
• Easier to understand and reason about programs.
2.3.4 Disadvantages
• Less control over low-level system operations.
2.4.1 Characteristics
• Programs are written as facts, rules, and queries.
31
COS 201: Computer Programming I Lecture Notes
• parent(john, mary).
• parent(mary, james).
2.4.4 Advantages
• High level of abstraction and simplicity.
2.4.5 Disadvantages
• Can be inefficient for large-scale computations.
32
COS 201: Computer Programming I Lecture Notes
2.5.1 Characteristics
• Code is usually interpreted rather than compiled.
2.5.4 Advantages
• Easy to learn and use.
33
COS 201: Computer Programming I Lecture Notes
2.5.5 Disadvantages
• Generally slower execution compared to compiled languages.
2.6.1 Characteristics
• Based on a top-down design approach.
34
COS 201: Computer Programming I Lecture Notes
• Pascal
• Fortran
• BASIC
2.6.4 Advantages
• Easy to understand and implement for small programs.
2.6.5 Disadvantages
• Difficult to manage large and complex programs.
35
COS 201: Computer Programming I Lecture Notes
2.7.1 Characteristics
• Emphasizes a clear and logical program structure.
• Iteration: Repetition of statements using loops such as for, while, and do-while.
2.7.3 Advantages
• Improves code readability and understanding.
2.7.4 Disadvantages
• Can become less efficient for very complex systems.
36
COS 201: Computer Programming I Lecture Notes
2.8.1 Characteristics
• Programs are organized around objects.
• C++
• Python
• C#
37
COS 201: Computer Programming I Lecture Notes
2.8.5 Advantages
• Improved code reusability through inheritance.
2.8.6 Disadvantages
• Can be complex for beginners.
38
COS 201: Computer Programming I Lecture Notes
Logic programming was introduced as a paradigm based on formal logic where pro-
grams consist of facts, rules, and queries. Computation is achieved through logical infer-
ence and reasoning. This paradigm is particularly useful in artificial intelligence, expert
systems, natural language processing, and knowledge-based applications.
The chapter also explored scripting programming, which involves writing interpreted
programs that automate tasks and extend the functionality of existing systems. Scripting
languages such as Python, JavaScript, PHP, and Bash are widely used for web develop-
ment, system administration, automation, and rapid application development.
Procedural programming was presented as a traditional paradigm that organizes pro-
grams into procedures or functions executed in a step-by-step manner. It follows a top-
down design approach and forms the foundation of many early programming languages
such as C, Pascal, Fortran, and BASIC. While procedural programming is simple and
efficient for small applications, it becomes increasingly difficult to manage as software
systems grow in complexity.
Structured programming was discussed as an extension of procedural programming
that emphasizes clear program organization through sequence, selection, and iteration
control structures. By minimizing the use of unstructured jumps such as goto statements,
structured programming improves readability, reliability, maintainability, and software
quality.
The chapter examined OOP, one of the most widely used programming paradigms
in modern software development. OOP organizes programs around objects that combine
data and behavior. The paradigm is built upon the principles of encapsulation, abstrac-
tion, inheritance, and polymorphism. These principles promote code reuse, modularity,
scalability, and maintainability while allowing software systems to model real-world en-
tities effectively.
Moreover, the chapter demonstrated that each programming paradigm offers unique
strengths and is suitable for different types of applications. Modern programming lan-
guages often support multiple paradigms, enabling developers to combine approaches and
leverage the advantages of each paradigm when developing software solutions.
2.10 Exercises
1. Define the term programming paradigm.
39
COS 201: Computer Programming I Lecture Notes
10. Why does functional programming discourage changing data after creation?
15. Identify five application areas where functional programming is commonly used.
23. Explain the concepts of facts, rules, and queries in logic programming.
40
COS 201: Computer Programming I Lecture Notes
40. Explain the limitations of procedural programming for large software systems.
43. Describe the three basic control structures used in structured programming.
41
COS 201: Computer Programming I Lecture Notes
63. Discuss the similarities and differences between structured programming and pro-
cedural programming.
65. Identify the most appropriate programming paradigm for developing an expert sys-
tem and justify your answer.
66. Explain why functional programming is well suited for concurrent and parallel com-
puting.
67. Discuss how programming paradigms influence software quality and maintainability.
3. Write a short report explaining why functional programming has become increas-
ingly important in multicore computing environments.
5. Design a simple family relationship knowledge base using facts and rules similar to
those used in logic programming.
42
COS 201: Computer Programming I Lecture Notes
6. Develop a shell script or Python script that automates a repetitive task on a com-
puter system.
10. Compare the suitability of scripting languages and compiled languages for web
application development.
13. Study an open-source software project and identify the programming paradigms
used in its implementation.
14. Discuss the impact of programming paradigms on software maintenance and scal-
ability.
15. Evaluate the strengths and weaknesses of each programming paradigm and recom-
mend situations where each should be used.
43
Chapter 3
44
COS 201: Computer Programming I Lecture Notes
• JVM (Java Virtual Machine): Executes Java bytecode and enables platform
independence.
3. Class Definition
4. Main Method
5. User-Defined Methods
A package is a mechanism used in Java to organize related classes and interfaces into a
logical grouping. The package statement specifies the package to which a particular Java
class belongs. It must appear as the first non-comment statement in a Java source file.
Packages help programmers manage large applications by organizing code into mean-
ingful namespaces, thereby avoiding naming conflicts between classes with the same name.
Syntax
package packageName;
Example
package [Link];
45
COS 201: Computer Programming I Lecture Notes
Benefits of Using Packages As software projects grow larger, the number of classes
increases significantly. Without packages, managing hundreds or thousands of classes
becomes difficult. Packages provide a hierarchical structure that makes locating and
maintaining classes easier.
For example, an educational management system may contain packages such as:
[Link]
[Link]
[Link]
[Link]
Java provides a vast collection of predefined classes stored in packages known as the
Java API (Application Programming Interface). To use classes from other packages,
programmers often need to import them into their programs.
An import statement allows a class to access classes and interfaces from external
packages without having to specify their fully qualified names repeatedly.
Syntax
import [Link];
or
import packageName.*;
Examples
import [Link];
import [Link];
import [Link].*;
46
COS 201: Computer Programming I Lecture Notes
Why Import Statements are Important Without import statements, every exter-
nal class must be referenced using its complete package path.
For example:
[Link] input =
new [Link]([Link]);
Package Purpose
[Link] Utility classes such as Scanner and ArrayList
[Link] Input and output operations
[Link] Networking applications
[Link] Database connectivity
[Link] Date and time operations
• Improve readability.
3. Class Definition
The class is the fundamental building block of every Java program. A class acts as a
blueprint or template from which objects are created.
In object-oriented programming, a class encapsulates data (attributes) and behavior
(methods) into a single unit.
Syntax
public class ClassName {
Example
47
COS 201: Computer Programming I Lecture Notes
String name;
int age;
• Encapsulation
• Code reusability
• Modularity
• Maintainability
• Object-oriented design
Every executable Java program must contain at least one class definition because Java
is a fully object-oriented language.
48
COS 201: Computer Programming I Lecture Notes
4. Main Method
The main method is the entry point of a Java application. When a Java program is
executed, the Java Virtual Machine (JVM) searches for the main method and begins
execution from that point.
Without a main method, a standalone Java application cannot run.
Syntax
public static void main(String[] args)
Example
public static void main(String[] args) {
[Link]("Welcome to Java");
}
Keyword Meaning
public Accessible from anywhere
static Can execute without creating an object
void Does not return any value
main JVM-recognized starting method
String[] args Stores command-line arguments
• Creating objects.
• Calling methods.
Example
public class Demo {
[Link]("Program Started");
49
COS 201: Computer Programming I Lecture Notes
displayMessage();
}
5. User-Defined Methods
// statements
Example
public void displayGreeting() {
[Link]("Welcome");
}
• Reduce duplication.
• Improve readability.
• Enhance maintainability.
50
COS 201: Computer Programming I Lecture Notes
Example
public int addNumbers(int a, int b) {
return a + b;
}
In summary, the package statement organizes classes into namespaces, import state-
ments provide access to external classes, class definitions serve as blueprints for objects,
the main method acts as the program’s entry point, and user-defined methods provide
reusable functionality. Together, these components form the basic skeletal structure of
every Java application.
51
COS 201: Computer Programming I Lecture Notes
// Constructor(s)
// Other methods
// Method body
package [Link];
import [Link];
// Instance variable
private static int a;
private static int b;
// Main method
public static void main(String[] args) {
Scanner input = new Scanner([Link]);
int a;
int b;
int sum;
[Link]("Enter an integer: ");
a = [Link]();
[Link]("Enter another integer: ");
b = [Link]();
52
COS 201: Computer Programming I Lecture Notes
sum = a + b;
[Link]("The sum is: " + sum);
}
}
Class Definition
• Platform independence.
53
COS 201: Computer Programming I Lecture Notes
Java remains one of the most important programming languages in modern software
development due to its portability, reliability, and scalability.
54
COS 201: Computer Programming I Lecture Notes
3.8 Exercises
A. Objective Questions
1. Java is originally developed by which company?
55
COS 201: Computer Programming I Lecture Notes
C. Practical Exercises
1. Write a simple Java program that prints your name and department.
2. Create a Java program that accepts two numbers from the user and displays their
sum.
4. Create a Java class called Student with attributes name and age, and display their
values using a method.
5. Write a program that imports the Scanner class and takes input from the user.
56
Chapter 4
4.1 Introduction
Data is the core element that every application processes in programming. Whether
it is a simple calculator, a banking system, or a complex artificial intelligence system,
all programs operate by storing, manipulating, and retrieving data. Java handles data
through variables that are classified using data types.
Variables act as named memory locations used to store values, while data types define
the kind of data a variable can hold. These form the foundation of all Java programming
operations.
Example:
int age;
double salary;
char grade;
57
COS 201: Computer Programming I Lecture Notes
• Java is case-sensitive.
58
COS 201: Computer Programming I Lecture Notes
1. Local Variables
2. Instance Variables
3. Static Variables
59
COS 201: Computer Programming I Lecture Notes
Example:
byte a = 10;
short b = 1000;
int c = 50000;
long d = 100000L;
Example:
float pi = 3.14f;
double salary = 45000.75;
60
COS 201: Computer Programming I Lecture Notes
Example:
char grade = ’A’;
Example:
boolean isActive = true;
• String
• Arrays
• Classes
• Interfaces
Example:
String name = "John";
int[] numbers = {1, 2, 3, 4};
61
COS 201: Computer Programming I Lecture Notes
62
COS 201: Computer Programming I Lecture Notes
4.11 Exercises
A. Objective Questions
1. What is a variable in Java?
C. Practical Exercises
1. Write a Java program that declares variables of all primitive data types.
3. Write a program that stores student details using different data types.
4. Create a class with instance and static variables and display their values.
63
Chapter 5
Scanner Class
5.1 Introduction
In Java programming, input is an essential part of interacting with users. Many programs
require data from the user during execution, such as names, numbers, and other values.
To handle user input efficiently, Java provides a built-in class known as the Scanner
class, which is part of the [Link] package.
The Scanner class simplifies the process of reading input from different sources, such
as the keyboard (standard input), files, and strings.
Here:
64
COS 201: Computer Programming I Lecture Notes
or
String word = [Link]();
Difference:
65
COS 201: Computer Programming I Lecture Notes
[Link]("\nUser Details:");
[Link]("Name: " + name);
[Link]("Age: " + age);
[Link]("GPA: " + gpa);
}
}
66
COS 201: Computer Programming I Lecture Notes
• Be careful when mixing nextLine() with other input methods due to newline
handling.
[Link]();
67
COS 201: Computer Programming I Lecture Notes
5.12 Exercises
A. Objective Questions
1. In which package is the Scanner class found?
68
COS 201: Computer Programming I Lecture Notes
C. Practical Exercises
1. Write a Java program that reads your name, age, and department using Scanner.
2. Create a program that reads two integers and prints their sum.
5. Write a program that reads student marks and calculates the average.
69
Chapter 6
6.1 Introduction
In Java programming, expressions and operators are fundamental components used to
manipulate data and perform computations. An expression is a combination of vari-
ables, constants, operators, and method calls that evaluates to a single value. Operators
are special symbols that instruct the compiler to perform specific mathematical, logical,
or relational operations.
Understanding expressions and operators is essential because they form the basis of
decision-making, calculations, and data processing in Java programs.
2. Relational Expressions
3. Logical Expressions
4. Assignment Expressions
70
COS 201: Computer Programming I Lecture Notes
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus (remainder)
Example:
int a = 10;
int b = 3;
Operator Description
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
71
COS 201: Computer Programming I Lecture Notes
Example:
int x = 10;
int y = 20;
Operator Description
&& Logical AND
|| Logical OR
! Logical NOT
Example:
int age = 20;
Operator Description
= Assign
+= Add and assign
-= Subtract and assign
*= Multiply and assign
/= Divide and assign
%= Modulus and assign
Example:
72
COS 201: Computer Programming I Lecture Notes
int a = 10;
a += 5;
a -= 2;
a *= 3;
a /= 2;
[Link](a);
Operator Description
+ Unary plus (positive sign)
- Unary minus (negation)
++ Increment operator
-- Decrement operator
! Logical NOT
73
COS 201: Computer Programming I Lecture Notes
int a = 5;
int b = -a;
[Link](b); // Output: -5
Pre-Increment (++x)
Explanation:
Post-Increment (x++)
In post-increment, the current value is used first before the variable is incremented.
Example:
int x = 5;
int y = x++;
[Link](x); // 6
[Link](y); // 5
Explanation:
• Then x is incremented by 1.
74
COS 201: Computer Programming I Lecture Notes
Pre-Decrement (–x)
Explanation:
• The value of x is first decreased.
Post-Decrement (x–)
Explanation:
• The original value of x is assigned to y.
• Then x is decreased by 1.
75
COS 201: Computer Programming I Lecture Notes
1. Parentheses ()
3. Unary operators (!, unary plus, unary minus, pre-increment (++x), pre-decrement(–
x))
6. Relational operators
8. Logical OR (||)
9. Assignment operators
Example:
int result = 10 + 5 * 2;
[Link](result); // 20, not 30
76
COS 201: Computer Programming I Lecture Notes
Left-to-Right Associativity
In left-to-right associativity, operators are evaluated from left to right. Most binary
operators in programming languages follow this rule.
Example:
int a = 10 - 5 - 2;
Step-by-step evaluation:
• First: 10 − 5 = 5
• Then: 5 − 2 = 3
Thus, a = 3.
Examples of operators with left-to-right associativity include:
• Arithmetic operators: +, −, ∗, /, %
• Postfix increment/decrement: x + +, x − −
Right-to-Left Associativity
In right-to-left associativity, operators are evaluated from right to left. This is commonly
seen in assignment and unary operators.
Example:
int a = 5;
int b = 10;
int c = 15;
a = b = c;
Step-by-step evaluation:
• First: b = c results in b = 15
• Then: a = 15
77
COS 201: Computer Programming I Lecture Notes
int a = 10;
double b = a + 2.5;
double a = 10.7;
int b = (int) a;
78
COS 201: Computer Programming I Lecture Notes
6.15 Exercises
A. Objective Questions
1. What is an expression in Java?
79
COS 201: Computer Programming I Lecture Notes
C. Practical Exercises
1. Write a program that performs all arithmetic operations on two numbers.
3. Write a program that evaluates logical expressions using AND, OR, and NOT.
5. Write a program that calculates the average of three numbers using expressions.
80
Chapter 7
Type Conversion
7.1 Introduction
In Java programming, data is stored using different data types such as int, double,
float, char, and boolean. During program execution, it is often necessary to convert
data from one type to another. This process is known as type conversion.
Type conversion allows programmers to perform operations involving different data
types, store values in compatible variables, and manipulate data effectively. Java provides
both automatic and manual mechanisms for converting data types.
Understanding type conversion is important because improper conversions may result
in data loss, reduced precision, or compilation errors.
In this example, the integer value stored in age is converted into a double value and
stored in ageDouble.
81
COS 201: Computer Programming I Lecture Notes
[Link](result);
Output
100.0
[Link](value);
82
COS 201: Computer Programming I Lecture Notes
Output
65
• No loss of information.
7.6.1 Syntax
[Link](result);
Output
25
83
COS 201: Computer Programming I Lecture Notes
[Link](pop);
7.7 Casting
Casting refers to the explicit conversion of one data type into another.
There are two forms of casting:
[Link](wholeSalary);
Output
45000
84
COS 201: Computer Programming I Lecture Notes
double result = a + b;
[Link](result);
Output
13.5
In this case, Java automatically converts a into a double before performing the addi-
tion.
int sum = a + b;
Even though both variables are bytes, the result is promoted to an integer.
[Link](value);
Output
85
COS 201: Computer Programming I Lecture Notes
65
[Link](letter);
Output
B
[Link](value);
[Link](value);
[Link](text);
86
COS 201: Computer Programming I Lecture Notes
double x = 9.99;
int y = (int) x;
Result:
9
7.12.2 Overflow
int x = 130;
byte y = (byte) x;
The resulting value may not be what is expected because the byte data type cannot
store values larger than 127.
87
COS 201: Computer Programming I Lecture Notes
• Financial applications.
• Database applications.
7.16 Exercises
A. Objective Questions
1. What is type conversion?
88
COS 201: Computer Programming I Lecture Notes
C. Practical Exercises
1. Write a Java program that demonstrates widening conversion from int to double.
2. Write a program that converts a double value into an integer using casting.
4. Write a program that converts a numeric string into an integer and performs arith-
metic operations on it.
5. Create a program that accepts a string from the user and converts it into a double
value.
7. Write a program that converts an integer into a character and displays the result.
89
Chapter 8
Control Structures
8.1 Introduction
A computer executes instructions sequentially, one statement after another. However,
real-world problems often require programs to make decisions, repeat tasks, and exe-
cute different actions depending on specific conditions. Control structures provide the
mechanisms that determine the order in which program statements are executed.
Control structures are fundamental building blocks of Java programming. They enable
programmers to control the flow of execution, allowing programs to become dynamic,
interactive, and intelligent.
Java provides three major categories of control structures:
These structures make it possible to create programs that can solve complex problems
efficiently.
90
COS 201: Computer Programming I Lecture Notes
[Link]("Step 3");
}
}
Output
Step 1
Step 2
Step 3
• if statement
• if-else statement
• if-else-if ladder
• Nested if statement
• switch statement
Syntax
if(condition) {
// statements
}
91
COS 201: Computer Programming I Lecture Notes
Start
Age ≥ 18?
Yes No
End
Flowchart of If Statement
Example
int age = 20;
Output
Syntax
92
COS 201: Computer Programming I Lecture Notes
Start
Score ≥ 45?
Yes No
Display Display
“Pass.” “Fail.”
End
if(condition) {
// true block
}
else {
// false block
}
Flowchart
Example
int score = 45;
Output
93
COS 201: Computer Programming I Lecture Notes
Fail
Syntax
if(condition1) {
// block 1
}
else if(condition2) {
// block 2
}
else if(condition3) {
// block 3
}
else {
// default block
}
Flowchart
94
COS 201: Computer Programming I Lecture Notes
Start
Yes Display
Score ≥ 70? End
Grade A
No
Yes Display
Score ≥ 60? End
Grade B
No
Yes Display
Score ≥ 50? End
Grade C
No
Display
End
Fail
95
COS 201: Computer Programming I Lecture Notes
[Link]("Grade A");
}
else if(score >= 60) {
[Link]("Grade B");
}
else if(score >= 50) {
[Link]("Grade C");
}
else {
[Link]("Fail");
}
}
}
Output
Grade A
Explanation
• The program first checks whether the score is greater than or equal to 70.
• If the first condition had been false, Java would continue checking the next condi-
tions until a true condition was found.
• If none of the conditions were true, the else block would execute.
Syntax
96
COS 201: Computer Programming I Lecture Notes
if(condition1) {
if(condition2) {
Flowchart
Example
int age = 25;
boolean hasLicense = true;
Output
Eligible to drive.
8.8.1 Syntax
switch(expression) {
case value1:
97
COS 201: Computer Programming I Lecture Notes
Start
No
Condition 1? End
Yes
No
Condition 2? End
Yes
Execute Statements
End
statements;
break;
case value2:
statements;
break;
default:
statements;
}
98
COS 201: Computer Programming I Lecture Notes
8.8.2 Flowchart
Start
Switch Expression
Yes Execute
Case 1? End
Case 1
No
Yes Execute
Case 2? End
Case 2
No
Yes Execute
Case 3? End
Case 3
No
Execute
End
Default
4. Stop at break.
99
COS 201: Computer Programming I Lecture Notes
Example
int day = 3;
switch(day) {
case 1:
[Link]("Monday");
break;
case 2:
[Link]("Tuesday");
break;
case 3:
[Link]("Wednesday");
break;
default:
[Link]("Invalid Day");
}
Output
Wednesday
switch(department) {
case "CSC":
[Link]("Computer Science");
break;
case "ICT":
[Link]("Information and Communication Technology");
break;
case "CYB":
[Link]("Cybersecurity");
break;
100
COS 201: Computer Programming I Lecture Notes
case "CHM":
[Link]("Chemistry");
break;
case "MTH":
[Link]("Mathematics");
break;
default:
[Link]("Unknown Department");
}
1. while loop
2. do-while loop
3. for loop
Syntax
while(condition) {
statements;
}
Example
101
COS 201: Computer Programming I Lecture Notes
int count = 1;
while(count <= 5) {
[Link](count);
count++;
}
Output
1
2
3
4
5
In this example, the variable count is initialized to 1. The while loop continues to
execute as long as count <= 5. During each iteration, the current value of count is
displayed and then incremented by 1. When count becomes 6, the condition evaluates
to false, and the loop terminates.
Syntax
do {
statements;
} while(condition);
Example
int count = 1;
do {
[Link](count);
count++;
102
COS 201: Computer Programming I Lecture Notes
Start
Initialize Variables
No
Condition? End
Yes
Execute Statements
Update Variables
Output
1
2
3
4
5
Explanation
In this example, the statements inside the do block are executed before the condition
count <= 5 is evaluated. After each iteration, the value of count is incremented by 1.
The loop continues as long as the condition remains true. When count becomes 6, the
condition evaluates to false, and the loop terminates.
103
COS 201: Computer Programming I Lecture Notes
Start
Execute Statements
Update Variables
Yes No
Condition? End
Syntax
104
COS 201: Computer Programming I Lecture Notes
Flowchart
Start
Initialization
No
Condition? End
Yes
Execute Statements
Update
Example
for(int count = 1; count <= 5; count++) {
[Link](count);
}
Output
1
2
3
4
5
Explanation
In this example, the variable count is initialized to 1. Before each iteration, the condition
count <= 5 is evaluated. If the condition is true, the statements inside the loop are
executed. After each iteration, the update expression count++ increments the value of
105
COS 201: Computer Programming I Lecture Notes
count by 1. When count becomes 6, the condition evaluates to false, and the loop
terminates.
Components
• Initialization
• Condition
• Update expression
Example
for(int i = 1; i <= 5; i++) {
[Link](i);
}
Output
1
2
3
4
5
Syntax
106
COS 201: Computer Programming I Lecture Notes
Example
for(int i = 1; i <= 3; i++) {
for(int j = 1; j <= 2; j++) {
[Link](i + "," + j);
}
}
Explanation
In this example:
• For each value of i, the inner loop variable j takes the values 1 and 2.
• The statement inside the inner loop is executed once for every combination of i
and j.
1. i = 1
• j = 1 → prints 1,1
• j = 2 → prints 1,2
2. i = 2
• j = 1 → prints 2,1
• j = 2 → prints 2,2
3. i = 3
• j = 1 → prints 3,1
• j = 2 → prints 3,2
Output
1,1
1,2
2,1
2,2
3,1
3,2
Note: If the outer loop executes m times and the inner loop executes n times for
each outer iteration, then the statements inside the inner loop execute a total of m × n
times.
107
COS 201: Computer Programming I Lecture Notes
Although this works correctly, the index variable i is only used to access array ele-
ments.
The enhanced for loop eliminates the need for the index variable.
Enhanced for Loop
int[] scores = {70, 80, 90};
The output remains the same, but the code is simpler and easier to understand.
Syntax
Syntax Explanation
The enhanced for loop consists of the following components:
108
COS 201: Computer Programming I Lecture Notes
• dataType – The data type of the elements stored in the array or collection.
• variable – A temporary variable that stores the current element during each iter-
ation.
General Form
for(Type item : collection) {
// use item
}
The loop:
for(int score : scores) {
[Link](score);
}
executes as follows:
109
COS 201: Computer Programming I Lecture Notes
Output
70
80
90
Output
Sum = 100
Output
Zauwali
Usman
Lawan
110
COS 201: Computer Programming I Lecture Notes
[Link]("Apple");
[Link]("Banana");
[Link]("Orange");
Output
Apple
Banana
Orange
111
COS 201: Computer Programming I Lecture Notes
• Adding or removing elements from a collection during iteration may cause errors.
The enhanced for loop (for-each loop) provides a concise and readable way to traverse
arrays and collections in Java. It automatically accesses each element one by one, elimi-
nating the need for loop counters and index management. It is particularly useful when
every element must be processed and the element position is not important. Because
of its simplicity and safety, it is one of the most commonly used looping constructs in
modern Java programming.
112
COS 201: Computer Programming I Lecture Notes
The two most commonly used loop control statements in Java are:
1. break
2. continue
• for loops
• while loops
• do-while loops
• switch statements
Syntax
break;
113
COS 201: Computer Programming I Lecture Notes
Flow of Execution
if(i == 5)
break;
[Link](i);
}
Output
1
2
3
4
Step-by-Step Execution
i Condition (i == 5) Action
1 False Print 1
2 False Print 2
3 False Print 3
4 False Print 4
5 True break executes, loop terminates
Once i becomes 5, the break statement executes and the loop ends immediately.
114
COS 201: Computer Programming I Lecture Notes
int count = 1;
while(true) {
if(count > 3)
break;
[Link](count);
count++;
}
Output
1
2
3
In this example, the loop condition is always true. The break statement provides a
way to exit the loop when a specific condition is met.
Syntax
continue;
115
COS 201: Computer Programming I Lecture Notes
Flow of Execution
if(i == 3)
continue;
[Link](i);
}
Output
1
2
4
5
Step-by-Step Execution
i Condition (i == 3) Action
1 False Print 1
2 False Print 2
3 True Skip printing
4 False Print 4
5 False Print 5
116
COS 201: Computer Programming I Lecture Notes
if(i % 2 != 0)
continue;
[Link](i);
}
Output
2
4
6
8
10
The loop skips all odd numbers and prints only even numbers.
117
COS 201: Computer Programming I Lecture Notes
Illustration
Consider the following sequence:
1 2 3 4 5
Using break at 3:
1 2
1 2 4 5
• Avoid excessive use of loop control statements, as they can make code difficult to
follow.
• Ensure that loop control logic remains clear and easy to understand.
Loop control statements modify the normal execution of loops. The break statement
immediately terminates a loop and transfers control to the statement following the loop.
The continue statement skips the current iteration and proceeds directly to the next
iteration. These statements are powerful tools for controlling program flow and writing
efficient, flexible loops.
118
COS 201: Computer Programming I Lecture Notes
Output
Running...
Running...
Running...
Running...
...
The statement while(true) always evaluates to true, so the loop never terminates.
while(i <= 5) {
[Link](i);
}
Since i remains equal to 1 throughout the execution, the condition i <= 5 always
remains true.
119
COS 201: Computer Programming I Lecture Notes
while(i <= 5) {
[Link](i);
i++;
}
Output
1
2
3
4
5
while(true) {
[Link](count);
if(count == 5)
break;
count++;
}
Output
1
2
3
4
5
In this example, the loop is intentionally infinite, but the break statement provides
a mechanism to terminate it when the value of count reaches 5.
120
COS 201: Computer Programming I Lecture Notes
5. Event-Driven Applications – Wait for user actions such as mouse clicks and
keyboard input.
Disadvantages
121
COS 201: Computer Programming I Lecture Notes
Practical Examples
The following examples demonstrate how loops can be applied to solve common program-
ming problems.
Output
Sum = 55
Explanation
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55
This example demonstrates how loops can automate repetitive calculations efficiently
and reduce the amount of code required to perform mathematical operations.
122
COS 201: Computer Programming I Lecture Notes
Output
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
5 x 11 = 55
5 x 12 = 60
Explanation
3. During each iteration, the expression 5*i calculates the product of 5 and the current
value of i.
123
COS 201: Computer Programming I Lecture Notes
Trace Table
Value of i Output
1 5x1=5
2 5 x 2 = 10
3 5 x 3 = 15
4 5 x 4 = 20
5 5 x 5 = 25
.. ..
. .
12 5 x 12 = 60
Practical Applications
• Mathematical computations.
Output
2
4
6
8
10
12
14
16
18
20
124
COS 201: Computer Programming I Lecture Notes
Explanation
4. Because the value increases by 2 each time, only even numbers are generated.
Trace Table
Iteration Value of i
1 2
2 4
3 6
4 8
5 10
6 12
7 14
8 16
9 18
10 20
The modulus operator (%) returns the remainder after division. If the remainder is 0,
the number is even.
Practical Applications
125
COS 201: Computer Programming I Lecture Notes
These examples illustrate how loops can automate repetitive tasks, generate mathe-
matical sequences, and perform calculations efficiently with minimal code.
In this example, only the first println() statement belongs to the inner if statement.
The second statement executes regardless of the condition.
Correct Example
if(age >= 18) {
if(hasLicense) {
[Link]("Drive");
[Link]("Welcome");
}
}
126
COS 201: Computer Programming I Lecture Notes
The assignment operator assigns a value, whereas the comparison operator checks
whether two values are equal.
Correct Example
if(number == 10) {
[Link]("Equal");
}
The variable i is never updated, causing the condition to remain true indefinitely.
Correct Example
int i = 1;
127
COS 201: Computer Programming I Lecture Notes
case 2:
[Link]("Tuesday");
break;
}
128
COS 201: Computer Programming I Lecture Notes
The variable decreases instead of increasing, causing the loop condition to remain
true.
Correct Example
for(int i = 1; i <= 10; i++) {
[Link](i);
}
129
COS 201: Computer Programming I Lecture Notes
Better Example
int studentAge;
double accountBalance;
130
COS 201: Computer Programming I Lecture Notes
case 2:
[Link]("Tuesday");
break;
131
COS 201: Computer Programming I Lecture Notes
default:
[Link]("Invalid");
}
132
COS 201: Computer Programming I Lecture Notes
Comments should clarify complex logic rather than describe obvious statements.
By consistently applying these best practices, programmers can develop software that
is reliable, efficient, maintainable, and easier for others to understand and modify.
133
COS 201: Computer Programming I Lecture Notes
applications require the ability to alter the flow of execution based on specific conditions
or user input.
The chapter then explored selection structures, which enable a program to choose
between alternative courses of action. Various decision-making statements available in
Java were discussed, including the if, if-else, if-else-if ladder, nested if statements,
and the switch statement. These structures allow programs to evaluate conditions and
execute different blocks of code depending on whether the conditions are true or false.
Such decision-making capabilities are essential for creating intelligent and interactive
applications.
The concept of iteration structures, commonly known as loops, was also presented.
Loops enable a program to execute a block of code repeatedly without requiring the pro-
grammer to write the same statements multiple times. The chapter covered the while,
do-while, for, and enhanced for loops, explaining their syntax, operation, and ap-
propriate use cases. These looping structures are particularly useful when processing
collections of data, performing repetitive calculations, or automating recurring tasks.
In addition, the chapter discussed nested control structures, where one control
structure is placed inside another. Examples of nested if statements and nested loops
demonstrated how more complex program logic can be constructed to solve real-world
problems. The use of nested structures allows programmers to model sophisticated
decision-making processes and handle multidimensional data effectively.
Special attention was given to loop control statements, namely break and continue.
The break statement was shown to terminate a loop immediately, while the continue
statement skips the remainder of the current iteration and proceeds to the next itera-
tion. These statements provide additional flexibility in controlling loop behavior and can
improve both program efficiency and readability when used appropriately.
The chapter further examined infinite loops, explaining how they occur when a
loop’s termination condition never becomes false. Both intentional and unintentional
infinite loops were discussed, along with practical applications in areas such as servers,
operating systems, and event-driven systems. Techniques for preventing accidental infi-
nite loops and safely terminating loops were also presented.
Several practical programming examples demonstrated how control structures can be
applied to solve common computational problems. Examples included calculating sums,
generating multiplication tables, displaying even numbers, and controlling program flow
through decision-making statements. These examples reinforced the theoretical concepts
and illustrated how control structures are used in everyday programming tasks.
The chapter also highlighted common programming errors related to control struc-
tures, such as incorrect loop conditions, missing break statements, improper variable
updates, and off-by-one errors. A set of programming best practices was also provided
to encourage the development of clean, readable, maintainable, and efficient code. By
134
COS 201: Computer Programming I Lecture Notes
mastering the control structures discussed in this chapter, students gain the ability to
design programs that can make decisions, perform repetitive tasks efficiently, and solve a
wide variety of real-world computing problems.
8.23 Exercises
1. Define the term control structure. Explain why control structures are important
in programming.
(a) if
(b) if-else
(c) switch
(d) while
(e) for
4. Write a Java program that determines whether a number entered by the user is
positive, negative, or zero.
5. Write a Java program that accepts a student’s score and displays the corresponding
grade using an if-else-if ladder.
7. Write a Java program that displays the name of a day based on a number entered
by the user (1–7) using a switch statement.
135
COS 201: Computer Programming I Lecture Notes
int x = 5;
if(x > 3) {
[Link]("A");
} else {
[Link]("B");
}
11. Write a Java program that displays all numbers from 1 to 100 using a for loop.
12. Write a Java program that displays all odd numbers between 1 and 50.
13. Write a Java program that calculates the sum of all integers from 1 to 100.
14. Write a Java program that calculates the factorial of a given positive integer.
15. Write a Java program that generates the multiplication table of any number entered
by the user.
*
**
***
****
*****
17. Write a Java program that displays the following pattern using nested loops:
*****
****
***
**
*
18. Explain the purpose of the break statement. Give an example illustrating its use.
136
COS 201: Computer Programming I Lecture Notes
19. Explain the purpose of the continue statement. Give an example illustrating its
use.
20. What is an infinite loop? Describe two common causes of accidental infinite loops.
[Link](i);
}
23. Write a Java program that repeatedly asks the user to enter a password until the
correct password is entered.
24. Write a Java program that finds the largest number among five numbers entered
by the user.
25. Using nested loops, write a Java program that displays the following multiplication
table:
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
26. Write a Java program that counts the number of vowels in a word entered by the
user.
27. Write a Java program that reverses a number entered by the user.
137
COS 201: Computer Programming I Lecture Notes
29. Discuss three common programming errors associated with loops and explain how
they can be avoided.
30. Describe five best practices that programmers should follow when writing control
structures in Java.
*
***
*****
*******
*********
2. Using nested loops, write a Java program to display the following inverted pyramid:
*********
*******
*****
***
*
3. Using nested loops, write a Java program to display the following square block:
*****
*****
*****
*****
*****
4. Using nested loops, write a Java program to display the following hollow square:
*****
* *
* *
* *
*****
138
COS 201: Computer Programming I Lecture Notes
5. Using nested loops, write a Java program to display the following right triangle:
*
**
***
****
*****
6. Using nested loops, write a Java program to display the following inverted right
triangle:
*****
****
***
**
*
7. Using nested loops, write a Java program to display the following left-aligned tri-
angle:
*
**
***
****
*****
8. Using nested loops, write a Java program to display the following inverted left-
aligned triangle:
*****
****
***
**
*
9. Using nested loops, write a Java program to display the following diamond pattern:
*
***
*****
139
COS 201: Computer Programming I Lecture Notes
*******
*********
*******
*****
***
*
10. Using nested loops, write a Java program to display the following hollow pyramid:
*
* *
* *
* *
*********
11. Using nested loops, write a Java program to display the following number triangle:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
12. Using nested loops, write a Java program to display Floyd’s Triangle:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
13. Using nested loops, write a Java program to display the following multiplication
pattern:
1
2 4
3 6 9
4 8 12 16
5 10 15 20 25
140
COS 201: Computer Programming I Lecture Notes
14. Using nested loops, print four triangles positioned at different corners of the output.
Top-Left Triangle
*****
****
***
**
*
Top-Right Triangle
*****
****
***
**
*
Bottom-Left Triangle
*
**
***
****
*****
Bottom-Right Triangle
*
**
***
****
*****
15. Using nested loops, combine the four triangles above into a single pattern.
***** *****
**** ****
*** ***
** **
141
COS 201: Computer Programming I Lecture Notes
* *
* *
** **
*** ***
**** ****
***** *****
16. Using nested loops, write a Java program to display the following butterfly pattern:
* *
** **
*** ***
**** ****
**********
**** ****
*** ***
** **
* *
17. Using nested loops, write a Java program to display the following X-pattern:
* *
* *
* *
* *
*
* *
* *
* *
* *
18. Using nested loops, write a Java program to display the following checkerboard
pattern:
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
142
COS 201: Computer Programming I Lecture Notes
19. Using nested loops, write a Java program to display Pascal’s Triangle up to 5 rows.
20. Design your own star pattern consisting of at least 10 rows and implement it using
nested loops.
Programming Challenge
Design and implement a menu-driven Java application that repeatedly displays the fol-
lowing menu until the user chooses to exit:
The program should use appropriate selection and iteration structures to perform each
task. Ensure that invalid menu choices are handled properly.
143
Chapter 9
9.1 Introduction
Data is not limited to numbers alone, many applications process textual information such
as names, addresses, passwords, messages, documents, and web content. Java provides
powerful support for handling text through characters and strings.
A character represents a single symbol such as a letter, digit, punctuation mark, or
special symbol, while a string represents a sequence of characters.
Examples:
• Character: ’A’
• Character: ’7’
• Character: ’@’
String processing is one of the most important aspects of software development be-
cause most applications interact with users through text.
This chapter discusses characters, strings, string operations, string methods, character
processing, and practical applications of text manipulation in Java.
144
COS 201: Computer Programming I Lecture Notes
[Link](letter);
}
}
Output
Example
char letter = 65;
[Link](letter);
145
COS 201: Computer Programming I Lecture Notes
Output
Example
[Link]("Java\nProgramming");
Output
Java
Programming
146
COS 201: Computer Programming I Lecture Notes
It is important to understand that strings and numbers are not the same thing. Con-
sider the following examples:
12345
"12345"
The first value is a numeric integer that can be used in arithmetic calculations, while
the second value is a string consisting of five characters. Although they appear similar,
Java treats them differently.
In this example:
Once created, the variable name stores a reference to a String object containing the
text "Ahmed".
Another example is shown below:
String university = "Northwest University Kano";
String course = "Computer Science";
String message = "Welcome to Java Programming";
These variables can later be used throughout a program whenever the stored text is
needed.
147
COS 201: Computer Programming I Lecture Notes
String literals are stored by Java in a special memory area known as the String Pool,
which helps improve memory efficiency by reusing identical strings whenever possible.
J A V A
0 1 2 3
• Character J is at index 0.
• Character A is at index 1.
• Character V is at index 2.
• Character A is at index 3.
This is the most commonly used approach because it is simple and memory-efficient.
148
COS 201: Computer Programming I Lecture Notes
• Generating reports.
Without strings, programs would not be able to interact effectively with users.
[Link](greeting);
Output
Hello World
149
COS 201: Computer Programming I Lecture Notes
[Link](firstName);
[Link](lastName);
Output
Amina
Yusuf
• A name
• An address
• A phone number
• An email address
• A password
7. Strings are widely used for storing and manipulating textual data.
150
COS 201: Computer Programming I Lecture Notes
Both methods create strings that can store and manipulate text, but they differ in
how Java allocates memory and manages the resulting String objects.
In this statement:
When Java encounters a string literal, it stores the string in a special memory area
called the String Pool. The String Pool is designed to improve memory efficiency by
reusing identical string values whenever possible.
For example:
String name1 = "Java";
String name2 = "Java";
151
COS 201: Computer Programming I Lecture Notes
In this case, Java stores only one copy of the string "Java" in memory. Both name1
and name2 refer to the same String object in the String Pool.
This optimization reduces memory consumption and improves application perfor-
mance.
Examples:
String university = "Northwest University Kano";
String course = "Computer Science";
String country = "Nigeria";
In this approach:
Unlike string literals, this method creates a new object every time the statement is
executed, even if an identical string already exists.
Example:
String str1 = new String("Java");
String str2 = new String("Java");
Although both strings contain the same text, Java creates two separate String objects.
This can increase memory usage compared to using string literals.
152
COS 201: Computer Programming I Lecture Notes
Although less commonly used, creating strings with new has certain advantages:
Complete example:
String name;
name = "Aminu";
[Link](name);
153
COS 201: Computer Programming I Lecture Notes
Output
Aminu
Alternatively:
String firstName = "Fatima",
lastName = "Ali",
department = "Computer Science";
[Link](name1);
[Link](name2);
}
}
Output
Aminu
Aminu
154
COS 201: Computer Programming I Lecture Notes
Although both variables produce the same output, the underlying memory manage-
ment differs.
Strings declaration and initialization provides the foundation for learning more ad-
vanced string operations such as concatenation, comparison, searching, extraction, mod-
ification, and validation, which are essential skills in Java programming.
155
COS 201: Computer Programming I Lecture Notes
Displaying strings is essential in almost every Java application because programs often
need to communicate information to users, such as messages, instructions, results, error
notifications, and reports.
Consider the following example:
String university =
"Northwest University Kano";
[Link](university);
Output
In this example:
When the program executes, Java retrieves the value stored in the variable and prints
it on the screen.
• println() – A method that displays data and automatically moves to a new line
afterward.
Together, these components allow Java programs to display information on the console
window.
156
COS 201: Computer Programming I Lecture Notes
Output
Output
Output
Hello World
Unlike println(), the print() method does not automatically move to a new line
after displaying text.
Comparison:
157
COS 201: Computer Programming I Lecture Notes
[Link]("Hello");
[Link]("World");
Output
Hello
World
[Link](firstName);
[Link](lastName);
Output
Amina
Yusuf
The values stored inside the variables are displayed rather than the variable names
themselves.
Output
The plus sign (+) joins the text and the variable value into a single output statement.
Another example:
158
COS 201: Computer Programming I Lecture Notes
String university =
"Northwest University Kano";
[Link](
"University: " + university);
Output
[Link](
firstName + " " + lastName);
Output
Muktar Danlami
Notice the space character (" ") placed between the two names to improve readability.
Output
This approach is commonly used when generating reports and displaying user infor-
mation.
159
COS 201: Computer Programming I Lecture Notes
Practical Example
The following program demonstrates various ways of displaying strings.
public class DisplayStringsDemo {
String university =
"Northwest University Kano";
String course =
"Java Programming";
[Link](university);
[Link](course);
[Link](
"Welcome to " + course);
[Link](
"Institution: " + university);
}
}
Output
160
COS 201: Computer Programming I Lecture Notes
[Link]("Hello");
If name has not been declared, the program will not compile.
[Link](universty);
161
COS 201: Computer Programming I Lecture Notes
8. Displaying strings is one of the most frequently used operations in Java program-
ming.
A new string object is created rather than modifying the original string.
String fullName =
firstName + " " + lastName;
[Link](fullName);
Output
Aminu Mahmoud
162
COS 201: Computer Programming I Lecture Notes
[Link](
"Name: " + name +
", Age: " + age
);
Output
For example:
String text = "Java";
[Link]([Link]());
9.11.1 length()
The length() method returns the total number of characters contained in a string,
including letters, digits, spaces, and special characters.
Syntax
[Link]();
163
COS 201: Computer Programming I Lecture Notes
Example
[Link]([Link]());
Output
[Link]([Link]());
Output
11
Notice that the space between Hello and World is counted as a character.
Applications
• Validating passwords.
9.11.2 charAt()
The charAt() method returns the character located at a specified index position within
a string.
Remember that string indexing begins at zero.
Syntax
[Link](index);
164
COS 201: Computer Programming I Lecture Notes
Example
[Link]([Link](0));
Output
Character positions:
J a v a
0 1 2 3
Another example:
String text = "Computer";
[Link]([Link](3));
Output
Important Note
[Link]([Link](10));
Applications
165
COS 201: Computer Programming I Lecture Notes
9.11.3 toUpperCase()
The toUpperCase() method converts all alphabetic characters in a string to uppercase.
Syntax
[Link]();
Example
[Link](
[Link]()
);
Output
JAVA
Another example:
String text = "Computer Science";
[Link](
[Link]()
);
Output
COMPUTER SCIENCE
Applications
• Formatting reports.
9.11.4 toLowerCase()
The toLowerCase() method converts all alphabetic characters in a string to lowercase.
166
COS 201: Computer Programming I Lecture Notes
Syntax
[Link]();
Example
[Link](
[Link]()
);
Output
java
Another example:
String text = "COMPUTER SCIENCE";
[Link](
[Link]()
);
Output
computer science
Applications
• Data normalization.
• Search functionality.
9.11.5 equals()
The equals() method compares the actual contents of two strings.
It returns:
• false otherwise.
167
COS 201: Computer Programming I Lecture Notes
Syntax
[Link](string2);
Example
String s1 = "Java";
String s2 = "Java";
[Link](
[Link](s2)
);
Output
true
[Link](
[Link](s2)
);
Output
false
Important Note
Correct:
[Link](s2)
9.11.6 equalsIgnoreCase()
The equalsIgnoreCase() method compares two strings while ignoring differences in
uppercase and lowercase letters.
168
COS 201: Computer Programming I Lecture Notes
Syntax
[Link](string2);
Example
String s1 = "JAVA";
String s2 = "java";
[Link](
[Link](s2)
);
Output
true
Another example:
String username = "Admin";
[Link](
[Link]("admin")
);
Output
true
Applications
• Login systems.
• Search operations.
9.11.7 compareTo()
The compareTo() method compares two strings alphabetically (lexicographically).
Syntax
[Link](string2);
169
COS 201: Computer Programming I Lecture Notes
Example
String s1 = "Apple";
String s2 = "Banana";
[Link](
[Link](s2)
);
Output
-1
Examples:
Applications
• Sorting names.
• Alphabetical ordering.
• Dictionary applications.
9.11.8 contains()
The contains() method checks whether a string contains a specified sequence of char-
acters.
It returns either true or false.
Syntax
[Link](text);
170
COS 201: Computer Programming I Lecture Notes
Example
String text =
"Computer Science";
[Link](
[Link]("Science")
);
Output
true
Another example:
String course =
"Java Programming";
[Link](
[Link]("Python")
);
Output
false
Applications
• Search functions.
• Input validation.
• Keyword detection.
• Text filtering.
171
COS 201: Computer Programming I Lecture Notes
• false otherwise.
These methods are commonly used in file processing, data validation, web applica-
tions, search systems, and user input verification.
Syntax
[Link](prefix);
where prefix represents the text to be checked at the beginning of the string.
172
COS 201: Computer Programming I Lecture Notes
startsWith() Example
[Link](
[Link]("Pro")
);
Output
true
The output is true because the string "Programming" begins with the characters
"Pro".
Example 2
[Link](
[Link]("Gram")
);
Output
false
The output is false because "Programming" does not begin with "Gram".
Example 3
String university =
"Northwest University Kano";
[Link](
[Link]("North")
);
Output
true
173
COS 201: Computer Programming I Lecture Notes
Case Sensitivity
[Link](
[Link]("pro")
);
Output
false
Although the letters are the same, the method distinguishes between uppercase and
lowercase characters.
Applications of startsWith()
• Validating usernames.
• Input validation.
Example:
String website =
"[Link]
if([Link]("https"))
{
[Link](
"Secure website"
);
}
174
COS 201: Computer Programming I Lecture Notes
Syntax
[Link](suffix);
where suffix represents the text to be checked at the end of the string.
endsWith() Example
[Link](
[Link]("ing")
);
Output
true
The output is true because the string "Programming" ends with "ing".
Example 2
[Link](
[Link]("Pro")
);
Output
false
The output is false because "Programming" does not end with "Pro".
Example 3
175
COS 201: Computer Programming I Lecture Notes
[Link](
[Link](".pdf")
);
Output
true
Case Sensitivity
[Link](
[Link](".pdf")
);
Output
false
The result is false because PDF and pdf are considered different.
Applications of endsWith()
• Data filtering.
Example:
176
COS 201: Computer Programming I Lecture Notes
if([Link](".docx"))
{
[Link](
"Word document detected"
);
}
if([Link]("@") &&
[Link](".com"))
{
[Link](
"Valid email format"
);
}
Output
Practical Example
The following program demonstrates both methods:
public class StartsEndsDemo {
String course =
"Java Programming";
[Link](
177
COS 201: Computer Programming I Lecture Notes
[Link]("Java"));
[Link](
[Link]("ming"));
}
}
Output
true
true
This returns false because "Pro" appears at the beginning rather than the end.
This causes a compilation error because Java interprets Pro as a variable name.
178
COS 201: Computer Programming I Lecture Notes
5. These methods are widely used for validation and text processing.
6. They are particularly useful when working with file names, URLs, email addresses,
and user input.
The startsWith() and endsWith() methods are simple yet powerful tools for an-
alyzing strings. They enable programmers to quickly verify text patterns and perform
common validation tasks that occur in real-world software applications.
9.13 indexOf()
The indexOf() method is used to locate the position of a character or substring within a
string. It returns the index of the first occurrence of the specified character or substring.
Since Java uses zero-based indexing, the first character of a string is located at index
0, the second character at index 1, and so on.
The indexOf() method is extremely useful when searching for specific characters,
validating input, parsing text, and processing user-entered data.
9.13.1 Syntax
[Link](character);
or
[Link](substring);
[Link](
[Link](’p’)
);
179
COS 201: Computer Programming I Lecture Notes
Output
C o m p u t e r
0 1 2 3 4 5 6 7
[Link](
[Link]("Science")
);
Output
[Link](
[Link](’x’)
);
Output
-1
The result -1 indicates that the character does not appear in the string.
180
COS 201: Computer Programming I Lecture Notes
[Link](
[Link](’ ’)
);
Output
• Parsing strings.
Example:
String email =
"student@[Link]";
[Link](
[Link](’@’)
);
Output
181
COS 201: Computer Programming I Lecture Notes
Example:
String text = "Java";
[Link](
[Link](’j’)
);
Output
-1
Because ’J’ and ’j’ are different characters, the method does not find a match.
9.14 substring()
The substring() method extracts a portion of a string and returns it as a new string.
Rather than modifying the original string, Java creates and returns a new String
object containing the selected characters.
This method is frequently used when extracting names, codes, file extensions, dates,
and other portions of text.
Sometimes we may only need the word "Java" or "Programming" rather than the
entire string. The substring() method allows us to extract only the required portion.
9.14.2 Syntax
There are two forms of the method.
182
COS 201: Computer Programming I Lecture Notes
Method 1
[Link](startIndex);
Extracts characters from the specified starting position to the end of the string.
Method 2
[Link](
startIndex,
endIndex
);
[Link](
[Link](0, 7)
);
Output
Program
Character positions:
P r o g r a m m i n g
0 1 2 3 4 5 6 7 8 9 10
Program
[Link](
[Link](3)
);
183
COS 201: Computer Programming I Lecture Notes
Output
gramming
The extraction starts at index 3 and continues to the end of the string.
[Link](
[Link](0, 5)
);
Output
Amina
[Link](
[Link](6)
);
Output
.pdf
This technique is often used when processing files.
• Processing dates.
184
COS 201: Computer Programming I Lecture Notes
Example:
String text = "Java";
[Link](
[Link](10)
);
7. These methods help programmers search, locate, and extract information efficiently.
The indexOf() and substring() methods are among the most powerful and fre-
quently used String methods in Java. Together, they provide the ability to locate in-
formation within strings and extract meaningful portions of text, making them essential
tools for real-world software development.
185
COS 201: Computer Programming I Lecture Notes
9.15 replace()
The replace() method is used to replace characters or substrings within a string with
new characters or substrings.
Since strings in Java are immutable, the original string is not modified. Instead, the
method returns a new string containing the replacements.
The replace() method is commonly used for correcting text, changing words, for-
matting data, and processing user input.
Suppose we want to change the word "Java" to "Python". Rather than creating a
completely new string manually, we can use the replace() method.
9.15.2 Syntax
Replacing Characters
[Link](
oldCharacter,
newCharacter
);
Replacing Substrings
[Link](
oldString,
newString
);
[Link](
[Link](
"Java",
186
COS 201: Computer Programming I Lecture Notes
"Python"
)
);
Output
Python
[Link](
[Link](’a’, ’o’)
);
Output
bonono
String sentence =
"I love Java";
[Link](
[Link](
"Java",
"Programming"
)
);
Output
I love Programming
187
COS 201: Computer Programming I Lecture Notes
String text =
"Computer Science";
[Link](
[Link](" ", "-")
);
Output
Computer-Science
String newText =
[Link](
"Java",
"Python"
);
[Link](text);
[Link](newText);
Output
Java
Python
• Correcting text.
188
COS 201: Computer Programming I Lecture Notes
Example:
String text = "Java";
[Link](
[Link](
"java",
"Python"
)
);
Output
Java
9.16 trim()
The trim() method removes leading and trailing whitespace from a string.
Leading whitespace refers to spaces at the beginning of a string, while trailing whites-
pace refers to spaces at the end.
The method is useful when processing user input because users often accidentally
enter extra spaces before or after text.
Like other String methods, trim() does not modify the original string. Instead, it
returns a new string with the unnecessary spaces removed.
189
COS 201: Computer Programming I Lecture Notes
Java
or
Java
Although the text appears similar, the spaces are actually part of the string and may
cause comparisons to fail.
The trim() method helps remove these unwanted spaces.
9.16.2 Syntax
[Link]();
[Link](
[Link]()
);
Output
Java
[Link](
[Link]()
);
Output
student123
190
COS 201: Computer Programming I Lecture Notes
[Link](
[Link]().equals(s2)
);
Output
true
Without trimming, the comparison would return false because the spaces are con-
sidered part of the string.
[Link](
[Link]()
);
Output
Computer Science
String cleaned =
[Link]();
[Link](text);
[Link](cleaned);
191
COS 201: Computer Programming I Lecture Notes
Output
Java
Java
192
COS 201: Computer Programming I Lecture Notes
7. These methods are widely used in text processing and input validation.
The replace() and trim() methods are essential tools for cleaning, modifying, and
formatting text in Java applications. They help programmers prepare strings for storage,
comparison, display, and further processing.
The == operator compares references, while the equals() method compares contents.
193
COS 201: Computer Programming I Lecture Notes
if(s1 == s2)
{
[Link]("Equal");
}
The == operator checks whether both variables refer to the same object in memory.
In some cases, Java may store identical string literals in a shared memory area called
the String Pool. When this happens, s1 == s2 may return true.
However, relying on this behavior is dangerous because it does not actually compare
the text inside the strings.
[Link](s1 == s2);
Output
false
Java
the result is false because two separate String objects were created in memory.
s2 -----> "Java"
Even though the contents are identical, the references are different.
Therefore:
s1 == s2
returns:
false
194
COS 201: Computer Programming I Lecture Notes
if([Link](s2))
{
[Link]("Equal");
}
Output
Equal
The equals() method compares the actual characters contained in both strings.
If the contents are identical, the method returns true.
Another Example
[Link](
[Link](secondName)
);
Output
true
Since both strings contain exactly the same sequence of characters, the result is true.
[Link](
[Link](s2)
);
195
COS 201: Computer Programming I Lecture Notes
Output
false
Although the letters are the same, the uppercase and lowercase characters are differ-
ent.
[Link](
[Link](s2)
);
Output
true
This method compares the strings without considering differences in letter case.
String username =
"student";
String entered =
"student";
if([Link](entered))
{
[Link](
"Login Successful"
);
}
else
{
[Link](
"Invalid Username"
);
}
196
COS 201: Computer Programming I Lecture Notes
Output
Login Successful
String comparison is frequently used in login systems, forms, and data validation.
String entered =
" java123 ";
[Link](
[Link](
[Link]()
)
);
Output
true
The trim() method removes leading and trailing spaces before comparison.
197
COS 201: Computer Programming I Lecture Notes
5. Understanding the difference between references and contents helps prevent pro-
gramming errors.
While the char data type can store individual characters, Java also provides the
Character class, which contains many useful methods for examining and manipulating
characters.
The Character class belongs to the [Link] package and is automatically available
in every Java program.
198
COS 201: Computer Programming I Lecture Notes
These operations are very common when processing text, validating user input, and
developing data-entry applications.
[Link](grade);
Output
Notice that characters are enclosed in single quotation marks (’ ’), whereas strings
use double quotation marks (" ").
Character String
Stores one character Stores multiple characters
Uses char Uses String
Single quotes Double quotes
’A’ "A"
Example:
char letter = ’J’;
199
COS 201: Computer Programming I Lecture Notes
• isLetter()
• isDigit()
• isUpperCase()
• isLowerCase()
• isWhitespace()
• toUpperCase()
• toLowerCase()
• Form validation.
• Password verification.
• Text editors.
200
COS 201: Computer Programming I Lecture Notes
• Search applications.
• Educational software.
For example, a program may verify whether a user’s input contains only letters and
numbers before accepting it.
• Character methods are useful when processing text one character at a time.
4. The Character class contains methods for testing and converting characters.
6. The Character class is useful for text processing and input validation.
The Character class is an important utility class in Java that provides powerful
methods for analyzing and manipulating individual characters. It plays a vital role in
text processing, validation, and many real-world programming applications.
201
COS 201: Computer Programming I Lecture Notes
Most Character methods are static methods, meaning they are called using the class
name Character rather than through an object.
General syntax:
[Link](character);
The following are some of the most commonly used Character methods.
9.19.1 isLetter()
The isLetter() method checks whether a character is an alphabetic letter.
It returns:
• false otherwise.
Syntax
[Link](character);
Example
[Link](
[Link](’A’)
);
Output
true
Another Example
[Link](
[Link](’9’)
);
Output
false
202
COS 201: Computer Programming I Lecture Notes
Applications
• Name validation.
• Text processing.
9.19.2 isDigit()
The isDigit() method determines whether a character is a numeric digit.
It returns:
• false otherwise.
Syntax
[Link](character);
Example
[Link](
[Link](’7’)
);
Output
true
Another Example
[Link](
[Link](’A’)
);
Output
false
203
COS 201: Computer Programming I Lecture Notes
Applications
• Number validation.
9.20 isUpperCase()
The isUpperCase() method checks whether a character is an uppercase letter.
It returns:
• false otherwise.
Syntax
[Link](character);
Example
[Link](
[Link](’A’)
);
Output
true
Another Example
[Link](
[Link](’a’)
);
Output
false
204
COS 201: Computer Programming I Lecture Notes
Applications
• Password validation.
• Text formatting.
9.21 isLowerCase()
The isLowerCase() method checks whether a character is a lowercase letter.
It returns:
• false otherwise.
Syntax
[Link](character);
Example
[Link](
[Link](’a’)
);
Output
true
Another Example
[Link](
[Link](’A’)
);
Output
false
205
COS 201: Computer Programming I Lecture Notes
Applications
• Input validation.
• Text analysis.
• Formatting text.
9.22 toUpperCase()
The toUpperCase() method converts a character to its uppercase equivalent.
If the character is already uppercase, it remains unchanged.
Syntax
[Link](character);
Example
[Link](
[Link](’a’)
);
Output
Another Example
[Link](
[Link](’Z’)
);
Output
206
COS 201: Computer Programming I Lecture Notes
Applications
• Standardizing text.
• Case-insensitive processing.
• Data formatting.
9.23 toLowerCase()
The toLowerCase() method converts a character to its lowercase equivalent.
If the character is already lowercase, it remains unchanged.
Syntax
[Link](character);
Example
[Link](
[Link](’A’)
);
Output
Another Example
[Link](
[Link](’m’)
);
Output
Since ’m’ is already lowercase, the method returns the same character.
207
COS 201: Computer Programming I Lecture Notes
Applications
• Standardizing text.
• Data normalization.
• Case-insensitive comparisons.
Practical Example
The following program demonstrates several Character methods together.
char ch = ’A’;
[Link](
[Link](ch)
);
[Link](
[Link](ch)
);
[Link](
[Link](ch)
);
[Link](
[Link](ch)
);
Output
true
false
true
a
208
COS 201: Computer Programming I Lecture Notes
7. These methods are useful for validation, formatting, and text processing.
The Character class provides powerful tools for working with individual characters in
Java. By using methods such as isLetter(), isDigit(), isUpperCase(), and toLowerCase(),
programmers can efficiently validate, analyze, and manipulate textual data in real-world
applications.
• Counting digits.
• Counting letters.
209
COS 201: Computer Programming I Lecture Notes
• Validating passwords.
J a v a
0 1 2 3
for(int i = 0;
i < [Link]();
i++)
{
[Link](
[Link](i)
);
}
Output
J
a
v
a
The loop begins at index 0 and continues until the final character.
210
COS 201: Computer Programming I Lecture Notes
int count = 0;
for(int i = 0;
i < [Link]();
i++)
{
if([Link](
[Link](i)))
{
count++;
}
}
[Link](count);
Output
C S C 1 0 1
Character Digit?
C No
S No
C No
1 Yes
0 Yes
1 Yes
211
COS 201: Computer Programming I Lecture Notes
int letters = 0;
for(int i = 0;
i < [Link]();
i++)
{
if([Link](
[Link](i)))
{
letters++;
}
}
[Link](letters);
Output
C
S
C
int count = 0;
for(int i = 0;
i < [Link]();
i++)
{
212
COS 201: Computer Programming I Lecture Notes
if([Link](
[Link](i)))
{
count++;
}
}
[Link](count);
Output
2
The uppercase letters are:
J
P
int count = 0;
for(int i = 0;
i < [Link]();
i++)
{
if([Link](
[Link](i)))
{
count++;
}
}
[Link](count);
Output
3
The lowercase letters are:
a
v
a
213
COS 201: Computer Programming I Lecture Notes
int spaces = 0;
for(int i = 0;
i < [Link]();
i++)
{
if([Link](i) == ’ ’)
{
spaces++;
}
}
[Link](spaces);
Output
for(int i = 0;
i < [Link]();
i++)
{
[Link](
[Link](
[Link](i)
)
);
}
Output
214
COS 201: Computer Programming I Lecture Notes
JAVA
for(int i = 0;
i < [Link]();
i++)
{
if([Link](
[Link](i)))
{
hasDigit = true;
}
}
[Link](hasDigit);
Output
true
// Process ch
}
215
COS 201: Computer Programming I Lecture Notes
Explanation:
• Password validation.
• Form validation.
• Text editors.
• Search engines.
• Data cleaning.
• File processing.
216
COS 201: Computer Programming I Lecture Notes
int vowels = 0;
217
COS 201: Computer Programming I Lecture Notes
char ch =
[Link](
[Link](i));
if(ch == ’a’ ||
ch == ’e’ ||
ch == ’i’ ||
ch == ’o’ ||
ch == ’u’)
{
vowels++;
}
}
[Link](
"Vowels = " + vowels
);
for(int i = [Link]()-1;
i >= 0;
i--)
{
[Link](
[Link](i)
);
}
Output
avaJ
218
COS 201: Computer Programming I Lecture Notes
StringBuilder sb =
new StringBuilder("Java");
[Link](" Programming");
[Link](sb);
Output
Java Programming
Method Description
append() Adds text at the end
insert() Inserts text at a position
delete() Removes characters
replace() Replaces characters
reverse() Reverses contents
length() Returns length
• Search engines
• Text editors
• Email processing
• Data validation
• Chat applications
• Web development
• Database systems
219
COS 201: Computer Programming I Lecture Notes
220
COS 201: Computer Programming I Lecture Notes
security, reliability, and memory management, but it can also affect performance when
many modifications are required.
The chapter introduced string concatenation, which combines two or more strings into
a single string. In Java, concatenation is commonly performed using the + operator. This
feature makes it easy to create messages, display output, and combine user input with
other text. We also examined escape sequences, which allow special characters such as
quotation marks, tabs, and new lines to be included within string literals.
A variety of useful methods provided by the String class were discussed. These meth-
ods allow programmers to determine the length of a string, access individual characters,
compare strings, search for characters or substrings, extract portions of text, replace
characters, remove unwanted spaces, and convert text between uppercase and lowercase
forms. Such operations are essential in text processing and data validation tasks.
The chapter also covered proper string comparison techniques. While the == oper-
ator compares object references, the equals() method compares the actual contents of
strings. Understanding this distinction is important for writing correct Java programs
and avoiding common programming errors.
In addition, we studied the Character class, which provides a collection of methods for
working with individual characters. These methods can determine whether a character
is a letter, digit, uppercase letter, or lowercase letter, and can also convert characters
between uppercase and lowercase forms. The Character class is useful when analyzing or
validating textual input.
It then examined techniques for processing strings one character at a time using
loops together with the charAt() method. Through practical examples, we learned how
to count digits, letters, uppercase characters, lowercase characters, and spaces within
a string. Character-by-character processing forms the foundation of many real-world
applications such as password validation, text analysis, and data verification.
The chapter further introduced the StringBuilder class, which provides a more ef-
ficient way to modify text repeatedly. Unlike ordinary strings, a StringBuilder object
can be changed without creating new objects each time a modification is made. For ap-
plications that perform frequent string manipulations, StringBuilder offers significant
performance advantages.
Strings and character processing are fundamental concepts in Java programming.
Nearly every software application interacts with textual information in some form, whether
through user input, files, databases, web pages, or network communication. Mastering
strings, characters, and the associated Java classes equips programmers with the skills
needed to build robust, efficient, and user-friendly applications.
221
COS 201: Computer Programming I Lecture Notes
Conceptual Questions
1. Define the term character in Java.
2. Define the term string. How does a string differ from a character?
3. Explain the difference between single quotation marks (’ ’) and double quotation
marks (" ").
6. What is the difference between primitive data types and objects? Under which
category does the String class fall?
7. Explain the concept of string immutability. Why are Java strings immutable?
(a) indexOf()
(b) replace()
(c) trim()
(d) startsWith()
(e) endsWith()
15. Differentiate between the String class and the StringBuilder class.
222
COS 201: Computer Programming I Lecture Notes
18. Explain how loops can be used to process strings character by character.
20. Explain the advantages of using StringBuilder when performing repeated string
modifications.
Programming Exercises
21. Write a Java program that displays your full name using string concatenation.
22. Write a program that stores your university name in a string and displays:
23. Write a program that converts a string entered by the user to uppercase.
24. Write a program that converts a string entered by the user to lowercase.
28. Write a program that counts the number of digits contained in a string.
29. Write a program that counts the number of uppercase letters in a string.
30. Write a program that counts the number of lowercase letters in a string.
32. Write a program that determines whether a string begins with the word “Java”.
33. Write a program that determines whether a filename ends with the extension “.txt”.
34. Write a program that searches for a specific word within a sentence and displays
its position.
223
COS 201: Computer Programming I Lecture Notes
35. Write a program that replaces all spaces in a string with underscores.
36. Write a program that replaces all occurrences of the letter a with @.
37. Write a program that removes leading and trailing spaces from user input.
38. Write a program that extracts the first five characters of a string using the substring()
method.
39. Write a program that displays each character of a string on a separate line.
42. Write a program that counts the occurrences of a particular character in a string.
43. Write a program that validates whether a username starts with a letter.
44. Write a program that validates whether a password contains at least one digit.
45. Write a program that validates whether a password contains at least one uppercase
letter.
49. Write a program that creates a sentence using StringBuilder and appends three
additional words.
Challenge Exercises
1. Write a program that counts the number of words in a sentence.
4. Write a program that converts a sentence to title case (first letter of each word
capitalized).
5. Write a program that checks whether two strings are anagrams of each other.
224
COS 201: Computer Programming I Lecture Notes
8. Write a program that masks all digits in a phone number except the last four digits.
aaabbcccc
becomes
a3b2c4
10. Design a menu-driven application that allows the user to perform multiple string
operations such as searching, replacing, converting case, and counting characters.
225
Chapter 10
Arrays
10.1 Introduction
In programming, it is often necessary to store multiple values of the same type. For
example, a university may need to store the scores of hundreds of students in a course, a
weather application may need to store temperature readings collected over several days,
and a banking system may need to keep track of daily account balances.
Without arrays, programmers would have to create separate variables for each value:
int score1 = 78;
int score2 = 85;
int score3 = 92;
int score4 = 67;
int score5 = 88;
This approach becomes impractical when dealing with large amounts of data.
Java provides the array data structure to solve this problem efficiently.
An array is a collection of elements of the same data type stored in contiguous memory
locations and accessed using an index.
• Define an array.
226
COS 201: Computer Programming I Lecture Notes
78 85 92 67 88
0 1 2 3 4
The numbers in the second row represent the array indices.
227
COS 201: Computer Programming I Lecture Notes
or
dataType arrayName[];
Examples
int[] scores;
double[] temperatures;
char[] grades;
String[] names;
Syntax
Example
int[] scores = new int[5];
228
COS 201: Computer Programming I Lecture Notes
scores[0] = 78;
scores[1] = 85;
scores[2] = 92;
scores[3] = 67;
scores[4] = 88;
229
COS 201: Computer Programming I Lecture Notes
[Link](scores[2]);
Output
92
scores[1] = 90;
[Link](scores[1]);
Output
90
[Link]([Link]);
Output
230
COS 201: Computer Programming I Lecture Notes
10.15.1 Syntax
Example
int[] scores = {78, 85, 92};
231
COS 201: Computer Programming I Lecture Notes
int sum = 0;
[Link](sum);
Output
410
int sum = 0;
double average =
(double) sum / [Link];
[Link](average);
Output
82.0
232
COS 201: Computer Programming I Lecture Notes
[Link](largest);
Output
92
[Link](smallest);
Output
67
233
COS 201: Computer Programming I Lecture Notes
[Link](found);
Output
true
import [Link];
Example
import [Link];
[Link](values);
234
COS 201: Computer Programming I Lecture Notes
Output
9 12 21 45 78
import [Link];
int[] copy =
[Link](original,
[Link]);
235
COS 201: Computer Programming I Lecture Notes
return data;
}
10.27.1 Declaration
int[][] matrix;
10.27.2 Creation
int[][] matrix =
new int[3][4];
236
COS 201: Computer Programming I Lecture Notes
Output
[Link]();
}
237
COS 201: Computer Programming I Lecture Notes
• Payroll systems
• Scientific computing
• Data analysis
• Computer graphics
• Image processing
• Database applications
• Artificial intelligence
• Machine learning
• Game development
Conceptual Questions
1. Define the term character in Java.
2. Define the term string. How does a string differ from a character?
3. Explain the difference between single quotation marks (’ ’) and double quotation
marks (" ").
6. What is the difference between primitive data types and objects? Under which
category does the String class fall?
238
COS 201: Computer Programming I Lecture Notes
7. Explain the concept of string immutability. Why are Java strings immutable?
(a) indexOf()
(b) replace()
(c) trim()
(d) startsWith()
(e) endsWith()
15. Differentiate between the String class and the StringBuilder class.
18. Explain how loops can be used to process strings character by character.
20. Explain the advantages of using StringBuilder when performing repeated string
modifications.
Programming Exercises
21. Write a Java program that displays your full name using string concatenation.
22. Write a program that stores your university name in a string and displays:
239
COS 201: Computer Programming I Lecture Notes
23. Write a program that converts a string entered by the user to uppercase.
24. Write a program that converts a string entered by the user to lowercase.
28. Write a program that counts the number of digits contained in a string.
29. Write a program that counts the number of uppercase letters in a string.
30. Write a program that counts the number of lowercase letters in a string.
32. Write a program that determines whether a string begins with the word “Java”.
33. Write a program that determines whether a filename ends with the extension “.txt”.
34. Write a program that searches for a specific word within a sentence and displays
its position.
35. Write a program that replaces all spaces in a string with underscores.
36. Write a program that replaces all occurrences of the letter a with @.
37. Write a program that removes leading and trailing spaces from user input.
38. Write a program that extracts the first five characters of a string using the substring()
method.
39. Write a program that displays each character of a string on a separate line.
42. Write a program that counts the occurrences of a particular character in a string.
43. Write a program that validates whether a username starts with a letter.
44. Write a program that validates whether a password contains at least one digit.
45. Write a program that validates whether a password contains at least one uppercase
letter.
240
COS 201: Computer Programming I Lecture Notes
49. Write a program that creates a sentence using StringBuilder and appends three
additional words.
Challenge Exercises
1. Write a program that counts the number of words in a sentence.
4. Write a program that converts a sentence to title case (first letter of each word
capitalized).
5. Write a program that checks whether two strings are anagrams of each other.
8. Write a program that masks all digits in a phone number except the last four digits.
aaabbcccc
becomes
a3b2c4
10. Design a menu-driven application that allows the user to perform multiple string
operations such as searching, replacing, converting case, and counting characters.
241
COS 201: Computer Programming I Lecture Notes
242
COS 201: Computer Programming I Lecture Notes
of columns, jagged arrays provide greater flexibility when dealing with data structures
that require varying row sizes. This feature is useful in many practical applications where
data is not uniformly distributed.
Throughout the chapter, emphasis was placed on the importance of loops when work-
ing with arrays. Because arrays often contain many elements, loops provide an efficient
way to process each element systematically. Combining arrays with loops enables pro-
grammers to perform complex operations with minimal code.
Arrays are among the most widely used data structures in software development.
They serve as the foundation for many advanced data structures and algorithms and
are used extensively in fields such as scientific computing, business applications, game
development, database systems, data analysis, artificial intelligence, and web applications.
A solid understanding of arrays is therefore essential for every programmer, as it provides
the basis for efficient data storage, organization, and processing in Java programs.
243
Chapter 11
11.1 Introduction
As programs become larger and more complex, it becomes necessary to organize code
into smaller, manageable, and reusable units. In Java, this is achieved through the use
of methods. A method is a collection of statements that performs a specific task and
can be executed whenever needed.
Methods improve program readability, reduce code duplication, simplify debugging,
and encourage modular programming. Instead of writing the same code repeatedly, a
programmer can place the code inside a method and call it whenever required.
Java also supports method overloading, a feature that allows multiple methods to
have the same name but different parameter lists. Method overloading increases program
flexibility and improves code readability.
This chapter discusses methods, method declarations, method calls, parameter pass-
ing, return values, scope of variables, recursion, and method overloading.
• Displaying a message
• Sorting an array
244
COS 201: Computer Programming I Lecture Notes
1. Code Reusability
A method can be called multiple times without rewriting code.
2. Modularity
Programs can be divided into smaller logical units.
3. Simplified Testing
Individual methods can be tested independently.
4. Easy Maintenance
Changes can be made in one place without affecting the entire program.
5. Improved Readability
Methods make programs easier to understand.
Example:
public static void displayMessage()
{
[Link]("Welcome to Java");
}
245
COS 201: Computer Programming I Lecture Notes
• public
• private
• protected
• default
Example:
public static void show()
{
}
• int
• double
• float
• char
• boolean
• String
• void
Example:
public static int square(int n)
{
return n * n;
}
246
COS 201: Computer Programming I Lecture Notes
• calculateArea()
• findMaximum()
• printReport()
• getAverage()
Here:
247
COS 201: Computer Programming I Lecture Notes
Complete Example:
public class Test
{
public static void greet()
{
[Link]("Good Morning");
}
Output:
Good Morning
Method call:
displayName("Aminu");
Output:
Aminu
248
COS 201: Computer Programming I Lecture Notes
Method call:
int result = square(5);
[Link](result);
Output:
25
Example:
public static int maximum(int a, int b)
{
if(a > b)
return a;
else
return b;
}
249
COS 201: Computer Programming I Lecture Notes
Method call:
welcome();
250
COS 201: Computer Programming I Lecture Notes
change(num);
[Link](num);
}
Output:
50
Characteristics:
251
COS 201: Computer Programming I Lecture Notes
{
[Link](x);
}
1. Memory is allocated.
4. Method executes.
11.16 Recursion
Recursion occurs when a method calls itself.
Example:
public static void countDown(int n)
{
if(n == 0)
return;
[Link](n);
countDown(n - 1);
}
Call:
countDown(5);
Output:
252
COS 201: Computer Programming I Lecture Notes
5
4
3
2
1
n! = n × (n − 1)!
Example:
public static int factorial(int n)
{
if(n == 0)
return 1;
Output:
factorial(5) = 120
253
COS 201: Computer Programming I Lecture Notes
When an overloaded method is called, the Java compiler examines the arguments sup-
plied in the method call and determines which version of the method should be executed.
This process is called compile-time polymorphism or static binding.
The methods have the same name, add(), but their parameter types are different.
The compiler automatically selects the correct method.
[Link](
add(5, 3));
[Link](
add(5.5, 3.2));
Output
8
8.7
In the first call, the compiler uses the version that accepts two integers.
In the second call, the compiler uses the version that accepts two double values.
254
COS 201: Computer Programming I Lecture Notes
This causes a compilation error because both methods have identical parameter lists.
To overload methods successfully, the parameter lists must be different.
Method overloading allows multiple methods to share the same name while having
different parameter lists. The compiler determines which version to execute based on the
arguments supplied during the method call. Method overloading improves readability,
promotes code reuse, and makes programs easier to understand and maintain.
255
COS 201: Computer Programming I Lecture Notes
• Improved readability
• Easier maintenance
1. Number of parameters
3. Order of parameters
256
COS 201: Computer Programming I Lecture Notes
Compiler Error:
257
COS 201: Computer Programming I Lecture Notes
Output:
6
10.0
24
258
COS 201: Computer Programming I Lecture Notes
Output:
75.0
80.0
• Infinite recursion
259
COS 201: Computer Programming I Lecture Notes
Method overloading allows multiple methods to share the same name while differing
in parameter lists. Overloading enhances flexibility and readability by enabling similar
operations to be grouped under a common method name. Understanding methods and
method overloading is essential for developing structured, efficient, and reusable Java
programs.
8. What is recursion?
12. Why can’t methods be overloaded by changing only the return type?
260
COS 201: Computer Programming I Lecture Notes
• Circle
• Rectangle
• Triangle
• Integer
• Double
• String
10. Design a calculator program using overloaded methods for addition, subtraction,
multiplication, and division.
11. Write a program that calculates student averages using overloaded methods.
15. Design a menu-driven application that demonstrates method calls and method over-
loading.
261
Chapter 12
Object-Oriented Programming
Concepts
12.1 Introduction
Object-Oriented Programming (OOP) is a programming paradigm that organizes soft-
ware design around objects rather than functions and logic. An object represents a
real-world entity that contains both data (attributes) and behavior (methods).
Java is a fully object-oriented programming language, meaning that almost everything
in Java is based on classes and objects. OOP helps in building software that is modular,
reusable, scalable, and easier to maintain.
1. Encapsulation
2. Abstraction
3. Inheritance
4. Polymorphism
262
COS 201: Computer Programming I Lecture Notes
12.3.1 Class
A class is a blueprint or template used to create objects. It defines the properties and
behaviors that objects will have.
class Student {
String name;
int age;
void display() {
[Link](name);
[Link](age);
}
}
12.3.2 Object
An object is an instance of a class. It represents a real-world entity created from a class.
public class Test {
public static void main(String[] args) {
[Link] = "Aminu";
[Link] = 20;
[Link]();
}
}
12.4 Encapsulation
Encapsulation is the process of wrapping data (variables) and methods into a single unit
called a class, and restricting direct access to some components using access modifiers.
263
COS 201: Computer Programming I Lecture Notes
• Increased security
• Improved maintainability
Example
class Account {
private double balance;
12.5 Abstraction
Abstraction is the concept of hiding implementation details and showing only essential
features to the user.
It focuses on what an object does rather than how it does it.
• Increases security
264
COS 201: Computer Programming I Lecture Notes
}
}
12.6 Inheritance
Inheritance allows one class to acquire properties and behaviors of another class.
It promotes code reuse and establishes an IS-A relationship.
class Animal {
void eat() {
[Link]("Eating...");
}
}
12.7 Polymorphism
Polymorphism means "many forms". It allows the same method or operation to behave
differently depending on the object.
There are two types:
Example
class Animal {
void sound() {
[Link]("Animal sound");
}
}
265
COS 201: Computer Programming I Lecture Notes
}
}
266
COS 201: Computer Programming I Lecture Notes
• Banking systems
• Mobile applications
• Web applications
• Game development
• Simulation systems
• Enterprise software
267
COS 201: Computer Programming I Lecture Notes
268
COS 201: Computer Programming I Lecture Notes
involved. This flexibility enables programmers to write more general, adaptable, and
extensible code, making it easier to add new functionality without significantly changing
existing programs.
The chapter highlighted how these four principles work together to create robust and
scalable software systems. Encapsulation protects data, abstraction simplifies complexity,
inheritance promotes code reuse, and polymorphism provides flexibility. Together, these
principles form the foundation of object-oriented software design and development.
The chapter discussed the major advantages of Object-Oriented Programming. OOP
improves modularity by organizing programs into independent classes and objects. It
enhances reusability through inheritance and class-based design, reducing development
time and code duplication. OOP also improves maintainability by making programs
easier to modify, debug, test, and extend. These benefits have made OOP one of the
most widely used programming paradigms in modern software development.
A solid understanding of Object-Oriented Programming is essential for mastering
Java and developing professional software applications. The concepts introduced in this
chapter provide the foundation for more advanced topics such as class design, inheritance
hierarchies, interfaces, abstract classes, exception handling, graphical user interfaces, and
enterprise software development.
Conceptual Questions
1. Define Object-Oriented Programming (OOP).
269
COS 201: Computer Programming I Lecture Notes
13. Explain the terms parent class, child class, superclass, and subclass.
18. Explain how the four principles of OOP work together to improve software quality.
22. Explain the concept of code reuse and its relationship with inheritance.
(a) Class
(b) Object
(c) Method
(d) Attribute
(e) Constructor
270
COS 201: Computer Programming I Lecture Notes
31. Give two examples of software systems that make extensive use of OOP.
32. Explain why large software projects commonly use OOP principles.
Programming Exercises
33. Write a Java program that creates a class named Student with attributes for name
and matriculation number. Create an object of the class and display its information.
34. Write a Java program that creates a class named Book with attributes for title,
author, and price. Create two book objects and display their details.
36. Write a program demonstrating encapsulation using a class named Employee con-
taining private data members and public methods for accessing them.
37. Write a program that creates a class named Rectangle with methods for calculating
area and perimeter.
38. Write a program that creates a class named Circle with methods for calculating
area and circumference.
39. Write a program showing inheritance between a class named Person and a class
named Student.
40. Write a program showing inheritance between a class named Vehicle and a class
named Car.
41. Write a program showing inheritance between a class named Animal and a class
named Dog.
42. Create a class hierarchy consisting of Employee, Manager, and Director. Demon-
strate inheritance among the classes.
271
COS 201: Computer Programming I Lecture Notes
45. Create a program where different classes implement the same method in different
ways to demonstrate polymorphism.
46. Write a program that models a university system using classes such as Student,
Lecturer, and Course.
47. Write a program that models a library management system using classes and ob-
jects.
48. Write a program that models a banking system using OOP concepts.
49. Write a program that models a hospital management system using OOP principles.
(a) Classes
(b) Objects
(c) Attributes
(d) Methods
2. Design a simple library management system and identify the OOP concepts used.
4. Design a vehicle management system and explain how inheritance can be applied.
5. Design an online shopping system and explain how polymorphism can be used.
8. Design a university information system that incorporates all four OOP principles.
Challenge Exercises
1. Develop a complete banking application that demonstrates encapsulation, inheri-
tance, and polymorphism.
2. Create a payroll system where different employee types calculate salaries differently
using polymorphism.
272
COS 201: Computer Programming I Lecture Notes
4. Build a simple inventory management system using classes, objects, and inheritance.
• Encapsulation
• Abstraction
• Inheritance
• Polymorphism
273
Chapter 13
13.1 Introduction
Object-Oriented Programming (OOP) is built on four fundamental principles: encapsu-
lation, abstraction, inheritance, and polymorphism. These principles help in designing
software that is modular, reusable, and easier to maintain.
This chapter focuses on two important OOP concepts: inheritance and polymor-
phism. Inheritance allows one class to acquire properties and behaviors of another class,
while polymorphism allows a single action to behave differently in different contexts.
Together, these concepts form the foundation of advanced Java programming and are
widely used in real-world software systems.
• Code reusability
• Reduced redundancy
• Easier maintenance
274
COS 201: Computer Programming I Lecture Notes
1. Single inheritance
2. Multilevel inheritance
3. Hierarchical inheritance
Note: Java does not support multiple inheritance with classes to avoid ambiguity, but
it can be achieved using interfaces.
Output
275
COS 201: Computer Programming I Lecture Notes
Eating...
Barking...
276
COS 201: Computer Programming I Lecture Notes
void eat() {
[Link]("Eating...");
}
}
Example
class Animal {
void sound() {
[Link]("Animal sound");
}
}
277
COS 201: Computer Programming I Lecture Notes
Example
class Animal {
void sound() {
[Link]("Animal sound");
}
}
278
COS 201: Computer Programming I Lecture Notes
Output
Dog barks
279
COS 201: Computer Programming I Lecture Notes
a = new Cat();
[Link]();
a = new Animal();
[Link]();
}
}
280
COS 201: Computer Programming I Lecture Notes
void sleep() {
[Link]("Sleeping...");
}
}
13.16 Interfaces
An interface is a blueprint of a class that contains abstract methods.
Example
interface Animal {
void sound();
}
281
COS 201: Computer Programming I Lecture Notes
interface B {
void showB();
}
class C implements A, B {
public void showA() {
[Link]("A");
}
• Game development
• Database systems
• Banking systems
• Simulation systems
• Cloud-based applications
282
COS 201: Computer Programming I Lecture Notes
283
COS 201: Computer Programming I Lecture Notes
The chapter further explored the concept of polymorphism, which enables a single
interface to represent multiple forms or behaviors. Polymorphism allows programmers to
write general-purpose code that can work with different object types through a common
reference. As a result, programs become more flexible, extensible, and easier to maintain.
Two major forms of polymorphism were discussed. Method overloading is an
example of compile-time polymorphism, where multiple methods share the same name
but differ in their parameter lists. The compiler determines which version of the method
to execute based on the arguments supplied. In contrast, method overriding is an
example of runtime polymorphism, where the method implementation is selected during
program execution based on the actual object type.
The chapter also introduced abstract classes, which provide a mechanism for achiev-
ing abstraction in Java. An abstract class cannot be instantiated directly and may contain
both abstract methods and concrete methods. Abstract classes serve as templates for re-
lated subclasses by defining common characteristics while allowing subclasses to provide
specific implementations of abstract behaviors.
Another important abstraction mechanism discussed was the interface. An interface
defines a contract that specifies what methods a class must implement without providing
complete implementations. Interfaces promote loose coupling, increase flexibility, and
support the design of highly modular software systems. By implementing interfaces,
unrelated classes can share common behaviors while maintaining independent class hier-
archies.
A significant advantage of interfaces is that they enable a form of multiple inher-
itance in Java. While a class can inherit from only one parent class, it can implement
multiple interfaces. This feature allows a class to acquire behaviors from multiple sources
without the complications associated with multiple class inheritance.
Throughout the chapter, we saw how inheritance, polymorphism, abstract classes,
and interfaces work together to support object-oriented design. Inheritance provides code
reuse, polymorphism enables flexibility, abstract classes establish common foundations,
and interfaces define contracts for behavior. Together, these features help developers
build software that is easier to understand, maintain, extend, and reuse.
Mastering these concepts is essential for developing professional Java applications.
They form the basis for many advanced topics in software engineering and are widely used
in frameworks, libraries, enterprise applications, graphical user interfaces, web systems,
and large-scale software projects.
284
COS 201: Computer Programming I Lecture Notes
4. What is polymorphism?
12. Why does Java not support multiple inheritance with classes?
15. Design a simple system that uses inheritance and method overriding.
285
Chapter 14
14.1 Introduction
Input and output (I/O) operations are fundamental in programming because they allow
a program to interact with users and external systems. In Java, input refers to receiving
data from the user or another source, while output refers to displaying data to the screen
or sending it to another destination.
Simple input and output operations are essential for building interactive applications
such as calculators, banking systems, registration systems, and command-line programs.
This chapter introduces basic input and output in Java using the Scanner class for
input and [Link] for output.
[Link]("Hello ");
[Link]("World");
286
COS 201: Computer Programming I Lecture Notes
[Link]();
Output
Hello World
Welcome to Java Programming
Specifier Description
%d Integer values
%f Floating-point values
%s Strings
%c Characters
%.2f Floating-point with 2 decimal places
Example
public class PrintfExample {
public static void main(String[] args) {
287
COS 201: Computer Programming I Lecture Notes
• BufferedReader
• Console
import [Link];
Method Description
nextInt() Reads an integer
nextDouble() Reads a floating-point number
next() Reads a single word
nextLine() Reads an entire line
nextBoolean() Reads true/false value
288
COS 201: Computer Programming I Lecture Notes
Output Example
Enter your name: Aminu
Enter your age: 21
Name: Aminu
Age: 21
int a = [Link]();
int b = [Link]();
int c = [Link]();
int sum = a + b + c;
289
COS 201: Computer Programming I Lecture Notes
Problem Example
14.8.1 Solution
Add an extra nextLine():
int age = [Link]();
[Link](); // consume newline
String name = [Link]();
290
COS 201: Computer Programming I Lecture Notes
int b = [Link]();
int sum = a + b;
int product = a * b;
• File
• FileWriter
• FileReader
• BufferedReader
• PrintWriter
291
COS 201: Computer Programming I Lecture Notes
292
COS 201: Computer Programming I Lecture Notes
We also examined a common issue that occurs when mixing Scanner methods such as
nextInt() and nextLine(). Because numeric input methods leave the newline character
in the input buffer, unexpected behavior may occur when a subsequent nextLine() call
is made. We learned techniques for handling this situation correctly to ensure reliable
input processing.
Throughout the chapter, emphasis was placed on the importance of validating and
handling user input carefully. Programs should be designed to accept data accurately
and provide meaningful feedback when invalid input is entered. Proper input handling
contributes to the reliability, usability, and robustness of software applications.
Input and output operations are fundamental to virtually every software system.
Whether a program is reading information from users, files, databases, sensors, or net-
work connections, input mechanisms provide the data required for processing. Similarly,
output operations enable programs to communicate results through screens, reports, files,
printers, or other devices.
A solid understanding of Java input and output techniques is essential for building
interactive applications. The concepts introduced in this chapter provide the founda-
tion for more advanced topics such as file handling, graphical user interfaces, database
connectivity, network programming, and enterprise application development. Mastering
these skills enables programmers to create software that effectively communicates with
users and responds to real-world data.
2. Differentiate between the print() and println() methods in Java. Provide ex-
amples to illustrate your answer.
3. What is the purpose of the Scanner class in Java? Why must it be imported before
use?
4. Write a Java program that reads a user’s name and age from the keyboard and
displays the information in a well-formatted sentence.
5. List and briefly explain any five methods provided by the Scanner class.
6. Explain the purpose of the printf() method. What advantages does formatted
output provide compared to print() and println()?
7. Write a Java program that accepts three numbers from the user and calculates their
average.
293
COS 201: Computer Programming I Lecture Notes
8. Describe the common problem that occurs when nextInt() is followed by nextLine().
How can this issue be resolved?
9. Write a Java program that reads a single character from the user and displays it
on the screen.
10. Develop a simple calculator program that accepts two numbers and an arithmetic
operator from the user, then displays the result of the operation.
11. In which Java package is the Scanner class located? Write the import statement
required to use it.
12. Explain how to read an entire sentence, including spaces, from the keyboard in
Java.
13. Write a Java program that converts a temperature entered in degrees Celsius to
degrees Fahrenheit and displays the result.
14. Discuss at least four common input-related errors that programmers may encounter
when using the Scanner class.
15. Why is input validation important in software applications? Discuss its role in
improving program reliability and security.
16. Write a Java program that asks the user to enter the length and width of a rectangle
and then calculates and displays its area and perimeter.
17. Create a program that accepts a student’s name and three examination scores, then
calculates and displays the average score.
18. Explain the difference between next() and nextLine() with suitable examples.
19. Write a Java program that prompts the user to enter their year of birth and then
calculates their current age.
20. Discuss five real-world applications where user input and output operations play a
critical role in software systems.
294
Chapter 15
Recursion
15.1 Introduction
Recursion is a powerful programming technique in which a method calls itself in order to
solve a problem. Instead of solving a problem directly, recursion breaks the problem into
smaller sub-problems of the same type until a base condition is reached.
Recursion is widely used for problems that have a natural repetitive structure such
as mathematical computations, searching, sorting, and tree-based algorithms.
• Recursive Case: The part where the method calls itself with a smaller input.
Without a base case, recursion will continue indefinitely and cause a stack overflow
error.
295
COS 201: Computer Programming I Lecture Notes
else
{
return methodName(smallerProblem);
}
}
n! = n × (n − 1) × (n − 2) × · · · × 1
Recursive definition:
n! = n × (n − 1)!
296
COS 201: Computer Programming I Lecture Notes
}
}
Output
Factorial = 120
F (n) = F (n − 1) + F (n − 2)
with:
F (0) = 0, F (1) = 1
if (n == 1)
return 1;
297
COS 201: Computer Programming I Lecture Notes
{
[Link](fib(i) + " ");
}
}
}
Output
0 1 1 2 3 5 8 13 21 34
298
COS 201: Computer Programming I Lecture Notes
[Link](n);
print(n - 1);
}
Example:
if (n == 0)
return;
Recursion Iteration
Function calls itself Uses loops (for, while)
Uses stack memory Uses less memory
More readable for complex prob- More efficient in most cases
lems
May cause stack overflow No stack overflow risk
299
COS 201: Computer Programming I Lecture Notes
• Fibonacci sequence
• Binary search
• Graph algorithms
public static int search(int[] arr, int left, int right, int key)
{
if (left > right)
return -1;
if (arr[mid] == key)
return mid;
300
COS 201: Computer Programming I Lecture Notes
3. Infinite recursion
301
COS 201: Computer Programming I Lecture Notes
We learned that recursion is particularly useful for problems that exhibit a repetitive or
self-similar structure. Instead of using loops to repeatedly perform operations, recursive
methods solve a smaller portion of the problem during each call until the base case is
reached. This approach often leads to cleaner and more intuitive solutions, especially for
mathematical computations and hierarchical data structures.
The chapter introduced the relationship between recursion and the call stack. Every
time a recursive method is invoked, a new stack frame is created in memory to store local
variables, parameters, and return information. As recursive calls continue, additional
stack frames are added to the stack. Once the base case is reached, the recursive calls
begin to return, and the stack frames are removed in the reverse order in which they
were created. Understanding this process is important for analyzing the behavior and
performance of recursive algorithms.
Several classic examples of recursion were examined, including the calculation of fac-
torials and the generation of the Fibonacci sequence. These examples demonstrated
how a large problem can be divided into smaller subproblems and solved through re-
peated self-calls. Such examples provide a foundation for understanding more advanced
recursive algorithms used in real-world applications.
We also discussed different forms of recursion. Direct recursion occurs when a
method calls itself directly. Indirect recursion occurs when one method calls another
method, which eventually calls the original method. Tail recursion is a specialized
form of recursion in which the recursive call is the final operation performed by the
method. Tail recursion can sometimes be optimized by compilers in certain programming
languages, although Java does not perform automatic tail-call optimization.
The chapter highlighted the advantages of recursion, including simplicity, readability,
and the ability to solve complex problems using concise code. Recursive solutions are
often easier to design for tasks involving trees, graphs, divide-and-conquer algorithms,
and mathematical computations. They can closely mirror the logical structure of the
problem being solved.
However, recursion also has limitations. Because each recursive call requires additional
stack memory, recursive algorithms may consume more memory than iterative solutions.
Excessive recursion can lead to stack overflow errors if the recursion depth becomes too
large. In some cases, recursive solutions may also be less efficient due to the overhead
associated with repeated method calls.
Throughout the chapter, we compared recursion with iteration. While both ap-
proaches can often solve the same problems, iterative solutions generally use loops and
consume less memory, whereas recursive solutions may offer greater clarity and simplic-
ity. Choosing between recursion and iteration depends on the nature of the problem,
performance requirements, and code maintainability considerations.
A solid understanding of recursion is essential for advanced programming and al-
302
COS 201: Computer Programming I Lecture Notes
gorithm design. Many important computer science concepts, including tree traversal,
searching algorithms, sorting techniques, backtracking, dynamic programming, and divide-
and-conquer strategies, rely heavily on recursive thinking. By mastering recursion, pro-
grammers gain a valuable tool for solving complex computational problems in a structured
and elegant manner.
2. Identify and explain the two essential components of every recursive method.
3. Write a Java program that uses a recursive method to calculate the factorial of a
given positive integer.
4. Write a recursive method that generates the Fibonacci sequence and displays the
first n Fibonacci numbers.
5. Differentiate between recursion and iteration. Discuss the advantages and disad-
vantages of each approach.
6. What is a base case in recursion? Why is it necessary for the correct execution of
a recursive algorithm?
7. Explain the concept of stack overflow in recursive programs. Under what conditions
can it occur?
8. Write a Java program that implements the binary search algorithm using recursion.
10. List and explain at least five advantages and five disadvantages of recursion.
11. Define tail recursion and explain how it differs from ordinary recursion. Provide a
suitable example.
12. Discuss at least five real-world applications of recursion in computer science and
software development.
13. Why are some recursive algorithms less efficient than iterative solutions? Explain
with examples.
14. What happens if a recursive method does not contain a valid base case?
15. Design and implement a recursive Java program that reverses a string entered by
the user.
303
COS 201: Computer Programming I Lecture Notes
16. Write a recursive method that calculates the sum of all integers from 1 to n.
17. Develop a recursive program that determines whether a given string is a palindrome.
19. Explain how memory is allocated and managed during recursive method calls.
20. Trace the execution of a recursive factorial method for the input value 5, showing
all recursive calls and returns.
21. Write a recursive program that finds the greatest common divisor (GCD) of two
integers using Euclid’s algorithm.
22. Explain the difference between direct recursion and indirect recursion with suitable
examples.
23. Write a recursive method that counts the number of digits in a positive integer.
25. Design a recursive solution for traversing all elements of a directory structure or
hierarchical tree.
304
Chapter 16
Searching Algorithms
16.1 Introduction
Searching is one of the most fundamental operations in computer programming. It in-
volves finding the location of a specific element within a collection of data such as an
array, list, or database.
In Java, searching algorithms are widely used in applications such as databases, file
systems, information retrieval systems, and software applications.
This chapter focuses on the two most common searching techniques:
• Linear Search
• Binary Search
• Time complexity
• Number of comparisons
• Memory usage
305
COS 201: Computer Programming I Lecture Notes
if (result != -1)
[Link]("Element found at index " + result);
else
[Link]("Element not found");
}
}
Output
306
COS 201: Computer Programming I Lecture Notes
if (arr[mid] == key)
return mid;
307
COS 201: Computer Programming I Lecture Notes
return -1;
}
Output
Result index: 3
public static int search(int[] arr, int left, int right, int key)
{
if (left > right)
return -1;
308
COS 201: Computer Programming I Lecture Notes
if (arr[mid] == key)
return mid;
309
COS 201: Computer Programming I Lecture Notes
16.9 Disadvantages
• Linear search is inefficient for large datasets
310
COS 201: Computer Programming I Lecture Notes
2. Describe the linear search algorithm in detail. Illustrate the step-by-step process of
how linear search locates a target element in an array using a suitable example.
3. Discuss the advantages and disadvantages of linear search. Under what circum-
stances is linear search preferred over other searching techniques?
4. Explain the binary search algorithm. Using a sorted array of integers, demonstrate
how binary search repeatedly divides the search space until the target element is
311
COS 201: Computer Programming I Lecture Notes
found.
5. What are the major advantages of binary search compared to linear search? Discuss
its efficiency, speed, and practical applications.
6. Compare and contrast linear search and binary search with respect to their working
principles, efficiency, memory requirements, and suitability for different types of
datasets.
7. Write a Java program that implements the linear search algorithm to find a specified
element in an array. Display an appropriate message indicating whether the element
is found or not.
8. Develop a Java program that implements the iterative version of binary search. Test
the program using different sets of sorted data and explain the output obtained.
9. Write a recursive binary search algorithm in Java. Explain how recursion is used
in the search process and identify the base case and recursive case in your solution.
10. Explain the concept of recursion in searching algorithms. Discuss the advantages
and disadvantages of recursive binary search when compared with its iterative coun-
terpart.
11. Determine and explain the time complexity of linear search in the best-case, average-
case, and worst-case scenarios. Give examples for each case.
12. Analyze the time complexity of binary search. Explain why binary search is con-
sidered one of the most efficient searching algorithms for sorted datasets.
13. What condition must be satisfied before binary search can be applied to a collection
of data? Explain why this requirement is essential for the algorithm to function
correctly.
14. What would happen if binary search were applied to an unsorted array? Use an
example to demonstrate the incorrect results that may occur.
15. Explain the role and significance of the middle element (mid) in binary search. How
does the comparison with the middle element help reduce the search space?
16. Discuss common programming errors that may occur when implementing searching
algorithms. Suggest methods for detecting and correcting these errors.
17. Why is binary search generally more efficient than linear search for large datasets?
Support your answer with examples and complexity analysis.
312
COS 201: Computer Programming I Lecture Notes
19. Give at least five real-world applications where searching algorithms are used. Ex-
plain how searching improves the efficiency of these applications.
Show the complete sequence of steps performed by binary search to locate the value
70.
Demonstrate how linear search would locate the value 63. Count the number of
comparisons performed.
22. Design and implement a Java program that searches for a student’s registration
number in an array of student records and displays the student’s details if found.
23. Write a program that allows a user to choose between linear search and binary
search for locating an element in an array. Compare the results and discuss the
performance of both methods.
24. Create a menu-driven Java application that stores employee records and provides
searching functionality using both linear and binary search techniques.
25. Assume a database contains one million sorted records. Discuss which searching
algorithm would be most suitable for locating a record and justify your answer with
appropriate complexity analysis.
26. Explain how searching algorithms are used in search engines, online shopping plat-
forms, library management systems, banking systems, and student information sys-
tems.
27. Investigate and discuss the limitations of binary search. Are there situations where
linear search may still be a better choice? Provide examples.
29. Design an algorithm and draw a flowchart for the binary search process.
313
COS 201: Computer Programming I Lecture Notes
30. Design an algorithm and draw a flowchart for a student record search system that
allows users to enter a student ID and retrieves the corresponding record from a
collection.
314
Chapter 17
Sorting Algorithms
17.1 Introduction
Sorting is the process of arranging data in a particular order, typically ascending or
descending. Sorting is one of the most important operations in computer science because
it improves the efficiency of searching and data processing.
Sorting algorithms are widely used in databases, operating systems, search engines,
and software applications that handle large amounts of data.
This chapter introduces basic sorting techniques including Bubble Sort, Selection Sort,
and Insertion Sort.
315
COS 201: Computer Programming I Lecture Notes
316
COS 201: Computer Programming I Lecture Notes
}
}
}
sort(data);
Output
1 2 4 5 8
317
COS 201: Computer Programming I Lecture Notes
sort(data);
Output
10 13 14 29 37
318
COS 201: Computer Programming I Lecture Notes
arr[j + 1] = key;
319
COS 201: Computer Programming I Lecture Notes
}
}
sort(data);
Output
5 6 11 12 13
320
COS 201: Computer Programming I Lecture Notes
17.10 Disadvantages
• Inefficient for large datasets (simple sorts)
• Search engines
• E-commerce platforms
• Data analytics
• Operating systems
321
COS 201: Computer Programming I Lecture Notes
2. Explain the concept of sorting data in ascending and descending order. Provide
suitable examples to illustrate both arrangements.
3. Describe the Bubble Sort algorithm in detail. Using a list of numbers, demonstrate
each pass of the algorithm until the list becomes fully sorted.
322
COS 201: Computer Programming I Lecture Notes
4. Explain the swapping process used in Bubble Sort. Why are adjacent elements
compared and exchanged during each iteration?
5. Write a Java program that implements the Bubble Sort algorithm to arrange a set
of integers in ascending order.
6. Discuss the advantages and disadvantages of Bubble Sort. In what situations might
Bubble Sort still be useful despite its inefficiency?
7. Explain the Selection Sort algorithm. Describe how the minimum element is iden-
tified and placed in its correct position during each pass.
show all the steps involved in sorting the data using Selection Sort.
9. Write a Java program that implements the Selection Sort algorithm and displays
the sorted output.
10. Explain why Selection Sort is considered inefficient for large datasets. Support your
explanation with complexity analysis.
11. Describe the Insertion Sort algorithm in detail. Explain how the sorted and unsorted
portions of the array are maintained during execution.
demonstrate the complete process of sorting the data using Insertion Sort.
13. Write a Java program that implements the Insertion Sort algorithm to sort an array
of integers.
14. Compare Bubble Sort, Selection Sort, and Insertion Sort with respect to their work-
ing principles, number of comparisons, number of swaps, and efficiency.
15. Discuss the advantages and disadvantages of Insertion Sort. Under what circum-
stances can Insertion Sort perform efficiently?
16. Explain the concept of time complexity in sorting algorithms. Why is time com-
plexity important when evaluating algorithm performance?
17. Determine the best-case, average-case, and worst-case time complexities of Bubble
Sort, Selection Sort, and Insertion Sort.
323
COS 201: Computer Programming I Lecture Notes
18. Why are simple sorting algorithms generally unsuitable for very large datasets?
Discuss the limitations associated with their performance.
19. Explain how sorting improves the efficiency of searching operations and data re-
trieval processes.
20. List and explain at least five advantages of sorting data in computer applications.
21. Discuss the role of sorting in database management systems, library systems, stu-
dent information systems, banking applications, and e-commerce platforms.
22. Give at least ten real-life applications where sorting algorithms are used. Explain
how sorting contributes to the effectiveness of each application.
23. What challenges might arise if large datasets are not sorted? Discuss the impact
on searching, reporting, and decision-making processes.
24. Explain the difference between stable and unstable sorting algorithms. Determine
whether Bubble Sort, Selection Sort, and Insertion Sort are stable or unstable.
25. Differentiate between internal sorting and external sorting. Give practical examples
of each.
26. Discuss common programming errors encountered when implementing sorting al-
gorithms and suggest methods for avoiding such errors.
27. Explain the concept of in-place sorting. Which of the sorting algorithms studied in
this chapter are considered in-place algorithms?
perform Bubble Sort manually and show the result after each pass.
perform Selection Sort manually and show the state of the array after each pass.
perform Insertion Sort manually and show the insertion process for each element.
31. Write a Java program that accepts a list of student names from the user and sorts
them alphabetically using any suitable sorting algorithm.
324
COS 201: Computer Programming I Lecture Notes
32. Develop a Java application that sorts examination scores in descending order and
displays the highest and lowest scores.
33. Design a menu-driven program that allows users to choose between Bubble Sort,
Selection Sort, and Insertion Sort for sorting a dataset.
34. Create a program that sorts employee records based on employee identification
numbers and displays the sorted records.
35. Design a student record management system that stores student information and
sorts the records according to registration numbers, names, or examination scores.
36. Compare the performance of Bubble Sort, Selection Sort, and Insertion Sort by
sorting datasets of different sizes. Present your observations and conclusions.
37. Draw a flowchart for the Bubble Sort algorithm and explain each stage of the
process.
38. Draw a flowchart for the Selection Sort algorithm and explain how the minimum
element is selected during each iteration.
39. Draw a flowchart for the Insertion Sort algorithm and explain how elements are
inserted into their correct positions.
40. Investigate modern sorting algorithms such as Merge Sort and Quick Sort. Explain
why they are generally preferred over Bubble Sort, Selection Sort, and Insertion
Sort for large datasets.
325
References
1. Deitel, P. J. & Deitel, H. M. (2017). Java: How to Program (Early Objects Version),
11th Edition. Pearson Education, Boston, USA.
4. Oracle Corporation (2024). The Java Tutorials and Java SE Documentation. Or-
acle, USA. Available at: [Link]
5. Sierra, K. & Bates, B. (2005). Head First Java, 2nd Edition. O’Reilly Media,
Sebastopol, USA.
7. Eckel, B. (2006). Thinking in Java, 4th Edition. Prentice Hall, Upper Saddle River,
USA.
8. Gosling, J., Joy, B., Steele, G., Bracha, G., Buckley, A. (2014). The Java Language
Specification, Java SE 8 Edition. Oracle Press, USA.
9. Sierra, K. & Bates, B. (2005). Head First Java. O’Reilly Media, USA.
11. Bloch, J. (2018). Effective Java, 3rd Edition. Addison-Wesley Professional, Boston,
USA.
12. Flanagan, D. (2005). Java in a Nutshell, 5th Edition. O’Reilly Media, Sebastopol,
USA.
326
Appendix A
2. Standard Deviation
3. Temperature Conversion
4. Simple Calculator
2. Binary Search
2. Selection Sort
3. Insertion Sort
2. Fibonacci Series
327