0% found this document useful (0 votes)
102 views198 pages

Java Programming Exercises and Solutions

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)
102 views198 pages

Java Programming Exercises and Solutions

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

Java Programming Exercises and

Solutions
Table of Contents
1. Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
2. About the Author . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
3. Book Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
4. How to Use This Book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
5. Additional Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
Chapter 1: Variable Declarations in Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1. Introduction to Java Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.1. The Anatomy of a Java Variable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.2. Types of Variables in Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.3. Best Practices for Variable Declaration. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.4. Exercises. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
Chapter 2: Java Arithmetic Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2. Basic Arithmetic in Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
2.1. Arithmetic Operators in Java. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
2.2. The Math Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
2.3. Best Practices for Arithmetic Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
2.4. Java Data Types and Memory Allocation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
2.5. Choosing the Right Data Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
2.6. Exercises. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
Chapter 3: Java Control Structures. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
3. If Statements and Loops in Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
3.1. Conditional Statements. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
3.2. Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
3.3. Best Practices for Control Structures. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
3.4. Common Pitfalls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
3.5. Exercises. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
Chapter 4: Arrays in Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
4. Arrays in Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
4.1. Declaring and Initializing Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
4.2. Common Array Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
4.3. Best Practices for Working with Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
4.4. Common Pitfalls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
4.5. Exercises. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
Chapter 5: Methods in Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
5. Methods in Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
5.1. Defining Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
5.2. Return Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
5.3. Method Overloading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
5.4. Varargs (Variable-Length Argument Lists). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
5.5. Best Practices for Methods. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
5.6. Common Pitfalls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
5.7. Exercises. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
Chapter 6: Classes and Objects in Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
6. Classes and Objects in Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
6.1. Defining Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
6.2. Creating Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
6.3. Constructors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
6.4. Instance Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
6.5. Instance Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
6.6. Access Modifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
6.7. Getters and Setters. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
6.8. Method Overloading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
6.9. The this Keyword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
6.10. Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
Chapter 7: Inheritance in Java. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
7. Inheritance in Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
7.1. Defining Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
7.2. Creating Subclass Objects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
7.3. Method Overriding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
7.4. The super Keyword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
7.5. Constructors and Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
7.6. Inheritance Best Practices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
7.7. Exercises. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
Chapter 8: Polymorphism in Java. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
8. Polymorphism in Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
8.1. Types of Polymorphism . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
8.2. Method Overloading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
8.3. Exercises. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Chapter 9: Abstraction in Java. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
9. Abstraction in Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
9.1. Abstract Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
9.2. Abstract Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
9.3. Benefits of Abstraction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
9.4. Exercises. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
Chapter 10: Interfaces in Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
10. Interfaces in Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
10.1. Defining Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
10.2. Implementing Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
10.3. Default Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
10.4. Static Methods. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
10.5. Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
Chapter 11: Exceptions in Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
11. Exceptions in Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
11.1. Built-in Exceptions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
11.2. User-Defined Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
11.3. Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
Appendix A: SolutionsSolutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
A.1. Chapter 1 Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
A.2. Chapter 2 Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
A.3. Chapter 3 Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
A.4. Chapter 4 Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
A.5. Chapter 5 Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
A.6. Chapter 6 Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
A.7. Chapter 7 Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
A.8. Chapter 8 Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134
A.9. Chapter 9 Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
A.10. Chapter 10 Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
A.11. Chapter 11 Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164
A.12. Chapter 11 Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
By altmemy

1
1. Preface
Welcome to "Java Programming Exercises and Solutions," a comprehensive guide designed to
enhance your Java programming skills. This book caters to both beginners and intermediate
programmers, offering a structured approach to mastering Java through practical exercises and
detailed solutions.

2. About the Author


This book is authored by altmemy, an experienced Java programmer and educator dedicated to
helping others excel in the field of software development.

3. Book Structure
Each chapter in this book is carefully crafted to cover specific Java topics, presenting:

1. A series of targeted exercises to reinforce key concepts

2. Comprehensive solutions with explanations to deepen understanding

3. Progressive difficulty levels to challenge and grow your skills

4. How to Use This Book


To maximize your learning experience:

1. Attempt each exercise independently before reviewing the solution

2. Study the provided solutions to understand alternative approaches

3. Practice regularly to reinforce your learning

5. Additional Resources
For further assistance and discussion:

• Follow the author on Twitter: altmemy

• Join our community on Telegram: java

We encourage you to engage with these platforms for questions, clarifications, and to connect with
fellow Java enthusiasts.

Thank you for choosing "Java Programming Exercises and Solutions." We hope this
book serves as a valuable resource in your journey to Java mastery.

Happy coding!

altmemy

2
Chapter 1: Variable Declarations in
Java
This chapter introduces the fundamental concepts of variable declarations in
Java, covering various data types and their usage in programming.

3
Chapter 1. Introduction to Java Variables
Variables are the cornerstone of any programming language, and Java is no exception. A variable is
essentially a container that holds a value in a computer’s memory. Understanding how to declare
and use variables effectively is crucial for writing efficient and maintainable Java code.

1.1. The Anatomy of a Java Variable


In Java, a variable declaration typically consists of three parts:

1. Data Type: Specifies what kind of data the variable will store (e.g., int, double, String).

2. Variable Name: A unique identifier for the variable.

3. Initial Value (optional): The starting value assigned to the variable.

The general syntax is:

dataType variableName = initialValue;

1.2. Types of Variables in Java


Java provides several types of variables, each serving a specific purpose:

1.2.1. Primitive Data Types:

• byte, short, int, long for integer values

• float, double for floating-point numbers

• boolean for true/false values

• char for single characters

1.2.2. Reference Data Types:

• String for text

• Arrays

• Objects of classes

1.2.3. Based on Scope and Lifetime:

• Local Variables: Declared within a method

• Instance Variables: Associated with an instance of a class

• Static Variables: Shared across all instances of a class

4
1.3. Best Practices for Variable Declaration
1.3.1. Naming Conventions:

• Use camelCase for variable names (e.g., myVariable)

• Choose descriptive names that reflect the variable’s purpose

1.3.2. Initialization:

• Initialize variables when declared, if possible

• Use the final keyword for constants

1.3.3. Scope Management:

• Declare variables in the narrowest scope possible

• Avoid global variables when local variables suffice

1.3.4. Type Selection:

• Choose the appropriate data type based on the data’s nature and range

• Consider memory usage and performance implications

By mastering variable declarations, you lay a solid foundation for your Java
 programming journey. The exercises in this chapter will help you practice these
concepts and reinforce your understanding of Java variables.

1.4. Exercises
1. Declare an integer variable to store your age.

2. Create a String variable for your name and assign it a value.

3. Define a constant for the value of pi using the final keyword.

4. Declare a boolean variable to indicate if a user is active.

5. Create a double variable to store the height of a person.

6. Define a character variable to store the first letter of your name.

7. Declare an integer array to store the first 5 prime numbers.

8. Create a String array to store the names of the days of the week.

9. Define a float variable for the price of a product.

10. Declare a long variable to store the population of a country.

11. Create a byte variable to store the age of a child.

12. Define a short variable to store the number of pages in a book.

13. Declare a String variable to store an email address.

5
14. Create an integer variable to store the current year.

15. Define a constant for the speed of light in a vacuum (299,792,458 m/s).

16. Declare a boolean variable to indicate if a number is prime.

17. Create a double array to store the grades of a student.

18. Define a character array to store the vowels (a, e, i, o, u).

19. Declare a float variable to store the temperature in Celsius.

20. Create a long variable to store the distance between Earth and the Sun (in kilometers).

6
Chapter 2: Java Arithmetic
Operations
This chapter introduces the fundamental concepts of variable declarations in
Java, covering various data types and their usage in programming.

7
Chapter 2. Basic Arithmetic in Java
Arithmetic operations are at the heart of many programming tasks. Java provides a robust set of
operators to perform various mathematical calculations, from simple addition to more complex
operations.

2.1. Arithmetic Operators in Java


Java supports the following basic arithmetic operators:

Addition (+): Adds two operands Subtraction (-): Subtracts the second operand from the first
Multiplication ()*: Multiplies two operands Division (/): Divides the first operand by the second
Modulus (%): Returns the remainder when the first operand is divided by the second

2.1.1. Order of Operations

Java follows the standard mathematical order of operations (PEMDAS):

Parentheses Exponents (handled by Math.pow() in Java) Multiplication and Division (left to right)
Addition and Subtraction (left to right)

2.1.2. Integer vs. Floating-Point Arithmetic

It’s crucial to understand the difference between integer and floating-point arithmetic in Java:

Integer division truncates the result (e.g., 5 / 2 equals 2, not 2.5) To get a floating-point result, at least
one operand must be a floating-point number

2.1.3. Type Casting in Arithmetic Operations

When performing operations with different data types, Java uses automatic type promotion:

If one operand is a double, the other is converted to double If one operand is a float, the other is
converted to float If one operand is a long, the other is converted to long Otherwise, both operands
are converted to int

2.2. The Math Class


Java’s Math class provides additional mathematical operations:

Math.abs(): Absolute value Math.pow(): Exponentiation Math.sqrt(): Square root Math.random():


Random number generation

2.3. Best Practices for Arithmetic Operations


Be aware of integer division: Use casting or floating-point numbers when precise results are needed
Avoid division by zero: Always check for zero before using it as a divisor Use parentheses for
clarity: Even when not strictly necessary, parentheses can make your code more readable Be

8
mindful of overflow: Large calculations can exceed the limits of int or long

Understanding these concepts will allow you to perform accurate calculations in your Java
programs and avoid common pitfalls associated with arithmetic operations.

2.4. Java Data Types and Memory Allocation


Understanding the memory allocation for different data types is crucial for efficient programming.
Here’s a comprehensive table of Java’s primitive data types, their size in memory, value range, and
typical usage:

Data Type Size (bits) Size (bytes) Value Range Typical Usage

byte 8 1 -128 to 127 Small integer values,


saving memory in large
arrays

short 16 2 -32,768 to 32,767 Short integer values,


conserving memory
31 31
int 32 4 -2 to 2 -1 Default choice for
integer values
63 63
long 64 8 -2 to 2 -1 Large integer values,
timestamps

float 32 4 ±3.4E±38 (7 decimal Fractional numbers,


digits) conserving memory

double 64 8 ±1.7E±308 (15 decimal Default choice for


digits) decimal values, precise
calculations

boolean 1 1 (or 4) true or false Logical conditions,


flags

char 16 2 0 to 65,535 Single Unicode


characters

The actual memory usage of boolean can vary. While it only needs 1 bit to store its
value, for efficiency reasons, JVM might use a full byte or even 4 bytes. Reference
 data types (like String, arrays, and objects) use different amounts of memory
depending on their content and implementation.

2.5. Choosing the Right Data Type


When selecting a data type, consider:

Range of values: Choose a type that can accommodate all possible values. Precision: For floating-
point numbers, consider the required decimal precision. Memory efficiency: In large-scale
applications or arrays, using smaller data types can significantly reduce memory usage.
Performance: Operations on smaller data types can be faster, but this is often negligible in modern

9
JVMs. Compatibility: Ensure the chosen type is compatible with libraries or methods you’re using.

By understanding these characteristics, you can make informed decisions about which data type to
use in different scenarios, balancing between memory usage, precision, and performance
requirements.

2.6. Exercises
1. Write a Java expression to add two numbers.

2. Create a Java expression to subtract one number from another.

3. Write a Java expression to multiply two numbers.

4. Create a Java expression to divide one number by another.

5. Write a Java expression to find the remainder of the division of two numbers (modulus).

6. Create a Java expression to calculate the square of a number.

7. Write a Java expression to calculate the cube of a number.

8. Create a Java expression to calculate the square root of a number using Math.sqrt().

9. Write a Java expression to calculate the power of a number using Math.pow().

10. Create a Java expression to convert inches to centimeters (1 inch = 2.54 cm).

11. Write a Java expression to calculate the perimeter of a rectangle.

12. Create a Java expression to calculate the area of a triangle.

13. Write a Java expression to convert kilometers to miles (1 km ≈ 0.621371 miles).

14. Create a Java expression to calculate the circumference of a circle (C = 2 * π * r).

15. Write a Java expression to calculate the volume of a cube.

16. Create a Java expression to calculate the volume of a sphere (V = 4/3 * π * r^3).

17. Write a Java expression to calculate the average of four numbers.

18. Create a Java expression to find the maximum of three numbers using Math.max().

19. Write a Java expression to find the minimum of three numbers using Math.min().

20. Create a Java expression to calculate the absolute value of a number using Math.abs().

10
Chapter 3: Java Control Structures
This chapter explores the fundamental control structures in Java, focusing on
conditional statements and loops. These structures form the backbone of
program flow and logic in Java applications.

11
Chapter 3. If Statements and Loops in Java
Control structures in Java allow you to control the flow of your program’s execution. They enable
you to make decisions, repeat actions, and create complex logic in your applications. The two main
categories we’ll focus on are conditional statements (if-else) and loops.

3.1. Conditional Statements


Conditional statements allow your program to make decisions based on certain conditions.

3.1.1. If-Else Statement

The basic structure of an if-else statement is:

if (condition) {
// code to execute if condition is true
} else {
// code to execute if condition is false
}
You can also use else-if for multiple conditions:
[source,java]
if (condition1) {
// code for condition1
} else if (condition2) {
// code for condition2
} else {
// code if no condition is true
}

3.1.2. Switch Statement

For multiple condition checking, a switch statement can be more efficient:

switch (variable) {
case value1:
// code for value1
break;
case value2:
// code for value2
break;
default:
// default code
}

12
3.2. Loops
Loops allow you to repeat a block of code multiple times.

3.2.1. For Loop

Used when you know how many times you want to repeat a block of code:

for (initialization; condition; update) {


// code to repeat
}

3.2.2. While Loop

Used when you want to repeat a block of code while a condition is true:

while (condition) {
// code to repeat
}

3.2.3. Do-While Loop

Similar to while loop, but ensures the code block is executed at least once:

do {
// code to repeat
} while (condition);

3.2.4. Enhanced For Loop (For-Each)

Used for iterating through arrays or collections:

for (dataType item : collection) {


// code to process item
}

3.3. Best Practices for Control Structures


Keep it simple: Avoid deeply nested conditions or loops when possible. Use meaningful names: For
loop variables and conditions, use descriptive names. Consider readability: Sometimes a switch
statement is more readable than multiple if-else statements. Be careful with infinite loops: Ensure
your loop conditions will eventually become false. Use braces: Even for single-line blocks, use
braces to improve readability and prevent errors.

13
3.4. Common Pitfalls
Off-by-one errors: Be careful with loop boundaries, especially when using < or ⇐ in for loops.
Confusing = and ==: Remember, = is for assignment, == is for comparison. Forgetting break in
switch statements: Without break, execution "falls through" to the next case. Infinite loops: Always
ensure there’s a way for your loops to terminate.

Understanding these control structures is crucial for writing efficient and logical Java programs.
The exercises in this chapter will help you practice implementing these concepts in real code.

3.5. Exercises
1. Write an if-else statement in Java to check if a number is positive or negative.

2. Create a for loop to print the first 10 even numbers.

3. Use a switch statement to display the day of the week based on a number input.

4. Write a while loop to calculate the sum of the first 100 natural numbers.

5. Create a do-while loop to print numbers from 1 to 10.

6. Write an if-else-if statement to grade students based on their marks.

7. Create a nested for loop to print a multiplication table for numbers 1 through 5.

8. Use a break statement to exit a loop when a specific condition is met.

9. Write a continue statement to skip printing even numbers in a loop from 1 to 10.

10. Create an enhanced for loop to iterate over an array of integers.

11. Write a program to find the largest of three numbers using nested if-else statements.

12. Create a program to print the Fibonacci series using a for loop.

13. Write a program to reverse the digits of a number using a while loop.

14. Create a program to count the number of vowels in a string using a for loop.

15. Write a program to check if a number is prime using a for loop.

16. Create a program to find the factorial of a number using a while loop.

17. Write a program to find the sum of digits of a number using a while loop.

18. Create a program to print all prime numbers between 1 and 100 using a for loop.

19. Write a program to check if a string is a palindrome using an if statement and a loop.

20. Create a program to find the GCD (Greatest Common Divisor) of two numbers using a while
loop.

21. Write a Java program to count the number of even and odd numbers in an array.

22. Create a program to print all the prime numbers between 50 and 150.

23. Write a Java program to check if a year is a leap year using if-else statements.

24. Create a Java program to find the smallest number in an array using a for loop.

25. Write a program to print a pattern of stars in a right-angled triangle using nested loops.

14
26. Create a Java program to check if two strings are anagrams using loops.

27. Write a program to count the occurrences of a character in a string using a for loop.

28. Create a Java program to reverse an array using a for loop.

29. Write a Java program to find the second smallest number in an array.

30. Create a program to calculate the power of a number using a loop instead of Math.pow().

31. Write a Java program to print the sum of the first n odd numbers.

32. Create a Java program to find the length of the longest consecutive sequence of zeros in a binary
string.

33. Write a Java program to print a diamond pattern using nested loops.

34. Create a Java program to implement a basic calculator using if-else statements and a loop.

35. Write a Java program to rotate the elements of an array to the right by a given number of
positions.

36. Create a Java program to find the sum of all prime numbers between 1 and 200.

37. Write a Java program to calculate the sum of the series 1 + 1/2 + 1/3 + … + 1/n.

38. Create a Java program to check if a given number is an Armstrong number.

39. Write a Java program to find the factorial of a number using recursion.

40. Create a Java program to print the Pascal’s triangle up to n rows using nested loops.

15
Chapter 4: Arrays in Java
This chapter delves into arrays, a fundamental data structure in Java used to
store collections of elements of the same type. We’ll explore one-dimensional
and multi-dimensional arrays, common operations, and best practices for
working with arrays.

16
Chapter 4. Arrays in Java
Arrays in Java provide a powerful and efficient way to handle collections of data. They offer fixed-
size, ordered collections of elements, all of the same type.

4.1. Declaring and Initializing Arrays


4.1.1. One-Dimensional Arrays

int[] numbers;
// Declaration and initialization
int[] numbers = new int[5]; // Creates an array of 5 integers
// Declaration, creation and initialization
int[] numbers = {1, 2, 3, 4, 5};

4.1.2. Multi-Dimensional Arrays

int[][] matrix = new int[3][3];


// Three-dimensional array
int[][][] cube = new int[3][3][3];
// Jagged array (arrays of arrays)
int[][] jagged = new int[3][];
jagged[0] = new int[1];
jagged[1] = new int[2];
jagged[2] = new int[3];

4.2. Common Array Operations


Accessing Elements:

Use index notation: array[index] Remember: Array indices start at 0

Iterating Through Arrays:

Using for loop:

for (int i = 0; i < array.length; i++) {


System.out.println(array[i]);
}

Using enhanced for loop:

for (int element : array) {


System.out.println(element);

17
}

Array Length:

Use the length property: array.length

Copying Arrays:

Using System.arraycopy():

System.arraycopy(sourceArray, srcPos, destArray, destPos, length);

Using Arrays.copyOf():

int[] newArray = Arrays.copyOf(originalArray, newLength);

Sorting Arrays:

Use Arrays.sort(array) for ascending order For descending order or custom sorting, use
Arrays.sort(array, Collections.reverseOrder()) or implement a custom Comparator

4.3. Best Practices for Working with Arrays


Choose the Right Size: Estimate the maximum size needed to avoid unnecessary memory allocation.
Use Enhanced For Loop: When possible, use the enhanced for loop for cleaner and more readable
code. Bounds Checking: Always ensure you’re not accessing elements outside the array bounds to
avoid ArrayIndexOutOfBoundsException. Prefer ArrayList for Dynamic Sizing: If you need a
dynamically sized array, consider using ArrayList instead. Use Arrays Utility Methods: Leverage the
java.util.Arrays class for common operations like sorting, searching, and filling arrays. Consider
Memory Usage: Large arrays can consume significant memory. Use appropriate data types and
consider alternative data structures for very large datasets. Initialization: Always initialize arrays
before use to avoid NullPointerException. Multi-Dimensional Arrays: Be cautious with multi-
dimensional arrays as they can quickly become complex. Consider using objects or more
specialized data structures for complex data relationships.

4.4. Common Pitfalls


Off-by-One Errors: Remember that array indices start at 0 and go up to length - 1. Forgetting to
Initialize: Declaring an array without initializing it can lead to NullPointerException. Assuming All
Elements are Initialized: When you create a new array, primitive types are initialized to their
default values, but object references are null. Inefficient Resizing: Frequently resizing arrays can be
inefficient. If you need a dynamic size, consider using ArrayList.

Understanding arrays is crucial for effective Java programming. They form the basis for many more
complex data structures and are essential in solving a wide range of programming problems.

18
4.5. Exercises
1. Write a Java program to declare and initialize an integer array with five elements.

2. Create a Java program to find the sum of all elements in an integer array.

3. Write a Java program to find the average of elements in a double array.

4. Create a Java program to find the maximum element in an integer array.

5. Write a Java program to find the minimum element in an integer array.

6. Create a Java program to reverse an integer array.

7. Write a Java program to sort an integer array in ascending order.

8. Create a Java program to sort an integer array in descending order.

9. Write a Java program to find the second largest element in an integer array.

10. Create a Java program to merge two integer arrays into a third array.

11. Write a Java program to remove duplicate elements from an integer array.

