[Go to site: main page, start]

0% found this document useful (0 votes)
5 views42 pages

Java Project File

The document outlines practical experiments for a course on Object Oriented Programming with Java, covering topics such as setting up the Java environment, writing and executing basic Java programs, and understanding core OOP concepts like encapsulation, inheritance, and polymorphism. Each experiment includes objectives, theoretical background, program code, expected output, and conclusions. The document also addresses exception handling and multithreading techniques in Java.

Uploaded by

rishabhverma4509
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)
5 views42 pages

Java Project File

The document outlines practical experiments for a course on Object Oriented Programming with Java, covering topics such as setting up the Java environment, writing and executing basic Java programs, and understanding core OOP concepts like encapsulation, inheritance, and polymorphism. Each experiment includes objectives, theoretical background, program code, expected output, and conclusions. The document also addresses exception handling and multithreading techniques in Java.

Uploaded by

rishabhverma4509
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

BCS452 – Object Oriented Programming with Java | Practical File

Experiment 1

Use Java Compiler and Eclipse Platform to Write and Execute Java
Program
AIM
To write and execute a basic Java program using the Java compiler (javac) and Eclipse IDE.

OBJECTIVE
Students will learn how to set up the Java Development Environment, write a simple Java program,
and execute it using both command line (javac/java) and Eclipse IDE.

THEORY
Java is a high-level, object-oriented programming language developed by Sun Microsystems. A Java
program is compiled using 'javac' into bytecode (.class file), then executed by the Java Virtual
Machine (JVM) using 'java'.
Eclipse is a popular Integrated Development Environment (IDE) for Java development that provides
features like syntax highlighting, code completion, debugging, and project management.
Steps to compile and run a Java program:
1. Write the source code in a .java file
2. Compile using: javac [Link]
3. Execute using: java ClassName

PROGRAM CODE
// Experiment 1: Hello World - First Java Program

// File: [Link]

