You are on page 1of 85

Werabe University

Institute of Technology

Department Of Information Systems

Fundamental of Object Oriented Programming Lab Manual

Prepared By: Fetiya Kedir (BSc)

September 2023

Werabe University

Werabe, Ethiopia
The Lab Manual Submitted By: Fetiya Kedir (BSc)

Approved by Department Head:-

__________________ _______________ _____________

Name Signature Date

Approved by college of IOT Dean:-

__________________ _______________ ____________

Name Signature Date


Acknowledgments

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.

OOP LAB MANUAL I


Abstract
This lab manual serves as a comprehensive guide for students embarking on a journey into the
world of Object-Oriented Programming (OOP) using the Java programming language. Java,
renowned for its portability, robustness, and versatility, has played a pivotal role in software
development for decades.

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.

OOP LAB MANUAL II


Finally, students learn about File I/O, enabling them to read from and write to files. This skill is
indispensable for real-world applications that involve data storage and retrieval.

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.

OOP LAB MANUAL III


Table of Contents
Acknowledgments............................................................................................................................ i
Abstract ........................................................................................................................................... ii
CHAPTER ONE ............................................................................................................................. 1
Introduction to Object Oriented Programming (JAVA) ................................................................. 1
Introduction to Object Oriented Programming ........................................................................... 1
Introduction to Java..................................................................................................................... 2
Introduction to Integrated Development Environments (IDEs) and Its Installation Process ...... 3
CHAPTER TWO .......................................................................................................................... 10
Basic Java Syntax ......................................................................................................................... 10
Introduction ............................................................................................................................... 10
Java Hello World Program........................................................................................................ 11
Java Variables and Literals ....................................................................................................... 12
Java Variables ....................................................................................................................... 12
Rules for Naming Variables in Java ..................................................................................... 13
Java literals............................................................................................................................ 13
Java Keywords and Identifiers .................................................................................................. 16
Java Keywords ...................................................................................................................... 16
Java identifiers ...................................................................................................................... 16
Java Data Types (Primitive)...................................................................................................... 17
Java Operators ........................................................................................................................... 21
Java Basic Input and Output ..................................................................................................... 27
Java Comments ......................................................................................................................... 28
Exercises ....................................................................................................................................... 28
CHAPTER THREE ...................................................................................................................... 30
Flow Control Structures and Arrays ............................................................................................. 30
Conditional Statements ............................................................................................................. 30
Java if.. Statement ................................................................................................................. 30
Java if...else (if-then-else) Statement .................................................................................... 31
Java if...else...if Statement .................................................................................................... 32

OOP LAB MANUAL IV


Java Nested if..else Statement ............................................................................................... 33
Java switch Statement ............................................................................................................... 34
Java for Loop ............................................................................................................................ 35
Java for Loop ........................................................................................................................ 35
Java while loop ..................................................................................................................... 37
Java do...while loop .............................................................................................................. 38
Jump Statement in Java ............................................................................................................. 40
Java break Statement............................................................................................................. 40
Java continue Statement ........................................................................................................ 42
Java Arrays................................................................................................................................ 44
Multidimensional Arrays ...................................................................................................... 47
Exercise ......................................................................................................................................... 48
CHAPTER FOUR ......................................................................................................................... 49
Objects and Classes....................................................................................................................... 49
Introduction to Classes and Objects .......................................................................................... 49
Object-Oriented Concepts:........................................................................................................ 50
 Encapsulation: ................................................................................................................ 50
 Abstraction: .................................................................................................................... 50
 Inheritance ...................................................................................................................... 50
 Polymorphism ................................................................................................................ 50
Constructors and Overloading: ............................................................................................. 50
Methods and Method Overloading: ...................................................................................... 50
Using 'this' Keyword: ............................................................................................................ 50
Exercise ......................................................................................................................................... 56
CHAPTER FIVE .......................................................................................................................... 58
Exception Handling in Java .......................................................................................................... 58
Introduction to Exceptions ........................................................................................................ 58
Types of Exceptions:................................................................................................................. 59
Checked Exceptions: ............................................................................................................. 59
Unchecked Exceptions (Runtime Exceptions): .................................................................... 59

OOP LAB MANUAL V


Handling Exceptions ................................................................................................................. 59
try-catch Blocks: ................................................................................................................... 59
finally Block: ........................................................................................................................ 59
throw Statement: ................................................................................................................... 59
throws Clause: ....................................................................................................................... 59
Commonly Used Exceptions..................................................................................................... 59
 ArithmeticException: ..................................................................................................... 59
 NullPointerException ..................................................................................................... 60
 ArrayIndexOutOfBoundsException ............................................................................... 60
Custom Exceptions ................................................................................................................... 60
 Creating Custom Exception Classes: ............................................................................. 60
 Throwing Custom Exceptions: ....................................................................................... 60
Exercise ......................................................................................................................................... 67
CHAPTER SIX ............................................................................................................................. 69
File I/O in Java .............................................................................................................................. 69
Introduction to File I/O: ............................................................................................................ 69
File Classes in Java: .................................................................................................................. 70
Reading from Files:................................................................................................................... 70
Writing to Files: ........................................................................................................................ 70
Binary File I/O: ......................................................................................................................... 70
Exception Handling in File I/O: ................................................................................................ 71
File and Directory Manipulation:.............................................................................................. 71
Exercise ......................................................................................................................................... 75
Reference ...................................................................................................................................... 77

OOP LAB MANUAL VI


CHAPTER ONE

Introduction to Object Oriented Programming (JAVA)


Objective:

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.

Introduction to Object Oriented 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.

OOP LAB MANUAL 1


 Classes: Classes serve as blueprints or templates for creating objects. They define the
structure and behavior of objects of that class. For example, a "Car" class might have
attributes like "color" and "model" and methods like "startEngine" and "stopEngine."
 Objects: Objects are instances of classes. They represent specific instances of real-world
