0% found this document useful (0 votes)
301 views77 pages

OOPS With Java Lab Manual 2023-24

The document is a laboratory manual for the Object Oriented Programming with Java Lab course (BCS-452) for B.Tech. Semester IV students at JSS Academy of Technical Education. It includes the institute's vision and mission, educational objectives, course outcomes, a list of experiments, safety precautions, guidelines for report preparation, and assessment criteria. The manual aims to equip students with practical skills in Java programming and related technologies.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
301 views77 pages

OOPS With Java Lab Manual 2023-24

The document is a laboratory manual for the Object Oriented Programming with Java Lab course (BCS-452) for B.Tech. Semester IV students at JSS Academy of Technical Education. It includes the institute's vision and mission, educational objectives, course outcomes, a list of experiments, safety precautions, guidelines for report preparation, and assessment criteria. The manual aims to equip students with practical skills in Java programming and related technologies.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 77

OBJECT ORIENTED PROGRAMMING WITH

JAVA LAB
LABORATORY MANUAL
B.Tech., Semester -IV
Subject Code: BCS-

452

Session: 2024-25, Even Semester


Name:

Roll. No.:

Group/Branch:

JSS MAHAVIDYAPEETHA
DEPARTMENT OF INFORMATION TECHNOLOGY
JSS ACADEMY OF TECHNICAL EDUCATION
C-20/1, SECTOR-62, NOIDA
C212: Object Oriented Programming with Java Lab (BCS-452)

Table of Contents
1. Vision and Mission of the Institute
2. Vision and Mission of the Department
3. Programme Educational Objectives (PEOs)
4. Programme Outcomes (POs)
5. Programme Specific Outcomes (PSOs)
6. University Syllabus
7. Course Outcomes (COs)
8. CO- PO and CO-PSO mapping
9. Course Overview
10. List of Experiments
11. DOs and DON’Ts
12. General Safety Precautions
13. Guidelines for students for report preparation
14. Lab assessment criteria
15. Details of Conducted Experiments
16. Lab Experiments

Department of Information Technology 2024-25


C212: Object Oriented Programming with Java Lab (BCS-452)

Vision and Mission of the Institute


Vision:
“JSS Academy of Technical Education Noida aims to become an Institution of excellence in
imparting quality Outcome Based Education that empowers the young generation with
Knowledge, Skills,Research, Aptitude and Ethical values to solve Contemporary Challenging
Problems”

Mission:
M1: Develop a platform for achieving globally acceptable level of intellectual acumen and
technological competence.
M2: Create an inspiring ambience that raises the motivation level for conducting quality
research.
M3: Provide an environment for acquiring ethical values and positive attitude.

Vision and Mission of the Department


Vision:
“To become a Centre of Excellence in teaching and research in Information Technology for
producing skilled professionals having a zeal to serve society”

Mission:
M1: To create an environment where students can be equipped with strong fundamental
concepts, programming and problem solving skills.
M2: To provide an exposure to emerging technologies by providing hands on experience for
generating competent professionals.
M3: To promote Research and Development in the frontier areas of Information Technology
and encourage students for pursuing higher education
M4: To inculcate in students ethics, professional values, team work and leadership skills.

Department of Information Technology 2024-25


C212: Object Oriented Programming with Java Lab (BCS-452)

Programme Educational Objectives (PEOs)


PEO1: To provide students with a sound knowledge of mathematical, scientific and
engineering fundamentals required to solve real world problems.

PEO2: To develop research oriented analytical ability among students and to prepare them
for making technical contribution to the society.

PEO3: To develop in students the ability to apply state-of-the–art tools and techniques for
designing software products to meet the needs of Industry with due consideration for
environment friendly and sustainable development.

PEO4:To prepare students with effective communication skills, professional ethics and
managerial skills.

PEO5: To prepare students with the ability to upgrade their skills and knowledge for life-
long learning.

Department of Information Technology 2024-25


C212: Object Oriented Programming with Java Lab (BCS-452)

Programme Outcomes (POs)


PO1: Engineering knowledge: Apply the knowledge of mathematics, science, engineering
fundamentals, and an engineering specialization to the solution of complex
engineering problems.
PO2: Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of
mathematics, natural sciences, and engineering sciences.
PO3: Design/development of solutions: Design solutions for complex engineering problems
and design system components or processes that meet the specified needs with
appropriate consideration for the public health and safety, and the cultural, societal,
and environmental considerations.
PO4: Conduct investigations of complex problems: Use research-based knowledge and
research methods including design of experiments, analysis and interpretation of data,
and synthesis of the information to provide valid conclusions.
PO5: Modern tool usage: Create, select, and apply appropriate techniques, resources, and
modern engineering and IT tools including prediction and modeling to complex
engineering activities with an understanding of the limitations.
PO6: The engineer and society: Apply reasoning informed by the contextual knowledge to
assess societal, health, safety, legal and cultural issues and the consequent
responsibilities relevant to the professional engineering practice.
PO7: Environment and sustainability: Understand the impact of the professional
engineering solutions in societal and environmental contexts, and demonstrate the
knowledge of, and need for sustainable development.
PO8: Ethics: Apply ethical principles and commit to professional ethics and responsibilities
and norms of the engineering practice.
PO9: Individual and team work: Function effectively as an individual, and as a member or
leader in diverse teams, and in multidisciplinary settings.
PO10: Communication: Communicate effectively on complex engineering activities with
the engineering community and with society at large, such as, being able to
comprehend and write effective reports and design documentation, make effective
presentations, and give and receive clear instructions.
PO11: Project management and finance: Demonstrate knowledge and understanding of
the engineering and management principles and apply these to one’s own work, as a
member and leader in a team, to manage projects and in multidisciplinary environments.
PO12: Life-long learning: Recognize the need for, and have the preparation and ability to
engage in independent and life-long learning in the broadest context of technological
change.

Department of Information Technology 2024-25


C212: Object Oriented Programming with Java Lab (BCS-452)

Program Specific Outcomes (PSOs)


PSO1: Analyze, identify and clearly define a problem for solving user needs by selecting,
creating and evaluating a computer based system through an effective project plan.

PSO2: Design, implement and evaluate processes, components and/or programs using
modern techniques, skills and tools of core Information Technologies to effectively
integrate secure IT-based solutions into the user environment.

PSO3: Develop impactful IT solutions by using research based knowledge and research
methods in the fields of integration, interface issues, security & assurance and
implementation.

Department of Information Technology 2024-25


C212: Object Oriented Programming with Java Lab (BCS-452)

University Syllabus
1. Use Java compiler and eclipse platform to write and execute java program.
2. Creating simple java programs using command line arguments
3. Understand OOP concepts and basics of Java programming.
4. Create Java programs using inheritance and polymorphism.
5. Implement error-handling techniques using exception handling and multithreading.
6. Create java program with the use of java packages.
7. Construct java program using Java I/O package.
8. Create industry oriented application using Spring Framework.
9. Test RESTful web services using Spring Boot.
10. Test Frontend web application with Spring Boot

Department of Information Technology 2024-25


C212: Object Oriented Programming with Java Lab (BCS-452)

Course Outcomes (COs)


Upon successful completion of the course, the students will be able to
C212.1: Implement object oriented concepts such as objects, class abstraction and message
passing.
C212.2: Implement the friend function and function overloading
C212.3: Implement Operator overloading, Inheritance and method overriding.
C212.4: Implement virtual function to achieve Run time polymorphism.
C212.5 Implement the various functions on String, Apply I/O operation to handle file system.

CO-PO Mapping:
PO 1 PO 2 PO 3 PO 4 PO 5 PO 6 PO 7 PO 8 PO 9 PO1 0 PO1 1 P1 2

C212.3 3 3 3 3 2 2 3 3
1
C212.3 3 3 3 3 2 2 3 3
2
C212.3 3 3 3 3 2 2 3 3
3
C212.3 3 3 3 3 2 2 3 3
4
C212.3 3 3 3 3 2 2 3 3
5

CO-PSO Mapping

PSO1PSO2
C212.1 2 3
C212.2 2 3
C212.3 2 3
C212.4 2 3
C212.5 2 3

Department of Information Technology 2024-25


C212: Object Oriented Programming with Java Lab (BCS-452)

Course Overview

This “JAVA PROGRAMMING” lab manual is intended to teach the basic Java Applications
and Java Applets. Readers of this manual must be familiar with the basic syntax of C or C++
and Object Oriented features. Java is increasingly becoming the default choice of the IT
industry especially industries involved in software development at system level. Therefore,
for proper development of Java Applications among the students, this practical lab manual
has been prepared. The manual contains the exercise programs and their solution for easy &
quick understanding of the students. We hope that this practical manual will be helpful for
students of IT for understanding the subject from the point of view of applied aspects. There
is always scope for improvement in the manual. We would appreciate to receive valuable
suggestions from readers and users for future use.

Department of Information Technology 2024-25


C212: Object Oriented Programming with Java Lab (BCS-452)

List of Experiments mapped with COs

Sl.no. List of Experiments Course


Outcome
s

1 Use Java compiler and eclipse platform to write C212.1


