0% found this document useful (0 votes)
1 views329 pages

COS201 Programming

Uploaded by

enstaflow5
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views329 pages

COS201 Programming

Uploaded by

enstaflow5
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

NORTHWEST UNIVERSITY KANO

Faculty of Computing

Department of Computer Science

COS 201:
COMPUTER PROGRAMMING I

Lecture Notes

Prepared By

Aminu Abdulkadir Mahmoud


Umar Shafiu Haruna
Lawan Garba
Muktar Danlami
Zauwali Sabitu Paki
Usman Haruna

Academic Session 2025/2026


COS 201
Computer Programming I

Course Unit: 2 Credit Units

Level: 200

Semester: First Semester

Prepared By

Aminu Abdulkadir Mahmoud


Umar Shafiu Haruna
Lawan Garba
Muktar Danlami
Zauwali Sabitu Paki
Usman Haruna

Department of Computer Science


Northwest University Kano
The Authors

Contents

1 Introduction to Computer Programming 17


1.1 Meaning of Computer Programming . . . . . . . . . . . . . . . . . . . . . 17
1.2 Objectives of Programming . . . . . . . . . . . . . . . . . . . . . . . . . 18
1.3 Characteristics of a Good Program . . . . . . . . . . . . . . . . . . . . . 19
1.3.1 Correctness . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
1.3.2 Efficiency . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
1.3.3 Readability . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
1.3.4 Maintainability . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
1.3.5 Reliability . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
1.3.6 Reusability . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
1.3.7 Portability . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
1.3.8 Security . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
1.3.9 Scalability . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
1.3.10 Robustness . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
1.4 Chapter Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
1.5 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22

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.4.3 Example Concept (Prolog Style) . . . . . . . . . . . . . . . . . . . 32


2.4.4 Advantages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
2.4.5 Disadvantages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
2.5 Scripting Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
2.5.1 Characteristics . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
2.5.2 Common Uses of Scripting Languages . . . . . . . . . . . . . . . . 33
2.5.3 Examples of Scripting Languages . . . . . . . . . . . . . . . . . . 33
2.5.4 Advantages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
2.5.5 Disadvantages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
2.6 Procedural Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
2.6.1 Characteristics . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
2.6.2 Components of Procedural Programming . . . . . . . . . . . . . . 34
2.6.3 Examples of Procedural Languages . . . . . . . . . . . . . . . . . 35
2.6.4 Advantages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
2.6.5 Disadvantages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
2.7 Structured Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
2.7.1 Characteristics . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
2.7.2 Basic Control Structures . . . . . . . . . . . . . . . . . . . . . . . 36
2.7.3 Advantages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
2.7.4 Disadvantages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
2.8 Object-Oriented Programming . . . . . . . . . . . . . . . . . . . . . . . . 36
2.8.1 Characteristics . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
2.8.2 Core Principles of OOP . . . . . . . . . . . . . . . . . . . . . . . 37
2.8.3 Components of OOP . . . . . . . . . . . . . . . . . . . . . . . . . 37
2.8.4 Examples of Object-Oriented Languages . . . . . . . . . . . . . . 37
2.8.5 Advantages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
2.8.6 Disadvantages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
2.9 Chapter Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
2.10 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
2.11 Practical and Critical Thinking Exercises . . . . . . . . . . . . . . . . . . 42

3 Introduction to Java Programming 44


3.1 Overview of Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
3.2 Features of Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
3.3 Java Development Environment . . . . . . . . . . . . . . . . . . . . . . . 44
3.4 Basic Structure of a Java Program . . . . . . . . . . . . . . . . . . . . . 45
3.4.1 General Skeleton of a Java Program . . . . . . . . . . . . . . . . . 51
3.4.2 Complete Example . . . . . . . . . . . . . . . . . . . . . . . . . . 52
3.4.3 Visual Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . 53

2
COS 201: Computer Programming I Lecture Notes

3.5 Advantages of Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53


3.6 Disadvantages of Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
3.7 Chapter Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
3.8 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55

4 Variables and Data Types 57


4.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
4.2 Variables in Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
4.2.1 Declaration of Variables . . . . . . . . . . . . . . . . . . . . . . . 57
4.2.2 Initialization of Variables . . . . . . . . . . . . . . . . . . . . . . . 58
4.2.3 Assignment of Variables . . . . . . . . . . . . . . . . . . . . . . . 58
4.2.4 Rules for Naming Variables . . . . . . . . . . . . . . . . . . . . . 58
4.2.5 Variable Naming Conventions . . . . . . . . . . . . . . . . . . . . 58
4.3 Types of Variables in Java . . . . . . . . . . . . . . . . . . . . . . . . . . 59
4.3.1 Local Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
4.3.2 Instance Variables . . . . . . . . . . . . . . . . . . . . . . . . . . 59
4.3.3 Static Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
4.4 Data Types in Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
4.5 Primitive Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
4.5.1 Integer Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
4.5.2 Floating Point Types . . . . . . . . . . . . . . . . . . . . . . . . . 60
4.5.3 Character Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
4.5.4 Boolean Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
4.6 Non-Primitive Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . 61
4.7 Type Conversion in Java . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
4.7.1 Implicit Conversion (Widening) . . . . . . . . . . . . . . . . . . . 61
4.7.2 Explicit Conversion (Narrowing) . . . . . . . . . . . . . . . . . . . 62
4.8 Default Values of Data Types . . . . . . . . . . . . . . . . . . . . . . . . 62
4.9 Importance of Variables and Data Types . . . . . . . . . . . . . . . . . . 62
4.10 Chapter Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
4.11 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63

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

5.4.3 Reading Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65


5.4.4 Reading Boolean Values . . . . . . . . . . . . . . . . . . . . . . . 65
5.4.5 Reading Character Values . . . . . . . . . . . . . . . . . . . . . . 65
5.5 Example of Scanner Class Usage . . . . . . . . . . . . . . . . . . . . . . . 66
5.6 Common Methods of Scanner Class . . . . . . . . . . . . . . . . . . . . . 66
5.7 Important Notes When Using Scanner . . . . . . . . . . . . . . . . . . . 67
5.8 Common Input Problem (nextLine Issue) . . . . . . . . . . . . . . . . . . 67
5.9 Advantages of Scanner Class . . . . . . . . . . . . . . . . . . . . . . . . . 67
5.10 Limitations of Scanner Class . . . . . . . . . . . . . . . . . . . . . . . . . 67
5.11 Chapter Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
5.12 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68

6 Expressions and Operators 70


6.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
6.2 Expressions in Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
6.2.1 Types of Expressions . . . . . . . . . . . . . . . . . . . . . . . . . 70
6.3 Operators in Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
6.4 Arithmetic Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
6.5 Relational Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
6.6 Logical Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
6.7 Assignment Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
6.8 Unary Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
6.8.1 Unary Plus (+) . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
6.8.2 Unary Minus (-) . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
6.8.3 Increment Operator (++) . . . . . . . . . . . . . . . . . . . . . . 74
6.8.4 Decrement Operator (–) . . . . . . . . . . . . . . . . . . . . . . . 74
6.8.5 Logical NOT (!) Operator . . . . . . . . . . . . . . . . . . . . . . 75
6.9 Operator Precedence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
6.10 Operator Associativity . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
6.10.1 Types of Associativity . . . . . . . . . . . . . . . . . . . . . . . . 76
6.10.2 Importance of Associativity . . . . . . . . . . . . . . . . . . . . . 78
6.11 Type Conversion in Expressions . . . . . . . . . . . . . . . . . . . . . . . 78
6.11.1 Implicit Conversion . . . . . . . . . . . . . . . . . . . . . . . . . . 78
6.11.2 Explicit Conversion . . . . . . . . . . . . . . . . . . . . . . . . . . 78
6.12 Common Errors in Expressions . . . . . . . . . . . . . . . . . . . . . . . 78
6.13 Importance of Expressions and Operators . . . . . . . . . . . . . . . . . . 79
6.14 Chapter Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
6.15 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79

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

8.4 The if Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91


8.5 The if-else Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
8.6 The if-else-if Ladder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
8.7 Nested if Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
8.8 The switch Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
8.8.1 Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
8.8.2 Flowchart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
8.9 How switch Works . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
8.10 Switch with String Values . . . . . . . . . . . . . . . . . . . . . . . . . . 100
8.11 Iteration Control Structures . . . . . . . . . . . . . . . . . . . . . . . . . 101
8.12 The while Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
8.13 The do-while Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
8.14 Difference Between while and do-while . . . . . . . . . . . . . . . . . . . 104
8.15 The for Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
8.16 Nested Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
8.17 Enhanced for Loop (For-Each Loop) . . . . . . . . . . . . . . . . . . . . 108
8.17.1 Why Use the Enhanced for Loop? . . . . . . . . . . . . . . . . . . 108
8.17.2 How the Enhanced for Loop Works . . . . . . . . . . . . . . . . . 109
8.17.3 Using Enhanced for Loop with Collections . . . . . . . . . . . . . 111
8.17.4 Advantages of the Enhanced for Loop . . . . . . . . . . . . . . . . 111
8.17.5 Limitations of the Enhanced for Loop . . . . . . . . . . . . . . . . 111
8.17.6 Comparison: for Loop vs Enhanced for Loop . . . . . . . . . . . . 112
8.17.7 When to Use the Enhanced for Loop . . . . . . . . . . . . . . . . 112
8.18 Loop Control Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
8.18.1 The break Statement . . . . . . . . . . . . . . . . . . . . . . . . . 113
8.18.2 The continue Statement . . . . . . . . . . . . . . . . . . . . . . . 115
8.18.3 Difference Between break and continue . . . . . . . . . . . . . . . 117
8.18.4 Best Practices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
8.19 Infinite Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
8.19.1 Causes of Infinite Loops . . . . . . . . . . . . . . . . . . . . . . . 119
8.19.2 Breaking Out of an Infinite Loop . . . . . . . . . . . . . . . . . . 120
8.19.3 Applications of Infinite Loops . . . . . . . . . . . . . . . . . . . . 121
8.19.4 Advantages and Disadvantages . . . . . . . . . . . . . . . . . . . 121
8.19.5 Best Practices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
8.19.6 Finding the Sum of Numbers . . . . . . . . . . . . . . . . . . . . 122
8.19.7 Multiplication Table . . . . . . . . . . . . . . . . . . . . . . . . . 123
8.19.8 Even Numbers from 1 to 20 . . . . . . . . . . . . . . . . . . . . . 124
8.20 Common Programming Errors . . . . . . . . . . . . . . . . . . . . . . . . 126
8.20.1 Forgetting Braces in Nested Statements . . . . . . . . . . . . . . . 126

6
COS 201: Computer Programming I Lecture Notes

8.20.2 Using Assignment Operator (=) Instead of Comparison Operator


(==) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
8.20.3 Creating Infinite Loops Accidentally . . . . . . . . . . . . . . . . 127
8.20.4 Missing Break Statements in Switch Cases . . . . . . . . . . . . . 128
8.20.5 Incorrect Loop Conditions . . . . . . . . . . . . . . . . . . . . . . 128
8.20.6 Updating Loop Variables Improperly . . . . . . . . . . . . . . . . 129
8.20.7 Off-by-One Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
8.20.8 Summary of Common Errors . . . . . . . . . . . . . . . . . . . . . 130
8.21 Best Practices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
8.21.1 Use Meaningful Variable Names . . . . . . . . . . . . . . . . . . . 130
8.21.2 Keep Conditions Simple and Readable . . . . . . . . . . . . . . . 130
8.21.3 Avoid Deeply Nested Structures . . . . . . . . . . . . . . . . . . . 131
8.21.4 Always Test Boundary Conditions . . . . . . . . . . . . . . . . . . 131
8.21.5 Use Switch Statements for Multiple Fixed Choices . . . . . . . . . 131
8.21.6 Use For Loops When the Number of Iterations Is Known . . . . . 132
8.21.7 Use While Loops When the Number of Iterations Is Unknown . . 132
8.21.8 Properly Indent Code . . . . . . . . . . . . . . . . . . . . . . . . . 132
8.21.9 Comment Important Sections of Code . . . . . . . . . . . . . . . 132
8.21.10 Write Modular Programs . . . . . . . . . . . . . . . . . . . . . . . 133
8.21.11 Benefits of Following Best Practices . . . . . . . . . . . . . . . . . 133
8.22 Chapter Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
8.23 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135

9 Strings and Character Processing 144


9.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144
9.2 Characters in Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144
9.2.1 Declaring Character Variables . . . . . . . . . . . . . . . . . . . . 145
9.2.2 Displaying Characters . . . . . . . . . . . . . . . . . . . . . . . . 145
9.3 Unicode Representation . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
9.4 Escape Sequences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146
9.5 Introduction to Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146
9.5.1 Strings in Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
9.5.2 String Literals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
9.5.3 Characters Within a String . . . . . . . . . . . . . . . . . . . . . 148
9.5.4 Creating String Objects . . . . . . . . . . . . . . . . . . . . . . . 148
9.5.5 Why Strings Are Important . . . . . . . . . . . . . . . . . . . . . 149
9.5.6 Displaying Strings . . . . . . . . . . . . . . . . . . . . . . . . . . 149
9.5.7 Strings and User Interaction . . . . . . . . . . . . . . . . . . . . . 150
9.5.8 Characteristics of Strings . . . . . . . . . . . . . . . . . . . . . . . 150

7
COS 201: Computer Programming I Lecture Notes

9.6 Declaring and Initializing Strings . . . . . . . . . . . . . . . . . . . . . . 151


9.6.1 Method 1: String Literal . . . . . . . . . . . . . . . . . . . . . . . 151
9.6.2 Method 2: Using the new Keyword . . . . . . . . . . . . . . . . . 152
9.6.3 Comparison of the Two Methods . . . . . . . . . . . . . . . . . . 153
9.6.4 Declaring a String Without Initialization . . . . . . . . . . . . . . 153
9.6.5 Declaring Multiple Strings . . . . . . . . . . . . . . . . . . . . . . 154
9.6.6 Example Program . . . . . . . . . . . . . . . . . . . . . . . . . . . 154
9.6.7 Best Practices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
9.6.8 Key Points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
9.7 Displaying Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
9.7.1 Understanding [Link]() . . . . . . . . . . . . . . . 156
9.7.2 Displaying a String Literal Directly . . . . . . . . . . . . . . . . . 157
9.7.3 Displaying Multiple Strings . . . . . . . . . . . . . . . . . . . . . 157
9.7.4 Using print() Instead of println() . . . . . . . . . . . . . . . . 157
9.7.5 Displaying String Variables . . . . . . . . . . . . . . . . . . . . . 158
9.7.6 Combining Text and Variables . . . . . . . . . . . . . . . . . . . . 158
9.7.7 Displaying Several String Variables . . . . . . . . . . . . . . . . . 159
9.7.8 Displaying Formatted Information . . . . . . . . . . . . . . . . . . 159
9.7.9 Common Errors When Displaying Strings . . . . . . . . . . . . . 160
9.7.10 Best Practices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
9.7.11 Key Points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
9.8 String Immutability . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162
9.9 String Concatenation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162
9.10 Concatenating Strings and Variables . . . . . . . . . . . . . . . . . . . . 162
9.11 Common String Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
9.11.1 length() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
9.11.2 charAt() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164
9.11.3 toUpperCase() . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166
9.11.4 toLowerCase() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166
9.11.5 equals() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167
9.11.6 equalsIgnoreCase() . . . . . . . . . . . . . . . . . . . . . . . . . . 168
9.11.7 compareTo() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169
9.11.8 contains() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170
9.11.9 Summary of Common String Methods . . . . . . . . . . . . . . . 172
9.12 startsWith() and endsWith() . . . . . . . . . . . . . . . . . . . . . . . . . 172
9.12.1 The startsWith() Method . . . . . . . . . . . . . . . . . . . . . 172
9.12.2 The endsWith() Method . . . . . . . . . . . . . . . . . . . . . . . 175
9.12.3 Using Both Methods Together . . . . . . . . . . . . . . . . . . . . 177
9.12.4 Comparison of startsWith() and endsWith() . . . . . . . . . . . . 178

8
COS 201: Computer Programming I Lecture Notes

9.12.5 Common Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178


9.12.6 Key Points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
9.13 indexOf() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
9.13.1 Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
9.13.2 Example: Finding a Character . . . . . . . . . . . . . . . . . . . . 179
9.13.3 Example: Finding a Substring . . . . . . . . . . . . . . . . . . . . 180
9.13.4 When the Character Does Not Exist . . . . . . . . . . . . . . . . 180
9.13.5 Finding Spaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181
9.13.6 Applications of indexOf() . . . . . . . . . . . . . . . . . . . . . . 181
9.13.7 Important Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . 182
9.14 substring() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182
9.14.1 Why Use substring()? . . . . . . . . . . . . . . . . . . . . . . . . 182
9.14.2 Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182
9.14.3 Applications of substring() . . . . . . . . . . . . . . . . . . . . . . 184
9.14.4 Important Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
9.14.5 Comparison of indexOf() and substring() . . . . . . . . . . . . . . 185
9.14.6 Key Points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
9.15 replace() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186
9.15.1 Why Use replace()? . . . . . . . . . . . . . . . . . . . . . . . . . . 186
9.15.2 Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186
9.15.3 Example: Replacing a Word . . . . . . . . . . . . . . . . . . . . . 186
9.15.4 Example: Replacing Characters . . . . . . . . . . . . . . . . . . . 187
9.15.5 Example: Replacing Multiple Words . . . . . . . . . . . . . . . . 187
9.15.6 Example: Replacing Spaces . . . . . . . . . . . . . . . . . . . . . 188
9.15.7 Original String Remains Unchanged . . . . . . . . . . . . . . . . . 188
9.15.8 Applications of replace() . . . . . . . . . . . . . . . . . . . . . . . 188
9.15.9 Important Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
9.16 trim() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
9.16.1 Why Use trim()? . . . . . . . . . . . . . . . . . . . . . . . . . . . 190
9.16.2 Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190
9.16.3 Spaces Inside a String Are Not Removed . . . . . . . . . . . . . . 191
9.16.4 Original String Remains Unchanged . . . . . . . . . . . . . . . . . 191
9.16.5 Applications of trim() . . . . . . . . . . . . . . . . . . . . . . . . 192
9.16.6 Important Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . 192
9.16.7 Comparison of replace() and trim() . . . . . . . . . . . . . . . . . 192
9.16.8 Key Points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193
9.17 String Comparison . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193
9.17.1 References vs Contents . . . . . . . . . . . . . . . . . . . . . . . . 193
9.17.2 Incorrect Comparison Using == . . . . . . . . . . . . . . . . . . . 194

9
COS 201: Computer Programming I Lecture Notes

9.17.3 Memory Illustration . . . . . . . . . . . . . . . . . . . . . . . . . 194


9.17.4 Correct Comparison Using equals() . . . . . . . . . . . . . . . . . 195
9.17.5 Case Sensitivity . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195
9.17.6 Ignoring Letter Case . . . . . . . . . . . . . . . . . . . . . . . . . 196
9.17.7 Comparing User Input . . . . . . . . . . . . . . . . . . . . . . . . 197
9.17.8 Summary of Comparison Methods . . . . . . . . . . . . . . . . . . 197
9.17.9 Important Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . 197
9.17.10 Key Points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198
9.18 The Character Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198
9.18.1 Why Use the Character Class? . . . . . . . . . . . . . . . . . . . . 198
9.18.2 Creating Character Variables . . . . . . . . . . . . . . . . . . . . 199
9.18.3 Character vs String . . . . . . . . . . . . . . . . . . . . . . . . . . 199
9.18.4 Common Character Class Methods . . . . . . . . . . . . . . . . . 200
9.18.5 Advantages of the Character Class . . . . . . . . . . . . . . . . . 200
9.18.6 Applications of the Character Class . . . . . . . . . . . . . . . . . 200
9.18.7 Important Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
9.18.8 Key Points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
9.19 Character Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
9.19.1 isLetter() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202
9.19.2 isDigit() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203
9.20 isUpperCase() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204
9.21 isLowerCase() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205
9.22 toUpperCase() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206
9.23 toLowerCase() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207
9.24 Summary Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
9.25 Key Points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
9.26 Processing Individual Characters . . . . . . . . . . . . . . . . . . . . . . 209
9.26.1 Accessing Characters One at a Time . . . . . . . . . . . . . . . . 210
9.26.2 General Pattern for Character Processing . . . . . . . . . . . . . . 215
9.26.3 Applications of Character Processing . . . . . . . . . . . . . . . . 216
9.26.4 Important Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . 216
9.26.5 Summary Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217
9.26.6 Key Points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217
9.27 StringBuilder Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218
9.28 Common StringBuilder Methods . . . . . . . . . . . . . . . . . . . . . . . 219
9.29 Applications of String Processing . . . . . . . . . . . . . . . . . . . . . . 219
9.30 Common Programming Errors . . . . . . . . . . . . . . . . . . . . . . . . 220
9.31 Best Practices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220
9.32 Chapter Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220

10
COS 201: Computer Programming I Lecture Notes

9.33 Review Questions and Exercises . . . . . . . . . . . . . . . . . . . . . . . 222

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

10.27.2 Creation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236


10.28Initializing a Two-Dimensional Array . . . . . . . . . . . . . . . . . . . . 236
10.29Accessing Elements in a 2D Array . . . . . . . . . . . . . . . . . . . . . . 237
10.30Traversing a Two-Dimensional Array . . . . . . . . . . . . . . . . . . . . 237
10.31Jagged Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237
10.32Applications of Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238
10.33Review Questions and Exercises . . . . . . . . . . . . . . . . . . . . . . . 238
10.34Chapter Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242

11 Methods and Method Overloading 244


11.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 244
11.2 What is a Method? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 244
11.3 Advantages of Using Methods . . . . . . . . . . . . . . . . . . . . . . . . 245
11.4 Structure of a Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245
11.5 Components of a Method . . . . . . . . . . . . . . . . . . . . . . . . . . . 246
11.5.1 Access Modifier . . . . . . . . . . . . . . . . . . . . . . . . . . . . 246
11.5.2 Return Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 246
11.5.3 Method Name . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 247
11.5.4 Parameter List . . . . . . . . . . . . . . . . . . . . . . . . . . . . 247
11.5.5 Method Body . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 247
11.6 Defining and Calling Methods . . . . . . . . . . . . . . . . . . . . . . . . 247
11.6.1 Method Definition . . . . . . . . . . . . . . . . . . . . . . . . . . 247
11.6.2 Method Call . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 248
11.7 Methods with Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . 248
11.8 Methods Returning Values . . . . . . . . . . . . . . . . . . . . . . . . . . 249
11.9 The return Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249
11.10Void Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249
11.11Actual and Formal Parameters . . . . . . . . . . . . . . . . . . . . . . . . 250
11.11.1 Formal Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . 250
11.11.2 Actual Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . 250
11.12Parameter Passing in Java . . . . . . . . . . . . . . . . . . . . . . . . . . 250
11.13Local Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251
11.14Scope of Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251
11.15Method Call Stack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 252
11.16Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 252
11.17Factorial Using Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . 253
11.18Introduction to Method Overloading . . . . . . . . . . . . . . . . . . . . 253
11.18.1 Benefits of Method Overloading . . . . . . . . . . . . . . . . . . . 254
11.18.2 Important Rule . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255

12
COS 201: Computer Programming I Lecture Notes

11.19Why Use Method Overloading? . . . . . . . . . . . . . . . . . . . . . . . 255


11.20Rules for Method Overloading . . . . . . . . . . . . . . . . . . . . . . . . 256
11.20.1 Different Number of Parameters . . . . . . . . . . . . . . . . . . . 256
11.20.2 Different Data Types . . . . . . . . . . . . . . . . . . . . . . . . . 256
11.20.3 Different Parameter Order . . . . . . . . . . . . . . . . . . . . . . 257
11.21Invalid Method Overloading . . . . . . . . . . . . . . . . . . . . . . . . . 257
11.22Best Practices for Writing Methods . . . . . . . . . . . . . . . . . . . . . 259
11.23Common Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259
11.24Chapter Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259
11.25Review Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 260
11.26Programming Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . 260

12 Object-Oriented Programming Concepts 262


12.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262
12.2 Fundamental Principles of OOP . . . . . . . . . . . . . . . . . . . . . . . 262
12.3 Objects and Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263
12.3.1 Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263
12.3.2 Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263
12.4 Encapsulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263
12.4.1 Advantages of Encapsulation . . . . . . . . . . . . . . . . . . . . . 263
12.5 Abstraction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264
12.5.1 Advantages of Abstraction . . . . . . . . . . . . . . . . . . . . . . 264
12.6 Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 265
12.7 Polymorphism . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 265
12.8 Relationship Between OOP Concepts . . . . . . . . . . . . . . . . . . . . 266
12.9 Advantages of Object-Oriented Programming . . . . . . . . . . . . . . . . 266
12.10Disadvantages of Object-Oriented Programming . . . . . . . . . . . . . . 266
12.11Real-World Applications of OOP . . . . . . . . . . . . . . . . . . . . . . 267
12.12Common Programming Errors . . . . . . . . . . . . . . . . . . . . . . . . 267
12.13Best Practices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267
12.14Chapter Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 268
12.15Review Questions and Exercises . . . . . . . . . . . . . . . . . . . . . . . 269

13 Inheritance and Polymorphism 274


13.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274
13.2 Inheritance in Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274
13.3 Advantages of Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . 274
13.4 Types of Inheritance in Java . . . . . . . . . . . . . . . . . . . . . . . . . 275
13.5 Single Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275

13
COS 201: Computer Programming I Lecture Notes

13.6 Multilevel Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276


13.7 Hierarchical Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . 276
13.8 The super Keyword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277
13.9 Method Overriding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 278
13.9.1 Rules of Method Overriding . . . . . . . . . . . . . . . . . . . . . 278
13.10Dynamic Method Dispatch . . . . . . . . . . . . . . . . . . . . . . . . . . 278
13.11Polymorphism in Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279
13.12Compile-Time Polymorphism . . . . . . . . . . . . . . . . . . . . . . . . 279
13.13Runtime Polymorphism . . . . . . . . . . . . . . . . . . . . . . . . . . . . 280
13.14Difference Between Overloading and Overriding . . . . . . . . . . . . . . 280
13.15Abstract Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281
13.16Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281
13.17Multiple Inheritance Using Interfaces . . . . . . . . . . . . . . . . . . . . 281
13.18Applications of Inheritance and Polymorphism . . . . . . . . . . . . . . . 282
13.19Common Programming Errors . . . . . . . . . . . . . . . . . . . . . . . . 282
13.20Best Practices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283
13.21Chapter Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283
13.22Review Questions and Exercises . . . . . . . . . . . . . . . . . . . . . . . 284

14 Simple Input and Output 286


14.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 286
14.2 Standard Output in Java . . . . . . . . . . . . . . . . . . . . . . . . . . . 286
14.3 Formatted Output Using printf . . . . . . . . . . . . . . . . . . . . . . . 287
14.3.1 Format Specifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . 287
14.4 Standard Input in Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . 288
14.5 The Scanner Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 288
14.5.1 Importing Scanner . . . . . . . . . . . . . . . . . . . . . . . . . . 288
14.5.2 Creating a Scanner Object . . . . . . . . . . . . . . . . . . . . . . 288
14.6 Reading Different Data Types . . . . . . . . . . . . . . . . . . . . . . . . 288
14.7 Reading Multiple Inputs . . . . . . . . . . . . . . . . . . . . . . . . . . . 289
14.8 Common Issue: nextLine() Problem . . . . . . . . . . . . . . . . . . . . . 290
14.8.1 Solution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290
14.9 Reading Characters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290
14.10File Input and Output (Introduction) . . . . . . . . . . . . . . . . . . . . 291
14.11Best Practices for Input and Output . . . . . . . . . . . . . . . . . . . . 291
14.12Common Programming Errors . . . . . . . . . . . . . . . . . . . . . . . . 291
14.13Chapter Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 292
14.14Review Questions and Exercises . . . . . . . . . . . . . . . . . . . . . . . 293

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

