0% found this document useful (0 votes)
313 views

Java Lab Manual Aky

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
313 views

Java Lab Manual Aky

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

Object-Oriented Programming with Java Lab

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Object Oriented Programming with Java(BCS-403)

LABORATORY MANUAL

B.TECH, 2nd Year, Semester-IV

COMPUTER SCIENCE
&
ENGINEERING

MANUAL CONTENTS

This manual is intended for the 2nd year students of Computer Science &
Engineering in the subject of Object Oriented programming with Java. This manual
typically contains practical/lab sessions related Object Oriented programming with
Java.

Students are advised to thoroughly go through this manual rather than only topics
mentioned in the syllabus as practical aspects are the key to understanding and
conceptual visualization of theoretical aspects covered in the books.
Object-Oriented Programming with Java Lab

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Good Luck for your Enjoyable Laboratory Sessions

HOD, CSE

PREFACE

This manual is designed in accordance to the new syllabus (2023-24) prescribed by


A.K.T.U. for the Fourth Semester Object Oriented Programming with Java.
This practical manual will be helpful for students of Computer Science &
Engineering to understand the course from the point of view of applied aspects.
Though all the efforts have been made to make this manual error-free, some errors
might have crept in inadvertently. Suggestions from the readers for the improvement
of the manual are most welcomed.

Vision of the Institute

“To become a leading institute of providing professionally competent and socially


responsive technocrats with high moral values."
Object-Oriented Programming with Java Lab

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Mission of the Institute

M1. To create an eco-system for the dissemination of technical knowledge, to achieve


academic excellence.

M2. To develop technocrats with creative skills and leadership qualities, to solve local
and global challenges.

M3. To impart human values and ethics in students, to make them socially and
eco-friendly responsible.

Vision of the Department

“To produce globally competent professionals having social values and commitment to
serve the global needs with the ability to work in an interdisciplinary environment."

Mission of the Department

M1. "To impart quality education to the students to enhance their ethical,
professional and leadership qualities to make them globally competitive."

M2. "To create a conducive environment in which students can explore computational
problems and analyze them to identify the optimal solutions."

M3. "To strive for continual enhancement of technical knowledge & innovation through
industry interface to accomplish global needs."
Object-Oriented Programming with Java Lab

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Program Educational Objectives (PEOs)

PEO1: Students must be able to apply software engineering principles to analyze


complex computing problems and identify their solutions.

PEO2: Students must be able to analyze, design, and implement the latest
technology-driven projects.

PEO3: Students must be able to work in a collaborative environment and understand


the ethical, social, and economic impact of their work.

Program Outcomes (POs)

PO’s An Engineering Graduate of the Department of Computer Science and Engineering


Program will be able to demonstrate:
PO1 ENGINEERING KNOWLEDGE: Apply the knowledge of mathematics, including
discrete mathematics, probability, statistics and fundamentals of various engineering
disciplines like computer science and engineering, electronic engineering and Electrical
engineering in the core information technologies.
PO2 PROBLEM ANALYSIS: Analyze a problem and identify the computing
requirements appropriate to its solution.
PO3 DESIGN/DEVELOPMENT OF SOLUTIONS: Design and implement hardware
and software systems, components, process or program to meet the desired needs within
reasonable economic, environmental, social, political, ethical, health and safety,
manufacturability, and sustainability constraints.
Object-Oriented Programming with Java Lab

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

PO4 CONDUCT INVESTIGATIONS OF COMPLEX PROBLEMS: Reassess literature