entities and have their own unique data and state. For instance, a "Car" object may have a
color of "red" and a model of "sedan."
 Encapsulation: Encapsulation is the practice of bundling data (attributes) and the methods
(functions) that operate on that data into a single unit, the class. It restricts direct access to
an object's internal state and enforces access through methods, providing data security and
abstraction.
 Inheritance: Inheritance allows one class (subclass or derived class) to inherit the
properties and behaviors of another class (superclass or base class). It facilitates code reuse
and supports the "is-a" relationship. For example, a "SportsCar" class can inherit from the
"Car" class.
 Polymorphism: Polymorphism enables objects of different classes to be treated as objects
of a common superclass. It allows methods to be implemented in multiple ways, typically
through method overriding. Polymorphism promotes flexibility and extensibility in code.
 Abstraction: Abstraction involves simplifying complex reality by modeling classes based
on relevant attributes and behaviors while ignoring unnecessary details. It helps manage
complexity and makes code more understandable.

Introduction to Java

Java is a high-level, object-oriented programming language developed by Sun Microsystems (now


owned by Oracle Corporation) in the mid-1990s. It is known for its platform independence, strong
typing, and extensive standard library, making it a popular choice for a wide range of applications,
including web development, mobile app development, and enterprise software.

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

OOP LAB MANUAL 2


 Object-Oriented Nature: Java is a pure object-oriented language, where everything is
treated as an object. It encourages the use of classes and objects to structure code and
implement OOP principles like encapsulation, inheritance, and polymorphism.
 Strong Typing: Java enforces strong typing, meaning that variables must be declared with
specific data types, and type compatibility is strictly checked at compile-time. This
contributes to code safety and reliability.
 Extensive Standard Library: Java provides a vast standard library (Java API) with pre-
built classes and packages for various tasks, including data manipulation, I/O, networking,
and graphical user interface (GUI) development. This library simplifies common
programming tasks.
 Memory Management: Java includes automatic memory management through garbage
collection. Developers do not need to manually allocate or deallocate memory, reducing
the risk of memory-related errors.
 Security: Java places a strong emphasis on security. The JVM enforces various security
measures to prevent malicious code execution and unauthorized access to system
resources.
 Multithreading: Java supports multithreading, allowing developers to create concurrent
programs that can take advantage of modern multi-core processors.
 Portability: The platform independence of Java makes it highly portable, suitable for
developing applications that can run on diverse operating systems and hardware platforms.

Introduction to Integrated Development Environments (IDEs) and Its Installation Process

An Integrated Development Environment, commonly referred to as an IDE, is a software


application that provides a comprehensive set of tools and features for software development. It
serves as a centralized platform for programmers and developers to write, edit, test, debug, and
manage code efficiently. IDEs are particularly useful for streamlining the development process
and enhancing productivity. Here are some key aspects of IDEs:

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

OOP LAB MANUAL 3


 Compiler/Interpreter Integration: IDEs often integrate compilers or interpreters for
various programming languages, allowing developers to compile and run their code
directly within the IDE.
 Debugging Tools: Debugging features like breakpoints, variable inspection, and step-by-
step execution are integral parts of IDEs, enabling developers to identify and resolve issues
in their code efficiently.
 Project Management: IDEs facilitate project organization by providing tools to create,
open, and manage projects and project files. This helps keep code and resources well
structured.
 Version Control Integration: Many IDEs integrate with version control systems (e.g.,
Git) to support collaborative development and source code management.
 Code Completion: IDEs offer code suggestion and auto-completion features that help
developers write code faster and with fewer errors by offering context-aware suggestions.
 Error Highlighting: IDEs highlight syntax errors, typos, and potential issues in real-time,
helping developers catch mistakes before running the code.
 Integrated Build Tools: They often come with built-in build tools for compiling,
packaging, and deploying applications, simplifying the build process.
 Extensions and Plugins: IDEs allow users to enhance their functionality by installing
extensions or plugins tailored to specific programming languages, frameworks, or tools.
 User-Friendly Interface: IDEs typically offer a user-friendly interface with customizable
layouts, allowing developers to arrange windows, panels, and toolbars according to their
preferences.
 Cross-Platform Support: Many IDEs are cross-platform, meaning they are available for
different operating systems, allowing developers to work on Windows, macOS, and Linux
seamlessly.

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.

Step 1: Download and Install NetBeans

OOP LAB MANUAL 4


 Visit the NetBeans Website: Go to the official NetBeans website at
https://netbeans.apache.org/.
 Download the Installer: On the website's homepage, click on the "Download" button or
navigate to the "Downloads" section. Choose the appropriate version of NetBeans for your
operating system (Windows, macOS, or Linux).
 Run the Installer: Once the installer is downloaded, run the executable file (e.g., netbeans-
<version>-installer.exe on Windows). Follow the installation wizard's prompts.
 Select Installation Options: During installation, you can choose which components to
install. For Java development, make sure to select the "Java SE" package. You can also
include other packages based on your needs, such as "Java EE" for web development.
 Complete the Installation: Follow the remaining steps in the installation wizard to
complete the installation process.
Step 2: Install the Java Development Kit (JDK)
NetBeans relies on the Java Development Kit (JDK) to compile and run Java programs. If you do
not already have a JDK installed, follow these steps:
 Download the JDK: Visit the official Oracle JDK download page at
https://www.oracle.com/java/technologies/javase-downloads.html.
 Accept the License Agreement: Choose the appropriate version of the JDK (e.g., JDK 8,
JDK 11) and accept the license agreement.
 Download and Install: Download the JDK installer for your operating system and run it.
Follow the installation instructions.
 Set Environment Variables (Optional): In some cases, you may need to set the
JAVA_HOME environment variable to point to your JDK installation directory. This is
necessary for NetBeans to locate the JDK.
Step 3: Launch NetBeans
 Open NetBeans: After installation is complete, launch NetBeans from your computer's