16 Searching Algorithms 305


16.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305
16.2 Concept of Searching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305
16.3 Linear Search . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305
16.3.1 Algorithm Steps . . . . . . . . . . . . . . . . . . . . . . . . . . . . 306
16.3.2 Java Implementation . . . . . . . . . . . . . . . . . . . . . . . . . 306
16.3.3 Time Complexity . . . . . . . . . . . . . . . . . . . . . . . . . . . 307
16.4 Binary Search . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 307
16.4.1 Algorithm Steps . . . . . . . . . . . . . . . . . . . . . . . . . . . . 307
16.5 Iterative Binary Search . . . . . . . . . . . . . . . . . . . . . . . . . . . . 307
16.5.1 Time Complexity . . . . . . . . . . . . . . . . . . . . . . . . . . . 308
16.6 Recursive Binary Search . . . . . . . . . . . . . . . . . . . . . . . . . . . 308
16.7 Linear Search vs Binary Search . . . . . . . . . . . . . . . . . . . . . . . 309
16.8 Advantages of Searching Algorithms . . . . . . . . . . . . . . . . . . . . . 309
16.9 Disadvantages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310
16.10Applications of Searching Algorithms . . . . . . . . . . . . . . . . . . . . 310
16.11Common Programming Errors . . . . . . . . . . . . . . . . . . . . . . . . 310
16.12Best Practices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310

15
COS 201: Computer Programming I Lecture Notes

16.13Chapter Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311


16.14Review Questions and Exercises . . . . . . . . . . . . . . . . . . . . . . . 311

17 Sorting Algorithms 313


17.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313
17.2 Concept of Sorting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313
17.3 Importance of Sorting . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313
17.4 Types of Sorting Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . 314
17.5 Bubble Sort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 314
17.5.1 Algorithm Steps . . . . . . . . . . . . . . . . . . . . . . . . . . . . 314
17.5.2 Java Implementation . . . . . . . . . . . . . . . . . . . . . . . . . 314
17.5.3 Time Complexity . . . . . . . . . . . . . . . . . . . . . . . . . . . 315
17.6 Selection Sort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315
17.6.1 Algorithm Steps . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315
17.6.2 Java Implementation . . . . . . . . . . . . . . . . . . . . . . . . . 316
17.6.3 Time Complexity . . . . . . . . . . . . . . . . . . . . . . . . . . . 317
17.7 Insertion Sort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317
17.7.1 Algorithm Steps . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317
17.7.2 Java Implementation . . . . . . . . . . . . . . . . . . . . . . . . . 317
17.7.3 Time Complexity . . . . . . . . . . . . . . . . . . . . . . . . . . . 318
17.8 Comparison of Sorting Algorithms . . . . . . . . . . . . . . . . . . . . . . 318
17.9 Advantages of Sorting Algorithms . . . . . . . . . . . . . . . . . . . . . . 318
17.10Disadvantages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 319
17.11Applications of Sorting . . . . . . . . . . . . . . . . . . . . . . . . . . . . 319
17.12Common Programming Errors . . . . . . . . . . . . . . . . . . . . . . . . 319
17.13Best Practices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 319
17.14Chapter Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 320
17.15Review Questions and Exercises . . . . . . . . . . . . . . . . . . . . . . . 320

References 321

A Laboratory Practical Exercises 322


A.1 Basic Programming Exercises . . . . . . . . . . . . . . . . . . . . . . . . 322
A.2 Searching Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 322
A.3 Sorting Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 322
A.4 Recursion Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 322

16
Chapter 1

Introduction to Computer
Programming

1.1 Meaning of Computer Programming


Computer programming is the systematic process of designing, writing, testing, debug-
ging, documenting, and maintaining a set of instructions that direct a computer to per-
form specific tasks or solve particular problems. These instructions, known as a program,
are written using a programming language that serves as a medium of communication
between humans and computers. Through programming, a programmer translates a
problem-solving procedure or algorithm into a form that can be understood and exe-
cuted by a computer system.
Programming is one of the fundamental disciplines in Computer Science and Infor-
mation Technology because it provides the means through which software applications
are developed. Every software system, ranging from simple calculators and mobile appli-
cations to complex operating systems, databases, artificial intelligence systems, and web
applications, is created through programming. The primary goal of programming is to
develop efficient, reliable, and maintainable solutions to real-world problems.
Computer programming involves several stages, including problem analysis, algorithm
design, coding, compilation, testing, debugging, documentation, and maintenance. Dur-
ing problem analysis, the programmer studies and understands the requirements of the
problem to be solved. An algorithm is then developed as a step-by-step procedure for
solving the problem. The algorithm is translated into source code using an appropriate
programming language such as Java, Python, C++, or JavaScript. After coding, the
program is compiled or interpreted, tested for correctness, and debugged to eliminate
errors before deployment.
Programming enables computers to automate repetitive tasks, process large volumes
of data efficiently, control hardware devices, and provide intelligent solutions in various

17
COS 201: Computer Programming I Lecture Notes

fields such as education, healthcare, banking, agriculture, transportation, communication,


security, and scientific research. As technology continues to evolve, computer program-
ming remains a critical skill for developing innovative software solutions and advancing
technological progress.
Computer programming can be defined as the art and science of creating executable
instructions that enable a computer to perform desired operations accurately, efficiently,
and reliably.

1.2 Objectives of Programming


The primary objective of computer programming is to develop solutions that enable com-
puters to perform useful tasks efficiently, accurately, and reliably. Programming serves as
the foundation for software development and plays a vital role in automating processes,
managing information, and controlling computing systems. Through programming, orga-
nizations and individuals can solve complex problems, improve productivity, and create
innovative technological solutions. The major objectives of programming are discussed
below.

1. Solving Real-World Problems


One of the most important objectives of programming is to provide solutions to
practical problems encountered in everyday life. Programmers develop applications
and systems that address challenges in various fields such as education, health-
care, banking, agriculture, transportation, communication, and scientific research.
By translating problem requirements into executable instructions, programming en-
ables computers to perform tasks that would otherwise be difficult, time-consuming,
or impossible to accomplish manually.

2. Automation of Repetitive Tasks


Programming allows repetitive and routine activities to be automated, thereby
reducing human effort and minimizing errors. Tasks such as payroll processing,
inventory management, report generation, data entry, and transaction processing
can be performed automatically through computer programs. Automation improves
productivity, saves time, and enables organizations to focus on more strategic ac-
tivities.

3. Efficient Data Processing


Modern organizations generate and manage enormous amounts of data. Program-
ming provides mechanisms for collecting, storing, processing, analyzing, and pre-
senting data efficiently. Computer programs can perform complex calculations, sort

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 Characteristics of a Good Program


A good computer program is one that not only produces the correct output but also
exhibits qualities that make it efficient, reliable, easy to understand, and simple to main-
tain. The quality of a program is often evaluated based on certain desirable characteristics
that contribute to its effectiveness and long-term usability. These characteristics are im-
portant because software systems often undergo continuous modifications, updates, and
enhancements throughout their lifecycle. The major characteristics of a good program
are discussed below.

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.4 Chapter Summary


This chapter introduced the fundamental concept of computer programming as the pro-
cess of designing, writing, testing, debugging, documenting, and maintaining instructions
that enable computers to perform specific tasks. Programming serves as a communication
medium between humans and computers through programming languages and forms the
foundation of all software development activities.
The chapter explained that programming is essential for developing applications rang-
ing from simple utilities to complex systems such as operating systems, databases, ar-
tificial intelligence applications, and web-based solutions. It also highlighted the major
stages involved in program development, including problem analysis, algorithm design,
coding, compilation, testing, debugging, documentation, and maintenance.
The objectives of programming were discussed in detail. These objectives include
solving real-world problems, automating repetitive tasks, processing data efficiently, de-
veloping software applications, and controlling hardware devices. Programming enables
organizations and individuals to improve productivity, increase accuracy, reduce opera-
tional costs, and create innovative technological solutions across various sectors such as
education, healthcare, banking, agriculture, transportation, and scientific research.
The chapter further examined the characteristics of a good program. A quality pro-
gram should produce correct results, utilize resources efficiently, and remain easy to read
and understand. It should also be maintainable, allowing future modifications and en-
hancements without excessive effort. Other important characteristics include reliability,
reusability, portability, security, scalability, and robustness. These qualities ensure that
software systems remain effective, adaptable, secure, and useful throughout their lifecycle.
The chapter also established the foundation for the study of computer programming by
emphasizing its importance, objectives, and the essential qualities required for developing
professional and high-quality software systems.

1.5 Exercises
1. Define computer programming.

2. Explain the difference between a computer program and a programming language.

3. Describe the major stages involved in the program development process.

4. Why is programming considered a fundamental discipline in Computer Science?

5. Discuss the role of algorithms in computer programming.

6. Explain how programming contributes to solving real-world problems.

22
COS 201: Computer Programming I Lecture Notes

7. Describe five applications of computer programming in modern society.

8. Explain the importance of automation in programming.

9. How does programming facilitate efficient data processing?

10. Differentiate between software development and hardware control as objectives of


programming.

11. List and explain the major objectives of programming.

12. Why is programming important in the development of Internet of Things (IoT)


systems?

13. Define a good computer program.

14. Explain the concept of program correctness.

15. Why is correctness considered the most important characteristic of a program?

16. Define program efficiency and discuss its significance.

17. Explain how algorithm selection affects program efficiency.

18. What is readability in programming? Why is it important?

19. State three techniques that improve the readability of a program.

20. Define maintainability and explain its benefits.

21. Discuss the importance of reliability in critical software systems.

22. Explain the concept of code reusability and its advantages.

23. What is portability? Give examples of portable software.

24. Explain the importance of security in software development.

25. Differentiate between authentication and authorization.

26. Define scalability and discuss why it is important in modern applications.

27. Explain the concept of robustness in programming.

28. Compare reliability and robustness.

29. Discuss how maintainability contributes to software longevity.

30. Explain why reusable code reduces software development costs.

23
COS 201: Computer Programming I Lecture Notes

31. Describe the relationship between readability and maintainability.

32. Why is portability important for organizations using multiple computing platforms?

33. Explain the role of security in protecting sensitive information.

34. Discuss the consequences of poor software scalability.

35. How can programmers improve the robustness of a software system?

36. Give practical examples of software systems where reliability is critical.

37. Explain how programming is used in healthcare applications.

38. Describe the role of programming in banking and financial systems.

39. Discuss the use of programming in industrial automation.

40. Explain how programming supports scientific research and innovation.

Practical and Critical Thinking Exercises


1. Identify a real-world problem in your school or community and explain how a com-
puter program could be developed to solve it.

2. Consider an online banking system. Discuss the characteristics of a good program


that are most important for such a system and justify your answer.

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.

7. Describe how automation through programming can improve efficiency in a univer-


sity registration system.

8. Suggest security measures that should be implemented in an online examination


system.

9. Discuss how programming contributes to technological advancement in developing


countries.

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

Each of these paradigms has distinct characteristics, advantages, and applications.


In this chapter, we shall examine the fundamental concepts, features, advantages, and
practical applications of the major programming paradigms used in modern software
development.

2.2 Functional Programming


Functional programming is a programming paradigm that treats computation as the
evaluation of mathematical functions. It is based on the idea that programs should
be constructed by composing and applying functions rather than by using sequences of
commands that modify program state. In functional programming, functions are used as
the primary building blocks of software, and emphasis is placed on producing predictable
and reliable outcomes.
Unlike procedural programming, where programs are organized around a sequence
of instructions that manipulate variables, functional programming focuses on describing
what should be computed rather than how the computation should be performed. This
approach minimizes side effects, reduces complexity, and promotes the development of
programs that are easier to understand, test, and maintain.
Functional programming originated from mathematical concepts, particularly lambda
calculus, and has influenced many modern programming languages. Languages such as
Haskell, Lisp, Scala, F#, and Erlang are primarily functional programming languages,
while languages such as Java, Python, JavaScript, and C++ have incorporated functional
programming features.

2.2.1 Characteristics of Functional Programming


Functional programming possesses several distinctive characteristics that differentiate it
from other programming paradigms.

27
COS 201: Computer Programming I Lecture Notes

Functions are First-Class Citizens

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.

Avoids Changing Data

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.

Uses Recursion Instead of Loops

Recursion is commonly used in functional programming to perform repetitive operations.


A recursive function repeatedly calls itself until a specified termination condition is met.
Since many functional languages minimize or eliminate traditional looping constructs
such as for and while loops, recursion becomes the primary mechanism for iteration.

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.

2.2.2 Advantages of Functional Programming


Functional programming offers several benefits that make it attractive for software de-
velopment, particularly in applications involving complex computations and concurrent

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.

• Better Parallel Processing


Since immutable data cannot be modified by multiple processes simultaneously,
functional programs are naturally suited for concurrent and parallel execution. This
characteristic reduces synchronization issues and improves performance on multi-
core systems.

• Improved Code Reusability


Functions can be reused in different parts of a program without modification, re-
ducing duplication and improving software quality.

• Enhanced Maintainability
Programs written using functional principles are often shorter, clearer, and easier
to maintain because they emphasize modularity and abstraction.

• Reduced Side Effects


The avoidance of mutable data and reliance on pure functions reduce unintended
interactions between program components, leading to more reliable software sys-
tems.

2.2.3 Applications of Functional Programming


Functional programming is widely used in areas that require reliability, scalability, and
efficient processing of large amounts of data. Common application areas include:

• Artificial Intelligence Systems

• Data Science and Analytics

• Financial Applications

29
COS 201: Computer Programming I Lecture Notes

• Distributed Systems

• Concurrent and Parallel Computing

• Compiler Design

• Machine Learning Applications

Functional programming is a paradigm that focuses on computation through the eval-


uation of functions while emphasizing immutability, recursion, pure functions, and the
avoidance of side effects. Its characteristics make programs more predictable, main-
tainable, and suitable for modern computing environments that require concurrency and
scalability. As a result, functional programming continues to play a significant role in con-
temporary software development and influences many modern programming languages.

2.3 Declarative Programming


Declarative programming is a programming paradigm in which the programmer describes
what the program should accomplish, rather than explicitly specifying how to achieve it.
Instead of writing step-by-step instructions, the focus is on expressing logic, relationships,
and constraints.
In declarative programming, the underlying execution system (such as a compiler,
interpreter, or query engine) determines the most efficient way to perform the computa-
tion. This contrasts with imperative programming, where the programmer controls the
flow of execution in detail.

2.3.1 Characteristics
• Emphasizes what needs to be done, not how.

• Reduces side effects and promotes predictability.

• Relies on expressions rather than statements.

• Often uses higher-level abstractions.

2.3.2 Types of Declarative Programming


• Functional Programming: Computation is based on mathematical functions and
avoids changing state.

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

• Improved code readability and maintainability.

• Reduced complexity in program design.

• Better suitability for parallel and distributed execution.

2.3.4 Disadvantages
• Less control over low-level system operations.

• Performance may be harder to optimize manually.

• Can have a steep learning curve for beginners.

Declarative programming is widely used in modern software development, especially


in domains such as web development, artificial intelligence, and data querying systems.

2.4 Logic Programming


Logic programming is a programming paradigm based on formal logic, where program
statements are expressed as logical facts and rules. Instead of specifying a sequence of
instructions, the programmer defines a set of relationships, and the system uses logical
inference to derive conclusions.
In logic programming, computation is performed by applying rules of deduction to a
knowledge base of facts. The system attempts to satisfy queries by searching for logical
proofs that match the given conditions.

2.4.1 Characteristics
• Programs are written as facts, rules, and queries.

• Execution is based on formal logic inference.

• Uses pattern matching and backtracking to find solutions.

• Focuses on what is true rather than how to compute.

31
COS 201: Computer Programming I Lecture Notes

2.4.2 Components of Logic Programming


• Facts: Basic assertions about objects or relationships.

• Rules: Logical implications that define relationships between facts.

• Queries: Questions posed to the system to retrieve information.

2.4.3 Example Concept (Prolog Style)


A simple logic system may define relationships such as:

• parent(john, mary).

• parent(mary, james).

• grandparent(X, Y) :- parent(X, Z), parent(Z, Y).

A query such as grandparent(john, james). would be evaluated using inference


rules.

2.4.4 Advantages
• High level of abstraction and simplicity.

• Useful for solving problems involving relationships and rules.

• Well-suited for artificial intelligence and expert systems.

• Supports automatic reasoning and inference.

2.4.5 Disadvantages
• Can be inefficient for large-scale computations.

• Difficult to debug compared to imperative languages.

• Limited practical use outside specialized domains.

Logic programming is commonly used in artificial intelligence, natural language pro-


cessing, and knowledge-based systems, where reasoning over facts and relationships is
essential.

32
COS 201: Computer Programming I Lecture Notes

2.5 Scripting Programming


Scripting programming refers to a programming paradigm in which programs are written
as scripts that are interpreted at runtime rather than compiled beforehand. Scripting lan-
guages are typically used to automate tasks, control software environments, and enhance
the functionality of existing applications.
Scripting programs are usually shorter and more flexible compared to traditional
programming languages, making them ideal for rapid development and quick prototyping.

2.5.1 Characteristics
• Code is usually interpreted rather than compiled.

• Designed for automation and rapid development.

• Often integrated with other software systems.

• Supports high-level operations with minimal syntax complexity.

2.5.2 Common Uses of Scripting Languages


• Web development (client-side and server-side scripting).

• System administration and automation tasks.

• Game development for event handling and logic control.

• Data processing and text manipulation.

2.5.3 Examples of Scripting Languages


• JavaScript (web browser scripting).

• Python (automation, data processing, and general-purpose scripting).

• PHP (server-side web scripting).

• Bash (Unix/Linux shell scripting).

2.5.4 Advantages
• Easy to learn and use.

• Fast development and execution for small tasks.

• Highly flexible and adaptable.

33
COS 201: Computer Programming I Lecture Notes

• Strong integration with other systems and tools.

2.5.5 Disadvantages
• Generally slower execution compared to compiled languages.

• Less suitable for large-scale system development.

• Limited low-level hardware control.

Scripting programming plays a crucial role in modern computing by enabling automa-


tion, enhancing web interactivity, and simplifying complex system operations.

2.6 Procedural Programming


Procedural programming is a programming paradigm that organizes code into procedures
or routines (also known as functions or subroutines). It is based on a step-by-step execu-
tion model where a program is structured as a sequence of instructions that manipulate
data.
In procedural programming, the program is divided into reusable blocks of code, and
each block performs a specific task. Data is typically shared globally or passed between
procedures.

2.6.1 Characteristics
• Based on a top-down design approach.

• Uses procedures/functions to structure code.

• Emphasizes step-by-step execution of instructions.

• Data and functions are often separate entities.

2.6.2 Components of Procedural Programming


• Procedures/Functions: Blocks of code that perform specific tasks.

• Variables: Used to store data values.

• Control Structures: Such as loops and conditionals for flow control.

34
COS 201: Computer Programming I Lecture Notes

2.6.3 Examples of Procedural Languages


• C

• Pascal

• Fortran

• BASIC

2.6.4 Advantages
• Easy to understand and implement for small programs.

• Code reusability through functions.

• Simple program flow and structure.

• Efficient use of system resources.

2.6.5 Disadvantages
• Difficult to manage large and complex programs.

• Lack of strong data security (global data can be modified).

• Poor scalability compared to modern paradigms.

• Limited support for real-world modeling.

Procedural programming forms the foundation of many early programming languages


and continues to influence modern software development practices.

2.7 Structured Programming


Structured programming is a programming paradigm that emphasizes the use of clear,
logical, and hierarchical program structures. It aims to improve the clarity, quality,
and development time of software by using well-defined control structures instead of
unstructured jumps such as the goto statement.
In structured programming, a program is divided into small, manageable blocks of
code, making it easier to read, debug, and maintain.

35
COS 201: Computer Programming I Lecture Notes

2.7.1 Characteristics
• Emphasizes a clear and logical program structure.

• Uses control structures such as sequence, selection, and iteration.

• Avoids or minimizes the use of goto statements.

• Encourages modular design through functions or procedures.

2.7.2 Basic Control Structures


• Sequence: Execution of statements in a linear order.

• Selection: Decision-making using constructs such as if, if-else, and switch.

• Iteration: Repetition of statements using loops such as for, while, and do-while.

2.7.3 Advantages
• Improves code readability and understanding.

• Makes debugging and testing easier.

• Enhances program reliability and maintainability.

• Reduces complexity in program design.

2.7.4 Disadvantages
• Can become less efficient for very complex systems.

• May lead to repetitive code without proper abstraction.

• Limited flexibility compared to more advanced paradigms like OOP.

Structured programming forms the foundation of modern programming practices and


strongly influences procedural and object-oriented programming paradigms.

2.8 Object-Oriented Programming


Object-Oriented Programming (OOP) is a programming paradigm based on the concept
of objects, which represent real-world entities. These objects contain both data (at-
tributes or properties) and methods (functions or behaviors) that operate on the data.
OOP is designed to improve software modularity, reusability, and maintainability by
structuring programs around objects rather than procedures or functions alone.

36
COS 201: Computer Programming I Lecture Notes

2.8.1 Characteristics
• Programs are organized around objects.

• Combines data and behavior within a single unit.

• Supports modular and reusable code design.

• Models real-world entities effectively.

2.8.2 Core Principles of OOP


• Encapsulation: Wrapping data and methods into a single unit (class) and re-
stricting direct access to some components.

• Abstraction: Hiding internal implementation details and showing only essential


features.

• Inheritance: Allowing a new class to acquire properties and behaviors of an ex-


isting class.

• Polymorphism: Allowing entities to take multiple forms, enabling method over-


riding and overloading.

2.8.3 Components of OOP


• Class: A blueprint for creating objects.

• Object: An instance of a class.

• Method: A function defined within a class.

• Attribute: A property or data field of a class.

2.8.4 Examples of Object-Oriented Languages


• Java

• C++

• Python

• C#

37
COS 201: Computer Programming I Lecture Notes

2.8.5 Advantages
• Improved code reusability through inheritance.

• Easier maintenance and modification.

• Better organization of complex software systems.

• Strong modeling of real-world systems.

2.8.6 Disadvantages
• Can be complex for beginners.

• Requires more memory and processing overhead.

• Overuse of abstraction may complicate design.

• Not always suitable for small or simple programs.

Object-Oriented Programming is widely used in modern software development due to


its flexibility, scalability, and ability to model complex systems effectively.

2.9 Chapter Summary


This chapter introduced programming paradigms as fundamental approaches and method-
ologies used in designing and developing software systems. A programming paradigm pro-
vides a framework that guides programmers in structuring programs, representing data,
and performing computations. Understanding programming paradigms enables develop-
ers to select appropriate techniques for solving different types of computational problems
and producing efficient, maintainable, and reliable software.
The chapter examined several major programming paradigms used in modern soft-
ware development. Functional programming was presented as a paradigm that treats
computation as the evaluation of mathematical functions. It emphasizes pure functions,
immutability, recursion, higher-order functions, and the avoidance of side effects. These
characteristics make functional programs easier to test, maintain, and execute in parallel
environments.
Declarative programming was discussed as an approach that focuses on describing
what a program should accomplish rather than specifying how the computation should
be performed. The paradigm emphasizes high-level abstractions, reduced complexity, and
improved readability. Functional programming, logic programming, and database query
languages such as SQL were identified as important forms of declarative programming.

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.

2. Explain the importance of programming paradigms in software development.

3. Differentiate between a programming language and a programming paradigm.

4. List the major programming paradigms discussed in this chapter.

39
COS 201: Computer Programming I Lecture Notes

5. Explain why modern programming languages often support multiple programming


paradigms.

6. Define functional programming.

7. Describe the role of mathematical functions in functional programming.

8. What is meant by the statement that functions are first-class citizens?

9. Explain the concept of immutability in functional programming.

10. Why does functional programming discourage changing data after creation?

11. Define a pure function and give an example.

12. Explain the concept of higher-order functions.

13. Why is recursion commonly used in functional programming?

14. Discuss four advantages of functional programming.

15. Identify five application areas where functional programming is commonly used.

16. Define declarative programming.

17. Differentiate between declarative programming and imperative programming.

18. Explain the major characteristics of declarative programming.

19. State three types of declarative programming.

20. Explain how SQL demonstrates the principles of declarative programming.

21. Discuss the advantages and disadvantages of declarative programming.

22. Define logic programming.

23. Explain the concepts of facts, rules, and queries in logic programming.

24. Describe the role of inference in logic programming.

25. Explain the purpose of pattern matching and backtracking.

26. Discuss the advantages of logic programming.

27. Identify application areas where logic programming is commonly used.

28. Define scripting programming.

29. Differentiate between scripting languages and compiled programming languages.

40
COS 201: Computer Programming I Lecture Notes

30. State four characteristics of scripting programming.

31. Explain the role of scripting languages in web development.

32. List four examples of scripting languages.

33. Discuss the advantages and disadvantages of scripting programming.

34. Define procedural programming.

35. Explain the top-down design approach used in procedural programming.

36. Describe the components of procedural programming.

37. Differentiate between procedures and functions.

38. List four examples of procedural programming languages.

39. Discuss the advantages of procedural programming.

40. Explain the limitations of procedural programming for large software systems.

41. Define structured programming.

42. Explain the objectives of structured programming.

43. Describe the three basic control structures used in structured programming.

44. Explain the difference between sequence, selection, and iteration.

45. Why is the use of goto statements discouraged in structured programming?

46. Discuss the advantages and disadvantages of structured programming.

47. Define Object-Oriented Programming (OOP).

48. Explain the concept of an object in OOP.

49. Differentiate between a class and an object.

50. Define the term attribute.

51. Define the term method.

52. Explain the principle of encapsulation.

53. Explain the principle of abstraction.

54. Explain the principle of inheritance.

41
COS 201: Computer Programming I Lecture Notes

55. Explain the principle of polymorphism.

56. Discuss the advantages of Object-Oriented Programming.

57. Explain the limitations of Object-Oriented Programming.

58. List four programming languages that support OOP.

59. Compare procedural programming and object-oriented programming.

60. Compare functional programming and procedural programming.

61. Compare declarative programming and procedural programming.

62. Compare scripting programming and procedural programming.

63. Discuss the similarities and differences between structured programming and pro-
cedural programming.

64. Explain why OOP is suitable for modeling real-world systems.

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.

2.11 Practical and Critical Thinking Exercises


1. Research a modern programming language such as Python, Java, or JavaScript and
identify the programming paradigms it supports.

2. Compare procedural programming and object-oriented programming by designing


a simple student management system using both approaches.

3. Write a short report explaining why functional programming has become increas-
ingly important in multicore computing environments.

4. Investigate how SQL demonstrates declarative programming principles and provide