and indulge in research to use research-based knowledge and methods to design and
conduct new experiments, as well as to organize, analyze and interpret data to produce
draw valid Conclusions and recommendations.
PO5 MODERN TOOL USAGE: Use appropriate techniques, resources, and modern
engineering and IT tools necessary for computer engineering practice.
PO6 THE ENGINEER AND SOCIETY: Show the understanding of local and global
impact of computing on individuals, organizations and society.
PO7 ENVIRONMENT AND SUSTAINABILITY: Integrate IT-based solutions in
environmental contexts, and demonstrate the knowledge of need for sustainable
development.
PO8 ETHICS: Demonstrate the knowledge of professional and ethical responsibilities
along with the norms of the engineering practice.
PO9 INDIVIDUAL AND TEAM WORK: Demonstrate leadership and an ability to work
as a member with responsibility to function on multi-disciplinary teams to accomplish a
common goal.
PO10 COMMUNICATION: Demonstrate effectively communicate skills in both oral and
written form with a range of audiences.
PO11 PROJECT MANAGEMENT AND FINANCE: Apply the knowledge and
understanding of engineering and management principles to design, planned budget and
propose IT project for an identified need within a specific scope.
PO12 LIFE-LONG LEARNING: Developed confidence to acquire new knowledge in the
computing discipline and to engage in life-long learning.

Program Specific Outcomes (PSOs)

PSO 1: Able to design and implement the data structures and algorithms to deliver
quality software products.

PSO 2: Able to apply Artificial Intelligence and Machine Learning concepts to solve
society-related needs.
Object-Oriented Programming with Java Lab

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Course Outcomes (COs)

Bloom's
Course Outcomes:
Level (BL)
CO Develop object-oriented programming concepts using Java L2
1
CO Implement exception handling, file handling, and multi-threading in Java L3
2
CO Apply new Java features to build Java programs L3
3
CO Analyse Java programs with the Collection Framework L3
4
CO L3
5 Test web and RESTful Web Services with Spring Boot using Spring K
Framework concepts
Object-Oriented Programming with Java Lab

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

INDEX
Object-Oriented Programming with Java Lab

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

S. No. LIST OF EXPERIMENTS COs BL


1 Use Java compiler and Eclipse platform to write and execute Java CO1 L2
programs.
2 Use Java compiler and Eclipse platform to write and execute Java CO1 L3
programs.

3 Understand OOP concepts and basics of Java programming. CO1 L3

4 Create Java programs using inheritance and polymorphism CO1 L3

5 Implement error-handling techniques using exception handling and CO2 L3


multithreading.

6 Create Java programs with the use of Java packages. CO1 L3

7 Construct Java program using Java I/O package. CO3 L3

8 Create industry-oriented applications using Spring Framework. CO5 L3

9 Test RESTful web services using Spring Boot. CO5 L3

10 Test Frontend web application with Spring Boot CO5 L3

INTRODUCTION

Aim
Object-Oriented Programming with Java Lab

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

This course aims to introduce the concepts of operating systems, designing principles of
operating systems, and implementation of operating systems, with a particular focus on
solving real problems related to various services/ functions provided by operating
systems. Practical experimentation with the programming language is strongly
encouraged.

Course Objectives

At the end of the course, the student will be able to:


CO1: Develop the object-oriented programming concepts using Java.
CO2: Implement exception handling, file handling, and multi-threading in Java
CO3: Apply new java features to build java programs.
CO4: Analyse java programs with Collection Framework.
CO5: Test web and RESTful Web Services with Spring Boot using Spring Framework concepts

Babu Banarasi Das Institute of Technology & Management, Lucknow


LAB MANUAL
Course Name: Object-Oriented Programming with Experiment No. 1
Java Lab
Branch:
Course Code: BCS-403 Semester: IV
CSE
Object-Oriented Programming with Java Lab

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Aim : Use Java compiler and Eclipse platform to write and execute Java programs.
Content: Here's a step-by-step guide on how to write and execute Java programs using
the Eclipse IDE:

1. Download and Install Eclipse**: Visit the official Eclipse website