and execute java program.

2 Creating simple java programs using command C212.1


line arguments

3 Understand OOP concepts and basics of Java C212.2


programming.

4 Create Java programs using inheritance and C212.3


polymorphism.

5 Implement error-handling techniques using C212.3


exception handling and multithreading.

6 Create java program with the use of java C212.4


packages.

7 Construct java program using Java I/O package. C212.4

8 Create industry oriented application using Spring C212.5


Framework.

Department of Information Technology 2024-25


C212: Object Oriented Programming with Java Lab (BCS-452)

9 Test RESTful web services using Spring Boot. C212.5

10 Test Frontend web application with Spring Boot C212.5

DOs and DON’Ts


Dos
1. Login-on with your username and password.
2. Log off the Computer every time when you leave the Lab.
3. Arrange your chair properly when you are leaving the lab.
4. Put your bags in the designated area.
5. Ask permission to print.

DON’Ts
1. Do not share your username and password.
2. Do not remove or disconnect cables or hardware parts.
3. Do not personalize the computer setting.
4. Do not run programs that continue to execute after you log off.
5. Do not download or install any programs, games or music on computer in Lab.
6. Personal Internet use chat room for Instant Messaging (IM) and Sites Strictly
Prohibited.
7. No Internet gaming activities allowed.
8. Tea, Coffee, Water & Eatables are not allowed in the Computer Lab.

Department of Information Technology 2024-25


C212: Object Oriented Programming with Java Lab (BCS-452)

General Safety Precautions


Precaution (In case of Injury or Electric Shock)

1. To break the victim with live electric source .Use an insulator such as fire wood or
plastic to break the contact. Do not touch the victim with bare hands to avoid the risk
of electrifying yourself.
2. Unplug the risk of faulty equipment. If main circuit breaker is accessible, turn the
circuit off.
3. If the victim is unconscious, start resuscitation immediately, use your hands to press
the chest in and out to continue breathing function. Use mouth-to-mouth resuscitation
if necessary.
4. Immediately call medical emergency and security. Remember! Time is critical; be best.

Ambulance : 9810611477(Fortis Ambulance)


120-2400222(Fortis
Ambulance) Security: 260(Gate No.1)
230(Gate No.2)

Precaution(In case of Fire)


1. Turn the equipment off. If power switch is not immediately accessible, take plug off.
2. If fire continues, try to curb the fire if possible by using the fire extinguisher or by
covering it with a heavy cloth if possible isolate the burning equipment from the other
surrounding equipment.
3. Sound the fire alarm by activating the nearest alarm switch located in the hallway.
4. Call security and emergency department immediately:
Emergency : 219 (Reception)
298(Health Center)

Security : 260 (Gate No.1)


230 (Gate No.2)

Department of Information Technology 2024-25


C212: Object Oriented Programming with Java Lab (BCS-452)

Guidelines to students for report preparation


All students are required to maintain a record of the experiments conducted by them.
Guidelines for its preparation are as follows: -

1) All files must contain a title page followed by an index page. The files will not be signed
by the faculty without an entry in the index page.

2) Student’s Name, Roll number and date of conduction of experiment must be written on all
pages.

3) For each experiment, the record must contain the following

(i) Aim/Objective of the experiment

(ii) Equipment’s required

(iii) Pre-experiment work (as given by the faculty)

(iv) Observation table

(v) Results/ output

Note:

1. Students must bring their lab record along with them whenever they come for the lab.

2. Students must ensure that their lab record is regularly evaluated.

Department of Information Technology 2024-25


C212: Object Oriented Programming with Java Lab (BCS-452)

Lab Assessment Criteria


An estimated 10 lab classes are conducted in a semester for each lab course. These lab classes are
assessed continuously. Each lab experiment is evaluated based on 5 assessment criteria as
shown in following table. Assessed performance in each experiment is used to compute CO
attainment as well as internal marks in the lab course.

Grading Needs
Exemplary (4) Competent
Criteria Improvement Poor (1)
(3)
(2)
AC1:
Complete procedure Underlined
Pre-Lab written Underlined concept
with concept is
Not able to write
work (for last is not clearly
underlined written but concept and
lab class, this understood
concept procedure
is is procedure
may be assessed
properly written incomplete
through viva)
Assigned problem
Assigned problem
is
is
properly
properly
analyzed, correct
AC2: analyzed, Assigned problem
solution
Program correct is properly Assigned problem
designed,
Writing/ solution analyzed & is
appropriate
Modeling designed, correct solution properly
language
appropriate designed analyzed
constructs/ tools
language
are applied,
constructs/
Program/solution
tools are
written is
applied
readable
Unable to
Able Is dependent totally
to
understand the
AC3: identify errors/ on
Able to identify reason for
Identification & bugs andsomeone for
errors/ bugs and errors/ bugs even
Removal of remove them identification of
remove them after they are
errors/ bugs with little bit errors/ bugs and
explicitly
of guidance their removal
pointed out
All variants of
All variants of Only few
input /output are input /output variants of input Solution is not well
AC4:Execution& tested, Solution is are not tested,/output are demonstrated
Demonstration well However, tested, and
demonstrated and solution is Solution is well implemented
implemented well demonstrated
demonstrated

Department of Information Technology 2024-25


C212: Object Oriented Programming with Java Lab (BCS-452)

concept is clearly and but concept is not


explained implemented implemented clearly
concept is concept is not explained
clearly clearly
explained explained
More than 70
Less than 40
% of the
Less than 70 % % of the
assigned
All assigned of the assigned assigned
problems are
problems are well problems are problems are
well recorded
recorded with well recorded well recorded
with objective,
objective, design with objective, with objective,
design
constructs and design contracts design
contracts and
AC5:Lab Record solution along and solution contracts and
solution along
Assessment with along with solution along
with
Performance Performance with
Performance
analysis using all analysis is done Performance
analysis is
variants of input with all variants analysis is
done with all
and output of input and done with all
variants of
output variants of
input and
input and
output
output

Department of Information Technology 2024-25


C212: Object Oriented Programming with Java Lab (BCS-452)

LAB EXPERIMENTS

Department of Information Technology 2024-25


C212: Object Oriented Programming with Java Lab (BCS-452)

LAB EXPERIMENT 1

OBJECTIVE: Use Java Compiler and Eclipse platform to write and execute java
program.

BRIEF DISCRIPTION: Writing a Java program in Eclipse or NetBeans can be very


exciting for you, especially if you are new to programming or just starting your coding. We
can edit, compile, run, and debug Java Programs using Eclipse and NetBeans.
Eclipse and NetBeans are two free popular integrated development environments for writing
Java programs. Both are easy to learn if you follow simple instructions.
We recommend that you use either one for writing Java programs. In the first section, we will
use Eclipse to develop a simple Java program.
We will guide you to essential instructions step by step to new users to create a project, create
a class, compile, and run a class in Eclipse.
PRE-EXPERIMENT QUESTIONS:
1. What is the compilation and execution process of a Java program?
2. How do you compile and execute in Java?
3. Which component is used to compile and execute Java program?
4. When we compile a Java program the result can be executed?

Requirements for Developing Simple Java Program in Eclipse

Following are some useful instructions needed for developing and executing a program in
java:
a) Install the Eclipse IDE. If you don’t have installed it, download the Eclipse IDE and install
it. For this, go to this tutorial: Download and Install Eclipse IDE for Java
Ad
b) Writing the java program.
c) Compiling java program.
d) Run java program.
Hope that you have successfully installed Eclipse IDE by following all instructions. Now, we
will understand to create a java project in Eclipse.

How to create Java Project in Eclipse?

Before creating Java programs in Eclipse IDE, we need to first create a project. A project is
like a folder structure that holds Java programs and all supporting files. We need to create
a project only once.
Follow all the steps below to create a Java project in Eclipse:

Department of Information Technology 2024-25


C212: Object Oriented Programming with Java Lab (BCS-452)

1. First of all, open Eclipse IDE and choose File > New > Java Project to display the New
Project wizard, as shown in Figure.

2. A new project wizard will be displayed. Select java project and then click on Next button
as shown in the below figure.

3. Type Java Project in the Project name field. As we type, the location field will be
automatically set by default. You may also customize the location for your project. Look
at the below figure to understand better.

Department of Information Technology 2024-25


C212: Object Oriented Programming with Java Lab (BCS-452)

4. Make sure that you chose the options “Use project folder as root for sources and
class files” so that the .java and .class files are in the same folder for easy access.
5. Click on the Finish button to create the project, as shown in the above Figure.
Now java project is created with the “src” folder as shown in the below figure. The next step is
to create a package folder.

Department of Information Technology 2024-25


C212: Object Oriented Programming with Java Lab (BCS-452)

How to create Java Package in Eclipse?

Follow all the steps below to create a package in java in Eclipse IDE:
1. Right-click on the newly created Java project > New > Package. A new java package
wizard will be open as shown in the below figure.

2. Type a package name “javaProgram” and click on Finish button. A package folder named
javaProgram is created on the left side.

How to create Java Class in Eclipse?