public class HelloWorld {

public static void main(String[] args) {

// Display a welcome message

[Link]("==============================");

[Link](" Welcome to Java Programming ");

[Link]("==============================");

[Link]();

[Link]("Hello, World!");

[Link]("This is my first Java program.");

// Basic arithmetic

int a = 10, b = 20;

[Link]("Sum of " + a + " and " + b + " = " + (a + b));

// String operations

Page 1
BCS452 – Object Oriented Programming with Java | Practical File

String name = "BCS452 OOP with Java";

[Link]("Subject: " + name);

[Link]("Length of subject name: " + [Link]());

EXPECTED OUTPUT
==============================

Welcome to Java Programming

==============================

Hello, World!

This is my first Java program.

Sum of 10 and 20 = 30

Subject: BCS452 OOP with Java

Length of subject name: 20

CONCLUSION
Successfully wrote and executed a Java program using both command-line compiler and Eclipse
IDE. Understood the process of writing, compiling (.class file generation), and running Java
programs.

Faculty Signature: _________________________

Page 2
BCS452 – Object Oriented Programming with Java | Practical File

Experiment 2

Creating Simple Java Programs Using Command Line Arguments


AIM
To create Java programs that accept and process command line arguments.

OBJECTIVE
To understand how to pass arguments to a Java program through the command line and process
them within the main() method using the String[] args parameter.

THEORY
Command line arguments in Java are passed to the main() method via the String[] args parameter.
These are the arguments provided after the class name when running a Java program.
Syntax: java ClassName arg1 arg2 arg3
Key points:
- args[0] is the first argument, args[1] is the second, etc.
- [Link] gives the total number of arguments passed
- All arguments are received as String; numeric conversions are done using [Link](),
[Link](), etc.

PROGRAM CODE
// Experiment 2: Command Line Arguments

// File: [Link]

// Run: java CommandLineDemo Alice 25 3.14

public class CommandLineDemo {

public static void main(String[] args) {

[Link]("=== Command Line Arguments Demo ===");

// Check if arguments are provided

if ([Link] == 0) {

[Link]("No arguments provided.");

[Link]("Usage: java CommandLineDemo <name> <age> <gpa>");

return;

[Link]("Number of arguments: " + [Link]);

// Access individual arguments

if ([Link] >= 1) {

String name = args[0];

Page 3
BCS452 – Object Oriented Programming with Java | Practical File

[Link]("Name: " + name);

if ([Link] >= 2) {

int age = [Link](args[1]);

[Link]("Age: " + age);

[Link]("Birth Year (approx): " + (2025 - age));

if ([Link] >= 3) {

double gpa = [Link](args[2]);

[Link]("GPA: %.2f%n", gpa);

// Display all arguments

[Link]("\n--- All Arguments ---");

for (int i = 0; i < [Link]; i++) {

[Link]("args[" + i + "] = " + args[i]);

EXPECTED OUTPUT
=== Command Line Arguments Demo ===

Number of arguments: 3

Name: Alice

Age: 25

Birth Year (approx): 2000

GPA: 3.14

--- All Arguments ---

args[0] = Alice

args[1] = 25

args[2] = 3.14

Page 4
BCS452 – Object Oriented Programming with Java | Practical File

CONCLUSION
Successfully demonstrated the use of command line arguments in Java. Understood how to access,
count, and convert arguments passed via String[] args at runtime.

Faculty Signature: _________________________

Page 5
BCS452 – Object Oriented Programming with Java | Practical File

Experiment 3

Understand OOP Concepts and Basics of Java Programming


AIM
To understand and implement core Object-Oriented Programming (OOP) concepts in Java.

OBJECTIVE
To demonstrate the four pillars of OOP — Encapsulation, Abstraction, Inheritance, and
Polymorphism — through practical Java code examples.

THEORY
Object-Oriented Programming (OOP) is a programming paradigm that organizes software design
around objects rather than functions. Java is a purely object-oriented language.
Four pillars of OOP:
1. Encapsulation: Binding data and methods together; hiding data using access modifiers (private,
public, protected).
2. Abstraction: Hiding implementation details and showing only the necessary features of an object.
3. Inheritance: Acquiring properties and behaviors of one class into another using 'extends'.
4. Polymorphism: One method/object behaving differently in different contexts (method overloading
& overriding).

PROGRAM CODE
// Experiment 3: OOP Concepts Demo

// File: [Link]

// Encapsulation: Using private fields with getters/setters

class Student {

private String name;

private int rollNo;

private double marks;

// Constructor

public Student(String name, int rollNo, double marks) {

[Link] = name;

[Link] = rollNo;

[Link] = marks;

// Getters

public String getName() { return name; }

public int getRollNo() { return rollNo; }

public double getMarks() { return marks; }

Page 6
BCS452 – Object Oriented Programming with Java | Practical File

// Method

public String getGrade() {

if (marks >= 90) return "A+";

else if (marks >= 75) return "A";

else if (marks >= 60) return "B";

else if (marks >= 50) return "C";

else return "F";

public void display() {

[Link]("Roll No: " + rollNo + " | Name: " + name +

" | Marks: " + marks + " | Grade: " + getGrade());

// Abstraction with abstract class

abstract class Shape {

abstract double area();

abstract double perimeter();

public void printInfo() {

[Link]("Area: %.2f, Perimeter: %.2f%n", area(), perimeter());

// Inheritance

class Circle extends Shape {

double radius;

Circle(double r) { [Link] = r; }

public double area() { return [Link] * radius * radius; }

public double perimeter() { return 2 * [Link] * radius; }

class Rectangle extends Shape {

double length, width;

Rectangle(double l, double w) { [Link] = l; [Link] = w; }

public double area() { return length * width; }

Page 7
BCS452 – Object Oriented Programming with Java | Practical File

public double perimeter() { return 2 * (length + width); }

public class OOPDemo {

public static void main(String[] args) {

[Link]("=== OOP Concepts Demo ===");

// Encapsulation

[Link]("\n-- Encapsulation (Student Records) --");

Student s1 = new Student("Ravi Kumar", 101, 88.5);

Student s2 = new Student("Priya Singh", 102, 72.0);

[Link]();

[Link]();

// Abstraction + Inheritance + Polymorphism

[Link]("\n-- Shape Area & Perimeter --");

Shape c = new Circle(5.0);

Shape r = new Rectangle(4.0, 6.0);

[Link]("Circle (r=5): "); [Link]();

[Link]("Rectangle (4x6): "); [Link]();

EXPECTED OUTPUT
=== OOP Concepts Demo ===

-- Encapsulation (Student Records) --

Roll No: 101 | Name: Ravi Kumar | Marks: 88.5 | Grade: A

Roll No: 102 | Name: Priya Singh | Marks: 72.0 | Grade: A

-- Shape Area & Perimeter --

Circle (r=5): Area: 78.54, Perimeter: 31.42

Rectangle (4x6): Area: 24.00, Perimeter: 20.00

Page 8
BCS452 – Object Oriented Programming with Java | Practical File

CONCLUSION
Successfully demonstrated all four pillars of OOP — Encapsulation using private fields and
getters/setters, Abstraction through abstract classes, Inheritance through class extension, and
Polymorphism through method overriding.

Faculty Signature: _________________________

Page 9
BCS452 – Object Oriented Programming with Java | Practical File

Experiment 4

Create Java Programs Using Inheritance and Polymorphism


AIM
To implement single, multilevel, and hierarchical inheritance and method overriding (runtime
polymorphism) in Java.

OBJECTIVE
To understand how inheritance promotes code reusability and how polymorphism allows one
interface to be used for a general class of actions.

THEORY
Inheritance allows a child class to inherit properties and methods from a parent class using the
'extends' keyword. It promotes code reuse.
Types of Inheritance in Java:
1. Single Inheritance: One child inherits from one parent.
2. Multilevel Inheritance: A → B → C (chain of inheritance).
3. Hierarchical Inheritance: One parent, multiple children.
Polymorphism means 'many forms'. Runtime polymorphism is achieved through method overriding
— the method that is called is determined at runtime based on the actual object type.
The 'super' keyword is used to call the parent class constructor or methods.

PROGRAM CODE
// Experiment 4: Inheritance and Polymorphism

// File: [Link]

// Base class

class Animal {

String name;

Animal(String name) {

[Link] = name;

public void makeSound() {

[Link](name + " makes a generic sound.");

public void eat() {

[Link](name + " is eating.");

Page 10
BCS452 – Object Oriented Programming with Java | Practical File

// Single Inheritance

class Dog extends Animal {

String breed;

Dog(String name, String breed) {

super(name); // Call parent constructor

[Link] = breed;

@Override

public void makeSound() {

[Link](name + " (" + breed + ") says: Woof! Woof!");

// Hierarchical Inheritance

class Cat extends Animal {

Cat(String name) { super(name); }

@Override

public void makeSound() {

[Link](name + " says: Meow! Meow!");

// Multilevel Inheritance

class GuideDog extends Dog {

GuideDog(String name) {

super(name, "Labrador");

public void guide() {

[Link](name + " is a trained guide dog!");

@Override

public void makeSound() {

Page 11
BCS452 – Object Oriented Programming with Java | Practical File

[Link](name + " (Guide Dog) says: Woof! (gentle)");

public class InheritanceDemo {

public static void main(String[] args) {

[Link]("=== Inheritance & Polymorphism Demo ===");

// Single Inheritance

[Link]("\n-- Single Inheritance --");

Dog dog = new Dog("Bruno", "German Shepherd");

[Link]();

[Link](); // Inherited from Animal

// Hierarchical Inheritance

[Link]("\n-- Hierarchical Inheritance --");

Cat cat = new Cat("Whiskers");

[Link]();

// Multilevel Inheritance

[Link]("\n-- Multilevel Inheritance --");

GuideDog gd = new GuideDog("Buddy");

[Link]();

[Link]();

[Link](); // From Animal (2 levels up)

// Runtime Polymorphism

[Link]("\n-- Runtime Polymorphism (Upcasting) --");

Animal[] animals = { new Dog("Rex", "Poodle"), new Cat("Luna"), new


GuideDog("Max") };

for (Animal a : animals) {

[Link](); // Calls overridden method based on actual type

Page 12
BCS452 – Object Oriented Programming with Java | Practical File

EXPECTED OUTPUT
=== Inheritance & Polymorphism Demo ===

-- Single Inheritance --

Bruno (German Shepherd) says: Woof! Woof!

Bruno is eating.

-- Hierarchical Inheritance --

Whiskers says: Meow! Meow!

-- Multilevel Inheritance --

Buddy (Guide Dog) says: Woof! (gentle)

Buddy is a trained guide dog!

Buddy is eating.

-- Runtime Polymorphism (Upcasting) --

Rex (Poodle) says: Woof! Woof!

Luna says: Meow! Meow!

Max (Guide Dog) says: Woof! (gentle)

CONCLUSION
Successfully demonstrated single, multilevel, and hierarchical inheritance. Implemented runtime
polymorphism through method overriding and upcasting. Understood the use of 'super' keyword.

Faculty Signature: _________________________

Page 13
BCS452 – Object Oriented Programming with Java | Practical File

Experiment 5

Implement Error-Handling Techniques Using Exception Handling and


Multithreading
AIM
To implement exception handling using try-catch-finally blocks and multithreading using the Thread
class and Runnable interface.

OBJECTIVE
To understand how to handle runtime errors gracefully and how to create concurrent programs using
threads in Java.

THEORY
Exception Handling: An exception is an unwanted event that interrupts normal program execution.
Java uses try, catch, finally, throw, and throws keywords.
- try: Block that contains code that might throw an exception.
- catch: Block that handles the specific exception.
- finally: Block that always executes, used for cleanup.
- throws: Declares exceptions a method may throw.
Multithreading: A thread is a lightweight sub-process. Java supports multithreading via:
1. Extending the Thread class
2. Implementing the Runnable interface
Thread lifecycle: New → Runnable → Running → Blocked → Dead

PROGRAM CODE
// Experiment 5: Exception Handling and Multithreading

// File: [Link]

// ---- PART A: Exception Handling ----

class ExceptionDemo {

// Custom Exception

static class NegativeBalanceException extends Exception {

NegativeBalanceException(String msg) { super(msg); }

static void withdraw(double balance, double amount) throws


NegativeBalanceException {

if (amount > balance) {

throw new NegativeBalanceException("Insufficient balance! Available:


" + balance);

[Link]("Withdrawn: " + amount + " | Remaining: " + (balance -


amount));

Page 14
BCS452 – Object Oriented Programming with Java | Practical File

static void demonstrateExceptions() {

[Link]("\n=== Exception Handling Demo ===");

// ArithmeticException

try {

int result = 10 / 0;

} catch (ArithmeticException e) {

[Link]("Caught ArithmeticException: " + [Link]());

} finally {

[Link]("Finally block executed.");

// ArrayIndexOutOfBoundsException

try {

int[] arr = {1, 2, 3};

[Link](arr[10]);

} catch (ArrayIndexOutOfBoundsException e) {

[Link]("Caught: Array index out of bounds!");

// NumberFormatException

try {

int n = [Link]("abc");

} catch (NumberFormatException e) {

[Link]("Caught NumberFormatException: " +


[Link]());

// Custom exception

try {

withdraw(1000.0, 1500.0);

} catch (NegativeBalanceException e) {

[Link]("Custom Exception: " + [Link]());

try {

withdraw(1000.0, 500.0);

Page 15
BCS452 – Object Oriented Programming with Java | Practical File

} catch (NegativeBalanceException e) {

[Link]([Link]());

// ---- PART B: Multithreading ----

// Method 1: Extending Thread class

class PrintNumbers extends Thread {

String threadName;

PrintNumbers(String name) { [Link] = name; }

@Override

public void run() {

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

[Link](threadName + " -> Count: " + i);

try { [Link](300); } catch (InterruptedException e) {}

// Method 2: Implementing Runnable interface

class PrintLetters implements Runnable {

@Override

public void run() {

char[] letters = {'A', 'B', 'C'};

for (char c : letters) {

[Link]("Runnable Thread -> Letter: " + c);

try { [Link](400); } catch (InterruptedException e) {}

public class ExceptionThreadDemo {

public static void main(String[] args) throws InterruptedException {

[Link]();

[Link]("\n=== Multithreading Demo ===");

Page 16
BCS452 – Object Oriented Programming with Java | Practical File

PrintNumbers t1 = new PrintNumbers("Thread-1");

PrintNumbers t2 = new PrintNumbers("Thread-2");

Thread t3 = new Thread(new PrintLetters());

[Link]();

[Link]();

[Link]();

[Link](); [Link](); [Link]();

[Link]("All threads completed.");

EXPECTED OUTPUT
=== Exception Handling Demo ===

Caught ArithmeticException: / by zero

Finally block executed.

Caught: Array index out of bounds!

Caught NumberFormatException: For input string: "abc"

Custom Exception: Insufficient balance! Available: 1000.0

Withdrawn: 500.0 | Remaining: 500.0

=== Multithreading Demo ===

Thread-1 -> Count: 1

Thread-2 -> Count: 1

Runnable Thread -> Letter: A

Thread-1 -> Count: 2 [Threads run concurrently]

...

All threads completed.

CONCLUSION
Successfully implemented exception handling using try-catch-finally and custom exceptions. Created
multithreaded programs using both Thread class and Runnable interface. Observed concurrent
execution behavior.

Faculty Signature: _________________________

Page 17
BCS452 – Object Oriented Programming with Java | Practical File

Experiment 6

Create Java Program with the Use of Java Packages


AIM
To create and use Java packages to organize classes and demonstrate access modifiers.

OBJECTIVE
To understand how packages organize Java classes, how to create user-defined packages, and how
import statements are used to access them.

THEORY
A package in Java is a namespace that organizes a set of related classes and interfaces. Packages
help avoid name conflicts and provide access protection.
Types of Packages:
1. Built-in Packages: [Link], [Link], [Link], [Link], etc.
2. User-defined Packages: Created using the 'package' keyword.
Creating a package: package packageName; (first statement in the Java file)
Importing: import [Link]; or import packageName.*;
Access Modifiers with Packages:
- public: Accessible everywhere
- protected: Accessible within package and subclasses
- default (no modifier): Accessible only within same package
- private: Accessible only within the same class

PROGRAM CODE
// Experiment 6: Java Packages

// File: [Link] (self-contained demo)

// Simulating package concepts in a single file

// In real usage, each class would be in its respective package folder

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

// Simulated '[Link]' package

class GeometryUtil {

public static double circleArea(double r) { return [Link] * r * r; }

public static double cylinderVolume(double r, double h) { return [Link] * r


* r * h; }

Page 18
BCS452 – Object Oriented Programming with Java | Practical File

public static double hypotenuse(double a, double b) { return [Link](a*a +


b*b); }

// Simulated '[Link]' package

class StringUtil {

public static String reverse(String s) {

return new StringBuilder(s).reverse().toString();

public static boolean isPalindrome(String s) {

return [Link](reverse(s));

public static int wordCount(String s) {

return [Link]().split("\\s+").length;

public class PackageDemo {

public static void main(String[] args) {

[Link]("=== Java Packages Demo ===");

// Using [Link] package

[Link]("\n-- [Link] Package --");

ArrayList<Integer> list = new ArrayList<>([Link](5, 2, 8, 1, 9,


3));

[Link]("Original: " + list);

[Link](list);

[Link]("Sorted: " + list);

[Link]("Max: " + [Link](list) + ", Min: " +


[Link](list));

// Using [Link]

[Link]("\n-- [Link] Package --");

[Link]("Sqrt(144) = %.1f%n", [Link](144));

[Link]("2^10 = %.0f%n", [Link](2, 10));

[Link]("Pi = %.5f%n", [Link]);

// Using custom GeometryUtil

[Link]("\n-- Custom GeometryUtil Class --");

Page 19
BCS452 – Object Oriented Programming with Java | Practical File

[Link]("Circle Area (r=7): %.2f%n",


[Link](7));

[Link]("Cylinder Volume (r=3, h=10): %.2f%n",


[Link](3, 10));

[Link]("Hypotenuse (3,4): %.2f%n", [Link](3,


4));

// Using custom StringUtil

[Link]("\n-- Custom StringUtil Class --");

String word = "MADAM";

[Link]("Reverse of '" + word + "': " +


[Link](word));

[Link]("Is '" + word + "' palindrome? " +


[Link](word));

[Link]("Word count: " + [Link]("Hello World


from Java"));

EXPECTED OUTPUT
=== Java Packages Demo ===

-- [Link] Package --

Original: [5, 2, 8, 1, 9, 3]

Sorted: [1, 2, 3, 5, 8, 9]

Max: 9, Min: 1

-- [Link] Package --

Sqrt(144) = 12.0

2^10 = 1024

Pi = 3.14159

-- Custom GeometryUtil Class --

Circle Area (r=7): 153.94

Cylinder Volume (r=3, h=10): 282.74

Hypotenuse (3,4): 5.00

-- Custom StringUtil Class --

Reverse of 'MADAM': MADAM

Is 'MADAM' palindrome? true

Word count: 4

Page 20
BCS452 – Object Oriented Programming with Java | Practical File

CONCLUSION
Successfully created and used Java packages. Demonstrated usage of built-in packages ([Link],
[Link]) and simulated user-defined utility packages for geometry and string operations.

Faculty Signature: _________________________

Page 21
BCS452 – Object Oriented Programming with Java | Practical File

Experiment 7

Construct Java Program Using Java I/O Package


AIM
To demonstrate file input/output operations using the [Link] package in Java.

OBJECTIVE
To understand how to read and write data to files using various I/O streams — FileWriter,
FileReader, BufferedReader, BufferedWriter, and Scanner.

THEORY
Java I/O (Input/Output) is used to process input and produce output. The [Link] package provides
classes for file handling.
Key I/O Classes:
- FileWriter / FileReader: Write/Read characters to/from files.
- BufferedWriter / BufferedReader: Buffered I/O for efficient reading/writing.
- PrintWriter: Prints formatted text to a file.
- Scanner: Reads input from files or console.
Streams in Java:
- Byte Streams: Handle I/O of 8-bit bytes (FileInputStream, FileOutputStream).
- Character Streams: Handle I/O of 16-bit Unicode characters (FileReader, FileWriter).
Always close file streams after use, preferably using try-with-resources.

PROGRAM CODE
// Experiment 7: Java I/O Package

// File: [Link]

import [Link].*;

import [Link];

public class FileIODemo {

// Method to write data to a file

static void writeToFile(String filename) throws IOException {

// Using BufferedWriter for efficient writing

try (BufferedWriter bw = new BufferedWriter(new FileWriter(filename))) {

[Link]("BCS452 - Object Oriented Programming with Java");

[Link]();

[Link]("Experiment 7: Java I/O Demo");

[Link]();

[Link]("Roll No: 12345");

[Link]();

Page 22
BCS452 – Object Oriented Programming with Java | Practical File

[Link]("Name: Ravi Kumar");

[Link]();

[Link]("Date: 2025-04-01");

[Link]();

[Link]("Data written to '" + filename + "'


successfully.");

// Method to read data from a file

static void readFromFile(String filename) throws IOException {

[Link]("\n--- Reading from '" + filename + "' ---");

try (BufferedReader br = new BufferedReader(new FileReader(filename))) {

String line;

int lineNo = 1;

while ((line = [Link]()) != null) {

[Link](lineNo++ + ": " + line);

// Method to append data to a file

static void appendToFile(String filename) throws IOException {

try (FileWriter fw = new FileWriter(filename, true);

BufferedWriter bw = new BufferedWriter(fw)) {

[Link]();

[Link]("--- Appended Record ---");

[Link]();

[Link]("Marks: 88.5 | Grade: A");

[Link]("Data appended successfully.");

// Copy file content

static void copyFile(String src, String dest) throws IOException {

try (BufferedReader br = new BufferedReader(new FileReader(src));

BufferedWriter bw = new BufferedWriter(new FileWriter(dest))) {

String line;

while ((line = [Link]()) != null) {

Page 23
BCS452 – Object Oriented Programming with Java | Practical File

[Link](line);

[Link]();

[Link]("File copied from '" + src + "' to '" + dest + "'.");

public static void main(String[] args) {

[Link]("=== Java I/O Package Demo ===");

String filename = "student_record.txt";

String copyFile = "student_record_copy.txt";

try {

// Write

writeToFile(filename);

// Append

appendToFile(filename);

// Read

readFromFile(filename);

// Copy

copyFile(filename, copyFile);

[Link]("\n--- Contents of Copied File ---");

readFromFile(copyFile);

// Check file properties

File f = new File(filename);

[Link]("\n--- File Properties ---");

[Link]("File Name: " + [Link]());

[Link]("File Size: " + [Link]() + " bytes");

[Link]("Absolute Path: " + [Link]());

[Link]("Can Read: " + [Link]());

[Link]("Can Write: " + [Link]());

} catch (IOException e) {

[Link]("I/O Error: " + [Link]());

Page 24
BCS452 – Object Oriented Programming with Java | Practical File

EXPECTED OUTPUT
=== Java I/O Package Demo ===

Data written to 'student_record.txt' successfully.

Data appended successfully.

--- Reading from 'student_record.txt' ---

1: BCS452 - Object Oriented Programming with Java

2: Experiment 7: Java I/O Demo

3: Roll No: 12345

4: Name: Ravi Kumar

5: Date: 2025-04-01

6:

7: --- Appended Record ---

8: Marks: 88.5 | Grade: A

File copied from 'student_record.txt' to 'student_record_copy.txt'.

--- File Properties ---

File Name: student_record.txt

File Size: 142 bytes

Can Read: true

Can Write: true

CONCLUSION
Successfully demonstrated Java I/O operations including writing, reading, appending, and copying
files using BufferedReader, BufferedWriter, FileReader, and FileWriter. Used try-with-resources for
automatic stream closing.

Faculty Signature: _________________________

Page 25
BCS452 – Object Oriented Programming with Java | Practical File

Experiment 8

Create Industry Oriented Application Using Spring Framework


AIM
To create an industry-oriented Student Management application using the Spring Framework with
dependency injection and MVC architecture.

OBJECTIVE
To understand Spring Framework's core concepts — IoC (Inversion of Control), Dependency
Injection (DI), Spring Beans, and the Spring MVC pattern — by building a practical application.

THEORY
Spring Framework is the most popular Java enterprise framework for building scalable, maintainable
industry-level applications.
Core Concepts:
1. IoC Container: Manages Java object lifecycle and configuration (ApplicationContext,
BeanFactory).
2. Dependency Injection (DI): Objects are provided their dependencies rather than creating them —
via Constructor Injection or Setter Injection.
3. Spring Beans: Objects managed by the Spring IoC container, defined using @Component,
@Service, @Repository annotations.
4. Spring MVC: Model-View-Controller pattern for web applications using @Controller,
@RequestMapping.
5. @Autowired: Auto-wires dependencies by type.
Key Annotations: @Component, @Service, @Repository, @Controller, @Autowired,
@Configuration, @Bean
Maven Dependency: spring-context (for core), spring-webmvc (for web layer).

PROGRAM CODE
// Experiment 8: Industry Application using Spring Framework

// Simulated without Spring runtime — demonstrates the pattern and structure

// In real Spring project, configure with [Link] and ApplicationContext

import [Link].*;

// ---- Model Layer (Entity) ----

class Employee {

private int id;

private String name;

private String department;

private double salary;

public Employee(int id, String name, String department, double salary) {

[Link] = id; [Link] = name;

Page 26
BCS452 – Object Oriented Programming with Java | Practical File

[Link] = department; [Link] = salary;

public int getId() { return id; }

public String getName() { return name; }

public String getDepartment(){ return department; }

public double getSalary() { return salary; }

public String toString() {

return [Link]("ID:%-4d | %-15s | %-12s | Rs. %.2f", id, name,


department, salary);

// ---- Repository Layer (@Repository) ----

// Simulates @Repository - Data Access Object

class EmployeeRepository {

private List<Employee> db = new ArrayList<>();

private int nextId = 1;

public void save(String name, String dept, double salary) {

[Link](new Employee(nextId++, name, dept, salary));

public List<Employee> findAll() { return db; }

public Optional<Employee> findById(int id) {

return [Link]().filter(e -> [Link]() == id).findFirst();

public List<Employee> findByDept(String dept) {

List<Employee> result = new ArrayList<>();

for (Employee e : db) if ([Link]().equalsIgnoreCase(dept))


[Link](e);

return result;

// ---- Service Layer (@Service) ----

// Simulates @Service - Business Logic

class EmployeeService {

// @Autowired - Dependency Injection

private EmployeeRepository repo;

Page 27
BCS452 – Object Oriented Programming with Java | Practical File

public EmployeeService(EmployeeRepository repo) {

[Link] = repo; // Constructor Injection

public void addEmployee(String name, String dept, double salary) {

[Link](name, dept, salary);

[Link]("Employee '" + name + "' added successfully.");

public void listAll() {

List<Employee> list = [Link]();

if ([Link]()) { [Link]("No employees found."); return;


}

[Link]("\n" + "-".repeat(60));

[Link]("%-6s | %-15s | %-12s | %s%n", "ID", "Name",


"Department", "Salary");

[Link]("-".repeat(60));

[Link]([Link]::println);

[Link]("-".repeat(60));

public double getAverageSalary() {

return
[Link]().stream().mapToDouble(Employee::getSalary).average().orElse(0);

public void getDeptReport() {

Map<String, Long> deptCount = new HashMap<>();

for (Employee e : [Link]()) {

[Link]([Link](), 1L, Long::sum);

[Link]("\n--- Department Report ---");

[Link]((k,v) -> [Link](k + ": " + v + "


employee(s)"));

// ---- Controller Layer (@Controller) ----

// Simulates Spring @Controller / @RestController

Page 28
BCS452 – Object Oriented Programming with Java | Practical File

class EmployeeController {

private EmployeeService service; // @Autowired

public EmployeeController(EmployeeService service) {

[Link] = service; // Dependency Injection

// @GetMapping("/employees")

public void handleGetAll() {

[Link]("\n[GET /employees]");

[Link]();

// @PostMapping("/employees")

public void handleAdd(String name, String dept, double salary) {

[Link]("\n[POST /employees]");

[Link](name, dept, salary);

// @GetMapping("/employees/report")

public void handleReport() {

[Link]("\n[GET /employees/report]");

[Link]();

[Link]("Average Salary: Rs. %.2f%n",


[Link]());

// ---- Main (Simulates Spring ApplicationContext) ----

public class SpringAppDemo {

public static void main(String[] args) {

[Link]("=== Spring Framework - Employee Management App ===");

[Link]("[ApplicationContext] Initializing Spring Beans...");

// Spring IoC: Bean creation + Dependency Injection

EmployeeRepository repo = new EmployeeRepository(); // @Repository


Bean

EmployeeService service = new EmployeeService(repo); // @Service


Bean

Page 29
BCS452 – Object Oriented Programming with Java | Practical File

EmployeeController controller = new EmployeeController(service); //


@Controller Bean

[Link]("[ApplicationContext] Beans initialized


successfully.");

// Simulate HTTP requests via Controller

[Link]("Amit Sharma", "Engineering", 75000);

[Link]("Priya Singh", "HR", 55000);

[Link]("Rahul Verma", "Engineering", 80000);

[Link]("Sneha Gupta", "Finance", 65000);

[Link]("Vikas Yadav", "Engineering", 70000);

[Link]();

[Link]();

EXPECTED OUTPUT
=== Spring Framework - Employee Management App ===

[ApplicationContext] Initializing Spring Beans...

[ApplicationContext] Beans initialized successfully.

[POST /employees]

Employee 'Amit Sharma' added successfully.

... (repeated for each employee)

[GET /employees]

------------------------------------------------------------

ID | Name | Department | Salary

------------------------------------------------------------

ID:1 | Amit Sharma | Engineering | Rs. 75000.00

ID:2 | Priya Singh | HR | Rs. 55000.00

ID:3 | Rahul Verma | Engineering | Rs. 80000.00

ID:4 | Sneha Gupta | Finance | Rs. 65000.00

ID:5 | Vikas Yadav | Engineering | Rs. 70000.00

[GET /employees/report]

--- Department Report ---

Page 30
BCS452 – Object Oriented Programming with Java | Practical File

Engineering: 3 employee(s)

HR: 1 employee(s)

Finance: 1 employee(s)

Average Salary: Rs. 69000.00

CONCLUSION
Successfully demonstrated the Spring Framework architecture with three-layer design: Repository
(data), Service (business logic), and Controller (request handling). Implemented Dependency
Injection via constructor injection and simulated the Spring IoC container.

Faculty Signature: _________________________

Page 31
BCS452 – Object Oriented Programming with Java | Practical File

Experiment 9

Test RESTful Web Services Using Spring Boot


AIM
To build and test a RESTful web service API using Spring Boot with full CRUD operations.

OBJECTIVE
To understand how Spring Boot simplifies REST API development using @RestController,
@RequestMapping, @GetMapping, @PostMapping, @PutMapping, @DeleteMapping, and
ResponseEntity.

THEORY
REST (Representational State Transfer) is an architectural style for building web services. RESTful
APIs use HTTP methods to perform CRUD operations.
HTTP Methods in REST:
- GET: Retrieve data (Read)
- POST: Create new data
- PUT: Update existing data
- DELETE: Remove data
Spring Boot Key Annotations:
- @SpringBootApplication: Marks the main entry point; enables auto-configuration.
- @RestController: Combines @Controller + @ResponseBody; returns JSON directly.
- @RequestMapping: Maps HTTP requests to handler methods.
- @PathVariable: Extracts value from URI path.
- @RequestBody: Maps HTTP request body to a Java object.
- ResponseEntity<T>: Represents HTTP response including status code and body.
Spring Boot auto-configures an embedded Tomcat server on port 8080 by default.

PROGRAM CODE
// Experiment 9: RESTful Web Services using Spring Boot

// NOTE: In a real Spring Boot project, add spring-boot-starter-web to [Link]

// This is a simulation showing the complete REST API structure

import [Link].*;

// ---- Model ----

class Product {

private int id;

private String name;

private String category;

private double price;

private int quantity;

public Product(int id, String name, String category, double price, int qty) {

Page 32
BCS452 – Object Oriented Programming with Java | Practical File

[Link] = id; [Link] = name; [Link] = category;

[Link] = price; [Link] = qty;

public int getId() { return id; }

public String getName() { return name; }

public double getPrice() { return price; }

public int getQuantity() { return quantity; }

public void setPrice(double p) { [Link] = p; }

public void setQuantity(int q) { [Link] = q; }

public String toString() {

return [Link]("{id:%d, name:'%s', category:'%s', price:%.2f,


qty:%d}",

id, name, category, price, quantity);

// ---- Simulated ResponseEntity ----

class ResponseEntity<T> {

private int statusCode;

private T body;

private String status;

public ResponseEntity(T body, int code, String status) {

[Link] = body; [Link] = code; [Link] = status;

public void print(String method, String uri) {

[Link]("\n[" + method + " " + uri + "] -> HTTP " + statusCode
+ " " + status);

[Link]("Response: " + body);

// ---- @RestController ----

// @RequestMapping("/api/products")

class ProductController {

private Map<Integer, Product> store = new LinkedHashMap<>();

private int nextId = 1;

Page 33
BCS452 – Object Oriented Programming with Java | Practical File

// GET /api/products -> Returns all products

public ResponseEntity<String> getAllProducts() {

if ([Link]()) return new ResponseEntity<>("[]", 200, "OK");

StringBuilder sb = new StringBuilder("[\n");

[Link]().forEach(p -> [Link](" ").append(p).append(",\n"));

[Link]("]");

return new ResponseEntity<>([Link](), 200, "OK");

// GET /api/products/{id} -> Returns product by ID

public ResponseEntity<String> getProductById(int id) {

Product p = [Link](id);

if (p == null) return new ResponseEntity<>("Product not found", 404, "NOT


FOUND");

return new ResponseEntity<>([Link](), 200, "OK");

// POST /api/products -> Create new product

public ResponseEntity<String> createProduct(String name, String cat, double


price, int qty) {

Product p = new Product(nextId++, name, cat, price, qty);

[Link]([Link](), p);

return new ResponseEntity<>("Created: " + p, 201, "CREATED");

// PUT /api/products/{id} -> Update product

public ResponseEntity<String> updateProduct(int id, double price, int qty) {

Product p = [Link](id);

if (p == null) return new ResponseEntity<>("Product not found", 404, "NOT


FOUND");

[Link](price); [Link](qty);

return new ResponseEntity<>("Updated: " + p, 200, "OK");

// DELETE /api/products/{id} -> Delete product

public ResponseEntity<String> deleteProduct(int id) {

if (![Link](id)) return new ResponseEntity<>("Not found", 404,


"NOT FOUND");

[Link](id);

return new ResponseEntity<>("Product " + id + " deleted.", 200, "OK");

Page 34
BCS452 – Object Oriented Programming with Java | Practical File

// ---- @SpringBootApplication ----

public class SpringBootRESTDemo {

public static void main(String[] args) {

[Link]("=== Spring Boot REST API - Product Service ===");

[Link]("Server started on [Link]

ProductController api = new ProductController();

// POST - Create Products

[Link]("Laptop", "Electronics", 55999.99, 10).print("POST",


"/api/products");

[Link]("Mouse", "Electronics", 799.00, 50).print("POST",


"/api/products");

[Link]("Notebook","Stationery", 49.00, 200).print("POST",


"/api/products");

// GET all

[Link]().print("GET", "/api/products");

// GET by ID

[Link](1).print("GET", "/api/products/1");

[Link](99).print("GET", "/api/products/99");

// PUT - Update

[Link](2, 699.00, 45).print("PUT", "/api/products/2");

// DELETE

[Link](3).print("DELETE", "/api/products/3");

// GET all after changes

[Link]("\n--- Final State ---");

[Link]().print("GET", "/api/products");

EXPECTED OUTPUT

Page 35
BCS452 – Object Oriented Programming with Java | Practical File

=== Spring Boot REST API - Product Service ===

Server started on [Link]

[POST /api/products] -> HTTP 201 CREATED

Response: Created: {id:1, name:'Laptop', category:'Electronics', price:55999.99,


qty:10}

[POST /api/products] -> HTTP 201 CREATED

Response: Created: {id:2, name:'Mouse', category:'Electronics', price:799.00,


qty:50}

[GET /api/products] -> HTTP 200 OK

Response: [

{id:1, name:'Laptop', ...},

{id:2, name:'Mouse', ...},

{id:3, name:'Notebook', ...}

[GET /api/products/1] -> HTTP 200 OK

[GET /api/products/99] -> HTTP 404 NOT FOUND

[PUT /api/products/2] -> HTTP 200 OK

Response: Updated: {id:2, name:'Mouse', price:699.00, qty:45}

[DELETE /api/products/3] -> HTTP 200 OK

CONCLUSION
Successfully built and tested a RESTful API with full CRUD operations using Spring Boot patterns.
Demonstrated GET, POST, PUT, DELETE endpoints with proper HTTP status codes (200, 201,
404). Understood @RestController, @RequestMapping, @PathVariable, and ResponseEntity.

Faculty Signature: _________________________

Page 36
BCS452 – Object Oriented Programming with Java | Practical File

Experiment 10

Test Frontend Web Application with Spring Boot


AIM
To integrate a frontend HTML/CSS/JavaScript web application with a Spring Boot backend and test
the complete full-stack application.

OBJECTIVE
To understand how Spring Boot serves static frontend files, how Thymeleaf template engine works,
and how a frontend communicates with Spring Boot REST endpoints using Fetch API.

THEORY
Spring Boot can serve frontend web applications in two ways:
1. Static Resources: Place HTML/CSS/JS files in src/main/resources/static/ folder. Spring Boot
auto-serves them.
2. Thymeleaf Templates: Server-side rendering using Thymeleaf engine; files placed in
src/main/resources/templates/.
Thymeleaf Key Attributes:
- th:text: Renders model attribute as text content
- th:each: Loops over a collection
- th:if / th:unless: Conditional rendering
- th:href / th:src: Dynamic URL generation
- th:action: Form action URL
Frontend-Backend Integration:
- The browser sends HTTP requests (via forms or JavaScript Fetch API) to Spring Boot REST
endpoints.
- Spring Boot processes the request and returns JSON or renders a Thymeleaf view.
- The response is displayed dynamically using JavaScript DOM manipulation.
Project Structure:
src/main/java/ -> Java source (Controllers, Services, Models)
src/main/resources/static/ -> HTML, CSS, JS files
src/main/resources/templates/ -> Thymeleaf HTML templates

PROGRAM CODE
// Experiment 10: Frontend Web Application with Spring Boot

// Demonstrates: Spring Boot Backend + HTML/CSS/JS Frontend

// ============================================

// FILE 1: [Link] (Backend)

// ============================================

// package [Link];

//

// import [Link];

// import [Link];

// import [Link].*;

Page 37
BCS452 – Object Oriented Programming with Java | Practical File

// import [Link].*;

import [Link].*;

// @Controller (serves Thymeleaf views)

class StudentController {

private List<Map<String,String>> students = new ArrayList<>();

private int nextId = 1;

// @GetMapping("/") or @GetMapping("/students")

// Returns 'students' view with model data

public String showHomePage(Map<String, Object> model) {

[Link]("students", students);

[Link]("count", [Link]());

[Link]("[GET /students] -> Rendering '[Link]'


template");

[Link](" Model: { students: " + [Link]() + " records,


count: " + [Link]() + " }");

return "students"; // maps to templates/[Link]

// @PostMapping("/students/add")

// @RequestParam String name, String branch, String email

public String addStudent(String name, String branch, String email,

Map<String, Object> model) {

Map<String,String> s = new LinkedHashMap<>();

[Link]("id", [Link](nextId++));

[Link]("name", name);

[Link]("branch", branch);

[Link]("email", email);

[Link](s);

[Link]("[POST /students/add] -> Added student: " + name);

return showHomePage(model);

// @DeleteMapping("/students/{id}")

// @ResponseBody (REST endpoint for JS Fetch)

public String deleteStudent(int id) {

[Link](s -> [Link]("id").equals([Link](id)));

Page 38
BCS452 – Object Oriented Programming with Java | Practical File

[Link]("[DELETE /students/" + id + "] -> Student removed");

return "{\"status\": \"deleted\", \"id\": " + id + "}";

// ============================================

// FILE 2: [Link] (Thymeleaf Template)

// Path: src/main/resources/templates/[Link]

// ============================================

/*

<!DOCTYPE html>

<html xmlns:th="[Link]

<head>

<title>Student Management</title>

<link rel="stylesheet" th:href="@{/css/[Link]}">

</head>

<body>

<div class="container">

<h1>Student Management Portal</h1>

<p>Total Students: <strong th:text="${count}">0</strong></p>

<!-- Add Student Form -->

<form th:action="@{/students/add}" method="post">

<input type="text" name="name" placeholder="Full Name" required/>

<input type="text" name="branch" placeholder="Branch" required/>

<input type="email" name="email" placeholder="Email" required/>

<button type="submit">Add Student</button>

</form>

<!-- Student Table (th:each loop) -->

<table>

<tr><th>ID</th><th>Name</th><th>Branch</th><th>Email</th><th>Action</th></tr>

<tr th:each="s : ${students}">

<td th:text="${[Link]}">1</td>

<td th:text="${[Link]}">Name</td>

<td th:text="${[Link]}">Branch</td>

<td th:text="${[Link]}">Email</td>

<td>

Page 39
BCS452 – Object Oriented Programming with Java | Practical File

<!-- JS Fetch API for DELETE -->

<button >

</td>

</tr>

<tr th:if="${#[Link](students)}">

<td colspan="5">No students found.</td>

</tr>

</table>

</div>

<script th:src="@{/js/[Link]}"></script>

</body>

</html>

*/

// ============================================

// FILE 3: [Link] (Frontend JavaScript)

// Path: src/main/resources/static/js/[Link]

// ============================================

/*

function deleteStudent(id) {

if (!confirm('Delete student ' + id + '?')) return;

fetch('/students/' + id, { method: 'DELETE' })

.then(res => [Link]())

.then(data => {

alert('Deleted: ' + [Link]);

[Link](); // Refresh the page

})

.catch(err => [Link]('Error:', err));

*/

// ============================================

// MAIN - Simulates the full-stack interaction

// ============================================

public class SpringBootFrontendDemo {

public static void main(String[] args) {

[Link]("=== Spring Boot Full-Stack App ===");

Page 40
BCS452 – Object Oriented Programming with Java | Practical File

[Link]("Embedded Tomcat started on port 8080");

[Link]("Open browser: [Link]

StudentController ctrl = new StudentController();

Map<String, Object> model = new HashMap<>();

// User fills form -> POST request

[Link]("Ravi Kumar", "CSE", "ravi@[Link]", model);

[Link]("Priya Singh", "ECE", "priya@[Link]", model);

[Link]("Amit Verma", "ME", "amit@[Link]", model);

// User loads page -> GET request

[Link]("\n--- Thymeleaf renders [Link] ---");

[Link](model);

@SuppressWarnings("unchecked")

List<Map<String,String>> list = (List<Map<String,String>>)


[Link]("students");

[Link]("Rendered Table:");

[Link]("%-4s | %-15s | %-6s |


%s%n","ID","Name","Branch","Email");

[Link]("-".repeat(55));

[Link](s -> [Link]("%-4s | %-15s | %-6s | %s%n",

[Link]("id"),[Link]("name"),[Link]("branch"),[Link]("email")));

// User clicks Delete -> JS Fetch DELETE request

[Link]("\n--- JS Fetch DELETE ---");

[Link]([Link](2));

// Updated view

[Link]("\n--- Updated Page (after delete) ---");

[Link](model);

[Link](s -> [Link]("%-4s | %-15s | %-6s%n",

[Link]("id"),[Link]("name"),[Link]("branch")));

EXPECTED OUTPUT
=== Spring Boot Full-Stack App ===

Embedded Tomcat started on port 8080

Page 41
BCS452 – Object Oriented Programming with Java | Practical File

Open browser: [Link]

[POST /students/add] -> Added student: Ravi Kumar

[POST /students/add] -> Added student: Priya Singh

[POST /students/add] -> Added student: Amit Verma

--- Thymeleaf renders [Link] ---

[GET /students] -> Rendering '[Link]' template

Model: { students: 3 records, count: 3 }

Rendered Table:

ID | Name | Branch | Email

-------------------------------------------------------

1 | Ravi Kumar | CSE | ravi@[Link]

2 | Priya Singh | ECE | priya@[Link]

3 | Amit Verma | ME | amit@[Link]

--- JS Fetch DELETE ---

[DELETE /students/2] -> Student removed

{"status": "deleted", "id": 2}

--- Updated Page (after delete) ---

1 | Ravi Kumar | CSE

3 | Amit Verma | ME

CONCLUSION
Successfully built a full-stack web application using Spring Boot backend and an HTML/Thymeleaf
frontend. Demonstrated static file serving, Thymeleaf template rendering with model data, form
submission via POST, and asynchronous DELETE via JavaScript Fetch API.

Faculty Signature: _________________________

Page 42

You might also like