applications menu or desktop shortcut.

OOP LAB MANUAL 5


Figure 1: The NetBeans IDE start Page

Step 4: Configure NetBeans for Java Development


 Choose a Development Environment: On the initial start-up, NetBeans may ask you to
choose a development environment. Select "Java" and click "Next."
 Select JDK: NetBeans will prompt you to select the JDK. Choose the JDK you installed
in the previous step.
Step 5: Create Your First Java Project
1. Create a New Java Project:
 Click on "File" in the top menu.
 Select "New Project."
 Choose "Java" under "Categories" and "Java Application" under "Projects."
 Click "Next.

Figure 2: Starting a New Java Project from NetBeans IDE

2. Configure the Project:

OOP LAB MANUAL 6


 Enter a project name (e.g., "MyFirstJavaProject").
 Choose a project location on your computer.
 Ensure that "Create Main Class" is checked.
 Click "Finish."
3. Write Your First Java Program:
 NetBeans will automatically generate a Java class with a main method. This is where your
program will start.

Figure 3: Program Writing Environment

 Write your Java code in this class. For example, you can use System.out.println("Hello,
World!"); for a simple "Hello World" program.

OOP LAB MANUAL 7


Figure 4: The First Java Program

4. Run the Program:


 Right-click on your project in the "Projects" pane on the left.
 Select "Run." OR
 Hover on button on the top menu section until you get “Run” and click on it.

Figure 5: The Run Option

5. View Output: The program's output will be displayed in the "Output" pane at the bottom of the
NetBeans window.

OOP LAB MANUAL 8


Figure 6: The Output of the First Program

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.

OOP LAB MANUAL 9


CHAPTER TWO

Basic Java Syntax

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.

Objective: In this chapter,

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

OOP LAB MANUAL 10


Java Hello World Program

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

 public class MyFirstJavaProject{ ... }

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.

 public static void main(String[] args) { ... }

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.

OOP LAB MANUAL 11


How does it work? Good question. However, we will not discuss it in this article. After all,
it's a basic program to introduce Java programming language to a newbie. We will learn the
meaning of public, static, void, and how methods work? in later chapters.
For now, just remember that the main function is the entry point of your Java application,
and it's mandatory in a Java program.
 System.out.println("Hello, World!");
The code above is a print statement. It prints the text Hello, World! to standard output (your
screen). The text inside the quotation marks is called String in Java. Notice the print statement is
inside the main function, which is inside the class definition.
Java Variables and Literals
Java Variables

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

Create Variables in Java


Here's how we create a variable in Java,

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.

OOP LAB MANUAL 12


Rules for Naming Variables in Java

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,

 Variable names cannot start with numbers. For example,


int 1age; // invalid variables
 Variable names can't use whitespace. For example,
int my age; // invalid variables
Here, is we need to use variable names having more than one word, use all lowercase letters for
the first word and capitalize the first letter of each subsequent word. For example, myAge.
 When creating variables, choose a name that makes sense. For example, score, number,
level makes more sense than variable names such as s, n, and l.
 If you choose one-word variable names, use all lowercase letters. For example, it is better
to use speed rather than SPEED, or sPEED.
Java literals
Literals are data used for representing fixed values. They can be used directly in the code. For
example,

int a = 1;
float b = 2.5;

OOP LAB MANUAL 13


char c = 'F';

Here, 1, 2.5, and 'F' are literals.

Here are different types of literals in Java.

1. Boolean Literals

In Java, boolean literals are used to initialize boolean data types. They can store two values: true
and false. For example,

boolean flag1 = false;


boolean flag2 = true;

Here, false and true are two boolean literals.


2. Integer Literals: An integer literal is a numeric value(associated with numbers) without any
fractional or exponential part. There are 4 types of integer literals in Java:

 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

OOP LAB MANUAL 14


In Java, binary starts with 0b, octal starts with 0, and hexadecimal starts with 0x.

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

double myDouble = 3.4;


float myFloat = 3.4F;

// 3.445*10^2
double myDoubleScientific = 3.445e2;

System.out.println(myDouble); // prints 3.4


System.out.println(myFloat); // prints 3.4
System.out.println(myDoubleScientific); // prints 344.5
}
}

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,

char letter = 'a';

Here, a is the character literal.


We can also use escape sequences as character literals. For
example, \b (backspace), \t (tab), \n (new line), etc.

OOP LAB MANUAL 15


5. String literals: A string literal is a sequence of characters enclosed inside double-quotes. For
example,

String str1 = "Java Programming";


String str2 = "OOP Programing";

Here, Java Programming and OOP Programing are two string literals.

Java Keywords and Identifiers


Java Keywords
Keywords are predefined, reserved words used in Java programming that have special meanings
to the compiler. For example:

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.

OOP LAB MANUAL 16


Rules for Naming an Identifier

 Identifiers cannot be a keyword.


 Identifiers are case-sensitive.
 It can have a sequence of letters and digits. However, it must begin with a letter, $ or _.
The first letter of an identifier cannot be a digit.
 It's a convention to start an identifier with a letter rather and $ or _.
 Whitespaces are not allowed.
 Similarly, you cannot use symbols such as @, #, and so on.

Here are some valid identifiers: Here are some invalid identifiers:

 score  class
 level  float
 highestScore  1number
 number1  highest Score
 convertToString  @pple

Java Data Types (Primitive)


As the name suggests, data types specify the type of data that can be stored inside Java is a
statically-typed language. This means that all variables must be declared before they can be used.

int speed;

Note: In addition to primitive data types, there are also referenced types (object type).

There are Eight Primitive Data Types

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.

Example 1: Java boolean data type

Public class BooleanExample {


public static void main(String[] args) {

OOP LAB MANUAL 17


boolean flag = true;
System.out.println(flag); // prints true
}
}

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