After the creation of package in the java project, we can create a program in java in the java
project using the following steps:
1. Right-click on package name “javaProgram” and choose File > New > Class to display the
New Java Class wizard.

Department of Information Technology 2024-25


C212: Object Oriented Programming with Java Lab (BCS-452)

2. Type Hello in the Name field > check the option public static void main(String[] args)
as shown in the below figure.

3. Click on Finish button to produce template for the program source code named Hello.java.
A class named Hello.java will be created below the package name on the left-hand side.
Now we will write the first simple java program in the template as written in the following
source code.
Program source code:
package javaProgram;

public class Hello {

public static void main(String[] args)

System.out.println("Hello World");

We have developed a simple java program in the Eclipse IDE. The next step is compiling and
executing a java program.

How to Compile and Run Java Program in Eclipse?

Department of Information Technology 2024-25


C212: Object Oriented Programming with Java Lab (BCS-452)

To run java program, right-click the class in the project to display a context menu. Choose
Run As > Java Application in the context menu to run java program.
The output is displayed in the Console pane, as shown in the below figure.

Input:
Java program with finite set of Input.

Output:
Program specific containing finite set of sequence.

POST –EXPERIMENT QUESTIONS:

1. What happens when the following program is compiled and run? Select the one
correct answer?
public class example
{ int i[] = {0};
public static void main(String args[]) {
int i[] = {1};
change_i(i);
System.out.println(i[0]);
}
public static void change_i(int i[])
{ int j[] = {2};
i = j;
}
}
A .The program does not compile.

B. prints 0

C. prints 1

D. prints 2

Correct Answer: C

Department of Information Technology 2024-25


C212: Object Oriented Programming with Java Lab (BCS-452)

LAB EXPERIMENT 2

OBJECTIVE: Creating Simple java programs using command line arguments.

BRIEF DESCRIPTION: The java command-line argument is an argument i.e. passed at the
time of running the java program.

The arguments passed from the console can be received in the java program and it can be
used as an input.

So, it provides a convenient way to check the behavior of the program for the different
values. You can pass N (1,2,3 and so on) numbers of arguments from the command prompt.

PRE-EXPERIMENT QUESTIONS:
What are command line arguments with example?
Which data type is used to store command line arguments?
Which of the following is used to handle command line arguments?
What are the properties of command line arguments?

Simple example of command-line argument in java

In this example, we are receiving only one argument and printing it. To run this java program, you
must pass at least one argument from the command prompt.
1. class CommandLineExample{
2. public static void main(String args[]){
3. System.out.println("Your first argument is: "+args[0]);
4. }
5. }
1. compile by > javac CommandLineExample.java
2. run by > java CommandLineExample sonoo
Output: Your first argument is: sonoo

Input:
Java program
Output:
Finite set of output.
POST-EXPERIMENT QUESTIONS:
1. What is a command line argument in Java with example?
2. How many command line arguments we can pass in Java?
3. Which data type is used to store command line arguments in Java?
4. What are the two strings as command line arguments in Java?

Department of Information Technology 2024-25


C212: Object Oriented Programming with Java Lab (BCS-452)

LAB EXPERIMENT 3

OBJECTIVE: Understand OOP Concepts and basics of Java Programming.

BRIEF DESCRIPTION:

Java OOPs Concepts

Simula is considered the first object-oriented programming language. The programming


paradigm where everything is represented as an object is known as a truly object-oriented
programming language.

Smalltalk is considered the first truly object-oriented programming language.

The popular object-oriented languages are Java, C#, PHP, Python, C++, etc.

The main aim of object-oriented programming is to implement real-world entities, for example,
object, classes, abstraction, inheritance, polymorphism, etc.

OOPs (Object-Oriented Programming System)

Object means a real-world entity such as a pen, chair, table, computer, watch, etc. Object-
Oriented Programming is a methodology or paradigm to design a program using classes
and objects. It simplifies software development and maintenance by providing some
concepts:

o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation

Apart from these concepts, there are some other terms which are used in Object-Oriented
design:

o Coupling
o Cohesion
o Association
o Aggregation
o Composition

Department of Information Technology 2024-25


C212: Object Oriented Programming with Java Lab (BCS-452)

Object

Any entity that has state and behavior is known as an object. For example, a chair, pen, table,
keyboard, bike, etc. It can be physical or logical.

An Object can be defined as an instance of a class. An object contains an address and takes up
some space in memory. Objects can communicate without knowing the details of each other's
data or code. The only necessary thing is the type of message accepted and the type of
response returned by the objects.

Example: A dog is an object because it has states like color, name, breed, etc. as well as
behaviors like wagging the tail, barking, eating, etc.

Class

Collection of objects is called class. It is a logical entity.

A class can also be defined as a blueprint from which you can create an individual object. Class
doesn't consume any space.

Inheritance

When one object acquires all the properties and behaviors of a parent object, it is known as
inheritance. It provides code reusability. It is used to achieve runtime polymorphism.

Department of Information Technology 2024-25


C212: Object Oriented Programming with Java Lab (BCS-452)

Polymorphism

If one task is performed in different ways, it is known as polymorphism. For example: to


convince the customer differently, to draw something, for example, shape, triangle, rectangle,
etc.

In Java, we use method overloading and method overriding to achieve polymorphism.

Another example can be to speak something; for example, a cat speaks meow, dog barks
woof, etc.

Abstraction

Hiding internal details and showing functionality is known as abstraction. For example phone
call, we don't know the internal processing.

In Java, we use abstract class and interface to achieve abstraction.

Encapsulation

Binding (or wrapping) code and data together into a single unit are known as encapsulation.
For example, a capsule, it is wrapped with different medicines.

A java class is the example of encapsulation. Java bean is the fully encapsulated class
because all the data members are private here.

Coupling

Coupling refers to the knowledge or information or dependency of another class. It arises


when classes are aware of each other. If a class has the details information of another class,
there is strong coupling. In Java, we use private, protected, and public modifiers to display
the visibility level of a class, method, and field. You can use interfaces for the weaker
coupling because there is no concrete implementation.

Cohesion

Cohesion refers to the level of a component which performs a single well-defined task. A
single well-defined task is done by a highly cohesive method. The weakly cohesive method
will split the task into separate parts. The java.io package is a highly cohesive package
because it has

Department of Information Technology 2024-25


C212: Object Oriented Programming with Java Lab (BCS-452)

I/O related classes and interface. However, the java.util package is a weakly cohesive
package because it has unrelated classes and interfaces.

Association

Association represents the relationship between the objects. Here, one object can be
associated with one object or many objects. There can be four types of association between
the objects:

o One to One
o One to Many
o Many to One, and
o Many to Many

Let's understand the relationship with real-time examples. For example, One country can
have one prime minister (one to one), and a prime minister can have many ministers (one to
many). Also, many MP's can have one prime minister (many to one), and many ministers can
have many departments (many to many).

Association can be undirectional or bidirectional.

Aggregation

Aggregation is a way to achieve Association. Aggregation represents the relationship where


one object contains other objects as a part of its state. It represents the weak relationship
between objects. It is also termed as a has-a relationship in Java. Like, inheritance represents
the is-a relationship. It is another way to reuse objects.

Composition

The composition is also a way to achieve Association. The composition represents the
relationship where one object contains other objects as a part of its state. There is a strong
relationship between the containing object and the dependent object. It is the state where
containing objects do not have an independent existence. If you delete the parent object, all
the child objects will be deleted automatically.

PRE-EXPERIMENT QUESTIONS:
1. What are 4 types of OOPs?
2. What are the 5 aspects of OOP?
3. Why polymorphism is used in OOPS?
4. Why do we use OOP?

Department of Information Technology 2024-25


C212: Object Oriented Programming with Java Lab (BCS-452)

Advantage of OOPs over Procedure-oriented programming language

1) OOPs makes development and maintenance easier, whereas, in a procedure-oriented


programming language, it is not easy to manage if code grows as project size increases.

2) OOPs provides data hiding, whereas, in a procedure-oriented programming language,


global data can be accessed from anywhere.

Figure: Data Representation in Procedure-Oriented Programming

Figure: Data Representation in Object-Oriented Programming.

3) OOPs provides the ability to simulate real-world event much more effectively. We can
provide the solution of real word problem if we are using the Object-Oriented Programming
language.

What is the difference between an object-oriented programming language and object-based


programming language?

Object-based programming language follows all the features of OOPs except Inheritance.
JavaScript and VBScript are examples of object-based programming languages.

Department of Information Technology 2024-25


C212: Object Oriented Programming with Java Lab (BCS-452)

Input:
Java Program

Output:
Finite set of Output sequence.

POST-EXPERIMENT QUESTIONS:

1. How is Java different from C?


2. What is Java?
3. Explain different data types in Java
4. What is Class Loader?
5. Can we declare pointer in Java?
6. What is JIT?
7. Define copy constructor in Java
8. Define object in Java
9. JDK
10. JVM
11. What is aggregation?
12. Which Java operator is right-associative?

Department of Information Technology 2024-25


C212: Object Oriented Programming with Java Lab (BCS-452)