12. Create a Java program to find the intersection of two integer arrays.

13. Write a Java program to find the union of two integer arrays.

14. Create a Java program to shift elements of an integer array to the left by one position.

15. Write a Java program to shift elements of an integer array to the right by one position.

16. Create a Java program to find the frequency of each element in an integer array.

17. Write a Java program to check if an integer array contains a specific value.

18. Create a Java program to copy an integer array to another array.

19. Write a Java program to find the common elements between two integer arrays.

20. Create a Java program to find the difference between two integer arrays.

21. Write a Java program to initialize a 2D integer array with dimensions 3x3.

22. Create a Java program to calculate the sum of all elements in a 2D array.

23. Write a Java program to find the maximum element in a 2D array.

24. Create a Java program to find the minimum element in a 2D array.

25. Write a Java program to print the elements of a 2D array in matrix form.

26. Create a Java program to calculate the sum of each row in a 2D array.

27. Write a Java program to calculate the sum of each column in a 2D array.

28. Create a Java program to transpose a 2D array.

29. Write a Java program to check if a 2D array is a square matrix.

30. Create a Java program to find the main diagonal elements of a 2D array.

31. Write a Java program to find the secondary diagonal elements of a 2D array.

32. Create a Java program to find the sum of the main diagonal elements in a 2D array.

33. Write a Java program to find the sum of the secondary diagonal elements in a 2D array.

19
34. Create a Java program to calculate the sum of the border elements of a 2D array.

35. Write a Java program to count the occurrences of a specific value in a 2D array.

36. Create a Java program to multiply two 2D arrays.

37. Write a Java program to add two 2D arrays.

38. Create a Java program to subtract one 2D array from another.

39. Write a Java program to check if two 2D arrays are equal.

40. Create a Java program to flatten a 2D array into a 1D array.

20
Chapter 5: Methods in Java
This chapter explores methods in Java, a fundamental concept in object-oriented
programming. We’ll cover defining, calling, and using methods, along with
important concepts like parameters, return values, and method overloading.

21
Chapter 5. Methods in Java
Methods in Java are blocks of code that perform specific tasks. They are essential for organizing
code, promoting reusability, and implementing the principle of modularity in Java programs.

5.1. Defining Methods


The basic structure of a method in Java is:

accessModifier returnType methodName(parameterList) {


// method body
return returnValue; // if applicable
}
For example:
[source,java]
public int add(int a, int b) {
return a + b;
}

5.1.1. Method Components

Access Modifier: Determines the visibility of the method (e.g., public, private, protected). Return
Type: Specifies the type of value the method returns (or void if it doesn’t return anything). Method
Name: A descriptive name for the method, following Java naming conventions. Parameter List:
Input values the method accepts (can be empty). Method Body: The actual code that performs the
task. Return Statement: Used to return a value from the method (if the return type is not void).

5.1.2. Calling Methods

Methods are called by using the method name followed by parentheses containing any required
arguments:

int result = add(5, 3); // Calling the add method

5.1.3. Parameters and Arguments

Parameters are variables in the method declaration. Arguments are the actual values passed to the
method when it’s called.

Parameter Passing

Pass by Value: Java uses pass-by-value for primitive types. Pass by Reference: For objects, the
reference is passed by value.

22
5.2. Return Values
Methods can return a single value of the specified return type. Use return statement to send a value
back to the caller. Methods declared as void don’t return a value.

5.3. Method Overloading


Method overloading allows multiple methods with the same name but different parameter lists:

public int add(int a, int b) {


return a + b;
}
public double add(double a, double b) {
return a + b;
}

5.4. Varargs (Variable-Length Argument Lists)


Varargs allow a method to accept an arbitrary number of arguments:

public int sum(int... numbers) {


int total = 0;
for (int num : numbers) {
total += num;
}
return total;
}

5.5. Best Practices for Methods


Single Responsibility: Each method should perform a single, well-defined task. Descriptive Names:
Use clear, descriptive names that indicate what the method does. Keep Methods Short: Aim for
methods that are 20-30 lines or less for better readability. Minimize Parameters: Try to keep the
number of parameters to 4 or fewer. Use Comments: Provide JavaDoc comments for public methods
explaining purpose, parameters, and return values. Consistent Abstraction Level: Methods within a
class should have a consistent level of abstraction. Avoid Side Effects: Methods should not
unexpectedly alter the state of the program.

5.6. Common Pitfalls


Overusing Static Methods: While useful, overuse can lead to procedural rather than object-oriented
code. Ignoring Return Values: Always consider what to do with returned values. Method Naming
Confusion: Ensure method names clearly convey their purpose. Excessive Method Overloading: Can
lead to confusion and maintenance issues.

23
Understanding methods is crucial for writing clean, efficient, and maintainable Java code. They
form the building blocks of Java programs and are fundamental to object-oriented design.

5.7. Exercises
1. Write a Java method to find the maximum of two numbers.

2. Create a Java method to calculate the factorial of a number.

3. Write a Java method to check if a number is prime.

4. Create a Java method to reverse a string.

5. Write a Java method to calculate the power of a number.

6. Create a Java method to find the greatest common divisor (GCD) of two numbers.

7. Write a Java method to check if a string is a palindrome.

8. Create a Java method to find the sum of digits of a number.

9. Write a Java method to convert a binary number to a decimal number.

10. Create a Java method to find the length of the longest word in a string.

11. Write a Java method to print the Fibonacci series up to a given number.

12. Create a Java method to find the average of an array of integers.

13. Write a Java method to check if a character is a vowel.

14. Create a Java method to calculate the area of a rectangle.

15. Write a Java method to count the occurrences of a character in a string.

16. Create a Java method to find the minimum element in an array of integers.

17. Write a Java method to sort an array of integers in ascending order.

18. Create a Java method to merge two arrays into a third array.

19. Write a Java method to find the second largest element in an array of integers.

20. Create a Java method to print a 2D array.

21. Write a Java method to find the sum of two numbers.

22. Create a Java method to find the product of two numbers.

23. Write a Java method to find the difference between two numbers.

24. Create a Java method to find the quotient and remainder of two numbers.

25. Write a Java method to convert Celsius to Fahrenheit.

26. Create a Java method to convert Fahrenheit to Celsius.

27. Write a Java method to find the perimeter of a rectangle.

28. Create a Java method to find the area of a circle.

29. Write a Java method to check if a string contains a specific character.

30. Create a Java method to find the maximum element in an array of doubles.

31. Write a Java method to find the median of an array of integers.

24
32. Create a Java method to find the mode of an array of integers.

33. Write a Java method to calculate the compound interest.

34. Create a Java method to find the HCF (Highest Common Factor) of two numbers.

35. Write a Java method to generate a random number within a given range.

36. Create a Java method to count the number of words in a string.

37. Write a Java method to capitalize the first letter of each word in a string.

38. Create a Java method to find the standard deviation of an array of doubles.

39. Write a Java method to count the number of vowels in a string.

40. Create a Java method to check if a given year is a leap year.

25
Chapter 6: Classes and Objects in
Java
This chapter delves into classes and objects in Java, the cornerstones of object-
oriented programming. We’ll cover defining classes, creating objects, using
constructors, and understanding instance variables and methods.

26
Chapter 6. Classes and Objects in Java
In Java, classes and objects are fundamental to creating reusable and modular code. A class is a
blueprint for objects, and objects are instances of classes.

6.1. Defining Classes


A class in Java is defined using the class keyword. Here is the basic structure:

accessModifier class ClassName {


// fields (instance variables)
// constructors
// methods
}

For example:

public class Car {


// fields
String color;
String model;

// constructor
public Car(String color, String model) {
this.color = color;
this.model = model;
}

// method
public void displayInfo() {
System.out.println("Color: " + color + ", Model: " + model);
}
}

6.2. Creating Objects


Objects are instances of classes created using the new keyword:

Car myCar = new Car("Red", "Toyota");


myCar.displayInfo(); // Calling the method

6.3. Constructors
Constructors are special methods used to initialize objects. They have the same name as the class

27
and do not have a return type:

public Car(String color, String model) {


this.color = color;
this.model = model;
}

6.4. Instance Variables


Instance variables are attributes of an object, defined within a class but outside any method:

public class Car {


String color;
String model;
// ...
}

6.5. Instance Methods


Instance methods are functions defined within a class that operate on instance variables:

public void displayInfo() {


System.out.println("Color: " + color + ", Model: " + model);
}

6.6. Access Modifiers


Access modifiers define the visibility of classes, methods, and variables. The most common are: -
public: Accessible from any other class. - private: Accessible only within the class it’s defined. -
protected: Accessible within the same package and subclasses.

6.7. Getters and Setters


Getters and setters are methods used to access and modify private instance variables:

public class Car {


private String color;
private String model;

public String getColor() {


return color;
}

public void setColor(String color) {

28
this.color = color;
}

public String getModel() {


return model;
}

public void setModel(String model) {


this.model = model;
}
}

6.8. Method Overloading


Method overloading allows multiple methods with the same name but different parameter lists:

public void displayInfo() {


System.out.println("Color: " + color + ", Model: " + model);
}

public void displayInfo(String prefix) {


System.out.println(prefix + ": Color: " + color + ", Model: " + model);
}

6.9. The this Keyword


The this keyword refers to the current instance of the class. It’s often used to distinguish instance
variables from parameters:

public Car(String color, String model) {


this.color = color;
this.model = model;
}

6.10. Exercises
1. Write a Java class called Person with fields for name and age, and a method to display the
person’s details.

2. Create a class named Rectangle with fields for width and height. Include methods to calculate
the area and perimeter.

3. Define a Book class with attributes for title, author, and price. Implement a method to display the
book details.

4. Write a class Circle with a field for radius. Provide methods to calculate the area and
circumference.

29
5. Create a BankAccount class with fields for account number, account holder name, and balance.
Implement deposit and withdrawal methods.

6. Develop a Student class with fields for name, ID, and grades. Include a method to calculate the
average grade.

7. Define a class Employee with attributes for name, ID, and salary. Write methods to give a raise
and display the employee’s details.

8. Write a class Dog with fields for name, breed, and age. Implement a method to display the dog’s
details.

9. Create a Laptop class with fields for brand, model, and price. Include a method to display the
laptop details.

10. Develop a Movie class with attributes for title, genre, and rating. Write a method to display the
movie details.

11. Define a Point class with fields for x and y coordinates. Implement methods to calculate the
distance to another point.

12. Write a class Triangle with fields for the lengths of its sides. Provide methods to calculate the
perimeter and area.

13. Create a Song class with attributes for title, artist, and duration. Include a method to display the
song details.

14. Develop a Flight class with fields for flight number, destination, and departure time. Implement
a method to display the flight details.

15. Define a House class with attributes for address, number of rooms, and price. Write a method to
display the house details.

16. Write a class Phone with fields for brand, model, and price. Implement a method to display the
phone details.

17. Create a Car class with attributes for make, model, and year. Include a method to display the car
details.

18. Develop a City class with fields for name, population, and country. Write a method to display
the city details.

19. Define a Teacher class with attributes for name, subject, and years of experience. Implement a
method to display the teacher’s details.

20. Write a class Camera with fields for brand, model, and resolution. Include a method to display
the camera details.

21. Write a Java class called Student with fields for student ID, name, and major. Include a method
to display the student’s information.

22. Create a class named Animal with fields for species, age, and habitat. Implement a method to
display the animal’s details.

23. Define a Product class with attributes for product ID, name, and price. Write a method to display
the product details.

24. Develop a Bank class with fields for bank name, branch, and location. Include methods to add
and display branch details.

30
25. Write a class Library with fields for library name and a list of books. Implement methods to add
books and display the library’s book list.

26. Create a Restaurant class with attributes for name, address, and a list of menu items. Write
methods to add and display menu items.

27. Define a Course class with fields for course name, code, and credits. Implement a method to
display the course details.

28. Develop a Department class with attributes for department name, head of department, and a list
of courses. Include methods to add courses and display department details.

29. Write a class Hospital with fields for hospital name, address, and a list of doctors. Implement
methods to add and display doctors' details.

30. Create a University class with attributes for university name, location, and a list of departments.
Write methods to add and display department details.

31. Define a Schedule class with fields for day, time, and activity. Implement a method to display the
schedule details.

32. Develop a Gym class with attributes for gym name, location, and a list of equipment. Include
methods to add and display equipment details.

33. Write a class Patient with fields for patient ID, name, and medical history. Implement a method
to display the patient’s details.

34. Create a Doctor class with attributes for doctor ID, name, and specialty. Include a method to
display the doctor’s details.

35. Define a LibraryMember class with fields for member ID, name, and a list of borrowed books.
Write methods to add and display borrowed books.

36. Develop a Conference class with attributes for conference name, date, and a list of speakers.
Include methods to add and display speaker details.

37. Write a class Magazine with fields for title, issue number, and publication date. Implement a
method to display the magazine details.

38. Create a Museum class with attributes for museum name, location, and a list of exhibits. Write
methods to add and display exhibit details.

39. Define a Vehicle class with fields for make, model, and year. Implement methods to display the
vehicle details and calculate the vehicle’s age.

40. Develop a Workshop class with attributes for workshop title, date, and a list of participants.
Include methods to add and display participant details.

41. Write a class Festival with fields for festival name, location, and a list of events. Implement
methods to add and display event details.

42. Create a Hotel class with attributes for hotel name, location, and a list of rooms. Write methods
to add and display room details.

43. Define a Park class with fields for park name, location, and a list of facilities. Implement
methods to add and display facility details.

44. Develop a Zoo class with attributes for zoo name, location, and a list of animals. Include methods
to add and display animal details.

31
45. Write a class Concert with fields for concert name, date, and a list of performers. Implement
methods to add and display performer details.

46. Create a Festival class with attributes for festival name, date, and a list of activities. Write
methods to add and display activity details.

47. Define a SportsTeam class with fields for team name, sport, and a list of players. Implement
methods to add and display player details.

48. Develop a MuseumExhibit class with attributes for exhibit name, description, and date of display.
Include methods to add and display exhibit details.

49. Write a class Event with fields for event name, date, and location. Implement a method to
display the event details.

50. Create a Company class with attributes for company name, industry, and a list of employees.
Write methods to add and display employee details.

32
Chapter 7: Inheritance in Java
This chapter explores inheritance in Java, a key feature of object-oriented
programming that allows one class to inherit fields and methods from another.
We’ll cover the basics of inheritance, the extends keyword, method overriding,
and the super keyword.

33
Chapter 7. Inheritance in Java
Inheritance enables the creation of a new class based on an existing class. The new class, known as
the subclass or derived class, inherits attributes and methods from the existing class, called the
superclass or base class.

7.1. Defining Inheritance


To define inheritance in Java, use the extends keyword. Here is the basic structure:

class Superclass {
// fields
// methods
}

class Subclass extends Superclass {


// additional fields
// additional methods
}

For example:

public class Animal {


public void eat() {
System.out.println("This animal eats food.");
}
}

public class Dog extends Animal {


public void bark() {
System.out.println("The dog barks.");
}
}

7.2. Creating Subclass Objects


You can create an object of the subclass and access both its own methods and the inherited
methods:

Dog myDog = new Dog();


myDog.eat(); // Inherited method
myDog.bark(); // Subclass method

34
7.3. Method Overriding
Method overriding occurs when a subclass provides a specific implementation of a method already
defined in its superclass. The method in the subclass should have the same name, return type, and
parameters as the method in the superclass:

public class Animal {


public void makeSound() {
System.out.println("This animal makes a sound.");
}
}

public class Dog extends Animal {


@Override
public void makeSound() {
System.out.println("The dog barks.");
}
}

7.4. The super Keyword


The super keyword refers to the superclass and can be used to access superclass methods and
constructors:

public class Animal {


public void eat() {
System.out.println("This animal eats food.");
}
}

public class Dog extends Animal {


@Override
public void eat() {
super.eat(); // Calls the superclass method
System.out.println("The dog eats kibble.");
}
}

7.5. Constructors and Inheritance


A subclass inherits all the constructors of its superclass but cannot directly access them unless
using super(). The super() call must be the first statement in the subclass constructor:

public class Animal {


private String name;

35
public Animal(String name) {
this.name = name;
}
}

public class Dog extends Animal {


public Dog(String name) {
super(name); // Calls the superclass constructor
}
}

7.6. Inheritance Best Practices


• Use inheritance to represent an "is-a" relationship.

• Favor composition over inheritance if the relationship is not strictly hierarchical.

• Avoid deep inheritance hierarchies as they can be hard to manage and understand.

7.7. Exercises
1. Create a superclass Vehicle with a method move(). Define a subclass Car that overrides the move()
method.

2. Define a class Person with a method display(). Create a subclass Employee that adds an
employeeId field and overrides the display() method.

3. Write a superclass Shape with a method area(). Implement subclasses Circle and Rectangle that
calculate the area specific to their shapes.

4. Define a superclass BankAccount with fields accountNumber and balance. Create a subclass
SavingsAccount that adds an interestRate field and a method to calculate interest.

5. Create a class Book with a method read(). Define a subclass EBook that overrides the read()
method to include reading on an electronic device.

6. Write a superclass Animal with a method sound(). Implement subclasses Cat and Bird, each
providing their specific sounds.

7. Define a class Appliance with a method turnOn(). Create a subclass WashingMachine that overrides
the turnOn() method.

8. Create a superclass Member with fields name and memberId. Define a subclass StudentMember that
adds a course field and overrides a displayDetails() method.

9. Write a superclass Fruit with a method taste(). Implement subclasses Apple and Orange that
provide their specific taste descriptions.

10. Define a class Gadget with a method use(). Create a subclass Smartphone that overrides the use()
method.

11. Create a superclass Building with a method structure(). Define a subclass House that overrides
the structure() method.

12. Write a class Musician with a method playInstrument(). Create a subclass Guitarist that adds a

36
guitarType field and overrides the playInstrument() method.

13. Define a class Device with a method powerOn(). Implement a subclass Laptop that overrides the
powerOn() method.

14. Create a superclass Vehicle with a method fuelType(). Define a subclass ElectricCar that
overrides the fuelType() method to indicate it uses electricity.

15. Write a class Employee with fields name and salary. Create a subclass Manager that adds a
department field and overrides the displayDetails() method.

16. Define a class Instrument with a method play(). Implement subclasses Piano and Violin, each
providing their specific implementations of the play() method.

17. Create a superclass Account with fields accountNumber and balance. Define a subclass
CheckingAccount that overrides a withdraw() method.

18. Write a class Artist with a method createArt(). Create a subclass Painter that adds a medium field
and overrides the createArt() method.

19. Define a class Game with a method start(). Implement a subclass BoardGame that overrides the
start() method.

20. Create a superclass Course with a method getDuration(). Define a subclass OnlineCourse that
overrides the getDuration() method to specify the duration for online learning.

21. Create a superclass Appliance with a method operate(). Define a subclass Microwave that
overrides the operate() method.

22. Write a class Person with a method speak(). Create a subclass Teacher that adds a subject field
and overrides the speak() method.

23. Define a class Plant with a method grow(). Implement subclasses Flower and Tree that provide
their specific growth processes.

24. Create a superclass Computer with fields brand and processor. Define a subclass Laptop that adds a
batteryLife field and overrides the displayDetails() method.

25. Write a class Vehicle with a method speed(). Create a subclass Bike that overrides the speed()
method.

26. Define a class Employee with a method work(). Implement subclasses Developer and Designer,
each providing their specific implementations of the work() method.

27. Create a superclass Animal with a method habitat(). Define a subclass Fish that overrides the
habitat() method.

28. Write a class Furniture with a method material(). Create a subclass Chair that adds a type field
and overrides the material() method.

29. Define a class Appliance with a method function(). Implement a subclass Refrigerator that
overrides the function() method.

30. Create a superclass Vehicle with a method capacity(). Define a subclass Bus that overrides the
capacity() method.

31. Write a class Account with fields accountId and balance. Create a subclass FixedDepositAccount
that adds an interestRate field and overrides a calculateInterest() method.

32. Define a class Shape with a method draw(). Implement subclasses Square and Triangle that

37
provide their specific implementations of the draw() method.

33. Create a superclass Instrument with a method tune(). Define a subclass Flute that overrides the
tune() method.

34. Write a class Building with a method build(). Create a subclass Skyscraper that overrides the
build() method.

35. Define a class Vehicle with a method start(). Implement subclasses Truck and Motorcycle, each
providing their specific implementations of the start() method.

36. Create a superclass Employee with fields name and department. Define a subclass Intern that adds a
duration field and overrides the displayDetails() method.

37. Write a class Product with fields productId and price. Create a subclass Electronics that adds a
warranty field and overrides the displayDetails() method.

38. Define a class Person with a method introduce(). Implement subclasses Student and Professor,
each providing their specific implementations of the introduce() method.

39. Create a superclass Gadget with a method useGadget(). Define a subclass Tablet that overrides
the useGadget() method.

40. Write a class Artist with a method create(). Create a subclass Sculptor that adds a material field
and overrides the create() method.

41. Define a class Vehicle with a method fuelEfficiency(). Implement subclasses HybridCar and
DieselTruck that provide their specific fuel efficiency details.

42. Create a superclass Device with a method turnOn(). Define a subclass Smartwatch that overrides
the turnOn() method.

43. Write a class Employee with a method performDuties(). Create a subclass Janitor that adds a
shift field and overrides the performDuties() method.

