Java Programming Exercises and Solutions
Java Programming Exercises and Solutions
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.
3. Book Structure
Each chapter in this book is carefully crafted to cover specific Java topics, presenting:
5. Additional Resources
For further assistance and discussion:
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. Data Type: Specifies what kind of data the variable will store (e.g., int, double, String).
• Arrays
• Objects of classes
4
1.3. Best Practices for Variable Declaration
1.3.1. Naming Conventions:
1.3.2. Initialization:
• Choose the appropriate data type based on the data’s nature and range
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.
8. Create a String array to store the names of the days of the week.
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).
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.
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
Parentheses Exponents (handled by Math.pow() in Java) Multiplication and Division (left to right)
Addition and Subtraction (left to right)
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
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
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.
Data Type Size (bits) Size (bytes) Value Range Typical Usage
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.
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.
5. Write a Java expression to find the remainder of the division of two numbers (modulus).
8. Create a Java expression to calculate the square root of a number using Math.sqrt().
10. Create a Java expression to convert inches to centimeters (1 inch = 2.54 cm).
16. Create a Java expression to calculate the volume of a sphere (V = 4/3 * π * r^3).
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.
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
}
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.
Used when you know how many times you want to repeat a block of code:
Used when you want to repeat a block of code while a condition is true:
while (condition) {
// code to repeat
}
Similar to while loop, but ensures the code block is executed at least once:
do {
// code to repeat
} while (condition);
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.
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.
7. Create a nested for loop to print a multiplication table for numbers 1 through 5.
9. Write a continue statement to skip printing even numbers in a loop from 1 to 10.
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.
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.
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.
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.
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};
17
}
Array Length:
Copying Arrays:
Using System.arraycopy():
Using Arrays.copyOf():
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
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.
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.
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.
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.
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.
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.
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).
Methods are called by using the method name followed by parentheses containing any required
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.
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.
6. Create a Java method to find the greatest common divisor (GCD) of two numbers.
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.
16. Create a Java method to find the minimum element in an array of integers.
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.
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.
30. Create a Java method to find the maximum element in an array of doubles.
24
32. Create a Java method to find the mode of an array of integers.
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.
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.
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.
For example:
// 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.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:
28
this.color = color;
}
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.
class Superclass {
// fields
// methods
}
For example:
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:
35
public Animal(String name) {
this.name = name;
}
}
• 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.
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:
40
runtime rather than compile-time. It is the basis for runtime polymorphism:
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.
• 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.
@Override
public void makeSound() {
System.out.println("Dog barks.");
}
}
47
}
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.
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.
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.
import java.io.*;
51
11.1.2. Unchecked Exceptions
Unchecked exceptions are exceptions that are not checked at compile time. These are subclasses of
RuntimeException.
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.
To create a user-defined exception, extend the Exception class or one of its subclasses.
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.
8. Create a custom exception called ProductNotFoundException that is thrown when a product is not
found in a database.
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.
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.
18. Create a custom exception called TimeOutException that is thrown when an operation times out.
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.
24. Create a custom exception called DuplicateEntryException that is thrown when a duplicate entry
is encountered.
26. Create a custom exception called OperationFailedException that is thrown when an operation
fails to complete successfully.
28. Create a custom exception called ConfigurationException that is thrown when there is a
configuration error.
30. Create a custom exception called TransactionFailedException that is thrown when a transaction
fails.
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.
36. Create a custom exception called DatabaseConnectionException that is thrown when a database
connection fails.
38. Create a custom exception called FileUploadException that is thrown when a file upload fails.
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.
2.
3.
4.
5.
6.
7.
8.
9.
55
float price = 19.99f;
10.
11.
byte childAge = 5;
12.
13.
14.
15.
16.
17.
18.
19.
56
float temperature = 36.5f;
20.
2.
3.
4.
5.
6.
7.
8.
57
double squareRoot = Math.sqrt(num);
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
58
int max = Math.max(num1, Math.max(num2, num3));
19.
20.
if (number > 0) {
System.out.println("Positive");
} else if (number < 0) {
System.out.println("Negative");
} else {
System.out.println("Zero");
}
2.
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.
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.
9.
10.
11.
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.
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.
19.
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.
22.
23.
64
} else {
System.out.println(year + " is not a leap year");
}
24.
25.
26.
27.
int count = 0;
for (char c : str.toCharArray()) {
if (c == targetChar) {
count++;
}
}
System.out.println("Occurrences of " + targetChar + ": " + count);
28.
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.
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.
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.
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.
2.
int sum = 0;
for (int num : numbers) {
sum += num;
69
}
System.out.println("Sum: " + sum);
3.
4.
5.
6.
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.
11.
71
int[] result = Arrays.copyOf(unique, size);
System.out.println("Array without duplicates: " + Arrays.toString(result));
12.
13.
72
int[] result = Arrays.copyOf(union, size);
System.out.println("Union: " + Arrays.toString(result));
14.
15.
16.
17.
73
boolean contains = false;
for (int num : numbers) {
if (num == target) {
contains = true;
break;
}
}
System.out.println("Contains " + target + ": " + contains);
18.
19.
20.
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.
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.
26.
27.
28.
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.
30.
31.
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.
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.
40.
2.
80
public static int factorial(int n) {
int result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}
3.
4.
5.
6.
81
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
7.
8.
9.
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.
12.
13.
14.
83
15.
16.
17.
18.
84
}
return merged;
}
19.
20.
21.
22.
23.
85
public static int difference(int a, int b) {
return a - b;
}
24.
25.
26.
27.
28.
29.
86
30.
31.
32.
33.
87
}
34.
35.
36.
37.
38.
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.
40.
89
}
2.
3.
4.
90
this.radius = radius;
}
5.
6.
91
private double[] grades;
7.
8.
92
this.age = age;
}
9.
10.
11.
93
public class Point {
private double x;
private double y;
12.
13.
94
}
14.
15.
16.
95
public class Phone {
private String brand;
private String model;
private double price;
17.
18.
96
public void displayDetails() {
System.out.println("Name: " + name + ", Population: " + population + ",
Country: " + country);
}
}
19.
20.
21.
97
private String studentId;
private String name;
private String major;
22.
23.
98
System.out.println("Product ID: " + productId + ", Name: " + name + ", Price:
" + price);
}
}
24.
import java.util.ArrayList;
import java.util.List;
25.
import java.util.ArrayList;
import java.util.List;
99
}
26.
import java.util.ArrayList;
import java.util.List;
27.
100
public void displayDetails() {
System.out.println("Course Name: " + courseName + ", Course Code: " +
courseCode + ", Credits: " + credits);
}
}
28.
import java.util.ArrayList;
import java.util.List;
29.
import java.util.ArrayList;
import java.util.List;
101
public void addDoctor(String doctor) {
doctors.add(doctor);
}
30.
import java.util.ArrayList;
import java.util.List;
31.
102
this.day = day;
this.time = time;
this.activity = activity;
}
32.
import java.util.ArrayList;
import java.util.List;
33.
103
}
34.
35.
import java.util.ArrayList;
import java.util.List;
104
System.out.println("Borrowed Book: " + book);
}
}
}
36.
import java.util.ArrayList;
import java.util.List;
37.
105
}
38.
import java.util.ArrayList;
import java.util.List;
39.
106
}
40.
import java.util.ArrayList;
import java.util.List;
41.
import java.util.ArrayList;
import java.util.List;
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;
43.
import java.util.ArrayList;
import java.util.List;
108
public void addFacility(String facility) {
facilities.add(facility);
}
44.
import java.util.ArrayList;
import java.util.List;
45.
import java.util.ArrayList;
import java.util.List;
109
public Concert(String concertName, String date) {
this.concertName = concertName;
this.date = date;
}
46.
import java.util.ArrayList;
import java.util.List;
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<>();
48.
49.
111
public Event(String eventName, String date, String location) {
this.eventName = eventName;
this.date = date;
this.location = location;
}
50.
import java.util.ArrayList;
import java.util.List;
112
public class Car extends Vehicle {
@Override
public void move() {
System.out.println("The car is driving.");
}
}
2.
@Override
public void display() {
System.out.println("Employee ID: " + employeeId);
}
}
3.
@Override
public double area() {
return Math.PI * Math.pow(radius, 2);
}
}
113
private double width;
private double height;
@Override
public double area() {
return width * height;
}
}
4.
5.
114
public void read() {
System.out.println("Reading an electronic book.");
}
}
6.
7.
8.
115
public Member(String name, String memberId) {
this.name = name;
this.memberId = memberId;
}
@Override
public void displayDetails() {
System.out.println("Name: " + name + ", Member ID: " + memberId + ", Course: "
+ course);
}
}
9.
10.
116
public class Gadget {
public void use() {
System.out.println("Using the gadget.");
}
}
11.
12.
@Override
public void playInstrument() {
System.out.println("Playing a " + guitarType + " guitar.");
}
117
}
13.
14.
15.
118
public class Manager extends Employee {
private String department;
@Override
public void displayDetails() {
System.out.println("Name: " + name + ", Salary: " + salary + ", Department: "
+ department);
}
}
16.
17.
119
public void withdraw(double amount) {
if (amount <= balance) {
balance -= amount;
} else {
System.out.println("Insufficient 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.
@Override
public void createArt() {
System.out.println("Creating art with " + medium + ".");
}
}
19.
120
public void start() {
System.out.println("Starting the game.");
}
}
20.
21.
22.
121
}
}
@Override
public void speak() {
System.out.println("The teacher speaks about " + subject + ".");
}
}
23.
24.
122
public void displayDetails() {
System.out.println("Brand: " + brand + ", Processor: " + processor);
}
}
@Override
public void displayDetails() {
System.out.println("Brand: " + brand + ", Processor: " + processor + ",
Battery Life: " + batteryLife + " hours");
}
}
25.
26.
123
public class Designer extends Employee {
@Override
public void work() {
System.out.println("The designer creates designs.");
}
}
27.
28.
@Override
public void material() {
System.out.println("The chair is made of " + type + ".");
}
}
29.
124
public void function() {
System.out.println("The appliance performs a function.");
}
}
30.
31.
125
return balance * interestRate / 100;
}
}
32.
33.
34.
126
public class Skyscraper extends Building {
@Override
public void build() {
System.out.println("Building a skyscraper.");
}
}
35.
36.
127
super(name, department);
this.duration = duration;
}
@Override
public void displayDetails() {
System.out.println("Name: " + name + ", Department: " + department + ",
Internship Duration: " + duration + " months");
}
}
37.
@Override
public void displayDetails() {
System.out.println("Product ID: " + productId + ", Price: " + price + ",
Warranty: " + warranty + " years");
}
}
38.
128
public class Student extends Person {
@Override
public void introduce() {
System.out.println("Introducing a student.");
}
}
39.
40.
@Override
public void create() {
System.out.println("Creating a sculpture with " + material + ".");
}
129
}
41.
42.
43.
130
public class Janitor extends Employee {
private String shift;
@Override
public void performDuties() {
System.out.println("The janitor performs duties during the " + shift + "
shift.");
}
}
44.
45.
131
}
46.
@Override
public void displayDetails() {
System.out.println("Name: " + name + ", Age: " + age + ", Sport: " + sport);
}
}
47.
132
public void assemble() {
System.out.println("Assembling the shelf.");
}
}
48.
49.
@Override
public void design() {
System.out.println("Designing the museum with " + exhibitCount + "
exhibits.");
}
}
50.
133
}
}
2.
134
@Override
public void makePayment() {
System.out.println("Payment made with credit card.");
}
}
3.
4.
135
@Override
public void play() {
System.out.println("Playing the drum.");
}
}
5.
6.
@Override
public double area() {
return 0.5 * base * height;
}
136
}
@Override
public double area() {
return width * height;
}
}
7.
8.
137
}
}
9.
10.
138
}
}
11.
12.
13.
139
public abstract class Food {
public abstract void eat();
}
14.
15.
140
public class Manager extends Employee {
@Override
public double calculateSalary() {
return 6000;
}
}
16.
17.
141
public class Helicopter extends Flyable {
@Override
public void fly() {
System.out.println("Helicopter is flying.");
}
}
18.
19.
142
20.
2.
143
public void takeOff() {
// Default implementation
}
@Override
public void land() {
System.out.println("Airplane is landing.");
}
}
@Override
public void land() {
System.out.println("Helicopter is landing.");
}
}
3.
144
}
}
4.
5.
6.
145
public class Drawable {
public void draw() {
// Default implementation
}
}
7.
@Override
public double area() {
return width * height;
}
}
146
@Override
public double area() {
return 0.5 * base * height;
}
}
8.
@Override
public void discharge() {
System.out.println("Battery is discharging.");
}
}
@Override
public void discharge() {
System.out.println("Capacitor is discharging.");
}
}
9.
147
public class PDFDocument extends Document {
@Override
public void print() {
System.out.println("Printing PDF document.");
}
}
10.
@Override
public void load() {
System.out.println("Loading from database.");
}
}
@Override
public void load() {
System.out.println("Loading from file storage.");
}
}
148
11.
12.
@Override
public void stop() {
System.out.println("Engine is stopping.");
}
}
149
@Override
public void stop() {
System.out.println("Fan is stopping.");
}
}
13.
14.
150
15.
16.
17.
151
public class Lion extends Animal {
@Override
public void makeSound() {
System.out.println("Lion roars.");
}
}
18.
19.
152
public class Train extends Transport {
@Override
public void move() {
System.out.println("Train is moving.");
}
}
20.
@Override
public void pause() {
System.out.println("Music is paused.");
}
153
}
@Override
public void pause() {
System.out.println("Video is paused.");
}
}
2.
@Override
public double calculateArea() {
return Math.PI * radius * radius;
}
}
@Override
public double calculateArea() {
return side * side;
}
}
3.
154
void moveForward();
void moveBackward();
}
@Override
public void moveBackward() {
System.out.println("Robot moves backward.");
}
}
@Override
public void moveBackward() {
System.out.println("Car moves backward.");
}
}
4.
5.
155
public interface Resizable {
void resizeUp();
void resizeDown();
}
@Override
public void resizeDown() {
System.out.println("Window is resized down.");
}
}
@Override
public void resizeDown() {
System.out.println("Image is resized down.");
}
}
6.
156
7.
@Override
public void stop() {
System.out.println("Machine is stopping.");
}
}
@Override
public void stop() {
System.out.println("Engine is stopping.");
}
}
8.
@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.
@Override
public void discharge() {
System.out.println("Discharging battery.");
}
}
@Override
public void discharge() {
System.out.println("Discharging electric car.");
}
}
10.
158
public class EmailService implements Notifiable {
@Override
public void sendNotification() {
System.out.println("Sending email notification.");
}
}
11.
@Override
public void land() {
System.out.println("Bird is landing.");
}
}
@Override
public void land() {
System.out.println("Airplane is landing.");
}
}
12.
159
void connect();
void disconnect();
}
@Override
public void disconnect() {
System.out.println("Disconnecting from WiFi.");
}
}
@Override
public void disconnect() {
System.out.println("Disconnecting from Bluetooth.");
}
}
13.
14.
160
public interface Repairable {
void repair();
}
15.
16.
161
}
}
17.
18.
162
}
19.
20.
@Override
public void endGame() {
System.out.println("Ending chess game.");
}
}
@Override
public void endGame() {
163
System.out.println("Ending football game.");
}
}
import java.io.*;
import java.sql.*;
// Demonstrating SQLException
try {
Connection conn = DriverManager.getConnection
("jdbc:mysql://localhost/test", "user", "password");
} catch (SQLException e) {
System.out.println("SQLException caught: " + e.getMessage());
}
}
}
2.
164
System.out.println("Caught: " + e.getMessage());
}
}
}
3.
4.
5.
165
System.out.println("ClassNotFoundException caught: " + e.getMessage());
}
}
}
6.
try {
if (withdrawAmount > balance) {
throw new InsufficientFundsException("Insufficient funds for
withdrawal.");
}
} catch (InsufficientFundsException e) {
System.out.println("Caught: " + e.getMessage());
}
}
}
7.
8.
166
}
}
try {
if (product == null) {
throw new ProductNotFoundException("Product with ID " + productId + "
not found.");
}
} catch (ProductNotFoundException e) {
System.out.println("Caught: " + e.getMessage());
}
}
}
9.
thread.start();
thread.interrupt();
}
}
10.
try {
167
if (!hasAccess) {
throw new UnauthorizedAccessException("User does not have access.");
}
} catch (UnauthorizedAccessException e) {
System.out.println("Caught: " + e.getMessage());
}
}
}
11.
12.
13.
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.
try {
if (stock == 0) {
throw new OutOfStockException("Item is out of stock.");
}
} catch (OutOfStockException e) {
System.out.println("Caught: " + e.getMessage());
}
}
}
15.
16.
169
class PermissionDeniedException extends Exception {
public PermissionDeniedException(String message) {
super(message);
}
}
try {
if (!hasPermission) {
throw new PermissionDeniedException("Permission denied.");
}
} catch (PermissionDeniedException e) {
System.out.println("Caught: " + e.getMessage());
}
}
}
17.
import java.io.*;
18.
try {
if (operationTimedOut) {
170
throw new TimeOutException("Operation timed out.");
}
} catch (TimeOutException e) {
System.out.println("Caught: " + e.getMessage());
}
}
}
19.
20.
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.
23.
24.
172
class DuplicateEntryException extends Exception {
public DuplicateEntryException(String message) {
super(message);
}
}
25.
26.
173
boolean operationSuccessful = false;
if (!operationSuccessful) {
throw new OperationFailedException("Operation failed to complete
successfully.");
}
} catch (OperationFailedException e) {
System.out.println("Caught: " + e.getMessage());
}
}
}
27.
28.
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.
31.
import java.util.*;
175
32.
try {
if (withdrawAmount > balance) {
throw new InsufficientBalanceException("Insufficient balance.");
}
} catch (InsufficientBalanceException e) {
System.out.println("Caught: " + e.getMessage());
}
}
}
33.
import java.io.*;
34.
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.
36.
177
37.
thread.start();
thread.interrupt();
}
}
38.
39.
178
getMessage());
}
}
}
40.
import java.io.*;
import java.sql.*;
// 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.
3.
4.
180
}
5.
6.
try {
if (withdrawAmount > balance) {
throw new InsufficientFundsException("Insufficient funds for
withdrawal.");
}
} catch (InsufficientFundsException e) {
System.out.println("Caught: " + e.getMessage());
}
}
181
}
7.
8.
try {
if (product == null) {
throw new ProductNotFoundException("Product with ID " + productId + "
not found.");
}
} catch (ProductNotFoundException e) {
System.out.println("Caught: " + e.getMessage());
}
}
}
9.
182
System.out.println("InterruptedException caught: " + e.getMessage());
}
});
thread.start();
thread.interrupt();
}
}
10.
try {
if (!hasAccess) {
throw new UnauthorizedAccessException("User does not have access.");
}
} catch (UnauthorizedAccessException e) {
System.out.println("Caught: " + e.getMessage());
}
}
}
11.
12.
183
super(message);
}
}
13.
14.
try {
if (stock == 0) {
throw new OutOfStockException("Item is out of stock.");
}
} catch (OutOfStockException e) {
184
System.out.println("Caught: " + e.getMessage());
}
}
}
15.
16.
try {
if (!hasPermission) {
throw new PermissionDeniedException("Permission denied.");
}
} catch (PermissionDeniedException e) {
System.out.println("Caught: " + e.getMessage());
}
}
}
17.
import java.io.*;
185
FileInputStream file = new FileInputStream("nonexistentfile.txt");
} catch (FileNotFoundException e) {
System.out.println("FileNotFoundException caught: " + e.getMessage());
}
}
}
18.
try {
if (operationTimedOut) {
throw new TimeOutException("Operation timed out.");
}
} catch (TimeOutException e) {
System.out.println("Caught: " + e.getMessage());
}
}
}
19.
20.
186
super(message);
}
}
21.
import java.util.*;
22.
187
}
}
}
23.
24.
25.
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.
27.
28.
189
class ConfigurationException extends Exception {
public ConfigurationException(String message) {
super(message);
}
}
29.
30.
190
System.out.println("Caught: " + e.getMessage());
}
}
}
31.
import java.util.*;
32.
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.
35.
192
36.
37.
thread.start();
thread.interrupt();
}
}
38.
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.
40.
194