LAB EXPERIMENT 4

OBJECTIVE: Create Java programs using Inheritance and Polymorphism. BRIEF

DESCRIPTION:

Inheritance in Java

Inheritance is an important feature of object-oriented programming in Java. It allows for one


class (child class) to inherit the fields and methods of another class (parent class). For
instance, we might want a child class Dog to inherent traits from a more general parent
class Animal.

When defining a child class in Java, we use the keyword extends to inherit from a parent class.
// Parent Class
class Animal {
// Animal class members
}

// Child Class
class Dog extends Animal {
// Dog inherits traits from Animal

// additional Dog class members


}

Main() method in Java

In simple Java programs, you may work with just one class and one file. However, as your
programs become more complex you will work with multiple classes, each of which requires
its own file. Only one of these files in the Java package requires a main() method, and this is
the file that will be run in the package.

For example, say we have two files in our Java package for two different classes:

 Shape, the parent class.


 Square, the child class.

If the Java file containing our Shape class is the only one with a main() method, this is the file
that will be run for our Java package.
// Shape.java file
class Shape {
public static void main(String[] args) {
Square sq = new Square();

Department of Information Technology 2024-25


C212: Object Oriented Programming with Java Lab (BCS-452)

}
}

// Square.java file
class Square extends Shape {

super() in Java

In Java, a child class inherits its parent’s fields and methods, meaning it also inherits the
parent’s constructor. Sometimes we may want to modify the constructor, in which case we
can use the super() method, which acts like the parent constructor inside the child class
constructor.

Alternatively, we can also completely override a parent class constructor by writing a new
constructor for the child class.
// Parent class
class Animal {
String sound;
Animal(String snd) {
this.sound = snd;
}
}

// Child class
class Dog extends Animal {
// super() method can act like the parent constructor inside the child class constructor.
Dog() {
super("woof");
}
// alternatively, we can override the constructor completely by defining a new constructor.
Dog() {
this.sound = "woof";
}
}

Protected and Final keywords in Java

When creating classes in Java, sometimes we may want to control child class access to parent
class members. We can use the protected and final keywords to do just that.

protected keeps a parent class member accessible to its child classes, to files within its own
package, and by subclasses of this class in another package.

Adding final before a parent class method’s access modifier makes it so that any child classes
cannot modify that method - it is immutable.

Department of Information Technology 2024-25


C212: Object Oriented Programming with Java Lab (BCS-452)

class Student {
protected double gpa;
// any child class of Student can access gpa

final protected boolean isStudent() {


return true;
}
// any child class of Student cannot modify isStudent()
}

PRE-EXPERIMENT QUESTIONS:

1. What is Polymorphism?

2. What is Inheritance?

3. Differentiate between Function Overloading and Function Overriding?

Polymorphism in Java

Java incorporates the object-oriented programming principle of polymorphism.

Polymorphism allows a child class to share the information and behavior of its parent class
while also incorporating its own functionality. This allows for the benefits of simplified
syntax and reduced cognitive overload for developers.

// Parent class
class Animal {
public void greeting() {
System.out.println("The animal greets you.");
}
}

// Child class
class Cat extends Animal {
public void greeting() {
System.out.println("The cat meows.");
}
}

class MainClass {
public static void main(String[] args) {
Animal animal1 = new Animal(); // Animal object
Animal cat1 = new Cat(); // Cat object
animal1.greeting(); // prints "The animal greets you."

Department of Information Technology 2024-25


C212: Object Oriented Programming with Java Lab (BCS-452)

cat1.greeting(); // prints "The cat meows."


}
}

Input:
Java code
Output :
Finite set of output sequence.
POST-EXPERIMENT QUESTIONS:
1. How does inheritance used in polymorphism in Java?
2. Which polymorphism concept is used in inheritance question?
3. Does polymorphism require inheritance?
4. Is inheritance and overriding required for polymorphism?

Department of Information Technology 2024-25


C212: Object Oriented Programming with Java Lab (BCS-452)

LAB EXPERIMENT 5

OBJECTIVE: Implement error-handling techniques using exception handling and


Multithreading.

BRIEF DESCRIPTION:
Exception handling and multithreading are two essential concepts in the Java programming
language that are used to improve the performance and reliability of a program. Exception
handling is a mechanism that allows a program to handle errors and exceptional events,
while multithreading is a technique that enables a program to perform multiple tasks
simultaneously. In this article, we will discuss the basics of exception handling and
multithreading in Java and how they can be used to improve the performance and reliability
of your programs.

PRE-EXPERIMENT QUESTIONS:

1. What are error handling techniques?


2. What is error handling in Java?
3. What are different types of exception handling technique in Java?
4. What is the best practice for error handling in Java?

Try-catch-finally blocks are used in Java to handle exceptions. The catch block provides intended
to catch exceptions, and the try block is utilized to contain code that might throw them. Any
resources spent in the try block are cleaned up in the finally block. For example, the
following code snippet shows how to handle a FileNotFoundException, which is thrown
when a file that is to be read cannot be found:

try {
FileInputStream file = new FileInputStream("file.txt");
int data = file.read();
// do something with data
} catch (FileNotFoundException e)
{ System.err.println("File not found: " +
e.getMessage());
} finally {
file.close();
}
In this example, the try block is used to open the file and read its contents, while the catch block
is used to handle the FileNotFoundException that may be thrown. No matter whether this
exception was thrown, closing the file is done in the finally block.

Department of Information Technology 2024-25


C212: Object Oriented Programming with Java Lab (BCS-452)

Another important feature of exception handling in Java is the ability to throw custom
exceptions. It allows you to create your own exception classes that can be thrown and caught
in your code. For example, you might create a custom exception class called
InvalidDataException, which is thrown when the data read from a file is invalid:
class InvalidDataException extends Exception
{ public InvalidDataException(String message) {
super(message);
}
}
In this example, the InvalidDataException class is a subclass of the Exception class, and it
takes a message as its constructor argument. Just like any other Java exception, such
customized exception can indeed be thrown and handled in the same manner.
When a class inherits the thread class as well as overrides the run() method, a new thread is
created in this instance. This activates the new thread's entry point that was generated in the
class that extended the thread class. Additionally, the program's thread is launched and
operated using the start() method.
File name: Aman.java
// Java programme that uses threads and exceptions
// Importing Files and Classes
import java.io.*;
// The parent Class, which the child Class (Thread) inherits (Aman)
class Aman extends Thread {
// The ability to determine whether a thread is active
public void run()
{
System.out.println("It is a running thread");
// iterating with a for loop
for (int s = 0; s < 10; ++s) {
System.out.println("running the thread loop" + s);
}
}
// Loading the Main Driver Method
public static void main(String[] args)
{
// attempt-catch block for exception detection
try {

Department of Information Technology 2024-25


C212: Object Oriented Programming with Java Lab (BCS-452)

// Creation of the new thread


Aman srj = new Aman();
throw new RuntimeException();
}
// To manage exceptions, use a catch block.
catch (Exception e) {
System.out.println(
" There is no support for another thread. ");
}
}
}
Output:
There is no support for another thread
Now that we have covered exception handling, let's turn our attention to multithreading.
Multithreading is a technique that allows a program to perform multiple tasks
simultaneously, by creating and managing multiple threads of execution. Creating and
managing threads in Java is done and used the Thread class as well as the Runnable interface.
The Executable interface specifies a single function, run(), that includes the code that is
going to be performed by the thread, whereas the Thread class offers techniques for
initiating, stopping, and regulating the execution of such a thread.
For example, the following code snippet shows how to create and start a new thread:
class MyThread extends Thread
{ public void run() {
// code to be executed by the thread
}
}
MyThread myThread = new MyThread();
myThread.start();
As shown, the run() method is overridden by the MyThread class, which extends the Thread
class, to specify the thread's intended course of action. The start() method is then invoked in
order to start the thread's execution, after which an instance of such MyThread class is
created.
Input:
Java program containing exception.
Output:
Finite stream of output

Department of Information Technology 2024-25


C212: Object Oriented Programming with Java Lab (BCS-452)

POST EXPERIMENT QUESTIONS:


1. How do you handle exceptions that occur in a multi threaded application?
2. How exception handling can be implemented for handling multiple exceptions give an
example?
3. Which type of errors is handled by exception handling mechanism?

Department of Information Technology 2024-25


C212: Object Oriented Programming with Java Lab (BCS-452)

LAB EXPERIMENT 6

OBJECTIVE: Create java program with the use of java packages.

BRIEF DESCRIPTION:

In Java, a package is a group of classes, interfaces, enumeration, and annotations. Java contains
many pre-defined packages such as java.lang, java.io, java.net, etc. When we create any
Java program the java.lang package is imported by default. We need not to write the
package name at the top of the program. We can also create our own package by providing
the name that we want. In this section, we will learn how to create a package in Java.

We use package for the following reasons:

o The package makes the search easier for the classes and interfaces.
o It provides a fully qualified name that avoids naming conflicts.
o It also controls access.
o It organizes classes in a folder structure.
o It improves code reusability.
o Programmer can group classes and interfaces into a related package.

PRE-EXPERIMENT QUESTIONS
1. What are the basics of packages in Java?
2. What are the 6 packages in Java?
3. Which is the main package in Java?
4. How to import packages in Java?

Creating a Package

To create a package, follow the steps given below:

o Choose a package name according to the naming convention.


o Write the package name at the top of every source file (classes, interface,
enumeration, and annotations).
o Remember that there must be only one package statement in each source file.

Package Naming Convention

We follow the naming convention rules to name a package. Java has some predefined packages
and also allows us to create our own package. So, it is possible that a programmer can create
a class with the same name as a package that already contains that type in a predefined
package.
Department of Information Technology 2024-25
C212: Object Oriented Programming with Java Lab (BCS-452)

Let's take an example of the Rectangle class.

Suppose, a programmer creates a class with the name Rectangle in the package shape. The
class with the same name is already present in java.awt package. The compiler allows both
classes if they belong to the different packages. The fully qualified name of each class
contains the package name that differentiate both Rectangle classes. Therefore, the package
name of the user-defined class will be shape.Rectangle and the package name of the
predefined class will be java.awt.Rectangle.

o Package name must be in lower case that avoids conflict with the name of classes and
interfaces.
o Organizations used their internet domain name to define their package names. For
example, com.javatpoint.mypackage. Sometimes, the organization also uses the
region after the company name to name the package. For
example, com.javatpoint.region.mypackage.
o We use underscore in the package name if the domain name contains hyphen or other
special characters or package names begin with a digit or reserved keyword.

Domain Name Package Name Prefix

Hyphenated-name.example.org org.example.hyphenated_name

Example.int int_.example

123name.example.com com.example._123name

Importing a Package

If we want to use a package in Java program it is necessary to import that package at the top
of the program by using the import keyword before the package name.

Syntax:

1. import packageName;

Let's create a calculator program in Java using the package.

Add.java

1. package p1;
2. import java.util.*;
3. public class Add
4. {
5. int s;
6. public void sum()
7. {

Department of Information Technology 2024-25


C212: Object Oriented Programming with Java Lab (BCS-452)

8. System.out.print("Enter the first number: ");


9. Scanner scan=new Scanner(System.in);
10. int x=scan.nextInt();
11. System.out.print("Enter the second number: ");
12. Scanner scan1=new Scanner(System.in);
13. int y=scan1.nextInt();
14. s=x+y;
15. System.out.println("sum="+s);
16. }
17. }

Sub.java

1. package p2;
2. import java.util.*;
3. public class Sub
4. {
5. int d;
6. public void diff()
7. {
8. System.out.print("Enter the first number: ");
9. Scanner scan=new Scanner(System.in);
10. int x=scan.nextInt();
11. System.out.print("Enter the second number: ");
12. Scanner scan1=new Scanner(System.in);
13. int y=scan1.nextInt();
14. d=x-y;
15. System.out.println("Difference="+d);
16. }
17. }

Mult.java

1. package p3;
2. import java.util.*;
3. public class Mult
4. {
5. int m;
6. public void pro()
7. {
8. System.out.print("Enter the first number: ");
9. Scanner scan=new Scanner(System.in);
10. int x=scan.nextInt();

Department of Information Technology 2024-25


C212: Object Oriented Programming with Java Lab (BCS-452)

11. System.out.print("Enter the second number: ");


12. Scanner scan1=new Scanner(System.in);
13. int y=scan1.nextInt();
14. m=x*y;
15. System.out.println("Product="+m);
16. }
17. }

Div.java

1. package p4;
2. import java.util.*;
3. public class Div
4. {
5. int q;
6. public void divd()
7. {
8. System.out.print("Enter the first number: ");
9. Scanner scan=new Scanner(System.in);
10. int x=scan.nextInt();
11. System.out.print("Enter the second number: ");
12. Scanner scan1=new Scanner(System.in);
13. int y=scan1.nextInt();
14. q=x/y;
15. System.out.println("Division="+q);
16. }
17. }

Now, we are going to create the main class named Calculator. In this class, we have imported all
the packages that we have created above. It includes all the classes in the Calculator class.

Calculator.java

1. package p5;
2. //importing pre-defined package
3. import java.util.*;
4. //importing user-defined package
5. import p1.Add;
6. import p2.Sub;
7. import p3.Mult;
8. import p4.Div;
9. public class Calculator
10. {
11. public static void main(String args[])
12. {

Department of Information Technology 2024-25


C212: Object Oriented Programming with Java Lab (BCS-452)

13. System.out.print("Enter your choice: ");


14. Scanner scan=new Scanner(System.in);
15. int t=scan.nextInt();
16. switch(t)
17. {
18. case 1:
19. Add a=new Add();
20. a.sum();
21. break;
22. case 2:
23. Sub s=new Sub();
24. s.diff();
25. break;
26. case 3:
27. Mult m=new Mult();
28. m.pro();
29. break;
30. case 4:
31. Div d=new Div();
32. d.divd();
33. break;
34. }
35. }
36. }

When we compile the above program, it creates corresponding .class files in packages named p1,
p2, p3, p4, and p5, respectively.

The .class files are generated. Now, we can run the above program.

Output:

Enter your choice: 3


Enter the first number: 2

Department of Information Technology 2024-25


C212: Object Oriented Programming with Java Lab (BCS-452)

Enter the second number: 23


Product=46

Input:
Java program containing set of functionalities to create packages.

Output:
Finite set of output sequence.

POST-EXPERIMENT QUESTIONS:
1. What are the advantages of a java package?
2. Define Packages in Java?
3. Why are the packages used?
4. Can we import same package/class twice?
5. Explain the usage of Java packages?
6. What is the base class of all classes?
7. What do you think is the logic behind having a single base class for all classes?

LAB EXPERIMENT 7

Department of Information Technology 2024-25


C212: Object Oriented Programming with Java Lab (BCS-452)

OBJECTIVE: Create a java program using Java I/O package.

BRIEF DESCRIPTION:
Java brings various Streams with its I/O package that helps the user to perform all the
input-output operations. These streams support all the types of objects, data-types,
characters, files etc to fully execute the I/O operations.

Before exploring various input and output streams let’s look at 3 standard or default
streams that Java has to provide which are also most common in use:

1. System.in: This is the standard input stream that is used to read characters from the
keyboard or any other standard input device.
2. System.out: This is the standard output stream that is used to produce the result of a
program on an output device like the computer screen.
PRE-EXPERIMENT QUESTIONS
1. What is use of io package in Java?
2. What is the package for input output in Java?
3. Which three classes belong to the Java io package?

Department of Information Technology 2024-25


C212: Object Oriented Programming with Java Lab (BCS-452)

Here is a list of the various print functions that we use to output statements:
 print(): This method in Java is used to display a text on the console. This text is
passed as the parameter to this method in the form of String. This method prints the
text on the console and the cursor remains at the end of the text at the console. The
next printing takes place from just here.
Syntax:
System.out.print(parameter);
1.