(https://www.eclipse.org/) and download the latest version of Eclipse IDE for
Java Developers. Follow the installation instructions provided on the website for
your operating system.

2. Install Java Development Kit (JDK) : Before you can start programming in Java,
you need to have the JDK installed on your system. You can download the JDK from
the official Oracle website
(https://www.oracle.com/java/technologies/javase-jdk11-downloads.html). Follow the
installation instructions provided on the website for your operating system.

3. Open Eclipse : After installing Eclipse, launch the IDE.

4. Create a New Java Project :


- Go to File > New > Java Project.
- Enter a name for your project and click "Finish".

5. Create a New Java Class :


- Right-click on the src folder in your project explorer.
- Go to New > Class.
Enter a name for your class and click "Finish".

6. Write Your Java Code:


- Eclipse will open a new file with a `.java` extension.
Object-Oriented Programming with Java Lab

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

- Write your Java code inside the class.


- Save the file.

7. Compile and Run Your Program :


- Right-click on the Java file in the Package Explorer.
- Select "Run As" > "Java Application".
- Eclipse will compile your code and run the program. You'll see the output in the
console view at the bottom of the Eclipse window.

Here's an example of a simple Java program that prints "Hello, World!" to the console:

```java
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
```

Once you've written this code in Eclipse, you can follow the steps above to compile and
run it. You should see "Hello, World!" printed in the console view.

Babu Banarasi Das Institute of Technology & Management, Lucknow


LAB MANUAL
Course Name: Object-Oriented Programming with Experiment No. 2
Java
Branch:
Course Code: BCS-403 Semester: IV
CSE

Aim: Creating simple Java programs using command line arguments


Object-Oriented Programming with Java Lab

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Content: Here's a simple example of a Java program that takes command-line


arguments and prints them out:

```java
public class CommandLineArguments {
public static void main(String[] args) {
// Check if there are any command-line arguments
if (args.length == 0) {
System.out.println("No command-line arguments provided.");
} else {
System.out.println("Command-line arguments:");
// Loop through each command-line argument and print it
for (int i = 0; i < args.length; i++) {
System.out.println((i + 1) + ": " + args[i]);
}
}
}
}
```

To compile and run this program using command-line tools (assuming you have JDK
installed):

1. Write the code: Save the above code in a file named `CommandLineArguments.java`.
Object-Oriented Programming with Java Lab

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

2. Compile the program: Open your terminal or command prompt and navigate to the
directory containing `CommandLineArguments.java`. Then, run the following
command to compile the program:

```
javac CommandLineArguments.java
```

This will generate a file named `CommandLineArguments.class`.

3. Run the program with command-line arguments: Once the program is compiled, you
can run it with command-line arguments. For example:

```
java CommandLineArguments arg1 arg2 arg3
```

Replace `arg1`, `arg2`, and `arg3` with the command-line arguments you want to pass.
The program will then print out each argument.

If you run the program without providing any command-line arguments, it will display
a message indicating that no arguments were provided.

Babu Banarasi Das Institute of Technology & Management, Lucknow


LAB MANUAL
Course Name: Object-Oriented Programming with Experiment No. 3
Java
Object-Oriented Programming with Java Lab

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Branch:
Course Code: BCS-403 Semester: IV
CSE

Aim: Understand OOP concepts and basics of Java programming.

Content: Understanding Object-Oriented Programming (OOP) concepts is fundamental


to Java programming. Here's an overview of key OOP concepts and how they apply to
Java:

1. Classes and Objects:


- Classes are blueprints for objects. They define the properties (attributes) and
behaviors (methods) that objects of that type will have.
- Objects are instances of classes. They encapsulate state and behavior.

Example in Java:
```java
public class Car {
// Attributes
String make;
String model;
int year;

// Methods
void drive() {
// Method implementation
}
}
```

2. Encapsulation:
- Encapsulation refers to bundling data (attributes) and methods (behaviors) that
operate on the data into a single unit (i.e., class).
- Access to the data is typically controlled through methods.

Example in Java:
```java
public class Car {
Object-Oriented Programming with Java Lab

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

private String make;


private String model;
private int year;

public void setMake(String make) {


this.make = make;
}

public String getMake() {


return make;
}
}
```

3. Inheritance:
- Inheritance allows a class (subclass/child class) to inherit attributes and methods
from another class (superclass/parent class).
- It promotes code reusability and establishes a hierarchy among classes.

Example in Java:
```java
public class ElectricCar extends Car {
// Additional attributes and methods specific to ElectricCar
}
```

4. Polymorphism:
- Polymorphism allows objects of different classes to be treated as objects of a
common superclass.
- It enables method overriding and method overloading.

Example in Java (method overriding):


```java
public class Animal {
void makeSound() {
System.out.println("Some generic sound");
}
Object-Oriented Programming with Java Lab

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

public class Dog extends Animal {


@Override
void makeSound() {
System.out.println("Bark");
}
}
```

5. Abstraction:
- Abstraction refers to hiding complex implementation details and showing only the
necessary features of an object.
- Abstract classes and interfaces are used to achieve abstraction.

Example in Java (abstract class):


```java
public abstract class Shape {
abstract double area();
}

public class Circle extends Shape {


double radius;

@Override
double area() {
return Math.PI * radius * radius;
}
}
```

These are the fundamental OOP concepts that form the backbone of Java
programming. Understanding them will help you design and develop robust, modular,
and maintainable Java applications.
Object-Oriented Programming with Java Lab

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Babu Banarasi Das Institute of Technology & Management, Lucknow


LAB MANUAL
Course Name: Object-Oriented Programming with Experiment No. 4
Java
Branch:
Course Code: BCS- 403 Semester: IV
CSE

Aim: Create Java programs using inheritance and polymorphism.

Content: Create Java programs demonstrating inheritance and polymorphism.

Inheritance Example:

```java
// Parent class
class Vehicle {
void drive() {
System.out.println("Driving the vehicle");
}
}

// Child class inheriting from Vehicle


class Car extends Vehicle {
void drive() {
System.out.println("Driving the car");
}

void accelerate() {
System.out.println("Accelerating the car");
}
}

// Child class inheriting from Vehicle


class Truck extends Vehicle {
void drive() {
System.out.println("Driving the truck");
}
Object-Oriented Programming with Java Lab

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

void load() {
System.out.println("Loading the truck");
}
}

public class InheritanceExample {


public static void main(String[] args) {
Car myCar = new Car();
myCar.drive(); // Output: Driving the car
myCar.accelerate(); // Output: Accelerating the car

Truck myTruck = new Truck();


myTruck.drive(); // Output: Driving the truck
myTruck.load(); // Output: Loading the truck
}
}
```

In this example, `Car` and `Truck` are subclasses of the `Vehicle` class. They inherit the
`drive()` method from the `Vehicle` class, and each has its own specialized method
(`accelerate()` for `Car` and `load()` for `Truck`).

Polymorphism Example:

```java
// Parent class
class Animal {
void makeSound() {
System.out.println("Some generic sound");
}
}

// Child class overriding makeSound() method


class Dog extends Animal {
@Override
void makeSound() {
Object-Oriented Programming with Java Lab

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

System.out.println("Woof");
}
}

// Child class overriding makeSound() method


class Cat extends Animal {
@Override
void makeSound() {
System.out.println("Meow");
}
}

public class PolymorphismExample {


public static void main(String[] args) {
Animal myDog = new Dog();
myDog.makeSound(); // Output: Woof

Animal myCat = new Cat();


myCat.makeSound(); // Output: Meow
}
}
```

In this example, `Dog` and `Cat` are subclasses of the `Animal` class. They override the
`makeSound()` method of the `Animal` class with their own implementations. At
runtime, the appropriate version of the `makeSound()` method is called based on the
actual type of the object (`Dog` or `Cat`) referenced by the `Animal` reference variable.

Babu Banarasi Das Institute of Technology & Management, Lucknow


LAB MANUAL
Course Name: Object-Oriented Programming with Experiment No. 5
Java
Object-Oriented Programming with Java Lab

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Branch:
Course Code: BAC-403 Semester: IV
CSE

Aim: Implement error-handling techniques using exception handling and multithreading.

Content: Certainly! Let's first look at exception handling and then move on to
multithreading in Java.

Exception Handling:

Java provides a robust exception handling mechanism to deal with runtime errors or
exceptional situations. Here's an example demonstrating exception handling:

```java

public class ExceptionHandlingExample {

public static void main(String[] args) {

try {

// Attempt to divide by zero

int result = 10 / 0; // This will throw an ArithmeticException

System.out.println("Result: " + result); // This line won't execute

} catch (ArithmeticException e) {

// Handle the exception

System.out.println("Error: Division by zero");

} finally {

// Finally block always executes, whether exception occurs or not


Object-Oriented Programming with Java Lab

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

System.out.println("End of program");

```

In this example:

- We attempt to divide by zero, which results in an `ArithmeticException`.

- The exception is caught by the `catch` block, where we handle it by printing an error
message.

- The `finally` block is used to ensure cleanup tasks are performed, regardless of
whether an exception occurs or not.

Multithreading:

Multithreading in Java allows you to execute multiple threads concurrently. Here's a


simple example illustrating multithreading:

```java

class MyThread extends Thread {

public void run() {

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

System.out.println(Thread.currentThread().getName() + ": " + i);

try {
Object-Oriented Programming with Java Lab

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Thread.sleep(1000); // Pause execution for 1 second

} catch (InterruptedException e) {

System.out.println(e);

public class MultithreadingExample {

public static void main(String[] args) {

MyThread thread1 = new MyThread();

MyThread thread2 = new MyThread();

thread1.setName("Thread 1");

thread2.setName("Thread 2");

thread1.start();

thread2.start();

```

In this example:
Object-Oriented Programming with Java Lab

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

- We create a class `MyThread` that extends the `Thread` class and overrides the `run()`
method.

- Inside the `run()` method, each thread prints numbers from 1 to 5 at intervals of 1
second.

- In the `main()` method, we create two instances of `MyThread`, set their names, and
start them using the `start()` method.

These are basic examples of exception handling and multithreading in Java. Exception
handling helps in gracefully handling errors, while multithreading enables concurrent
execution, which can be useful for tasks that can be performed independently.

Babu Banarasi Das Institute of Technology & Management, Lucknow


LAB MANUAL
Course Name: Object-Oriented Programming with Experiment No. 6
Java
Branch:
Course Code: BCS-403 Semester: IV
CSE

Aim: Create Java programs with the use of Java packages.

Content: Certainly! Java packages are used to organize classes into namespaces, which
helps in avoiding naming conflicts and provides a way to group related classes together.
Here's an example of how you can create Java programs with the use of Java packages:

Suppose we have the following directory structure:

```
src
└── com
└── example
├── math
│ └── Calculator.java
Object-Oriented Programming with Java Lab

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

└── app
└── Main.java
```

Here, `com.example` is the package name.

1. **Calculator.java**:
```java
package com.example.math;

public class Calculator {


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

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


return a - b;
}
}
```

2. Main.java:
```java
package com.example.app;

import com.example.math.Calculator;

public class Main {


public static void main(String[] args) {
int a = 10;
int b = 5;

System.out.println("Sum: " + Calculator.add(a, b));


System.out.println("Difference: " + Calculator.subtract(a, b));
}
}
```
Object-Oriented Programming with Java Lab

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

3. Compile and Run:


To compile and run these Java programs, you can use the following commands from
the root directory of your project:

```
javac src/com/example/math/Calculator.java src/com/example/app/Main.java
java -cp src com.example.app.Main
```

This will compile the `Calculator.java` and `Main.java` files and run the `Main` class.
You should see the output of the sum and difference calculated by the `Calculator` class.

This example demonstrates how to organize classes into packages and access classes
from one package in another package. It's a good practice to organize your Java code
into packages, especially for larger projects, to keep it well-structured and
maintainable.

Babu Banarasi Das Institute of Technology & Management, Lucknow


LAB MANUAL
Course Name: Object-Oriented Programming with Experiment No. 7
Java
Branch:
Course Code: BCS-403 Semester: IV
CSE

Aim: Construct Java program using Java I/O package.

Content: Sure, here's a simple Java program that demonstrates reading from and
writing to a text file using the Java I/O package:

```java
import java.io.*;
Object-Oriented Programming with Java Lab

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

public class FileIOExample {


public static void main(String[] args) {
// Define the file name
String fileName = "sample.txt";

// Write data to the file


try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName))) {
writer.write("Hello, this is a sample text.");
writer.newLine();
writer.write("This text will be written to the file.");
writer.newLine();
System.out.println("Data has been written to the file.");
} catch (IOException e) {
System.out.println("Error writing to the file: " + e.getMessage());
}

// Read data from the file


try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
System.out.println("Reading data from the file:");
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (FileNotFoundException e) {
System.out.println("File not found: " + e.getMessage());
} catch (IOException e) {
System.out.println("Error reading from the file: " + e.getMessage());
}
}
}
```

In this program:
- We define a file name `sample.txt`.
- We write some sample text to the file using a `BufferedWriter`.
- We then read the contents of the file using a `BufferedReader` and print them to the
console.
Object-Oriented Programming with Java Lab

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Make sure to create a text file named `sample.txt` in the same directory as the Java file
or adjust the file path accordingly. This program demonstrates basic file I/O operations
in Java using the `java.io` package.

Babu Banarasi Das Institute of Technology & Management, Lucknow


LAB MANUAL
Course Name: Object-Oriented Programming with Experiment No. 8
Java
Branch:
Course Code: BCS-403 Semester: IV
CSE

Aim: Create industry-oriented applications using Spring Framework.

Content: Certainly! The Spring Framework is widely used in the industry for building
various types of applications, from web applications to enterprise systems. Here's an
example of a simple web application using Spring Boot, which is a part of the larger
Spring Framework ecosystem:

Simple Web Application with Spring Boot:

```java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
public class Application {

public static void main(String[] args) {


SpringApplication.run(Application.class, args);
}
Object-Oriented Programming with Java Lab

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

@RestController
class HelloWorldController {

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

In this example:
- We use Spring Boot's `@SpringBootApplication` annotation to mark the main class as
the entry point for the Spring Boot application.
- We define a `HelloWorldController` class with a single `hello()` method that returns a
simple "Hello, World!" message.
- We use Spring's `@RestController` annotation to mark the class as a RESTful
controller.

To run this application:


1. Make sure you have Spring Boot installed or include it as a dependency in your
`pom.xml` if you're using Maven or `build.gradle` if you're using Gradle.
2. Run the `main()` method of the `Application` class.
3. Access the endpoint `http://localhost:8080/hello` in your web browser or any REST
client. You should see the "Hello, World!" message.

This is a very basic example, but Spring Framework provides a wide range of features
and modules for building complex and scalable applications, including dependency
injection, MVC framework, data access, security, messaging, and more.
Industry-oriented applications often leverage these features to build robust and
maintainable systems.
Object-Oriented Programming with Java Lab

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Babu Banarasi Das Institute of Technology & Management, Lucknow


LAB MANUAL
Course Name: Object-Oriented Programming with Experiment No. 9
Java
Branch:
Course Code: BCS-403 Semester: IV
CSE

Aim: Test RESTful web services using Spring Boot.

Content: Testing RESTful web services in Spring Boot can be done using various testing
frameworks like JUnit, Mockito, and Spring Test. Here's an example of how you can
write integration tests for RESTful web services using Spring Boot's testing support:

```java
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import
org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;

@ExtendWith(SpringExtension.class)
@SpringBootTest
@AutoConfigureMockMvc
public class RestControllerIntegrationTest {

@Autowired
private MockMvc mockMvc;

@Test
public void testHelloEndpoint() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/hello")
Object-Oriented Programming with Java Lab

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

.contentType(MediaType.APPLICATION_JSON))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.content().string("Hello, World!"));
}
}
```

In this example:
- We use JUnit 5 (`@ExtendWith(SpringExtension.class)`) as the testing framework.
- `@SpringBootTest` is used to bootstrap the application context.
- `@AutoConfigureMockMvc` automatically configures the `MockMvc` instance.
- We autowire the `MockMvc` instance to perform HTTP requests against our RESTful
endpoints.
- The `testHelloEndpoint()` method tests the `/hello` endpoint by performing a GET
request and asserting that the response status is OK (200) and the response content is
"Hello, World!".

To run this test, you can simply execute it like any other JUnit test. Spring Boot will
automatically start an embedded web server and deploy your application for testing
purposes. The `MockMvc` instance provides a powerful way to test your RESTful
endpoints in a controlled environment. You can further enhance your tests by adding
more assertions for different scenarios and endpoints.

Babu Banarasi Das Institute of Technology & Management, Lucknow


LAB MANUAL
Course Name: Object-Oriented Programming with Experiment No. 10
Java
Branch:
Course Code: BCS-403 Semester: IV
CSE

Aim: Test Frontend web application with Spring Boot.


Object-Oriented Programming with Java Lab

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Content: To test a frontend web application with Spring Boot, you typically use tools
and libraries that specialize in frontend testing, such as Selenium or Cypress for
end-to-end testing, and Jest or Jasmine for unit testing. Spring Boot itself focuses more
on backend development, but you can still integrate frontend testing into your Spring
Boot project.

Here's an example of how you can set up and perform end-to-end testing using
Selenium for a simple frontend web application in a Spring Boot project:

1. Add Dependencies:
First, you need to add the necessary dependencies for Selenium and WebDriver. You
can do this by adding the following dependencies to your `pom.xml` if you're using
Maven:

```xml
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.141.59</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-chrome-driver</artifactId>
<version>3.141.59</version>
</dependency>
```

Or to your `build.gradle` if you're using Gradle:

```groovy
dependencies {
testImplementation 'org.seleniumhq.selenium:selenium-java:3.141.59'
testImplementation 'org.seleniumhq.selenium:selenium-chrome-driver:3.141.59'
}
```

2. Write Tests:
Object-Oriented Programming with Java Lab

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Create a test class where you can write your Selenium tests. Here's an example:

```java
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class FrontendTest {

private static WebDriver driver;

@BeforeAll
public static void setUp() {
// Set the path to ChromeDriver executable
System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
// Initialize ChromeDriver instance
driver = new ChromeDriver();
}

@Test
public void testHomePage() {
// Open the homepage URL
driver.get("http://localhost:8080");
// Perform assertions or interactions with the webpage using Selenium APIs
// For example:
// Assert.assertEquals("Expected Title", driver.getTitle());
// Assert.assertTrue(driver.findElement(By.id("someElement")).isDisplayed());
}

@AfterAll
public static void tearDown() {
// Quit the WebDriver instance
if (driver != null) {
driver.quit();
}
Object-Oriented Programming with Java Lab

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

}
}
```

Replace `"path/to/chromedriver"` with the actual path to your ChromeDriver


executable.

3. **Run Tests**:
Run your tests using your favorite testing tool or IDE. The test class you've created
will open a Chrome browser, navigate to your Spring Boot application's homepage
(assuming it's running locally on port 8080), and perform assertions or interactions as
specified.

This is just a basic example of how you can perform end-to-end testing for a frontend
web application integrated with Spring Boot using Selenium. Depending on your
application's complexity and requirements, you may need to write more tests covering
different scenarios and components of your frontend.

You might also like