44. Define a class Musician with a method perform(). Implement subclasses Vocalist and Drummer,
each providing their specific implementations of the perform() method.

45. Create a superclass Gadget with a method charge(). Define a subclass ElectricScooter that
overrides the charge() method.

46. Write a class Person with fields name and age. Create a subclass Athlete that adds a sport field
and overrides the displayDetails() method.

47. Define a class Furniture with a method assemble(). Implement subclasses Table and Shelf that
provide their specific implementations of the assemble() method.

48. Create a superclass Vehicle with a method maintenance(). Define a subclass SportsCar that
overrides the maintenance() method.

49. Write a class Building with a method design(). Create a subclass Museum that adds an
exhibitCount field and overrides the design() method.

50. Define a class Tool with a method useTool(). Implement subclasses Hammer and Wrench, each
providing their specific implementations of the useTool() method.

38
Chapter 8: Polymorphism in Java
This chapter explores polymorphism in Java, an essential concept in object-
oriented programming that allows objects of different classes to be treated as
objects of a common superclass. We’ll cover the basics of polymorphism,
dynamic method dispatch, and the use of abstract classes and interfaces.

39
Chapter 8. Polymorphism in Java
Polymorphism allows methods to perform different tasks based on the object that it is acting upon,
even though they share the same method name.

8.1. Types of Polymorphism


There are two types of polymorphism in Java: - Compile-time polymorphism (method overloading) -
Runtime polymorphism (method overriding)

8.2. Method Overloading


Method overloading allows a class to have multiple methods with the same name but different
parameters. It is a form of compile-time polymorphism:

public class MathOperations {


public int add(int a, int b) {
return a + b;
}

public double add(double a, double b) {


return a + b;
}
}

8.2.1. Method Overriding

Method overriding occurs when a subclass provides a specific implementation of a method already
defined in its superclass. It is a form of runtime polymorphism:

public class Animal {


public void makeSound() {
System.out.println("Animal makes a sound");
}
}

public class Dog extends Animal {


@Override
public void makeSound() {
System.out.println("Dog barks");
}
}

8.2.2. Dynamic Method Dispatch

Dynamic method dispatch is a mechanism by which a call to an overridden method is resolved at

40
runtime rather than compile-time. It is the basis for runtime polymorphism:

Animal myAnimal = new Dog();


myAnimal.makeSound(); // Outputs "Dog barks"

8.3. Exercises
1. Create an abstract class Appliance with an abstract method turnOn(). Define subclasses
Refrigerator and Oven that implement the turnOn() method.

2. Define a class Payment with a method makePayment(). Implement this method in classes
CreditCardPayment and PayPalPayment.

3. Write a superclass Vehicle with a method start(). Create subclasses Car and Motorcycle that
override the start() method.

4. Create an abstract class Instrument with an abstract method play(). Define subclasses Guitar and
Drum that implement the play() method.

5. Define a class Animal with a method sound(). Implement this method in classes Dog and Cat.

6. Write a superclass Shape with a method area(). Create subclasses Triangle and Rectangle that
override the area() method.

7. Create an abstract class Worker with an abstract method work(). Define subclasses Engineer and
Doctor that implement the work() method.

8. Define a class Printable with a method print(). Implement this method in classes Book and
Magazine.

9. Write a superclass Device with a method operate(). Create subclasses Laptop and Smartphone that
override the operate() method.

10. Create an abstract class Building with an abstract method construct(). Define subclasses House
and Skyscraper that implement the construct() method.

11. Define a class Playable with a method play(). Implement this method in classes VideoGame and
BoardGame.

12. Write a superclass Animal with a method move(). Create subclasses Fish and Bird that override
the move() method.

13. Create an abstract class Food with an abstract method eat(). Define subclasses Pizza and Salad
that implement the eat() method.

14. Define a class Drivable with a method drive(). Implement this method in classes Bicycle and
Truck.

15. Write a superclass Employee with a method calculateSalary(). Create subclasses Manager and
Developer that override the calculateSalary() method.

16. Create an abstract class Game with an abstract method start(). Define subclasses Chess and
Football that implement the start() method.

17. Define a class Flyable with a method fly(). Implement this method in classes Airplane and
Helicopter.

41
18. Write a superclass Plant with a method grow(). Create subclasses Flower and Tree that override
the grow() method.

19. Create an abstract class Transport with an abstract method move(). Define subclasses Car and
Bicycle that implement the move() method.

20. Define a class Readable with a method read(). Implement this method in classes EBook and
PrintedBook.

42
Chapter 9: Abstraction in Java
This chapter explores abstraction in Java, a fundamental concept in object-
oriented programming that allows you to hide the implementation details and
show only the functionality to the user. We’ll cover abstract classes, abstract
methods, interfaces, and the benefits of using abstraction.

43
Chapter 9. Abstraction in Java
Abstraction allows you to focus on what the object does instead of how it does it. It simplifies the
complexity by hiding the unnecessary details from the user.

9.1. Abstract Classes


An abstract class is a class that cannot be instantiated and is meant to be subclassed. It can have
abstract methods (without implementation) and concrete methods (with implementation).

public abstract class Animal {


public abstract void makeSound();

public void sleep() {


System.out.println("This animal is sleeping.");
}
}

9.2. Abstract Methods


Abstract methods are declared without implementation and must be overridden in the subclass.

public abstract class Animal {


public abstract void makeSound();
}

public class Dog extends Animal {


@Override
public void makeSound() {
System.out.println("Dog barks.");
}
}

9.3. Benefits of Abstraction


• Code Reusability: Abstract classes allow you to reuse code across multiple classes.

• Maintenance: Changes in the implementation details do not affect the code that uses the
abstraction.

• Flexibility: Abstraction allows you to change the implementation without changing the
interface.

9.4. Exercises
1. Create an abstract class Vehicle with an abstract method move(). Define subclasses Car and Bike

44
that implement the move() method.

2. Define a class Flyable with methods takeOff() and land(). Implement these methods in classes
Airplane and Helicopter.

3. Write an abstract class Appliance with an abstract method turnOn(). Create subclasses
WashingMachine and Microwave that implement the turnOn() method.

4. Create a class Playable with a method play(). Implement this method in classes Guitar and
Piano.

5. Define an abstract class Employee with an abstract method calculateSalary(). Create subclasses
FullTimeEmployee and PartTimeEmployee that implement the calculateSalary() method.

6. Write a class Drawable with a method draw(). Implement this method in classes Circle and
Square.

7. Create an abstract class Shape with an abstract method area(). Define subclasses Rectangle and
Triangle that implement the area() method.

8. Define a class Chargeable with methods charge() and discharge(). Implement these methods in
classes Battery and Capacitor.

9. Write an abstract class Document with an abstract method print(). Create subclasses PDFDocument
and WordDocument that implement the print() method.

10. Create a class Storable with methods save() and load(). Implement these methods in classes
Database and FileStorage.

11. Define an abstract class Food with an abstract method prepare(). Create subclasses Pizza and
Salad that implement the prepare() method.

12. Write a class Operable with methods start() and stop(). Implement these methods in classes
Engine and Fan.

13. Create an abstract class Game with an abstract method start(). Define subclasses Football and
Chess that implement the start() method.

14. Define a class Printable with a method print(). Implement this method in classes Book and
Magazine.

15. Write an abstract class Account with an abstract method calculateInterest(). Create subclasses
SavingsAccount and FixedDepositAccount that implement the calculateInterest() method.

16. Create a class Swimmable with a method swim(). Implement this method in classes Fish and Duck.

17. Define an abstract class Animal with an abstract method makeSound(). Create subclasses Lion and
Elephant that implement the makeSound() method.

18. Write a class Rechargeable with a method recharge(). Implement this method in classes
ElectricCar and Smartphone.

19. Create an abstract class Transport with an abstract method move(). Define subclasses Bus and
Train that implement the move() method.

20. Define a class Climbable with a method climb(). Implement this method in classes Monkey and
Mountaineer.

45
Chapter 10: Interfaces in Java
This chapter explores interfaces in Java, a powerful tool for achieving
abstraction and multiple inheritance. We’ll cover the basics of defining
interfaces, implementing interfaces in classes, default and static methods, and
functional interfaces.

46
Chapter 10. Interfaces in Java
An interface in Java is a reference type, similar to a class, that can contain only constants, method
signatures, default methods, static methods, and nested types. Interfaces cannot contain instance
fields or constructors.

10.1. Defining Interfaces


An interface is defined using the interface keyword. Here is the basic structure:

public interface Animal {


void eat();
void makeSound();
}

10.2. Implementing Interfaces


A class implements an interface using the implements keyword. The class must provide
implementations for all the methods declared in the interface.

public class Dog implements Animal {


@Override
public void eat() {
System.out.println("Dog eats.");
}

@Override
public void makeSound() {
System.out.println("Dog barks.");
}
}

10.3. Default Methods


Java 8 introduced default methods, which allow you to add new methods to interfaces without
breaking the existing implementations.

public interface Animal {


void eat();
void makeSound();

default void sleep() {


System.out.println("This animal is sleeping.");
}

47
}

10.4. Static Methods


Interfaces can also contain static methods, which are called on the interface itself rather than on
instances of the class.

public interface Animal {


void eat();
void makeSound();

static void description() {


System.out.println("Animals are living beings.");
}
}

10.5. Exercises
1. Define an interface Playable with methods play() and pause(). Implement this interface in
classes MusicPlayer and VideoPlayer.

2. Create an interface Shape with a method calculateArea(). Implement this interface in classes
Circle and Square.

3. Write an interface Movable with methods moveForward() and moveBackward(). Implement this
interface in classes Robot and Car.

4. Define an interface Printable with a method print(). Implement this interface in classes Report
and Invoice.

5. Create an interface Resizable with methods resizeUp() and resizeDown(). Implement this
interface in classes Window and Image.

6. Write an interface Drawable with a method draw(). Implement this interface in classes Line and
Rectangle.

7. Define an interface Operable with methods start() and stop(). Implement this interface in
classes Machine and Engine.

8. Create an interface Storable with methods save() and delete(). Implement this interface in
classes File and Database.

9. Write an interface Chargeable with methods charge() and discharge(). Implement this interface
in classes Battery and ElectricCar.

10. Define an interface Notifiable with a method sendNotification(). Implement this interface in
classes EmailService and SMSService.

11. Create an interface Flyable with methods takeOff() and land(). Implement this interface in
classes Bird and Airplane.

12. Write an interface Connectable with methods connect() and disconnect(). Implement this
interface in classes WiFi and Bluetooth.

48
13. Define an interface Updatable with a method update(). Implement this interface in classes
Software and Firmware.

14. Create an interface Repairable with a method repair(). Implement this interface in classes Car
and Computer.

15. Write an interface Buildable with a method build(). Implement this interface in classes House
and Boat.

16. Define an interface Monitorable with a method monitor(). Implement this interface in classes
Network and SecuritySystem.

17. Create an interface Sellable with a method sell(). Implement this interface in classes Product
and Service.

18. Write an interface Loggable with a method log(). Implement this interface in classes EventLogger
and TransactionLogger.

19. Define an interface Configurable with a method configure(). Implement this interface in classes
System and Application.

20. Create an interface Playable with methods startGame() and endGame(). Implement this interface
in classes Chess and Football.

49
Chapter 11: Exceptions in Java
This chapter explores exceptions in Java, a mechanism for handling runtime
errors. We’ll cover the basics of exceptions, the difference between checked and
unchecked exceptions, and how to create user-defined exceptions.

50
Chapter 11. Exceptions in Java
Exceptions are events that disrupt the normal flow of a program. Java provides a robust and
flexible system for handling exceptions, which includes built-in exceptions and the ability to create
user-defined exceptions.

11.1. Built-in Exceptions


Java has a rich set of built-in exceptions. These are divided into two main categories: checked
exceptions and unchecked exceptions.

11.1.1. Checked Exceptions

Checked exceptions are exceptions that are checked at compile time. If a method can throw a
checked exception, it must either handle the exception using a try-catch block or declare it using
the throws keyword.

Table 1. Table 1. Common Checked Exceptions

Exception Description
IOException Thrown when an I/O operation fails or is
interrupted.
SQLException Thrown when a database access error occurs.
ClassNotFoundException Thrown when an application tries to load a class
through its name but cannot find it.
InterruptedException Thrown when a thread is interrupted while it is
waiting, sleeping, or otherwise occupied.

Example of handling a checked exception:

import java.io.*;

public class CheckedExceptionExample {


public static void main(String[] args) {
try {
FileReader file = new FileReader("file.txt");
BufferedReader fileInput = new BufferedReader(file);
for (int counter = 0; counter < 3; counter++)
System.out.println(fileInput.readLine());
fileInput.close();
} catch (IOException e) {
System.out.println("IOException caught");
}
}
}

51
11.1.2. Unchecked Exceptions

Unchecked exceptions are exceptions that are not checked at compile time. These are subclasses of
RuntimeException.

Table 2. Table 2. Common Unchecked Exceptions

Exception Description
NullPointerException Thrown when an application attempts to use
null in a case where an object is required.
ArrayIndexOutOfBoundsException Thrown to indicate that an array has been
accessed with an illegal index.
ArithmeticException Thrown when an exceptional arithmetic
condition has occurred, such as division by zero.
IllegalArgumentException Thrown to indicate that a method has been
passed an illegal or inappropriate argument.

Example of handling an unchecked exception:

public class UncheckedExceptionExample {


public static void main(String[] args) {
try {
int[] arr = {1, 2, 3, 4, 5};
System.out.println(arr[10]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBoundsException caught");
}
}
}

11.2. User-Defined Exceptions


In addition to the built-in exceptions, Java allows you to define your own exceptions. This is useful
for application-specific error handling.

To create a user-defined exception, extend the Exception class or one of its subclasses.

class MyException extends Exception {


public MyException(String message) {
super(message);
}
}

public class UserDefinedExceptionExample {


public static void main(String[] args) {
try {
throw new MyException("This is a user-defined exception");

52
} catch (MyException e) {
System.out.println("Caught: " + e.getMessage());
}
}
}

11.3. Exercises
1. Write a program that demonstrates the use of IOException and SQLException.

2. Create a custom exception called InvalidAgeException that is thrown when an invalid age is
provided.

3. Write a program to demonstrate the handling of ArrayIndexOutOfBoundsException.

4. Create a custom exception called NegativeNumberException that is thrown when a negative


number is encountered.

5. Write a program that demonstrates the use of ClassNotFoundException.

6. Create a custom exception called InsufficientFundsException that is thrown when an attempt is


made to withdraw more money than is available in an account.

7. Write a program to demonstrate the handling of NullPointerException.

8. Create a custom exception called ProductNotFoundException that is thrown when a product is not
found in a database.

9. Write a program that demonstrates the use of InterruptedException.

10. Create a custom exception called UnauthorizedAccessException that is thrown when a user
attempts to access a restricted area.

11. Write a program to demonstrate the handling of ArithmeticException when dividing by zero.

12. Create a custom exception called InvalidInputException that is thrown when invalid input is
provided.

13. Write a program that demonstrates the use of IllegalArgumentException.

14. Create a custom exception called OutOfStockException that is thrown when an item is out of
stock.

15. Write a program to demonstrate the handling of NumberFormatException when parsing an invalid
integer.

16. Create a custom exception called PermissionDeniedException that is thrown when a user lacks
the necessary permissions to perform an action.

17. Write a program that demonstrates the use of FileNotFoundException.

18. Create a custom exception called TimeOutException that is thrown when an operation times out.

19. Write a program to demonstrate the handling of UnsupportedOperationException.

20. Create a custom exception called DataValidationException that is thrown when data validation
fails.

21. Write a program that demonstrates the use of IndexOutOfBoundsException with a list.

53
22. Create a custom exception called ResourceNotFoundException that is thrown when a resource is
not found.

23. Write a program to demonstrate the handling of StringIndexOutOfBoundsException.

24. Create a custom exception called DuplicateEntryException that is thrown when a duplicate entry
is encountered.

25. Write a program that demonstrates the use of IllegalStateException.

26. Create a custom exception called OperationFailedException that is thrown when an operation
fails to complete successfully.

27. Write a program to demonstrate the handling of ClassCastException.

28. Create a custom exception called ConfigurationException that is thrown when there is a
configuration error.

29. Write a program that demonstrates the use of NegativeArraySizeException.

30. Create a custom exception called TransactionFailedException that is thrown when a transaction
fails.

31. Write a program to demonstrate the handling of NoSuchElementException.

32. Create a custom exception called InsufficientBalanceException that is thrown when an attempt
is made to withdraw more funds than available.

33. Write a program that demonstrates the use of IOException with file operations.

34. Create a custom exception called InvalidOperationException that is thrown when an invalid
operation is performed.

35. Write a program to demonstrate the handling of SecurityException.

36. Create a custom exception called DatabaseConnectionException that is thrown when a database
connection fails.

37. Write a program that demonstrates the use of InterruptedException in a multi-threading


context.

38. Create a custom exception called FileUploadException that is thrown when a file upload fails.

39. Write a program to demonstrate the handling of ReflectiveOperationException.

40. Create a custom exception called InvalidFormatException that is thrown when data is in an
invalid format.

54
Appendix A: SolutionsSolutions
A.1. Chapter 1 Solutions
1.

int age = 25;

2.

String name = "John Doe";

3.

final double PI = 3.14159;

4.

boolean isActive = true;

5.

double height = 1.75;

6.

char firstLetter = 'J';

7.

int[] primeNumbers = {2, 3, 5, 7, 11};

8.

String[] daysOfWeek = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday",


"Friday", "Saturday"};

9.

55
float price = 19.99f;

10.

long population = 331002651L;

11.

byte childAge = 5;

12.

short numberOfPages = 350;

13.

String email = "[email protected]";

14.

int currentYear = 2024;

15.

final int SPEED_OF_LIGHT = 299792458;

16.

boolean isPrime = true;

17.

double[] grades = {90.5, 85.0, 78.5};

18.

char[] vowels = {'a', 'e', 'i', 'o', 'u'};

19.

56
float temperature = 36.5f;

20.

long distanceToSun = 149600000L;

A.2. Chapter 2 Solutions


1.

int sum = num1 + num2;

2.

int difference = num1 - num2;

3.

int product = num1 * num2;

4.

double quotient = num1 / num2;

5.

int remainder = num1 % num2;

6.

int square = num * num;

7.

int cube = num * num * num;

8.

57
double squareRoot = Math.sqrt(num);

9.

double power = Math.pow(base, exponent);

10.

double cm = inches * 2.54;

11.

int perimeter = 2 * (length + width);

12.

double area = (base * height) / 2;

13.

double miles = kilometers * 0.621371;

14.

double circumference = 2 * Math.PI * radius;

15.

int volumeCube = side * side * side;

16.

double volumeSphere = (4.0 / 3) * Math.PI * Math.pow(radius, 3);

17.

double average = (num1 + num2 + num3 + num4) / 4.0;

18.

58
int max = Math.max(num1, Math.max(num2, num3));

19.

int min = Math.min(num1, Math.min(num2, num3));

20.

int absValue = Math.abs(num);

A.3. Chapter 3 Solutions


1.

if (number > 0) {
System.out.println("Positive");
} else if (number < 0) {
System.out.println("Negative");
} else {
System.out.println("Zero");
}

2.

for (int i = 0; i < 20; i++) {


if (i % 2 == 0) {
System.out.println(i);
}
}

3.

switch(day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");

59
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
default:
System.out.println("Invalid day");
}

4.

int sum = 0;
int i = 1;
while (i <= 100) {
sum += i;
i++;
}
System.out.println("Sum: " + sum);

5.

int i = 1;
do {
System.out.println(i);
i++;
} while (i <= 10);

6.

if (marks >= 90) {


System.out.println("Grade: A");
} else if (marks >= 80) {
System.out.println("Grade: B");
} else if (marks >= 70) {
System.out.println("Grade: C");
} else if (marks >= 60) {
System.out.println("Grade: D");
} else {
System.out.println("Grade: F");
}

7.

60
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 5; j++) {
System.out.print(i * j + "\t");
}
System.out.println();
}

8.

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


if (i == 5) {
break;
}
System.out.println(i);
}

9.

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


if (i % 2 == 0) {
continue;
}
System.out.println(i);
}

10.

int[] numbers = {1, 2, 3, 4, 5};


for (int num : numbers) {
System.out.println(num);
}

11.

if (num1 >= num2 && num1 >= num3) {


System.out.println("Largest: " + num1);
} else if (num2 >= num1 && num2 >= num3) {
System.out.println("Largest: " + num2);
} else {
System.out.println("Largest: " + num3);
}

12.

61
int a = 0, b = 1;
for (int i = 1; i <= num; i++) {
System.out.print(a + " ");
int next = a + b;
a = b;
b = next;
}

13.

int reversed = 0;
while (num != 0) {
int digit = num % 10;
reversed = reversed * 10 + digit;
num /= 10;
}
System.out.println("Reversed Number: " + reversed);

14.

int vowelCount = 0;
for (char c : str.toCharArray()) {
if ("aeiouAEIOU".indexOf(c) != -1) {
vowelCount++;
}
}
System.out.println("Number of vowels: " + vowelCount);

15.

boolean isPrime = true;


for (int i = 2; i <= num / 2; i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
System.out.println(num + " is a prime number");
} else {
System.out.println(num + " is not a prime number");
}

