Department of Computer Science & Engineering
KCC ISTITUTE OF TECHNOLOGY & MANAGEMENT
2B-2C, Knowledge Park-III, Greater Noida, Uttar Pradesh
BCS452-Object Oriented Programming with Java
LAB FILE
(2024-25)
4th SEMESTER
SUBMITTED TO: SUBMITTED BY:
Mr. Pragati Upadhyay Student Name : Tanishk kumar
(Assistant Professor) B.Tech./CSE (AI&ML) th Sem)
Dept. of CSE Roll No: 2304921530180
Section:B4
Index
Sl. No. Name of the Experiment Date Page No.
Use Java compiler and eclipse platform to write and
1 3 -4
execute java program.
Creating simple java programs using command line
2 5-6
arguments
Understand OOP concepts and basics of Java
3 7-9
programming.
Create Java programs using inheritance and
4 10-12
polymorphism.
Implement error-handling techniques using exception
5 13 -15
handling and multithreading.
6 Create java program with the use of java packages. 16-17
7 Construct java program using Java I/O package. 18-20
Create industry oriented application using Spring
8 21-25
Framework.
9 Test RESTful web services using Spring Boot. 26 -30
10 Test Frontend web application with Spring Boot 31-35
2
Program-1
Writing and Executing Java Program using Eclipse
Objective: Understand how to set up and execute a Java program using the Eclipse IDE.
Procedure to Write and Execute a Java Program Using Eclipse
Step 1: Install Eclipse IDE
• Download Eclipse IDE for Java Developers from the official website
(https://www.eclipse.org).
• Install it on your system and launch the application.
Step 2: Create a New Java Project
1. Open Eclipse IDE.
2. Click on the File menu, then choose New > Java Project.
3. Enter a project name, for example, MyFirstProject.
4. Click Finish to create the project.
Step 3: Create a Java Class
1. In the Package Explorer panel, right-click on the src folder under your project.
2. Select New > Class.
3. Enter a class name, such as HelloWorld.
4. Check the box for public static void main(String[] args) to include the main
method.
5. Click Finish.
Step 4: Write the Java Program
Replace the generated code with the following simple program:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, Welcome to Java Programming!");
3
Step 5: Save and Run the Program
1. Press Ctrl + S to save the file.
2. Right-click anywhere in the code editor.
3. Select Run As > Java Application.
Output
When you run the program, the console at the bottom of the Eclipse window will display:
Hello, Welcome to Java Programming!
4
Program-2
Java Program using Command Line Arguments
Objective: Understand and use command-line arguments.
Procedure to Write and Execute Java Program using Command Line Arguments
Step 1: Open a Text Editor
Use any text editor like Notepad, Notepad++, or any IDE (but here, we’ll compile and run
using the command prompt).
Step 2: Write the Java Program
Write the Java code that accepts command-line arguments. Save the file with the same name
as the class name and with a .java extension.
public class CommandLineDemo {
public static void main(String[] args) {
System.out.println("Number of arguments passed: " + args.length);
for(int i = 0; i < args.length; i++) {
System.out.println("Argument " + (i + 1) + ": " + args[i]);
Step 3: Open Command Prompt
• Navigate to the folder where your .java file is saved using the cd command.
• For example:
cd C:\Users\YourName\Desktop
Step 4: Compile the Java Program
Use the javac command to compile the Java file.
javac CommandLineDemo.java
This will create a CommandLineDemo.class file.
Step 5: Run the Java Program with Command Line Arguments
Use the java command to run the program and pass arguments.
5
For example:
java CommandLineDemo Hello Java World
Output
Number of arguments passed: 3
Argument 1: Hello
Argument 2: Java
Argument 3: World
6
Program- 3
Understanding OOP Concepts and Java Basics
Objective: Learn OOP principles (Encapsulation, Inheritance, Polymorphism, Abstraction).
Procedure to Understand OOP Concepts and Java Basics
Step 1: Understand Key OOP Concepts
• Class: A blueprint or template for creating objects.
• Object: An instance of a class.
• Method: A function defined inside a class that operates on the data.
• Encapsulation: Wrapping data and methods together into a single unit (class).
Step 2: Write the Java Program
Use a text editor or IDE (like Eclipse or IntelliJ), and write the following Java code.
// Class definition
public class Student {
// Data members (attributes)
String name;
int age;
// Method to display student details
void displayInfo() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
// Main method to create and use object
public static void main(String[] args) {
// Creating an object of Student
7
Student s1 = new Student();
// Assigning values to object
s1.name = "Rahul";
s1.age = 20;
// Calling method to display details
s1.displayInfo();
Step 3: Save the Program
Save the file as Student.java.
Step 4: Compile the Program
Open Command Prompt (or Terminal), navigate to the folder where the file is saved, and
run:
javac Student.java
This will compile the program and create Student.class.
Step 5: Run the Program
Run the compiled program using:
java Student
Output
Name: Rahul
Age: 20
Explanation of Code
• Student is a class that contains two data members: name and age.
• The displayInfo() method prints the student's information.
8
• The main method creates an object s1 and assigns values to it.
• Then it calls displayInfo() to show the details.
9
Program-4
Java Programs using Inheritance and Polymorphism
Objective
To understand and implement the concepts of inheritance and polymorphism in Java
programming through a simple example.
Procedure to Implement Inheritance and Polymorphism in Java
Step 1: Understand the Concepts
• Inheritance: It allows one class to acquire the properties and methods of another
class using the extends keyword.
• Polymorphism: The ability of a method to behave differently based on the object
that is calling it. It can be achieved through method overriding.
Step 2: Write the Java Program
// Base class
class Animal {
void sound() {
System.out.println("Animal makes a sound");
// Derived class 1
class Dog extends Animal {
void sound() {
System.out.println("Dog barks");
10
// Derived class 2
class Cat extends Animal {
void sound() {
System.out.println("Cat meows");
// Main class
public class TestPolymorphism {
public static void main(String[] args) {
Animal a; // reference variable of type Animal
a = new Dog(); // Dog object
a.sound(); // Calls Dog's sound()
a = new Cat(); // Cat object
a.sound(); // Calls Cat's sound()
Step 3: Save the Program
Save the file as TestPolymorphism.java.
Step 4: Compile the Program
Open the Command Prompt, navigate to the location of the file, and type:
javac TestPolymorphism.java
Step 5: Run the Program
11
Type the following to run the program:
java TestPolymorphism
Output
Dog barks
Cat meows
Explanation of Code
• The Animal class is the base (super) class that has a method sound().
• The Dog and Cat classes inherit from Animal and override the sound() method.
• In the main method, a single Animal reference is used to point to different objects
(Dog and Cat), showing runtime polymorphism.
12
Program-5.
Exception Handling and Multithreading
Part 1: Exception Handling in Java
Objective
To demonstrate how to handle runtime errors using try, catch, and finally blocks in Java.
Procedure to Implement Exception Handling
Step 1: Open any text editor or IDE (such as Eclipse).
Step 2: Write the Java program using try-catch-finally.
Step 3: Save the file as ExceptionDemo.java.
Step 4: Compile and run the program using Command Prompt or the IDE.
Java Program: Exception Handling
public class ExceptionDemo {
public static void main(String[] args) {
try {
int a = 10;
int b = 0;
int result = a / b; // This will throw ArithmeticException
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: Division by zero is not allowed.");
} finally {
System.out.println("This block always executes.");
13
Output
Error: Division by zero is not allowed.
This block always executes.
Explanation
• The try block contains the code that may cause an exception.
• The catch block handles the specific exception.
• The finally block always executes, whether an exception occurs or not.
Part 2: Multithreading in Java
Objective
To demonstrate how to create and run multiple threads in Java using the Thread class.
Procedure to Implement Multithreading
Step 1: Open a text editor or IDE.
Step 2: Write the Java program by extending the Thread class.
Step 3: Save the file as ThreadDemo.java.
Step 4: Compile and run the program.
Java Program: Multithreading
class MyThread extends Thread {
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(Thread.currentThread().getName() + " - Count: " + i);
14
public class ThreadDemo {
public static void main(String[] args) {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
t1.setName("Thread One");
t2.setName("Thread Two");
t1.start();
t2.start();
Output (May Vary)
Thread One - Count: 1
Thread Two - Count: 1
Thread One - Count: 2
Thread Two - Count: 2
(Note: Output may vary each time due to concurrent thread execution.)
Explanation
• MyThread class extends Thread and overrides the run() method.
• start() begins the execution of each thread in parallel.
• Thread.currentThread().getName() returns the name of the currently running
thread.
15
Program-6
Java Program using Packages
Objective
To understand how to create and use user-defined packages in Java for organizing classes
logically and avoiding name conflicts.
Procedure to Create and Use Packages in Java
Step 1: Create a Package
1. Create a folder named mypackage.
2. Inside it, create a Java file Message.java.
3. Declare the package at the top of the file using the package keyword.
Step 2: Write the Package Class
Create a file at path mypackage/Message.java with the following code:
package mypackage;
public class Message {
public void show() {
System.out.println("Hello from the package!");
Step 3: Write the Main Program
Now, create a separate file in the parent directory (outside the mypackage folder) named
PackageTest.java:
import mypackage.Message;
public class PackageTest {
public static void main(String[] args) {
16
Message m = new Message();
m.show();
Step 4: Compile the Code
Open the command prompt and navigate to the parent directory of mypackage.
1. Compile the package class:
javac mypackage/Message.java
2. Compile the main class:
javac PackageTest.java
Step 5: Run the Program
Run the main class:
java PackageTest
Output
Hello from the package!
Explanation
• package mypackage; declares a custom package.
• The Message class belongs to the mypackage package.
• The PackageTest class imports and uses Message from the package.
• This demonstrates how packages help in organizing and modularizing code.
17
Program-7
Java I/O Package Example
Objective
To demonstrate file handling using the Java I/O package by reading from and writing to a
file.
Procedure to Use Java I/O Package in Java
Step 1: Understand Java I/O
Java provides the java.io package to handle input and output operations through classes like
FileWriter, FileReader, BufferedReader, and BufferedWriter.
Step 2: Write the Program
This program will:
• Write a string to a text file.
• Read that content back from the file and print it on the screen.
Java Program: File Write and Read using Java I/O
import java.io.*;
public class FileIOExample {
public static void main(String[] args) {
String fileName = "sample.txt";
String content = "Welcome to Java I/O programming!";
// Writing to a file
try {
FileWriter writer = new FileWriter(fileName);
18
writer.write(content);
writer.close();
System.out.println("Data written to file successfully.");
} catch (IOException e) {
System.out.println("An error occurred while writing to the file.");
e.printStackTrace();
// Reading from the file
try {
FileReader reader = new FileReader(fileName);
BufferedReader br = new BufferedReader(reader);
String line;
System.out.println("Data read from file:");
while ((line = br.readLine()) != null) {
System.out.println(line);
br.close();
} catch (IOException e) {
System.out.println("An error occurred while reading the file.");
e.printStackTrace();
Step 3: Save the Program
19
Save the file as FileIOExample.java.
Step 4: Compile the Program
Open Command Prompt or terminal and run:
javac FileIOExample.java
Step 5: Run the Program
Run the compiled class:
java FileIOExample
After running, a file named sample.txt will be created in the same directory.
Output
Data written to file successfully.
Data read from file:
Welcome to Java I/O programming!
Explanation of Code
• FileWriter writes content to a file.
• FileReader and BufferedReader are used to read the contents of a file line by line.
• try-catch is used for exception handling in case of I/O errors.
20
Program-8
Industry-Oriented Application using Spring Framework
Objective
To develop a basic Spring Boot RESTful web application simulating a real-world scenario,
such as an Employee Management System, where users can retrieve employee data via
HTTP requests.
Procedure to Develop a Spring Boot Application
Step 1: Install Prerequisites
• Install Java (JDK 11 or above)
• Install Spring Tool Suite (STS) or IntelliJ IDEA or use Spring Initializr
• Install Maven or use Gradle (if not using Spring Initializr)
Step 2: Create a Spring Boot Project
You can use https://start.spring.io with the following settings:
• Project: Maven
• Language: Java
• Spring Boot: 2.7+ or 3.x
• Dependencies:
o Spring Web
o Spring Boot DevTools
Download and extract the project, then open it in your IDE.
Step 3: Create a Model Class (Employee.java)
package com.example.demo.model;
21
public class Employee {
private int id;
private String name;
private String department;
public Employee(int id, String name, String department) {
this.id = id;
this.name = name;
this.department = department;
public int getId() {
return id;
public String getName() {
return name;
public String getDepartment() {
return department;
Step 4: Create a REST Controller (EmployeeController.java)
package com.example.demo.controller;
22
import com.example.demo.model.Employee;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
@RestController
@RequestMapping("/api/employees")
public class EmployeeController {
@GetMapping
public List<Employee> getAllEmployees() {
List<Employee> employees = new ArrayList<>();
employees.add(new Employee(1, "Amit", "IT"));
employees.add(new Employee(2, "Sonal", "HR"));
employees.add(new Employee(3, "Rahul", "Finance"));
return employees;
Step 5: Run the Spring Boot Application
Open DemoApplication.java (main class) and run it:
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
23
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
Step 6: Test the Application
Once the application is running, open a browser or use Postman to visit:
http://localhost:8080/api/employees
Output (in JSON format)
"id": 1,
"name": "Amit",
"department": "IT"
},
"id": 2,
"name": "Sonal",
"department": "HR"
},
"id": 3,
24
"name": "Rahul",
"department": "Finance"
Explanation
• @RestController: Marks the class as a REST API controller.
• @GetMapping: Handles HTTP GET requests.
• Employee: A simple Java class (POJO) representing a real-world model.
• Data is returned in JSON format, which is widely used in modern web applications
and APIs.
25
Program-9
Testing RESTful Services with Spring Boot
Objective
To demonstrate how to test RESTful APIs in a Spring Boot application using Spring Boot
Test and MockMvc.
Procedure to Test RESTful Services in Spring Boot
Step 1: Set Up a Spring Boot Project
Use https://start.spring.io with the following settings:
• Project: Maven
• Language: Java
• Spring Boot Version: 2.7 or 3.x
• Dependencies:
o Spring Web
o Spring Boot DevTools
o Spring Boot Starter Test
Generate and open the project in your IDE.
Step 2: Create the Model Class (Product.java)
package com.example.demo.model;
public class Product {
private int id;
private String name;
public Product(int id, String name) {
26
this.id = id;
this.name = name;
// Getters
public int getId() {
return id;
public String getName() {
return name;
Step 3: Create the Controller Class (ProductController.java)
package com.example.demo.controller;
import com.example.demo.model.Product;
import org.springframework.web.bind.annotation.*;
import java.util.Arrays;
import java.util.List;
@RestController
@RequestMapping("/api/products")
public class ProductController {
27
@GetMapping
public List<Product> getAllProducts() {
return Arrays.asList(
new Product(1, "Laptop"),
new Product(2, "Mobile"),
new Product(3, "Tablet")
);
Step 4: Create the Test Class (ProductControllerTest.java)
package com.example.demo;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import com.example.demo.controller.ProductController;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
@WebMvcTest(ProductController.class)
public class ProductControllerTest {
28
@Autowired
private MockMvc mockMvc;
@Test
void testGetAllProducts() throws Exception {
mockMvc.perform(get("/api/products"))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].name").value("Laptop"))
.andExpect(jsonPath("$[1].name").value("Mobile"))
.andExpect(jsonPath("$[2].name").value("Tablet"));
Step 5: Run the Test
• In your IDE (like IntelliJ or Eclipse), right-click on the test class
ProductControllerTest and select Run.
• Alternatively, run with Maven:
mvn test
Output
If successful, the console will show:
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
The test will validate the status code and content of the JSON response.
Explanation
29
• @WebMvcTest is used to test only the web layer (controller).
• MockMvc allows you to simulate HTTP requests without starting a full server.
• jsonPath is used to assert values from the returned JSON structure.
30
Program-10
Frontend Web Application with Spring Boot
Objective
To develop a simple web application with a frontend interface using Spring Boot and
Thymeleaf template engine that accepts user input and displays it on a web page.
Procedure to Build Frontend Web Application in Spring Boot
Step 1: Create a Spring Boot Project
Use https://start.spring.io with the following options:
• Project: Maven
• Language: Java
• Spring Boot: 2.7 or 3.x
• Dependencies:
o Spring Web
o Thymeleaf
o Spring Boot DevTools
Click Generate, extract the zip, and open the project in IntelliJ, Eclipse, or STS.
Step 2: Create Model Class (User.java)
package com.example.demo.model;
public class User {
private String name;
31
// Constructor
public User() {}
public User(String name) {
this.name = name;
// Getter and Setter
public String getName() {
return name;
public void setName(String name) {
this.name = name;
Step 3: Create Controller Class (UserController.java)
package com.example.demo.controller;
import com.example.demo.model.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
@Controller
32
public class UserController {
@GetMapping("/")
public String showForm(Model model) {
model.addAttribute("user", new User());
return "form";
@PostMapping("/submit")
public String submitForm(@ModelAttribute("user") User user, Model model) {
model.addAttribute("name", user.getName());
return "result";
Step 4: Create HTML Templates
Create a folder src/main/resources/templates and add the following two files.
form.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>User Form</title>
</head>
<body>
<h2>Enter Your Name</h2>
<form action="#" th:action="@{/submit}" th:object="${user}" method="post">
33
<input type="text" th:field="*{name}" placeholder="Name" />
<button type="submit">Submit</button>
</form>
</body>
</html>
result.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Result Page</title>
</head>
<body>
<h2>Welcome, <span th:text="${name}"></span>!</h2>
</body>
</html>
Step 5: Run the Application
Open the main class DemoApplication.java and run it:
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
34
SpringApplication.run(DemoApplication.class, args);
Step 6: Open in Browser
Visit:
http://localhost:8080/
Output
1. Input Page:
Enter Your Name
[Your Input Box] [Submit]
2. After Submission (if name entered is "Amit"):
Welcome, Amit!
Explanation
• @Controller is used for web MVC controller.
• Thymeleaf template engine renders HTML pages.
• ModelAttribute binds form data to the object.
• form.html is the input form; result.html displays the result.
35