Public class ShortExample {


public static void main(String[] args) {

OOP LAB MANUAL 18


short temperature;
temperature = -200;
System.out.println(temperature); // prints -200
}
}

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

int range = -4250000;


System.out.println(range); // print -4250000
}
}

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

Public class LongExample {

OOP LAB MANUAL 19


public static void main(String[] args) {

long range = -42332200000L;


System.out.println(range); // prints -42332200000
}
}
Notice, the use of L at the end of -42332200000. This represents that it's an integer of the long
type.
6. double type
 The double data type is a double-precision 64-bit floating-point.
 It should never be used for precise values such as currency.
 Default value: 0.0 (0.0d)
Example 6: Java double data type
Public class DoubleExample {
public static void main(String[] args) {

double number = -42.3;


System.out.println(number); // prints -42.3
}
}

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

float number = -42.3f;


System.out.println(number); // prints -42.3
}
}

OOP LAB MANUAL 20


Notice that we have used -42.3f instead of -42.3 in the above program. It's because -42.3 is a
double literal. To tell the compiler to treat -42.3 as float rather than double, you need to use f or F.
8. char type
 It's a 16-bit Unicode character.
 The minimum value of the char data type is '\u0000' (0) and the maximum value of the is
'\uffff'.
 Default value: '\u0000'
Example 8: Java char data type
Public class CharExample {
public static void main(String[] args) {

char letter = '\u0051';


System.out.println(letter); // prints Q
}
}

Here, the Unicode value of Q is \u0051. Hence, we get Q as the output.


Java Operators

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

OOP LAB MANUAL 21


Public class ArithmeticOperator {
public static void main(String[] args) {

// 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

2. Java Assignment Operators

Assignment operators are used in Java to assign values to variables. For example,

int age;
age = 5;

Example 2: Assignment Operators

OOP LAB MANUAL 22


Public class AssignmentOpt {
public static void main(String[] args) {

// create variables
int a = 4;
int var;

// assign value using =


var = a;
System.out.println("var using =: " + var);

// assign value using =+


var += a;
System.out.println("var using +=: " + var);

// assign value using =*


var *= a;
System.out.println("var using *=: " + var);
}
}
Run Code

Output

var using =: 4
var using +=: 8
var using *=: 32

3. Java Relational Operators


Relational operators are used to check the relationship between two operands. For example,

// check if a is less than b


a < b;

Here, < operator is the relational operator. It checks if a is less than b or not.

It returns either true or false.

Example 3: Relational Operators

OOP LAB MANUAL 23


Public class RelationalOpt {
public static void main(String[] args) {

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

4. Java Logical Operators


Logical operators are used to check whether an expression is true or false. They are used in decision
making.
Example 4: Logical Operators

OOP LAB MANUAL 24


Public class LogicalOpt {
public static void main(String[] args) {

// && 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
}
}

5. Java Unary Operators


Unary operators are used with only one operand. For example, ++ is a unary operator that increases
the value of a variable by 1. That is, ++5 will return 6.
Increment and Decrement Operators
Java also provides increment and decrement operators: ++ and -- respectively. ++ increases the
value of the operand by 1, while -- decrease it by 1. For example,

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

OOP LAB MANUAL 25


Public class UnaryOpt {
public static void main(String[] args) {

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

System.out.println("Value of b: " + b);

// 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

6. Java Bitwise Operators


Bitwise operators in Java are used to perform operations on individual bits. For example,

Bitwise complement Operation of 35

35 = 00100011 (In Binary)

~ 00100011
________
11011100 = 220 (In decimal)

OOP LAB MANUAL 26


Java Basic Input and Output

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.

Reading Input from the User:

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;

public class UserInputExample {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = scanner.nextLine();
System.out.println("Hello, " + name + "!");
scanner.close();
}
}

Output

Enter your name: John


Hello, John!

Output to the Console:

You can display output on the console using System.out.println() or System.out.print(). For
example:

public class ConsoleOutputExample {

OOP LAB MANUAL 27


public static void main(String[] args) {
System.out.println("Hello, World!");
int number = 42;
System.out.print("The answer is: " + number);
}
}

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,

// declare and initialize two variables


int a =1;
int b = 3;

// print the output


System.out.println("This is output");

Types of Comments in Java


In Java, there are two types of comments:
 single-line comment
 multi-line comment

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.

OOP LAB MANUAL 28


3. Declare variables to represent the following information and initialize them with appropriate
values:

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.

7. Write a Java program that prints a message like this:

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.

OOP LAB MANUAL 29


CHAPTER THREE

Flow Control Structures and Arrays

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.

Java if.. Statement

Example 1: Java if Statement

class IfStatement {
public static void main(String[] args) {

int number = 10;

// checks if number is less than 0


if (number < 0) {
System.out.println("The number is negative.");
}

OOP LAB MANUAL 30


System.out.println("Statement outside if block");
}
}
Output

Statement outside if block

Java if...else (if-then-else) Statement

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.

Example 3: Java if...else Statement

class IfElse {
public static void main(String[] args) {
int number = 10;

// checks if number is greater than 0


if (number > 0) {
System.out.println("The number is positive.");
}

// execute this block


// if number is not greater than 0
else {
System.out.println("The number is not positive.");
}

System.out.println("Statement outside if...else block");


}
}

OOP LAB MANUAL 31


Output

The number is positive.


Statement outside if...else block

Java if...else...if Statement

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;

// checks if number is greater than 0


if (number > 0) {
System.out.println("The number is positive.");
}

// checks if number is less than 0


else if (number < 0) {
System.out.println("The number is negative.");
}

// if both condition is false


else {
System.out.println("The number is 0.");
}
}
}

Outputs

The number is 0.

OOP LAB MANUAL 32


Java Nested if..else Statement

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

// declaring double type variables


Double n1 = -1.0, n2 = 4.5, n3 = -5.3, largest;

// checks if n1 is greater than or equal to n2


if (n1 >= n2) {

// if...else statement inside the if block


// checks if n1 is greater than or equal to n3
if (n1 >= n3) {
largest = n1;
}

else {
largest = n3;
}
} else {

// if..else statement inside else block


// checks if n2 is greater than or equal to n3
if (n2 >= n3) {
largest = n2;
}

else {
largest = n3;
}
}

System.out.println("Largest Number: " + largest);


}

OOP LAB MANUAL 33


}

Java switch Statement

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

// Java Program to check the size


// using the switch...case statement

class SwicthStatement {
public static void main(String[] args) {

int number = 44;


String size;

// switch statement to check size


switch (number) {

case 29:
size = "Small";
break;

case 42:
size = "Medium";
break;

// match the value of week


case 44:
size = "Large";
break;

case 48:
size = "Extra Large";
break;

default:
size = "Unknown";
break;

OOP LAB MANUAL 34


}
System.out.println("Size: " + size);
}
}

Output

Size: Large

break statement in Java switch...case

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.

In Java, there are three types of loops.

 for loop
 while loop
 do...while loop

Java for Loop

Java for loop is used to run a block of code for a certain number of times. The syntax
of for loop is:

for (initialExpression; testExpression; updateExpression) {


// body of the loop
}

Example 1: Display a Text Five Times

OOP LAB MANUAL 35


// Program to print a text 5 times

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

Example 2: Display numbers from 1 to 5

// Program to print numbers from 1 to 5

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

OOP LAB MANUAL 36


1
2
3
4
5

Java while and do...while 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 you can use a loop. It's just a simple example; you can achieve
much more with loops.

Java while loop

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
}