16.

62
int factorial = 1;
int i = 1;
while (i <= num) {
factorial *= i;
i++;
}
System.out.println("Factorial: " + factorial);

17.

int sumOfDigits = 0;
while (num != 0) {
sumOfDigits += num % 10;
num /= 10;
}
System.out.println("Sum of digits: " + sumOfDigits);

18.

for (int i = 2; i <= 100; i++) {


boolean isPrime = true;
for (int j = 2; j <= i / 2; j++) {
if (i % j == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
System.out.print(i + " ");
}
}

19.

boolean isPalindrome = true;


int length = str.length();
for (int i = 0; i < length / 2; i++) {
if (str.charAt(i) != str.charAt(length - i - 1)) {
isPalindrome = false;
break;
}
}
if (isPalindrome) {
System.out.println(str + " is a palindrome");
} else {
System.out.println(str + " is not a palindrome");

63
}

20.

int gcd = 1;
int a = num1, b = num2;
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
gcd = a;
System.out.println("GCD: " + gcd);

21.

int evenCount = 0, oddCount = 0;


for (int num : arr) {
if (num % 2 == 0) {
evenCount++;
} else {
oddCount++;
}
}
System.out.println("Even numbers: " + evenCount);
System.out.println("Odd numbers: " + oddCount);

22.

for (int i = 50; i <= 150; i++) {


boolean isPrime = true;
for (int j = 2; j <= i / 2; j++) {
if (i % j == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
System.out.print(i + " ");
}
}

23.

if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {


System.out.println(year + " is a leap year");

64
} else {
System.out.println(year + " is not a leap year");
}

24.

int smallest = arr[0];


for (int num : arr) {
if (num < smallest) {
smallest = num;
}
}
System.out.println("Smallest number: " + smallest);

25.

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


for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}

26.

char[] str1Array = str1.toCharArray();


char[] str2Array = str2.toCharArray();
Arrays.sort(str1Array);
Arrays.sort(str2Array);
boolean isAnagram = Arrays.equals(str1Array, str2Array);
System.out.println("Are anagrams: " + isAnagram);

27.

int count = 0;
for (char c : str.toCharArray()) {
if (c == targetChar) {
count++;
}
}
System.out.println("Occurrences of " + targetChar + ": " + count);

28.

int[] reversedArray = new int[arr.length];

65
for (int i = 0; i < arr.length; i++) {
reversedArray[i] = arr[arr.length - 1 - i];
}
System.out.println(Arrays.toString(reversedArray));

29.

Arrays.sort(arr);
int secondSmallest = arr[1];
System.out.println("Second smallest number: " + secondSmallest);

30.

int result = 1;
for (int i = 0; i < exponent; i++) {
result *= base;
}
System.out.println("Power: " + result);

31.

int sum = 0;
for (int i = 1; i <= n; i++) {
if (i % 2 != 0) {
sum += i;
}
}
System.out.println("Sum of first " + n + " odd numbers: " + sum);

32.

int maxZeros = 0, currentZeros = 0;


for (char c : binaryString.toCharArray()) {
if (c == '0') {
currentZeros++;
} else {
maxZeros = Math.max(maxZeros, currentZeros);
currentZeros = 0;
}
}
maxZeros = Math.max(maxZeros, currentZeros);
System.out.println("Longest sequence of zeros: " + maxZeros);

33.

66
int n = 5; // number of rows
for (int i = 1; i <= n; i++) {
for (int j = i; j < n; j++) {
System.out.print(" ");
}
for (int j = 1; j <= (2 * i - 1); j++) {
System.out.print("*");
}
System.out.println();
}
for (int i = n - 1; i >= 1; i--) {
for (int j = n; j > i; j--) {
System.out.print(" ");
}
for (int j = 1; j <= (2 * i - 1); j++) {
System.out.print("*");
}
System.out.println();
}

34.

Scanner scanner = new Scanner(System.in);


while (true) {
System.out.println("Enter an operation (+, -, *, /) or 'exit' to quit:");
String operation = scanner.nextLine();
if (operation.equals("exit")) {
break;
}
System.out.println("Enter two numbers:");
double num1 = scanner.nextDouble();
double num2 = scanner.nextDouble();
scanner.nextLine(); // consume newline
switch (operation) {
case "+":
System.out.println("Result: " + (num1 + num2));
break;
case "-":
System.out.println("Result: " + (num1 - num2));
break;
case "*":
System.out.println("Result: " + (num1 * num2));
break;
case "/":
if (num2 != 0) {
System.out.println("Result: " + (num1 / num2));
} else {
System.out.println("Cannot divide by zero");
}

67
break;
default:
System.out.println("Invalid operation");
}
}

35.

int n = arr.length;
int[] rotatedArray = new int[n];
int shift = 3; // number of positions to shift
for (int i = 0; i < n; i++) {
rotatedArray[(i + shift) % n] = arr[i];
}
System.out.println(Arrays.toString(rotatedArray));

36.

int sum = 0;
for (int i = 2; i <= 200; i++) {
boolean isPrime = true;
for (int j = 2; j <= i / 2; j++) {
if (i % j == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
sum += i;
}
}
System.out.println("Sum of all prime numbers between 1 and 200: " + sum);

37.

double sum = 0;
for (int i = 1; i <= n; i++) {
sum += 1.0 / i;
}
System.out.println("Sum of the series: " + sum);

38.

int originalNumber = num;


int result = 0;
int numberOfDigits = String.valueOf(num).length();

68
while (num != 0) {
int digit = num % 10;
result += Math.pow(digit, numberOfDigits);
num /= 10;
}
if (result == originalNumber) {
System.out.println(originalNumber + " is an Armstrong number");
} else {
System.out.println(originalNumber + " is not an Armstrong number");
}

39.

int factorial(int n) {
if (n == 0) {
return 1;
} else {
return n * factorial(n - 1);
}
}
System.out.println("Factorial: " + factorial(num));

40.

int n = 5; // number of rows


for (int i = 0; i < n; i++) {
int number = 1;
System.out.printf("%" + (n - i) * 2 + "s", "");
for (int j = 0; j <= i; j++) {
System.out.printf("%4d", number);
number = number * (i - j) / (j + 1);
}
System.out.println();
}

A.4. Chapter 4 Solutions


1.

int[] numbers = {1, 2, 3, 4, 5};

2.

int sum = 0;
for (int num : numbers) {
sum += num;

69
}
System.out.println("Sum: " + sum);

3.

double[] numbers = {1.0, 2.0, 3.0, 4.0, 5.0};


double sum = 0;
for (double num : numbers) {
sum += num;
}
double average = sum / numbers.length;
System.out.println("Average: " + average);

4.

int max = numbers[0];


for (int num : numbers) {
if (num > max) {
max = num;
}
}
System.out.println("Max: " + max);

5.

int min = numbers[0];


for (int num : numbers) {
if (num < min) {
min = num;
}
}
System.out.println("Min: " + min);

6.

int[] reversed = new int[numbers.length];


for (int i = 0; i < numbers.length; i++) {
reversed[i] = numbers[numbers.length - 1 - i];
}
System.out.println("Reversed: " + Arrays.toString(reversed));

7.

Arrays.sort(numbers);

70
System.out.println("Sorted in ascending order: " + Arrays.toString(numbers));

8.

Arrays.sort(numbers);
int[] descending = new int[numbers.length];
for (int i = 0; i < numbers.length; i++) {
descending[i] = numbers[numbers.length - 1 - i];
}
System.out.println("Sorted in descending order: " + Arrays.toString(descending));

9.

Arrays.sort(numbers);
int secondLargest = numbers[numbers.length - 2];
System.out.println("Second largest: " + secondLargest);

10.

int[] arr1 = {1, 2, 3};


int[] arr2 = {4, 5, 6};
int[] merged = new int[arr1.length + arr2.length];
for (int i = 0; i < arr1.length; i++) {
merged[i] = arr1[i];
}
for (int i = 0; i < arr2.length; i++) {
merged[arr1.length + i] = arr2[i];
}
System.out.println("Merged array: " + Arrays.toString(merged));

11.

int[] unique = new int[numbers.length];


int size = 0;
for (int i = 0; i < numbers.length; i++) {
boolean isDuplicate = false;
for (int j = 0; j < size; j++) {
if (numbers[i] == unique[j]) {
isDuplicate = true;
break;
}
}
if (!isDuplicate) {
unique[size++] = numbers[i];
}
}

71
int[] result = Arrays.copyOf(unique, size);
System.out.println("Array without duplicates: " + Arrays.toString(result));

12.

int[] arr1 = {1, 2, 3, 4};


int[] arr2 = {3, 4, 5, 6};
int[] intersection = new int[Math.min(arr1.length, arr2.length)];
int size = 0;
for (int i = 0; i < arr1.length; i++) {
for (int j = 0; j < arr2.length; j++) {
if (arr1[i] == arr2[j]) {
boolean isDuplicate = false;
for (int k = 0; k < size; k++) {
if (intersection[k] == arr1[i]) {
isDuplicate = true;
break;
}
}
if (!isDuplicate) {
intersection[size++] = arr1[i];
}
}
}
}
int[] result = Arrays.copyOf(intersection, size);
System.out.println("Intersection: " + Arrays.toString(result));

13.

int[] arr1 = {1, 2, 3, 4};


int[] arr2 = {3, 4, 5, 6};
int[] union = new int[arr1.length + arr2.length];
int size = 0;
for (int i = 0; i < arr1.length; i++) {
union[size++] = arr1[i];
}
for (int i = 0; i < arr2.length; i++) {
boolean isDuplicate = false;
for (int j = 0; j < size; j++) {
if (arr2[i] == union[j]) {
isDuplicate = true;
break;
}
}
if (!isDuplicate) {
union[size++] = arr2[i];
}
}

72
int[] result = Arrays.copyOf(union, size);
System.out.println("Union: " + Arrays.toString(result));

14.

int first = numbers[0];


for (int i = 0; i < numbers.length - 1; i++) {
numbers[i] = numbers[i + 1];
}
numbers[numbers.length - 1] = first;
System.out.println("Shifted left: " + Arrays.toString(numbers));

15.

int last = numbers[numbers.length - 1];


for (int i = numbers.length - 1; i > 0; i--) {
numbers[i] = numbers[i - 1];
}
numbers[0] = last;
System.out.println("Shifted right: " + Arrays.toString(numbers));

16.

int[] frequency = new int[numbers.length];


for (int i = 0; i < numbers.length; i++) {
frequency[i] = -1;
}
for (int i = 0; i < numbers.length; i++) {
int count = 1;
for (int j = i + 1; j < numbers.length; j++) {
if (numbers[i] == numbers[j]) {
count++;
frequency[j] = 0;
}
}
if (frequency[i] != 0) {
frequency[i] = count;
}
}
for (int i = 0; i < frequency.length; i++) {
if (frequency[i] != 0) {
System.out.println("Element: " + numbers[i] + ", Frequency: " + frequency[i]);
}
}

17.

73
boolean contains = false;
for (int num : numbers) {
if (num == target) {
contains = true;
break;
}
}
System.out.println("Contains " + target + ": " + contains);

18.

int[] copy = new int[numbers.length];


for (int i = 0; i < numbers.length; i++) {
copy[i] = numbers[i];
}
System.out.println("Copied array: " + Arrays.toString(copy));

19.

int[] arr1 = {1, 2, 3, 4};


int[] arr2 = {3, 4, 5, 6};
int[] common = new int[Math.min(arr1.length, arr2.length)];
int size = 0;
for (int i = 0; i < arr1.length; i++) {
for (int j = 0; j < arr2.length; j++) {
if (arr1[i] == arr2[j]) {
boolean isDuplicate = false;
for (int k = 0; k < size; k++) {
if (common[k] == arr1[i]) {
isDuplicate = true;
break;
}
}
if (!isDuplicate) {
common[size++] = arr1[i];
}
}
}
}
int[] result = Arrays.copyOf(common, size);
System.out.println("Common elements: " + Arrays.toString(result));

20.

int[] arr1 = {1, 2, 3, 4};


int[] arr2 = {3, 4, 5, 6};
int[] difference = new int[arr1.length];

74
int size = 0;
for (int i = 0; i < arr1.length; i++) {
boolean isCommon = false;
for (int j = 0; j < arr2.length; j++) {
if (arr1[i] == arr2[j]) {
isCommon = true;
break;
}
}
if (!isCommon) {
difference[size++] = arr1[i];
}
}
int[] result = Arrays.copyOf(difference, size);
System.out.println("Difference: " + Arrays.toString(result));

21.

int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

22.

int sum = 0;
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
sum += matrix[i][j];
}
}
System.out.println("Sum of all elements: " + sum);

23.

int max = matrix[0][0];


for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
if (matrix[i][j] > max) {
max = matrix[i][j];
}
}
}
System.out.println("Maximum element: " + max);

24.

75
int min = matrix[0][0];
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
if (matrix[i][j] < min) {
min = matrix[i][j];
}
}
}
System.out.println("Minimum element: " + min);

25.

for (int i = 0; i < matrix.length; i++) {


for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}

26.

for (int i = 0; i < matrix.length; i++) {


int rowSum = 0;
for (int j = 0; j < matrix[i].length; j++) {
rowSum += matrix[i][j];
}
System.out.println("Sum of row " + (i + 1) + ": " + rowSum);
}

27.

for (int j = 0; j < matrix[0].length; j++) {


int colSum = 0;
for (int i = 0; i < matrix.length; i++) {
colSum += matrix[i][j];
}
System.out.println("Sum of column " + (j + 1) + ": " + colSum);
}

28.

int[][] transpose = new int[matrix[0].length][matrix.length];


for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
transpose[j][i] = matrix[i][j];

76
}
}
System.out.println("Transpose of the matrix:");
for (int i = 0; i < transpose.length; i++) {
for (int j = 0; j < transpose[i].length; j++) {
System.out.print(transpose[i][j] + " ");
}
System.out.println();
}

29.

boolean isSquare = (matrix.length == matrix[0].length);


System.out.println("Is square matrix: " + isSquare);

30.

System.out.println("Main diagonal elements:");


for (int i = 0; i < matrix.length; i++) {
System.out.print(matrix[i][i] + " ");
}

31.

System.out.println("Secondary diagonal elements:");


for (int i = 0; i < matrix.length; i++) {
System.out.print(matrix[i][matrix.length - i - 1] + " ");
}

32.

int sumMainDiagonal = 0;
for (int i = 0; i < matrix.length; i++) {
sumMainDiagonal += matrix[i][i];
}
System.out.println("Sum of main diagonal elements: " + sumMainDiagonal);

33.

int sumSecondaryDiagonal = 0;
for (int i = 0; i < matrix.length; i++) {
sumSecondaryDiagonal += matrix[i][matrix.length - i - 1];
}
System.out.println("Sum of secondary diagonal elements: " + sumSecondaryDiagonal);

77
34.

int sumBorder = 0;
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
if (i == 0 || i == matrix.length - 1 || j == 0 || j == matrix[i].length - 1) {
sumBorder += matrix[i][j];
}
}
}
System.out.println("Sum of border elements: " + sumBorder);

35.

int target = 5; // specify the target value


int count = 0;
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
if (matrix[i][j] == target) {
count++;
}
}
}
System.out.println("Occurrences of " + target + ": " + count);

36.

int[][] matrix1 = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int[][] matrix2 = {
{9, 8, 7},
{6, 5, 4},
{3, 2, 1}
};
int[][] product = new int[matrix1.length][matrix2[0].length];
for (int i = 0; i < matrix1.length; i++) {
for (int j = 0; j < matrix2[0].length; j++) {
for (int k = 0; k < matrix1[0].length; k++) {
product[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}
System.out.println("Product of the matrices:");
for (int i = 0; i < product.length; i++) {
for (int j = 0; j < product[i].length; j++) {

78
System.out.print(product[i][j] + " ");
}
System.out.println();
}

37.

int[][] matrix1 = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int[][] matrix2 = {
{9, 8, 7},
{6, 5, 4},
{3, 2, 1}
};
int[][] sumMatrix = new int[matrix1.length][matrix1[0].length];
for (int i = 0; i < matrix1.length; i++) {
for (int j = 0; j < matrix1[i].length; j++) {
sumMatrix[i][j] = matrix1[i][j] + matrix2[i][j];
}
}
System.out.println("Sum of the matrices:");
for (int i = 0; i < sumMatrix.length; i++) {
for (int j = 0; j < sumMatrix[i].length; j++) {
System.out.print(sumMatrix[i][j] + " ");
}
System.out.println();
}

38.

int[][] matrix1 = {
{9, 8, 7},
{6, 5, 4},
{3, 2, 1}
};
int[][] matrix2 = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int[][] diffMatrix = new int[matrix1.length][matrix1[0].length];
for (int i = 0; i < matrix1.length; i++) {
for (int j = 0; j < matrix1[i].length; j++) {
diffMatrix[i][j] = matrix1[i][j] - matrix2[i][j];
}
}

79
System.out.println("Difference of the matrices:");
for (int i = 0; i < diffMatrix.length; i++) {
for (int j = 0; j < diffMatrix[i].length; j++) {
System.out.print(diffMatrix[i][j] + " ");
}
System.out.println();
}

39.

boolean isEqual = true;


if (matrix1.length != matrix2.length || matrix1[0].length != matrix2[0].length) {
isEqual = false;
} else {
for (int i = 0; i < matrix1.length; i++) {
for (int j = 0; j < matrix1[i].length; j++) {
if (matrix1[i][j] != matrix2[i][j]) {
isEqual = false;
break;
}
}
}
}
System.out.println("Are matrices equal: " + isEqual);

40.

int[] flattened = new int[matrix.length * matrix[0].length];


int index = 0;
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
flattened[index++] = matrix[i][j];
}
}
System.out.println("Flattened array: " + Arrays.toString(flattened));

A.5. Chapter 5 Solutions


1.

public static int max(int a, int b) {


return (a > b) ? a : b;
}

2.

80
public static int factorial(int n) {
int result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}

3.

public static boolean isPrime(int n) {


if (n <= 1) {
return false;
}
for (int i = 2; i <= n / 2; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}

4.

public static String reverse(String str) {


String reversed = "";
for (int i = str.length() - 1; i >= 0; i--) {
reversed += str.charAt(i);
}
return reversed;
}

5.

public static int power(int base, int exponent) {


int result = 1;
for (int i = 0; i < exponent; i++) {
result *= base;
}
return result;
}

6.

public static int gcd(int a, int b) {

81
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}

7.

public static boolean isPalindrome(String str) {


int length = str.length();
for (int i = 0; i < length / 2; i++) {
if (str.charAt(i) != str.charAt(length - i - 1)) {
return false;
}
}
return true;
}

8.

public static int sumOfDigits(int n) {


int sum = 0;
while (n != 0) {
sum += n % 10;
n /= 10;
}
return sum;
}

9.

public static int binaryToDecimal(String binary) {


int decimal = 0;
int base = 1;
for (int i = binary.length() - 1; i >= 0; i--) {
if (binary.charAt(i) == '1') {
decimal += base;
}
base *= 2;
}
return decimal;
}

10.

82
public static String longestWord(String sentence) {
String[] words = sentence.split("\\s+");
String longest = "";
for (String word : words) {
if (word.length() > longest.length()) {
longest = word;
}
}
return longest;
}

11.

public static void fibonacci(int n) {


int a = 0, b = 1;
for (int i = 1; i <= n; i++) {
System.out.print(a + " ");
int next = a + b;
a = b;
b = next;
}
}

12.

public static double average(int[] array) {


int sum = 0;
for (int num : array) {
sum += num;
}
return (double) sum / array.length;
}

13.

public static boolean isVowel(char c) {


return "AEIOUaeiou".indexOf(c) != -1;
}

14.

public static int areaOfRectangle(int length, int width) {


return length * width;
}

83
15.

public static int countOccurrences(String str, char c) {


int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == c) {
count++;
}
}
return count;
}

16.

public static int min(int[] array) {


int min = array[0];
for (int num : array) {
if (num < min) {
min = num;
}
}
return min;
}

17.