 Example:

// Java code to illustrate print()

import java.io.*;

class Demo_print {

public static void main(String[] args)

// using print()

// all are printed in the

// same line

System.out.print("GfG! ");

System.out.print("GfG! ");

System.out.print("GfG! ");

Department of Information Technology 2024-25


C212: Object Oriented Programming with Java Lab (BCS-452)

 Output:
 GfG! GfG! GfG!
 println(): This method in Java is also used to display a text on the console. It prints
the text on the console and the cursor moves to the start of the next line at the
console. The next printing takes place from the next line.
Syntax:
System.out.println(parameter);
Example:

// Java code to illustrate println()

import java.io.*;

class Demo_print {

public static void main(String[] args)

// using println()

// all are printed in the

// different line

System.out.println("GfG! ");

System.out.println("GfG! ");

Department of Information Technology 2024-25


C212: Object Oriented Programming with Java Lab (BCS-452)

System.out.println("GfG! ");

Output:
GfG!
GfG!
GfG!
 printf(): This is the easiest of all methods as this is similar to printf in C. Note that
System.out.print() and System.out.println() take a single argument, but printf() may
take multiple arguments. This is used to format the output in Java.
Example:

// A Java program to demonstrate working of printf() in Java

class JavaFormatter1 {

Department of Information Technology 2024-25


C212: Object Oriented Programming with Java Lab (BCS-452)

public static void main(String args[])

int x = 100;

System.out.printf(

"Printing simple"

+ " integer: x = %d\n",

x);

// this will print it upto

// 2 decimal places

System.out.printf(

"Formatted with"

+ " precision: PI = %.2f\n",

Math.PI);

float n = 5.2f;

// automatically appends zero

// to the rightmost part of decimal

Department of Information Technology 2024-25


C212: Object Oriented Programming with Java Lab (BCS-452)

System.out.printf( "Formatte

d to "

+ "specific width: n = %.4f\n",

n);

n = 2324435.3f;

// here number is formatted from

// right margin and occupies a

// width of 20 characters

System.out.printf(

"Formatted to "

+ "right margin: n = %20.4f\n",

n);

Output:
 Printing simple integer: x = 100
 Formatted with precision: PI = 3.14
 Formatted to specific width: n = 5.2000
 Formatted to right margin: n = 2324435.2500

Department of Information Technology 2024-25


C212: Object Oriented Programming with Java Lab (BCS-452)

2. System.err: This is the standard error stream that is used to output all the error data
that a program might throw, on a computer screen or any standard output device.
This stream also uses all the 3 above-mentioned functions to output the error data:
print()
println()
printf()
Example:

// Java code to illustrate standard

// input output streams

import java.io.*;

public class SimpleIO {

public static void main(String args[])

throws IOException

// InputStreamReader class to read input

InputStreamReader inp = null;

// Storing the input in inp

inp = new InputStreamReader(System.in);

Department of Information Technology 2024-25


C212: Object Oriented Programming with Java Lab (BCS-452)

System.out.println("Enter characters, "

+ " and '0' to quit.");

char c;

do {

c = (char)inp.read();

System.out.println(c);

} while (c != '0');

Input:
GeeksforGeeks0
Output:
Enter characters, and '0' to quit.
G
e
e

Department of Information Technology 2024-25


C212: Object Oriented Programming with Java Lab (BCS-452)

k
s
f
o
r
G
e
e
k
s
0

Types of Streams:
 Depending on the type of operations, streams can be divided into two primary classes:
1. Input Stream: These streams are used to read data that must be taken as an input
from a source array or file or any peripheral device. For eg., FileInputStream,
BufferedInputStream, ByteArrayInputStream etc.

2. Output Stream: These streams are used to write data as outputs into an array or file
or any output peripheral device. For eg., FileOutputStream, BufferedOutputStream,
ByteArrayOutputStream etc.