practical query examples.

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.

7. Identify a real-world application and discuss which programming paradigm would


be most suitable for its development.

8. Analyze the advantages and disadvantages of using Object-Oriented Programming


in the development of a university management system.

9. Research the use of functional programming in machine learning frameworks and


summarize your findings.

10. Compare the suitability of scripting languages and compiled languages for web
application development.

11. Explain how structured programming improves software reliability compared to


unstructured programming.

12. Create a table comparing Functional, Declarative, Logic, Scripting, Procedural,


Structured, and Object-Oriented Programming based on characteristics, advan-
tages, disadvantages, and application areas.

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

Introduction to Java Programming

Java is a high-level, object-oriented programming language developed by Sun Microsys-


tems (now owned by Oracle). It is designed to be platform-independent, meaning that
Java programs can run on any device that supports the Java Virtual Machine (JVM).

3.1 Overview of Java


Java is widely used for building web applications, mobile applications, desktop software,
and enterprise systems. Its philosophy of "Write Once, Run Anywhere" makes it one of
the most popular programming languages in the world.

3.2 Features of Java


• Platform Independent: Java code is compiled into bytecode that runs on any
JVM.

• Object-Oriented: Everything in Java is based on objects and classes.

• Secure: Provides a secure runtime environment with built-in security features.

• Robust: Strong memory management and exception handling.

• Multithreaded: Supports concurrent execution of multiple threads.

• Portable: Java programs can be moved easily across systems.

3.3 Java Development Environment


Java programming involves three main components:

44
COS 201: Computer Programming I Lecture Notes

• JDK (Java Development Kit): A software development kit used to develop


Java applications.

• JRE (Java Runtime Environment): Provides libraries and components to run


Java programs.

• JVM (Java Virtual Machine): Executes Java bytecode and enables platform
independence.

3.4 Basic Structure of a Java Program


A Java program is composed of several fundamental components that work together
to create a complete and functional application. Understanding these components is
essential for writing, reading, and maintaining Java programs effectively. The major
components of a Java program include:

1. Package Statement (optional)

2. Import Statements (optional)

3. Class Definition

4. Main Method

5. User-Defined Methods

1. Package Statement (Optional)

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

Purpose of Packages Packages serve several important purposes:

• Organize related classes and interfaces together.

• Prevent naming conflicts among classes.

• Improve code maintainability and readability.

• Facilitate access control and security.

• Support modular software development.

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]

This organization improves software structure and development efficiency.

2. Import Statements (Optional)

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]);

Using an import statement simplifies the code:


import [Link];

Scanner input = new Scanner([Link]);

Commonly Imported Packages

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

Advantages of Import Statements

• Reduce code complexity.

• Improve readability.

• Provide access to Java library classes.

• Promote code reuse.

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

public class Student {

Purpose of a Class A class defines:

• Attributes (variables or data members)

• Methods (behaviors or actions)

• Constructors (object initialization)

• Relationships with other classes

Example with Attributes and Methods


public class Student {

String name;
int age;

public void displayInfo() {


[Link](name);
[Link](age);
}
}

Importance of Classes Classes promote:

• 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");
}

Explanation of the Keywords

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

Role of the Main Method The main method is responsible for:

• Starting program execution.

• Creating objects.

• Calling methods.

• Coordinating application activities.

• Processing command-line inputs.

Example
public class Demo {

public static void main(String[] args) {

[Link]("Program Started");

49
COS 201: Computer Programming I Lecture Notes

displayMessage();
}

public static void displayMessage() {


[Link]("Hello World");
}
}

5. User-Defined Methods

A method is a named block of code designed to perform a specific task. User-defined