public static void sortAscending(int[] array) {


for (int i = 0; i < array.length - 1; i++) {
for (int j = i + 1; j < array.length; j++) {
if (array[i] > array[j]) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
}

18.

public static int[] mergeArrays(int[] arr1, int[] arr2) {


int[] merged = new int[arr1.length + arr2.length];
for (int i = 0; i < arr1.length; i++) {
merged[i] = arr1[i];
}
for (int i = 0; i < arr2.length; i++) {
merged[arr1.length + i] = arr2[i];

84
}
return merged;
}

19.

public static int secondLargest(int[] array) {


int largest = Integer.MIN_VALUE;
int secondLargest = Integer.MIN_VALUE;
for (int num : array) {
if (num > largest) {
secondLargest = largest;
largest = num;
} else if (num > secondLargest && num < largest) {
secondLargest = num;
}
}
return secondLargest;
}

20.

public static void print2DArray(int[][] array) {


for (int[] row : array) {
for (int element : row) {
System.out.print(element + " ");
}
System.out.println();
}
}

21.

public static int sum(int a, int b) {


return a + b;
}

22.

public static int product(int a, int b) {


return a * b;
}

23.

85
public static int difference(int a, int b) {
return a - b;
}

24.

public static int[] quotientAndRemainder(int a, int b) {


int[] result = new int[2];
result[0] = a / b;
result[1] = a % b;
return result;
}

25.

public static double celsiusToFahrenheit(double celsius) {


return (celsius * 9/5) + 32;
}

26.

public static double fahrenheitToCelsius(double fahrenheit) {


return (fahrenheit - 32) * 5/9;
}

27.

public static int perimeterOfRectangle(int length, int width) {


return 2 * (length + width);
}

28.

public static double areaOfCircle(double radius) {


return Math.PI * radius * radius;
}

29.

public static boolean containsCharacter(String str, char c) {


return str.indexOf(c) >= 0;
}

86
30.

public static double max(double[] array) {


double max = array[0];
for (double num : array) {
if (num > max) {
max = num;
}
}
return max;
}

31.

public static double median(int[] array) {


Arrays.sort(array);
int length = array.length;
if (length % 2 == 0) {
return (array[length/2 - 1] + array[length/2]) / 2.0;
} else {
return array[length/2];
}
}

32.

public static int mode(int[] array) {


HashMap<Integer, Integer> frequencyMap = new HashMap<>();
for (int num : array) {
frequencyMap.put(num, frequencyMap.getOrDefault(num, 0) + 1);
}
int mode = array[0];
int maxCount = 0;
for (Map.Entry<Integer, Integer> entry : frequencyMap.entrySet()) {
if (entry.getValue() > maxCount) {
maxCount = entry.getValue();
mode = entry.getKey();
}
}
return mode;
}

33.

public static double compoundInterest(double principal, double rate, int time) {


return principal * Math.pow((1 + rate / 100), time) - principal;

87
}

34.

public static int hcf(int a, int b) {


while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}

35.

public static int randomInRange(int min, int max) {


return (int)(Math.random() * (max - min + 1)) + min;
}

36.

public static int countWords(String str) {


if (str.isEmpty()) {
return 0;
}
String[] words = str.trim().split("\\s+");
return words.length;
}

37.

public static String capitalizeFirstLetter(String str) {


String[] words = str.split("\\s+");
StringBuilder capitalized = new StringBuilder();
for (String word : words) {
capitalized.append(Character.toUpperCase(word.charAt(0)))
.append(word.substring(1)).append(" ");
}
return capitalized.toString().trim();
}

38.

public static double standardDeviation(double[] array) {


double mean = 0;

88
for (double num : array) {
mean += num;
}
mean /= array.length;
double sum = 0;
for (double num : array) {
sum += Math.pow(num - mean, 2);
}
return Math.sqrt(sum / array.length);
}

39.

public static int countVowels(String str) {


int count = 0;
String vowels = "aeiouAEIOU";
for (int i = 0; i < str.length(); i++) {
if (vowels.indexOf(str.charAt(i)) != -1) {
count++;
}
}
return count;
}

40.

public static boolean isLeapYear(int year) {


return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}

A.6. Chapter 6 Solutions


1.

public class Person {


private String name;
private int age;

public Person(String name, int age) {


this.name = name;
this.age = age;
}

public void displayDetails() {


System.out.println("Name: " + name + ", Age: " + age);
}

89
}

2.

public class Rectangle {


private double width;
private double height;

public Rectangle(double width, double height) {


this.width = width;
this.height = height;
}

public double calculateArea() {


return width * height;
}

public double calculatePerimeter() {


return 2 * (width + height);
}
}

3.

public class Book {


private String title;
private String author;
private double price;

public Book(String title, String author, double price) {


this.title = title;
this.author = author;
this.price = price;
}

public void displayDetails() {


System.out.println("Title: " + title + ", Author: " + author + ", Price: " +
price);
}
}

4.

public class Circle {


private double radius;

public Circle(double radius) {

90
this.radius = radius;
}

public double calculateArea() {


return Math.PI * Math.pow(radius, 2);
}

public double calculateCircumference() {


return 2 * Math.PI * radius;
}
}

5.

public class BankAccount {


private String accountNumber;
private String accountHolderName;
private double balance;

public BankAccount(String accountNumber, String accountHolderName, double balance)


{
this.accountNumber = accountNumber;
this.accountHolderName = accountHolderName;
this.balance = balance;
}

public void deposit(double amount) {


balance += amount;
}

public void withdraw(double amount) {


if (amount <= balance) {
balance -= amount;
} else {
System.out.println("Insufficient funds");
}
}

public void displayAccountDetails() {


System.out.println("Account Number: " + accountNumber + ", Account Holder: " +
accountHolderName + ", Balance: " + balance);
}
}

6.

public class Student {


private String name;
private String id;

91
private double[] grades;

public Student(String name, String id, double[] grades) {


this.name = name;
this.id = id;
this.grades = grades;
}

public double calculateAverageGrade() {


double sum = 0;
for (double grade : grades) {
sum += grade;
}
return sum / grades.length;
}
}

7.

public class Employee {


private String name;
private String id;
private double salary;

public Employee(String name, String id, double salary) {


this.name = name;
this.id = id;
this.salary = salary;
}

public void giveRaise(double amount) {


salary += amount;
}

public void displayDetails() {


System.out.println("Name: " + name + ", ID: " + id + ", Salary: " + salary);
}
}

8.

public class Dog {


private String name;
private String breed;
private int age;

public Dog(String name, String breed, int age) {


this.name = name;
this.breed = breed;

92
this.age = age;
}

public void displayDetails() {


System.out.println("Name: " + name + ", Breed: " + breed + ", Age: " + age);
}
}

9.

public class Laptop {


private String brand;
private String model;
private double price;

public Laptop(String brand, String model, double price) {


this.brand = brand;
this.model = model;
this.price = price;
}

public void displayDetails() {


System.out.println("Brand: " + brand + ", Model: " + model + ", Price: " +
price);
}
}

10.

public class Movie {


private String title;
private String genre;
private double rating;

public Movie(String title, String genre, double rating) {


this.title = title;
this.genre = genre;
this.rating = rating;
}

public void displayDetails() {


System.out.println("Title: " + title + ", Genre: " + genre + ", Rating: " +
rating);
}
}

11.

93
public class Point {
private double x;
private double y;

public Point(double x, double y) {


this.x = x;
this.y = y;
}

public double calculateDistance(Point other) {


return Math.sqrt(Math.pow(this.x, other.x) + Math.pow(this.y, other.y));
}
}

12.

public class Triangle {


private double side1;
private double side2;
private double side3;

public Triangle(double side1, double side2, double side3) {


this.side1 = side1;
this.side2 = side2;
this.side3 = side3;
}

public double calculatePerimeter() {


return side1 + side2 + side3;
}

public double calculateArea() {


double s = calculatePerimeter() / 2;
return Math.sqrt(s * (s - side1) * (s - side2) * (s - side3));
}
}

13.

public class Song {


private String title;
private String artist;
private double duration;

public Song(String title, String artist, double duration) {


this.title = title;
this.artist = artist;
this.duration = duration;

94
}

public void displayDetails() {


System.out.println("Title: " + title + ", Artist: " + artist + ", Duration: "
+ duration);
}
}

14.

public class Flight {


private String flightNumber;
private String destination;
private String departureTime;

public Flight(String flightNumber, String destination, String departureTime) {


this.flightNumber = flightNumber;
this.destination = destination;
this.departureTime = departureTime;
}

public void displayDetails() {


System.out.println("Flight Number: " + flightNumber + ", Destination: " +
destination + ", Departure Time: " + departureTime);
}
}

15.

public class House {


private String address;
private int numberOfRooms;
private double price;

public House(String address, int numberOfRooms, double price) {


this.address = address;
this.numberOfRooms = numberOfRooms;
this.price = price;
}

public void displayDetails() {


System.out.println("Address: " + address + ", Number of Rooms: " +
numberOfRooms + ", Price: " + price);
}
}

16.

95
public class Phone {
private String brand;
private String model;
private double price;

public Phone(String brand, String model, double price) {


this.brand = brand;
this.model = model;
this.price = price;
}

public void displayDetails() {


System.out.println("Brand: " + brand + ", Model: " + model + ", Price: " +
price);
}
}

17.

public class Car {


private String make;
private String model;
private int year;

public Car(String make, String model, int year) {


this.make = make;
this.model = model;
this.year = year;
}

public void displayDetails() {


System.out.println("Make: " + make + ", Model: " + model + ", Year: " + year);
}
}

18.

public class City {


private String name;
private int population;
private String country;

public City(String name, int population, String country) {


this.name = name;
this.population = population;
this.country = country;
}

96
public void displayDetails() {
System.out.println("Name: " + name + ", Population: " + population + ",
Country: " + country);
}
}

19.

public class Teacher {


private String name;
private String subject;
private int yearsOfExperience;

public Teacher(String name, String subject, int yearsOfExperience) {


this.name = name;
this.subject = subject;
this.yearsOfExperience = yearsOfExperience;
}

public void displayDetails() {


System.out.println("Name: " + name + ", Subject: " + subject + ", Years of
Experience: " + yearsOfExperience);
}
}

20.

public class Camera {


private String brand;
private String model;
private double resolution;

public Camera(String brand, String model, double resolution) {


this.brand = brand;
this.model = model;
this.resolution = resolution;
}

public void displayDetails() {


System.out.println("Brand: " + brand + ", Model: " + model + ", Resolution: "
+ resolution);
}
}

21.

public class Student {

97
private String studentId;
private String name;
private String major;

public Student(String studentId, String name, String major) {


this.studentId = studentId;
this.name = name;
this.major = major;
}

public void displayDetails() {


System.out.println("Student ID: " + studentId + ", Name: " + name + ", Major:
" + major);
}
}

22.

public class Animal {


private String species;
private int age;
private String habitat;

public Animal(String species, int age, String habitat) {


this.species = species;
this.age = age;
this.habitat = habitat;
}

public void displayDetails() {


System.out.println("Species: " + species + ", Age: " + age + ", Habitat: " +
habitat);
}
}

23.

public class Product {


private String productId;
private String name;
private double price;

public Product(String productId, String name, double price) {


this.productId = productId;
this.name = name;
this.price = price;
}

public void displayDetails() {

98
System.out.println("Product ID: " + productId + ", Name: " + name + ", Price:
" + price);
}
}

24.

import java.util.ArrayList;
import java.util.List;

public class Bank {


private String bankName;
private String branch;
private String location;
private List<String> branches = new ArrayList<>();

public Bank(String bankName, String branch, String location) {


this.bankName = bankName;
this.branch = branch;
this.location = location;
}

public void addBranch(String branch) {


branches.add(branch);
}

public void displayBranches() {


System.out.println("Bank: " + bankName + ", Location: " + location);
for (String branch : branches) {
System.out.println("Branch: " + branch);
}
}
}

25.

import java.util.ArrayList;
import java.util.List;

public class Library {


private String libraryName;
private List<String> books = new ArrayList<>();

public Library(String libraryName) {


this.libraryName = libraryName;
}

public void addBook(String book) {


books.add(book);

99
}

public void displayBooks() {


System.out.println("Library: " + libraryName);
for (String book : books) {
System.out.println("Book: " + book);
}
}
}

26.

import java.util.ArrayList;
import java.util.List;

public class Restaurant {


private String name;
private String address;
private List<String> menuItems = new ArrayList<>();

public Restaurant(String name, String address) {


this.name = name;
this.address = address;
}

public void addMenuItem(String item) {


menuItems.add(item);
}

public void displayMenu() {


System.out.println("Restaurant: " + name + ", Address: " + address);
for (String item : menuItems) {
System.out.println("Menu Item: " + item);
}
}
}

27.

public class Course {


private String courseName;
private String courseCode;
private int credits;

public Course(String courseName, String courseCode, int credits) {


this.courseName = courseName;
this.courseCode = courseCode;
this.credits = credits;
}

100
public void displayDetails() {
System.out.println("Course Name: " + courseName + ", Course Code: " +
courseCode + ", Credits: " + credits);
}
}

28.

import java.util.ArrayList;
import java.util.List;

public class Department {


private String departmentName;
private String headOfDepartment;
private List<String> courses = new ArrayList<>();

public Department(String departmentName, String headOfDepartment) {


this.departmentName = departmentName;
this.headOfDepartment = headOfDepartment;
}

public void addCourse(String course) {


courses.add(course);
}

public void displayDetails() {


System.out.println("Department: " + departmentName + ", Head: " +
headOfDepartment);
for (String course : courses) {
System.out.println("Course: " + course);
}
}
}

29.

import java.util.ArrayList;
import java.util.List;

public class Hospital {


private String hospitalName;
private String address;
private List<String> doctors = new ArrayList<>();

public Hospital(String hospitalName, String address) {


this.hospitalName = hospitalName;
this.address = address;
}

101
public void addDoctor(String doctor) {
doctors.add(doctor);
}

public void displayDetails() {


System.out.println("Hospital: " + hospitalName + ", Address: " + address);
for (String doctor : doctors) {
System.out.println("Doctor: " + doctor);
}
}
}

30.

import java.util.ArrayList;
import java.util.List;

public class University {


private String universityName;
private String location;
private List<String> departments = new ArrayList<>();

public University(String universityName, String location) {


this.universityName = universityName;
this.location = location;
}

public void addDepartment(String department) {


departments.add(department);
}

public void displayDetails() {


System.out.println("University: " + universityName + ", Location: " +
location);
for (String department : departments) {
System.out.println("Department: " + department);
}
}
}

31.

public class Schedule {


private String day;
private String time;
private String activity;

public Schedule(String day, String time, String activity) {

102
this.day = day;
this.time = time;
this.activity = activity;
}

public void displayDetails() {


System.out.println("Day: " + day + ", Time: " + time + ", Activity: " +
activity);
}
}

32.

import java.util.ArrayList;
import java.util.List;

public class Gym {


private String gymName;
private String location;
private List<String> equipment = new ArrayList<>();

public Gym(String gymName, String location) {


this.gymName = gymName;
this.location = location;
}

public void addEquipment(String item) {


equipment.add(item);
}

public void displayDetails() {


System.out.println("Gym: " + gymName + ", Location: " + location);
for (String item : equipment) {
System.out.println("Equipment: " + item);
}
}
}

33.

public class Patient {


private String patientId;
private String name;
private String medicalHistory;

public Patient(String patientId, String name, String medicalHistory) {


this.patientId = patientId;
this.name = name;
this.medicalHistory = medicalHistory;

103
}

public void displayDetails() {


System.out.println("Patient ID: " + patientId + ", Name: " + name + ", Medical
History: " + medicalHistory);
}
}

34.

public class Doctor {


private String doctorId;
private String name;
private String specialty;

public Doctor(String doctorId, String name, String specialty) {


this.doctorId = doctorId;
this.name = name;
this.specialty = specialty;
}

public void displayDetails() {


System.out.println("Doctor ID: " + doctorId + ", Name: " + name + ",
Specialty: " + specialty);
}
}

35.

import java.util.ArrayList;
import java.util.List;

public class LibraryMember {


private String memberId;
private String name;
private List<String> borrowedBooks = new ArrayList<>();

public LibraryMember(String memberId, String name) {


this.memberId = memberId;
this.name = name;
}

public void addBorrowedBook(String book) {


borrowedBooks.add(book);
}

public void displayDetails() {


System.out.println("Member ID: " + memberId + ", Name: " + name);
for (String book : borrowedBooks) {

104
System.out.println("Borrowed Book: " + book);
}
}
}

36.

import java.util.ArrayList;
import java.util.List;

public class Conference {


private String conferenceName;
private String date;
private List<String> speakers = new ArrayList<>();

public Conference(String conferenceName, String date) {


this.conferenceName = conferenceName;
this.date = date;
}

public void addSpeaker(String speaker) {


speakers.add(speaker);
}

public void displayDetails() {


System.out.println("Conference: " + conferenceName + ", Date: " + date);
for (String speaker : speakers) {
System.out.println("Speaker: " + speaker);
}
}
}

37.

public class Magazine {


private String title;
private int issueNumber;
private String publicationDate;

public Magazine(String title, int issueNumber, String publicationDate) {


this.title = title;
this.issueNumber = issueNumber;
this.publicationDate = publicationDate;
}

public void displayDetails() {


System.out.println("Title: " + title + ", Issue Number: " + issueNumber + ",
Publication Date: " + publicationDate);
}

105
}

38.

import java.util.ArrayList;
import java.util.List;

public class Museum {


private String museumName;
private String location;
private List<String> exhibits = new ArrayList<>();

public Museum(String museumName, String location) {


this.museumName = museumName;
this.location = location;
}

public void addExhibit(String exhibit) {


exhibits.add(exhibit);
}

public void displayDetails() {


System.out.println("Museum: " + museumName + ", Location: " + location);
for (String exhibit : exhibits) {
System.out.println("Exhibit: " + exhibit);
}
}
}

39.

public class Vehicle {


private String make;
private String model;
private int year;

public Vehicle(String make, String model, int year) {


this.make = make;
this.model = model;
this.year = year;
}

public void displayDetails() {


System.out.println("Make: " + make + ", Model: " + model + ", Year: " + year);
}

public int calculateAge(int currentYear) {


return currentYear - year;
}

106
}

40.

import java.util.ArrayList;
import java.util.List;

public class Workshop {


private String title;
private String date;
private List<String> participants = new ArrayList<>();

public Workshop(String title, String date) {


this.title = title;
this.date = date;
}

public void addParticipant(String participant) {


participants.add(participant);
}

public void displayDetails() {


System.out.println("Workshop: " + title + ", Date: " + date);
for (String participant : participants) {
System.out.println("Participant: " + participant);
}
}
}

41.

import java.util.ArrayList;
import java.util.List;

public class Festival {


private String festivalName;
private String location;
private List<String> events = new ArrayList<>();

public Festival(String festivalName, String location) {


this.festivalName = festivalName;
this.location = location;
}

public void addEvent(String event) {


events.add(event);
}

public void displayDetails() {

107
System.out.println("Festival: " + festivalName + ", Location: " + location);
for (String event : events) {
System.out.println("Event: " + event);
}
}
}

42.

import java.util.ArrayList;
import java.util.List;

public class Hotel {


private String hotelName;
private String location;
private List<String> rooms = new ArrayList<>();

public Hotel(String hotelName, String location) {


this.hotelName = hotelName;
this.location = location;
}

public void addRoom(String room) {


rooms.add(room);
}

public void displayDetails() {


System.out.println("Hotel: " + hotelName + ", Location: " + location);
for (String room : rooms) {
System.out.println("Room: " + room);
}
}
}

43.

import java.util.ArrayList;
import java.util.List;

public class Park {


private String parkName;
private String location;
private List<String> facilities = new ArrayList<>();

public Park(String parkName, String location) {


this.parkName = parkName;
this.location = location;
}

108
public void addFacility(String facility) {
facilities.add(facility);
}

public void displayDetails() {


System.out.println("Park: " + parkName + ", Location: " + location);
for (String facility : facilities) {
System.out.println("Facility: " + facility);
}
}
}

44.

import java.util.ArrayList;
import java.util.List;

public class Zoo {


private String zooName;
private String location;
private List<String> animals = new ArrayList<>();

public Zoo(String zooName, String location) {


this.zooName = zooName;
this.location = location;
}

public void addAnimal(String animal) {


animals.add(animal);
}

public void displayDetails() {


System.out.println("Zoo: " + zooName + ", Location: " + location);
for (String animal : animals) {
System.out.println("Animal: " + animal);
}
}
}

45.

import java.util.ArrayList;
import java.util.List;

public class Concert {


private String concertName;
private String date;
private List<String> performers = new ArrayList<>();

109
public Concert(String concertName, String date) {
this.concertName = concertName;
this.date = date;
}

public void addPerformer(String performer) {


performers.add(performer);
}

public void displayDetails() {


System.out.println("Concert: " + concertName + ", Date: " + date);
for (String performer : performers) {
System.out.println("Performer: " + performer);
}
}
}

46.

import java.util.ArrayList;
import java.util.List;

public class Festival {


private String festivalName;
private String date;
private List<String> activities = new ArrayList<>();

public Festival(String festivalName, String date) {


this.festivalName = festivalName;
this.date = date;
}

public void addActivity(String activity) {


activities.add(activity);
}

public void displayDetails() {


System.out.println("Festival: " + festivalName + ", Date: " + date);
for (String activity : activities) {
System.out.println("Activity: " + activity);
}
}
}

47.

import java.util.ArrayList;
import java.util.List;

110
public class SportsTeam {
private String teamName;
private String sport;
private List<String> players = new ArrayList<>();

public SportsTeam(String teamName, String sport) {


this.teamName = teamName;
this.sport = sport;
}

public void addPlayer(String player) {


players.add(player);
}

public void displayDetails() {


System.out.println("Team: " + teamName + ", Sport: " + sport);
for (String player : players) {
System.out.println("Player: " + player);
}
}
}

48.

public class MuseumExhibit {


private String exhibitName;
private String description;
private String dateOfDisplay;

public MuseumExhibit(String exhibitName, String description, String dateOfDisplay)


{
this.exhibitName = exhibitName;
this.description = description;
this.dateOfDisplay = dateOfDisplay;
}

public void displayDetails() {


System.out.println("Exhibit Name: " + exhibitName + ", Description: " +
description + ", Date of Display: " + dateOfDisplay);
}
}

49.

public class Event {


private String eventName;
private String date;
private String location;

111
public Event(String eventName, String date, String location) {
this.eventName = eventName;
this.date = date;
this.location = location;
}

public void displayDetails() {


System.out.println("Event Name: " + eventName + ", Date: " + date + ",
Location: " + location);
}
}

50.

import java.util.ArrayList;
import java.util.List;

public class Company {


private String companyName;
private String industry;
private List<String> employees = new ArrayList<>();

public Company(String companyName, String industry) {


this.companyName = companyName;
this.industry = industry;
}

public void addEmployee(String employee) {


employees.add(employee);
}

public void displayDetails() {


System.out.println("Company: " + companyName + ", Industry: " + industry);
for (String employee : employees) {
System.out.println("Employee: " + employee);
}
}
}

A.7. Chapter 7 Solutions


1.

public class Vehicle {


public void move() {
System.out.println("The vehicle is moving.");
}
}

112
public class Car extends Vehicle {
@Override
public void move() {
System.out.println("The car is driving.");
}
}

2.

public class Person {


public void display() {
System.out.println("Displaying person details.");
}
}

public class Employee extends Person {


private String employeeId;

public Employee(String employeeId) {


this.employeeId = employeeId;
}

@Override
public void display() {
System.out.println("Employee ID: " + employeeId);
}
}

3.

public abstract class Shape {


public abstract double area();
}

public class Circle extends Shape {


private double radius;

public Circle(double radius) {


this.radius = radius;
}

@Override
public double area() {
return Math.PI * Math.pow(radius, 2);
}
}

public class Rectangle extends Shape {

113
private double width;
private double height;

public Rectangle(double width, double height) {


this.width = width;
this.height = height;
}

@Override
public double area() {
return width * height;
}
}

4.

public class BankAccount {


protected String accountNumber;
protected double balance;

public BankAccount(String accountNumber, double balance) {


this.accountNumber = accountNumber;
this.balance = balance;
}
}

public class SavingsAccount extends BankAccount {


private double interestRate;

public SavingsAccount(String accountNumber, double balance, double interestRate) {


super(accountNumber, balance);
this.interestRate = interestRate;
}

public double calculateInterest() {


return balance * interestRate / 100;
}
}

5.

public class Book {


public void read() {
System.out.println("Reading a physical book.");
}
}

public class EBook extends Book {


@Override

114
public void read() {
System.out.println("Reading an electronic book.");
}
}

6.

public class Animal {


public void sound() {
System.out.println("This animal makes a sound.");
}
}

public class Cat extends Animal {


@Override
public void sound() {
System.out.println("The cat meows.");
}
}

public class Bird extends Animal {


@Override
public void sound() {
System.out.println("The bird chirps.");
}
}

7.

public class Appliance {


public void turnOn() {
System.out.println("The appliance is turned on.");
}
}

public class WashingMachine extends Appliance {


@Override
public void turnOn() {
System.out.println("The washing machine is turned on.");
}
}

8.

public class Member {


protected String name;
protected String memberId;

115
public Member(String name, String memberId) {
this.name = name;
this.memberId = memberId;
}

public void displayDetails() {


System.out.println("Name: " + name + ", Member ID: " + memberId);
}
}

public class StudentMember extends Member {


private String course;

public StudentMember(String name, String memberId, String course) {


super(name, memberId);
this.course = course;
}

@Override
public void displayDetails() {
System.out.println("Name: " + name + ", Member ID: " + memberId + ", Course: "
+ course);
}
}

9.

public class Fruit {


public void taste() {
System.out.println("This fruit tastes good.");
}
}

public class Apple extends Fruit {


@Override
public void taste() {
System.out.println("The apple is sweet.");
}
}

public class Orange extends Fruit {


@Override
public void taste() {
System.out.println("The orange is tangy.");
}
}

10.

116
public class Gadget {
public void use() {
System.out.println("Using the gadget.");
}
}

public class Smartphone extends Gadget {


@Override
public void use() {
System.out.println("Using the smartphone.");
}
}

11.

public class Building {


public void structure() {
System.out.println("The building has a structure.");
}
}

public class House extends Building {


@Override
public void structure() {
System.out.println("The house has a roof and walls.");
}
}

12.

public class Musician {


public void playInstrument() {
System.out.println("Playing an instrument.");
}
}

public class Guitarist extends Musician {


private String guitarType;

public Guitarist(String guitarType) {


this.guitarType = guitarType;
}

@Override
public void playInstrument() {
System.out.println("Playing a " + guitarType + " guitar.");
}

117
}

13.

public class Device {


public void powerOn() {
System.out.println("The device is powered on.");
}
}

public class Laptop extends Device {


@Override
public void powerOn() {
System.out.println("The laptop is powered on.");
}
}

14.

public class Vehicle {


public void fuelType() {
System.out.println("The vehicle uses fuel.");
}
}

public class ElectricCar extends Vehicle {


@Override
public void fuelType() {
System.out.println("The electric car uses electricity.");
}
}

15.

public class Employee {


protected String name;
protected double salary;

public Employee(String name, double salary) {


this.name = name;
this.salary = salary;
}

public void displayDetails() {


System.out.println("Name: " + name + ", Salary: " + salary);
}
}

118
public class Manager extends Employee {
private String department;

public Manager(String name, double salary, String department) {


super(name, salary);
this.department = department;
}

@Override
public void displayDetails() {
System.out.println("Name: " + name + ", Salary: " + salary + ", Department: "
+ department);
}
}

16.

public class Instrument {


public void play() {
System.out.println("Playing the instrument.");
}
}

public class Piano extends Instrument {


@Override
public void play() {
System.out.println("Playing the piano.");
}
}

public class Violin extends Instrument {


@Override
public void play() {
System.out.println("Playing the violin.");
}
}

17.

public class Account {


protected String accountNumber;
protected double balance;

public Account(String accountNumber, double balance) {


this.accountNumber = accountNumber;
this.balance = balance;
}

119
public void withdraw(double amount) {
if (amount <= balance) {
balance -= amount;
} else {
System.out.println("Insufficient balance.");
}
}
}

public class CheckingAccount extends Account {


public CheckingAccount(String accountNumber, double balance) {
super(accountNumber, balance);
}

@Override
public void withdraw(double amount) {
if (amount <= balance) {
balance -= amount;
System.out.println("Withdrawal of " + amount + " successful.");
} else {
System.out.println("Insufficient balance for withdrawal.");
}
}
}

18.

public class Artist {


public void createArt() {
System.out.println("Creating art.");
}
}

public class Painter extends Artist {


private String medium;

public Painter(String medium) {


this.medium = medium;
}

@Override
public void createArt() {
System.out.println("Creating art with " + medium + ".");
}
}

19.

public class Game {

120
public void start() {
System.out.println("Starting the game.");
}
}

public class BoardGame extends Game {


@Override
public void start() {
System.out.println("Starting the board game.");
}
}

20.

public class Course {


public void getDuration() {
System.out.println("Course duration.");
}
}

public class OnlineCourse extends Course {


@Override
public void getDuration() {
System.out.println("Online course duration.");
}
}

21.

public class Appliance {


public void operate() {
System.out.println("Operating the appliance.");
}
}

public class Microwave extends Appliance {


@Override
public void operate() {
System.out.println("Operating the microwave.");
}
}

22.

public class Person {


public void speak() {
System.out.println("The person speaks.");

121
}
}

public class Teacher extends Person {


private String subject;

public Teacher(String subject) {


this.subject = subject;
}

@Override
public void speak() {
System.out.println("The teacher speaks about " + subject + ".");
}
}

23.

public class Plant {


public void grow() {
System.out.println("The plant grows.");
}
}

public class Flower extends Plant {


@Override
public void grow() {
System.out.println("The flower blooms.");
}
}

public class Tree extends Plant {


@Override
public void grow() {
System.out.println("The tree grows tall.");
}
}

24.

public class Computer {


protected String brand;
protected String processor;

public Computer(String brand, String processor) {


this.brand = brand;
this.processor = processor;
}

122
public void displayDetails() {
System.out.println("Brand: " + brand + ", Processor: " + processor);
}
}

public class Laptop extends Computer {


private double batteryLife;

public Laptop(String brand, String processor, double batteryLife) {


super(brand, processor);
this.batteryLife = batteryLife;
}

@Override
public void displayDetails() {
System.out.println("Brand: " + brand + ", Processor: " + processor + ",
Battery Life: " + batteryLife + " hours");
}
}

25.

public class Vehicle {


public void speed() {
System.out.println("The vehicle moves at a certain speed.");
}
}

public class Bike extends Vehicle {


@Override
public void speed() {
System.out.println("The bike moves fast.");
}
}

26.

public class Employee {


public void work() {
System.out.println("The employee works.");
}
}

public class Developer extends Employee {


@Override
public void work() {
System.out.println("The developer writes code.");
}
}

123
public class Designer extends Employee {
@Override
public void work() {
System.out.println("The designer creates designs.");
}
}

27.

public class Animal {


public void habitat() {
System.out.println("The animal lives in a habitat.");
}
}

public class Fish extends Animal {


@Override
public void habitat() {
System.out.println("The fish lives in water.");
}
}

28.

public class Furniture {


public void material() {
System.out.println("The furniture is made of material.");
}
}

public class Chair extends Furniture {


private String type;

public Chair(String type) {


this.type = type;
}

@Override
public void material() {
System.out.println("The chair is made of " + type + ".");
}
}

29.

public class Appliance {

124
public void function() {
System.out.println("The appliance performs a function.");
}
}

public class Refrigerator extends Appliance {


@Override
public void function() {
System.out.println("The refrigerator keeps food cold.");
}
}

30.

public class Vehicle {


public void capacity() {
System.out.println("The vehicle has a capacity.");
}
}

public class Bus extends Vehicle {


@Override
public void capacity() {
System.out.println("The bus can carry many passengers.");
}
}

31.

public class Account {


protected String accountId;
protected double balance;

public Account(String accountId, double balance) {


this.accountId = accountId;
this.balance = balance;
}
}

public class FixedDepositAccount extends Account {


private double interestRate;

public FixedDepositAccount(String accountId, double balance, double interestRate)


{
super(accountId, balance);
this.interestRate = interestRate;
}

public double calculateInterest() {

125
return balance * interestRate / 100;
}
}

32.

public abstract class Shape {


public abstract void draw();
}

public class Square extends Shape {


@Override
public void draw() {
System.out.println("Drawing a square.");
}
}

public class Triangle extends Shape {


@Override
public void draw() {
System.out.println("Drawing a triangle.");
}
}

33.

public class Instrument {


public void tune() {
System.out.println("Tuning the instrument.");
}
}

public class Flute extends Instrument {


@Override
public void tune() {
System.out.println("Tuning the flute.");
}
}

34.

public class Building {


public void build() {
System.out.println("Building a structure.");
}
}

126
public class Skyscraper extends Building {
@Override
public void build() {
System.out.println("Building a skyscraper.");
}
}

35.

public class Vehicle {


public void start() {
System.out.println("The vehicle starts.");
}
}

public class Truck extends Vehicle {


@Override
public void start() {
System.out.println("The truck starts with a roar.");
}
}

public class Motorcycle extends Vehicle {


@Override
public void start() {
System.out.println("The motorcycle starts with a vroom.");
}
}

36.

public class Employee {


protected String name;
protected String department;

public Employee(String name, String department) {


this.name = name;
this.department = department;
}

public void displayDetails() {


System.out.println("Name: " + name + ", Department: " + department);
}
}

public class Intern extends Employee {


private int duration;

public Intern(String name, String department, int duration) {

127
super(name, department);
this.duration = duration;
}

@Override
public void displayDetails() {
System.out.println("Name: " + name + ", Department: " + department + ",
Internship Duration: " + duration + " months");
}
}

37.

public class Product {


protected String productId;
protected double price;

public Product(String productId, double price) {


this.productId = productId;
this.price = price;
}

public void displayDetails() {


System.out.println("Product ID: " + productId + ", Price: " + price);
}
}

public class Electronics extends Product {


private int warranty;

public Electronics(String productId, double price, int warranty) {


super(productId, price);
this.warranty = warranty;
}

@Override
public void displayDetails() {
System.out.println("Product ID: " + productId + ", Price: " + price + ",
Warranty: " + warranty + " years");
}
}

38.

public class Person {


public void introduce() {
System.out.println("Introducing a person.");
}
}

128
public class Student extends Person {
@Override
public void introduce() {
System.out.println("Introducing a student.");
}
}

public class Professor extends Person {


@Override
public void introduce() {
System.out.println("Introducing a professor.");
}
}

39.

public class Gadget {


public void useGadget() {
System.out.println("Using the gadget.");
}
}

public class Tablet extends Gadget {


@Override
public void useGadget() {
System.out.println("Using the tablet.");
}
}

40.

public class Artist {


public void create() {
System.out.println("Creating art.");
}
}

public class Sculptor extends Artist {


private String material;

public Sculptor(String material) {


this.material = material;
}

@Override
public void create() {
System.out.println("Creating a sculpture with " + material + ".");
}

129
}

41.

public class Vehicle {


public void fuelEfficiency() {
System.out.println("The vehicle has a certain fuel efficiency.");
}
}

public class HybridCar extends Vehicle {


@Override
public void fuelEfficiency() {
System.out.println("The hybrid car has excellent fuel efficiency.");
}
}

public class DieselTruck extends Vehicle {


@Override
public void fuelEfficiency() {
System.out.println("The diesel truck has moderate fuel efficiency.");
}
}

42.

public class Device {


public void turnOn() {
System.out.println("The device is turning on.");
}
}

public class Smartwatch extends Device {


@Override
public void turnOn() {
System.out.println("The smartwatch is turning on.");
}
}

43.

public class Employee {


public void performDuties() {
System.out.println("The employee performs duties.");
}
}

130
public class Janitor extends Employee {
private String shift;

public Janitor(String shift) {


this.shift = shift;
}

@Override
public void performDuties() {
System.out.println("The janitor performs duties during the " + shift + "
shift.");
}
}

44.

public class Musician {


public void perform() {
System.out.println("The musician performs.");
}
}

public class Vocalist extends Musician {


@Override
public void perform() {
System.out.println("The vocalist sings.");
}
}

public class Drummer extends Musician {


@Override
public void perform() {
System.out.println("The drummer plays the drums.");
}
}

45.

public class Gadget {


public void charge() {
System.out.println("Charging the gadget.");
}
}

public class ElectricScooter extends Gadget {


@Override
public void charge() {
System.out.println("Charging the electric scooter.");
}

131
}

46.

public class Person {


protected String name;
protected int age;

public Person(String name, int age) {


this.name = name;
this.age = age;
}

public void displayDetails() {


System.out.println("Name: " + name + ", Age: " + age);
}
}

public class Athlete extends Person {


private String sport;

public Athlete(String name, int age, String sport) {


super(name, age);
this.sport = sport;
}

@Override
public void displayDetails() {
System.out.println("Name: " + name + ", Age: " + age + ", Sport: " + sport);
}
}

47.

public class Furniture {


public void assemble() {
System.out.println("Assembling the furniture.");
}
}

public class Table extends Furniture {


@Override
public void assemble() {
System.out.println("Assembling the table.");
}
}

public class Shelf extends Furniture {


@Override

132
public void assemble() {
System.out.println("Assembling the shelf.");
}
}

48.

public class Vehicle {


public void maintenance() {
System.out.println("The vehicle needs maintenance.");
}
}

public class SportsCar extends Vehicle {


@Override
public void maintenance() {
System.out.println("The sports car needs high maintenance.");
}
}

49.

public class Building {


public void design() {
System.out.println("Designing the building.");
}
}

public class Museum extends Building {


private int exhibitCount;

public Museum(int exhibitCount) {


this.exhibitCount = exhibitCount;
}

@Override
public void design() {
System.out.println("Designing the museum with " + exhibitCount + "
exhibits.");
}
}

50.

public class Tool {


public void useTool() {
System.out.println("Using the tool.");

133
}
}

public class Hammer extends Tool {


@Override
public void useTool() {
System.out.println("Using the hammer.");
}
}

public class Wrench extends Tool {


@Override
public void useTool() {
System.out.println("Using the wrench.");
}
}

A.8. Chapter 8 Solutions


1.

public abstract class Appliance {


public abstract void turnOn();
}

public class Refrigerator extends Appliance {


@Override
public void turnOn() {
System.out.println("Refrigerator is turned on.");
}
}

public class Oven extends Appliance {


@Override
public void turnOn() {
System.out.println("Oven is turned on.");
}
}

2.

public class Payment {


public void makePayment() {
// Default implementation
}
}

public class CreditCardPayment extends Payment {

134
@Override
public void makePayment() {
System.out.println("Payment made with credit card.");
}
}

public class PayPalPayment extends Payment {


@Override
public void makePayment() {
System.out.println("Payment made with PayPal.");
}
}

3.

public class Vehicle {


public void start() {
System.out.println("Vehicle is starting.");
}
}

public class Car extends Vehicle {


@Override
public void start() {
System.out.println("Car is starting.");
}
}

public class Motorcycle extends Vehicle {


@Override
public void start() {
System.out.println("Motorcycle is starting.");
}
}

4.

public abstract class Instrument {


public abstract void play();
}

public class Guitar extends Instrument {


@Override
public void play() {
System.out.println("Playing the guitar.");
}
}

public class Drum extends Instrument {

135
@Override
public void play() {
System.out.println("Playing the drum.");
}
}

5.

public class Animal {


public void sound() {
// Default implementation
}
}

public class Dog extends Animal {


@Override
public void sound() {
System.out.println("Dog barks.");
}
}

public class Cat extends Animal {


@Override
public void sound() {
System.out.println("Cat meows.");
}
}

6.

public class Shape {


public double area() {
return 0;
}
}

public class Triangle extends Shape {


private double base;
private double height;

public Triangle(double base, double height) {


this.base = base;
this.height = height;
}

@Override
public double area() {
return 0.5 * base * height;
}

136
}

public class Rectangle extends Shape {


private double width;
private double height;

public Rectangle(double width, double height) {


this.width = width;
this.height = height;
}

@Override
public double area() {
return width * height;
}
}

7.

public abstract class Worker {


public abstract void work();
}

public class Engineer extends Worker {


@Override
public void work() {
System.out.println("Engineer is working.");
}
}

public class Doctor extends Worker {


@Override
public void work() {
System.out.println("Doctor is treating patients.");
}
}

8.

public class Printable {


public void print() {
// Default implementation
}
}

public class Book extends Printable {


@Override
public void print() {
System.out.println("Printing a book.");

137
}
}

public class Magazine extends Printable {


@Override
public void print() {
System.out.println("Printing a magazine.");
}
}

9.

public class Device {


public void operate() {
System.out.println("Operating the device.");
}
}

public class Laptop extends Device {


@Override
public void operate() {
System.out.println("Operating the laptop.");
}
}

public class Smartphone extends Device {


@Override
public void operate() {
System.out.println("Operating the smartphone.");
}
}

10.

public abstract class Building {


public abstract void construct();
}

public class House extends Building {


@Override
public void construct() {
System.out.println("Constructing a house.");
}
}

public class Skyscraper extends Building {


@Override
public void construct() {
System.out.println("Constructing a skyscraper.");

138
}
}

11.

public class Playable {


public void play() {
// Default implementation
}
}

public class VideoGame extends Playable {


@Override
public void play() {
System.out.println("Playing a video game.");
}
}

public class BoardGame extends Playable {


@Override
public void play() {
System.out.println("Playing a board game.");
}
}

12.

public class Animal {


public void move() {
System.out.println("Animal moves.");
}
}

public class Fish extends Animal {


@Override
public void move() {
System.out.println("Fish swims.");
}
}

public class Bird extends Animal {


@Override
public void move() {
System.out.println("Bird flies.");
}
}

13.

139
public abstract class Food {
public abstract void eat();
}

public class Pizza extends Food {


@Override
public void eat() {
System.out.println("Eating pizza.");
}
}

public class Salad extends Food {


@Override
public void eat() {
System.out.println("Eating salad.");
}
}

14.

public class Drivable {


public void drive() {
// Default implementation
}
}

public class Bicycle extends Drivable {


@Override
public void drive() {
System.out.println("Driving a bicycle.");
}
}

public class Truck extends Drivable {


@Override
public void drive() {
System.out.println("Driving a truck.");
}
}

15.

public class Employee {


public double calculateSalary() {
return 0;
}
}

140
public class Manager extends Employee {
@Override
public double calculateSalary() {
return 6000;
}
}

public class Developer extends Employee {


@Override
public double calculateSalary() {
return 5000;
}
}

16.

public abstract class Game {


public abstract void start();
}

public class Chess extends Game {


@Override
public void start() {
System.out.println("Starting a game of chess.");
}
}

public class Football extends Game {


@Override
public void start() {
System.out.println("Starting a game of football.");
}
}

17.

public class Flyable {


public void fly() {
// Default implementation
}
}

public class Airplane extends Flyable {


@Override
public void fly() {
System.out.println("Airplane is flying.");
}
}

141
public class Helicopter extends Flyable {
@Override
public void fly() {
System.out.println("Helicopter is flying.");
}
}

18.

public class Plant {


public void grow() {
System.out.println("Plant is growing.");
}
}

public class Flower extends Plant {


@Override
public void grow() {
System.out.println("Flower is blooming.");
}
}

public class Tree extends Plant {


@Override
public void grow() {
System.out.println("Tree is growing taller.");
}
}

19.

public abstract class Transport {


public abstract void move();
}

public class Car extends Transport {


@Override
public void move() {
System.out.println("Car is driving.");
}
}

public class Bicycle extends Transport {


@Override
public void move() {
System.out.println("Bicycle is being ridden.");
}
}

142
20.

public class Readable {


public void read() {
// Default implementation
}
}

public class EBook extends Readable {


@Override
public void read() {
System.out.println("Reading an ebook.");
}
}

public class PrintedBook extends Readable {


@Override
public void read() {
System.out.println("Reading a printed book.");
}
}

A.9. Chapter 9 Solutions


1.

public abstract class Vehicle {


public abstract void move();
}

public class Car extends Vehicle {


@Override
public void move() {
System.out.println("Car is moving.");
}
}

public class Bike extends Vehicle {


@Override
public void move() {
System.out.println("Bike is moving.");
}
}

2.

public class Flyable {

143
public void takeOff() {
// Default implementation
}

public void land() {


// Default implementation
}
}

public class Airplane extends Flyable {


@Override
public void takeOff() {
System.out.println("Airplane is taking off.");
}

@Override
public void land() {
System.out.println("Airplane is landing.");
}
}

public class Helicopter extends Flyable {


@Override
public void takeOff() {
System.out.println("Helicopter is taking off.");
}

@Override
public void land() {
System.out.println("Helicopter is landing.");
}
}

3.

public abstract class Appliance {


public abstract void turnOn();
}

public class WashingMachine extends Appliance {


@Override
public void turnOn() {
System.out.println("Washing Machine is turned on.");
}
}

public class Microwave extends Appliance {


@Override
public void turnOn() {
System.out.println("Microwave is turned on.");

144
}
}

4.

public class Playable {


public void play() {
// Default implementation
}
}

public class Guitar extends Playable {


@Override
public void play() {
System.out.println("Playing the guitar.");
}
}

public class Piano extends Playable {


@Override
public void play() {
System.out.println("Playing the piano.");
}
}

5.

public abstract class Employee {


public abstract double calculateSalary();
}

public class FullTimeEmployee extends Employee {


@Override
public double calculateSalary() {
return 5000;
}
}

public class PartTimeEmployee extends Employee {


@Override
public double calculateSalary() {
return 2000;
}
}

6.

145
public class Drawable {
public void draw() {
// Default implementation
}
}

public class Circle extends Drawable {


@Override
public void draw() {
System.out.println("Drawing a circle.");
}
}

public class Square extends Drawable {


@Override
public void draw() {
System.out.println("Drawing a square.");
}
}

7.

public abstract class Shape {


public abstract double area();
}

public class Rectangle extends Shape {


private double width;
private double height;

public Rectangle(double width, double height) {


this.width = width;
this.height = height;
}

@Override
public double area() {
return width * height;
}
}

public class Triangle extends Shape {


private double base;
private double height;

public Triangle(double base, double height) {


this.base = base;
this.height = height;
}

146
@Override
public double area() {
return 0.5 * base * height;
}
}

8.

public class Chargeable {


public void charge() {
// Default implementation
}

public void discharge() {


// Default implementation
}
}

public class Battery extends Chargeable {


@Override
public void charge() {
System.out.println("Battery is charging.");
}

@Override
public void discharge() {
System.out.println("Battery is discharging.");
}
}

public class Capacitor extends Chargeable {


@Override
public void charge() {
System.out.println("Capacitor is charging.");
}

@Override
public void discharge() {
System.out.println("Capacitor is discharging.");
}
}

9.

public abstract class Document {


public abstract void print();
}

147
public class PDFDocument extends Document {
@Override
public void print() {
System.out.println("Printing PDF document.");
}
}

public class WordDocument extends Document {


@Override
public void print() {
System.out.println("Printing Word document.");
}
}

10.

public class Storable {


public void save() {
// Default implementation
}

public void load() {


// Default implementation
}
}

public class Database extends Storable {


@Override
public void save() {
System.out.println("Saving to database.");
}

@Override
public void load() {
System.out.println("Loading from database.");
}
}

public class FileStorage extends Storable {


@Override
public void save() {
System.out.println("Saving to file storage.");
}

@Override
public void load() {
System.out.println("Loading from file storage.");
}
}

148
11.

public abstract class Food {


public abstract void prepare();
}

public class Pizza extends Food {


@Override
public void prepare() {
System.out.println("Preparing pizza.");
}
}

public class Salad extends Food {


@Override
public void prepare() {
System.out.println("Preparing salad.");
}
}

12.

public class Operable {


public void start() {
// Default implementation
}

public void stop() {


// Default implementation
}
}

public class Engine extends Operable {


@Override
public void start() {
System.out.println("Engine is starting.");
}

@Override
public void stop() {
System.out.println("Engine is stopping.");
}
}

public class Fan extends Operable {


@Override
public void start() {
System.out.println("Fan is starting.");
}

149
@Override
public void stop() {
System.out.println("Fan is stopping.");
}
}

13.

public abstract class Game {


public abstract void start();
}

public class Football extends Game {


@Override
public void start() {
System.out.println("Starting a game of football.");
}
}

public class Chess extends Game {


@Override
public void start() {
System.out.println("Starting a game of chess.");
}
}

14.

public class Printable {


public void print() {
// Default implementation
}
}

public class Book extends Printable {


@Override
public void print() {
System.out.println("Printing a book.");
}
}

public class Magazine extends Printable {


@Override
public void print() {
System.out.println("Printing a magazine.");
}
}

150
15.

public abstract class Account {


public abstract double calculateInterest();
}

public class SavingsAccount extends Account {


@Override
public double calculateInterest() {
return 0.05;
}
}

public class FixedDepositAccount extends Account {


@Override
public double calculateInterest() {
return 0.07;
}
}

16.

public class Swimmable {


public void swim() {
// Default implementation
}
}

public class Fish extends Swimmable {


@Override
public void swim() {
System.out.println("Fish is swimming.");
}
}

public class Duck extends Swimmable {


@Override
public void swim() {
System.out.println("Duck is swimming.");
}
}

17.

public abstract class Animal {


public abstract void makeSound();
}

151
public class Lion extends Animal {
@Override
public void makeSound() {
System.out.println("Lion roars.");
}
}

public class Elephant extends Animal {


@Override
public void makeSound() {
System.out.println("Elephant trumpets.");
}
}

18.

public class Rechargeable {


public void recharge() {
// Default implementation
}
}

public class ElectricCar extends Rechargeable {


@Override
public void recharge() {
System.out.println("Electric car is recharging.");
}
}

public class Smartphone extends Rechargeable {


@Override
public void recharge() {
System.out.println("Smartphone is recharging.");
}
}

19.

public abstract class Transport {


public abstract void move();
}

public class Bus extends Transport {


@Override
public void move() {
System.out.println("Bus is moving.");
}
}

152
public class Train extends Transport {
@Override
public void move() {
System.out.println("Train is moving.");
}
}

20.

public class Climbable {


public void climb() {
// Default implementation
}
}

public class Monkey extends Climbable {


@Override
public void climb() {
System.out.println("Monkey is climbing.");
}
}

public class Mountaineer extends Climbable {


@Override
public void climb() {
System.out.println("Mountaineer is climbing.");
}
}

A.10. Chapter 10 Solutions


1.

public interface Playable {


void play();
void pause();
}

public class MusicPlayer implements Playable {


@Override
public void play() {
System.out.println("Music is playing.");
}

@Override
public void pause() {
System.out.println("Music is paused.");
}

153
}

public class VideoPlayer implements Playable {


@Override
public void play() {
System.out.println("Video is playing.");
}

@Override
public void pause() {
System.out.println("Video is paused.");
}
}

2.

public interface Shape {


double calculateArea();
}

public class Circle implements Shape {


private double radius;

public Circle(double radius) {


this.radius = radius;
}

@Override
public double calculateArea() {
return Math.PI * radius * radius;
}
}

public class Square implements Shape {


private double side;

public Square(double side) {


this.side = side;
}

@Override
public double calculateArea() {
return side * side;
}
}

3.

public interface Movable {

154
void moveForward();
void moveBackward();
}

public class Robot implements Movable {


@Override
public void moveForward() {
System.out.println("Robot moves forward.");
}

@Override
public void moveBackward() {
System.out.println("Robot moves backward.");
}
}

public class Car implements Movable {


@Override
public void moveForward() {
System.out.println("Car moves forward.");
}

@Override
public void moveBackward() {
System.out.println("Car moves backward.");
}
}

4.

public interface Printable {


void print();
}

public class Report implements Printable {


@Override
public void print() {
System.out.println("Printing report.");
}
}

public class Invoice implements Printable {


@Override
public void print() {
System.out.println("Printing invoice.");
}
}

5.

155
public interface Resizable {
void resizeUp();
void resizeDown();
}

public class Window implements Resizable {


@Override
public void resizeUp() {
System.out.println("Window is resized up.");
}

@Override
public void resizeDown() {
System.out.println("Window is resized down.");
}
}

public class Image implements Resizable {


@Override
public void resizeUp() {
System.out.println("Image is resized up.");
}

@Override
public void resizeDown() {
System.out.println("Image is resized down.");
}
}

6.

public interface Drawable {


void draw();
}

public class Line implements Drawable {


@Override
public void draw() {
System.out.println("Drawing a line.");
}
}

public class Rectangle implements Drawable {


@Override
public void draw() {
System.out.println("Drawing a rectangle.");
}
}

156
7.

public interface Operable {


void start();
void stop();
}

public class Machine implements Operable {


@Override
public void start() {
System.out.println("Machine is starting.");
}

@Override
public void stop() {
System.out.println("Machine is stopping.");
}
}

public class Engine implements Operable {


@Override
public void start() {
System.out.println("Engine is starting.");
}

@Override
public void stop() {
System.out.println("Engine is stopping.");
}
}

8.

public interface Storable {


void save();
void delete();
}

public class File implements Storable {


@Override
public void save() {
System.out.println("Saving file.");
}

@Override
public void delete() {
System.out.println("Deleting file.");
}
}

157
public class Database implements Storable {
@Override
public void save() {
System.out.println("Saving to database.");
}

@Override
public void delete() {
System.out.println("Deleting from database.");
}
}

9.

public interface Chargeable {


void charge();
void discharge();
}

public class Battery implements Chargeable {


@Override
public void charge() {
System.out.println("Charging battery.");
}

@Override
public void discharge() {
System.out.println("Discharging battery.");
}
}

public class ElectricCar implements Chargeable {


@Override
public void charge() {
System.out.println("Charging electric car.");
}

@Override
public void discharge() {
System.out.println("Discharging electric car.");
}
}

10.

public interface Notifiable {


void sendNotification();
}

158
public class EmailService implements Notifiable {
@Override
public void sendNotification() {
System.out.println("Sending email notification.");
}
}

public class SMSService implements Notifiable {


@Override
public void sendNotification() {
System.out.println("Sending SMS notification.");
}
}

11.

public interface Flyable {


void takeOff();
void land();
}

public class Bird implements Flyable {


@Override
public void takeOff() {
System.out.println("Bird is taking off.");
}

@Override
public void land() {
System.out.println("Bird is landing.");
}
}

public class Airplane implements Flyable {


@Override
public void takeOff() {
System.out.println("Airplane is taking off.");
}

@Override
public void land() {
System.out.println("Airplane is landing.");
}
}

12.

public interface Connectable {

159
void connect();
void disconnect();
}

public class WiFi implements Connectable {


@Override
public void connect() {
System.out.println("Connecting to WiFi.");
}

@Override
public void disconnect() {
System.out.println("Disconnecting from WiFi.");
}
}

public class Bluetooth implements Connectable {


@Override
public void connect() {
System.out.println("Connecting to Bluetooth.");
}

@Override
public void disconnect() {
System.out.println("Disconnecting from Bluetooth.");
}
}

13.

public interface Updatable {


void update();
}

public class Software implements Updatable {


@Override
public void update() {
System.out.println("Updating software.");
}
}

public class Firmware implements Updatable {


@Override
public void update() {
System.out.println("Updating firmware.");
}
}

14.

160
public interface Repairable {
void repair();
}

public class Car implements Repairable {


@Override
public void repair() {
System.out.println("Repairing car.");
}
}

public class Computer implements Repairable {


@Override
public void repair() {
System.out.println("Repairing computer.");
}
}

15.

public interface Buildable {


void build();
}

public class House implements Buildable {


@Override
public void build() {
System.out.println("Building house.");
}
}

public class Boat implements Buildable {


@Override
public void build() {
System.out.println("Building boat.");
}
}

16.

public interface Monitorable {


void monitor();
}

public class Network implements Monitorable {


@Override
public void monitor() {
System.out.println("Monitoring network.");

161
}
}

public class SecuritySystem implements Monitorable {


@Override
public void monitor() {
System.out.println("Monitoring security system.");
}
}

17.

public interface Sellable {


void sell();
}

public class Product implements Sellable {


@Override
public void sell() {
System.out.println("Selling product.");
}
}

public class Service implements Sellable {


@Override
public void sell() {
System.out.println("Selling service.");
}
}

18.

public interface Loggable {


void log();
}

public class EventLogger implements Loggable {


@Override
public void log() {
System.out.println("Logging event.");
}
}

public class TransactionLogger implements Loggable {


@Override
public void log() {
System.out.println("Logging transaction.");
}

162
}

19.

public interface Configurable {


void configure();
}

public class System implements Configurable {


@Override
public void configure() {
System.out.println("Configuring system.");
}
}

public class Application implements Configurable {


@Override
public void configure() {
System.out.println("Configuring application.");
}
}

20.

public interface Playable {


void startGame();
void endGame();
}

public class Chess implements Playable {


@Override
public void startGame() {
System.out.println("Starting chess game.");
}

@Override
public void endGame() {
System.out.println("Ending chess game.");
}
}

public class Football implements Playable {


@Override
public void startGame() {
System.out.println("Starting football game.");
}

@Override
public void endGame() {

163
System.out.println("Ending football game.");
}
}

A.11. Chapter 11 Solutions


1.

import java.io.*;
import java.sql.*;

public class CheckedExceptionsDemo {


public static void main(String[] args) {
// Demonstrating IOException
try {
FileReader file = new FileReader("nonexistentfile.txt");
BufferedReader fileInput = new BufferedReader(file);
fileInput.close();
} catch (IOException e) {
System.out.println("IOException caught: " + e.getMessage());
}

// Demonstrating SQLException
try {
Connection conn = DriverManager.getConnection
("jdbc:mysql://localhost/test", "user", "password");
} catch (SQLException e) {
System.out.println("SQLException caught: " + e.getMessage());
}
}
}

2.

class InvalidAgeException extends Exception {


public InvalidAgeException(String message) {
super(message);
}
}

public class InvalidAgeExceptionDemo {


public static void main(String[] args) {
try {
int age = -1;
if (age < 0) {
throw new InvalidAgeException("Age cannot be negative.");
}
} catch (InvalidAgeException e) {

164
System.out.println("Caught: " + e.getMessage());
}
}
}

3.

public class ArrayIndexOutOfBoundsExceptionDemo {


public static void main(String[] args) {
try {
int[] arr = {1, 2, 3, 4, 5};
System.out.println(arr[10]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBoundsException caught: " + e
.getMessage());
}
}
}

4.

class NegativeNumberException extends Exception {


public NegativeNumberException(String message) {
super(message);
}
}

public class NegativeNumberExceptionDemo {


public static void main(String[] args) {
try {
int number = -10;
if (number < 0) {
throw new NegativeNumberException("Number cannot be negative.");
}
} catch (NegativeNumberException e) {
System.out.println("Caught: " + e.getMessage());
}
}
}

5.

public class ClassNotFoundExceptionDemo {


public static void main(String[] args) {
try {
Class.forName("com.nonexistent.Class");
} catch (ClassNotFoundException e) {

165
System.out.println("ClassNotFoundException caught: " + e.getMessage());
}
}
}

6.

class InsufficientFundsException extends Exception {


public InsufficientFundsException(String message) {
super(message);
}
}

public class InsufficientFundsExceptionDemo {


public static void main(String[] args) {
double balance = 500.0;
double withdrawAmount = 600.0;

try {
if (withdrawAmount > balance) {
throw new InsufficientFundsException("Insufficient funds for
withdrawal.");
}
} catch (InsufficientFundsException e) {
System.out.println("Caught: " + e.getMessage());
}
}
}

7.

public class NullPointerExceptionDemo {


public static void main(String[] args) {
try {
String str = null;
System.out.println(str.length());
} catch (NullPointerException e) {
System.out.println("NullPointerException caught: " + e.getMessage());
}
}
}

8.

class ProductNotFoundException extends Exception {


public ProductNotFoundException(String message) {
super(message);

166
}
}

public class ProductNotFoundExceptionDemo {


public static void main(String[] args) {
String productId = "12345";
String product = null; // Simulating product not found

try {
if (product == null) {
throw new ProductNotFoundException("Product with ID " + productId + "
not found.");
}
} catch (ProductNotFoundException e) {
System.out.println("Caught: " + e.getMessage());
}
}
}

9.

public class InterruptedExceptionDemo {


public static void main(String[] args) {
Thread thread = new Thread(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("InterruptedException caught: " + e.getMessage());
}
});

thread.start();
thread.interrupt();
}
}

10.

class UnauthorizedAccessException extends Exception {


public UnauthorizedAccessException(String message) {
super(message);
}
}

public class UnauthorizedAccessExceptionDemo {


public static void main(String[] args) {
boolean hasAccess = false;

try {

167
if (!hasAccess) {
throw new UnauthorizedAccessException("User does not have access.");
}
} catch (UnauthorizedAccessException e) {
System.out.println("Caught: " + e.getMessage());
}
}
}

11.

public class ArithmeticExceptionDemo {


public static void main(String[] args) {
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("ArithmeticException caught: " + e.getMessage());
}
}
}

12.

class InvalidInputException extends Exception {


public InvalidInputException(String message) {
super(message);
}
}

public class InvalidInputExceptionDemo {


public static void main(String[] args) {
try {
String input = "invalid";
if (!input.matches("\\d+")) {
throw new InvalidInputException("Invalid input provided.");
}
} catch (InvalidInputException e) {
System.out.println("Caught: " + e.getMessage());
}
}
}

13.

public class IllegalArgumentExceptionDemo {


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

168
int age = -1;
if (age < 0) {
throw new IllegalArgumentException("Age cannot be negative.");
}
} catch (IllegalArgumentException e) {
System.out.println("IllegalArgumentException caught: " + e.getMessage());
}
}
}

14.

class OutOfStockException extends Exception {


public OutOfStockException(String message) {
super(message);
}
}

public class OutOfStockExceptionDemo {


public static void main(String[] args) {
int stock = 0;

try {
if (stock == 0) {
throw new OutOfStockException("Item is out of stock.");
}
} catch (OutOfStockException e) {
System.out.println("Caught: " + e.getMessage());
}
}
}

15.

public class NumberFormatExceptionDemo {


public static void main(String[] args) {
try {
String str = "invalid";
int number = Integer.parseInt(str);
} catch (NumberFormatException e) {
System.out.println("NumberFormatException caught: " + e.getMessage());
}
}
}

16.

169
class PermissionDeniedException extends Exception {
public PermissionDeniedException(String message) {
super(message);
}
}

public class PermissionDeniedExceptionDemo {


public static void main(String[] args) {
boolean hasPermission = false;

try {
if (!hasPermission) {
throw new PermissionDeniedException("Permission denied.");
}
} catch (PermissionDeniedException e) {
System.out.println("Caught: " + e.getMessage());
}
}
}

17.

import java.io.*;

public class FileNotFoundExceptionDemo {


public static void main(String[] args) {
try {
FileInputStream file = new FileInputStream("nonexistentfile.txt");
} catch (FileNotFoundException e) {
System.out.println("FileNotFoundException caught: " + e.getMessage());
}
}
}

18.

class TimeOutException extends Exception {


public TimeOutException(String message) {
super(message);
}
}

public class TimeOutExceptionDemo {


public static void main(String[] args) {
boolean operationTimedOut = true;

try {
if (operationTimedOut) {

170
throw new TimeOutException("Operation timed out.");
}
} catch (TimeOutException e) {
System.out.println("Caught: " + e.getMessage());
}
}
}

19.

public class UnsupportedOperationExceptionDemo {


public static void main(String[] args) {
try {
throw new UnsupportedOperationException("This operation is not
supported.");
} catch (UnsupportedOperationException e) {
System.out.println("UnsupportedOperationException caught: " + e.
getMessage());
}
}
}

20.

class DataValidationException extends Exception {


public DataValidationException(String message) {
super(message);
}
}

public class DataValidationExceptionDemo {


public static void main(String[] args) {
try {
String data = "invalid_data";
if (!data.matches("[a-zA-Z0-9]+")) {
throw new DataValidationException("Data validation failed.");
}
} catch (DataValidationException e) {
System.out.println("Caught: " + e.getMessage());
}
}
}

21.

import java.util.*;

171
public class IndexOutOfBoundsExceptionDemo {
public static void main(String[] args) {
try {
List<String> list = new ArrayList<>(Arrays.asList("A", "B", "C"));
System.out.println(list.get(10));
} catch (IndexOutOfBoundsException e) {
System.out.println("IndexOutOfBoundsException caught: " + e.getMessage());
}
}
}

22.

class ResourceNotFoundException extends Exception {


public ResourceNotFoundException(String message) {
super(message);
}
}

public class ResourceNotFoundExceptionDemo {


public static void main(String[] args) {
try {
String resource = null; // Simulating resource not found
if (resource == null) {
throw new ResourceNotFoundException("Resource not found.");
}
} catch (ResourceNotFoundException e) {
System.out.println("Caught: " + e.getMessage());
}
}
}

23.

public class StringIndexOutOfBoundsExceptionDemo {


public static void main(String[] args) {
try {
String str = "Hello";
char ch = str.charAt(10);
} catch (StringIndexOutOfBoundsException e) {
System.out.println("StringIndexOutOfBoundsException caught: " + e
.getMessage());
}
}
}

24.

172
class DuplicateEntryException extends Exception {
public DuplicateEntryException(String message) {
super(message);
}
}

public class DuplicateEntryExceptionDemo {


public static void main(String[] args) {
try {
String[] entries = {"entry1", "entry2", "entry1"};
Set<String> entrySet = new HashSet<>();
for (String entry : entries) {
if (!entrySet.add(entry)) {
throw new DuplicateEntryException("Duplicate entry found: " +
entry);
}
}
} catch (DuplicateEntryException e) {
System.out.println("Caught: " + e.getMessage());
}
}
}

25.

public class IllegalStateExceptionDemo {


public static void main(String[] args) {
try {
List<String> list = new ArrayList<>();
Iterator<String> iterator = list.iterator();
iterator.remove();
} catch (IllegalStateException e) {
System.out.println("IllegalStateException caught: " + e.getMessage());
}
}
}

26.

class OperationFailedException extends Exception {


public OperationFailedException(String message) {
super(message);
}
}

public class OperationFailedExceptionDemo {


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

173
boolean operationSuccessful = false;
if (!operationSuccessful) {
throw new OperationFailedException("Operation failed to complete
successfully.");
}
} catch (OperationFailedException e) {
System.out.println("Caught: " + e.getMessage());
}
}
}

27.

public class ClassCastExceptionDemo {


public static void main(String[] args) {
try {
Object obj = new Integer(0);
String str = (String) obj;
} catch (ClassCastException e) {
System.out.println("ClassCastException caught: " + e.getMessage());
}
}
}

28.

class ConfigurationException extends Exception {


public ConfigurationException(String message) {
super(message);
}
}

public class ConfigurationExceptionDemo {


public static void main(String[] args) {
try {
boolean configurationValid = false;
if (!configurationValid) {
throw new ConfigurationException("Configuration error occurred.");
}
} catch (ConfigurationException e) {
System.out.println("Caught: " + e.getMessage());
}
}
}

29.

174
public class NegativeArraySizeExceptionDemo {
public static void main(String[] args) {
try {
int[] arr = new int[-10];
} catch (NegativeArraySizeException e) {
System.out.println("NegativeArraySizeException caught: " + e.
getMessage());
}
}
}

30.

class TransactionFailedException extends Exception {


public TransactionFailedException(String message) {
super(message);
}
}

public class TransactionFailedExceptionDemo {


public static void main(String[] args) {
try {
boolean transactionSuccessful = false;
if (!transactionSuccessful) {
throw new TransactionFailedException("Transaction failed.");
}
} catch (TransactionFailedException e) {
System.out.println("Caught: " + e.getMessage());
}
}
}

31.

import java.util.*;

public class NoSuchElementExceptionDemo {


public static void main(String[] args) {
try {
List<String> list = new ArrayList<>();
Iterator<String> iterator = list.iterator();
String nextElement = iterator.next();
} catch (NoSuchElementException e) {
System.out.println("NoSuchElementException caught: " + e.getMessage());
}
}
}

175
32.

class InsufficientBalanceException extends Exception {


public InsufficientBalanceException(String message) {
super(message);
}
}

public class InsufficientBalanceExceptionDemo {


public static void main(String[] args) {
double balance = 100.0;
double withdrawAmount = 150.0;

try {
if (withdrawAmount > balance) {
throw new InsufficientBalanceException("Insufficient balance.");
}
} catch (InsufficientBalanceException e) {
System.out.println("Caught: " + e.getMessage());
}
}
}

33.

import java.io.*;

public class IOExceptionDemo {


public static void main(String[] args) {
try {
BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
String line = reader.readLine();
System.out.println(line);
reader.close();
} catch (IOException e) {
System.out.println("IOException caught: " + e.getMessage());
}
}
}

34.

class InvalidOperationException extends Exception {


public InvalidOperationException(String message) {
super(message);
}
}

176
public class InvalidOperationExceptionDemo {
public static void main(String[] args) {
try {
boolean invalidOperation = true;
if (invalidOperation) {
throw new InvalidOperationException("Invalid operation performed.");
}
} catch (InvalidOperationException e) {
System.out.println("Caught: " + e.getMessage());
}
}
}

35.

public class SecurityExceptionDemo {


public static void main(String[] args) {
try {
System.setSecurityManager(new SecurityManager());
System.getSecurityManager().checkRead("file.txt");
} catch (SecurityException e) {
System.out.println("SecurityException caught: " + e.getMessage());
}
}
}

36.

class DatabaseConnectionException extends Exception {


public DatabaseConnectionException(String message) {
super(message);
}
}

public class DatabaseConnectionExceptionDemo {


public static void main(String[] args) {
try {
boolean databaseConnected = false;
if (!databaseConnected) {
throw new DatabaseConnectionException("Failed to connect to the
database.");
}
} catch (DatabaseConnectionException e) {
System.out.println("Caught: " + e.getMessage());
}
}
}

177
37.

public class InterruptedExceptionMultiThreadingDemo {


public static void main(String[] args) {
Thread thread = new Thread(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("InterruptedException caught in thread: " + e
.getMessage());
}
});

thread.start();
thread.interrupt();
}
}

38.

class FileUploadException extends Exception {


public FileUploadException(String message) {
super(message);
}
}

public class FileUploadExceptionDemo {


public static void main(String[] args) {
try {
boolean uploadSuccessful = false;
if (!uploadSuccessful) {
throw new FileUploadException("File upload failed.");
}
} catch (FileUploadException e) {
System.out.println("Caught: " + e.getMessage());
}
}
}

39.

public class ReflectiveOperationExceptionDemo {


public static void main(String[] args) {
try {
Class<?> cls = Class.forName("java.lang.String");
Object instance = cls.getDeclaredConstructor().newInstance();
} catch (ReflectiveOperationException e) {
System.out.println("ReflectiveOperationException caught: " + e.

178
getMessage());
}
}
}

40.

class InvalidFormatException extends Exception {


public InvalidFormatException(String message) {
super(message);
}
}

public class InvalidFormatExceptionDemo {


public static void main(String[] args) {
try {
String data = "invalid_data";
if (!data.matches("\\d+")) {
throw new InvalidFormatException("Invalid format.");
}
} catch (InvalidFormatException e) {
System.out.println("Caught: " + e.getMessage());
}
}
}

A.12. Chapter 11 Solutions


1.

import java.io.*;
import java.sql.*;

public class CheckedExceptionsDemo {


public static void main(String[] args) {
// Demonstrating IOException
try {
FileReader file = new FileReader("nonexistentfile.txt");
BufferedReader fileInput = new BufferedReader(file);
fileInput.close();
} catch (IOException e) {
System.out.println("IOException caught: " + e.getMessage());
}

// Demonstrating SQLException
try {
Connection conn = DriverManager.getConnection
("jdbc:mysql://localhost/test", "user", "password");

179
} catch (SQLException e) {
System.out.println("SQLException caught: " + e.getMessage());
}
}
}

2.

class InvalidAgeException extends Exception {


public InvalidAgeException(String message) {
super(message);
}
}

public class InvalidAgeExceptionDemo {


public static void main(String[] args) {
try {
int age = -1;
if (age < 0) {
throw new InvalidAgeException("Age cannot be negative.");
}
} catch (InvalidAgeException e) {
System.out.println("Caught: " + e.getMessage());
}
}
}

3.

public class ArrayIndexOutOfBoundsExceptionDemo {


public static void main(String[] args) {
try {
int[] arr = {1, 2, 3, 4, 5};
System.out.println(arr[10]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBoundsException caught: " + e
.getMessage());
}
}
}

4.

class NegativeNumberException extends Exception {


public NegativeNumberException(String message) {
super(message);
}

180
}

public class NegativeNumberExceptionDemo {


public static void main(String[] args) {
try {
int number = -10;
if (number < 0) {
throw new NegativeNumberException("Number cannot be negative.");
}
} catch (NegativeNumberException e) {
System.out.println("Caught: " + e.getMessage());
}
}
}

5.

public class ClassNotFoundExceptionDemo {


public static void main(String[] args) {
try {
Class.forName("com.nonexistent.Class");
} catch (ClassNotFoundException e) {
System.out.println("ClassNotFoundException caught: " + e.getMessage());
}
}
}

6.

class InsufficientFundsException extends Exception {


public InsufficientFundsException(String message) {
super(message);
}
}

public class InsufficientFundsExceptionDemo {


public static void main(String[] args) {
double balance = 500.0;
double withdrawAmount = 600.0;

try {
if (withdrawAmount > balance) {
throw new InsufficientFundsException("Insufficient funds for
withdrawal.");
}
} catch (InsufficientFundsException e) {
System.out.println("Caught: " + e.getMessage());
}
}

181
}

7.

public class NullPointerExceptionDemo {


public static void main(String[] args) {
try {
String str = null;
System.out.println(str.length());
} catch (NullPointerException e) {
System.out.println("NullPointerException caught: " + e.getMessage());
}
}
}

8.

class ProductNotFoundException extends Exception {


public ProductNotFoundException(String message) {
super(message);
}
}

public class ProductNotFoundExceptionDemo {


public static void main(String[] args) {
String productId = "12345";
String product = null; // Simulating product not found

try {
if (product == null) {
throw new ProductNotFoundException("Product with ID " + productId + "
not found.");
}
} catch (ProductNotFoundException e) {
System.out.println("Caught: " + e.getMessage());
}
}
}

9.

public class InterruptedExceptionDemo {


public static void main(String[] args) {
Thread thread = new Thread(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {

182
System.out.println("InterruptedException caught: " + e.getMessage());
}
});

thread.start();
thread.interrupt();
}
}

10.

class UnauthorizedAccessException extends Exception {


public UnauthorizedAccessException(String message) {
super(message);
}
}

public class UnauthorizedAccessExceptionDemo {


public static void main(String[] args) {
boolean hasAccess = false;

try {
if (!hasAccess) {
throw new UnauthorizedAccessException("User does not have access.");
}
} catch (UnauthorizedAccessException e) {
System.out.println("Caught: " + e.getMessage());
}
}
}

11.

public class ArithmeticExceptionDemo {


public static void main(String[] args) {
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("ArithmeticException caught: " + e.getMessage());
}
}
}

12.

class InvalidInputException extends Exception {


public InvalidInputException(String message) {

183
super(message);
}
}

public class InvalidInputExceptionDemo {


public static void main(String[] args) {
try {
String input = "invalid";
if (!input.matches("\\d+")) {
throw new InvalidInputException("Invalid input provided.");
}
} catch (InvalidInputException e) {
System.out.println("Caught: " + e.getMessage());
}
}
}

13.

public class IllegalArgumentExceptionDemo {


public static void main(String[] args) {
try {
int age = -1;
if (age < 0) {
throw new IllegalArgumentException("Age cannot be negative.");
}
} catch (IllegalArgumentException e) {
System.out.println("IllegalArgumentException caught: " + e.getMessage());
}
}
}

14.

class OutOfStockException extends Exception {


public OutOfStockException(String message) {
super(message);
}
}

public class OutOfStockExceptionDemo {


public static void main(String[] args) {
int stock = 0;

try {
if (stock == 0) {
throw new OutOfStockException("Item is out of stock.");
}
} catch (OutOfStockException e) {

184
System.out.println("Caught: " + e.getMessage());
}
}
}

15.

public class NumberFormatExceptionDemo {


public static void main(String[] args) {
try {
String str = "invalid";
int number = Integer.parseInt(str);
} catch (NumberFormatException e) {
System.out.println("NumberFormatException caught: " + e.getMessage());
}
}
}

16.

class PermissionDeniedException extends Exception {


public PermissionDeniedException(String message) {
super(message);
}
}

public class PermissionDeniedExceptionDemo {


public static void main(String[] args) {
boolean hasPermission = false;

try {
if (!hasPermission) {
throw new PermissionDeniedException("Permission denied.");
}
} catch (PermissionDeniedException e) {
System.out.println("Caught: " + e.getMessage());
}
}
}

17.

import java.io.*;

public class FileNotFoundExceptionDemo {


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

185
FileInputStream file = new FileInputStream("nonexistentfile.txt");
} catch (FileNotFoundException e) {
System.out.println("FileNotFoundException caught: " + e.getMessage());
}
}
}

18.

class TimeOutException extends Exception {


public TimeOutException(String message) {
super(message);
}
}

public class TimeOutExceptionDemo {


public static void main(String[] args) {
boolean operationTimedOut = true;

try {
if (operationTimedOut) {
throw new TimeOutException("Operation timed out.");
}
} catch (TimeOutException e) {
System.out.println("Caught: " + e.getMessage());
}
}
}

19.

public class UnsupportedOperationExceptionDemo {


public static void main(String[] args) {
try {
throw new UnsupportedOperationException("This operation is not
supported.");
} catch (UnsupportedOperationException e) {
System.out.println("UnsupportedOperationException caught: " + e.
getMessage());
}
}
}

20.

class DataValidationException extends Exception {


public DataValidationException(String message) {

186
super(message);
}
}

public class DataValidationExceptionDemo {


public static void main(String[] args) {
try {
String data = "invalid_data";
if (!data.matches("[a-zA-Z0-9]+")) {
throw new DataValidationException("Data validation failed.");
}
} catch (DataValidationException e) {
System.out.println("Caught: " + e.getMessage());
}
}
}

21.

import java.util.*;

public class IndexOutOfBoundsExceptionDemo {


public static void main(String[] args) {
try {
List<String> list = new ArrayList<>(Arrays.asList("A", "B", "C"));
System.out.println(list.get(10));
} catch (IndexOutOfBoundsException e) {
System.out.println("IndexOutOfBoundsException caught: " + e.getMessage());
}
}
}

22.

class ResourceNotFoundException extends Exception {


public ResourceNotFoundException(String message) {
super(message);
}
}

public class ResourceNotFoundExceptionDemo {


public static void main(String[] args) {
try {
String resource = null; // Simulating resource not found
if (resource == null) {
throw new ResourceNotFoundException("Resource not found.");
}
} catch (ResourceNotFoundException e) {
System.out.println("Caught: " + e.getMessage());

187
}
}
}

23.

public class StringIndexOutOfBoundsExceptionDemo {


public static void main(String[] args) {
try {
String str = "Hello";
char ch = str.charAt(10);
} catch (StringIndexOutOfBoundsException e) {
System.out.println("StringIndexOutOfBoundsException caught: " + e
.getMessage());
}
}
}

24.

class DuplicateEntryException extends Exception {


public DuplicateEntryException(String message) {
super(message);
}
}

public class DuplicateEntryExceptionDemo {


public static void main(String[] args) {
try {
String[] entries = {"entry1", "entry2", "entry1"};
Set<String> entrySet = new HashSet<>();
for (String entry : entries) {
if (!entrySet.add(entry)) {
throw new DuplicateEntryException("Duplicate entry found: " +
entry);
}
}
} catch (DuplicateEntryException e) {
System.out.println("Caught: " + e.getMessage());
}
}
}

25.

public class IllegalStateExceptionDemo {


public static void main(String[] args) {

188
try {
List<String> list = new ArrayList<>();
Iterator<String> iterator = list.iterator();
iterator.remove();
} catch (IllegalStateException e) {
System.out.println("IllegalStateException caught: " + e.getMessage());
}
}
}

26.

class OperationFailedException extends Exception {


public OperationFailedException(String message) {
super(message);
}
}

public class OperationFailedExceptionDemo {


public static void main(String[] args) {
try {
boolean operationSuccessful = false;
if (!operationSuccessful) {
throw new OperationFailedException("Operation failed to complete
successfully.");
}
} catch (OperationFailedException e) {
System.out.println("Caught: " + e.getMessage());
}
}
}

27.

public class ClassCastExceptionDemo {


public static void main(String[] args) {
try {
Object obj = new Integer(0);
String str = (String) obj;
} catch (ClassCastException e) {
System.out.println("ClassCastException caught: " + e.getMessage());
}
}
}

28.

189
class ConfigurationException extends Exception {
public ConfigurationException(String message) {
super(message);
}
}

public class ConfigurationExceptionDemo {


public static void main(String[] args) {
try {
boolean configurationValid = false;
if (!configurationValid) {
throw new ConfigurationException("Configuration error occurred.");
}
} catch (ConfigurationException e) {
System.out.println("Caught: " + e.getMessage());
}
}
}

29.

public class NegativeArraySizeExceptionDemo {


public static void main(String[] args) {
try {
int[] arr = new int[-10];
} catch (NegativeArraySizeException e) {
System.out.println("NegativeArraySizeException caught: " + e.
getMessage());
}
}
}

30.

class TransactionFailedException extends Exception {


public TransactionFailedException(String message) {
super(message);
}
}

public class TransactionFailedExceptionDemo {


public static void main(String[] args) {
try {
boolean transactionSuccessful = false;
if (!transactionSuccessful) {
throw new TransactionFailedException("Transaction failed.");
}
} catch (TransactionFailedException e) {

190
System.out.println("Caught: " + e.getMessage());
}
}
}

31.

import java.util.*;

public class NoSuchElementExceptionDemo {


public static void main(String[] args) {
try {
List<String> list = new ArrayList<>();
Iterator<String> iterator = list.iterator();
String nextElement = iterator.next();
} catch (NoSuchElementException e) {
System.out.println("NoSuchElementException caught: " + e.getMessage());
}
}
}

32.

class InsufficientBalanceException extends Exception {


public InsufficientBalanceException(String message) {
super(message);
}
}

public class InsufficientBalanceExceptionDemo {


public static void main(String[] args) {
double balance = 100.0;
double withdrawAmount = 150.0;

try {
if (withdrawAmount > balance) {
throw new InsufficientBalanceException("Insufficient balance.");
}
} catch (InsufficientBalanceException e) {
System.out.println("Caught: " + e.getMessage());
}
}
}

33.

import java.io.*;

191
public class IOExceptionDemo {
public static void main(String[] args) {
try {
BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
String line = reader.readLine();
System.out.println(line);
reader.close();
} catch (IOException e) {
System.out.println("IOException caught: " + e.getMessage());
}
}
}

34.

class InvalidOperationException extends Exception {


public InvalidOperationException(String message) {
super(message);
}
}

public class InvalidOperationExceptionDemo {


public static void main(String[] args) {
try {
boolean invalidOperation = true;
if (invalidOperation) {
throw new InvalidOperationException("Invalid operation performed.");
}
} catch (InvalidOperationException e) {
System.out.println("Caught: " + e.getMessage());
}
}
}

35.

public class SecurityExceptionDemo {


public static void main(String[] args) {
try {
System.setSecurityManager(new SecurityManager());
System.getSecurityManager().checkRead("file.txt");
} catch (SecurityException e) {
System.out.println("SecurityException caught: " + e.getMessage());
}
}
}

192
36.

class DatabaseConnectionException extends Exception {


public DatabaseConnectionException(String message) {
super(message);
}
}

public class DatabaseConnectionExceptionDemo {


public static void main(String[] args) {
try {
boolean databaseConnected = false;
if (!databaseConnected) {
throw new DatabaseConnectionException("Failed to connect to the
database.");
}
} catch (DatabaseConnectionException e) {
System.out.println("Caught: " + e.getMessage());
}
}
}

37.

public class InterruptedExceptionMultiThreadingDemo {


public static void main(String[] args) {
Thread thread = new Thread(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("InterruptedException caught in thread: " + e
.getMessage());
}
});

thread.start();
thread.interrupt();
}
}

38.

class FileUploadException extends Exception {


public FileUploadException(String message) {
super(message);
}
}

193
public class FileUploadExceptionDemo {
public static void main(String[] args) {
try {
boolean uploadSuccessful = false;
if (!uploadSuccessful) {
throw new FileUploadException("File upload failed.");
}
} catch (FileUploadException e) {
System.out.println("Caught: " + e.getMessage());
}
}
}

39.

public class ReflectiveOperationExceptionDemo {


public static void main(String[] args) {
try {
Class<?> cls = Class.forName("java.lang.String");
Object instance = cls.getDeclaredConstructor().newInstance();
} catch (ReflectiveOperationException e) {
System.out.println("ReflectiveOperationException caught: " + e.
getMessage());
}
}
}

40.

class InvalidFormatException extends Exception {


public InvalidFormatException(String message) {
super(message);
}
}

public class InvalidFormatExceptionDemo {


public static void main(String[] args) {
try {
String data = "invalid_data";
if (!data.matches("\\d+")) {
throw new InvalidFormatException("Invalid format.");
}
} catch (InvalidFormatException e) {
System.out.println("Caught: " + e.getMessage());
}
}
}

194

You might also like