GL BAJAJ Institute of Technology and Management
[Approvedby AICTE,[Link] &Affiliatedto [Link]
Abdul Kalam Technical University, Lucknow, U.P. India]
Department of Computer Science and Engineering - Artificial
Intelligence
Object Oriented Programing with Java Lab (BCS-452)
Lab File
Session: 2025-26
Submitted To: Submitted By:
Mr. MOHIT KUMAR Name: Udit Patel
Assistant Professor Roll No.: 2401921520269
CSE-AI Department Branch: CSE-AI Sec: AI-04
Semester: IV
INDEX
Date of
S. No. List of Programs Date Signature
Submission
Use Java compiler and eclipse
1. pla orm to write and execute java
programs.
Crea ng simple java programs using
2. command line arguments.
Understand OOP concepts and basics
3. of Java programming (Classes, Objects,
Methods).
Create Java programs using
4. inheritance and polymorphism.
Implement error-handling techniques
5. using excep on handling and
mul threading.
Create a java program with the use of
6. java packages.
Construct a java program using Java
7. I/O package (Reading/Wri ng Files).
Create an industry-oriented
applica on using Spring Framework
8.
(Dependency Injec on/IoC).
Test RESTful web services using Spring
9. Boot (GET, POST, PUT, DELETE APIs).
Test Frontend web applica on with
10. Spring Boot.
PROGRAM NO. – 1
Aim:
Use Java compiler to write and execute a java program
Theory:
Displaying text is the simplest program used to demonstrate the basic syntax of a programming
language. It is usually the first program written by beginners to understand how output works.
1.1 Install JDK and configure Environment Variables Steps:
1. Download JDK 17+ from [Link]
2. Install and set JAVA_HOME = C:\Program Files\Java\jdk-17
3. Add %JAVA_HOME%\bin to PATH
4. Verify: javac -version & java -version OUTPUT:
1.2 Write and compile a "Hello World" program in Eclipse
PROGRAM:
public class HelloWorld { public static void main(String[]
args) { [Link]("Hello, World!"); [Link]("Welcome to
Java Programming Lab");
}}
OUTPUT:
1.3 Create a program to display default values of all primitive data types
PROGRAM:
public class practice { static byte b; static short s; static int i; static long l; static
float f; static double d; static char c; static boolean bool; public static void
main(String[] args) {
[Link]("Default values of primitive data types:");
[Link]("byte: " + b);
[Link]("short: " + s);
[Link]("int: " + i);
[Link]("long: " + l);
[Link]("float: " + f);
[Link]("double: " + d);
[Link]("char: '" + c + "' (ASCII: " + (int)c + ")");
[Link]("boolean: " + bool);
}
}
OUTPUT
PROGRAM NO. – 2
Aim:
To simple java programs using command line arguments.
Theory:
Java programs can receive input directly from the command line using the args[] array in the main
method. These arguments are passed as strings and can be converted into other data typ
-es for processing within the program. Proper validation and exception handling are important to
ensure that the inputs are correct and the program runs smoothly.
2.1 Write a program to accept two numbers via args[] and display their sum
PROGRAM:
public class SumArgs { public static
void main(String[] args) { if
([Link] != 2) {
[Link]("Usage: java SumArgs <num1> <num2>"); return;
}
try { int num1 = [Link](args[0]); int num2 =
[Link](args[1]);
[Link]("Sum of " + num1 + " + " + num2 + " = " + (num1 + num2));
} catch (NumberFormatException e)
{ [Link]("Please enter
valid integers!");
}}}
OUTPUT:
2.2 Create a program to take Username via command line andprint personalized
greeting
PROGRAM:
public class Greeting { public static void main(String[] args) { if ([Link]
== 0) { [Link]("Usage: java Greeting
<username>"); return; } String username = args[0]; [Link]("Hello "
+ username + "!");
[Link]("Welcome to Java Programming Laboratory!");
}}
OUTPUT:
PROGRAM NO. – 3
Aim:
Understand OOP concepts and basics of Java programming (Classes, Objects, Methods).
Theory:
This demonstrates the use of classes and objects in Java by defining properties and creating
multiple instances. It shows how methods can perform operations like calculating volume using
object data. It also illustrates constructor overloading, where different constructors are used to
initialize objects in various ways.
3.1 Define a Box class with dimensions; instantiate multiple objects:
PROGRAM
class Box { double length, width, height; Box(double l, double w, double h) { length = l;
width = w; height = h; } void displayDimensions() {
[Link]("Box Dimensions: %.2f x %.2f x %.2f\n", length, width,height); }
} public class BoxDemo { public sta c void main(String[] args) { Box box1 = new Box(10.5,
5.2, 8.0); Box box2 = new Box(15.0, 7.5, 12.3);
[Link](); [Link]("Box 2:"); [Link](); }
}
OUTPUT:
3.2 Implement calculateVolume() method:
PROGRAM
class Box { double length, width, height; Box(double l, double w, double h)
{ length = l; width = w; height = h; } double
calculateVolume() { return length * width * height; } void display() {
[Link]("Volume: %.2f cubic units\n", calculateVolume());
} } public class BoxVolume {
public static void main(String[] args) { Box box
= new Box(12, 8, 6); [Link](); } }
OUTPUT:
3.3 Demonstrate Constructor Overloading:
PROGRAM
class Box { double length,
width, height;
// Default constructor Box() { length = width = height = 1.0;
[Link]("Default constructor called");
}
// Parameterized constructor
Box(double side) { length =
width = height = side;
[Link]("Single parameter constructor called");
Box(double l, double w, double h) {
length = l; width = w; height = h;
}
double volume() { return
length * width * height; } }
public class BoxConstructor {
public sta c void main(String[]
args) { Box b1 = new Box(); //
Default Box b2 = new Box(5.0);
// Single param Box b3 = new
Box(2, 4, 6); // Three params
[Link] ("b1 volume:
%.2f\n", [Link]());
[Link] ("b2 volume:
%.2f\n", [Link]());
[Link] ("b3 volume:
%.2f\n", [Link]()); } }
OUTPUT:
PROGRAM NO. – 4
Aim:
To create Java programs using inheritance and polymorphism.
Theory:
Inheritance allows a class to acquire properties and methods from another class, promoting code
reuse. It can be single or multilevel based on the hierarchy. Polymorphism enables one method to
have different behaviors. Method overriding is used to redefine a parent class method in the child
class. These concepts make programs more flexible and organized.
4.1 Implement Single Inheritance (Animal → Dog):
PROGRAM
class Animal{ String name; Animal(String name){
[Link] = name; [Link](name); } void eat(){
[Link]("I eat both veg and non-veg"); } void
sleep(){ [Link]("few of us sleep more. few sleep
less"); } void sound(){ [Link]("We have
different sounds"); } } class Dog extends Animal{
Dog(String name){
super(name); }
void bark(){ [Link]("I bark"); } } public class Exp_4{ public sta c void
main(String[] args) { Dog dog = new Dog("Cooper"); [Link](); [Link]();
[Link](); [Link](); } }
OUTPUT:
4.2 Implement Multilevel Inheritance (Shape → Rectangle → Square):
PROGRAM
class Shape{ String
color; Shape(String
color){ [Link] =
color;
}
void displayColor(){
[Link]("Color: "+color); } } class
Rectangle extends Shape{ double l; double
w; Rectangle(String color,double
l,double w){ super(color); this.l = l; this.w =
w; } double recArea(){ return l*w; } } class
Square extends Rectangle{ double side;
Square(String color,double side){
super(color,side,side); [Link] = side; } double
displayArea(){ return side*side;
}
}
public class Exp_4_2 { public sta c
void main(String[] args){ Square sq =
new Square("blue",5);
[Link]([Link]());
}
}
OUTPUT:
4.3 Demonstrate Method Overriding:
PROGRAM
class Animal2{ void sound(){
[Link]("I am an animal"); }
} class Dog2 extends Animal2{
@Override void sound()
[Link]("woof! woof!"); } }
class Cat2 extends Animal2{ @Override void
sound() {
[Link]("Meow! Meow!");
}
}
public class Exp_4_3 {
public sta c void main(String[] args) {
Animal2[] animals = {new Dog2(),new Cat2()};
for(Animal2 a:animals){ [Link](); } } }
OUTPUT:
PROGRAM NO. – 5
Aim:
To implement error-handling techniques using exception handling and multithreading.
Theory:
Exception handling in Java is used to manage runtime errors and prevent program crashes using
try, catch, and finally blocks. It helps in handling unexpected situations like array index errors
gracefully. Multithreading allows multiple tasks to run simultaneously, improving performance
and efficiency. Threads can be created by extending the Thread class or implementing the
Runnable interface. These concepts help in building robust and responsive applications.
5.1 Use try-catch-finally for ArrayIndexOutOfBoundsException:
PROGRAM
public class Exp_5_1 { public static void
main(String[] args) { int []arr = {10,20,30}; try{
[Link]("Array at index 5="+arr[5]);
} catch(ArrayIndexOutOfBoundsException e){
[Link]("Error: "+[Link]());
[Link]("Array Length: "+3);
} finally{ [Link]("Finally block
executed"); }
}
}
OUTPUT:
5.2 Create two threads by extending Thread class:
PROGRAM
class MyThread1 extends Thread{
public void run(){ for(int i=1;i<=8;i++){
[Link]("Thread1: "+(i+5));
try{ [Link](500); }
catch(InterruptedExcep on e){ } } }
} class MyThread2 extends Thread{
public void run(){ for(int i=1;i<=9;i++)
{ [Link]("Thread2: "+
(i+1)); try{ [Link](500); }
catch(InterruptedException e){ } } } }
public class Exp_5_2 { public sta c void
main(String[] args) { MyThread1 t1 =
new MyThread1(); MyThread2 t2 =
new MyThread2();
[Link]();
[Link](); } }
OUTPUT:
5.3 Implement Runnable interface:
PROGRAM
class MyThreadClass implements Runnable{
public void run(){ for (int i=0;i<=12;i++){
[Link]("MyRunnable "+(i+20)); try{
[Link](500); } catch(InterruptedExcep on
e){ } } } }
public class Exp_5_3 { public sta c void
main(String[] args) { Thread t1 = new Thread(new
MyThreadClass()); [Link](); } }
OUTPUT:
PROGRAM NO. – 6
Aim:
To create a java program with the use of java packages.
Theory:
Packages in Java are used to organize classes into structured namespaces, making code easier to
manage and reuse. They help avoid naming conflicts and improve readability in large projects.
Methods can be grouped logically inside packages and accessed using import statements. This
allows better modular programming and separation of concerns. Overall, packages make programs
more organized and scalable.
Directory Structure:
com/
calculator/ math/
[Link]
[Link] (in root)
File: com/calculator/math/[Link] package [Link];
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;
}
public static int multiply(int a, int b) {
return a * b; } public sta c double
divide(double a, double b) {
if (b == 0) return 0.0; return a / b; }
File: [Link]
import [Link]; public
class MainClass {
public sta c void main(String[] args) {
[Link]("5 + 3 = " + [Link](5, 3));
[Link]("10 - 4 = " + [Link](10, 4));
[Link]("6 * 7 = " + [Link] ply(6, 7));
[Link]("15 / 3 = " + [Link](15, 3)); }
}
OUTPUT:
PROGRAM NO. – 7
Aim:
To construct a java program using Java I/O package (Reading/Writing Files).
Theory:
Java I/O is used to perform input and output operations, especially for reading from and writing
to files. Classes like FileWriter and FileReader help in handling file operations efficiently.
BufferedReader is used to read data line by line, improving performance. File handling allows
storing and retrieving data permanently. These concepts are essential for managing data in
realworld applications.
7.1 Use FileWriter to create and write file
File: [Link]:
PROGRAM
import [Link];
import [Link];
public class FileWriterDemo { public static void
main(String[] args) { try (FileWriter fw = new
FileWriter("[Link]")) { [Link]("Hello Java
File Handling!\n"); [Link]("This is line 2.\n");
[Link]("Experiment 7.1 completed.");
[Link]("File written successfully!");
} catch (IOException e)
{
[Link]();
}}}
OUTPUT:
7.2 Use FileReader and BufferedReader
File: [Link]
PROGRAM:
import [Link].*; public class FileReaderDemo { public sta c void main(String[]
args) { try (BufferedReader br = new BufferedReader(new
FileReader("[Link]"))) {
String line;
[Link]("File content:");
while ((line = [Link]()) != null) { [Link](line);
} } catch
(IOExcep on e) {
[Link](); }
}}
OUTPUT:
7.3 Copy content from [Link] to [Link]
File: [Link] PROGRAM:
import [Link].*;
public class FileCopy { public sta c void main(String[] args) { try (BufferedReader
br = new BufferedReader(new FileReader("[Link]")); FileWriter fw = new
FileWriter("[Link]")) { String line; while ((line =
[Link]()) != null) { [Link](line
+ "\n");
}
[Link]("File copied successfully!");
catch (IOExcep on e) {
[Link]();
}}
OUTPUT:
PROGRAM NO. – 8
Aim:
To create an industry-oriented application using Spring Framework (Dependency
Injection/IoC).
Theory:
The Spring Framework uses Dependency Injection (DI) and Inversion of Control (IoC) to manage
object creation and dependencies. It removes the need for manual object instantiation, making
code loosely coupled. Beans are defined and configured using classes like AppConfig.
Dependencies can be injected using constructor or setter methods. This approach makes
applications more modular, flexible, and easier to maintain.
Complete Maven Project Structure [Link]
src/main/java/ com/lab/ [Link] [Link]
[Link]
File: [Link]
<project xmlns="[Link]
<modelVersion>4.0.0</modelVersion>
<groupId>[Link]</groupId>
<artifactId>spring-di</artifactId>
<version>1.0</version>
<dependencies>
<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.21</version>
</dependency>
</dependencies>
</project>
File: src/main/java/com/lab/[Link] package [Link]; public class Student
{ private String name; private int age; private String course; // Se er Injec on
public void setName(String name) { [Link] = name; } public void setAge(int
age) { [Link] = age; } public void setCourse(String course) { [Link] = course;
} // Constructor Injec on public Student(String name, int age) { [Link] = name;
[Link] = age;
}
public void display() {
[Link]("Student: " + name + ", Age: " + age + ", Course: " + course);
File: src/main/java/com/lab/AppConfi[Link] package [Link];
import [Link]; import
[Link]; @Configuration public class
AppConfig { @Bean(name = "student1") public Student setterStudent() { Student student =
new Student("Alice", 20); [Link]("Java"); return student; } @Bean(name =
"student2") public Student constructorStudent() { return new Student("Bob", 22); } }
File: src/main/java/com/lab/[Link] package [Link]; import
[Link] onContext; import
[Link] [Link] onConfigApplica onContext; public class MainApp {
public sta c void main(String[] args) { Applica onContext context = new
Annota onConfigApplica onContext(AppConfi[Link]); Student
s1 = [Link]("student1", [Link]); Student s2 =
[Link]("student2", [Link]);
[Link]("=== Se er Injec on ==="); [Link]();
[Link]("\n=== Constructor Injec on ===");
[Link]("Spring"); [Link]();
}}
Maven Commands:
mvn clean compile exec:java -[Link]="[Link]"
OUTPUT:
PROGRAM NO. – 9
Aim:
To test RESTful web services using Spring Boot (GET, POST, PUT, DELETE APIs).
Theory:
RESTful web services use HTTP methods like GET, POST, PUT, and DELETE to perform
operations on resources. Spring Boot simplifies building REST APIs by providing
autoconfiguration and embedded servers. Controllers handle client requests and return responses
in formats like JSON. Annotations like @RestController and @RequestMapping are used to
define endpoints. This approach helps in building scalable and loosely coupled web applications.
File: [Link]
<project xmlns="[Link] <modelVersion>4.0.0</modelVersion>
<groupId>[Link]</groupId>
<artifactId>rest-crud</artifactId>
<version>1.0</version>
<parent>
<groupId>[Link]</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.5</version>
</parent>
<dependencies>
<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
</project>
File: src/main/java/com/lab/[Link] package [Link];
public class User { private Long id; private String name;
private String email; // Constructors public User() {} public
User(Long id, String name, String email) { [Link] = id;
[Link] = name; [Link]
= email;
// Ge ers & Se ers public Long getId() { return id; }
public void setId(Long id) { [Link] = id; } public String
getName() { return name; } public void setName(String
name) { [Link] = name; } public String getEmail() {
return email; } public void setEmail(String email) {
[Link] = email; }
File: src/main/java/com/lab/[Link] package [Link];
import java.u [Link]; import java.u [Link]; import
[Link] on.*;
@RestController
@RequestMapping("/api/users") public class
UserController { private Map<Long, User> users =
new HashMap<>(); private sta c Long counter = 1L;
// GET - Get all users @GetMapping public
Map<Long, User> getAllUsers() { return users;
// POST - Create user
@PostMapping
public User createUser(@RequestBody User user) {
[Link](counter++); [Link]([Link](), user);
return user;
// PUT - Update user @PutMapping("/{id}") public User updateUser(@PathVariable
Long id, @RequestBody User userDetails) { User user = [Link](id);
if (user != null) {
[Link]([Link]());
[Link]([Link]()); } return user; }
// DELETE - Delete user @DeleteMapping("/{id}")
public String deleteUser(@PathVariable Long id) {
[Link](id); return "User with ID " + id + "
deleted successfully"; } }
File: src/main/java/com/lab/RestApplica [Link] package [Link];
import [Link] on; import
[Link]fi[Link] on;
@SpringBootApplica on public class RestApplica on { public sta c void
main(String[] args) { SpringApplica [Link](RestApplica [Link], args); }
} Run: mvn spring-boot:run
OUTPUT:
PROGRAM NO. – 10
Aim:
To test Frontend a web applica on with Spring Boot.
Theory:
Front-end and API integration connects the user interface with backend services to perform
operations like creating, reading, updating, and deleting data. Spring Boot with Thymeleaf allows
dynamic rendering of HTML pages using server-side data. The frontend sends requests to REST
APIs, and the backend processes them and returns responses. This integration enables full-stack
applications where users can interact with data through a web interface. It results in a complete
end-to-end system with both UI and backend working together.
Complete Full-Stack Application
Add to [Link] (Spring Boot Project from Exp 9):
<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
File: src/main/resources/templates/[Link]
<!DOCTYPE html>
<html xmlns:th="[Link]
<head>
<title>User Management System</title>
<meta charset="UTF-8">
<style> body { font-family: Arial; margin:
40px; } table { border-collapse: collapse;
width: 100%; } th, td { border: 1px solid
#ddd; padding: 8px; text-align: left; } th {
background-color: #f2f2f2; } button {
padding: 5px 10px; margin: 2px; } input {
padding: 5px; margin: 2px; }
</style>
</head>
<body>
<h1>User Management System</h1>
<h3>Add New User</h3>
<form th:ac on="@{/}" method="post">
<input type="text" name="name" placeholder="Name" required>
<input type="email" name="email" placeholder="Email" required>
<bu on type="submit">Add User</bu on>
</form>
<h3>Users List</h3>
<table>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Ac ons</th>
</tr>
<tr th:each="user : ${users}">
<td th:text="${[Link]}"></td>
<td th:text="${[Link]}"></td>
<td th:text="${[Link]}"></td> <td> <a th:href="@{'/delete/' +
${[Link]}}"> <bu on>Delete</bu on> </a> </td> </tr> </table> <script>
func on deleteUser(id) { if (confirm('Delete this user?')) { fetch('/api/users/' +
id, {method: 'DELETE'}) .then(() => loca [Link]()); } } </script> </body>
</html>
Updated Controller: src/main/java/com/lab/[Link] // Add this method
to exis ng controller @GetMapping("/") public String home(Model model) {
[Link] ribute("users", users); return "index";
}
Run: mvn spring-boot:run Access: h p://localhost:8080
OUTPUT: