Lab Manual OOps With Java.doc
Lab Manual OOps With Java.doc
OF
OBJECT ORIENTED PROGRAMMING
WITH JAVA
BCS452
2024-25
COMPUTER SCIENCE & ENGINEERING,
COMPUTER SCIENCE & ENGINEERING- DATA SCIENCE
COMPUTER SCIENCE & ENGINEERING- AIML
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.
To become a leading institute of providing professionally competent and socially responsive technocrats
with high moral values.
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 committed to serve the global
needs with ability to work in an interdisciplinary environment
M1: To impart quality education to enhance ethical, professional and leadership qualities to make them
globally competitive.
M2: To create a conducive environment in which students can explore computational problems, analyze
them and identify their optimal solutions.
M3: To strive for continual enhancement of technical knowledge & innovation through industry interface
to accomplish global needs.
PE01: Students must be able to apply software engineering principles to analyze complex computing
problems and identify their solutions.
PE02: Students must be able to analyze, design, and implement the latest technology-driven projects.
PE03: Students must be able to work in a collaborative environment and understand the ethical, social,
and economic impact of their work.
Object
Oriented
1
BCS452 Programming 0 0 2 50 50 50 100 1
.
with Java
Lab
Course Objectives:
The teacher will explain:
1 Understand Java Fundamentals: Gain a comprehensive understanding of Java's history,
environment, source file structure, and compilation process, along with fundamental
programming structures including classes, methods, and control flow.
2 Master Object-Oriented Programming Concepts: Learn and apply core object-oriented
programming principles such as inheritance, encapsulation, polymorphism, and abstraction,
including the use of interfaces and abstract classes.
3 Implement Exception Handling: Develop skills in managing exceptions in Java, including
understanding different types of exceptions, control flow in exception handling, and the use
of try-catch-finally blocks.
4 Utilize Java Collections Framework: Explore the Java Collections Framework, including
various collection types (List, Set, Map), their interfaces, and how to effectively use iterators
and sorting mechanisms.
5 Leverage Spring Framework and Spring Boot: Understand the fundamentals of the
Spring Framework, including dependency injection and aspect-oriented programming, and
learn to build RESTful web services using Spring Boot
Pre- requisite:
1. Introduction to Programming Concepts: Understanding fundamental programming concepts like
variables, loops, and functions.
2. Basic Knowledge of installing JVM and any editor and working on command prompt.
3. Java Extension Pack: Install this extension pack in VS Code to enable Java support
CO-PO-PSO Mapping
S. No
List of Programs as per AKTU
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
S
. No List of Programs with enhancement of faculty
1 a. Use Java compiler and any editor like eclipse or VS Code platform to write and execute
java program.
b. Creating simple java programs using command line arguments.
2 a. Demonstrate key OOP concepts such as inheritance, and polymorphism (Overloading
and Overriding) with simple examples.
b. Demonstrate encapsulation and abstraction with simple examples.
3 a. Demonstrate try-catch, finally, and throws in exception handling.
b. Implement multithreading by creating a program where two threads calculate Fibonacci
numbers simultaneously, and handle potential issues (e.g., race conditions) with
synchronization.
4 a. Write a program to read from a file and display its contents on the console.
b. Write a program to write user input to a file.
5 Implement the interface using both a traditional anonymous inner class and a lambda expression.
6 Demonstrate the use of try-with-resources to handle automatic resource management with
BufferedReader, FileReader, or database connections.
Implement programs that demonstrate the use of various collection classes at different levels of
7 the hierarchy (e.g., Collection, List, Set, Queue, Map).
Write a program that demonstrates the use of the Iterator interface to traverse a List and a Set.
8 Use hasNext() and next() methods to iterate over collections like ArrayList and HashSet.
9 Test RESTful web services using Spring Boot.
10 Test Frontend web application with Spring Boot.
List of Value added Program
Implement the consumer producer problem with the synchronized methods produce() and
consume(), with proper wait-notify mechanisms.
INDEX
Da Sig
S. No Program Name CO BTL
te n
1 a. Use Java compiler and any editor like eclipse or VS Code platform CO1 L3
to write and execute java program.
b. Creating simple java programs using command line arguments.
2 a. Demonstrate key OOP concepts such as inheritance, and CO1 L3
polymorphism (Overloading and Overriding) with simple
examples.
b. Demonstrate encapsulation and abstraction with simple examples.
3 a. Demonstrate try-catch, finally, and throws in exception handling. CO2 L3
b. Implement multithreading by creating a program where two threads
calculate Fibonacci numbers simultaneously, and handle potential
issues (e.g., race conditions) with synchronization.
4 a. Write a program to read from a file and display its contents on the CO2 L3
console
b. Write a program to write user input to a file.
5 Implement the interface using both a traditional anonymous inner class and a CO3 L4
lambda expression.
6 Demonstrate the use of try-with-resources to handle automatic resource CO3 L4
management with BufferedReader, FileReader, or database connections.
Implement programs that demonstrate the use of various collection classes at CO4 L4
7 different levels of the hierarchy (e.g., Collection, List, Set, Queue, Map).
Write a program that demonstrates the use of the Iterator interface to traverse CO4 L4
8 a List and a Set. Use hasNext() and next() methods to iterate over collections
like ArrayList and HashSet.
Test RESTful web services using Spring Boot. CO5 L4
9
Test Frontend web application with Spring Boot. CO5 L4
10
Implement the consumer producer problem with the synchronized methods CO2 L3
11 produce() and consume(), with proper wait-notify mechanisms.
1. Computer- Multi-core processor, Min 8 GB RAM, Min 256 GB SSD storage, monitor
2. Input Devices- keyboard, mouse
3. Development Environment- Operating System: Windows, macOS, or Linux
4. Development Tools:
a) Text Editor/IDE: Visual Studio Code, Sublime Text, or Eclipse for writing Java code.
b) Java Development Kit (JDK): JDK (version 8 or higher) for developing Java applications,
including Servlets and Java Beans.
2. Objective: Use Java compiler and any editor like eclipse or VS Code platform to write and
execute java program.
5. Outcome of the Practical: By the end of this practical, student will be able to Set up a Java
development environment using Visual Studio Code. Write, compile, and execute a simple Java
program. Understand the basic structure of a Java program, including the main method. Identify and
resolve common compilation errors. Utilize the debugging tools available in VS Code to troubleshoot
their code. Gain confidence in modifying and extending Java programs for more complex tasks.
5. Outcome of the Practical: By the end of this practical, student will be able to create a Java
program that accepts and processes command line arguments. Compile and run Java programs from the
command line. Understand how to access and manipulate command line arguments within a Java
program. Gain confidence in using command line arguments for various programming tasks.
2. Objective: Demonstrate key OOP concepts such as inheritance, and polymorphism (Overloading and Overriding)
with simple examples.
3. Code and Procedure:
ShapeExample.java
// Base class
class Shape {
// Overloaded method to display shape information
void displayInfo() {
System.out.println("This is a shape.");
}
void displayInfo(String name) {
System.out.println("This is a " + name + ".");
}
// Method to calculate area (to be overridden)
double area() {
return 0; // Default implementation
}
}
// Derived class: Circle – Inheritance is done here
class Circle extends Shape {
double radius;
Circle(double radius) {
this.radius = radius;
}
// Overriding the area method
@Override
double area() {
return Math.PI * radius * radius; // Area of circle
}
// Overriding the displayInfo method
@Override
void displayInfo() {
System.out.println("This is a circle with radius: " + radius);
}
}
// Derived class: Rectangle
class Rectangle extends Shape {
double length;
double width;
Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
// Overriding the area method
@Override
double area() {
return length * width; // Area of rectangle
}
// Overriding the displayInfo method
@Override
void displayInfo() {
System.out.println("This is a rectangle with length: " + length + " and width: " + width);
}
}
// Main class to demonstrate the functionality
public class ShapeExample {
public static void main(String[] args) {
Shape myCircle = new Circle(5); // Create a Circle object
Shape myRectangle = new Rectangle(4, 6); // Create a Rectangle object
// Display information and area for Circle
myCircle.displayInfo(); // Calls the overridden method in Circle
System.out.println("Area of Circle: " + myCircle.area()); // Calls the overridden area method
// Display information and area for Rectangle
myRectangle.displayInfo(); // Calls the overridden method in Rectangle
System.out.println("Area of Rectangle: " + myRectangle.area()); // Calls the overridden area
method
// Using the overloaded method in Shape
myCircle.displayInfo("Circle"); // Calls the overloaded method in Shape
myRectangle.displayInfo("Rectangle"); // Calls the overloaded method in Shape
}
}
4. Output:
5. Outcome of the Practical: Students will learn how to override and Overload methods in classes
to provide specific implementations, demonstrating polymorphism in action. Also, they
understand how to create a base class and derived classes, as the concept of inheritance enabling
code reuse and establishing hierarchical relationships between classes and thus will build
confidence in modifying and extending Java applications, preparing them for more complex
programming challenges in future projects.
4. Output:
5. Outcome of the Practical: Students learn to encapsulate data using private fields in
the BankAccount class, ensuring controlled access through public methods. They also learned the
use of Setter and Getter methods .Also they gain the knowledge of abstraction by using an abstract
class to define essential behaviors without revealing implementation details.
6. Assessment Criteria:
Record 3 Marks
Execution 4 Marks
Viva 3 Marks
7. Viva Questions/Review Questions:
● What is encapsulation in Java? Can you provide a simple definition?
● How does encapsulation enhance data security in a class?
● What are the access modifiers used to implement encapsulation?
● What is abstraction in Java, and how does it differ from encapsulation?
● Can you explain the purpose of an abstract class in Java?
● What is the difference between an abstract method and a concrete method?
● How do you declare an abstract class in Java?
● In the provided program, how is the account balance encapsulated?
● Why is the setBalance method private in the SavingsAccount class?
● How does using an abstract class promote code reusability in Java?
2. Objective: Implement multithreading by creating a program where two threads calculate Fibonacci
numbers simultaneously, and handle potential issues (e.g., race conditions) with synchronization.
4. Output:
Output of the Main.java file
5. Outcome of the Practical: Students will gain hands-on experience with key Java concepts such as
multithreading, synchronization, and thread management. They will learn how to create and manage
threads to execute tasks concurrently, enhancing their understanding of parallel processing. They
will also understand the importance of synchronization in preventing race conditions when multiple
threads access shared resources. This practical will also highlight the challenges of recursive
algorithms in a multithreaded context, encouraging students to think critically about performance
optimization and thread safety in real-world applications.
6. Assessment Criteria:
Record 3 Marks
Execution 4 Marks
Viva 4 Marks
2. Objective: Write a program to read from a file and display its contents on the console.
FileReadDemo.java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
Output of FileReadDemo.java file reading the data line by line from sample.txt file
5. Outcome of the Practical: Students will learn how to read data from files in Java, utilize file
handling classes such as FileReader and BufferedReader, and implement exception handling to
manage potential errors. They will also gain experience in using the try-with-resources statement for
efficient resource management, enhancing their overall programming skills in file operations.
4. Output:
5. Outcome of the Practical: Students will learn how to write data to files in Java, utilize file
handling classes such as FileWriter and BufferedWriter, and implement exception handling to
manage potential errors. They will also gain experience in capturing user input and managing
resources effectively, enhancing their overall programming skills in file operations.
6. Assessment Criteria:
Record 3 Marks
Execution 4 Marks
Viva 3 Marks
7. Viva Questions/Review Questions:
● What is the purpose of the FileWriter class in Java?
● How does the BufferedWriter class improve file writing performance?
● What is the significance of using a try-with-resources statement?
● How do you handle exceptions that may occur during file writing?
● What happens if the specified file already exists when writing to it?
● Can you explain the difference between FileWriter and PrintWriter?
● How would you modify the program to append data to an existing file instead of overwriting?
● What is the role of the newLine() method in the BufferedWriter class?
● How can you change the output file name based on user input?
● Why is it important to close file resources after use?
Practical No. 5
1. Experiment Description: Interfaces are used to define a contract that classes can implement. With
the introduction of lambda expressions in Java 8, developers can write more concise and readable
code, especially when working with functional interfaces (interfaces with a single abstract method).
This practical will involve creating a simple functional interface and implementing it using both an
anonymous inner class and a lambda expression.
Program Structure:
Functional Interface: Define a functional interface with a single abstract method.
Anonymous Inner Class Implementation: Implement the interface using an anonymous inner class.
Lambda Expression Implementation: Implement the same interface using a lambda expression.
Functional Interface: The Greeting interface is defined with a single abstract method greet(String
name). The @FunctionalInterface annotation indicates that this interface is intended to be a functional
interface.
Anonymous Inner Class: In the main method, an instance of the Greeting interface is created using an
anonymous inner class. The greet method is overridden to provide the implementation, which prints a
greeting message.
Lambda Expression: The same interface is implemented using a lambda expression, which provides a
more concise way to define the greet method. The lambda expression takes a single
parameter name and prints the greeting message.
When the program is executed, it will display two greeting messages: one from the anonymous inner
class implementation and another from the lambda expression implementation. This practical will help
students understand how to implement interfaces in different ways and appreciate the simplicity and
readability of lambda expressions.
2. Objective: Implement the interface using both a traditional anonymous inner class and a lambda
expression.
3. Code and Procedure:
InterfaceImplementationDemo.java
// Step 1: Define a functional interface
@FunctionalInterface
interface Greeting {
void greet(String name);
}
public class InterfaceImplementationDemo {
public static void main(String[] args) {
// Step 2: Implementing the interface using an anonymous inner class
Greeting greetingAnonymous = new Greeting() {
@Override
public void greet(String name) {
System.out.println("Hello, " + name + "! (from Anonymous Inner Class)");
}
};
greetingAnonymous.greet("Alice");
// Step 3: Implementing the interface using a lambda expression
Greeting greetingLambda = (name) -> System.out.println("Hello, " + name + "! (from Lambda
Expression)");
greetingLambda.greet("Bob");
}
}
4. Output:
5. Outcome of the Practical: Students will learn how to define and implement functional interfaces
in Java. They will understand the differences between traditional anonymous inner classes and
lambda expressions, including the benefits of using lambda expressions for cleaner and more
concise code. Additionally, students will gain experience in functional programming concepts and
how they can be applied in Java.
6. Assessment Criteria:
Record 3 Marks
Execution 4 Marks
Viva 3 Marks
7. Viva Questions/Review Questions:
● What is a functional interface in Java?
● How does the @FunctionalInterface annotation help in defining a functional interface?
● What are the advantages of using lambda expressions over anonymous inner classes?
● Can a functional interface have multiple abstract methods? Why or why not?
● How do you implement a functional interface using an anonymous inner class?
● What is the syntax of a lambda expression in Java?
● Can lambda expressions access variables from the enclosing scope? If so, how?
● What are some common functional interfaces provided by the Java standard library?
● How do lambda expressions improve code readability and maintainability?
● Can you provide an example of a situation where using a lambda expression would be more
beneficial than using an anonymous inner class?
Practical No. 6
1. Experiment Description: Managing resources such as file streams, database connections, and
network sockets is crucial for building robust applications. The try-with-resources statement,
introduced in Java 7, simplifies resource management by automatically closing resources when they
are no longer needed. This practical will involve reading data from a file
using BufferedReader and FileReader within a try-with-resources block.
Program Structure:
File Creation: Before running the program, students should create a text file (e.g., input.txt) with some
sample text content.
Resource Management: The program will read the contents of the file
using BufferedReader and FileReader within a try-with-resources statement.
● The program imports necessary classes for file handling: BufferedReader, FileReader,
and IOException.
● The filePath variable specifies the location of the text file to be read.
● A try-with-resources statement is used to create a BufferedReader object, which
automatically closes the resource after use.
● The program reads the file line by line using a while loop and prints each line to the console.
● If an IOException occurs (e.g., if the file is not found), an error message is displayed.
● The BufferedReader is automatically closed at the end of the try block, ensuring that
resources are managed efficiently.
● When the program is executed, it will read the contents of input.txt and display them on the
console. If the file does not exist or an error occurs during reading, an appropriate error message
will be shown. This practical will help students understand the benefits of using try-with-resources
for automatic resource management and how it simplifies code by eliminating the need for explicit
resource closing.
2. Objective: Demonstrate the use of try-with-resources to handle automatic resource management
with BufferedReader, FileReader, or database connections.
3. Code and Procedure:
TryWithResourcesDemo.java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
5. Outcome of the Practical: Students will learn how to effectively utilize different collection classes
such as ArrayList, HashSet, PriorityQueue, and HashMap to store, manipulate, and retrieve data.
Students will develop the ability to choose the appropriate collection type based on specific
requirements, such as the need for ordered elements, unique values, or key-value pairs.
Practical No. 8
1. Experiment Description: The Iterator interface provides a standard way to traverse collections in
Java. It allows for the removal of elements during iteration and provides a way to access elements
sequentially without exposing the underlying structure of the collection. This practical will involve
creating a program that uses an ArrayList and a HashSet, demonstrating how to iterate through both
collections using the Iterator interface.
Program Structure:
List Implementation: Use ArrayList to demonstrate iteration.
Set Implementation: Use HashSet to demonstrate iteration.
ArrayList: An ArrayList is created and populated with fruit names. An Iterator is obtained from
the ArrayList using the iterator() method. The while loop uses hasNext() to check if there are more
elements to iterate over and next() to retrieve the next element.
HashSet: A HashSet is created and populated with animal names. Similarly, an Iterator is obtained
from the HashSet, and the same iteration process is followed to print the animal names.
When the program is executed, it will display the elements of the ArrayList followed by the elements of
the HashSet. This practical will help students understand how to use the Iterator interface to traverse
collections in Java, highlighting the differences in iteration between a List and a Set.
2. Objective: Write a program that demonstrates the use of the Iterator interface to traverse a List and
a Set. Use hasNext() and next() methods to iterate over collections like ArrayList and HashSet.
3. Code and Procedure:
IteratorDemo.java
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
public class IteratorDemo {
public static void main(String[] args) {
// 1. Demonstrating Iterator with ArrayList
System.out.println("Demonstrating ArrayList with Iterator:");
ArrayList<String> arrayList = new ArrayList<>();
arrayList.add("Apple");
arrayList.add("Banana");
arrayList.add("Cherry");
// Creating an iterator for the ArrayList
Iterator<String> listIterator = arrayList.iterator();
while (listIterator.hasNext()) {
String fruit = listIterator.next();
System.out.println(fruit);}
// 2. Demonstrating Iterator with HashSet
System.out.println("\nDemonstrating HashSet with Iterator:");
HashSet<String> hashSet = new HashSet<>();
hashSet.add("Dog");
hashSet.add("Cat");
hashSet.add("Bird");
// Creating an iterator for the HashSet
Iterator<String> setIterator = hashSet.iterator();
while (setIterator.hasNext()) {
String animal = setIterator.next();
System.out.println(animal);
}
}
}
4. Output:
Output of IteratorDemo.Java file showing results for Iterator in ArrayList and HashSet
5. Outcome of the Practical: Students will learn how to effectively use the Iterator interface to
traverse collections in Java. They will understand the importance of
the hasNext() and next() methods in the iteration process and how to apply these methods to
different collection types such as ArrayList and HashSet. This experience will enhance their ability
to manipulate collections and improve their overall programming skills in Java.
6. Assessment Criteria:
Record 3 Marks
Execution 4 Marks
Viva 3 Marks
Settings.json
{
"debug.javascript.defaultRuntimeExecutable": {
"pwa-node": "node"
},
"java.configuration.runtimes": [
{ "name":"JavaSE-17",
"path":"C:\\Program Files\\Java\\jdk-21",
"default": true}
]
}
SpringtestexampleApplication.java
package org.restexample.springtestexample;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringtestexampleApplication {
public static void main(String[] args) {
SpringApplication.run(SpringtestexampleApplication.class, args);
}
}
SampleRestController.java
package org.restexample.springtestexample;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
@RestController
@RequestMapping("/api")
public class SampleRestController {
@GetMapping("/greetings")
public String getGreetings() {
return "Hello, World";
}
@PostMapping("/echo")
public String echoMessage(@RequestBody String message) {
return "You Sent:" + message;
}
}
samplerequest.http
For get
get http:/localhost:8080/api/greetings
For post
post http://localhost:8080/api/echo
Content-Type: application/json
{
"message":"Testing RESTful web services using Springboot"
}
4. Output:
Output of Samplerequest.http file for testing get method on clicking Send Request
Output of Samplerequest.http file for testing post method on clicking Send Request
5. Outcome of the Practical: Students will gain hands-on experience in writing unit and integration
tests for RESTful services. They will also gain the knowledge of testing the GET and POST
methods and how to handle http requests.
UserController.java
@RestController
@RequestMapping("/api/users")
public class UserController {
@Autowired
private UserRepository userRepository;
@GetMapping
public List<User> getAllUsers() {
return userRepository.findAll();
}
@PostMapping
public User createUser (@RequestBody User user) {
return userRepository.save(user);
}
}
UserControllerTest.java
@SpringBootTest
@AutoConfigureMockMvc
public class UserControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
public void testGetAllUsers() throws Exception {
mockMvc.perform(get("/api/users"))
.andExpect(status().isOk());
}
@Test
public void testCreateUser () throws Exception {
String userJson = "{\"name\":\"John Doe\", \"email\":\"[email protected]\"}";
mockMvc.perform(post("/api/users")
.contentType(MediaType.APPLICATION_JSON)
.content(userJson))
.andExpect(status().isCreated());
}
}
UserComponent.js
import React, { useEffect, useState } from 'react';
import axios from 'axios';
const UserList = () => {
const [users, setUsers] = useState([]);
useEffect(() => {
axios.get('/api/users')
.then(response => setUsers(response.data));
}, []);
return (
<div>
<h1>User List</h1>
<ul>
{users.map(user => (
<li key={user.id}>{user.name} - {user.email}</li>
))}
</ul>
</div>
);
};
export default UserList;
UserTest.js
import { render, screen } from '@testing-library/react';
import UserList from './User List';
import axios from 'axios';
jest.mock('axios');
test('renders user list', async () => {
axios.get.mockResolvedValueOnce({ data: [{ id: 1, name: 'John Doe', email:
'[email protected]' }] });
render(<User List />);
const userElement = await screen.findByText(/John Doe/i);
expect(userElement).toBeInTheDocument();
});
4. Output: (only for reference)
5. Outcome of the Practical: Students will gain hands-on experience in:
● Setting up a Spring Boot application and creating RESTful APIs.
● Building a frontend application using a JavaScript framework.
● Writing unit and integration tests to validate the functionality of both the frontend and backend.
● Understanding the importance of testing in software development.
5. Outcome of the Practical: Students will learn how to implement the Producer-Consumer
problem using synchronized methods in Java. They will understand the concepts of thread
synchronization, the use of wait-notify mechanisms, and how to manage shared resources in a
concurrent environment. This experience will enhance their understanding of multithreading and
concurrency in Java.
6. Assessment Criteria:
Record 3 Marks
Execution 4 Marks
Viva 3 Marks
Textbooks
Reference Books