Example 2: Sum of Positive Numbers Only

// Java program to find the sum of positive numbers


import java.util.Scanner;

class Main {
public static void main(String[] args) {

int sum = 0;

// create an object of Scanner class


Scanner input = new Scanner(System.in);

// take integer input from the user


System.out.println("Enter a number");
int number = input.nextInt();

OOP LAB MANUAL 37


// while loop continues
// until entered number is positive
while (number >= 0) {
// add only positive numbers
sum += number;

System.out.println("Enter a number");
number = input.nextInt();
}

System.out.println("Sum = " + sum);


input.close();
}
}
Run Code

Output

Enter a number
25
Enter a number
9
Enter a number
5
Enter a number
-3
Sum = 39

Java do...while loop

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

Example 1: Factorial of Given number

OOP LAB MANUAL 38


import java.util.Scanner;

public class FactorialCalculator {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
int number = scanner.nextInt();

int factorial = 1;
int i = 1;

do {
factorial *= i;
i++;
} while (i <= number);

System.out.println("The factorial of " + number + " is " + factorial);


}
}

Output:

Enter a positive integer: 5


The Factorial of 5 is 120

Example 2: A do…while loop example for password validation

import java.util.Scanner;

public class PasswordValidation {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String correctPassword = "secret";
String enteredPassword;

do {
System.out.print("Enter the password: ");
enteredPassword = scanner.next();

OOP LAB MANUAL 39


if (enteredPassword.equals(correctPassword)) {
System.out.println("Access granted!");
break;
} else {
System.out.println("Incorrect password. Try again.");
}
} while (true);
}
}

Output

Enter the password: incorrect


Incorrect password. Try again.
Enter the password: secret
Access granted!

Jump Statement in Java

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.

Java break 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.

Example 1: Java break statement

Public class BreakStatement {


public static void main(String[] args) {

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

OOP LAB MANUAL 40


// if the value of i is 5 the loop terminates
if (i == 5) {
break;
}
System.out.println(i);
}
}
}
Output:

1
2
3
4

Example 2: Java break statement

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;

public class UserInputSum {


public static void main(String[] args) {

Double number, sum = 0.0;

// create an object of Scanner


Scanner input = new Scanner(System.in);

while (true) {
System.out.print("Enter a number: ");

// takes double input from user


number = input.nextDouble();

// if number is negative the loop terminates


if (number < 0.0) {
break;

OOP LAB MANUAL 41


}

sum += number;
}
System.out.println("Sum = " + sum);
}
}
Output:

Enter a number: 3.2


Enter a number: 5
Enter a number: 2.3
Enter a number: 0
Enter a number: -4.5
Sum = 10.5

Java continue Statement

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

Example 1: Java continue statement

Public class ContStat {


public static void main(String[] args) {

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

// if value of i is between 4 and 9


// continue is executed
if (i > 4 && i < 9) {
continue;
}
System.out.println(i);
}
}

OOP LAB MANUAL 42


}
Output:

1
2
3
4
9
10

Example 2: Compute the sum of 5 positive numbers

import java.util.Scanner;

public class ContStatement {


public static void main(String[] args) {

Double number, sum = 0.0;


// create an object of Scanner
Scanner input = new Scanner(System.in);

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


System.out.print("Enter number " + i + " : ");
// takes input from the user
number = input.nextDouble();

// if number is negative
// continue statement is executed
if (number <= 0.0) {
continue;
}

sum += number;
}
System.out.println("Sum = " + sum);
input.close();
}
}

OOP LAB MANUAL 43


Output:

Enter number 1: 2.2


Enter number 2: 5.6
Enter number 3: 0
Enter number 4: -2.4
Enter number 5: -3
Sum = 7.8

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.

String[] array = new String[100];

Here, the above array cannot store more than 100 names. The number of values in a Java array is
always fixed.

How to declare an array in Java?

In Java, here is how we can declare an array.

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;

How to Initialize Arrays in Java?

In Java, we can initialize arrays during declaration. For example,

//declare and initialize and array


int[] age = {12, 4, 5, 2, 5};

How to Access Elements of an Array in Java?

OOP LAB MANUAL 44


We can access the element of an array using the index number. Here is the syntax for accessing
elements of an array,

