Professional Documents
Culture Documents
OOP Lab Manual Fetiya Kedir
OOP Lab Manual Fetiya Kedir
Institute of Technology
September 2023
Werabe University
Werabe, Ethiopia
The Lab Manual Submitted By: Fetiya Kedir (BSc)
I want to begin by expressing my gratitude to Almighty Allah for His guidance and blessings
throughout this endeavour. I extend my heartfelt thanks to the Department head of Information
Systems at Werabe University for their invaluable support and mentorship. I am also grateful to
the Institute of Technology at Werabe University for providing the necessary resources and
environment for this project. To my colleagues and my dear family and friends, your contributions
and encouragement have been deeply appreciated. Thank you all for your vital roles in the success
of this project.
The manual begins with an introduction to Java's rich history, tracing its evolution from inception
to its current prominence in the software industry. This initial context sets the stage for students to
appreciate the significance of Java in modern programming.
Next, students are introduced to various Integrated Development Environments (IDEs) suitable for
Java development. A step-by-step guide empowers them to choose, install, and configure an IDE,
laying the foundation for their coding journey.
With the tools in place, students delve into the fundamental aspects of Java syntax, data types, and
variables. They acquire the skills to declare variables, manipulate data, and craft basic programs.
The manual then explores control structures, allowing students to grasp the essential concepts of
conditional statements and loops. These constructs are pivotal for controlling program flow and
implementing logic in their code.
Transitioning to the core of the course, students delve into object-oriented programming concepts.
They learn about classes, objects, constructors, inheritance, polymorphism, and encapsulation.
These principles form the bedrock of modern software development and empower students to
design robust and extensible programs.
Furthermore, the manual equips students with the ability to handle exceptions gracefully.
Exception handling is a critical skill that ensures the reliability and stability of their Java
applications.
In addition to these foundational topics, the manual introduces students to Java's Collections
Framework. They gain proficiency in working with arrays, lists, maps, and sets, which are essential
data structures for managing and manipulating data in their programs.
Overall, this lab manual is designed to provide students with a solid grounding in Java
programming and object-oriented concepts. It equips them with the knowledge and skills needed
to build Java applications and lays the groundwork for more advanced topics in subsequent
chapters of the course.
The primary objective of this chapter is to introduce students to the world of Java programming.
They will gain a foundational understanding of Java's history, its significance in the software
industry, and the fundamental concepts that underpin the language.
Key Topics:
Java's Origins: Explore the history and origin of the Java programming language, including its
development by Sun Microsystems and its evolution into one of the most widely used
programming languages today.
Java's Cross-Platform Nature: Understand Java's unique feature of "write once, run anywhere"
and how it achieves platform independence through the Java Virtual Machine (JVM).
Key Features of Java: Highlight key features that set Java apart, such as its strong typing, object-
oriented nature, and extensive standard library.
Setting Up Your Development Environment: Briefly touch upon the importance of choosing an
appropriate Integrated Development Environment (IDE) and guide students on setting up their
development environment for Java programming.
As the name suggests, Object-Oriented Programming or OOPs refers to languages that use
objects in programming, they use objects as a primary source to implement what is to happen in
the code. Objects are seen by the viewer or user, performing tasks assigned by you. Object-oriented
programming aims to implement real-world entities like inheritance, hiding, polymorphism etc. in
programming. The main aim of OOP is to bind together the data and the functions that operate on
them so that no other part of the code can access this data except that function.
Introduction to Java
Platform Independence: Java achieves platform independence through the Java Virtual
Machine (JVM). Java source code is compiled into bytecode, which is executed by the
JVM. As long as a JVM is available for a particular platform, Java programs can run on it
without modification, adhering to the "write once, run anywhere" principle.
Code Editor: IDEs include a code editor with syntax highlighting and code formatting
capabilities, making it easier for developers to write and edit code with proper indentation
and color-coded keywords.
Let us create a step-by-step guide for setting up the NetBeans Integrated Development
Environment (IDE) for Java programming. This guide will include detailed instructions from
installation to creating your first Java project.
Write your Java code in this class. For example, you can use System.out.println("Hello,
World!"); for a simple "Hello World" program.
5. View Output: The program's output will be displayed in the "Output" pane at the bottom of the
NetBeans window.
Congratulations! You have successfully set up NetBeans for Java programming and created
your first Java project. You can now continue to develop Java applications using NetBeans IDE.
In Chapter 1, we took our first steps into the world of Java, exploring its history, significance, and
the essential tools needed to write Java code. Now, in Chapter 2, we dive deeper into the core of
Java programming. Here, we will unravel the syntax that underlies all Java programs, introduce
you to the various data types available in Java, and show you how to declare and use variables to
store and manipulate data.
The student will learn the fundamental building blocks of Java programming.
The Student will gain an understanding of Java syntax, data types, and how to declare and
use variables.
Identify different data types and how to apply them to the given problems.
Students should be able to know different operators used for problem-solving techniques.
Introduction
In the world of programming, understanding the language you are working with is akin to
knowing the grammar and vocabulary of a foreign land. Just as you cannot construct meaningful
sentences without words and grammar, you cannot create functional software without mastering
the syntax, data types, and variables of a programming language.
Why This Chapter Matters: Before you can create complex applications or solve real-
world problems with Java, you need to become proficient in its foundational elements. This chapter
will empower you with the essential knowledge and skills required to write Java code effectively.
By the end of this chapter, you will have the tools you need to start creating your Java programs.
By the end of this chapter, you will possess the skills and confidence needed to write well-
structured Java code, declare and utilize variables effectively, and understand the data types that
Java offers. These skills are not only foundational but also essential for the journey ahead as you
continue to explore the world of Object-Oriented Programming in Java.
A "Hello, World!" is a simple program that outputs Hello, World! On the screen. Since
it's a very simple program, it's often used to introduce a new programming language to a newbie.
Let's explore how Java "Hello, World!" program works.
/* */ and //
In Java, any line starting with // and /* */ is a comment. Comments are intended for users reading
the code to understand the intent and functionality of the program. It is completely ignored by the
Java compiler (an application that translates Java program to Java bytecode that computer can
execute).
In Java, every application begins with a class definition. In the program, HelloWorld is the name
of the class, and the class definition is the same. For now, just remember that every Java application
has a class definition, and the name of the class should match the filename in Java.
This is the main method. Every application in Java must contain the main method. The Java
compiler starts executing the code from the main method.
A variable is a location in memory (storage area) to hold data. To indicate the storage area, each
variable should be given a unique name (identifier).
Here, speedLimit is a variable of int data type and we have assigned value 80 to it. The int data
type suggests that the variable can only hold integers. In the example, we have assigned value to
the variable during declaration. However, it's not mandatory. You can declare variables and assign
variables separately. For example,
Note: Java is a statically-typed language. It means that all variables must be declared before they
can be used.
However, we cannot change the data type of a variable in Java within the same scope.
Java programming language has its own set of rules and conventions for naming variables. Here's
what you need to know:
Java is case sensitive. Hence, age and AGE are two different variables. For example,
Variables must start with either a letter or an underscore, _ or a dollar, $ sign. For example,
int a = 1;
float b = 2.5;
1. Boolean Literals
In Java, boolean literals are used to initialize boolean data types. They can store two values: true
and false. For example,
binary (base 2)
decimal (base 10)
octal (base 8)
hexadecimal (base 16)For example:
// binary
int binaryNumber = 0b10010;
// octal
int octalNumber = 027;
// decimal
int decNumber = 34;
// hexadecimal
int hexNumber = 0x2F; // 0x represents hexadecimal
// binary
int binNumber = 0b10010; // 0b represents binary
Note: Integer literals are used to initialize variables of integer types like byte, short, int, and long.
3. Floating-point Literals: A floating-point literal is a numeric literal that has either a fractional
form or an exponential form. For example,
class Main {
public static void main(String[] args) {
// 3.445*10^2
double myDoubleScientific = 3.445e2;
Note: The floating-point literals are used to initialize float and double type variables.
4. Character Literals: Character literals are unicode character enclosed inside single quotes. For
example,
Here, Java Programming and OOP Programing are two string literals.
int score;
Here, int is a keyword. It indicates that the variable score is of integer type (32-bit signed two's
complement integer).
You cannot use keywords like int, for, class, etc as variable name (or identifiers) as they are part
of the Java programming language syntax.
Beside these keywords, you cannot also use true, false and null as identifiers. It is because they
are literals.
Java identifiers
Identifiers are the name given to variables, classes, methods, etc. Consider the above code;
int score;
Here, score is a variable (an identifier). You cannot use keywords as variable names. It's because
keywords have predefined meanings. For example,
int float;
The above code is wrong. It's because float is a keyword and cannot be used as a variable name.
Here are some valid identifiers: Here are some invalid identifiers:
score class
level float
highestScore 1number
number1 highest Score
convertToString @pple
int speed;
Note: In addition to primitive data types, there are also referenced types (object type).
1. boolean type
The boolean data type has two possible values, either true or false.
Default value: false.
They are usually used for true/false conditions.
2. byte type
The byte data type can have values from -128 to 127 (8-bit signed two's complement
integer).
If it's certain that the value of a variable will be within -128 to 127, then it is used instead
of int to save memory.
Default value: 0
Example 2: Java byte data type
Public class ByteExample {
public static void main(String[] args) {
byte range;
range = 124;
System.out.println(range); // prints 124
}
}
3. short type
The short data type in Java can have values from -32768 to 32767 (16-bit signed two's
complement integer).
If it's certain that the value of a variable will be within -32768 and 32767, then it is used
instead of other integer data types (int, long).
Default value: 0
Example 3: Java short data type
4. int type
The int data type can have values from -231 to 231-1 (32-bit signed two's complement
integer).
If you are using Java 8 or later, you can use an unsigned 32-bit integer. This will have a
minimum value of 0 and a maximum value of 232-1.
Default value: 0
Example 4: Java int data type
Public class IntExample {
public static void main(String[] args) {
5. long type
The long data type can have values from -263 to 263-1 (64-bit signed two's complement
integer).
If you are using Java 8 or later, you can use an unsigned 64-bit integer with a minimum
value of 0 and a maximum value of 264-1.
Default value: 0
Example 5: Java long data type
7. float type
The float data type is a single-precision 32-bit floating-point. Learn more about single-
precision and double-precision floating-point if you are interested.
It should never be used for precise values such as currency.
Default value: 0.0 (0.0f)
Example 7: Java float data type
Public class FloatExample {
public static void main(String[] args) {
Operators are symbols that perform operations on variables and values. For example, + is an
operator used for addition, while * is also an operator used for multiplication.
Operators in Java can be classified into 5 types:
Arithmetic Operators
Assignment Operators
Relational Operators
Logical Operators
Unary Operators
Bitwise Operators
1. Java Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations on variables and data. For example,
Example 1: Arithmetic Operators
// declare variables
int a = 12, b = 5;
// addition operator
System.out.println("a + b = " + (a + b));
// subtraction operator
System.out.println("a - b = " + (a - b));
// multiplication operator
System.out.println("a * b = " + (a * b));
// division operator
System.out.println("a / b = " + (a / b));
// modulo operator
System.out.println("a % b = " + (a % b));
}
}
Output
a + b = 17
a-b=7
a * b = 60
a/b=2
a%b=2
Assignment operators are used in Java to assign values to variables. For example,
int age;
age = 5;
// create variables
int a = 4;
int var;
Output
var using =: 4
var using +=: 8
var using *=: 32
Here, < operator is the relational operator. It checks if a is less than b or not.
// create variables
int a = 7, b = 11;
// value of a and b
System.out.println("a is " + a + " and b is " + b);
// == operator
System.out.println(a == b); // false
// != operator
System.out.println(a != b); // true
// > operator
System.out.println(a > b); // false
// < operator
System.out.println(a < b); // true
// >= operator
System.out.println(a >= b); // false
// <= operator
System.out.println(a <= b); // true
}
}
// && operator
System.out.println((5 > 3) && (8 > 5)); // true
System.out.println((5 > 3) && (8 < 5)); // false
// || operator
System.out.println((5 < 3) || (8 > 5)); // true
System.out.println((5 > 3) || (8 < 5)); // true
System.out.println((5 < 3) || (8 < 5)); // false
// ! operator
System.out.println(!(5 == 3)); // true
System.out.println(!(5 > 3)); // false
}
}
int num = 5;
// increase num by 1
++num;
Here, the value of num gets increased to 6 from its initial value of 5.
Example 5: Increment and Decrement Operators
// declare variables
int a = 12, b = 12;
int result1, result2;
// original value
System.out.println("Value of a: " + a);
// increment operator
result1 = ++a;
System.out.println("After increment: " + result1);
// decrement operator
result2 = --b;
System.out.println("After decrement: " + result2);
}
}
Output
Value of a: 12
After increment: 13
Value of b: 12
After decrement: 11
~ 00100011
________
11011100 = 220 (In decimal)
Java Basic Input and Output (I/O) involves reading data from standard input (e.g., keyboard) and
writing data to standard output (e.g., screen/console). Here, we'll cover some fundamental concepts
and examples related to Java I/O.
To read input from the user, you can use the Scanner class from the java.util package. Here's an
example:
import java.util.Scanner;
Output
You can display output on the console using System.out.println() or System.out.print(). For
example:
Output
Hello, World!
The answer is: 42
Java Comments
In computer programming, comments are a portion of the program that are completely ignored by
Java compilers. They are mainly used to help programmers to understand the code. For example,
Exercises
1. Write a Java program that prints your name to the console.
2. Add single-line and multi-line comments to your program to explain what each part of the
code does.
Your age
Your height (in meters)
The number of siblings you have
Your favorite color (as a string)
4. Calculate the area of a rectangle using the formula area = length * width. Declare variables for
length and width, and then calculate and print the area.
5. Create a program that calculates the average of three exam scores. Declare three variables for
the scores, calculate the average as a double, and print it to the console.
6. Declare a constant named PI and assign the value 3.14159 to it. Then, use it to calculate and
print the circumference of a circle with a given radius.
Hello, World!
I am learning Java.
8. Declare two variables, x and y, and initialize them with integer values. Swap the values of x
and y without using a third variable and print the values before and after the swap.
Objective: In this chapter, you will explore how to control the flow of your Java programs using
conditional statements and loops. Additionally, you will learn about arrays, a fundamental data
structure for handling collections of data.
Conditional Statements
Definition: Conditional statements allow you to make decisions in your Java programs by
executing different code blocks based on specified conditions.
class IfStatement {
public static void main(String[] args) {
The if statement executes a certain section of code if the test expression is evaluated to true.
However, if the test expression is evaluated to false, it does nothing.
In this case, we can use an optional else block. Statements inside the body of else block are
executed if the test expression is evaluated to false. This is known as the if-...else statement in
Java.
class IfElse {
public static void main(String[] args) {
int number = 10;
In Java, we have an if...else...if ladder, that can be used to execute one block of code among
multiple other blocks.
Example 4: Java if...else...if Statement
class IfElseIf {
public static void main(String[] args) {
int number = 0;
Outputs
The number is 0.
In Java, it is also possible to use if..else statements inside an if...else statement. It's called the
nested if...else statement. Here's a program to find the largest of 3 numbers using the nested
if...else statement.
Example 5: Nested if...else Statement
class NestedIf {
public static void main(String[] args) {
else {
largest = n3;
}
} else {
else {
largest = n3;
}
}
The switch statement provides a way to select one of many code blocks to be executed based on
the value of a single expression. The switch statement allows us to execute a block of code
among many alternatives.
Example: Java switch Statement
class SwicthStatement {
public static void main(String[] args) {
case 29:
size = "Small";
break;
case 42:
size = "Medium";
break;
case 48:
size = "Extra Large";
break;
default:
size = "Unknown";
break;
Output
Size: Large
Notice that we have been using break in each case block. The break statement is used to terminate
the switch-case statement. If break is not used, all the cases after the matching case are also
executed.
Java for Loop
In computer programming, loops are used to repeat a block of code. For example, if you want to
show a message 100 times, then rather than typing the same code 100 times, you can use a loop.
for loop
while loop
do...while loop
Java for loop is used to run a block of code for a certain number of times. The syntax
of for loop is:
class Main {
public static void main(String[] args) {
int n = 5;
// for loop
for (int i = 1; i <= n; ++i) {
System.out.println("Java is fun");
}
}
}
Output
Java is fun
Java is fun
Java is fun
Java is fun
Java is fun
class Main {
public static void main(String[] args) {
int n = 5;
// for loop
for (int i = 1; i <= n; ++i) {
System.out.println(i);
}
}
}
Output
In computer programming, loops are used to repeat a block of code. For example, if you want to
show a message 100 times, then you can use a loop. It's just a simple example; you can achieve
much more with loops.
Java while loop is used to run a specific code until a certain condition is met. The syntax of the
while loop is:
while (testExpression) {
// body of loop
}
class Main {
public static void main(String[] args) {
int sum = 0;
System.out.println("Enter a number");
number = input.nextInt();
}
Output
Enter a number
25
Enter a number
9
Enter a number
5
Enter a number
-3
Sum = 39
The do...while loop is similar to while loop. However, the body of do...while loop is executed once
before the test expression is checked. For example,
do {
// body of loop
} while(textExpression);
int factorial = 1;
int i = 1;
do {
factorial *= i;
i++;
} while (i <= number);
Output:
import java.util.Scanner;
do {
System.out.print("Enter the password: ");
enteredPassword = scanner.next();
Output
Jumping statements are control statements that transfer execution control from one point to
another point in the program. There are two Jump statements that are provided in the Java
programming language:
Break statement.
Continue statement.
While working with loops, it is sometimes desirable to skip some statements inside the loop or
terminate the loop immediately without checking the test expression. In such cases, break and
continue statements are used.
// for loop
for (int i = 1; i <= 10; ++i) {
1
2
3
4
The program below calculates the sum of numbers entered by the user until user enters a
negative number. To take input from the user, we have used the Scanner object.
import java.util.Scanner;
while (true) {
System.out.print("Enter a number: ");
sum += number;
}
System.out.println("Sum = " + sum);
}
}
Output:
While working with loops, sometimes you might want to skip some statements or terminate the
loop. In such cases, break and continue statements are used. The continue statement skips the
current iteration of a loop (for, while, do...while, etc). After the continue statement, the program
moves to the end of the loop. And, test expression is evaluated (update statement is evaluated in
case of the for loop).
// for loop
for (int i = 1; i <= 10; ++i) {
1
2
3
4
9
10
import java.util.Scanner;
// if number is negative
// continue statement is executed
if (number <= 0.0) {
continue;
}
sum += number;
}
System.out.println("Sum = " + sum);
input.close();
}
}
Java Arrays
An array is a collection of similar types of data. For example, if we want to store the names of
100 people then we can create an array of the string type that can store 100 names.
Here, the above array cannot store more than 100 names. The number of values in a Java array is
always fixed.
dataType[] arrayName;
dataType - it can be primitive data types like int, char, double, byte, etc. or Java objects
arrayName - it is an identifier. For example,
double[] data;
class Main {
public static void main(String[] args) {
// create an array
int[] age = {12, 4, 5, 2, 5};
Output
class Main {
public static void main(String[] args) {
// create an array
int[] age = {12, 4, 5};
class Main {
public static void main(String[] args) {
Output:
Multidimensional Arrays
Arrays we have mentioned till now are called one-dimensional arrays. However, we can declare
multidimensional arrays in Java. A multidimensional array is an array of arrays. That is, each
element of a multidimensional array is an array itself.
int[][] a = {
{1, -2, 3},
{-4, -5, 6, 9},
{7},
};
for (int i = 0; i < a.length; ++i) {
for(int j = 0; j < a[i].length; ++j) {
System.out.println(a[i][j]);
}
}
}
}
Output:
1
-2
3
-4
-5
6
9
7
2. Create a number guessing game. Generate a random number between 1 and 100. Allow the user
to guess the number. Use a while loop to keep the game going until the user correctly guesses the
number. Provide hints like "too high" or "too low."
3. Write a program that takes an integer as input from the user and prints its multiplication table
from 1 to 10 using a for loop.
4. Write a Java program that calculates and displays the sum of even numbers from 1 to 100 using
a while loop.
5. Build a menu-driven calculator program using a while loop. The menu should include options
for addition, subtraction, multiplication, division, and exit. Continuously prompt the user for their
choice and perform the selected operation until they choose to exit
6. Write a Java program that uses the continue statement to skip the iteration of a loop for specific
values.
7. Write a Java program that uses the break statement to exit a loop when a specific condition is
met.
8. Create an array of integers and find both the maximum and minimum values within the array.
Display both values.
9. Implement a program that takes an array of integers and reverses the order of its elements.
Display the reversed array.
10. Write a program that performs matrix operations using 2D arrays. Allow the user to input
two matrices and perform addition and multiplication operations on them. Display the results.
Classes: In Java, a class is a blueprint or template for creating objects. It defines the
structure and behavior of objects. A class typically contains fields (attributes) to represent
data and methods (behaviors) to perform actions.
Objects: Objects are instances of classes. They represent real-world entities and have their
own state (values of attributes) and behavior (methods). Objects are created based on class
definitions.
Creating Objects: To create an object, you use the new keyword followed by the class
constructor.
Class Members:
Fields (Attributes): Fields are variables declared within a class to store data. They
represent the characteristics or properties of objects. Fields can have various data types,
including primitives and other objects.
Methods (Behaviors): Methods are functions defined within a class to perform specific
actions or operations. Methods are called on objects to manipulate their data or perform
tasks.
Constructors: Constructors are special methods used to initialize objects when they are
created. They have the same name as the class and can have different parameter lists for
various object initializations.
Object-Oriented Concepts:
Constructors: Constructors are special methods used for initializing objects. They have
the same name as the class and are called when objects are created. Constructors can be
overloaded to provide multiple initialization options.
Methods: Methods are functions defined within a class to perform specific tasks or actions.
They encapsulate behavior and can be called on objects.
Method Overloading: Method overloading allows multiple methods with the same name
in a class, differing in the number or types of parameters. This provides flexibility in
method usage.
'this' Keyword: The 'this' keyword refers to the current instance of the class. It is often used
to disambiguate between instance variables and method parameters with the same names.
Output
My Car Information:
Brand: Toyota
Model: Camry
Example 2: Write a Java program that defines a class named Rectangle with fields for length and
width. Create objects of the Rectangle class using both a default constructor and a parameterized
constructor. Calculate and display the area of each rectangle.
Example 3: Write a Java program that defines a class named Calculator with methods for addition
and subtraction. Create an object of the Calculator class, perform addition and subtraction
operations, and display the results.
Output
Addition Result: 8
Subtraction Result: 6
Example 4: Write a Java program that demonstrates the use of the 'this' keyword. Create a class
named Person with fields for name and age. Use 'this' to set the object's name and age. Create two
objects of the Person class, display their information, and highlight the use of 'this'.
System.out.println("\nPerson 2 Information:");
person2.displayInfo();
}
}
Output
Person 1 Information:
Name: Alice
Age: 25
Person 2 Information:
Name: Bob
Age: 30
Encapsulation Example: 5 Write a Java program that demonstrates encapsulation. Create a class
named Student with private fields for name and age. Provide public getter methods to access these
fields. Instantiate a Student object, set its name and age, and then display these values using the
getter methods.
Output
Inheritance Example: 6 Write a Java program that demonstrates inheritance. Create a base class
Animal with a makeSound method. Create two subclasses, Dog and Cat, which override the
makeSound method to produce different sound messages. Instantiate objects of both subclasses
and call the makeSound method on each of them.
Output
Dog barks.
Cat meows.
Polymorphism Example: 7 Write a Java program that demonstrates polymorphism. Create a base
class Shape with an abstract method calculateArea(). Implement two subclasses, Circle and
Rectangle, which provide concrete implementations of calculateArea(). Instantiate objects of both
subclasses and call the calculateArea method on each of them.
Output
Abstraction Example: 8 Write a Java program that demonstrates abstraction. Create an abstract
class Vehicle with an abstract method start(). Implement a concrete subclass Car that provides a
specific implementation of the start method. Instantiate a Car object and call its start method.
Output
Car started.
3. Develop a class StudentGrade to store student names and their corresponding grades. Create
methods to add students and their grades, calculate the average grade, and display the list of
students with their grades.
4. Create a class called Person with private fields for name, age, and address. Provide public
getter and setter methods for each field. Create a Person object, set its information using setter
methods, and display the information using getter methods.
5. Design a class hierarchy for geometric shapes. Create a base class called Shape with methods
to calculate area and perimeter. Create subclasses like Circle, Rectangle, and Triangle that inherit
from Shape and provide implementations for area and perimeter calculations.
6. Create an interface called Drawable with a method draw(). Implement this interface in
multiple classes like Circle, Square, and Triangle, each providing its own draw method to display
a graphical representation of the shape. Create objects of these classes and call their draw
methods.
7. Design a banking system. Create an abstract class BankAccount with fields for account
number and balance. Implement concrete subclasses like SavingsAccount and CheckingAccount
that extend BankAccount and provide methods for deposit, withdrawal, and interest calculation.
8. Create a Library class that can contain multiple Book objects. Implement a Book class with
fields for title, author, and publication year. The Library class should have methods to add books,
remove books, and list all the books in the library.
9. Create an interface called Playable with methods like play(), pause(), and stop(). Implement
this interface in classes representing different media types, such as AudioPlayer, VideoPlayer,
and Game. Demonstrate polymorphism by creating a playlist of different playable objects and
playing them.
10. Design a class hierarchy for vehicles. Create a base class called Vehicle with fields like
make, model, and year. Implement subclasses for specific vehicle types, such as Car, Truck, and
Motorcycle. Include appropriate constructors and methods to display vehicle details.
Learn About Exceptions: Understand what exceptions are and why they are crucial in
Java programming.
Master Exception Handling: Gain proficiency in using try-catch blocks to gracefully
manage exceptions, ensuring that programs continue running smoothly.
Explore Exception Types: Identify and address common exceptions like
ArithmeticException and NullPointerException that occur in real-world applications.
Create Custom Exceptions: Discover how to design and use custom exception classes to
handle unique error scenarios within your Java programs.
Adopt Best Practices: Acquire knowledge of best practices in exception handling,
including providing informative error messages, logging exceptions, and utilizing
exception chaining.
Enhance Application Robustness: Recognize the significance of exception handling in
building robust, reliable Java applications that can withstand unexpected errors.
Master Debugging and Troubleshooting: Develop expertise in using exception
information for effective debugging and troubleshooting, ensuring smoother application
development.
By the end of this chapter, students will possess the skills and knowledge needed to effectively
handle exceptions in Java, leading to the creation of more resilient and reliable software
applications.
Introduction to Exceptions
What are Exceptions?: Exceptions are unexpected or erroneous events that occur during the
execution of a Java program. They can disrupt the normal flow of a program and need to be handled
gracefully.
Types of Exceptions:
Checked Exceptions: These are exceptions that are checked by the compiler. You must either
catch them using try-catch blocks or declare them in the method signature using the throws
keyword.
Unchecked Exceptions (Runtime Exceptions): These are exceptions that do not need to be
explicitly caught or declared. They typically indicate programming errors and can be prevented
through proper coding practices.
Handling Exceptions
try-catch Blocks:
The try block encloses the code that may throw an exception.
The catch block catches and handles the exception, providing error-handling code.
Multiple catch blocks can be used to catch different types of exceptions.
finally Block:
The finally block contains code that is always executed, regardless of whether an exception
occurs. It's often used for resource cleanup.
throw Statement:
The throw statement is used to manually throw an exception. It allows you to create custom
exceptions or rethrow existing ones.
throws Clause:
The throws clause in a method signature declares that the method may throw certain
exceptions. It's used for checked exceptions and specifies that the caller must handle these
exceptions.
Custom Exceptions
Creating Custom Exception Classes: You can create your own custom exception
classes by extending the Exception class or one of its subclasses.
Throwing Custom Exceptions: Custom exceptions are thrown using the throw
statement. They allow you to handle specific error conditions in your application.
Exception handling is a crucial aspect of writing robust and reliable Java programs. It allows you
to gracefully handle errors and exceptions, preventing unexpected program terminations and
providing better user experiences.
Here are examples for each of the common exception types, along with how to handle them
using try-catch blocks:
1. Handling ArithmeticException
Output
Error: / by zero
Output
Error: null
try {
int value = numbers[3]; // This will throw an
ArrayIndexOutOfBoundsException
System.out.println("Value: " + value);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
Output
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class IOExceptionExample {
public static void main(String[] args) {
try {
BufferedReader reader = new BufferedReader(new
FileReader("nonexistent.txt"));
String line = reader.readLine();
System.out.println("Read Line: " + line);
reader.close();
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
Output
Output
Error: / by zero
Finally block executed.
Output
try {
int value = numbers[3]; // This will throw an
ArrayIndexOutOfBoundsException
System.out.println("Value: " + value);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: " + e.getMessage());
} finally {
System.out.println("Finally block executed.");
}
}
}
Output
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
try {
reader = new BufferedReader(new FileReader("nonexistent.txt"));
String line = reader.readLine();
System.out.println("Read Line: " + line);
Output
class BankAccount {
private double balance;
try {
account.deposit(1000);
account.withdraw(500);
account.withdraw(-200); // This will throw a NegativeValueException
} catch (NegativeValueException e) {
System.err.println("Error: " + e.getMessage());
}
Output
In this example:
Exercise
1. Write a program that takes two integers as input and divides them. Handle the case where
division by zero might occur. If an exception is caught, display an error message.
2. Create a program that asks the user to enter a number. Handle the scenario where the user enters
non-numeric input (e.g., a string). If non-numeric input is detected, catch the exception and inform
the user.
3. Write a program that reads the contents of a text file specified by the user. Handle the
FileNotFoundException and display a message if the file does not exist.
4. Create an array of integers and attempt to access an element at an index that is out of bounds.
Handle the ArrayIndexOutOfBoundsException and display an error message.
5. Build a program that converts temperatures from Celsius to Fahrenheit. Allow the user to input
the temperature in Celsius. Handle any input errors, such as non-numeric input, and provide
feedback.
7. Define a custom exception class called InvalidInputException. Create a program that accepts an
integer input. If the input is less than 10, throw an instance of InvalidInputException. Catch this
exception and display an error message.
8. Build a program that takes two integers as input. If the second integer is odd, throw a custom
exception named OddNumberException. Handle this exception and display an appropriate
message.
9. Create a program that simulates a password verification process. Ask the user to enter a
password. If the password is less than 6 characters long, throw a PasswordLengthException.
Handle this exception and provide feedback.
In this chapter, students will learn how to work with files in Java, including reading and writing
data to files. They will understand the importance of file I/O and how to handle exceptions
associated with file operations.
I/O Streams
A stream is a communication channel that a program has with the outside world. It is used to
transfer data items in succession. An Input/Output (I/O) Stream represents an input source or an
output destination. A stream can represent many different kinds of sources and destinations,
including disk files, devices, other programs, and memory arrays. Streams support many different
kinds of data, including simple bytes, primitive data types, localized characters, and objects. Some
streams simply pass on data; others manipulate and transform the data in useful ways. No matter
how they work internally, all streams present the same simple model to programs that use them:
A stream is a sequence of data.
File I/O (Input/Output): File I/O refers to the process of reading from and writing to files.
In Java, it involves interactions with files on the file system.
Importance of File I/O: File I/O is crucial for tasks like data persistence, configuration
management, and data exchange with external sources. It allows programs to store and
retrieve data beyond their runtime.
Types of Data: Data in files can be categorized as text data (human-readable) and binary
data (non-human-readable, often used for structured data).
Writing to Files:
FileOutputStream: Used for writing binary data to files.
BufferedWriter: A higher-level class for writing text data to files. It offers buffering
and methods for writing lines and characters.
Exception Handling: Writing to files can also result in exceptions like IOException,
which must be handled properly.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
Output
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.IOException;
Output
import java.io.FileOutputStream;
import java.io.IOException;
Example 5:
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
while (true) {
System.out.print("Enter data row (comma-separated values) or
'exit' to finish: ");
String rowData = scanner.nextLine();
if (rowData.equalsIgnoreCase("exit")) {
break;
}
writer.write(rowData);
writer.newLine();
}
Asks the user to enter the name of the CSV file they want to create.
Asks the user to enter the header (column names) for the CSV file.
Allows the user to enter data rows, each as a comma-separated string.
Saves the data to the specified CSV file.
Handles exceptions related to file write operations and displays appropriate error messages.
Exercise
1. Write a program that copies the contents of one text file to another. Allow the user to specify
the source and destination file paths.
2. Create a program that reads a CSV (Comma-Separated Values) file and displays its content in a
tabular format. Handle cases where the file might be missing or incorrectly formatted.
3. Develop a file search program that takes a directory path and a file name as input. Search for
the specified file within the directory and its subdirectories. Display the paths of matching files
found.
4. Write a program that reads a text file and counts the number of words in it. Display the word
count at the end.
5. Create a program that renames a file. Allow the user to specify the current file name and the
new file name. Handle cases where the file doesn't exist or the new name is invalid.
6. Build a program that lists all the files and directories in a given directory. Display their names,
sizes, and last modification dates.
7. Develop a program that allows the user to enter data into a table and then save that data to a
CSV file. Implement error handling for file write operations.
8. Create a data backup program that periodically copies files from one directory to another.
Implement options for scheduling backups.
9. Write a program that intentionally generates and handles exceptions during file I/O operations.
Implement custom exception classes to differentiate between different error scenarios.
10. Build a program that reads binary data from a file and interprets it. For example, read and
display the header of an image file in binary format.
Sierra, K., & Bates, B. (2005). Head First Java (Second Edition). O'Reilly Media.
Bloch, J. (2018). Effective Java: Programming Language Guide (Third Edition). Addison-
Wesley Professional.
https://www.programiz.com/java-programming
https://www.w3schools.com/java