methods are methods created by programmers to provide reusable functionality within a
program.
Methods help break large programs into smaller, manageable units.
Syntax
accessModifier returnType methodName(parameters) {

// statements

Example
public void displayGreeting() {

[Link]("Welcome");
}

Advantages of User-Defined Methods

• Promote code reuse.

• Reduce duplication.

• Improve readability.

• Simplify testing and debugging.

• Enhance maintainability.

50
COS 201: Computer Programming I Lecture Notes

Types of User-Defined Methods Methods can be classified according to whether


they accept parameters and/or return values.

Method Type Description


No parameters, no return value Performs a task only
Parameters, no return value Receives input and performs a task
No parameters, returns value Produces a result
Parameters and returns value Receives input and returns output

Example
public int addNumbers(int a, int b) {

return a + b;
}

Calling a Method A method executes only when it is called.


int result = addNumbers(5, 3);
[Link](result);

Importance of User-Defined Methods Large software systems may contain hun-


dreds or thousands of methods. By dividing functionality into methods, programmers
can develop modular, reusable, and maintainable software. Methods are therefore one of
the most important tools for managing complexity in software development.

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.

3.4.1 General Skeleton of a Java Program

package packageName; // Optional

import [Link]; // Optional


import packageName.*; // Optional

public class ClassName {

// Instance variables or class variables

51
COS 201: Computer Programming I Lecture Notes

// Constructor(s)

public static void main(String[] args) {

// Statements to execute when program starts

// Other methods

public void methodName() {

// Method body

3.4.2 Complete Example

package [Link];

import [Link];

public class StudentRecord {

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

3.4.3 Visual Structure

Package Statement (Optional)


Import Statements (Optional)

Class Definition

Variables / Data Members


Constructor(s)
main() Method
Other Methods

Figure 3.1: General Structure of a Java Program

3.5 Advantages of Java


• Easy to learn and widely supported.

• Strong community and rich libraries.

• Platform independence.

• High performance with Just-In-Time (JIT) compiler.

3.6 Disadvantages of Java


• Slower than some compiled languages like C++.

• Requires more memory.

• Verbose syntax compared to modern languages.

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.

3.7 Chapter Summary


This chapter introduced the fundamentals of Java programming, a high-level, object-
oriented, and platform-independent programming language developed by Sun Microsys-
tems and now maintained by Oracle. Java is widely used in developing web applications,
mobile applications, desktop software, and enterprise systems due to its portability and
the philosophy of "Write Once, Run Anywhere".
The chapter began by discussing the major features of Java, including platform inde-
pendence, object-oriented programming principles, security, robustness, multithreading,
and portability. These features make Java a powerful and widely adopted programming
language.
The Java development environment was also explained, highlighting the roles of the
Java Development Kit (JDK), Java Runtime Environment (JRE), and Java Virtual Ma-
chine (JVM). These components work together to enable the development, execution,
and platform independence of Java programs.
Furthermore, the basic structure of a Java program was discussed in detail. A Java
program consists of five main components: package statements, import statements, class
definitions, the main method, and user-defined methods. Each of these components plays
a crucial role in organizing, executing, and structuring Java programs efficiently.
The chapter also explained the importance of packages in organizing related classes,
import statements for accessing external libraries, and classes as blueprints for objects.
The main method was identified as the entry point of every Java application, while user-
defined methods were introduced as reusable blocks of code that enhance modularity and
reduce redundancy.
A general skeleton of a Java program was presented to show how all components
fit together in a typical Java application. Finally, the advantages and disadvantages of
Java were discussed, emphasizing its portability, strong community support, and perfor-
mance benefits, as well as its verbosity and higher memory usage compared to some other
languages.
Overall, Java provides a strong foundation for modern software development, combin-
ing object-oriented principles with platform independence and robust system architecture.

54
COS 201: Computer Programming I Lecture Notes

3.8 Exercises

A. Objective Questions
1. Java is originally developed by which company?

2. What is the main philosophy of Java?

3. What does JVM stand for?

4. Which component of Java executes bytecode?

5. What is the entry point of every Java program?

6. Which keyword is used to define a class in Java?

7. What is the purpose of the import statement?

8. Which package contains the Scanner class?

9. What does the keyword static mean in the main method?

10. List two advantages of Java.

B. Short Answer Questions


1. Explain the concept of platform independence in Java.

2. Differentiate between JDK, JRE, and JVM.

3. Describe the structure of a Java program.

4. What is a package in Java and why is it used?

5. Explain the importance of the main method.

6. What are user-defined methods?

7. State five features of Java.

8. Explain the role of import statements in Java programming.

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.

3. Write a program that demonstrates the use of a user-defined method to multiply


two numbers.

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

Variables and Data Types

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.

4.2 Variables in Java


A variable is a named memory location used to store data that can change during
program execution. It can be thought of as a container that holds a value.

4.2.1 Declaration of Variables


A variable must be declared before it is used.
Syntax:
dataType variableName;

Example:
int age;
double salary;
char grade;

57
COS 201: Computer Programming I Lecture Notes

4.2.2 Initialization of Variables


A variable can be assigned a value at the time of declaration or later in the program.
Example:
int age = 20;
double salary = 45000.50;
char grade = ’A’;

4.2.3 Assignment of Variables


Variables can be updated using the assignment operator (=).
int age = 20;
age = 25;

Here, the value of age changes from 20 to 25.

4.2.4 Rules for Naming Variables


A valid variable name must be a valid identifier. An Identifier is a name given to pro-
gramming elements. Java has strict rules for Identifiers:

• Must begin with a letter, underscore, or dollar sign.

• Cannot start with a number.

• Cannot contain spaces.

• Cannot use reserved keywords.

• Java is case-sensitive.

4.2.5 Variable Naming Conventions


Although not enforced by the compiler, conventions improve readability:

• Use camelCase for variables (e.g., studentAge).

• Use meaningful names (e.g., totalMarks instead of tm).

• Avoid single-letter variables except in loops.

58
COS 201: Computer Programming I Lecture Notes

4.3 Types of Variables in Java


Java supports three main types of variables:

1. Local Variables

2. Instance Variables

3. Static Variables

4.3.1 Local Variables


Local variables are declared inside a method, constructor, or block. They are accessible
only within that block.
Example:
public void display() {
int age = 20; // local variable
[Link](age);
}

4.3.2 Instance Variables


Instance variables are declared inside a class but outside methods. Each object of the
class has its own copy.
Example:
public class Student {
String name; // instance variable
int age; // instance variable
}

4.3.3 Static Variables


Static variables are shared among all objects of a class. They are declared using the
static keyword.
Example:
public class Student {
static String school = "ABC University";
}

59
COS 201: Computer Programming I Lecture Notes

4.4 Data Types in Java


A data type defines the type of data a variable can store. Java is a strongly typed
language, meaning every variable must have a data type.
Data types in Java are divided into two categories:

1. Primitive Data Types

2. Non-Primitive (Reference) Data Types

4.5 Primitive Data Types


Primitive data types are the basic building blocks of data manipulation in Java. There
are eight primitive data types:

4.5.1 Integer Types


• byte: 8-bit integer

• short: 16-bit integer

• int: 32-bit integer

• long: 64-bit integer

Example:
byte a = 10;
short b = 1000;
int c = 50000;
long d = 100000L;

4.5.2 Floating Point Types


• float: 32-bit decimal number

• double: 64-bit decimal number

Example:
float pi = 3.14f;
double salary = 45000.75;

60
COS 201: Computer Programming I Lecture Notes

4.5.3 Character Type


• char: stores a single character

Example:
char grade = ’A’;

4.5.4 Boolean Type


• boolean: stores true or false

Example:
boolean isActive = true;

4.6 Non-Primitive Data Types


Non-primitive data types are more complex and are used to store multiple values or
objects.
Examples include:

• String

• Arrays

• Classes

• Interfaces

Example:
String name = "John";
int[] numbers = {1, 2, 3, 4};

4.7 Type Conversion in Java


Type conversion is the process of converting one data type into another.

4.7.1 Implicit Conversion (Widening)


Occurs automatically when a smaller type is converted to a larger type.
int a = 10;
double b = a; // automatic conversion

61
COS 201: Computer Programming I Lecture Notes

4.7.2 Explicit Conversion (Narrowing)


Requires manual casting when converting larger types to smaller types.
double a = 10.5;
int b = (int) a;

4.8 Default Values of Data Types


When variables are declared as class members, they are assigned default values:

Data Type Default Value


int 0
double 0.0
char ’\u0000’
boolean false
String null

4.9 Importance of Variables and Data Types


Variables and data types are essential in Java because they:

• Define how data is stored in memory

• Ensure type safety

• Improve program efficiency

• Enable structured programming

• Support data manipulation and computation

4.10 Chapter Summary


This chapter introduced variables and data types in Java. Variables are named memory
locations used to store data, while data types define the nature of data that can be
stored in those variables. Java supports primitive data types such as int, float, char, and
boolean, as well as non-primitive types such as String and arrays.
The chapter also explained variable types (local, instance, and static variables), rules
for variable declaration, type conversion, and default values. Understanding variables
and data types is fundamental for writing correct and efficient Java programs.

62
COS 201: Computer Programming I Lecture Notes

4.11 Exercises

A. Objective Questions
1. What is a variable in Java?

2. How many primitive data types exist in Java?

3. Which data type is used to store true or false values?

4. What is the default value of an int variable?

5. What is type casting?

6. What is the difference between local and instance variables?

7. Which data type is used for decimal numbers?

8. What keyword is used for static variables?

9. What is a non-primitive data type?

10. What is widening conversion?

B. Short Answer Questions


1. Explain the difference between variables and data types.

2. Describe the three types of variables in Java.

3. List and explain primitive data types in Java.

4. What are the rules for naming variables?

5. Explain explicit and implicit type conversion.

C. Practical Exercises
1. Write a Java program that declares variables of all primitive data types.

2. Create a program that converts int to double and double to int.

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.

5. Write a program that demonstrates type casting.

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.

5.2 Importing the Scanner Class


Before using the Scanner class, it must be imported from the Java utility package.
Syntax:
import [Link];

5.3 Creating a Scanner Object


To use the Scanner class, an object must be created.
Syntax:
Scanner input = new Scanner([Link]);

Here:

• Scanner is the class name.

• input is the object name (can be any valid identifier).

• [Link] represents standard input (keyboard).

64
COS 201: Computer Programming I Lecture Notes

5.4 Basic Input Methods


The Scanner class provides several methods for reading different types of input.

5.4.1 Reading Integer Values

int number = [Link]();

5.4.2 Reading Floating-Point Numbers

double value = [Link]();

5.4.3 Reading Strings

String name = [Link]();

or
String word = [Link]();

Difference:

• next() reads a single word.

• nextLine() reads an entire line including spaces.

5.4.4 Reading Boolean Values

boolean flag = [Link]();

5.4.5 Reading Character Values


Java does not provide a direct method for reading a single character. Instead, a character
is usually extracted from a string.
char grade = [Link]().charAt(0);

65
COS 201: Computer Programming I Lecture Notes

5.5 Example of Scanner Class Usage


import [Link];

public class UserInputExample {

public static void main(String[] args) {

Scanner input = new Scanner([Link]);

[Link]("Enter your name: ");


String name = [Link]();

[Link]("Enter your age: ");


int age = [Link]();

[Link]("Enter your GPA: ");


double gpa = [Link]();

[Link]("\nUser Details:");
[Link]("Name: " + name);
[Link]("Age: " + age);
[Link]("GPA: " + gpa);
}
}

5.6 Common Methods of Scanner Class


Method Description
nextInt() Reads an integer value
nextDouble() Reads a double value
nextFloat() Reads a float value
nextLong() Reads a long value
next() Reads a single word (string)
nextLine() Reads a full line of text
nextBoolean() Reads true or false

66
COS 201: Computer Programming I Lecture Notes

5.7 Important Notes When Using Scanner


• Always import [Link] before using it.

• Scanner should be created using [Link] for keyboard input.

• Be careful when mixing nextLine() with other input methods due to newline
handling.

• It is good practice to close the Scanner after use:

[Link]();

5.8 Common Input Problem (nextLine Issue)


When using nextInt() or nextDouble() before nextLine(), the input buffer may retain
a newline character, causing unexpected behavior.
Solution: Add an extra nextLine().
int age = [Link]();
[Link](); // consume leftover newline
String name = [Link]();

5.9 Advantages of Scanner Class


• Easy to use for beginners.

• Supports multiple data types.

• Reduces complexity of input handling.

• Part of standard Java library.

5.10 Limitations of Scanner Class


• Slower compared to other input methods like BufferedReader.

• Can cause input buffering issues.

• Not suitable for very large input processing systems.

67
COS 201: Computer Programming I Lecture Notes

5.11 Chapter Summary


This chapter introduced the Scanner class in Java, which is used for taking input from
users. The Scanner class belongs to the [Link] package and must be imported before
use. It allows reading different types of input such as integers, decimals, strings, and
boolean values.
The chapter explained how to create a Scanner object, use its common methods, and
handle common input issues such as the newline problem. Although Scanner is easy to
use and suitable for beginners, it may not be the most efficient choice for large-scale input
processing.

5.12 Exercises

A. Objective Questions
1. In which package is the Scanner class found?

2. What statement is used to import Scanner?

3. Which method is used to read an integer?

4. What is the purpose of [Link]?

5. What is the difference between next() and nextLine()?

6. Can Scanner read boolean values? (Yes/No)

7. What method reads a double value?

8. Why is nextLine() sometimes skipped?

9. What keyword is used to close a Scanner object?

10. Is Scanner suitable for large input processing systems?

B. Short Answer Questions


1. Explain the purpose of the Scanner class.

2. Describe how to create a Scanner object.

3. List five methods of the Scanner class.

4. Explain the newline problem in Scanner input.

5. State two advantages and two limitations of Scanner.

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.

3. Write a program that reads a character and prints it.

4. Create a program that demonstrates the use of nextLine() and next().

5. Write a program that reads student marks and calculates the average.

69
Chapter 6

Expressions and Operators

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.

6.2 Expressions in Java


An expression is a valid combination of variables, literals, operators, and method calls
that returns a value.
Examples of expressions:
int sum = a + b;
double result = (x * y) / z;
boolean status = (age > 18);

6.2.1 Types of Expressions


1. Arithmetic Expressions

2. Relational Expressions

3. Logical Expressions

4. Assignment Expressions

70
COS 201: Computer Programming I Lecture Notes

6.3 Operators in Java


Operators are symbols that perform operations on variables and values. Java provides
several categories of operators.

6.4 Arithmetic Operators


Arithmetic operators are used to perform basic mathematical operations.

Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus (remainder)

Example:
int a = 10;
int b = 3;

[Link](a + b); //output 13


[Link](a - b); //output 7
[Link](a * b); //output 30
[Link](a / b); //output 3 (integer division, decimal point will be
discarded)
[Link](a % b); //output 1

6.5 Relational Operators


Relational operators are used to compare two values. The result is always a boolean value
(true or false).

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;

[Link](x == y); //output false


[Link](x != y); //output true
[Link](x > y); //output false
[Link](x < y); //output true

6.6 Logical Operators


Logical operators are used to combine multiple conditions.

Operator Description
&& Logical AND
|| Logical OR
! Logical NOT

Example:
int age = 20;

[Link](age > 18 && age < 30); //output true


[Link](age > 18 || age < 10); //output false
[Link](!(age > 18));//output false

6.7 Assignment Operators


Assignment operators are used to assign values to variables.

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

6.8 Unary Operators


Unary operators operate on a single operand. They are widely used in programming
languages such as Java and C/C++ to perform operations like sign manipulation, logical
negation, and value updates.

Operator Description
+ Unary plus (positive sign)
- Unary minus (negation)
++ Increment operator
-- Decrement operator
! Logical NOT

6.8.1 Unary Plus (+)


The unary plus operator is used to indicate that a number is positive. It does not change
the value of the operand but explicitly denotes its sign. In most programming languages,
it is optional since numeric values are positive by default unless stated otherwise.
Example:
int a = 5;
int b = +a;
[Link](b); // Output: 5

6.8.2 Unary Minus (-)


The unary minus operator is used to negate the value of a numeric operand. It changes
a positive value to negative and a negative value to positive.
Example:

73
COS 201: Computer Programming I Lecture Notes

int a = 5;
int b = -a;
[Link](b); // Output: -5

6.8.3 Increment Operator (++)


The increment operator increases the value of a variable by 1. It has two forms: pre-
increment and post-increment.

Pre-Increment (++x)

In pre-increment, the value of the variable is increased before it is used in an expression.


Example:
int x = 5;
int y = ++x;
[Link](x); // 6
[Link](y); // 6

Explanation:

• The value of x is first incremented.

• The updated value is then assigned to y.

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:

• The original value of x is assigned to y.

• Then x is incremented by 1.

6.8.4 Decrement Operator (–)


The decrement operator reduces the value of a variable by 1. It also has two forms:
pre-decrement and post-decrement.

74
COS 201: Computer Programming I Lecture Notes

Pre-Decrement (–x)

In pre-decrement, the value is decreased before being used in an expression.


Example:
int x = 5;
int y = --x;
[Link](x); // 4
[Link](y); // 4

Explanation:
• The value of x is first decreased.

• The updated value is assigned to y.

Post-Decrement (x–)

In post-decrement, the current value is used first before being decremented.


Example:
int x = 5;
int y = x--;
[Link](x); // 4
[Link](y); // 5

Explanation:
• The original value of x is assigned to y.

• Then x is decreased by 1.

6.8.5 Logical NOT (!) Operator


The logical NOT operator negates a Boolean value. If a condition is true, it becomes
false, and vice versa.
Example:
boolean flag = true;
[Link](!flag); // false

• Unary plus and minus are used for sign manipulation.

• Increment and decrement operators modify values by 1.

• Pre-operators modify before evaluation, while post-operators modify after evalua-


tion.

• Logical NOT reverses Boolean values.

75
COS 201: Computer Programming I Lecture Notes

6.9 Operator Precedence


Operator precedence determines the order in which operators are evaluated in an expres-
sion.
Order of precedence (highest to lowest):

1. Parentheses ()

2. Unary operators (post-increment (x++) and post-decrement (x–))

3. Unary operators (!, unary plus, unary minus, pre-increment (++x), pre-decrement(–
x))

4. Multiplication (*), Division (/), Modulus (%)

5. Addition (+) and Subtraction (-)

6. Relational operators

7. Logical AND (&&)

8. Logical OR (||)

9. Assignment operators

Example:
int result = 10 + 5 * 2;
[Link](result); // 20, not 30

6.10 Operator Associativity


Operator associativity defines the direction in which an expression is evaluated when
two or more operators of the same precedence appear in an expression. While operator
precedence determines which operator is evaluated first, associativity determines how
operators of equal precedence are grouped.
In other words, associativity specifies whether an expression is evaluated from left to
right or from right to left.

6.10.1 Types of Associativity


There are two main types of associativity:

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: +, −, ∗, /, %

• Relational operators: <, >, <=, >=

• Postfix increment/decrement: x + +, x − −

• Logical operators: &&, ||

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

Thus, a = 15, b = 15, and c = 15.


Examples of operators with right-to-left associativity include:

• Assignment operators: =, + =, − =, ∗ =, etc.

• Unary operators: Prefix increment/decrement (+ + x, − − x), !, unary +, unary −

77
COS 201: Computer Programming I Lecture Notes

6.10.2 Importance of Associativity


Operator associativity is important because it:

• Determines correct evaluation of expressions.

• Prevents ambiguity in complex expressions.

• Helps programmers predict program behavior accurately.

• Associativity defines the direction of evaluation for operators of equal precedence.

• Left-to-right associativity is common for arithmetic and logical operators.

• Right-to-left associativity is common for assignment and unary operators.

6.11 Type Conversion in Expressions


When different data types are used in expressions, Java automatically performs type
conversion.

6.11.1 Implicit Conversion

int a = 10;
double b = a + 2.5;

6.11.2 Explicit Conversion

double a = 10.7;
int b = (int) a;

6.12 Common Errors in Expressions


• Division by zero

• Type mismatch errors

• Incorrect operator usage

• Misunderstanding operator precedence

78
COS 201: Computer Programming I Lecture Notes

6.13 Importance of Expressions and Operators


Expressions and operators are important because they:

• Enable mathematical computations

• Support decision-making in programs

• Allow data manipulation

• Form the basis of control structures

6.14 Chapter Summary


This chapter introduced expressions and operators in Java. Expressions are combinations
of variables, constants, and operators that evaluate to a single value. Operators are
symbols used to perform operations such as arithmetic, comparison, logical evaluation,
assignment, and unary operations.
The chapter explained different categories of operators, including arithmetic, rela-
tional, logical, assignment, and unary operators. It also discussed operator precedence
and type conversion in expressions. Understanding expressions and operators is essential
for performing calculations and building logical conditions in Java programs.

6.15 Exercises

A. Objective Questions
1. What is an expression in Java?

2. Which operator is used for comparison?

3. What is the result of relational expressions?

4. Which operator is used for logical AND?

5. What does the modulus operator (%) do?

6. What is operator precedence?

7. Which operator is used for assignment?

8. What is the result of 10 / 3 in Java (int)?

9. What is the increment operator?

10. What does the NOT operator do?

79
COS 201: Computer Programming I Lecture Notes

B. Short Answer Questions


1. Explain the difference between arithmetic and relational operators.

2. Describe logical operators with examples.

3. Explain operator precedence in Java.

4. Differentiate between ++i and i++.

5. What is type conversion in expressions?

C. Practical Exercises
1. Write a program that performs all arithmetic operations on two numbers.

2. Create a program that checks whether a number is greater than 50.

3. Write a program that evaluates logical expressions using AND, OR, and NOT.

4. Demonstrate the difference between pre-increment and post-increment.

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.

7.2 What is Type Conversion?


Type conversion is the process of changing a value from one data type to another.
For example:
int age = 20;
double ageDouble = age;

In this example, the integer value stored in age is converted into a double value and
stored in ageDouble.

7.3 Why Type Conversion is Necessary


Type conversion is necessary for several reasons:

• To perform arithmetic operations involving different data types.

• To store values in variables of different types.

81
COS 201: Computer Programming I Lecture Notes

• To increase numerical precision.

• To reduce memory usage when appropriate.

• To support interaction between different parts of a program.

7.4 Types of Type Conversion


Java supports two major forms of type conversion:

1. Implicit Type Conversion (Widening Conversion)

2. Explicit Type Conversion (Narrowing Conversion)

7.5 Implicit Type Conversion (Widening Conversion)


Implicit conversion occurs automatically when a smaller data type is converted into a
larger compatible data type.
Since the destination type can accommodate all possible values of the source type, no
data loss occurs.

7.5.1 Conversion Hierarchy


byte → short → int → long → float → double

7.5.2 Example 1: int to double


int number = 100;
double result = number;

[Link](result);

Output
100.0

7.5.3 Example 2: char to int


Each character has a corresponding Unicode value.
char letter = ’A’;
int value = letter;

[Link](value);

82
COS 201: Computer Programming I Lecture Notes

Output
65

7.5.4 Advantages of Widening Conversion


• Performed automatically by Java.

• No loss of information.

• Improves compatibility between data types.

• Simplifies arithmetic operations.

7.6 Explicit Type Conversion (Narrowing Conver-


sion)
Explicit conversion occurs when a larger data type is converted into a smaller data type.
Since the smaller type may not be able to store all values of the larger type, data loss
may occur. Therefore, Java requires the programmer to perform the conversion manually
using a cast operator.

7.6.1 Syntax

targetType variable = (targetType) value;

7.6.2 Example 1: double to int

double number = 25.75;


int result = (int) number;

[Link](result);

Output
25

Notice that the decimal portion (.75) is discarded.

83
COS 201: Computer Programming I Lecture Notes

7.6.3 Example 2: long to int

long population = 5000000L;


int pop = (int) population;

[Link](pop);

7.6.4 Risks of Narrowing Conversion


• Loss of decimal precision.

• Loss of significant digits.

• Overflow and underflow errors.

• Unexpected program behavior.

7.7 Casting
Casting refers to the explicit conversion of one data type into another.
There are two forms of casting:

1. Primitive Type Casting

2. Reference Type Casting

This chapter focuses on primitive type casting.

7.7.1 Primitive Type Casting Example

double salary = 45000.99;


int wholeSalary = (int) salary;

[Link](wholeSalary);

Output
45000

84
COS 201: Computer Programming I Lecture Notes

7.8 Type Conversion in Arithmetic Expressions


Java automatically converts operands to compatible types during arithmetic operations.
Example
int a = 10;
double b = 3.5;

double result = a + b;

[Link](result);

Output
13.5

In this case, Java automatically converts a into a double before performing the addi-
tion.

7.9 Promotion in Arithmetic Operations


Java promotes smaller data types to int during arithmetic operations.
Example
byte a = 10;
byte b = 20;

int sum = a + b;

Even though both variables are bytes, the result is promoted to an integer.

7.10 Conversion Between Characters and Integers


Characters are internally represented using Unicode values.

7.10.1 Character to Integer

char grade = ’A’;


int value = grade;

[Link](value);

Output

85
COS 201: Computer Programming I Lecture Notes

65

7.10.2 Integer to Character

int code = 66;


char letter = (char) code;

[Link](letter);

Output
B

7.11 String Conversion


Java provides methods for converting strings to numeric values and vice versa.

7.11.1 String to Integer

String num = "100";


int value = [Link](num);

[Link](value);

7.11.2 String to Double

String num = "25.75";


double value = [Link](num);

[Link](value);

7.11.3 Number to String

int age = 20;

String text = [Link](age);

[Link](text);

86
COS 201: Computer Programming I Lecture Notes

7.12 Common Type Conversion Errors

7.12.1 Loss of Precision

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.

7.12.3 Invalid String Conversion

String text = "ABC";


int value = [Link](text);

This causes a NumberFormatException.

7.13 Best Practices for Type Conversion


• Use implicit conversion whenever possible.

• Avoid unnecessary casting.

• Check for possible data loss before narrowing.

• Validate strings before converting them to numbers.

• Use meaningful variable names to improve readability.

7.14 Applications of Type Conversion


Type conversion is widely used in:

• Scientific and engineering calculations.

87
COS 201: Computer Programming I Lecture Notes

• Financial applications.

• User input processing.

• Database applications.

• Data communication systems.

• Web and mobile applications.

7.15 Chapter Summary


This chapter discussed type conversion in Java, which is the process of converting values
from one data type to another. Java supports two main forms of type conversion: implicit
(widening) conversion and explicit (narrowing) conversion. Widening conversions occur
automatically and do not result in data loss, while narrowing conversions require casting
and may lead to loss of information.
The chapter also explained type promotion in arithmetic expressions, conversions
between characters and integers, string conversions, common conversion errors, and best
practices. Understanding type conversion is essential for writing accurate, efficient, and
reliable Java programs.

7.16 Exercises

A. Objective Questions
1. What is type conversion?

2. What is another name for implicit conversion?

3. What is another name for explicit conversion?

4. Which conversion may result in data loss?

5. What keyword is used to perform casting?

6. What is the Unicode value of the character ’A’?

7. Which method converts a String to an integer?

8. Which method converts a String to a double?

9. What exception occurs when converting an invalid numeric string?

10. Does widening conversion require casting?

88
COS 201: Computer Programming I Lecture Notes

B. Short Answer Questions


1. Differentiate between widening and narrowing conversion.

2. Explain type casting with an example.

3. Describe type promotion in arithmetic expressions.

4. Explain how Java converts characters to integers.

5. Discuss common errors associated with type conversion.

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.

3. Create a program that converts a character into its Unicode value.

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.

6. Demonstrate overflow by converting a large integer into a byte.

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:

1. Sequential Control Structure

2. Selection (Decision-Making) Control Structure

3. Iteration (Looping) Control Structure

These structures make it possible to create programs that can solve complex problems
efficiently.

8.2 Sequential Control Structure


The sequential control structure is the default execution pattern in Java. Statements are
executed one after another in the order they appear in the program.
Example
public class SequentialExample {
public static void main(String[] args) {
[Link]("Step 1");
[Link]("Step 2");

90
COS 201: Computer Programming I Lecture Notes

[Link]("Step 3");
}
}

Output

Step 1
Step 2
Step 3

The statements execute from top to bottom without interruption.

8.3 Selection Control Structures


Selection structures allow a program to choose between alternative actions based on
specified conditions.
Java provides the following decision-making statements:

• if statement

• if-else statement

• if-else-if ladder

• Nested if statement

• switch statement

8.4 The if Statement


The if statement executes a block of code only when a specified condition is true.

Syntax

if(condition) {
// statements
}

91
COS 201: Computer Programming I Lecture Notes

Start

Age ≥ 18?

Yes No

Display Skip Statement


“You are an adult.”

End

Figure 8.1: Flowchart of a simple If Statement

Flowchart of If Statement

Example
int age = 20;

if (age >= 18) {


[Link]("You are an adult.");
}

Output

You are an adult.

8.5 The if-else Statement


The if-else statement allows a program to make decisions by executing one block of
code when a condition is true and another block when the condition is false.

Syntax

92
COS 201: Computer Programming I Lecture Notes

Start

Score ≥ 45?

Yes No

Display Display
“Pass.” “Fail.”

End

Figure 8.2: Flowchart of an if-else Statement

if(condition) {
// true block
}
else {
// false block
}

Flowchart

Example
int score = 45;

if(score >= 50) {


[Link]("Pass");
}
else {
[Link]("Fail");
}

Output

93
COS 201: Computer Programming I Lecture Notes

Fail

8.6 The if-else-if Ladder


When multiple conditions need to be evaluated, Java provides the if-else-if ladder.
The conditions are checked from top to bottom. As soon as one condition evaluates
to true, its corresponding block of code is executed, and the remaining conditions are
skipped.
This structure is useful when a program must choose one option from several alter-
natives.

Syntax

if(condition1) {
// block 1
}
else if(condition2) {
// block 2
}
else if(condition3) {
// block 3
}
else {
// default block
}

Flowchart

Example: Student Grading System


The following program determines a student’s grade based on the score obtained in an
examination.
public class GradingSystem {
public static void main(String[] args) {

int score = 75;

if(score >= 70) {

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

Figure 8.3: Flowchart of if-else-if Ladder Statements

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.

• Since the score is 75, the condition is true.

• The statement Grade A is displayed.

• The remaining else if conditions are not evaluated.

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

8.7 Nested if Statements


A nested if statement occurs when one if statement is placed inside another. It allows
a program to evaluate additional conditions only after a preceding condition has been
met.

Syntax

96
COS 201: Computer Programming I Lecture Notes

if(condition1) {

if(condition2) {

// statements executed when


// both conditions are true

Flowchart
Example
int age = 25;
boolean hasLicense = true;

if(age >= 18) {


if(hasLicense) {
[Link]("Eligible to drive.");
}
}

Output

Eligible to drive.

8.8 The switch Statement


The switch statement is a selection control structure used to execute one block of code
from multiple alternatives based on the value of a single expression or variable. It provides
a more readable and organized alternative to a long if-else-if ladder when comparing
the same variable against several possible values.

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

Figure 8.4: Flowchart of Nested If Statements

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

Figure 8.5: Flowchart of a Switch Statement

8.9 How switch Works


1. Evaluate the expression.

2. Compare the value with each case label.

3. Execute matching case.

4. Stop at break.

5. Execute default if no match exists.

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

8.10 Switch with String Values


Java allows strings in switch statements.
Example
String department = "CSC";

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

8.11 Iteration Control Structures


Iteration control structures enable a program to execute a set of statements repeatedly
based on a specified condition. These structures are commonly used when a task needs
to be performed multiple times until a particular condition is met.
Java provides three primary iteration control structures:

1. while loop

2. do-while loop

3. for loop

8.12 The while Loop


The while loop is an iteration control structure that repeatedly executes a block of
statements as long as a specified condition evaluates to true. The condition is evaluated
before each iteration, making the while loop a pre-test loop. If the condition is initially
false, the loop body will not execute.

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.

Flowchart of While Loop

8.13 The do-while Loop


The do-while loop is an iteration control structure that executes a block of statements
before evaluating its condition. Because the condition is checked after the loop body
executes, the statements inside the loop are guaranteed to run at least once. For this
reason, the do-while loop is known as a post-test loop.

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

Figure 8.6: Flowchart of a while Loop

} while(count <= 5);

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

Figure 8.7: Flowchart of a do-while Loop

Table 8.1: Comparison of while and do-while loops


while Loop do-while Loop
Condition checked first Condition checked after ex-
ecution
May execute zero times Executes at least once
Entry-controlled loop Exit-controlled loop

Flowchart of a do-while Loop

8.14 Difference Between while and do-while

8.15 The for Loop


The for loop is an iteration control structure that is commonly used when the number
of iterations is known beforehand. It combines initialization, condition checking, and
variable updating into a single statement, making it compact and easy to read.

Syntax

for(initialization; condition; update) {


statements;
}

104
COS 201: Computer Programming I Lecture Notes

Flowchart

Start

Initialization

No
Condition? End

Yes

Execute Statements

Update

Figure 8.8: Flowchart of a for Loop

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

8.16 Nested Loops


A nested loop is a loop that is placed inside another loop. The outer loop controls how
many times the inner loop executes. For every single iteration of the outer loop, the inner
loop completes all of its iterations before the outer loop proceeds to its next iteration.
Nested loops are commonly used when working with tables, matrices, patterns, grids,
and situations that require repeated processing within another repetitive task.

Syntax

for(initialization1; condition1; update1) {

for(initialization2; condition2; update2) {


statements;
}

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:

• The outer loop variable i takes the values 1, 2, and 3.

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

The execution occurs as follows:

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

8.17 Enhanced for Loop (For-Each Loop)


The enhanced for loop, also known as the for-each loop, is a simplified version of the
for loop introduced in Java 5. It is specifically designed for traversing the elements of
arrays and collections without the need to manage loop counters or index values.
The enhanced for loop automatically visits each element in a collection one at a time,
making the code shorter, cleaner, and easier to read.

8.17.1 Why Use the Enhanced for Loop?


When using a normal for loop to process every element of an array, a loop variable is
required to keep track of the current index.
Normal for Loop
int[] scores = {70, 80, 90};

for(int i = 0; i < [Link]; i++) {


[Link](scores[i]);
}

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

for(int score : scores) {


[Link](score);
}

The output remains the same, but the code is simpler and easier to understand.

Syntax

for(dataType variable : collection) {


statements;
}

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.

• collection – The array or collection being traversed.

• statements – The code executed for each element.

General Form
for(Type item : collection) {
// use item
}

8.17.2 How the Enhanced for Loop Works


Consider the following array:
int[] scores = {70, 80, 90};

The loop:
for(int score : scores) {
[Link](score);
}

executes as follows:

1. The first element (70) is assigned to score.

2. The statement inside the loop is executed.

3. The second element (80) is assigned to score.

4. The statement inside the loop is executed again.

5. The third element (90) is assigned to score.

6. The statement inside the loop is executed again.

7. No more elements remain, so the loop terminates.

109
COS 201: Computer Programming I Lecture Notes

Example: Displaying Array Elements


int[] scores = {70, 80, 90};

for(int score : scores) {


[Link](score);
}

Output

70
80
90

Example: Finding the Sum of Array Elements


The enhanced for loop is commonly used for processing numerical data.
int[] numbers = {10, 20, 30, 40};
int sum = 0;

for(int num : numbers) {


sum += num;
}

[Link]("Sum = " + sum);

Output

Sum = 100

Example: Working with Strings


The enhanced for loop can also iterate through arrays of strings.
String[] names = {"Zauwali", "Usman", "Muktar"};

for(String name : names) {


[Link](name);
}

Output

Zauwali
Usman
Lawan

110
COS 201: Computer Programming I Lecture Notes

8.17.3 Using Enhanced for Loop with Collections


The enhanced for loop is widely used with Java collections such as ArrayList.
import [Link];

public class Main {


public static void main(String[] args) {

ArrayList<String> fruits = new ArrayList<>();

[Link]("Apple");
[Link]("Banana");
[Link]("Orange");

for(String fruit : fruits) {


[Link](fruit);
}
}
}

Output

Apple
Banana
Orange

8.17.4 Advantages of the Enhanced for Loop


• Simpler and more readable code.

• Eliminates the need for loop counters.

• Reduces the chance of index-related errors.

• Ideal when every element must be processed.

• Works with arrays and Java collections.

8.17.5 Limitations of the Enhanced for Loop


Although convenient, the enhanced for loop has some limitations:

• The current index position is not directly available.

111
COS 201: Computer Programming I Lecture Notes

• Elements cannot easily be accessed by index.

• It is not suitable when elements need to be processed in reverse order.

• Adding or removing elements from a collection during iteration may cause errors.

8.17.6 Comparison: for Loop vs Enhanced for Loop

Feature Normal for Loop Enhanced for Loop


Uses index variable Yes No
Access element position Yes No
Simpler syntax No Yes
Works with arrays Yes Yes
Works with collections Yes Yes
Reverse traversal Yes No
Best for reading elements Good Excellent

Table 8.2: Comparison of normal and Enhanced for Loops

8.17.7 When to Use the Enhanced for Loop


Use the enhanced for loop when:

• You need to visit every element in an array or collection.

• The index position is not required.

• The goal is simply to read or process each element.

• Code readability and simplicity are important.

Use a normal for loop when:

• You need the index of elements.

• You need to traverse in reverse order.

• You need more control over the iteration process.

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

8.18 Loop Control Statements


By default, loops execute continuously until their termination condition becomes false.
However, there are situations where a programmer may need to alter the normal flow of
execution. Java provides special statements called loop control statements for this
purpose.
Loop control statements allow a program to:

• Terminate a loop before its normal completion.

• Skip specific iterations of a loop.

• Improve efficiency by avoiding unnecessary processing.

• Implement special logic based on certain conditions.

The two most commonly used loop control statements in Java are:

1. break

2. continue

8.18.1 The break Statement


The break statement immediately terminates the execution of a loop. When a break
statement is encountered, the loop stops and program control transfers to the first state-
ment following the loop.
The break statement can be used with:

• for loops

• while loops

• do-while loops

• switch statements

Syntax

break;

113
COS 201: Computer Programming I Lecture Notes

Flow of Execution

When a break statement executes:

1. The current loop iteration stops immediately.

2. The loop is terminated completely.

3. Remaining iterations are not executed.

4. Control moves to the statement after the loop.

Example 1: Terminating a Loop Early

for(int i = 1; i <= 10; i++) {

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.

Example 2: Using break in a while Loop

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.

Common Uses of break

• Searching for a specific value.

• Stopping processing when a condition is satisfied.

• Exiting infinite loops safely.

• Improving performance by avoiding unnecessary iterations.

8.18.2 The continue Statement


The continue statement skips the remaining statements in the current iteration and
immediately proceeds to the next iteration of the loop.
Unlike break, which terminates the loop entirely, continue only skips one iteration.

Syntax

continue;

115
COS 201: Computer Programming I Lecture Notes

Flow of Execution

When a continue statement executes:

1. The remaining statements in the current iteration are skipped.

2. Control moves directly to the loop update step.

3. The next iteration begins.

4. The loop continues normally.

Example 1: Skipping an Iteration

for(int i = 1; i <= 5; i++) {

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

When i becomes 3, the continue statement executes. The println() statement is


skipped, and the loop proceeds directly to the next iteration.

116
COS 201: Computer Programming I Lecture Notes

Example 2: Printing Only Even Numbers

for(int i = 1; i <= 10; i++) {

if(i % 2 != 0)
continue;

[Link](i);
}

Output

2
4
6
8
10

The loop skips all odd numbers and prints only even numbers.

Common Uses of continue

• Ignoring unwanted values.

• Filtering data during iteration.

• Skipping invalid input.

• Simplifying conditional logic inside loops.

8.18.3 Difference Between break and continue


Although both statements affect loop execution, they serve different purposes.

Feature break continue


Terminates the loop Yes No
Skips current iteration No Yes
Remaining iterations No Yes
execute
Transfers control out- Yes No
side loop
Used for early exit Yes No
Used for filtering iter- No Yes
ations

117
COS 201: Computer Programming I Lecture Notes

Illustration
Consider the following sequence:

1 2 3 4 5

Using break at 3:

1 2

The loop stops completely.


Using continue at 3:

1 2 4 5

Only the value 3 is skipped, while the loop continues.

8.18.4 Best Practices


• Use break when the loop should terminate immediately.

• Use continue when only the current iteration should be skipped.

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

8.19 Infinite Loops


An infinite loop is a loop that continues executing indefinitely because its termination
condition never becomes false. In other words, the loop has no valid exit condition, or
the condition required to terminate the loop is never reached. As a result, the program
repeatedly executes the same block of code without stopping.
Infinite loops can occur intentionally or unintentionally. Unintentional infinite loops
are usually the result of programming errors, such as forgetting to update a loop control
variable or writing an incorrect condition. Intentional infinite loops, however, are often
used in applications that are designed to run continuously, such as servers, operating
systems, embedded systems, and event-driven applications.

118
COS 201: Computer Programming I Lecture Notes

8.19.1 Causes of Infinite Loops


Common causes of infinite loops include:

• Using a condition that is always true.

• Forgetting to update the loop control variable.

• Updating the control variable incorrectly.

• Using an incorrect logical condition.

• Accidentally resetting the control variable inside the loop.

Example 1: Using a Constant True Condition


The following example creates an infinite loop because the condition is always true:
while(true) {
[Link]("Running...");
}

Output

Running...
Running...
Running...
Running...
...

The statement while(true) always evaluates to true, so the loop never terminates.

Example 2: Missing Update Statement


The following loop is intended to count from 1 to 5, but it becomes infinite because the
value of i is never incremented.
int i = 1;

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

Example 3: Corrected Version


To avoid the infinite loop, the control variable must be updated.
int i = 1;

while(i <= 5) {
[Link](i);
i++;
}

Output

1
2
3
4
5

8.19.2 Breaking Out of an Infinite Loop


Infinite loops can be terminated using a break statement when a specific condition is
met.
int count = 1;

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

8.19.3 Applications of Infinite Loops


Infinite loops are useful in many real-world systems:

1. Web Servers – Continuously wait for and process client requests.

2. Operating Systems – Monitor system resources and manage processes.

3. Game Development – Continuously update game graphics and user interactions.

4. Embedded Systems – Monitor sensors and control hardware devices.

5. Event-Driven Applications – Wait for user actions such as mouse clicks and
keyboard input.

8.19.4 Advantages and Disadvantages


Advantages

• Useful for applications that must run continuously.

• Allows programs to respond to events at any time.

• Provides a simple structure for monitoring and control systems.

Disadvantages

• Can consume excessive CPU resources if not properly controlled.

• May cause programs to become unresponsive.

• Can make debugging difficult when created accidentally.

8.19.5 Best Practices


To avoid unintended infinite loops:

• Ensure loop conditions eventually become false.

• Update loop control variables correctly.

• Test loop termination conditions thoroughly.

• Use break statements carefully.

• Monitor resource usage when designing continuous-running applications.

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.

8.19.6 Finding the Sum of Numbers


One of the most common uses of loops is performing repetitive calculations. The following
program calculates the sum of the integers from 1 to 10.
int sum = 0;

for(int i = 1; i <= 10; i++) {


sum += i;
}

[Link]("Sum = " + sum);

Output

Sum = 55

Explanation

1. The variable sum is initialized to 0.

2. The loop variable i starts at 1.

3. During each iteration, the current value of i is added to sum.

4. The loop continues until i reaches 10.

5. The final value stored in sum is displayed.

The calculation performed is:

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

8.19.7 Multiplication Table


A multiplication table is a common application of loops in programming. Instead of
manually writing each multiplication statement, a loop can repeatedly calculate and
display the results. This approach reduces code duplication and makes programs more
efficient and easier to maintain.
The following program displays the multiplication table of 5 from 1 to 12.
for(int i = 1; i <= 12; i++) {
[Link]("5 x " + i + " = " + (5*i));
}

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

1. The loop variable i is initialized to 1.

2. The loop continues as long as i is less than or equal to 12.

3. During each iteration, the expression 5*i calculates the product of 5 and the current
value of i.

4. The result is displayed in a formatted multiplication-table style.

5. After each iteration, i is incremented by 1.

6. The loop terminates when i becomes 13.

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

Multiplication tables are useful in:

• Educational software and learning applications.

• Mathematical computations.

• Financial calculations involving repeated multiplications.

• Generating tabular reports.

8.19.8 Even Numbers from 1 to 20


Loops can also be used to generate sequences of numbers that satisfy specific conditions.
In this example, a for loop is used to display all even numbers between 1 and 20.
An even number is any integer that is divisible by 2 without leaving a remainder.
for(int i = 2; i <= 20; i += 2) {
[Link](i);
}

Output

2
4
6
8
10
12
14
16
18
20

124
COS 201: Computer Programming I Lecture Notes

Explanation

1. The loop variable i is initialized to 2, which is the first even number.

2. The loop continues while i is less than or equal to 20.

3. After each iteration, i is increased by 2 using the statement i += 2.

4. Because the value increases by 2 each time, only even numbers are generated.

5. The loop terminates when i becomes greater than 20.

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

Alternative Method Using a Conditional Statement

Even numbers can also be generated by checking whether a number is divisible by 2.


for(int i = 1; i <= 20; i++) {
if(i % 2 == 0) {
[Link](i);
}
}

The modulus operator (%) returns the remainder after division. If the remainder is 0,
the number is even.

Practical Applications

Generating even numbers is useful in:

• Mathematical and statistical computations.

125
COS 201: Computer Programming I Lecture Notes

• Data filtering operations.

• Identifying divisible values in datasets.

• Developing algorithms involving number patterns.

These examples illustrate how loops can automate repetitive tasks, generate mathe-
matical sequences, and perform calculations efficiently with minimal code.

8.20 Common Programming Errors


Programming errors, commonly referred to as bugs, are mistakes made during software
development that cause a program to behave unexpectedly, produce incorrect results, or
fail to execute properly. Understanding common programming errors helps programmers
write more reliable, efficient, and maintainable code.

8.20.1 Forgetting Braces in Nested Statements


One of the most common mistakes among beginners is omitting braces ({}) when working
with nested conditional or loop statements.
Incorrect Example
if(age >= 18)
if(hasLicense)
[Link]("Drive");
[Link]("Welcome");

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

Using braces improves readability and prevents logical errors.

126
COS 201: Computer Programming I Lecture Notes

8.20.2 Using Assignment Operator (=) Instead of Comparison


Operator (==)
A common logical error occurs when programmers mistakenly use the assignment operator
= instead of the equality operator ==.
Incorrect Example
if(number = 10) {
[Link]("Equal");
}

The assignment operator assigns a value, whereas the comparison operator checks
whether two values are equal.
Correct Example
if(number == 10) {
[Link]("Equal");
}

Always ensure that comparison operations use relational operators appropriately.

8.20.3 Creating Infinite Loops Accidentally


An infinite loop occurs when a loop never reaches its termination condition.
Incorrect Example
int i = 1;

while(i <= 10) {


[Link](i);
}

The variable i is never updated, causing the condition to remain true indefinitely.
Correct Example
int i = 1;

while(i <= 10) {


[Link](i);
i++;
}

Always verify that loop control variables are updated correctly.

127
COS 201: Computer Programming I Lecture Notes

8.20.4 Missing Break Statements in Switch Cases


Forgetting the break statement can cause program execution to continue into the next
case, a behavior known as fall-through.
Incorrect Example
switch(day) {
case 1:
[Link]("Monday");
case 2:
[Link]("Tuesday");
}

If day equals 1, both messages will be displayed.


Correct Example
switch(day) {
case 1:
[Link]("Monday");
break;

case 2:
[Link]("Tuesday");
break;
}

Including break statements prevents unintended execution of subsequent cases.

8.20.5 Incorrect Loop Conditions


Using an incorrect condition may cause loops to execute too many times or not execute
at all.
Incorrect Example
for(int i = 1; i >= 10; i++) {
[Link](i);
}

Since the condition is false initially, the loop never executes.


Correct Example
for(int i = 1; i <= 10; i++) {
[Link](i);
}

Always verify that loop conditions reflect the intended logic.

128
COS 201: Computer Programming I Lecture Notes

8.20.6 Updating Loop Variables Improperly


Incorrect updates can lead to unexpected behavior or infinite loops.
Incorrect Example
for(int i = 1; i <= 10; i--) {
[Link](i);
}

The variable decreases instead of increasing, causing the loop condition to remain
true.
Correct Example
for(int i = 1; i <= 10; i++) {
[Link](i);
}

Ensure that loop variables move toward the termination condition.

8.20.7 Off-by-One Errors


An off-by-one error occurs when a loop executes one time too many or one time too few.
Incorrect Example
for(int i = 1; i < 10; i++) {
[Link](i);
}

This loop prints values from 1 to 9 instead of 1 to 10.


Correct Example
for(int i = 1; i <= 10; i++) {
[Link](i);
}

Carefully examine loop boundaries to avoid such mistakes.

129
COS 201: Computer Programming I Lecture Notes

8.20.8 Summary of Common Errors


Error Possible Consequence
Missing braces Incorrect execution of statements
Using = instead of == Logical errors in conditions
Infinite loops Program never terminates
Missing break in switch Unwanted fall-through behavior
Incorrect loop condition Loop executes incorrectly
Improper loop updates Infinite loops or wrong output
Off-by-one errors Missing or extra iterations

8.21 Best Practices


Best practices are recommended techniques and guidelines that help programmers write
clean, efficient, maintainable, and error-free code. Following these practices improves
software quality and reduces debugging time.

8.21.1 Use Meaningful Variable Names


Variables should clearly describe the data they store.
Poor Example
int x;
double y;

Better Example
int studentAge;
double accountBalance;

Meaningful names improve readability and maintainability.

8.21.2 Keep Conditions Simple and Readable


Complex conditions can be difficult to understand and debug.
Example
if(age >= 18 && age <= 60 && hasLicense) {
[Link]("Eligible");
}

Simple conditions make program logic easier to follow.

130
COS 201: Computer Programming I Lecture Notes

8.21.3 Avoid Deeply Nested Structures


Excessive nesting reduces code readability.
Poor Example
if(condition1) {
if(condition2) {
if(condition3) {
// code
}
}
}

Whenever possible, simplify logic or divide complex code into methods.

8.21.4 Always Test Boundary Conditions


Boundary values often reveal hidden bugs.
Examples include:

• Testing zero values.

• Testing maximum and minimum values.

• Testing empty input.

• Testing the first and last loop iterations.

Boundary testing improves program reliability.

8.21.5 Use Switch Statements for Multiple Fixed Choices


When a program must select one option from many predefined values, a switch statement
is often more readable than multiple if-else statements.
Example
switch(day) {
case 1:
[Link]("Monday");
break;

case 2:
[Link]("Tuesday");
break;

131
COS 201: Computer Programming I Lecture Notes

default:
[Link]("Invalid");
}

8.21.6 Use For Loops When the Number of Iterations Is Known


A for loop is ideal when the number of repetitions can be determined beforehand.
Example
for(int i = 1; i <= 10; i++) {
[Link](i);
}

8.21.7 Use While Loops When the Number of Iterations Is Un-


known
A while loop is suitable when repetition depends on a condition rather than a fixed
count.
Example
while(passwordIncorrect) {
// Request password again
}

8.21.8 Properly Indent Code


Consistent indentation improves readability and helps identify program structure.
Example
if(score >= 50) {
[Link]("Pass");
} else {
[Link]("Fail");
}

Most modern development environments automatically format code to maintain proper


indentation.

8.21.9 Comment Important Sections of Code


Comments help explain the purpose of code segments.

132
COS 201: Computer Programming I Lecture Notes

// Calculate total sales


totalSales = quantity * price;

Comments should clarify complex logic rather than describe obvious statements.

8.21.10 Write Modular Programs


Large programs should be divided into smaller methods or functions.
public static int add(int a, int b) {
return a + b;
}

Modular code is easier to test, debug, and maintain.

8.21.11 Benefits of Following Best Practices


• Improves code readability.

• Reduces programming errors.

• Simplifies debugging and testing.

• Enhances collaboration among programmers.

• Makes software easier to maintain and extend.

• Encourages professional programming standards.

By consistently applying these best practices, programmers can develop software that
is reliable, efficient, maintainable, and easier for others to understand and modify.

8.22 Chapter Summary


The concept of control structures was introduced as one of the fundamental building
blocks of programming in this chapter. Control structures determine the order in which
statements are executed within a program, allowing developers to create applications that
can make decisions, repeat tasks, and respond dynamically to different situations. With-
out control structures, programs would execute statements strictly from top to bottom,
limiting their ability to solve complex problems.
The chapter began with an examination of sequential execution, the default mode
of program execution in which statements are processed one after another in the order
they appear. While sequential execution is suitable for simple tasks, more sophisticated

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.

2. Differentiate between sequential, selection, and iteration control structures.


Provide one example of each.

3. State the purpose of the following Java statements:

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

6. Explain the difference between a switch statement and an if-else-if statement.


When would you prefer to use each?

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.

8. Explain the differences between the following loop structures:

(a) while loop


(b) do-while loop
(c) for loop

9. What will be the output of the following code?

135
COS 201: Computer Programming I Lecture Notes

int x = 5;

if(x > 3) {
[Link]("A");
} else {
[Link]("B");
}

10. What will be the output of the following code?


for(int i = 1; i <= 3; i++) {
[Link](i);
}

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.

16. Write a Java program that displays the following pattern:

*
**
***
****
*****

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.

21. Identify and correct the error in the following code:


int i = 1;

while(i <= 10) {


[Link](i);
}

22. Identify the output of the following code:


for(int i = 1; i <= 5; i++) {
if(i == 3)
continue;

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

28. Explain the term off-by-one error. Provide an example.

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.

Additional Nested Loop Exercises


1. Using nested loops, write a Java program to display the following pyramid:

*
***
*****
*******
*********

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:

1. Check Even or Odd


2. Calculate Factorial
3. Generate Multiplication Table
4. Display Numbers 1 - 100
5. 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

Strings and Character Processing

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: "Computer Science"

• String: "Northwest University Kano"

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.

9.2 Characters in Java


A character is represented using the primitive data type char.
Java stores characters using the Unicode standard, which supports thousands of char-
acters from different languages around the world.

144
COS 201: Computer Programming I Lecture Notes

9.2.1 Declaring Character Variables

char grade = ’A’;


char gender = ’M’;
char symbol = ’#’;
char digit = ’5’;

Notice that character literals are enclosed in single quotation marks.

9.2.2 Displaying Characters

public class CharacterExample {


public static void main(String[] args) {

char letter = ’J’;

[Link](letter);
}
}

Output

9.3 Unicode Representation


Java uses Unicode to represent characters.
Each character is assigned a unique numerical code.

Character Unicode Value


A 65
B 66
a 97
b 98
0 48
1 49

Table 9.1: Examples of Unicode Values

Example
char letter = 65;

[Link](letter);

145
COS 201: Computer Programming I Lecture Notes

Output

9.4 Escape Sequences


Escape sequences allow special characters to be represented within strings and character
literals.
Escape Sequence Meaning
\n New line
\t Horizontal tab
\b Backspace
\r Carriage return
\’ Single quotation mark
\" Double quotation mark
\\ Backslash

Table 9.2: Common Escape Sequences

Example
[Link]("Java\nProgramming");

Output

Java
Programming

9.5 Introduction to Strings


A string is a sequence of characters enclosed within double quotation marks. Strings are
one of the most commonly used data types in programming because they allow programs
to store, process, and manipulate textual information. Any collection of letters, digits,
symbols, spaces, or a combination of these characters can be represented as a string.
Examples of strings include names, addresses, messages, passwords, email addresses,
and other forms of textual data that users interact with daily. Whenever a program
displays text on the screen or accepts text input from a user, it is usually working with
strings.
Examples of string literals are shown below:
"Java"
"Northwest University Kano"
"12345"
"Hello World"

146
COS 201: Computer Programming I Lecture Notes

Each of the examples above represents a valid string:

• "Java" contains four alphabetic characters.

• "Northwest University Kano" contains letters and spaces.

• "12345" contains numeric characters, but it is still a string because it is enclosed


in quotation marks.

• "Hello World" contains letters and a space character.

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.

9.5.1 Strings in Java


In Java, strings are represented by the String class, which is part of the [Link]
package. Unlike primitive data types such as int, double, and char, a string is an
object.
A string variable can be declared and initialized as follows:
String name = "Ahmed";

In this example:

• String is the data type.

• name is the variable name.

• "Ahmed" is the string value assigned to the variable.

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

9.5.2 String Literals


A string literal is the actual text enclosed in double quotation marks.
Examples:
"Java Programming"
"Welcome"
"Computer Science"

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.

9.5.3 Characters Within a String


A string consists of individual characters arranged in a specific order. Each character
occupies a particular position called an index.
Consider the string:
String word = "JAVA";

The characters are stored as follows:

J A V A
0 1 2 3

Notice that indexing begins at zero rather than one. Therefore:

• 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 indexing system is used extensively when accessing or manipulating characters


within strings.

9.5.4 Creating String Objects


Strings can be created in two common ways.

Using a String Literal

String city = "Kano";

This is the most commonly used approach because it is simple and memory-efficient.

148
COS 201: Computer Programming I Lecture Notes

Using the new Keyword

String city = new String("Kano");

This statement explicitly creates a new String object in memory.


Although both approaches produce strings containing the same text, using string
literals is generally preferred because it utilizes the String Pool and reduces memory
usage.

9.5.5 Why Strings Are Important


Strings are essential because most real-world applications process textual information.
Examples include:

• Storing student names.

• Displaying menus and messages.

• Processing user input.

• Managing passwords and usernames.

• Handling email addresses.

• Generating reports.

• Reading and writing files.

• Communicating over networks and the Internet.

Without strings, programs would not be able to interact effectively with users.

9.5.6 Displaying Strings


Strings can be displayed using the [Link]() method.
Example:
String greeting = "Hello World";

[Link](greeting);

Output

Hello World

Multiple strings can also be displayed:

149
COS 201: Computer Programming I Lecture Notes

String firstName = "Amina";


String lastName = "Yusuf";

[Link](firstName);
[Link](lastName);

Output

Amina
Yusuf

9.5.7 Strings and User Interaction


Strings play a major role in user interaction because most information entered by users
is initially received as text.
For example, a user may enter:

• A name

• An address

• A phone number

• An email address

• A password

Programs store and process this information using String objects.

9.5.8 Characteristics of Strings


The following are important characteristics of strings in Java:

1. A string is a sequence of characters.

2. Strings are enclosed in double quotation marks.

3. Strings are objects of the String class.

4. Strings can contain letters, numbers, spaces, and symbols.

5. Every character in a string has an index position.

6. String indexing starts at zero.

7. Strings are widely used for storing and manipulating textual data.

150
COS 201: Computer Programming I Lecture Notes

8. Java provides many built-in methods for processing strings.

Understanding strings is fundamental to Java programming because almost every


application works with text in some form. In the sections that follow, we will explore how
to create, manipulate, compare, search, and process strings using the powerful methods
provided by Java’s String class.

9.6 Declaring and Initializing Strings


Before a string can be used in a Java program, it must first be declared and initialized.
Declaring a string creates a variable capable of storing textual data, while initializing a
string assigns an actual value to that variable.
Since strings are objects in Java, they are created using the String class. Java
provides two primary methods for creating String objects:

1. Using a string literal.

2. Using the new keyword and the String constructor.

Both methods create strings that can store and manipulate text, but they differ in
how Java allocates memory and manages the resulting String objects.

9.6.1 Method 1: String Literal


The simplest and most commonly used way to create a string is by using a string literal.
A string literal is a sequence of characters enclosed within double quotation marks.
String name = "Aminu";

In this statement:

• String specifies the data type.

• name is the variable name.

• "Aminu" is the string literal.

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.

Advantages of Using String Literals

Using string literals offers several benefits:

• Simpler and easier to read.

• Requires less code.

• Improves memory efficiency through the String Pool.

• Generally provides better performance.

• Widely used in professional Java applications.

Examples:
String university = "Northwest University Kano";
String course = "Computer Science";
String country = "Nigeria";

9.6.2 Method 2: Using the new Keyword


Another way to create a string is by explicitly creating a String object using the new
keyword.
String name = new String("Aminu");

In this approach:

• new instructs Java to create a new object.

• String("Aminu") calls the String constructor.

• A separate String object is created in memory.

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

Advantages of Using the new Keyword

Although less commonly used, creating strings with new has certain advantages:

• Guarantees the creation of a new object.

• Useful when object uniqueness is required.

• Helpful when studying object-oriented concepts.

• Can be useful in advanced memory management scenarios.

9.6.3 Comparison of the Two Methods


The following table summarizes the differences between the two approaches:

Feature String Literal Using new Key-


word
Syntax String s = "Java"; String s = new
String("Java");
Memory Usage More efficient Less efficient
Uses String Pool Yes No (creates new ob-
ject)
Performance Faster Slightly slower
Common Usage Very common Less common
Object Creation Reuses existing ob- Always creates a new
jects when possible object

9.6.4 Declaring a String Without Initialization


A string variable may also be declared without assigning a value immediately.
Example:
String name;

Later, a value can be assigned:


name = "Aminu";

Complete example:
String name;

name = "Aminu";

[Link](name);

153
COS 201: Computer Programming I Lecture Notes

Output

Aminu

9.6.5 Declaring Multiple Strings


Multiple string variables can be declared in a single statement.
Example:
String firstName, lastName, department;

They can then be initialized individually:


firstName = "Fatima";
lastName = "Ali";
department = "Computer Science";

Alternatively:
String firstName = "Fatima",
lastName = "Ali",
department = "Computer Science";

9.6.6 Example Program


The following program demonstrates both methods of creating strings.
public class StringCreationDemo {

public static void main(String[] args) {

String name1 = "Aminu";

String name2 = new String("Aminu");

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

9.6.7 Best Practices


When working with strings in Java, consider the following recommendations:

• Prefer string literals whenever possible.

• Use meaningful variable names.

• Avoid creating unnecessary String objects with new.

• Initialize variables before use.

• Follow standard naming conventions for readability.

9.6.8 Key Points


1. Strings are objects of the String class.

2. Strings can be created using string literals or the new keyword.

3. String literals are stored in the String Pool.

4. The String Pool improves memory efficiency by reusing existing strings.

5. The new keyword always creates a new String object.

6. String literals are generally preferred in Java programming.

7. String variables can be declared with or without immediate initialization.

8. Multiple string variables can be declared and initialized together.

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.

9.7 Displaying Strings


One of the most common operations performed on strings is displaying their contents to
the user. In Java, strings are typically displayed on the screen using the [Link]()
method. This method outputs the specified text and then moves the cursor to the next
line.

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

Northwest University Kano

In this example:

• A String variable named university is declared and initialized.

• The value assigned to the variable is "Northwest University Kano".

• The [Link]() method displays the contents of the variable.

When the program executes, Java retrieves the value stored in the variable and prints
it on the screen.

9.7.1 Understanding [Link]()


The statement
[Link](university);

contains three important components:

• System – A built-in Java class that provides access to system resources.

• out – A standard output stream connected to the console.

• 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

9.7.2 Displaying a String Literal Directly


A string can be displayed without first storing it in a variable.
Example:
[Link]("Welcome to Java Programming");

Output

Welcome to Java Programming

Here, the string literal is sent directly to the println() method.

9.7.3 Displaying Multiple Strings


Multiple strings can be displayed by using several println() statements.
Example:
[Link]("Northwest University Kano");
[Link]("Faculty of Computing");
[Link]("Computer Science Department");

Output

Northwest University Kano


Faculty of Computing
Computer Science Department

Each call to println() starts a new line.

9.7.4 Using print() Instead of println()


Java also provides the print() method.
Example:
[Link]("Hello ");
[Link]("World");

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

9.7.5 Displaying String Variables


String variables can be displayed just like other data types.
Example:
String firstName = "Amina";
String lastName = "Yusuf";

[Link](firstName);
[Link](lastName);

Output

Amina
Yusuf

The values stored inside the variables are displayed rather than the variable names
themselves.

9.7.6 Combining Text and Variables


A string variable can be displayed together with descriptive text.
Example:
String name = "Aminu";

[Link]("Student Name: " + name);

Output

Student Name: Aminu

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

University: Northwest University Kano

9.7.7 Displaying Several String Variables


Multiple string variables can be displayed in a single statement.
Example:
String firstName = "Muktar";
String lastName = "Danlami";

[Link](
firstName + " " + lastName);

Output

Muktar Danlami

Notice the space character (" ") placed between the two names to improve readability.

9.7.8 Displaying Formatted Information


Strings are often used to create organized output.
Example:
String name = "Usman Haruna";
String department =
"Computer Science";

[Link]("Name: " + name);


[Link]("Department: " + department);

Output

Name: Usman Haruna


Department: Computer Science

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 {

public static void main(String[] args) {

String university =
"Northwest University Kano";

String course =
"Java Programming";

[Link](university);

[Link](course);

[Link](
"Welcome to " + course);

[Link](
"Institution: " + university);
}
}

Output

Northwest University Kano


Java Programming
Welcome to Java Programming
Institution: Northwest University Kano

9.7.9 Common Errors When Displaying Strings


Beginners often make mistakes when displaying strings. Some common errors include:

1. Forgetting quotation marks around string literals.


[Link](Hello);

This produces an error because Java assumes Hello is a variable name.


Correct version:

160
COS 201: Computer Programming I Lecture Notes

[Link]("Hello");

2. Using an undeclared variable.


[Link](name);

If name has not been declared, the program will not compile.

3. Misspelling variable names.


String university =
"Northwest University Kano";

[Link](universty);

The variable name is misspelled, resulting in a compilation error.

9.7.10 Best Practices


When displaying strings, follow these recommendations:

• Use meaningful variable names.

• Include descriptive labels in output.

• Use proper spacing to improve readability.

• Use println() when output should appear on separate lines.

• Use print() when output should remain on the same line.

• Check spelling carefully when referencing variables.

9.7.11 Key Points


1. Strings are displayed using [Link]() or [Link]().

2. println() displays text and moves to a new line.

3. print() displays text without moving to a new line.

4. String variables can be displayed directly.

5. String literals can be displayed without variables.

6. The concatenation operator (+) can combine strings and variables.

161
COS 201: Computer Programming I Lecture Notes

7. Proper formatting improves the readability of program output.

8. Displaying strings is one of the most frequently used operations in Java program-
ming.

Being able to display strings effectively is a fundamental programming skill. It allows


programs to communicate with users, present results, display instructions, and provide
meaningful feedback during program execution.

9.8 String Immutability


Strings in Java are immutable.
This means that once a string object is created, its contents cannot be changed.
Example
String text = "Java";

text = text + " Programming";

A new string object is created rather than modifying the original string.

9.9 String Concatenation


Concatenation means joining strings together.
The concatenation operator is +.
Example
String firstName = "Aminu";
String lastName = "Mahmoud";

String fullName =
firstName + " " + lastName;

[Link](fullName);

Output

Aminu Mahmoud

9.10 Concatenating Strings and Variables

162
COS 201: Computer Programming I Lecture Notes

String name = "Fatima";


int age = 21;

[Link](
"Name: " + name +
", Age: " + age
);

Output

Name: Fatima, Age: 21

9.11 Common String Methods


The String class provides many built-in methods that allow programmers to manipulate,
analyze, and process text efficiently. These methods eliminate the need to manually
examine each character in a string and make string operations easier and more reliable.
String methods are called using the dot operator (.) after a String object. The general
syntax is:
[Link]();

For example:
String text = "Java";

[Link]([Link]());

Here, the length() method is called on the String object text.


The following sections discuss some of the most commonly used String methods in
Java.

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

String text = "Computer";

[Link]([Link]());

Output

The string "Computer" contains eight characters.


Another example:
String text = "Hello World";

[Link]([Link]());

Output

11

Notice that the space between Hello and World is counted as a character.

Applications

The length() method is useful for:

• Validating passwords.

• Checking input length.

• Counting characters in text.

• Processing strings in loops.

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

String text = "Java";

[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

Attempting to access an index outside the valid range causes an exception.


Example:
String text = "Java";

[Link]([Link](10));

This produces a StringIndexOutOfBoundsException.

Applications

• Extracting individual characters.

• Processing user input.

• Checking specific characters.

• Building text-processing 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

String text = "java";

[Link](
[Link]()
);

Output

JAVA

Another example:
String text = "Computer Science";

[Link](
[Link]()
);

Output

COMPUTER SCIENCE

Applications

• Standardizing user input.

• Formatting reports.

• Performing case-insensitive comparisons.

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

String text = "JAVA";

[Link](
[Link]()
);

Output

java

Another example:
String text = "COMPUTER SCIENCE";

[Link](
[Link]()
);

Output

computer science

Applications

• Data normalization.

• Search functionality.

• User input validation.

9.11.5 equals()
The equals() method compares the actual contents of two strings.
It returns:

• true if both strings contain exactly the same characters.

• 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

Example with different strings:


String s1 = "Java";
String s2 = "Python";

[Link](
[Link](s2)
);

Output

false

Important Note

Do not use == when comparing string contents.


Incorrect:
s1 == s2

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.

• User-friendly text comparisons.

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

The exact value may vary, but:

• Negative value: first string comes before second string.

• Zero: strings are equal.

• Positive value: first string comes after second string.

Examples:

Expression Result Meaning


"Apple".compareTo("Banana") Negative Apple comes first
"Java".compareTo("Java") 0 Equal strings
"Zoo".compareTo("Apple") Positive Zoo comes after Apple

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

9.11.9 Summary of Common String Methods


Method Purpose
length() Returns the number of characters in a string.
charAt() Returns a character at a specified index.
toUpperCase() Converts all letters to uppercase.
toLowerCase() Converts all letters to lowercase.
equals() Compares string contents exactly.
Compares strings without considering letter case.
equalsIgnoreCase()
compareTo() Compares strings alphabetically.
contains() Checks whether a string contains specific text.
These methods form the foundation of string manipulation in Java. Mastering them
will enable you to validate input, search text, compare strings, process user data, and
build more sophisticated applications.

9.12 startsWith() and endsWith()


When working with textual data, it is often necessary to determine whether a string begins
or ends with a particular sequence of characters. Java provides two useful methods for
this purpose:

• startsWith() — Checks whether a string begins with a specified prefix.

• endsWith() — Checks whether a string ends with a specified suffix.

Both methods return a Boolean value:

• true if the condition is satisfied.

• false otherwise.

These methods are commonly used in file processing, data validation, web applica-
tions, search systems, and user input verification.

9.12.1 The startsWith() Method


The startsWith() method checks whether a string begins with a specified sequence of
characters.

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

String text = "Programming";

[Link](
[Link]("Pro")
);

Output

true

The output is true because the string "Programming" begins with the characters
"Pro".

Example 2

String text = "Programming";

[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

The startsWith() method is case-sensitive.


Example:
String text = "Programming";

[Link](
[Link]("pro")
);

Output

false

Although the letters are the same, the method distinguishes between uppercase and
lowercase characters.

Applications of startsWith()

The startsWith() method is useful for:

• Validating usernames.

• Checking file names.

• Verifying URL prefixes.

• Searching text patterns.

• Input validation.

Example:
String website =
"[Link]

if([Link]("https"))
{
[Link](
"Secure website"
);
}

174
COS 201: Computer Programming I Lecture Notes

9.12.2 The endsWith() Method


The endsWith() method checks whether a string ends with a specified sequence of char-
acters.

Syntax

[Link](suffix);

where suffix represents the text to be checked at the end of the string.

endsWith() Example

String text = "Programming";

[Link](
[Link]("ing")
);

Output

true

The output is true because the string "Programming" ends with "ing".

Example 2

String text = "Programming";

[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

String filename = "[Link]";

[Link](
[Link](".pdf")
);

Output

true

Case Sensitivity

Like startsWith(), the endsWith() method is also case-sensitive.


Example:
String filename = "[Link]";

[Link](
[Link](".pdf")
);

Output

false

The result is false because PDF and pdf are considered different.

Applications of endsWith()

The endsWith() method is commonly used for:

• Checking file extensions.

• Validating email addresses.

• Verifying URL endings.

• Detecting document formats.

• Data filtering.

Example:

176
COS 201: Computer Programming I Lecture Notes

String file = "[Link]";

if([Link](".docx"))
{
[Link](
"Word document detected"
);
}

9.12.3 Using Both Methods Together


In many applications, both methods are used together to perform more comprehensive
validation.
Example:
String email =
"student@[Link]";

if([Link]("@") &&
[Link](".com"))
{
[Link](
"Valid email format"
);
}

Output

Valid email format

Practical Example
The following program demonstrates both methods:
public class StartsEndsDemo {

public static void main(String[] args) {

String course =
"Java Programming";

[Link](

177
COS 201: Computer Programming I Lecture Notes

[Link]("Java"));

[Link](
[Link]("ming"));
}
}

Output

true
true

9.12.4 Comparison of startsWith() and endsWith()


Feature startsWith() endsWith()
Purpose Checks the beginning of a Checks the end of a string
string
Return Type Boolean (true/false) Boolean (true/false)
Case Sensitive Yes Yes
Common Uses URLs, prefixes, usernames File extensions, suffixes,
email validation

9.12.5 Common Errors


Beginners often make the following mistakes:

1. Ignoring case sensitivity.


[Link]("pro");

This returns false if the string begins with "Pro".

2. Checking the wrong position in the string.


[Link]("Pro");

This returns false because "Pro" appears at the beginning rather than the end.

3. Forgetting quotation marks.


[Link](Pro);

This causes a compilation error because Java interprets Pro as a variable name.

178
COS 201: Computer Programming I Lecture Notes

9.12.6 Key Points


1. startsWith() checks whether a string begins with a specified prefix.

2. endsWith() checks whether a string ends with a specified suffix.

3. Both methods return a Boolean value.

4. Both methods are case-sensitive.

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

9.13.2 Example: Finding a Character

String text = "Computer";

[Link](
[Link](’p’)
);

179
COS 201: Computer Programming I Lecture Notes

Output

The character positions in the string are:

C o m p u t e r
0 1 2 3 4 5 6 7

Since the character ’p’ is located at index 3, the method returns 3.

9.13.3 Example: Finding a Substring

String text = "Computer Science";

[Link](
[Link]("Science")
);

Output

The substring "Science" begins at index 9.

9.13.4 When the Character Does Not Exist


If the specified character or substring is not found, the method returns -1.
Example:
String text = "Computer";

[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

9.13.5 Finding Spaces


The method can also locate spaces.
Example:
String text =
"Northwest University Kano";

[Link](
[Link](’ ’)
);

Output

This output indicates the position of the first space character.

9.13.6 Applications of indexOf()


The indexOf() method is commonly used for:

• Searching for characters or words.

• Locating delimiters in text.

• Parsing strings.

• Validating email addresses.

• Processing file names.

• Extracting information from larger strings.

Example:
String email =
"student@[Link]";

[Link](
[Link](’@’)
);

Output

The output identifies the location of the @ symbol.

181
COS 201: Computer Programming I Lecture Notes

9.13.7 Important Notes


• Indexing begins at 0.

• Only the first occurrence is returned.

• Returns -1 if the text is not found.

• The search is case-sensitive.

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.

9.14.1 Why Use substring()?


Suppose a string contains multiple pieces of information:
String course = "Java Programming";

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

Extracts characters beginning at startIndex and ending just before endIndex.

Example: Extracting a Portion of a String

String text = "Programming";

[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

The extraction begins at index 0 and stops before index 7.


Therefore, the characters returned are:

Program

Example: Extracting from a Starting Position

String text = "Programming";

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

Example: Extracting a Name


String fullName =
"Amina Yusuf";

[Link](
[Link](0, 5)
);

Output
Amina

Example: Extracting a File Extension


String file =
"[Link]";

[Link](
[Link](6)
);

Output
.pdf
This technique is often used when processing files.

9.14.3 Applications of substring()


The substring() method is useful for:
• Extracting names.

• Processing dates.

• Separating file names and extensions.

• Parsing user input.

• Reading formatted text.

• Extracting specific sections of strings.

184
COS 201: Computer Programming I Lecture Notes

9.14.4 Important Notes


• The starting index is included.

• The ending index is excluded.

• The original string remains unchanged.

• Invalid index values produce a StringIndexOutOfBoundsException.

Example:
String text = "Java";

[Link](
[Link](10)
);

This generates an exception because index 10 does not exist.

9.14.5 Comparison of indexOf() and substring()


Method Purpose Return Type
indexOf() Finds the position of a char- int
acter or substring
substring() Extracts part of a string String

9.14.6 Key Points


1. indexOf() returns the position of a character or substring.

2. indexOf() returns -1 when the text is not found.

3. substring() extracts a portion of a string.

4. The starting index is included in the extraction.

5. The ending index is excluded from the extraction.

6. Both methods are widely used in text processing applications.

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.

9.15.1 Why Use replace()?


Consider the following string:
String text = "Java";

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

9.15.3 Example: Replacing a Word

String text = "Java";

[Link](
[Link](
"Java",

186
COS 201: Computer Programming I Lecture Notes

"Python"
)
);

Output

Python

The word "Java" is replaced with "Python".

9.15.4 Example: Replacing Characters

String text = "banana";

[Link](
[Link](’a’, ’o’)
);

Output

bonono

Every occurrence of the character ’a’ is replaced with ’o’.

9.15.5 Example: Replacing Multiple Words

String sentence =
"I love Java";

[Link](
[Link](
"Java",
"Programming"
)
);

Output

I love Programming

187
COS 201: Computer Programming I Lecture Notes

9.15.6 Example: Replacing Spaces

String text =
"Computer Science";

[Link](
[Link](" ", "-")
);

Output

Computer-Science

This technique is useful when creating file names or web addresses.

9.15.7 Original String Remains Unchanged


The original string is not modified.
Example:
String text = "Java";

String newText =
[Link](
"Java",
"Python"
);

[Link](text);
[Link](newText);

Output

Java
Python

Notice that the variable text still contains "Java".

9.15.8 Applications of replace()


The replace() method is commonly used for:

• Correcting text.

• Replacing words in documents.

188
COS 201: Computer Programming I Lecture Notes

• Formatting user input.

• Removing unwanted characters.

• Creating file names and URLs.

• Data cleaning and preprocessing.

9.15.9 Important Notes


• The original string is not changed.

• All occurrences are replaced.

• The method returns a new string.

• The replacement is case-sensitive.

Example:
String text = "Java";

[Link](
[Link](
"java",
"Python"
)
);

Output

Java

Since "java" and "Java" are different, no replacement occurs.

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

9.16.1 Why Use trim()?


Suppose a user enters:

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]();

Example: Removing Extra Spaces


String text = " Java ";

[Link](
[Link]()
);

Output

Java

The spaces before and after the word are removed.

Example: User Input Processing


String username =
" student123 ";

[Link](
[Link]()
);

Output

student123

This ensures that the username is stored correctly.

190
COS 201: Computer Programming I Lecture Notes

Example: Comparing Strings After Trimming

String s1 = " Java ";


String s2 = "Java";

[Link](
[Link]().equals(s2)
);

Output

true

Without trimming, the comparison would return false because the spaces are con-
sidered part of the string.

9.16.3 Spaces Inside a String Are Not Removed


The trim() method only removes spaces at the beginning and end of a string.
Example:
String text =
"Computer Science";

[Link](
[Link]()
);

Output

Computer Science

The space between the words remains unchanged.

9.16.4 Original String Remains Unchanged

String text = " Java ";

String cleaned =
[Link]();

[Link](text);
[Link](cleaned);

191
COS 201: Computer Programming I Lecture Notes

Output

Java
Java

The original string still contains the spaces.

9.16.5 Applications of trim()


The trim() method is useful for:

• Cleaning user input.

• Processing form data.

• Comparing strings accurately.

• Removing accidental spaces.

• Preparing data for storage.

• Validating usernames and passwords.

9.16.6 Important Notes


• Removes whitespace only at the beginning and end of a string.

• Does not remove spaces between words.

• Returns a new string.

• The original string remains unchanged.

9.16.7 Comparison of replace() and trim()


Method Purpose Return Type
replace() Replaces characters or sub- String
strings
trim() Removes leading and trail- String
ing spaces

192
COS 201: Computer Programming I Lecture Notes

9.16.8 Key Points


1. replace() substitutes characters or substrings with new values.

2. replace() replaces all matching occurrences.

3. trim() removes whitespace at the beginning and end of a string.

4. trim() does not remove spaces between words.

5. Both methods return new strings.

6. Neither method changes the original string.

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.

9.17 String Comparison


Comparing strings is one of the most common operations in Java programming. Devel-
opers often need to determine whether two strings contain the same text, whether they
differ, or whether one comes before another alphabetically.
A common mistake made by beginners is using the == operator to compare strings.
Although this may sometimes appear to work, it is not the correct way to compare the
contents of strings.
To understand why, it is important to know the difference between a string object’s
reference and its actual content.

9.17.1 References vs Contents


Every String in Java is an object. When a String object is created, it is stored somewhere
in memory, and the variable stores a reference (memory address) to that object.
Therefore, there are two things that can be compared:

1. The memory locations (references).

2. The actual text stored inside the strings (contents).

The == operator compares references, while the equals() method compares contents.

193
COS 201: Computer Programming I Lecture Notes

9.17.2 Incorrect Comparison Using ==


String s1 = "Java";
String s2 = "Java";

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.

Example Demonstrating the Problem


String s1 = new String("Java");
String s2 = new String("Java");

[Link](s1 == s2);

Output

false

Although both strings contain the word:

Java

the result is false because two separate String objects were created in memory.

9.17.3 Memory Illustration


s1 -----> "Java"

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

9.17.4 Correct Comparison Using equals()


The proper way to compare strings is with the equals() method.
String s1 = "Java";
String s2 = "Java";

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

String firstName = "Amina";


String secondName = "Amina";

[Link](
[Link](secondName)
);

Output

true

Since both strings contain exactly the same sequence of characters, the result is true.

9.17.5 Case Sensitivity


The equals() method is case-sensitive.
Example:
String s1 = "JAVA";
String s2 = "java";

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

9.17.6 Ignoring Letter Case


If case should be ignored, use the equalsIgnoreCase() method.
String s1 = "JAVA";
String s2 = "java";

[Link](
[Link](s2)
);

Output

true

This method compares the strings without considering differences in letter case.

Practical Example: Username Validation

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.

9.17.7 Comparing User Input


When accepting user input, it is usually a good idea to remove unnecessary spaces before
comparison.
String password =
"java123";

String entered =
" java123 ";

[Link](
[Link](
[Link]()
)
);

Output

true

The trim() method removes leading and trailing spaces before comparison.

9.17.8 Summary of Comparison Methods


Method Purpose Return Type
== Compares object references boolean
equals() Compares string contents boolean
equalsIgnoreCase() Compares contents ignoring case boolean

9.17.9 Important Notes


• Strings are objects in Java.

• The == operator compares memory references.

• The equals() method compares actual string contents.

• The equals() method is case-sensitive.

197
COS 201: Computer Programming I Lecture Notes

• The equalsIgnoreCase() method ignores uppercase and lowercase differences.

• For content comparison, always prefer equals() or equalsIgnoreCase().

9.17.10 Key Points


1. Do not use == to compare string contents.

2. Use equals() when exact matching is required.

3. Use equalsIgnoreCase() when case should be ignored.

4. String comparison is essential for validation and decision-making.

5. Understanding the difference between references and contents helps prevent pro-
gramming errors.

String comparison is a fundamental concept in Java programming. While the ==


operator checks whether two variables refer to the same object, the equals() method
checks whether the actual text stored in the strings is the same. For reliable and accurate
comparisons, programmers should use equals() or equalsIgnoreCase() rather than the
== operator.

9.18 The Character Class


In Java, characters are represented using the primitive data type char. A char stores a
single character enclosed in single quotation marks.
Examples:
’A’
’B’
’7’
’#’

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.

9.18.1 Why Use the Character Class?


The Character class allows programmers to answer questions such as:

198
COS 201: Computer Programming I Lecture Notes

• Is this character a letter?

• Is this character a digit?

• Is this character uppercase?

• Is this character lowercase?

• Is this character whitespace?

• How can I convert a character to uppercase or lowercase?

These operations are very common when processing text, validating user input, and
developing data-entry applications.

9.18.2 Creating Character Variables


A character variable is declared using the char keyword.
Example:
char grade = ’A’;

[Link](grade);

Output

Notice that characters are enclosed in single quotation marks (’ ’), whereas strings
use double quotation marks (" ").

9.18.3 Character vs String


It is important to understand the difference between a character and a string.

Character String
Stores one character Stores multiple characters
Uses char Uses String
Single quotes Double quotes
’A’ "A"

Example:
char letter = ’J’;

String word = "Java";

199
COS 201: Computer Programming I Lecture Notes

9.18.4 Common Character Class Methods


The Character class contains many useful static methods.
Some of the most frequently used methods include:

• isLetter()

• isDigit()

• isUpperCase()

• isLowerCase()

• isWhitespace()

• toUpperCase()

• toLowerCase()

These methods are called using the class name Character.


Example:
[Link](’A’);

9.18.5 Advantages of the Character Class


The Character class provides several benefits:

• Simplifies character validation.

• Makes text processing easier.

• Supports conversion between uppercase and lowercase characters.

• Helps detect digits and letters.

• Improves program readability.

9.18.6 Applications of the Character Class


The Character class is widely used in:

• Form validation.

• Password verification.

• Text editors.

200
COS 201: Computer Programming I Lecture Notes

• Search applications.

• Data processing systems.

• Educational software.

For example, a program may verify whether a user’s input contains only letters and
numbers before accepting it.

9.18.7 Important Notes


• The Character class works with individual characters.

• Most Character methods are static methods.

• Characters use single quotation marks.

• Strings use double quotation marks.

• Character methods are useful when processing text one character at a time.

9.18.8 Key Points


1. Java provides the Character class for character manipulation.

2. A char stores a single character.

3. Character values are enclosed in single quotation marks.

4. The Character class contains methods for testing and converting characters.

5. Common methods include isLetter(), isDigit(), and toUpperCase().

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.

9.19 Character Methods


The Character class provides numerous methods that allow programmers to test, ana-
lyze, and convert individual characters.
These methods are particularly useful when validating user input, processing text
files, checking passwords, and working with strings character by character.

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:

• true if the character is a letter.

• false otherwise.

Syntax

[Link](character);

Example

[Link](
[Link](’A’)
);

Output

true

Since ’A’ is a letter, the method returns true.

Another Example

[Link](
[Link](’9’)
);

Output

false

The character ’9’ is a digit, not a letter.

202
COS 201: Computer Programming I Lecture Notes

Applications

• Name validation.

• Checking alphabetic input.

• Text processing.

9.19.2 isDigit()
The isDigit() method determines whether a character is a numeric digit.
It returns:

• true if the character is a digit.

• false otherwise.

Syntax

[Link](character);

Example

[Link](
[Link](’7’)
);

Output

true

Since ’7’ is a digit, the method returns true.

Another Example

[Link](
[Link](’A’)
);

Output

false

Because ’A’ is a letter, not a digit.

203
COS 201: Computer Programming I Lecture Notes

Applications

• Number validation.

• Processing identification numbers.

• Reading numerical input.

9.20 isUpperCase()
The isUpperCase() method checks whether a character is an uppercase letter.
It returns:

• true if the character is uppercase.

• false otherwise.

Syntax

[Link](character);

Example

[Link](
[Link](’A’)
);

Output

true

Another Example

[Link](
[Link](’a’)
);

Output

false

The letter ’a’ is lowercase, so the method returns false.

204
COS 201: Computer Programming I Lecture Notes

Applications
• Password validation.

• Text formatting.

• Checking naming conventions.

9.21 isLowerCase()
The isLowerCase() method checks whether a character is a lowercase letter.
It returns:

• true if the character is lowercase.

• false otherwise.

Syntax

[Link](character);

Example

[Link](
[Link](’a’)
);

Output

true

Another Example

[Link](
[Link](’A’)
);

Output

false

The letter ’A’ is uppercase, so the method returns 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

The lowercase letter ’a’ is converted to uppercase.

Another Example

[Link](
[Link](’Z’)
);

Output

Since ’Z’ is already uppercase, no change occurs.

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

The uppercase letter ’A’ is converted to lowercase.

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

9.24 Summary Table


Method Purpose
isLetter() Checks whether a character is a letter
isDigit() Checks whether a character is a digit
isUpperCase() Checks whether a character is upper-
case
isLowerCase() Checks whether a character is lowercase
toUpperCase() Converts a character to uppercase
toLowerCase() Converts a character to lowercase

9.25 Key Points


1. The Character class provides methods for analyzing characters.

2. isLetter() checks whether a character is alphabetic.

3. isDigit() checks whether a character is numeric.

4. isUpperCase() and isLowerCase() determine character case.

5. toUpperCase() converts characters to uppercase.

6. toLowerCase() converts characters to lowercase.

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.

9.26 Processing Individual Characters


In many programming tasks, it is necessary to examine a string one character at a time.
This process is known as character-by-character processing.
Instead of treating a string as a single block of text, a program can access each
individual character and perform operations such as:

• Counting digits.

• Counting letters.

209
COS 201: Computer Programming I Lecture Notes

• Counting uppercase or lowercase characters.

• Searching for special symbols.

• Validating passwords.

• Analyzing user input.

Character processing is usually performed using a loop together with:

• length() — to determine the number of characters.

• charAt() — to access individual characters.

• Character class methods such as isDigit() and isLetter().

9.26.1 Accessing Characters One at a Time


Consider the following string:
String text = "Java";

The characters are stored as:

J a v a
0 1 2 3

Using a loop, we can access each character individually.


String text = "Java";

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

Example: Counting Digits


One common application is counting the number of digits contained in a string.
String text = "CSC101";

int count = 0;

for(int i = 0;
i < [Link]();
i++)
{
if([Link](
[Link](i)))
{
count++;
}
}

[Link](count);

Output

How the Program Works

The string contains:

C S C 1 0 1

The loop examines each character:

Character Digit?
C No
S No
C No
1 Yes
0 Yes
1 Yes

Since three characters are digits, the value of count becomes:

211
COS 201: Computer Programming I Lecture Notes

Example: Counting Letters


The same technique can be used to count letters.
String text = "CSC101";

int letters = 0;

for(int i = 0;
i < [Link]();
i++)
{
if([Link](
[Link](i)))
{
letters++;
}
}

[Link](letters);

Output

The letters are:

C
S
C

Therefore, the count is 3.

Example: Counting Uppercase Letters

String text = "Java Programming";

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

Example: Counting Lowercase Letters


String text = "Java";

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

Example: Counting Spaces


Spaces can also be counted.
String text =
"Northwest University Kano";

int spaces = 0;

for(int i = 0;
i < [Link]();
i++)
{
if([Link](i) == ’ ’)
{
spaces++;
}
}

[Link](spaces);

Output

There are two spaces in the string.

Example: Converting to Uppercase


Character processing can also be used to modify text.
String text = "java";

for(int i = 0;
i < [Link]();
i++)
{
[Link](
[Link](
[Link](i)
)
);
}

Output

214
COS 201: Computer Programming I Lecture Notes

JAVA

Each character is converted individually.

Example: Password Validation


Suppose a password must contain at least one digit.
String password =
"java123";

boolean hasDigit = false;

for(int i = 0;
i < [Link]();
i++)
{
if([Link](
[Link](i)))
{
hasDigit = true;
}
}

[Link](hasDigit);

Output

true

Because the password contains digits, the result is true.

9.26.2 General Pattern for Character Processing


Most character-processing programs follow the same structure:
for(int i = 0;
i < [Link]();
i++)
{
char ch =
[Link](i);

// Process ch
}

215
COS 201: Computer Programming I Lecture Notes

Explanation:

1. Start at the first character.

2. Move through each character using a loop.

3. Extract the character using charAt().

4. Perform a test or operation.

5. Continue until all characters have been processed.

9.26.3 Applications of Character Processing


Character-by-character processing is used in:

• Password validation.

• Form validation.

• Text editors.

• Search engines.

• Compilers and interpreters.

• Data cleaning.

• File processing.

• Natural language processing.

9.26.4 Important Notes


• Use length() to determine the number of characters.

• Use charAt() to access individual characters.

• Character methods help classify characters.

• Loops are essential for processing entire strings.

• Index values begin at 0.

216
COS 201: Computer Programming I Lecture Notes

9.26.5 Summary Table


Operation Method Used
Count digits [Link]()
Count letters [Link]()
Count uppercase letters [Link]()
Count lowercase letters [Link]()
Convert to uppercase [Link]()
Convert to lowercase [Link]()
Access character charAt()
Determine string length length()

9.26.6 Key Points


1. Strings can be processed one character at a time.

2. Use loops together with charAt().

3. The Character class provides methods for testing characters.

4. Character processing is useful for validation and text analysis.

5. Counting digits, letters, and spaces are common applications.

6. Password checking often relies on character processing.

7. Character-by-character analysis is a fundamental programming technique.

Processing individual characters is a powerful technique that combines strings, loops,


conditional statements, and Character class methods. It enables Java programs to ana-
lyze, validate, and manipulate text efficiently and is widely used in real-world software
applications.

Practical Example: Counting Vowels


String text =
"Northwest University";

int vowels = 0;

for(int i = 0; i < [Link](); i++)


{

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

Practical Example: Reverse a String


String text = "Java";

for(int i = [Link]()-1;
i >= 0;
i--)
{
[Link](
[Link](i)
);
}

Output

avaJ

9.27 StringBuilder Class


When frequent modifications are required, Java provides the StringBuilder class.
Example

218
COS 201: Computer Programming I Lecture Notes

StringBuilder sb =
new StringBuilder("Java");

[Link](" Programming");

[Link](sb);

Output

Java Programming

9.28 Common StringBuilder Methods

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

Table 9.3: Common StringBuilder Methods

9.29 Applications of String Processing


String processing is widely used in:

• User authentication systems

• Search engines

• Text editors

• Email processing

• Data validation

• Chat applications

• Web development

• Database systems

• Natural Language Processing (NLP)

219
COS 201: Computer Programming I Lecture Notes

9.30 Common Programming Errors


1. Using == instead of equals().

2. Accessing invalid string indexes.

3. Forgetting that strings are immutable.

4. Confusing single and double quotation marks.

5. Ignoring case sensitivity during comparisons.

6. Using incorrect substring boundaries.

9.31 Best Practices


• Use equals() for string comparison.

• Validate string input before processing.

• Use StringBuilder for repeated modifications.

• Handle empty strings properly.

• Use meaningful variable names.

• Consider case sensitivity when comparing text.

9.32 Chapter Summary


This chapter explored how Java represents and manipulates textual data using characters
and strings. A single character is stored using the char data type, which is capable
of representing letters, digits, symbols, and special characters. Java uses the Unicode
character set, enabling programs to work with text from many different languages and
writing systems around the world.
The chapter also discussed that strings in Java are objects created from the String
class. A string represents a sequence of characters and is one of the most commonly
used data types in Java programming. Strings can be created using string literals or by
constructing String objects. Unlike primitive data types, strings are reference types and
provide a rich collection of methods for manipulating text.
An important characteristic of strings is that they are immutable. Once a string
object has been created, its contents cannot be changed. Operations that appear to
modify a string actually create and return a new string object. This design improves

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

9.33 Review Questions and Exercises


The following questions and programming exercises are designed to reinforce the concepts
covered in this chapter. Attempt all questions and write complete Java programs where
required.

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 (" ").

4. What is Unicode? Why is Unicode important in modern programming?

5. Explain the purpose of the char data type.

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?

8. What is string concatenation? Describe two ways of concatenating strings in Java.

9. Explain the purpose of escape sequences and provide three examples.

10. What is the role of the Character class in Java?

11. Differentiate between the methods charAt() and substring().

12. Explain the purpose of the length() method.

13. Differentiate between equals() and == when comparing strings.

14. Explain the purpose of the following methods:

(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

16. Explain why string processing is important in software development.

17. Discuss five real-world applications of string processing.

18. Explain how loops can be used to process strings character by character.

19. Describe how the methods [Link]() and [Link]() can


be used in input validation.

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:

(a) The original string.


(b) Its length.
(c) The first character.
(d) The last character.

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.

25. Write a program that counts the number of characters in a sentence.

26. Write a program that counts the number of vowels in a sentence.

27. Write a program that counts the number of consonants in a sentence.

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.

31. Write a program that counts the number of spaces in a sentence.

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.

40. Write a program that reverses a string.

41. Write a program that checks whether a string is a palindrome.

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.

46. Write a program that displays all digits found in a string.

47. Write a program that displays all letters found in a string.

48. Write a program that removes all digits from a string.

49. Write a program that creates a sentence using StringBuilder and appends three
additional words.

50. Write a program that uses StringBuilder to reverse a string.

Challenge Exercises
1. Write a program that counts the number of words in a sentence.

2. Write a program that determines the longest word in a sentence.

3. Write a program that counts the frequency of each vowel in a string.

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.

6. Write a program that removes duplicate characters from a string.

224
COS 201: Computer Programming I Lecture Notes

7. Write a program that validates an email address using string-processing techniques.

8. Write a program that masks all digits in a phone number except the last four digits.

9. Write a program that compresses consecutive repeated characters. For example:

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.

10.2 Learning Objectives


After studying this chapter, you should be able to:

• Define an array.

• Explain the advantages and limitations of arrays.

• Declare and initialize arrays.

• Access and modify array elements.

226
COS 201: Computer Programming I Lecture Notes

• Traverse arrays using loops.

• Perform common array operations.

• Work with multidimensional arrays.

• Use enhanced for loops with arrays.

• Apply arrays in real-world programming problems.

10.3 What is an Array?


An array is a fixed-size collection of elements of the same data type.
Characteristics of arrays include:

• All elements must have the same data type.

• Elements are stored in consecutive memory locations.

• Each element is identified by an index.

• Array size is fixed after creation.

• Indexing starts from zero.

10.3.1 Array Representation


Consider the following array:
int[] scores = {78, 85, 92, 67, 88};

78 85 92 67 88
0 1 2 3 4
The numbers in the second row represent the array indices.

10.4 Advantages of Arrays


Arrays offer several benefits:

1. Efficient storage of multiple values.

2. Easy access to elements using indices.

3. Simplifies program design.

4. Reduces the number of variables needed.

5. Facilitates data processing using loops.

227
COS 201: Computer Programming I Lecture Notes

10.5 Limitations of Arrays


Despite their usefulness, arrays have limitations:

1. Fixed size after creation.

2. Can store only one data type.

3. Insertion and deletion operations may be inefficient.

4. Memory may be wasted if the array is larger than required.

10.6 Declaring Arrays


The syntax for declaring an array is:
dataType[] arrayName;

or
dataType arrayName[];

Examples

int[] scores;
double[] temperatures;
char[] grades;
String[] names;

10.7 Creating Arrays


After declaration, memory must be allocated using the new keyword.

Syntax

arrayName = new dataType[size];

Example
int[] scores = new int[5];

This creates an array capable of storing five integers.

228
COS 201: Computer Programming I Lecture Notes

10.8 Array Declaration and Creation in One State-


ment
int[] scores = new int[5];

10.9 Default Values in Arrays


When arrays are created, Java automatically assigns default values.

Data Type Default Value


int 0
double 0.0
float 0.0f
char \u0000
boolean false
String null

Table 10.1: Default Array Values

10.10 Initializing Arrays


Initialization assigns values to array elements.

10.10.1 Method 1: Individual Assignment

int[] scores = new int[5];

scores[0] = 78;
scores[1] = 85;
scores[2] = 92;
scores[3] = 67;
scores[4] = 88;

10.10.2 Method 2: Array Initializer

int[] scores = {78, 85, 92, 67, 88};

229
COS 201: Computer Programming I Lecture Notes

10.11 Accessing Array Elements


Array elements are accessed using indices.
Example
int[] scores = {78, 85, 92, 67, 88};

[Link](scores[2]);

Output

92

10.12 Modifying Array Elements


int[] scores = {78, 85, 92};

scores[1] = 90;

[Link](scores[1]);

Output

90

10.13 Array Length


Every array has a built-in property called length.
int[] scores = {78, 85, 92, 67};

[Link]([Link]);

Output

10.14 Traversing Arrays


Traversal means visiting each element in an array.

230
COS 201: Computer Programming I Lecture Notes

10.14.1 Using a for Loop

int[] scores = {78, 85, 92, 67, 88};

for(int i = 0; i < [Link]; i++)


{
[Link](scores[i]);
}

10.15 Enhanced for Loop


Java provides an enhanced for loop for arrays.

10.15.1 Syntax

for(dataType variable : arrayName)


{
statements;
}

Example
int[] scores = {78, 85, 92};

for(int score : scores)


{
[Link](score);
}

10.16 Comparing and Enhanced for Loops

Traditional for Loop Enhanced for Loop


Uses index values No index required
Allows modification of elements Read-only traversal
Suitable for all situations Best for simple traversal

Table 10.2: Loop Comparison

231
COS 201: Computer Programming I Lecture Notes

10.17 Calculating the Sum of Array Elements


int[] scores = {78, 85, 92, 67, 88};

int sum = 0;

for(int score : scores)


{
sum += score;
}

[Link](sum);

Output

410

10.18 Calculating the Average


int[] scores = {78, 85, 92, 67, 88};

int sum = 0;

for(int score : scores)


{
sum += score;
}

double average =
(double) sum / [Link];

[Link](average);

Output

82.0

10.19 Finding the Largest Element

232
COS 201: Computer Programming I Lecture Notes

int[] scores = {78, 85, 92, 67, 88};

int largest = scores[0];

for(int i = 1; i < [Link]; i++)


{
if(scores[i] > largest)
{
largest = scores[i];
}
}

[Link](largest);

Output

92

10.20 Finding the Smallest Element


int[] scores = {78, 85, 92, 67, 88};

int smallest = scores[0];

for(int i = 1; i < [Link]; i++)


{
if(scores[i] < smallest)
{
smallest = scores[i];
}
}

[Link](smallest);

Output

67

10.21 Searching an Array


Searching involves locating a specific element.

233
COS 201: Computer Programming I Lecture Notes

10.21.1 Linear Search Example

int[] scores = {78, 85, 92, 67, 88};

int target = 92;


boolean found = false;

for(int score : scores)


{
if(score == target)
{
found = true;
break;
}
}

[Link](found);

Output

true

10.22 Sorting Arrays


Java provides the Arrays utility class.

10.22.1 Import Statement

import [Link];

Example
import [Link];

public class SortExample {

public static void main(String[] args)


{
int[] values =
{45, 12, 78, 21, 9};

[Link](values);

234
COS 201: Computer Programming I Lecture Notes

for(int value : values)


{
[Link](
value + " "
);
}
}
}

Output

9 12 21 45 78

10.23 Copying Arrays

10.23.1 Using [Link]()

import [Link];

int[] original = {1, 2, 3, 4};

int[] copy =
[Link](original,
[Link]);

10.24 Passing Arrays to Methods


Arrays can be passed as method arguments.
public static void display(int[] values)
{
for(int value : values)
{
[Link](value);
}
}

10.25 Returning Arrays from Methods

235
COS 201: Computer Programming I Lecture Notes

public static int[] createArray()


{
int[] data =
{10, 20, 30};

return data;
}

10.26 Multidimensional Arrays


A multidimensional array is an array whose elements are themselves arrays.
The most common type is the two-dimensional array.

10.27 Two-Dimensional Arrays


A two-dimensional array represents data arranged in rows and columns.

10.27.1 Declaration

int[][] matrix;

10.27.2 Creation

int[][] matrix =
new int[3][4];

This creates a matrix with 3 rows and 4 columns.

10.28 Initializing a Two-Dimensional Array


int[][] matrix =
{
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

236
COS 201: Computer Programming I Lecture Notes

10.29 Accessing Elements in a 2D Array


[Link](
matrix[1][2]
);

Output

10.30 Traversing a Two-Dimensional Array


for(int row = 0;
row < [Link];
row++)
{
for(int col = 0;
col < matrix[row].length;
col++)
{
[Link](
matrix[row][col] + " ");
}

[Link]();
}

10.31 Jagged Arrays


Java allows rows to have different lengths.
int[][] jagged =
{
{1, 2},
{3, 4, 5},
{6}
};

Such arrays are called jagged arrays.

237
COS 201: Computer Programming I Lecture Notes

10.32 Applications of Arrays


Arrays are widely used in:

• Student record systems

• Payroll systems

• Scientific computing

• Data analysis

• Computer graphics

• Image processing

• Database applications

• Artificial intelligence

• Machine learning

• Game development

10.33 Review Questions and Exercises


The following questions and programming exercises are designed to reinforce the concepts
covered in this chapter. Attempt all questions and write complete Java programs where
required.

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 (" ").

4. What is Unicode? Why is Unicode important in modern programming?

5. Explain the purpose of the char data type.

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?

8. What is string concatenation? Describe two ways of concatenating strings in Java.

9. Explain the purpose of escape sequences and provide three examples.

10. What is the role of the Character class in Java?

11. Differentiate between the methods charAt() and substring().

12. Explain the purpose of the length() method.

13. Differentiate between equals() and == when comparing strings.

14. Explain the purpose of the following methods:

(a) indexOf()
(b) replace()
(c) trim()
(d) startsWith()
(e) endsWith()

15. Differentiate between the String class and the StringBuilder class.

16. Explain why string processing is important in software development.

17. Discuss five real-world applications of string processing.

18. Explain how loops can be used to process strings character by character.

19. Describe how the methods [Link]() and [Link]() can


be used in input validation.

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:

(a) The original string.


(b) Its length.
(c) The first character.

239
COS 201: Computer Programming I Lecture Notes

(d) The last character.

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.

25. Write a program that counts the number of characters in a sentence.

26. Write a program that counts the number of vowels in a sentence.

27. Write a program that counts the number of consonants in a sentence.

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.

31. Write a program that counts the number of spaces in a sentence.

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.

40. Write a program that reverses a string.

41. Write a program that checks whether a string is a palindrome.

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

46. Write a program that displays all digits found in a string.

47. Write a program that displays all letters found in a string.

48. Write a program that removes all digits from a string.

49. Write a program that creates a sentence using StringBuilder and appends three
additional words.

50. Write a program that uses StringBuilder to reverse a string.

Challenge Exercises
1. Write a program that counts the number of words in a sentence.

2. Write a program that determines the longest word in a sentence.

3. Write a program that counts the frequency of each vowel in a string.

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.

6. Write a program that removes duplicate characters from a string.

7. Write a program that validates an email address using string-processing techniques.

8. Write a program that masks all digits in a phone number except the last four digits.

9. Write a program that compresses consecutive repeated characters. For example:

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

10.34 Chapter Summary


In this chapter, we studied arrays, one of the most important data structures in Java
programming. Arrays provide a convenient way to store and manage multiple values of
the same data type under a single variable name. Instead of creating separate variables
for related data, an array allows programmers to organize and process large collections
of information efficiently.
We learned that every element in an array is identified by an index, and array indexing
in Java always begins at zero. The first element is stored at index 0, the second at index 1,
and so on. By using indices, individual elements can be accessed, modified, and processed
as needed. Understanding array indexing is essential because many programming errors
occur when invalid indices are used.
An important characteristic of arrays is that their size is fixed once they are created.
The number of elements an array can store must be specified during array creation, and
this size cannot be changed later. Although array elements can be modified, the array
itself cannot automatically grow or shrink. This limitation makes it important to estimate
storage requirements carefully when designing programs.
The chapter demonstrated how to declare, create, initialize, and use arrays in Java.
We explored different techniques for assigning values to arrays, including direct initial-
ization and individual element assignment. We also learned how to retrieve and display
array elements using their corresponding indices.
Array traversal was another major topic covered in this chapter. Traversal refers
to visiting each element in an array to perform operations such as displaying values,
calculating totals, searching for specific items, or modifying data. Traditional for loops
provide precise control over array traversal by using index values, while enhanced for
loops offer a simpler and more readable way to process all elements sequentially.
Several common array-processing operations were examined, including searching, sort-
ing, copying, and aggregation. Searching enables a program to locate a specific value
within an array, while sorting arranges elements into a desired order, such as ascending
or descending. Copying allows data to be transferred from one array to another, and ag-
gregation operations such as calculating sums, averages, maximum values, and minimum
values help summarize the contents of an array.
The chapter also introduced multidimensional arrays, particularly two-dimensional
arrays. A two-dimensional array organizes data into rows and columns, making it suit-
able for representing tables, matrices, spreadsheets, seating arrangements, and similar
structures. We learned how to declare, initialize, access, and process elements within
two-dimensional arrays using nested loops.
In addition, we explored jagged arrays, which are arrays whose rows can have different
lengths. Unlike regular two-dimensional arrays where every row contains the same number

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

Methods and Method Overloading

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.

11.2 What is a Method?


A method is a named block of code that performs a particular task.
Examples of tasks performed by methods include:

• Calculating the average of numbers

• Displaying a message

• Sorting an array

• Finding the largest value

• Reading user input

244
COS 201: Computer Programming I Lecture Notes

• Performing mathematical computations

Methods allow a programmer to divide a large problem into smaller sub-problems.

11.3 Advantages of Using Methods


Methods provide numerous benefits:

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.

6. Reduced Program Complexity


Large programs become easier to manage.

11.4 Structure of a Method


The general syntax of a Java method is:
accessModifier returnType methodName(parameterList)
{
// method body
}

Example:
public static void displayMessage()
{
[Link]("Welcome to Java");
}

245
COS 201: Computer Programming I Lecture Notes

11.5 Components of a Method


A method consists of several parts.

11.5.1 Access Modifier


Determines where the method can be accessed.
Examples:

• public

• private

• protected

• default

Example:
public static void show()
{
}

11.5.2 Return Type


Specifies the type of value returned by the method.
Common return types:

• 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

11.5.3 Method Name


A meaningful identifier that describes the task performed.
Examples:

• calculateArea()

• findMaximum()

• printReport()

• getAverage()

11.5.4 Parameter List


Parameters receive data from the method caller.
Example:
public static int add(int a, int b)
{
return a + b;
}

Here:

• a and b are parameters

• Both are of type int

11.5.5 Method Body


Contains executable statements.
Example:
{
int sum = a + b;
return sum;
}

11.6 Defining and Calling Methods

11.6.1 Method Definition

247
COS 201: Computer Programming I Lecture Notes

public static void greet()


{
[Link]("Good Morning");
}

11.6.2 Method Call


greet();

Complete Example:
public class Test
{
public static void greet()
{
[Link]("Good Morning");
}

public static void main(String[] args)


{
greet();
}
}

Output:

Good Morning

11.7 Methods with Parameters


Parameters allow methods to receive input values.
Example:
public static void displayName(String name)
{
[Link](name);
}

Method call:
displayName("Aminu");

Output:

Aminu

248
COS 201: Computer Programming I Lecture Notes

11.8 Methods Returning Values


Some methods perform calculations and return results.
Example:
public static int square(int number)
{
return number * number;
}

Method call:
int result = square(5);
[Link](result);

Output:

25

11.9 The return Statement


The return statement:

• Ends method execution

• Sends a value back to the caller

Example:
public static int maximum(int a, int b)
{
if(a > b)
return a;
else
return b;
}

11.10 Void Methods


A void method does not return any value.
Example:

249
COS 201: Computer Programming I Lecture Notes

public static void welcome()


{
[Link]("Welcome");
}

Method call:
welcome();

11.11 Actual and Formal Parameters

11.11.1 Formal Parameters


Variables declared in the method header.
Example:
public static int add(int x, int y)
{
return x + y;
}

x and y are formal parameters.

11.11.2 Actual Parameters


Values supplied during method call.
Example:
add(10, 20);

10 and 20 are actual parameters.

11.12 Parameter Passing in Java


Java uses pass-by-value.
This means a copy of the value is passed to the method.
Example:
public static void change(int x)
{
x = 100;
}

250
COS 201: Computer Programming I Lecture Notes

public static void main(String[] args)


{
int num = 50;

change(num);

[Link](num);
}

Output:

50

The original value remains unchanged.

11.13 Local Variables


Variables declared inside a method are called local variables.
Example:
public static void test()
{
int number = 50;
}

Characteristics:

• Exist only inside the method

• Created when method starts

• Destroyed when method ends

11.14 Scope of Variables


Scope refers to the region where a variable can be accessed.
Example:
public static void show()
{
int x = 10;
}

public static void main(String[] args)

251
COS 201: Computer Programming I Lecture Notes

{
[Link](x);
}

This produces an error because x is outside its scope.

11.15 Method Call Stack


Whenever a method is called:

1. Memory is allocated.

2. Parameters are stored.

3. Local variables are created.

4. Method executes.

5. Memory is released when execution ends.

Methods are managed using a structure known as the call stack.

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

11.17 Factorial Using Recursion


Mathematical definition:

n! = n × (n − 1)!

Example:
public static int factorial(int n)
{
if(n == 0)
return 1;

return n * factorial(n - 1);


}

Output:

factorial(5) = 120

11.18 Introduction to Method Overloading


In Java, it is possible to create multiple methods with the same name as long as their
parameter lists are different. This feature is known as method overloading.
Method overloading enables a programmer to use a single method name to perform
similar operations on different types or amounts of data. Instead of creating several
methods with different names, overloaded methods provide a more organized and readable
approach to programming.
For two or more methods to be overloaded, they must have:

• The same method name.

• Different parameter lists.

The difference in parameter lists may involve:

• A different number of parameters.

253
COS 201: Computer Programming I Lecture Notes

• Different parameter data types.

• A different order of parameter types.

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.

Example: Overloading with Different Data Types

public static int add(int a, int b)


{
return a + b;
}

public static double add(


double a,
double b)
{
return a + b;
}

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.

11.18.1 Benefits of Method Overloading


Method overloading provides several advantages:

• Improves program readability.

254
COS 201: Computer Programming I Lecture Notes

• Reduces the number of method names that must be remembered.

• Allows similar operations to be grouped together.

• Makes programs easier to maintain.

• Supports code reuse.

For example, instead of creating methods named:


addIntegers()
addDoubles()
addThreeNumbers()

we can simply use:


add()

with different parameter lists.

11.18.2 Important Rule


The return type alone cannot be used to overload a method.
The following code is invalid:
public static int test()
{
return 10;
}

public static double test()


{
return 10.5;
}

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.

11.19 Why Use Method Overloading?


Benefits include:

255
COS 201: Computer Programming I Lecture Notes

• Improved readability

• Easier maintenance

• Logical grouping of similar operations

• Reduced need for different method names

11.20 Rules for Method Overloading


Methods can be overloaded by changing:

1. Number of parameters

2. Data types of parameters

3. Order of parameters

11.20.1 Different Number of Parameters

public static int add(int a, int b)


{
return a + b;
}

public static int add(int a, int b, int c)


{
return a + b + c;
}

11.20.2 Different Data Types

public static int add(int a, int b)


{
return a + b;
}

public static double add(double a, double b)


{
return a + b;
}

256
COS 201: Computer Programming I Lecture Notes

11.20.3 Different Parameter Order

public static void display(int a, String b)


{
}

public static void display(String b, int a)


{
}

11.21 Invalid Method Overloading


Changing only the return type does not overload a method.
Invalid:
public static int test()
{
return 10;
}

public static double test()


{
return 10.0;
}

Compiler Error:

Method already defined

Example of Method Overloading


public class Calculator
{
public static int multiply(int a, int b)
{
return a * b;
}

public static double multiply(double a, double b)


{
return a * b;

257
COS 201: Computer Programming I Lecture Notes

public static int multiply(int a, int b, int c)


{
return a * b * c;
}

public static void main(String[] args)


{
[Link](multiply(2,3));
[Link](multiply(2.5,4.0));
[Link](multiply(2,3,4));
}
}

Output:

6
10.0
24

Practical Example: Student Result System


public class ResultSystem
{
public static double average(int a, int b)
{
return (a + b) / 2.0;
}

public static double average(int a, int b, int c)


{
return (a + b + c) / 3.0;
}

public static void main(String[] args)


{
[Link](average(70,80));
[Link](average(70,80,90));
}
}

258
COS 201: Computer Programming I Lecture Notes

Output:

75.0
80.0

11.22 Best Practices for Writing Methods


1. Use meaningful method names.

2. Keep methods short and focused.

3. Avoid excessive parameters.

4. Use comments where necessary.

5. Reuse methods whenever possible.

6. Use method overloading appropriately.

7. Return values instead of relying heavily on global variables.

11.23 Common Errors


• Missing return statement

• Wrong parameter type

• Incorrect method call

• Calling a non-static method from a static context

• Infinite recursion

• Duplicate method definitions

• Incorrect argument count

11.24 Chapter Summary


Methods are reusable blocks of code designed to perform specific tasks. They improve
modularity, readability, maintainability, and code reuse. A method may accept parame-
ters, perform computations, and return results. Java uses pass-by-value when transfer-
ring arguments to methods. Variables declared inside methods are local and have limited
scope.

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.

11.25 Review Questions


1. What is a method in Java?

2. State five advantages of methods.

3. Differentiate between a void method and a value-returning method.

4. Explain the purpose of the return statement.

5. What is the difference between actual and formal parameters?

6. Explain pass-by-value in Java.

7. Define variable scope.

8. What is recursion?

9. Write a recursive method to compute factorial.

10. Define method overloading.

11. State the rules for method overloading.

12. Why can’t methods be overloaded by changing only the return type?

13. Differentiate between method overriding and method overloading.

14. Explain how the method call stack works.

15. Discuss the importance of modular programming using methods.

11.26 Programming Exercises


1. Write a method that calculates the square of a number.

2. Write a method that determines whether a number is even or odd.

3. Create a method that finds the maximum of three integers.

260
COS 201: Computer Programming I Lecture Notes

4. Write a method that computes the area of a rectangle.

5. Develop a method that converts Celsius to Fahrenheit.

6. Write a recursive method to calculate factorial.

7. Write a recursive method to compute Fibonacci numbers.

8. Overload a method named area() for:

• Circle
• Rectangle
• Triangle

9. Create overloaded methods named display() that accept:

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

12. Create a recursive method to reverse a string.

13. Write a method that counts vowels in a string.

14. Create a method that searches for a value in an array.

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.

12.2 Fundamental Principles of OOP


Object-Oriented Programming is based on four major principles:

1. Encapsulation

2. Abstraction

3. Inheritance

4. Polymorphism

These principles work together to support efficient software development.

262
COS 201: Computer Programming I Lecture Notes

12.3 Objects and Classes

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) {

Student s1 = new Student();

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

12.4.1 Advantages of Encapsulation


• Data hiding

263
COS 201: Computer Programming I Lecture Notes

• Increased security

• Better control of data

• Improved maintainability

Example
class Account {
private double balance;

public void setBalance(double b) {


balance = b;
}

public double getBalance() {


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

12.5.1 Advantages of Abstraction


• Reduces complexity

• Increases security

• Improves code clarity

Example Using Abstract Class

abstract class Vehicle {


abstract void start();
}

class Car extends Vehicle {


void start() {
[Link]("Car starts with key");

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

class Dog extends Animal {


void bark() {
[Link]("Barking...");
}
}

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:

1. Compile-time polymorphism (method overloading)

2. Runtime polymorphism (method overriding)

Example
class Animal {
void sound() {
[Link]("Animal sound");
}
}

class Dog extends Animal {


void sound() {
[Link]("Dog barks");

265
COS 201: Computer Programming I Lecture Notes

}
}

12.8 Relationship Between OOP Concepts


The four OOP principles are interconnected:

• Encapsulation protects data inside classes.

• Abstraction hides unnecessary details.

• Inheritance promotes code reuse.

• Polymorphism enables flexibility in behavior.

Together, they form the foundation of object-oriented design.

12.9 Advantages of Object-Oriented Programming


• Code reusability through inheritance

• Improved software maintainability

• Better security through encapsulation

• Easier troubleshooting and debugging

• Scalable and flexible system design

• Real-world modeling of problems

12.10 Disadvantages of Object-Oriented Programming


• More complex than procedural programming

• Requires more memory and processing

• Slower execution in some cases

• Steeper learning curve for beginners

266
COS 201: Computer Programming I Lecture Notes

12.11 Real-World Applications of OOP


Object-Oriented Programming is widely used in:

• Banking systems

• Mobile applications

• Web applications

• Game development

• Simulation systems

• Enterprise software

• Artificial intelligence systems

12.12 Common Programming Errors


1. Confusing class and object concepts

2. Improper use of access modifiers

3. Not using encapsulation properly

4. Misusing inheritance relationships

5. Incorrect implementation of polymorphism

12.13 Best Practices


• Always use encapsulation for data protection

• Use inheritance only for true IS-A relationships

• Prefer interfaces for flexibility

• Keep classes focused and simple

• Use meaningful class and method names

267
COS 201: Computer Programming I Lecture Notes

12.14 Chapter Summary


This chapter introduced the concept of OOP, a programming paradigm that organizes
software around objects rather than individual functions and procedures. OOP provides
a structured approach to software development by modeling real-world entities as objects
that contain both data and behaviors. Java is a fully object-oriented programming lan-
guage, and understanding OOP concepts is essential for developing modern applications.
We learned that the foundation of OOP is built upon classes and objects. A class
serves as a blueprint or template that defines the attributes and behaviors of a particular
type of object, while an object is an instance of a class created during program execution.
Through classes and objects, programmers can model real-world entities such as students,
employees, vehicles, bank accounts, and many other concepts in a natural and organized
manner.
The chapter examined the four fundamental principles of Object-Oriented Program-
ming: encapsulation, abstraction, inheritance, and polymorphism. These princi-
ples form the core of OOP and provide the mechanisms that make object-oriented software
flexible, reusable, and easier to maintain.
Encapsulation refers to the practice of combining data and the methods that operate
on that data within a single unit, known as a class. Encapsulation also involves restrict-
ing direct access to an object’s internal data through the use of access modifiers such as
private. Instead of allowing unrestricted access, data is typically accessed and modi-
fied through public methods, often called getters and setters. This approach improves
security, protects data integrity, and helps prevent accidental modification of important
information.
The concept of abstraction was introduced as a technique for hiding unnecessary
implementation details while exposing only the essential features of an object. Abstrac-
tion allows users of a class to focus on what an object does rather than how it performs
its tasks. By simplifying complex systems and reducing unnecessary details, abstraction
makes software easier to understand, use, and maintain.
The chapter also explored inheritance, a mechanism that allows one class to ac-
quire the attributes and behaviors of another class. Inheritance promotes code reuse
by enabling developers to create new classes based on existing ones without rewriting
previously developed functionality. The derived class, often called a subclass or child
class, can extend or modify the behavior of the parent class while retaining its existing
features. This capability helps reduce duplication and supports the creation of organized
class hierarchies.
Another key principle discussed was polymorphism. Polymorphism allows a single
interface, method, or reference to represent different forms of behavior. Through poly-
morphism, the same method call can produce different results depending on the object

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.

12.15 Review Questions and Exercises


The following review questions and programming exercises are designed to reinforce your
understanding of Object-Oriented Programming concepts and their implementation in
Java.

Conceptual Questions
1. Define Object-Oriented Programming (OOP).

2. Explain why OOP is considered an important programming paradigm in modern


software development.

3. List and explain the four fundamental principles of OOP.

4. Differentiate between a class and an object.

5. What is an object? Give three real-world examples of objects.

6. What is a class? Explain its role in object-oriented design.

7. Explain the relationship between classes and objects.

269
COS 201: Computer Programming I Lecture Notes

8. What is encapsulation? Why is it important?

9. Describe how access modifiers help achieve encapsulation.

10. Explain abstraction with a real-world example.

11. Differentiate between abstraction and encapsulation.

12. What is inheritance? Why is inheritance important in software development?

13. Explain the terms parent class, child class, superclass, and subclass.

14. What are the advantages of inheritance?

15. Define polymorphism in your own words.

16. Explain how polymorphism increases flexibility in software systems.

17. Differentiate between compile-time polymorphism and runtime polymorphism.

18. Explain how the four principles of OOP work together to improve software quality.

19. Discuss the advantages of Object-Oriented Programming.

20. Mention and explain at least three disadvantages of OOP.

21. Why is Java referred to as an object-oriented programming language?

22. Explain the concept of code reuse and its relationship with inheritance.

23. How does OOP improve software maintainability?

24. Explain how OOP supports modular program design.

25. Discuss five real-world applications of Object-Oriented Programming.

Short Answer Questions


26. Define the following terms:

(a) Class
(b) Object
(c) Method
(d) Attribute
(e) Constructor

27. State two benefits of encapsulation.

270
COS 201: Computer Programming I Lecture Notes

28. State two benefits of abstraction.

29. State two benefits of inheritance.

30. State two benefits of polymorphism.

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.

35. Write a program demonstrating encapsulation by creating a class named BankAccount


with private attributes and public getter and setter methods.

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.

43. Write a program demonstrating method overloading as an example of compile-time


polymorphism.

44. Write a program demonstrating method overriding as an example of runtime poly-


morphism.

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.

Analysis and Design Exercises


1. Design a simple student registration system and identify:

(a) Classes
(b) Objects
(c) Attributes
(d) Methods

2. Design a simple library management system and identify the OOP concepts used.

3. Design a payroll system and explain how encapsulation can be applied.

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.

6. Explain how abstraction can simplify the design of a banking application.

7. Create a class diagram for a school management system.

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.

3. Design a graphical representation of the relationships among classes in a university


management system.

272
COS 201: Computer Programming I Lecture Notes

4. Build a simple inventory management system using classes, objects, and inheritance.

5. Design a software application that demonstrates all four OOP principles:

• Encapsulation
• Abstraction
• Inheritance
• Polymorphism

Explain clearly how each principle is implemented in your design.

273
Chapter 13

Inheritance and Polymorphism

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.

13.2 Inheritance in Java


Inheritance is a mechanism in Java where one class (called the subclass or child class)
acquires the properties and behaviors of another class (called the superclass or parent
class).
It represents an IS-A relationship. For example, a Car is a Vehicle, and a Dog is
an Animal.

13.3 Advantages of Inheritance


Inheritance provides several benefits:

• Code reusability

• Reduced redundancy

• Easier maintenance

274
COS 201: Computer Programming I Lecture Notes

• Improved program structure

• Extensibility of existing code

13.4 Types of Inheritance in Java


Java supports the following types of inheritance:

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.

13.5 Single Inheritance


Single inheritance occurs when a class inherits from one parent class.
Example
class Animal {
void eat() {
[Link]("Eating...");
}
}

class Dog extends Animal {


void bark() {
[Link]("Barking...");
}
}

public class Test {


public static void main(String[] args) {
Dog d = new Dog();
[Link]();
[Link]();
}
}

Output

275
COS 201: Computer Programming I Lecture Notes

Eating...
Barking...

13.6 Multilevel Inheritance


In multilevel inheritance, a class is derived from another derived class.
Example
class Animal {
void eat() {
[Link]("Eating...");
}
}

class Dog extends Animal {


void bark() {
[Link]("Barking...");
}
}

class Puppy extends Dog {


void weep() {
[Link]("Weeping...");
}
}

public class Test {


public static void main(String[] args) {
Puppy p = new Puppy();
[Link]();
[Link]();
[Link]();
}
}

13.7 Hierarchical Inheritance


Hierarchical inheritance occurs when multiple classes inherit from a single parent class.
Example
class Animal {

276
COS 201: Computer Programming I Lecture Notes

void eat() {
[Link]("Eating...");
}
}

class Dog extends Animal {


void bark() {
[Link]("Barking...");
}
}

class Cat extends Animal {


void meow() {
[Link]("Meowing...");
}
}

13.8 The super Keyword


The super keyword refers to the parent class object. It is used to:

• Access parent class methods

• Access parent class constructors

• Access parent class variables

Example
class Animal {
void sound() {
[Link]("Animal sound");
}
}

class Dog extends Animal {


void sound() {
[Link]();
[Link]("Dog barks");
}
}

277
COS 201: Computer Programming I Lecture Notes

13.9 Method Overriding


Method overriding occurs when a subclass provides a specific implementation of a method
already defined in its superclass.
It is a key feature used to achieve runtime polymorphism.

13.9.1 Rules of Method Overriding


• Method must have the same name

• Method must have the same parameters

• Inheritance must exist

• Return type must be the same or covariant

Example
class Animal {
void sound() {
[Link]("Animal sound");
}
}

class Dog extends Animal {


@Override
void sound() {
[Link]("Dog barks");
}
}

13.10 Dynamic Method Dispatch


Dynamic method dispatch is the process by which a call to an overridden method is
resolved at runtime rather than compile time.
Example
class Animal {
void sound() {
[Link]("Animal sound");
}
}

278
COS 201: Computer Programming I Lecture Notes

class Dog extends Animal {


void sound() {
[Link]("Dog barks");
}
}

public class Test {


public static void main(String[] args) {
Animal a = new Dog();
[Link]();
}
}

Output
Dog barks

13.11 Polymorphism in Java


Polymorphism means many forms. It allows one interface to be used for different
underlying forms (objects).
There are two types of polymorphism:
1. Compile-time polymorphism (method overloading)

2. Runtime polymorphism (method overriding)

13.12 Compile-Time Polymorphism


Compile-time polymorphism is achieved through method overloading.
Example
class MathOperation {

int add(int a, int b) {


return a + b;
}

int add(int a, int b, int c) {


return a + b + c;
}
}

The method to execute is determined at compile time.

279
COS 201: Computer Programming I Lecture Notes

13.13 Runtime Polymorphism


Runtime polymorphism is achieved through method overriding.
Example
class Animal {
void sound() {
[Link]("Animal sound");
}
}

class Cat extends Animal {


void sound() {
[Link]("Meow");
}
}

public class Test {


public static void main(String[] args) {
Animal a;

a = new Cat();
[Link]();

a = new Animal();
[Link]();
}
}

13.14 Difference Between Overloading and Overrid-


ing

Method Overloading Method Overriding


Same method name, different pa- Same method name, same param-
rameters eters
Occurs in same class Occurs in parent and child classes
Compile-time polymorphism Runtime polymorphism
No inheritance required Requires inheritance

Table 13.1: Overloading vs Overriding

280
COS 201: Computer Programming I Lecture Notes

13.15 Abstract Classes


An abstract class is a class that cannot be instantiated and may contain abstract methods.
Example
abstract class Animal {
abstract void sound();

void sleep() {
[Link]("Sleeping...");
}
}

class Dog extends Animal {


void sound() {
[Link]("Dog barks");
}
}

13.16 Interfaces
An interface is a blueprint of a class that contains abstract methods.
Example
interface Animal {
void sound();
}

class Dog implements Animal {


public void sound() {
[Link]("Barking");
}
}

13.17 Multiple Inheritance Using Interfaces


Java supports multiple inheritance through interfaces.
interface A {
void showA();
}

281
COS 201: Computer Programming I Lecture Notes

interface B {
void showB();
}

class C implements A, B {
public void showA() {
[Link]("A");
}

public void showB() {


[Link]("B");
}
}

13.18 Applications of Inheritance and Polymorphism


• Software framework design

• GUI development (buttons, windows, events)

• Game development

• Database systems

• Banking systems

• Simulation systems

• Cloud-based applications

• Artificial intelligence systems

13.19 Common Programming Errors


1. Incorrect method overriding signature

2. Forgetting extends keyword

3. Attempting to instantiate abstract classes

4. Missing implementation of interface methods

5. Misusing inheritance instead of composition

282
COS 201: Computer Programming I Lecture Notes

13.20 Best Practices


• Use inheritance only for IS-A relationships

• Prefer interfaces for flexibility

• Avoid deep inheritance hierarchies

• Use method overriding carefully

• Follow naming conventions

13.21 Chapter Summary


In this chapter, we explored the concepts of inheritance, polymorphism, abstract
classes, and interfaces, which are among the most important features of Object-Oriented
Programming in Java. These concepts enable programmers to create flexible, reusable,
and maintainable software systems by organizing related classes into meaningful hierar-
chies and allowing objects to exhibit different behaviors through common interfaces.
We learned that inheritance is a mechanism that allows one class to acquire the
attributes and methods of another class. The class that provides the inherited features
is known as the parent class, superclass, or base class, while the class that inherits those
features is called the child class, subclass, or derived class. Through inheritance, develop-
ers can reuse existing code, reduce duplication, and extend the functionality of previously
defined classes without rewriting common behaviors.
The chapter introduced the different forms of inheritance supported by Java. Single
inheritance allows a class to inherit from one parent class. Multilevel inheritance
enables inheritance across multiple levels of a class hierarchy, where a class inherits from
another derived class. Hierarchical inheritance occurs when multiple child classes
inherit from the same parent class. Although Java does not support multiple inheritance
through classes, it provides alternative mechanisms through interfaces.
One of the major benefits of inheritance is its ability to promote code reuse. Com-
mon attributes and methods can be placed in a parent class and inherited by multiple
subclasses, reducing redundancy and improving maintainability. This approach makes
software systems easier to develop, update, and extend as requirements evolve.
We also examined method overriding, a technique that allows a subclass to pro-
vide its own implementation of a method that already exists in its parent class. When
a method is overridden, the version executed depends on the actual object being refer-
enced at runtime. This capability forms the basis of runtime polymorphism and allows
subclasses to customize inherited behavior while preserving a common interface.

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.

13.22 Review Questions and Exercises


1. Define inheritance in Java.

284
COS 201: Computer Programming I Lecture Notes

2. List types of inheritance supported in Java.

3. Differentiate between method overloading and overriding.

4. What is polymorphism?

5. Explain dynamic method dispatch.

6. Write a program demonstrating single inheritance.

7. Write a program demonstrating method overriding.

8. What is the purpose of the super keyword?

9. Differentiate between abstract classes and interfaces.

10. Write a program using interfaces.

11. Explain runtime polymorphism with an example.

12. Why does Java not support multiple inheritance with classes?

13. State advantages of inheritance.

14. Discuss real-world applications of polymorphism.

15. Design a simple system that uses inheritance and method overriding.

285
Chapter 14

Simple Input and Output

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.

14.2 Standard Output in Java


Java provides the [Link] object to display output on the screen.
The most commonly used methods are:

• [Link]() – prints output on the same line

• [Link]() – prints output and moves to the next line

• [Link]() – formatted output

Example: print() and println()

public class OutputExample {


public static void main(String[] args) {

[Link]("Hello ");
[Link]("World");

286
COS 201: Computer Programming I Lecture Notes

[Link]();

[Link]("Welcome to Java Programming");


}
}

Output

Hello World
Welcome to Java Programming

14.3 Formatted Output Using printf


The printf() method allows formatted output similar to C programming.

14.3.1 Format Specifiers

Specifier Description
%d Integer values
%f Floating-point values
%s Strings
%c Characters
%.2f Floating-point with 2 decimal places

Table 14.1: Common Format Specifiers

Example
public class PrintfExample {
public static void main(String[] args) {

String name = "Aminu";


int age = 21;
double gpa = 4.32;

[Link]("Name: %s%n", name);


[Link]("Age: %d%n", age);
[Link]("GPA: %.2f%n", gpa);
}
}

287
COS 201: Computer Programming I Lecture Notes

14.4 Standard Input in Java


Java does not provide direct input methods like some other languages. Instead, input is
handled using classes such as:

• Scanner (most common)

• BufferedReader

• Console

This chapter focuses on the Scanner class.

14.5 The Scanner Class


The Scanner class is used to read input from the keyboard.
It is found in the [Link] package.

14.5.1 Importing Scanner

import [Link];

14.5.2 Creating a Scanner Object

Scanner input = new Scanner([Link]);

14.6 Reading Different Data Types


The Scanner class provides different methods for reading input.

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

Table 14.2: Scanner Input Methods

288
COS 201: Computer Programming I Lecture Notes

Example: Reading User Input


import [Link];

public class InputExample {


public static void main(String[] args) {

Scanner input = new Scanner([Link]);

[Link]("Enter your name: ");


String name = [Link]();

[Link]("Enter your age: ");


int age = [Link]();

[Link]("Name: " + name);


[Link]("Age: " + age);
}
}

Output Example
Enter your name: Aminu
Enter your age: 21
Name: Aminu
Age: 21

14.7 Reading Multiple Inputs


Scanner input = new Scanner([Link]);

[Link]("Enter three numbers: ");

int a = [Link]();
int b = [Link]();
int c = [Link]();

int sum = a + b + c;

289
COS 201: Computer Programming I Lecture Notes

[Link]("Sum = " + sum);

14.8 Common Issue: nextLine() Problem


A common problem occurs when mixing nextLine() with other input methods.

Problem Example

int age = [Link]();


String name = [Link]();

The nextLine() may read the leftover newline character.

14.8.1 Solution
Add an extra nextLine():
int age = [Link]();
[Link](); // consume newline
String name = [Link]();

14.9 Reading Characters


Java does not have a direct method for reading a single character.
char grade = [Link]().charAt(0);

Example: Simple Calculator


import [Link];

public class Calculator {


public static void main(String[] args) {

Scanner input = new Scanner([Link]);

[Link]("Enter first number: ");


int a = [Link]();

[Link]("Enter second number: ");

290
COS 201: Computer Programming I Lecture Notes

int b = [Link]();

int sum = a + b;
int product = a * b;

[Link]("Sum = " + sum);


[Link]("Product = " + product);
}
}

14.10 File Input and Output (Introduction)


Java also supports reading from and writing to files using classes such as:

• File

• FileWriter

• FileReader

• BufferedReader

• PrintWriter

Note: File handling will be discussed in detail in a later chapter.

14.11 Best Practices for Input and Output


• Always close the Scanner when done (for large programs).

• Use meaningful prompts for user input.

• Validate user input where necessary.

• Prefer nextLine() when reading full sentences.

• Avoid mixing input methods without handling newline issues.

14.12 Common Programming Errors


1. Using incorrect Scanner method for data type.

2. Forgetting to import [Link].

291
COS 201: Computer Programming I Lecture Notes

3. Input mismatch errors (entering text instead of numbers).

4. Mixing nextLine() with other methods incorrectly.

5. Not handling invalid user input.

14.13 Chapter Summary


In this chapter, we examined the fundamental concepts of input and output in Java pro-
gramming. Input and output operations are essential components of interactive software
because they enable programs to communicate with users and external sources of data.
Without input and output capabilities, programs would be unable to receive information,
display results, or respond to user actions effectively.
We learned that output in Java is commonly performed using the [Link] object.
Through methods such as print(), println(), and printf(), Java programs can display
messages, values, calculations, and other information on the screen. These methods allow
programmers to provide meaningful feedback to users and present program results in a
clear and understandable manner.
The chapter introduced the differences between print() and println(). The print()
method displays output without moving the cursor to a new line, while println() au-
tomatically advances to the next line after displaying the output. Understanding these
methods helps programmers control the appearance and organization of program output.
We also explored formatted output using the printf() method. Formatted output
enables developers to display data in a structured and professional manner by using
format specifiers such as %d, %f, %s, and %c. This technique is particularly useful when
presenting numerical results, generating reports, or displaying tabular information.
A major portion of the chapter focused on obtaining input from users through the
Scanner class. The Scanner class, which belongs to the [Link] package, provides a
convenient way to read data entered through the keyboard. By creating a Scanner object
connected to [Link], programs can accept user input and process it during execution.
Several Scanner methods were discussed, each designed to read a specific type of
data. Methods such as nextInt(), nextDouble(), nextFloat(), nextLong(), and
nextBoolean() allow programs to read numeric and logical values, while methods such
as next() and nextLine() are used to read textual input. Selecting the appropriate
method ensures that user input is interpreted correctly according to the desired data
type.
The chapter highlighted the difference between next() and nextLine(). The next()
method reads only a single word and stops at whitespace, whereas nextLine() reads an
entire line of text, including spaces. Understanding this distinction is important when
designing programs that accept names, addresses, sentences, or other multi-word input.

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.

14.14 Review Questions and Exercises


1. Define the concepts of input and output in computer programming. Why are they
important in software development?

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.

15.2 Concept of Recursion


A recursive method is a method that calls itself either directly or indirectly.
Every recursive solution must have two main components:

• Base Case: The condition that stops recursion.

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

15.3 Structure of a Recursive Method


returnType methodName(parameters)
{
if (baseCondition)
{
return result;
}

295
COS 201: Computer Programming I Lecture Notes

else
{
return methodName(smallerProblem);
}
}

15.4 How Recursion Works


When a recursive method is called:

1. The method executes until it reaches the base case.

2. Each recursive call is stored in the call stack.

3. Once the base case is reached, execution begins to return back.

4. The stack unwinds and final results are produced.

Example: Factorial of a Number


The factorial of a number n is defined as:

n! = n × (n − 1) × (n − 2) × · · · × 1

Recursive definition:

n! = n × (n − 1)!

15.4.1 Java Implementation

public class Factorial {

public static int factorial(int n)


{
if (n == 0 || n == 1)
{
return 1; // base case
}
else
{
return n * factorial(n - 1); // recursive case

296
COS 201: Computer Programming I Lecture Notes

}
}

public static void main(String[] args)


{
int result = factorial(5);
[Link]("Factorial = " + result);
}
}

Output

Factorial = 120

Example: Fibonacci Sequence


The Fibonacci sequence is defined as:

F (n) = F (n − 1) + F (n − 2)

with:

F (0) = 0, F (1) = 1

15.4.2 Java Implementation

public class Fibonacci {

public static int fib(int n)


{
if (n == 0)
return 0;

if (n == 1)
return 1;

return fib(n - 1) + fib(n - 2);


}

public static void main(String[] args)


{
for (int i = 0; i < 10; i++)

297
COS 201: Computer Programming I Lecture Notes

{
[Link](fib(i) + " ");
}
}
}

Output

0 1 1 2 3 5 8 13 21 34

15.5 Types of Recursion

15.5.1 Direct Recursion


A method calls itself directly.
public static void A()
{
A();
}

15.5.2 Indirect Recursion


A method calls another method, which eventually calls the first method.
public static void A()
{
B();
}

public static void B()


{
A();
}

15.5.3 Tail Recursion


A recursive call is the last operation in the method.
public static void print(int n)
{
if (n == 0)
return;

298
COS 201: Computer Programming I Lecture Notes

[Link](n);
print(n - 1);
}

15.6 Base Case Importance


The base case is essential because it:

• Prevents infinite recursion

• Stops memory overflow

• Ensures correct termination

Example:
if (n == 0)
return;

15.7 Recursion vs Iteration

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

Table 15.1: Recursion vs Iteration

15.8 Advantages of Recursion


• Simplifies complex problems

• Short and clean code

• Useful for divide-and-conquer algorithms

• Natural fit for tree and graph problems

299
COS 201: Computer Programming I Lecture Notes

15.9 Disadvantages of Recursion


• High memory usage

• Slower due to repeated function calls

• Risk of stack overflow

• Difficult to debug in some cases

15.10 Common Applications of Recursion


• Factorial computation

• Fibonacci sequence

• Binary search

• Merge sort and quick sort

• Tree traversal (inorder, preorder, postorder)

• Graph algorithms

• Backtracking problems (maze solving, puzzles)

Example: Binary Search Using Recursion


public class BinarySearch {

public static int search(int[] arr, int left, int right, int key)
{
if (left > right)
return -1;

int mid = (left + right) / 2;

if (arr[mid] == key)
return mid;

if (key < arr[mid])


return search(arr, left, mid - 1, key);

300
COS 201: Computer Programming I Lecture Notes

return search(arr, mid + 1, right, key);


}
}

15.11 Common Programming Errors


1. Missing base case

2. Incorrect base condition

3. Infinite recursion

4. Stack overflow error

5. Wrong recursive call arguments

15.12 Best Practices


• Always define a clear base case

• Ensure recursion moves toward the base case

• Avoid unnecessary recursion when iteration is simpler

• Use recursion for naturally recursive problems

• Analyze time complexity carefully

15.13 Chapter Summary


In this chapter, we explored the concept of recursion, a powerful programming technique
in which a method calls itself in order to solve a problem. Recursion is widely used in
computer science because it provides a natural and elegant way of solving problems that
can be broken down into smaller versions of the same problem. Many complex algorithms
become simpler and easier to understand when implemented recursively.
A recursive method consists of two essential components: the base case and the
recursive case. The base case defines the condition under which the recursion stops,
preventing the method from calling itself indefinitely. The recursive case contains the
logic that reduces the problem into a smaller subproblem and calls the same method
again. Without a properly defined base case, recursion would continue endlessly and
eventually result in a stack overflow error.

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.

15.14 Review Questions and Exercises


1. Define recursion in Java and explain how it differs from a normal method call.

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.

9. What is indirect recursion? Illustrate your answer with an example.

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.

18. Write a recursive method to calculate the power of a number, xn .

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.

24. Discuss situations in which recursion is more appropriate than iteration.

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

16.2 Concept of Searching


Searching refers to the process of checking whether a particular value (called the key)
exists in a data structure and, if so, determining its position.
The efficiency of a search algorithm is measured in terms of:

• Time complexity

• Number of comparisons

• Memory usage

16.3 Linear Search


Linear search is the simplest searching algorithm. It checks each element of the array one
by one until the target value is found or the end of the array is reached.

305
COS 201: Computer Programming I Lecture Notes

16.3.1 Algorithm Steps


1. Start from the first element.

2. Compare each element with the target value.

3. If a match is found, return the index.

4. If not found, continue until the end of the array.

16.3.2 Java Implementation

public class LinearSearch {

public static int search(int[] arr, int key)


{
for (int i = 0; i < [Link]; i++)
{
if (arr[i] == key)
{
return i;
}
}
return -1;
}

public static void main(String[] args)


{
int[] data = {10, 25, 30, 45, 60};

int result = search(data, 30);

if (result != -1)
[Link]("Element found at index " + result);
else
[Link]("Element not found");
}
}

Output

Element found at index 2

306
COS 201: Computer Programming I Lecture Notes

16.3.3 Time Complexity


• Best case: O(1)

• Worst case: O(n)

• Average case: O(n)

16.4 Binary Search


Binary search is a more efficient algorithm but requires the data to be sorted.
It works by repeatedly dividing the search interval in half.

16.4.1 Algorithm Steps


1. Find the middle element.

2. Compare it with the target value.

3. If equal, return the index.

4. If the target is smaller, search the left half.

5. If the target is larger, search the right half.

6. Repeat until the value is found or the interval is empty.

16.5 Iterative Binary Search


public class BinarySearch {

public static int search(int[] arr, int key)


{
int left = 0;
int right = [Link] - 1;

while (left <= right)


{
int mid = (left + right) / 2;

if (arr[mid] == key)
return mid;

307
COS 201: Computer Programming I Lecture Notes

if (arr[mid] < key)


left = mid + 1;
else
right = mid - 1;
}

return -1;
}

public static void main(String[] args)


{
int[] data = {10, 20, 30, 40, 50, 60};

int result = search(data, 40);

[Link]("Result index: " + result);


}
}

Output

Result index: 3

16.5.1 Time Complexity


• Best case: O(1)

• Worst case: O(log n)

• Average case: O(log n)

16.6 Recursive Binary Search


Binary search can also be implemented using recursion.
public class RecursiveBinarySearch {

public static int search(int[] arr, int left, int right, int key)
{
if (left > right)
return -1;

int mid = (left + right) / 2;

308
COS 201: Computer Programming I Lecture Notes

if (arr[mid] == key)
return mid;

if (key < arr[mid])


return search(arr, left, mid - 1, key);

return search(arr, mid + 1, right, key);


}

public static void main(String[] args)


{
int[] data = {10, 20, 30, 40, 50};

int result = search(data, 0, [Link] - 1, 40);

[Link]("Found at index: " + result);


}
}

16.7 Linear Search vs Binary Search

Linear Search Binary Search


Works on unsorted data Requires sorted data
Checks each element sequentially Divides data into halves
Time complexity: O(n) Time complexity: O(log n)
Simple to implement More efficient but complex
Suitable for small datasets Suitable for large datasets

Table 16.1: Comparison of Linear and Binary Search

16.8 Advantages of Searching Algorithms


• Helps retrieve data efficiently

• Essential for databases and software systems

• Reduces computation time

• Improves performance of applications

309
COS 201: Computer Programming I Lecture Notes

16.9 Disadvantages
• Linear search is inefficient for large datasets

• Binary search requires sorted data

• Additional preprocessing may be required

16.10 Applications of Searching Algorithms


• Database querying

• File searching systems

• Web search engines

• Data analysis tools

• Artificial intelligence systems

16.11 Common Programming Errors


1. Incorrect loop boundaries in linear search

2. Not handling "element not found" cases

3. Using binary search on unsorted arrays

4. Incorrect mid calculation

5. Infinite loop in iterative binary search

16.12 Best Practices


• Always choose the right algorithm based on data size

• Ensure data is sorted before binary search

• Handle edge cases properly

• Prefer binary search for large sorted datasets

• Use meaningful variable names

310
COS 201: Computer Programming I Lecture Notes

16.13 Chapter Summary


In this chapter, the concept of searching was introduced as a fundamental operation
in computer programming used to locate specific data within a collection of elements.
Searching techniques enable programs to retrieve information efficiently and are widely
applied in databases, information systems, web applications, and many other computing
environments.
The chapter examined two major searching algorithms: linear search and binary
search. Linear search was presented as the simplest searching technique, where each
element in a collection is examined sequentially until the desired item is found or the
end of the collection is reached. Although easy to implement and suitable for small or
unsorted datasets, linear search becomes less efficient as the size of the dataset increases.
Binary search was introduced as a more efficient searching method for sorted datasets.
Unlike linear search, binary search repeatedly divides the search space into two halves,
significantly reducing the number of comparisons required to locate an element. This
divide-and-conquer approach makes binary search much faster than linear search for
large collections of sorted data.
The chapter also discussed both iterative and recursive implementations of binary
search, highlighting how recursion can be used to solve searching problems by repeatedly
applying the same logic to smaller portions of the dataset. Additionally, the advantages,
limitations, and performance characteristics of each searching technique were examined
to help programmers select the most appropriate method for different situations.
Searching algorithms are essential tools in software development, enabling efficient
data retrieval and improving the performance of applications that manage large volumes
of information.

16.14 Review Questions and Exercises


1. Define searching in computer programming. Explain its purpose and discuss why
searching algorithms are important in software development and data processing
applications.

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

18. Explain the concepts of best-case, average-case, and worst-case performance in


searching algorithms. Compare these cases for both linear and binary search.

19. Give at least five real-world applications where searching algorithms are used. Ex-
plain how searching improves the efficiency of these applications.

20. A sorted array contains the values:

10, 20, 30, 40, 50, 60, 70, 80, 90

Show the complete sequence of steps performed by binary search to locate the value
70.

21. Given the array:


15, 28, 39, 42, 55, 63, 77, 81

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.

28. Differentiate between iterative and recursive implementations of binary search.


Compare their readability, memory usage, execution speed, and ease of implemen-
tation.

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.

17.2 Concept of Sorting


Sorting refers to organizing elements in a list or array according to a specific order.
Common sorting orders include:

• Ascending order (smallest to largest)

• Descending order (largest to smallest)

17.3 Importance of Sorting


Sorting is important because it:

• Improves searching efficiency

• Makes data easier to analyze

• Supports data organization in databases

• Enhances user experience in applications

315
COS 201: Computer Programming I Lecture Notes

17.4 Types of Sorting Algorithms


Sorting algorithms can be classified into:

• Simple sorting algorithms (Bubble, Selection, Insertion)

• Efficient sorting algorithms (Merge Sort, Quick Sort)

This chapter focuses on simple sorting techniques.

17.5 Bubble Sort


Bubble Sort is the simplest sorting algorithm. It repeatedly compares adjacent elements
and swaps them if they are in the wrong order.

17.5.1 Algorithm Steps


1. Compare adjacent elements.

2. Swap if the left element is greater than the right element.

3. Repeat for all elements.

4. Continue passes until no swaps are needed.

17.5.2 Java Implementation

public class BubbleSort {

public static void sort(int[] arr)


{
int n = [Link];

for (int i = 0; i < n - 1; i++)


{
for (int j = 0; j < n - i - 1; j++)
{
if (arr[j] > arr[j + 1])
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}

316
COS 201: Computer Programming I Lecture Notes

}
}
}

public static void main(String[] args)


{
int[] data = {5, 1, 4, 2, 8};

sort(data);

for (int num : data)


{
[Link](num + " ");
}
}
}

Output

1 2 4 5 8

17.5.3 Time Complexity


• Best case: O(n) (already sorted)

• Worst case: O(n2 )

• Average case: O(n2 )

17.6 Selection Sort


Selection Sort divides the array into sorted and unsorted parts. It repeatedly selects the
smallest element from the unsorted part and places it in the correct position.

17.6.1 Algorithm Steps


1. Find the minimum element in the array.

2. Swap it with the first element.

3. Move the boundary of the sorted part.

4. Repeat until the array is sorted.

317
COS 201: Computer Programming I Lecture Notes

17.6.2 Java Implementation

public class SelectionSort {

public static void sort(int[] arr)


{
int n = [Link];

for (int i = 0; i < n - 1; i++)


{
int minIndex = i;

for (int j = i + 1; j < n; j++)


{
if (arr[j] < arr[minIndex])
{
minIndex = j;
}
}

int temp = arr[minIndex];


arr[minIndex] = arr[i];
arr[i] = temp;
}
}

public static void main(String[] args)


{
int[] data = {29, 10, 14, 37, 13};

sort(data);

for (int num : data)


{
[Link](num + " ");
}
}
}

Output

10 13 14 29 37

318
COS 201: Computer Programming I Lecture Notes

17.6.3 Time Complexity


• Best case: O(n2 )

• Worst case: O(n2 )

• Average case: O(n2 )

17.7 Insertion Sort


Insertion Sort builds the sorted array one element at a time by inserting each element
into its correct position.

17.7.1 Algorithm Steps


1. Start with the second element.

2. Compare it with previous elements.

3. Shift larger elements to the right.

4. Insert the element in the correct position.

17.7.2 Java Implementation

public class InsertionSort {

public static void sort(int[] arr)


{
int n = [Link];

for (int i = 1; i < n; i++)


{
int key = arr[i];
int j = i - 1;

while (j >= 0 && arr[j] > key)


{
arr[j + 1] = arr[j];
j--;
}

arr[j + 1] = key;

319
COS 201: Computer Programming I Lecture Notes

}
}

public static void main(String[] args)


{
int[] data = {12, 11, 13, 5, 6};

sort(data);

for (int num : data)


{
[Link](num + " ");
}
}
}

Output

5 6 11 12 13

17.7.3 Time Complexity


• Best case: O(n)

• Worst case: O(n2 )

• Average case: O(n2 )

17.8 Comparison of Sorting Algorithms

Algorithm Best Case Average Case Worst Case


Bubble Sort O(n) O(n2 ) O(n2 )
Selection Sort O(n2 ) O(n2 ) O(n2 )
Insertion Sort O(n) O(n2 ) O(n2 )

Table 17.1: Comparison of Sorting Algorithms

17.9 Advantages of Sorting Algorithms


• Organizes data efficiently

• Improves searching performance

320
COS 201: Computer Programming I Lecture Notes

• Useful in databases and file systems

• Essential for algorithm design

17.10 Disadvantages
• Inefficient for large datasets (simple sorts)

• High time complexity in worst cases

• Some algorithms require additional memory

17.11 Applications of Sorting


• Database management systems

• Search engines

• E-commerce platforms

• Data analytics

• Operating systems

17.12 Common Programming Errors


1. Incorrect loop boundaries

2. Wrong swap logic

3. Forgetting array indexing rules

4. Infinite loops in sorting conditions

5. Not handling edge cases (empty arrays)

17.13 Best Practices


• Choose the appropriate sorting algorithm

• Understand data size before selecting algorithm

• Prefer built-in sorting methods for production

• Always test with edge cases

321
COS 201: Computer Programming I Lecture Notes

17.14 Chapter Summary


This chapter introduced the concept of sorting, which is the process of arranging data
in a particular order, such as ascending or descending order. Sorting is one of the most
fundamental operations in computer programming because it helps organize data, making
it easier to access, analyze, and process. Well-organized data improves the performance of
many applications and serves as a foundation for efficient searching and data management
techniques.
The chapter examined several basic sorting algorithms, including Bubble Sort, Selec-
tion Sort, and Insertion Sort. Bubble Sort was presented as a simple comparison-based
algorithm that repeatedly compares adjacent elements and swaps them whenever they
are in the wrong order. Through multiple passes, larger elements gradually move toward
the end of the list until the entire collection is sorted.
Selection Sort was discussed as a method that repeatedly identifies the smallest (or
largest) element from the unsorted portion of the dataset and places it in its correct
position. This process continues until all elements have been arranged in the desired
order. Although Selection Sort performs fewer swaps than Bubble Sort, it still requires
multiple comparisons, making it less suitable for large datasets.
The chapter also introduced Insertion Sort, which builds a sorted sequence one element
at a time. Each new element is compared with the already sorted portion of the list and
inserted into its correct position. Insertion Sort is particularly effective for small datasets
and collections that are already partially sorted, as it can achieve good performance under
such conditions.
Furthermore, the strengths and limitations of these simple sorting algorithms were
analyzed. While Bubble Sort, Selection Sort, and Insertion Sort are relatively easy to
understand and implement, they become inefficient when handling large amounts of data
due to their quadratic time complexity. Nevertheless, they remain valuable for educa-
tional purposes and for applications involving small datasets.

17.15 Review Questions and Exercises


1. Define sorting in computer programming. Explain its purpose and discuss why
sorting is an important operation in data processing and software development.

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.

8. Using the list


64, 25, 12, 22, 11

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.

12. Using the list


9, 5, 1, 4, 3

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?

28. Given the array


45, 23, 78, 12, 56

perform Bubble Sort manually and show the result after each pass.

29. Given the array


31, 14, 59, 26, 41, 58

perform Selection Sort manually and show the state of the array after each pass.

30. Given the array


20, 15, 30, 10, 25

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.

2. Schildt, H. (2018). Java: The Complete Reference, 11th Edition. McGraw-Hill


Education, New York, USA.

3. Liang, Y. D. (2019). Introduction to Java Programming and Data Structures, 12th


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.

6. Horstmann, C. S. (2019). Core Java Volume I–Fundamentals, 11th Edition. Pren-


tice Hall / Pearson, Boston, 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.

10. Liang, Y. D. (2012). Introduction to Java Programming, 9th Edition. Pearson


Education, 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

Laboratory Practical Exercises

A.1 Basic Programming Exercises


1. Average of Numbers

2. Standard Deviation

3. Temperature Conversion

4. Simple Calculator

A.2 Searching Algorithms


1. Linear Search

2. Binary Search

A.3 Sorting Algorithms


1. Bubble Sort

2. Selection Sort

3. Insertion Sort

A.4 Recursion Exercises


1. Factorial

2. Fibonacci Series

3. Sum of Natural Numbers

327

You might also like