// access array elements


array[index]

Example: 1 Access Array Elements

class Main {
public static void main(String[] args) {

// create an array
int[] age = {12, 4, 5, 2, 5};

// access each array elements


System.out.println("Accessing Elements of Array:");
System.out.println("First Element: " + age[0]);
System.out.println("Second Element: " + age[1]);
System.out.println("Third Element: " + age[2]);
System.out.println("Fourth Element: " + age[3]);
System.out.println("Fifth Element: " + age[4]);
}
}
Run Code

Output

Accessing Elements of Array:


First Element: 12
Second Element: 4
Third Element: 5
Fourth Element: 2
Fifth Element: 5

Example: 2 Access the Array Elements by Using For Loop

class Main {
public static void main(String[] args) {

// create an array
int[] age = {12, 4, 5};

OOP LAB MANUAL 45


// loop through the array
// using for loop
System.out.println("Using for Loop:");
for(int i = 0; i < age.length; i++) {
System.out.println(age[i]);
}
}
}
Output

Using for Loop:


12
4
5

Example:3 Compute Sum and Average of Array Elements

class Main {
public static void main(String[] args) {

int[] numbers = {2, -9, 0, 5, 12, -25, 22, 9, 8, 12};


int sum = 0;
Double average;

// access all elements using for each loop


// add each element in sum
for (int number: numbers) {
sum += number;
}
// get the total number of elements
int arrayLength = numbers.length;

// calculate the average


// convert the average from int to double
average = ((double)sum / (double)arrayLength);
System.out.println("Sum = " + sum);
System.out.println("Average = " + average);
}
}

Output:

OOP LAB MANUAL 46


Sum = 36
Average = 3.6

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.

Example:2 Print all elements of 2d array Using Loop