 Depending on the types of file, Streams can be divided into two primary classes which
can be further divided into other classes as can be seen through the diagram below
followed by the explanations.

1. ByteStream: This is used to process data byte by byte (8 bits). Though it has many
classes, the FileInputStream and the FileOutputStream are the most popular ones.
The FileInputStream is used to read from the source and FileOutputStream is used
to write to the destination. Here is the list of various ByteStream Classes:
Stream class Description

BufferedInputStream It is used for Buffered Input Stream.

DataInputStream It contains method for reading java standard datatypes.

FileInputStream This is used to reads from a file

Department of Information Technology 2024-25


C212: Object Oriented Programming with Java Lab (BCS-452)

Stream class Description

InputStream This is an abstract class that describes stream input.

PrintStream This contains the most used print() and println() method

BufferedOutputStream This is used for Buffered Output Stream.

DataOutputStream This contains method for writing java standard data types.

FileOutputStream This is used to write to a file.

OutputStream This is an abstract class that describe stream output.

Example:

// Java Program illustrating the

// Byte Stream to copy

// contents of one file to another file.

import java.io.*;

public class BStream

{ public static void main(

String[] args) throws IOException

FileInputStream sourceStream = null;

Department of Information Technology 2024-25


C212: Object Oriented Programming with Java Lab (BCS-452)

FileOutputStream targetStream = null;

try {

sourceStream

= new FileInputStream("sorcefile.txt");

targetStream

= new FileOutputStream("targetfile.txt");

// Reading source file and writing

// content to target file byte by byte

int temp;

while ((

temp = sourceStream.read())

!= -1)

targetStream.write((byte)temp);

finally {

if (sourceStream != null)

sourceStream.close();

Department of Information Technology 2024-25


C212: Object Oriented Programming with Java Lab (BCS-452)

if (targetStream != null)

targetStream.close();

Output:
 Shows contents of file test.txt
 CharacterStream: In Java, characters are stored using Unicode conventions (Refer
this for details). Character stream automatically allows us to read/write data
character by character. Though it has many classes, the FileReader and the
FileWriter are the most popular ones. FileReader and FileWriter are character
streams used to read from the source and write to the destination respectively. Here
is the list of various CharacterStream Classes:
Stream class Description

BufferedReader It is used to handle buffered input stream.

FileReader This is an input stream that reads from file.

InputStreamReader This input stream is used to translate byte to character.

OutputStreamReader This output stream is used to translate character to byte.

Department of Information Technology 2024-25


C212: Object Oriented Programming with Java Lab (BCS-452)

Stream class Description

Reader This is an abstract class that define character stream input.

PrintWriter This contains the most used print() and println() method

Writer This is an abstract class that define character stream output.

BufferedWriter This is used to handle buffered output stream.

FileWriter This is used to output stream that writes to file.

 Example:

// Java Program illustrating that

// we can read a file in a human-readable

// format using FileReader

// Accessing FileReader, FileWriter,

// and IOException

import java.io.*;

public class GfG {

public static void main(

String[] args) throws IOException

FileReader sourceStream = null;

Department of Information Technology 2024-25


C212: Object Oriented Programming with Java Lab (BCS-452)

try {

sourceStream

= new FileReader("test.txt");

// Reading sourcefile and

// writing content to target file

// character by character.

int temp;

while ((

temp = sourceStream.read())

!= -1)

System.out.println((char)temp);

finally {

// Closing stream as no longer in use

if (sourceStream != null)

sourceStream.close();

Department of Information Technology 2024-25


C212: Object Oriented Programming with Java Lab (BCS-452)

Input:
Java Program
Output:
Finite sequence of output.
POST-EXPERIMENT QUESTIONS:
1. Which package is imported by default in Java?
2. What are types of package in Java?

Department of Information Technology 2024-25


C212: Object Oriented Programming with Java Lab (BCS-452)

LAB EXPERIMENT 8

OBJECTIVE: Create an industry oriented application using Spring Framework.

BRIEF DESCRIPTION:
Projects
From configuration to security, web apps to big data—whatever the infrastructure needs of your
application may be, there is a Spring Project to help you build it. Start small and use just what
you need—Spring is modular by design.

Please click on the below link for projects on Spring.


https://spring.io/projects

Department of Information Technology 2024-25


C212: Object Oriented Programming with Java Lab (BCS-452)

LAB EXPERIMENT 9

OBJECTIVE: Test RESTful web services using Spring Boot.

BRIEF DESCRITPTION:

A Spring Boot RESTful service is typically divided into three layers: Repository,
Service, and Controller. This layering helps to segregate the RESTful application
responsibilities and enabling loose coupling between the objects.

When you develop a layered RESTful application, you will also need to test the different
layers.

In this post, I will discuss testing Spring Boot RESTful Services with Spring MVC Test
and JUnit5.

The Maven POM

To start testing Spring Boot RESTful services, you need

spring-boot-starter-test, which is a starter dependency for Spring Testing.


This Spring Boot starter depenency also transitively brings in other testing dependencies
such as

Mockito
, JUnit
,
Hamcrest
,
AssertJ
.

PRE-EXPERIMENT QUESTIONS:
1. How to test Spring Boot REST service?
2. What are RESTful web services in Spring Boot?
3. How to test RESTful web services?

This is the dependency you need to add in the pom.xml file.

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>

Department of Information Technology 2024-25


C212: Object Oriented Programming with Java Lab (BCS-452)

<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
Testing the Repository Layer

This is the repository I will be testing.

@Repository
public interface ProductRepository extends JpaRepository <Product, Integer> {
}
Let’s start writing the test class,

ProductRepositoryTest
.
@ExtendWith(SpringExtension.class)
@DataJpaTest
class ProductRepositoryTest {
The first statement annotates the class with

@ExtendWith(SpringExtension.class)
. This integrates the Spring test context framework into the JUnit 5 Jupiter programming
model.
Our test will be an integration test as an external database is used. Being an integration
test, we need to load the Spring context in our test. We can do that using the

@SpringBootTest
annotation.
However, loading the entire Spring context is heavy and makes the tests slow.

Therefore, we will only load the Spring Data JPA slice of the Spring context. The

@DataJpaTest
annotation in the code does exactly that.
Next, let’s autowire the

ProductRepository
that we will test and write the
setup()
and
teardown()
methods.
@Autowired
private ProductRepository productRepository;
private Product product;
@BeforeEach
public void setUp() {
product = new Product(1,"Bat",2500);

Department of Information Technology 2024-25


C212: Object Oriented Programming with Java Lab (BCS-452)

}
@AfterEach
public void tearDown() {
productRepository.deleteAll();
product = null;
}

Test Case for Saving a Product

Let’s start writing a test for saving a product.

The test code is this.

@Test
public void givenProductToAddShouldReturnAddedProduct(){
productRepository.save(product);
Product fetchedProduct = productRepository.findById(product.getId()).get();
assertEquals(1, fetchedProduct.getId());
}

Test Case to Retrieve the List of Products

This test code tests for the retrieval of all products.

@Test
public void GivenGetAllProductShouldReturnListOfAllProducts(){
Product product1 = new Product(1,"ball",400);
Product product2 = new Product(2,"bat",500);
productRepository.save(product1);
productRepository.save(product2);
List<Product> productList = (List<Product>) productRepository.findAll();
assertEquals("bat", productList.get(1).getName());
}

Test Case to Retrieve Product by Id

This test code tests for retrieving a product by ID.

@Test
public void givenIdThenShouldReturnProductOfThatId()
{ Product product1 = new Product(1,"bat",3000);
Product product2 = productRepository.save(product1);
Optional<Product> optional = productRepository.findById(product2.getId());
assertEquals(product2.getId(), optional.get().getId());
assertEquals(product2.getName(), optional.get().getName());
}

Test Case to Delete a Product by Id

Department of Information Technology 2024-25


C212: Object Oriented Programming with Java Lab (BCS-452)

Finally, this test code tests for the deletion of products.

@Test
public void givenIdTODeleteThenShouldDeleteTheProduct()
{ Product product = new Product(4, "pen",160);
productRepository.save(product);
productRepository.deleteById(product.getId());
Optional optional = productRepository.findById(product.getId());
assertEquals(Optional.empty(), optional);
}
Let’s run the tests, as you can see from the output provided below, all the test case passes.

Testing the Service Layer

The Service layer class

ProductServiceImpl
is responsible for using the repository for performing CRUD operation.
This is the code of the

ProductServiceImpl
class.
ProductServiceImpl.java

@Service
public class ProductServiceImpl implements
ProductService{ private ProductRepository productRepository;
@Autowired
public void setProductRepository(ProductRepository productRepository){
this.productRepository =productRepository;
}
@Override
public Product addProduct(Product product) throws ProductAlreadyExistsException {
if(productRepository.existsById(product.getId())){
throw new ProductAlreadyExistsException();
}
return productRepository.save(product);
}

Department of Information Technology 2024-25


C212: Object Oriented Programming with Java Lab (BCS-452)

@Override
public List<Product> getAllProducts() {
return (List<Product>) productRepository.findAll();
}
@Override
public Product getProductByid(int id) {
return productRepository.findById(id).orElse(null);
}
@Override
public Product deleteProductById(int id) {
Product product = null;
Optional optional = productRepository.findById(id);
if (optional.isPresent()) {
product = productRepository.findById(id).get();
productRepository.deleteById(id);
}
return product;
}
We will write pure unit tests of the service implementation –

ProductServiceImpl
. The reason is that unit tests are super-fast and therefore cuts down developers’ time.
Note that in unit testing, when we have external dependencies, we mock the
dependencies. So in this example, we will mock the

ProductRepository
class.
For more information on mocking, refer to my post Mocking in Unit Tests with Mockito.

Let’s start writing the code. The code for the unit test is this.

@ExtendWith(MockitoExtension.class)
class ProductServiceTest {
@Mock
private ProductRepository productRepository;
@Autowired
@InjectMocks
private ProductServiceImpl productService;
private Product product1;
private Product product2;
List<Product> productList;
@BeforeEach
public void setUp() {
productList = new ArrayList<>();
product1 = new Product(1, "bread",20);
product2 = new Product(2, "jam",200);
productList.add(product1);
productList.add(product2);

Department of Information Technology 2024-25


C212: Object Oriented Programming with Java Lab (BCS-452)

}
@AfterEach
public void tearDown()
{ product1 = product2 =
null; productList = null;
}
Line 1 uses annotation. This

MockitoExtension
is a part of the Mockito library that is used to perform mocking. It initializes mocks in test
classes.
Then, Line5 – Line 6 uses the

@Mock
annotation on
ProductRepository
. At run time, Mockito will create a mock of
ProductRepository
.
Finally, Line 8-Line10 uses the

@Autowired
annotation to autowire in
ProductServiceImpl
. The
@InjectMock
the annotation will initialize the
ProductServiceImpl
object with the
ProductRepository
mock.

Test Case for Saving a Product

The test code for saving a product is this.

@Test
void givenProductToAddShouldReturnAddedProduct() throws
ProductAlreadyExistsException{
//stubbing
when(productRepository.save(any())).thenReturn(product1);
productService.addProduct(product1);
verify(productRepository,times(1)).save(any());
}

Test Code for Retrieval of all Products

@Test

Department of Information Technology 2024-25


C212: Object Oriented Programming with Java Lab (BCS-452)

public void GivenGetAllUsersShouldReturnListOfAllUsers(){


productRepository.save(product1);
//stubbing mock to return specific data
when(productRepository.findAll()).thenReturn(productList);
List<Product> productList1 =productService.getAllProducts();
assertEquals(productList1,productList);
verify(productRepository,times(1)).save(product1);
verify(productRepository,times(1)).findAll();
}

Test Case to Retrieve a Product by Id

The test code which tests for retrieving a product by ID is this.

@Test
public void givenIdThenShouldReturnProductOfThatId() {
Mockito.when(productRepository.findById(1)).thenReturn(Optional.ofNullable(product1)
);
assertThat(productService.getProductByid(product1.getId())).isEqualTo(product1);
}

Test Case to Delete a Product by Id

The test code for deleting a product of the respective id.

@Test
public void givenIdTODeleteThenShouldDeleteTheProduct(){
when(productService.deleteProductById(product1.getId())).thenReturn(product1);
//assertThat(productService.);
verify(productRepository,times(1)).findAll();
}
Let’s run the tests.

As you can see from the output provided below, all the test cases pass.

Testing the Controller Layer

We will also write a pure unit test for the controller.

Department of Information Technology 2024-25


C212: Object Oriented Programming with Java Lab (BCS-452)

The code of the ProductController.java class that we will test is this.

@RestController
@RequestMapping("api/v1")
public class ProductController {
private ProductService productService;
public ProductController(ProductService productService)
{ this.productService = productService;
}
@PostMapping("product")
public ResponseEntity<Product> addProduct(@RequestBody Product product) throws
ProductAlreadyExistsException {
Product saveProduct = productService.addProduct(product);
return new ResponseEntity<>(saveProduct, HttpStatus.CREATED);
}
@GetMapping("products")
public ResponseEntity<List<Product>> getAllProducts()
{ return new ResponseEntity<List<Product>>(
(List <Product>) productService.getAllProducts(),HttpStatus.OK);
}
@GetMapping("product/{id}")
public ResponseEntity<Product> getProductById(@PathVariable("id") int id){
return new ResponseEntity<>(productService.getProductByid(id),HttpStatus.OK);
}
@DeleteMapping("product/{id}")
public ResponseEntity<Product> deleteProduct(@PathVariable("id") int id) {
ResponseEntity responseEntity;
Product deletedProduct = productService.deleteProductById(id);
responseEntity = new ResponseEntity<Product>(deletedProduct, HttpStatus.OK);
return responseEntity;
}
}
As you can see in the preceding code, the controller has a dependency on the service
class,

ProductService
.
So in our test, we will use Mockito to mock

ProductService
and inject a mock on
ProductController
.
Now, let’s start writing the test class.

@ExtendWith(MockitoExtension.class)
class ProductControllerTest {
@Mock

Department of Information Technology 2024-25


C212: Object Oriented Programming with Java Lab (BCS-452)

private ProductService productService;


private Product product;
private List<Product> productList;
@InjectMocks
private ProductController productController;
@Autowired
private MockMvc mockMvc;
@BeforeEach
public void setup(){
product = new Product(1,"ball",670);
mockMvc = MockMvcBuilders.standaloneSetup(productController).build();
}
@AfterEach
void tearDown()
{ product = null;
}
Line 4-Line5 uses the

@Mock
annotation on
ProductService
. At run time, Mockito will create a mock of
ProductService
.
Next, Line 12-Line13 uses the

@Autowired
annotation to autowire in
MockMvc
. The
@InjectMock
annotation will initialize the
ProductController
object.
We need to send HTTP requests to the controller from our test class to assert they are
responding as expected. For that, Line 18 uses

MockMvc
.
MockMvc
provides a powerful way to mock Spring MVC. Through
@MockMvc
you can send
MockHttp
request to a controller and test how the controller responds.
You can create instance of

mockMvc

Department of Information Technology 2024-25


C212: Object Oriented Programming with Java Lab (BCS-452)

through two methods of


MockMvcBuilders
. I have used
standaloneSetup
which registers the controller instances. The other one is the
webappContextSetup
method.

Test Case to Post a Product

Let’s write a test for posting a product.

@Test
public void PostMappingOfProduct() throws Exception{
when(productService.addProduct(any())).thenReturn(product);
mockMvc.perform(post("/api/v1/product").
contentType(MediaType.APPLICATION_JSON).
content(asJsonString(product))).
andExpect(status().isCreated());
verify(productService,times(1)).addProduct(any());
}
In-Line 4-Line 7,

mockMvc
performs a post-operation of product on the URL
"/api/v1/product"
whose content type is
APPLICATION_JSON
. The status is
isCreated()
.

Test Case to Retrieve all Products

This test uses

mockMvc
to send a GET request to retrieve all products
@Test
public void GetMappingOfAllProduct() throws Exception {
when(productService.getAllProducts()).thenReturn(productList);
mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/products").
contentType(MediaType.APPLICATION_JSON).
content(asJsonString(product))).
andDo(MockMvcResultHandlers.print());
verify(productService).getAllProducts();
verify(productService,times(1)).getAllProducts();
}

Department of Information Technology 2024-25


C212: Object Oriented Programming with Java Lab (BCS-452)

In-Line 4-Line 7,

mockMvc
performs a GET request to retrieve all products from the URL
"/api/v1/products "
whose content type is
Json
. The content is
JsonString
of product details.
This is the output on running the test.

Test Case to Retrieve Product by Id

This test uses

mockMvc
to send a GET request to retrieve a product with a given id.
@Test
public void GetMappingOfProductShouldReturnRespectiveProducct() throws Exception {
when(productService.getProductByid(product.getId())).thenReturn(product);
mockMvc.perform(get("/api/v1/product/1").
contentType(MediaType.APPLICATION_JSON).
content(asJsonString(product))).
andExpect(MockMvcResultMatchers.status().isOk()).
andDo(MockMvcResultHandlers.print());
}
Similarly, in Line 4-Line 8,

Department of Information Technology 2024-25


C212: Object Oriented Programming with Java Lab (BCS-452)

mockmvc
performs a GET request to retrieve a product with given product id 1 from the URL
"/api/v1/product/1 "
. Its content type is
Json
and content is
JsonString
of product details.
The output on running the test is this.

Test Case to Delete a Product

This test uses

mockMvc
to send a DELETE request to delete a product with a given id.
@Test
public void DeleteMappingUrlAndIdThenShouldReturnDeletedProduct() throws
Exception {
when(productService.deleteProductById(product.getId())).thenReturn(product);
mockMvc.perform(delete("/api/v1/product/1")
.contentType(MediaType.APPLICATION_JSON)
.content(asJsonString(product)))
.andExpect(MockMvcResultMatchers.status().isOk()).
andDo(MockMvcResultHandlers.print());
}
public static String asJsonString(final Object obj){
try{
return new ObjectMapper().writeValueAsString(obj);
}catch (Exception e){

Department of Information Technology 2024-25


C212: Object Oriented Programming with Java Lab (BCS-452)

throw new RuntimeException(e);


}
}
In Line 4-Line 8,

mockmvc
performs a DELETE request to delete a product with id 1 from the URL
"/api/v1/product/1 "
. The content type is
Json
. The content is
JsonString
of product details.
Now, let’s run the test cases.

The output shows below that all the test cases passed.

Input:
What are RESTful web services in Spring Boot?
Output:
Client and server applications that communicate over the WWW
POST EXPERIMENT QUESTIONS:
1. What is a REST API and how does it function?
2. How does REST APIs differ from SOAP APIs?
3. What are the primary components of an HTTP request and response in a REST API?

Department of Information Technology 2024-25


C212: Object Oriented Programming with Java Lab (BCS-452)

LAB EXPERIMENT 10

OBJECTIVE: Test frontend web applications using Spring Boot

BRIEF DESCRIPTION:
There are so many different testing approaches in Spring Boot used for deploying the application
server. Testing in Spring Boot is an important feature of software development which ensures
that your application behaves as per the requirement and meets all the testing criteria. Spring
Boot provides a robust testing framework that supports Unit Testing, Integration Testing,
and End-to-End Testing.
1. Unit Tests:
 The Focus is on testing individual components or units of the code in isolation.
 Use tools like JUnit and Mockito for the writing unit tests.
2. Integration Tests:
 Test the interactions between the multiple components or modules.
 Ensures that different parts of the application work together perfectly.
 Typically involves testing repositories, services, and controllers.
3. End-to-End (E2E) Tests:
 Test the entire application from the end to end simulating real user scenarios.
 Involve testing application’s behavior through its external interfaces.
 Use tools like Selenium for the web applications.

PRE-EXPERIMENT QUESTIONS:
 How Java is used in Spring Boot?
 What are the important topics in Spring Boot?
 What is the main class in Spring Boot?

Testing Annotations in Spring Boot


@SpringBootTest:
 Indicates that the annotated class is the Spring Boot test.
 The Loads the complete application context.
@SpringBootTest
public class MySpringBootTest {
// Test methods go here
}
@RunWith(SpringRunner.class):
 The Specifies the class to run the tests.
 The SpringRunner is the alias for SpringJUnit4ClassRunner.
@RunWith(SpringRunner.class)
@SpringBootTest
public class MySpringBootTest {

Department of Information Technology 2024-25


C212: Object Oriented Programming with Java Lab (BCS-452)

// Test methods go here


}
@MockBean:
 The Mocks a Spring Bean for testing purposes.
 Useful for the isolating the unit of the code being tested.
@SpringBootTest
public class MyServiceTest {
@Autowired
private MyService myService;
@MockBean
private ExternalService externalService;
// Test methods go here
}
@Test:
 The Denotes a test method.
 Executed when running the test class.
@Test
public void myUnitTest() {
// Test logic goes here
}
Maven Dependencies for Testing
To get started with the testing in the Spring Boot project you need to include the following
dependencies in the your pom.xml file:
<dependencies>
<!-- Spring Boot Starter Test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

JUnit Testing Dependency


The Spring Boot uses JUnit as the default testing framework. The spring-boot-starter-test
dependency already includes the JUnit so you don’t need to add it explicitly.
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>

1. @SpringBootTest (Integration Testing)


The @SpringBootTest is a core annotation in Spring Boot for the integration testing. It can
be used to the specify the configuration of ApplicationContext for the your tests.
Let’s consider a simple controller class:

Department of Information Technology 2024-25


C212: Object Oriented Programming with Java Lab (BCS-452)

@RestController
public class MyController {
@GetMapping("/hello")
public String hello() {
return "Hello, World!";
}
}

Now, let’s write a test class:


@RunWith(SpringRunner.class)
@SpringBootTest
public class MyControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
public void testHelloEndpoint() throws Exception {
mockMvc.perform(get("/hello"))
.andExpect(status().isOk())
.andExpect(content().string("Hello, World!"));
}
}

Explanation:
 @RunWith(SpringRunner.class):The Specifies the runner that JUnit should use to run
the tests. The SpringRunner is the new name for the SpringJUnit4ClassRunner.
 @SpringBootTest: Used to indicate that the annotated class is the Spring Boot test
class.
Property File Configuration:
For testing, you might want to have a separate the application-test.properties file. The
Spring Boot automatically picks up properties from this file during the tests.
2. @TestConfiguration (Test Configuration)
The @TestConfiguration is used to the specify additional configuration for the tests. It is
often used to define @Bean methods for the test-specific beans.
@TestConfiguration
public class TestConfig {
@Bean
public MyService myService()
{ return new MyService();
}
}

3. @MockBean (Mocking)
The @MockBean is used to mock a bean of the specific type, making it convenient to test
components that depend on bean.
@RunWith(SpringRunner.class)
@SpringBootTest
public class MyServiceTest {

Department of Information Technology 2024-25


C212: Object Oriented Programming with Java Lab (BCS-452)

@Autowired
private MyService myService;
@MockBean
private ExternalService externalService;
@Test
public void testServiceMethod() {
// Define behavior for the mocked external service
when(externalService.getData()).thenReturn("Mocked Data");
// Now test the method from MyService that uses externalService
String result = myService.processData();
assertEquals("Processed: Mocked Data", result);
}
}

4. @WebMvcTest (Unit Testing)


The @WebMvcTest is used for the testing the controllers in the Spring MVC application. It
focuses only on MVC components.
@RunWith(SpringRunner.class)
@WebMvcTest(MyController.class)
public class MyControllerWebMvcTest {
@Autowired
private MockMvc mockMvc;
@Test
public void testHelloEndpoint() throws Exception {
mockMvc.perform(get("/hello"))
.andExpect(status().isOk())
.andExpect(content().string("Hello, World!"));
}
}

5. @DataJpaTest (Integration Testing)


The @DataJpaTest is used for the testing JPA repositories. It focuses only on the JPA
components.
@RunWith(SpringRunner.class)
@DataJpaTest
public class MyRepositoryTest {
@Autowired
private MyRepository myRepository;
@Test
public void testRepositoryMethod()
{ MyEntity entity = new MyEntity();
entity.setData("Test Data");
myRepository.save(entity);
MyEntity savedEntity = myRepository.findById(entity.getId()).orElse(null);
assertNotNull(savedEntity);
assertEquals("Test Data", savedEntity.getData());
}

Department of Information Technology 2024-25


C212: Object Oriented Programming with Java Lab (BCS-452)

Additional Annotations
 @AutoConfigureMockMvc: Used with the @SpringBootTest to automatically
configure a MockMvc instance.
 @DirtiesContext: Indicates that the ApplicationContext associated with test is dirty and
should be closed after the test.
 @Transactional: Used to indicate that a test-managed transaction should be used.

Conclusion
The Spring Boot’s testing support combined with the popular testing libraries like JUnit
and Mockito enables the developers to create comprehensive test suites for their
applications. By using the appropriate testing annotations and strategies you can ensure the
reliability and correctness of the your Spring Boot applications.

POST-EXPERIMENT QUESTIONS:
1. Can springboot be used for frontend?
2. How do I test my spring boot application?
3. How to test web client in Spring Boot?
4. Can we use spring boot for web application?

Department of Information Technology 2024-25

You might also like