Public class MultidimensionalArray {


public static void main(String[] args) {

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

OOP LAB MANUAL 47


Exercise
1. Write a Java program that prompts the user to enter a positive integer and calculates its factorial
using a for loop. Display the result.

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.

OOP LAB MANUAL 48


CHAPTER FOUR

Objects and Classes


Objective: In this chapter, you will explore the fundamental concepts of object-oriented
programming (OOP), including the creation of classes and objects, defining attributes (fields) and
behaviors (methods), and understanding the concept of encapsulation.

Introduction to Classes and Objects

Java is an object-oriented programming language. The core concept of the object-oriented


approach is to break complex problems into smaller objects.

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

MyClass myObject = new MyClass();

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.

OOP LAB MANUAL 49


 Access Modifiers: Access modifiers (e.g., public, private, protected, default) control the
visibility and accessibility of class members. They enforce encapsulation and data hiding.

Object-Oriented Concepts:

 Encapsulation: Encapsulation is the concept of bundling data (fields) and methods


(behaviors) that operate on that data into a single unit (a class). It promotes data hiding and
abstraction.
 Abstraction: Abstraction involves simplifying complex reality by modeling classes based
on relevant characteristics. It hides the unnecessary details while exposing essential
features.
 Inheritance: Inheritance allows a class to inherit attributes and methods from another
class (the superclass). It promotes code reuse and the creation of hierarchies.
 Polymorphism: Polymorphism enables objects of different classes to be treated as
objects of a common superclass. It allows for method overriding and dynamic method
binding.

Constructors and Overloading:

 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 and Method Overloading:

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

Using 'this' Keyword:

 '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.

OOP LAB MANUAL 50


Example 1: Write a Java program that defines a class named Car with fields for the car's brand
and model. Create an object of the Car class, set its brand and model, and then display the car's
information.

public class CarDemo {


public static void main(String[] args) {
Car myCar = new Car();
myCar.brand = "Toyota";
myCar.model = "Camry";

System.out.println("My Car Information:");


myCar.displayInfo();
}
}

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.

public class RectangleDemo {


public static void main(String[] args) {
Rectangle smallRectangle = new Rectangle();
Rectangle largeRectangle = new Rectangle(5, 3);

System.out.println("Area of Small Rectangle: " +


smallRectangle.calculateArea());
System.out.println("Area of Large Rectangle: " +
largeRectangle.calculateArea());
}
}

OOP LAB MANUAL 51


Output

Area of Small Rectangle: 0


Area of Large Rectangle: 15

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.

public class CalculatorDemo {


public static void main(String[] args) {
Calculator myCalculator = new Calculator();

int result1 = myCalculator.add(5, 3);


int result2 = myCalculator.subtract(8, 2);

System.out.println("Addition Result: " + result1);


System.out.println("Subtraction Result: " + result2);
}
}

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

public class PersonDemo {


public static void main(String[] args) {
Person person1 = new Person("Alice", 25);
Person person2 = new Person("Bob", 30);

OOP LAB MANUAL 52


System.out.println("Person 1 Information:");
person1.displayInfo();

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.

public class EncapsulationDemo {


public static void main(String[] args) {
// Create a Student object
Student student = new Student();

// Set student information using setter methods


student.setName("Alice");
student.setAge(20);

// Display student information using getter methods


System.out.println("Student Name: " + student.getName());
System.out.println("Student Age: " + student.getAge());
}

OOP LAB MANUAL 53


}

Output

Student Name: Alice


Student Age: 20

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.

public class InheritanceDemo {


public static void main(String[] args) {
// Create Dog and Cat objects
Animal dog = new Dog();
Animal cat = new Cat();

// Call makeSound on Dog and Cat objects


dog.makeSound();
cat.makeSound();
}
}

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.

OOP LAB MANUAL 54


public class PolymorphismDemo {
public static void main(String[] args) {
// Create Circle and Rectangle objects
Shape circle = new Circle(5.0);
Shape rectangle = new Rectangle(4.0, 6.0);

// Call calculateArea on Circle and Rectangle objects


System.out.println("Area of Circle: " + circle.calculateArea());
System.out.println("Area of Rectangle: " + rectangle.calculateArea());
}
}

Output

Area of Circle: 78.54


Area of Rectangle: 24.0

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.

public class AbstractionDemo {


public static void main(String[] args) {
// Create a Car object
Vehicle car = new Car();

// Call the start method on the Car object


car.start();
}
}

Output

Car started.

OOP LAB MANUAL 55


Exercise
1. Create a class named Student with fields for the student's name, age, and major. Include
methods to set and display this information for a student. Create two instances of the Student
class and display their information.

2. Create a class TemperatureConverter with methods to convert temperatures from Celsius to


Fahrenheit and vice versa. Allow the user to input a temperature in one scale, convert it, and
display the result.

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.

OOP LAB MANUAL 56


OOP LAB MANUAL 57
CHAPTER FIVE

Exception Handling in Java


Objectives

In this chapter, students will:

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

OOP LAB MANUAL 58


Need for Exception Handling: Exception handling is a mechanism that allows you to deal with
runtime errors in a systematic and controlled way. It prevents a program from crashing and helps
in providing informative error messages.

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.

Commonly Used Exceptions


 ArithmeticException: Thrown when an arithmetic operation results in an error, such as
division by zero.

OOP LAB MANUAL 59


 NullPointerException: Thrown when an attempt is made to access or invoke a method
on an object that is null.
 ArrayIndexOutOfBoundsException: Thrown when an attempt is made to access an
array element with an invalid index.
 IOException: Thrown for various I/O-related errors when working with files and streams.

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.

Best Practices in Exception Handling

 Proper Exception Messages: Include informative error messages in exceptions to aid


debugging and troubleshooting.
 Logging Exceptions: Use logging frameworks like Log4j or the built-in Java Logging API
to log exceptions and related information.
 Exception Chaining: Use exception chaining to provide context about the cause of an
exception by setting the original exception as the cause of a new exception.
 Handling or Propagating Exceptions: Decide whether to handle exceptions at the point
where they occur or propagate them up the call stack to be handled by a higher-level code.

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

public class ArithmeticExceptionExample {

OOP LAB MANUAL 60


public static void main(String[] args) {
try {
int result = divide(10, 0); // This will throw an ArithmeticException
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
}
}
static int divide(int a, int b) {
return a / b;
}
}

Output

Error: / by zero

Example 2: try-catch block with NullPointerException

public class NullPointerExceptionExample {


public static void main(String[] args) {
String text = null;
try {
int length = text.length(); // This will throw a NullPointerException
System.out.println("Length: " + length);
} catch (NullPointerException e) {
System.out.println("Error: " + e.getMessage());
}
}
}

Output

Error: null

Example 3: try-catch block with ArrayIndexOutOfBoundException

public class ArrayIndexOutOfBoundsExceptionExample {

OOP LAB MANUAL 61


public static void main(String[] args) {
int[] numbers = { 1, 2, 3 };

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

Error: Index 3 out of bounds for length 3

Example 4: try-catch block with IOException

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

Error: nonexistent.txt (No such file or directory)

OOP LAB MANUAL 62


Example 5: throw Statement with ArithmeticException and finally Block

public class ArithmeticExceptionWithFinally {


public static void main(String[] args) {
try {
int result = divide(10, 0); // This will throw an ArithmeticException
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
} finally {
System.out.println("Finally block executed.");
}
}
static int divide(int a, int b) {
return a / b;
}
}

Output

Error: / by zero
Finally block executed.

Example 6: throw Statement with NullPointerException and finally Block

public class NullPointerExceptionWithFinally {


public static void main(String[] args) {
String text = null;
try {
int length = text.length(); // This will throw a NullPointerException
System.out.println("Length: " + length);
} catch (NullPointerException e) {
System.out.println("Error: " + e.getMessage());
} finally {
System.out.println("Finally block executed.");
}
}

Output

OOP LAB MANUAL 63


Error: null
Finally block executed.

Example 7: throw Statement with ArrayIndexOutOfBoundsException and finally Block

public class ArrayIndexOutOfBoundsExceptionWithFinally {


public static void main(String[] args) {
int[] numbers = { 1, 2, 3 };

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

Error: Index 3 out of bounds for length 3


Finally block executed.

Example 8: throw Statement with IOException and finally Block

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class IOExceptionWithFinally {


public static void main(String[] args) {
BufferedReader reader = null;

try {
reader = new BufferedReader(new FileReader("nonexistent.txt"));
String line = reader.readLine();
System.out.println("Read Line: " + line);

OOP LAB MANUAL 64


} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
System.out.println("Error closing the file: " + e.getMessage());
}
System.out.println("Finally block executed.");
}
}
}

Output

Error: nonexistent.txt (No such file or directory)


Finally block executed.

Example 9: Example of custom exception handling in Java

class NegativeValueException extends Exception {


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

class BankAccount {
private double balance;

public void deposit(double amount) {


if (amount < 0) {
try {
throw new NegativeValueException("Invalid deposit amount: " +
amount);
} catch (NegativeValueException e) {
System.err.println("Error: " + e.getMessage());
}
} else {

OOP LAB MANUAL 65


balance += amount;
System.out.println("Deposited: " + amount);
}
}

public void withdraw(double amount) throws NegativeValueException {


if (amount < 0) {
throw new NegativeValueException("Invalid withdrawal amount: " +
amount);
}
if (balance >= amount) {
balance -= amount;
System.out.println("Withdrawn: " + amount);
} else {
System.out.println("Insufficient balance");
}
}

public double getBalance() {


return balance;
}
}

public class CustomExceptionExample {


public static void main(String[] args) {
BankAccount account = new BankAccount();

try {
account.deposit(1000);
account.withdraw(500);
account.withdraw(-200); // This will throw a NegativeValueException
} catch (NegativeValueException e) {
System.err.println("Error: " + e.getMessage());
}

System.out.println("Final Balance: " + account.getBalance());


}
}

Output

OOP LAB MANUAL 66


Deposited: 1000.0
Withdrawn: 500.0
Error: Invalid withdrawal amount: -200.0
Final Balance: 500.0

In this example:

 We create a NegativeValueException class to represent custom exceptions for negative


values.
 The BankAccount class handles deposit and withdrawal operations, checking for negative
values and throwing the custom exception when necessary.
 In the main method, we demonstrate how to use the BankAccount class to deposit,
withdraw, and handle the custom exception.
 When we attempt to withdraw a negative amount (-200.0), it throws a
NegativeValueException, and we catch and display the error message.
 The final balance after these transactions is 500.0.
 This example illustrates the creation and handling of custom exceptions in Java, allowing
you to gracefully manage exceptional situations specific to your application.

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.

OOP LAB MANUAL 67


6. Write a program that asks the user for their age. Handle cases where the user enters a negative
value or non-numeric input. Display an error message in these situations.

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.

OOP LAB MANUAL 68


CHAPTER SIX

File I/O in Java


Objective:

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.

Introduction to File I/O:


We have seen in this class how objects communicate with each other. Program often need to
communicate with the outside world. The means of communication are input (such as a keyboard)
and output (such as the computer screen). Programs can also communicate through stored data,
such as files.

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

OOP LAB MANUAL 69


File Classes in Java:
 File Class: The java.io.File class represents file and directory paths. It provides methods
for file/directory existence checks, path manipulation, and listing files and directories.
 Stream Classes: The java.io package offers various classes for working with files and
streams, including FileInputStream, FileOutputStream, BufferedReader, and
BufferedWriter.

Reading from Files:


 FileInputStream: This class is used for reading binary data from files. It reads data in
bytes.
 BufferedReader: A higher-level class used for reading text data from files. It allows
reading line by line and offers buffering for improved performance.
 Exception Handling: Reading from files can throw exceptions like
FileNotFoundException (when the file doesn't exist) and IOException (for other I/O
issues). These exceptions should be handled gracefully.

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.

Binary File I/O:


 Binary Data: Binary file I/O involves reading and writing non-text data, such as
images, audio, or serialized objects.
 DataInputStream/DataOutputStream: These classes provide methods for reading
and writing primitive data types and objects in binary format.
 Serialization: Java's serialization mechanism allows objects to be converted into a
binary stream for storage or transmission.

OOP LAB MANUAL 70


Exception Handling in File I/O:
 try-catch Blocks: File I/O operations should be wrapped in try blocks to catch
exceptions like IOException.
 finally Block: A finally block ensures that resources (like file handles) are properly
closed, even if an exception occurs.

File and Directory Manipulation:


 File Manipulation: Java provides methods like createNewFile(), delete(), and
renameTo() for creating, deleting, and renaming files.
 Directory Manipulation: Methods like mkdir(), mkdirs(), and listFiles() allow for
directory manipulation.

Example 1: Reading text from file

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadFileExample {


public static void main(String[] args) {
String filePath = "sample.txt";
try (BufferedReader reader = new BufferedReader(new
FileReader(filePath))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.err.println("An error occurred: " + e.getMessage());
}
}
}

Output

OOP LAB MANUAL 71


Output (if "sample.txt" contains):
This is line 1.
This is line 2.
This is line 3.

Example 2: Writing Text to file

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class WriteFileExample {


public static void main(String[] args) {
String filePath = "output.txt";
try (BufferedWriter writer = new BufferedWriter(new
FileWriter(filePath))) {
writer.write("Hello, world!");
writer.newLine(); // Add a new line
writer.write("Java File I/O example.");
} catch (IOException e) {
System.err.println("An error occurred: " + e.getMessage());
}
}
}

Example 3: Reading Binary Data from a file

import java.io.FileInputStream;
import java.io.IOException;

public class ReadBinaryFileExample {


public static void main(String[] args) {
String filePath = "binary.dat";
try (FileInputStream fis = new FileInputStream(filePath)) {
int byteRead;
while ((byteRead = fis.read()) != -1) {
System.out.print(byteRead + " ");
}
} catch (IOException e) {
System.err.println("An error occurred: " + e.getMessage());

OOP LAB MANUAL 72


}
}
}

Output

Output (if "binary.dat" contains binary data):


72 101 108 108 111 44 32 119 111 114 108 100 33

Example 4: Writing Binary Data to a File

import java.io.FileOutputStream;
import java.io.IOException;

public class WriteBinaryFileExample {


public static void main(String[] args) {
String filePath = "binary.dat";
try (FileOutputStream fos = new FileOutputStream(filePath)) {
byte[] data = { 72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108,
100, 33 };
fos.write(data);
} catch (IOException e) {
System.err.println("An error occurred: " + e.getMessage());
}
}
}

Example 5:

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class CSVDataEntry {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.println("CSV Data Entry Program");

OOP LAB MANUAL 73


System.out.print("Enter the name of the CSV file to create: ");
String fileName = scanner.nextLine();

try (BufferedWriter writer = new BufferedWriter(new


FileWriter(fileName))) {
// Read and write header
System.out.print("Enter CSV header (comma-separated values): ");
String header = scanner.nextLine();
writer.write(header);
writer.newLine();

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

System.out.println("Data saved to " + fileName);


} catch (IOException e) {
System.err.println("Error writing to the file: " + e.getMessage());
} finally {
scanner.close();
}
}
}

This program does the following:

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

OOP LAB MANUAL 74


 Please make sure to run this program in an environment where you have write access to
the directory where you intend to create the CSV file.

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.

OOP LAB MANUAL 75


OOP LAB MANUAL 76
Reference
Schildt, H. (2018). Java: The Complete Reference (Eleventh Edition). McGraw-Hill Education.

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

OOP LAB MANUAL 77

You might also like