Java Labfile Merged
Java Labfile Merged
Semester- IV
Lab File
OBJECT ORIENTED PROGRAMMIG USING JAVA
LAB
(BCS452)
Submitted To : Submitted By :
Faculty Name : Name :
Designation : Roll No. :
Section :
Table of Contents
Vision and Mission Statements of the Institute
List of Experiments
Index
Institute Vision Statement
i. To provide broad based quality education with knowledge and attitude to succeed in
Computer Science & Engineering careers.
ii. To prepare students for emerging trends in computer and related industry.
iii. To develop competence in students by providing them skills and aptitude to foster
culture of continuous and lifelong learning.
iv. To develop practicing engineers who investigate research, design, and find
workable solutions to complex engineering problems with awareness & concern for
society as well as environment.
iii. Graduates will be competent team leaders, effective communicators and capable of
working in multidisciplinary teams following ethical values.
iv. The graduates will be capable of adapting to new technologies/tools and constantly
upgrading their knowledge and skills with an attitude for lifelong learning
Department Program Outcomes (POs)
The students of Computer Science and Engineering Department will be able:
1. Engineering knowledge: Apply the knowledge of mathematics, science, Computer Science &
Engineering fundamentals, and an engineering specialization to the solution of complex
engineering problems.
2. Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of mathematics,
natural sciences, and Computer Science & Engineering sciences.
5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modelling to complex Computer Science &
Engineering activities with an understanding of the limitations.
6. The Engineering and Society: Apply reasoning informed by the contextual knowledge to
assess societal, health, safety, legal and cultural issues and the consequent responsibilities relevant
to the professional engineering practice in the field of Computer Science and Engineering.
7. Environment and sustainability: Understand the impact of the professional Computer Science
& Engineering solutions in societal and environmental contexts, and demonstrate the knowledge
of, and need for sustainable development.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the Computer Science & Engineering practice.
9. Individual and team work: Function effectively as an individual, and as a member or leader in
diverse teams, and in multidisciplinary settings.
11. Project management and finance: Demonstrate knowledge and understanding of the
Computer Science & Engineering and management principles and apply these to one’s own work,
as a member and leader in a team, to manage projects and in multidisciplinary environments.
12. Life-long learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.
Department Program Specific Outcomes (PSOs)
i) Course Objective:
Students shall be able to design and implement object-oriented solutions to real life problems,
algorithmic problems and web application development using basic Java programming
constructs, Collection Framework and Java Spring Boot respectively.
To apply [3. Apply] object-oriented approach to solve real-life problems and the
BCS-452.1 compilation and interpretation process of JRE, take argument from command
line and eclipse platform.
BCS-452.2 To analyze [4. Analyze] Java Collection Framework and new language features
for efficient application development.
BCS-452.3
To develop [6. Create] and deploy web applications using Spring Boot.
List of Experiments
Lab Correspo
Lab Experiment
No. nding CO
Write a simple Java program using Eclipse IDE to display the message "Hello, Java
World from Eclipse!" on the console, also use all major escape sequences including \n
1 (newline), \t (tab), \\ (backslash), \" (double quote), \' (single quote), and \r (carriage CO1
return). The program should demonstrate the basic structure of a Java application
including the main() method and System.out.println() function for output.
Write a Java program that accepts two integer numbers as command-line arguments,
2 calculates their sum, and displays the result. Ensure that the program properly parses CO1
the command-line arguments and handles basic integer operations.
Write a Java program to create two classes: Student and Rectangle.
The student class should have two data members: name and rollNo, with a
method to display the student's details.
3 The Rectangle class should have two data members: length and width, with a CO2
method to calculate and display the area of the rectangle.
Create objects for both classes, assign values to the data members, and invoke their
respective methods to display the output.
Write a Java program to demonstrate the concepts of inheritance and polymorphism:
Create two classes, Animal and Dog, where Dog inherits from Animal to
demonstrate single-level inheritance.
Override a method in the Dog class to demonstrate method overriding
(runtime polymorphism).
4 Implement method overloading within the Dog class by creating multiple CO2
versions of a bark() method with different parameters to demonstrate
compile- time polymorphism.
The program should create objects of the classes and invoke the methods to show
the behavior of inheritance, method overriding, and method overloading.
Write a Java program that demonstrates exception handling using try, catch, and
5 finally blocks to handle arithmetic exceptions. Extend the program to implement CO2
multithreading by creating and running two threads that print a message concurrently.
Write a Java program that creates a user-defined package named studentinfo,
containing a class Student with basic details. In another class, import this package
6 CO2
and display the student information, demonstrating the use of Java packages for
modular development.
Write a Java program that uses Java I/O streams to read data from a text file and write
7 data to another text file. The program should demonstrate file reading using CO2
FileReader and writing using FileWriter, along with proper exception handling.
Create a simple Spring-based Java application using annotation-based configuration.
The program should demonstrate dependency injection and include a service class
8 CO3
and a main class to invoke a method through Spring's @Component and @Autowired
annotations.
Develop a RESTful web service using Spring Boot. Create a controller that
9 responds to HTTP GET requests and returns a simple JSON message. Use Spring CO3
Boot annotations like @RestController and @GetMapping to handle requests.
Build a basic frontend web application using Spring Boot and Thymeleaf. Create a
webpage that collects user input from a form and displays the submitted data back
10 CO3
to the user. Demonstrate integration of backend logic with frontend rendering using
@Controller and Model.
Date
Date of Faculty
Lab of
Lab Experiment Subm Marks
Experim Signat
No. ission
ent ure
Write a simple Java program using Eclipse IDE to display
the message "Hello, Java World from Eclipse!" on the
console, also use all major escape sequences including \n
(newline), \t (tab), \\ (backslash), \" (double quote), \'
1
(single quote), and \r (carriage return). The program
should demonstrate the basic structure of a Java
application including the main() method and
System.out.println() function for output.
Write a Java program that accepts two integer numbers as
command-line arguments, calculates their sum, and
2 displays the result. Ensure that the program properly
parses the command-line arguments and handles basic
integer
operations.
Write a Java program to create two classes: Student and
Rectangle.
The student class should have two data
members: name and rollNo, with a method to
display the student's details.
3 The Rectangle class should have two data
members: length and width, with a method to
calculate and display the area of the rectangle.
Create objects for both classes, assign values to the data
members, and invoke their respective methods to
display the output.
Write a Java program to demonstrate the concepts of
inheritance and polymorphism:
Create two classes, Animal and Dog, where Dog
inherits from Animal to demonstrate single-level
inheritance.
Override a method in the Dog class to
demonstrate method overriding (runtime
4 polymorphism).
Implement method overloading within the Dog
class by creating multiple versions of a bark()
method with different parameters to demonstrate
compile-time polymorphism.
The program should create objects of the classes and
invoke the methods to show the behavior of inheritance,
method overriding, and method overloading.
Write a Java program that demonstrates exception
handling using try, catch, and finally blocks to handle
5 arithmetic exceptions. Extend the program to implement
multithreading by creating and running two threads that
print a message concurrently.
Write a Java program that creates a user-defined
package named studentinfo, containing a class Student
6
with basic
details. In another class, import this package and display
the student information, demonstrating the use of Java
packages for modular development.
Write a Java program that uses Java I/O streams to read
data from a text file and write data to another text file.
7 The program should demonstrate file reading using
FileReader and writing using FileWriter, along with
proper exception handling.
Create a simple Spring-based Java application using
annotation-based configuration. The program should
8 demonstrate dependency injection and include a service
class and a main class to invoke a method through
Spring's @Component and @Autowired annotations.
Develop a RESTful web service using Spring Boot.
Create a controller that responds to HTTP GET
9 requests and returns a simple JSON message. Use
Spring Boot annotations like @RestController and
@GetMapping to
handle requests.
Build a basic frontend web application using Spring
Boot and Thymeleaf. Create a webpage that collects
user input from a form and displays the submitted data
10
back to the user. Demonstrate integration of backend
logic with frontend rendering using @Controller and
Model.
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India
Experiment No. 1
Objective: Write a simple Java program using Eclipse IDE to display the message
"Hello, Java World from Eclipse!" on the console, also use all major escape sequences
including
\n (newline), \t (tab), \\ (backslash), \" (double quote), \' (single quote), and \r (carriage
return). The program should demonstrate the basic structure of a Java application
including the main() method and System.out.println() function for output.
Program:
public class EscapeDemo {
public static void main(String[] args) {
// Basic message
System.out.println("Hello, Java World from Eclipse!");
Experiment No. 2
Objective: Write a Java program that accepts two integer numbers as command-line
arguments, calculates their sum, and displays the result. Ensure that the program properly
parses the command-line arguments and handles basic integer operations.
Program:
public class CommandLineSum {
public static void main(String[] args) {
// Check if two arguments are provided
if (args.length < 2) {
System.out.println("Please provide two integer numbers as command-line
arguments.");
return;
}
try {
// Parse the arguments from String to int
int num1 = Integer.parseInt(args[0]);
int num2 = Integer.parseInt(args[1]);
Experiment No. 3
Objective: Write a Java program to create two classes: Student and Rectangle.
• The student class should have two data members: name and rollNo, with a method
to display the student's details.
• The Rectangle class should have two data members: length and width, with a
method to calculate and display the area of the rectangle.
Create objects for both classes, assign values to the data members, and invoke their
respective methods to display the output.
Program:
// Student class class Student
{
String name;
int rollNo;
// Constructor
Student(String name, int rollNo)
{
this.name = name;
this.rollNo = rollNo;
}
// Constructor
Rectangle(double length, double width)
{
this.length = length;
this.width = width;
}
// Method to calculate and display area
void displayArea()
{
double area = length * width;
{
public static void main(String[] args)
{
// Creating a Student object
Student student1 = new Student("Alice", 101);
student1.displayDetails(); System.out.println();
Experiment No. 4
Objective: Write a Java program to demonstrate the concepts of inheritance and
polymorphism:
Create two classes, Animal and Dog, where Dog inherits from Animal to
demonstrate single-level inheritance.
Override a method in the Dog class to demonstrate method overriding (runtime
polymorphism).
Implement method overloading within the Dog class by creating multiple
versions of a bark() method with different parameters to demonstrate compile-
time polymorphism.
The program should create objects of the classes and invoke the methods to show the
behavior of inheritance, method overriding, and method overloading.
Program:
class Animal {
void makeSound() {
System.out.println("The animal makes a sound.");
}
}
class Dog extends Animal {
void makeSound() {
System.out.println("The dog barks.");
}
void bark() {
System.out.println("Dog is barking normally.");
}
void bark(String type) {
System.out.println("Dog is barking in a " + type + " way.");
}
void bark(int times) {
System.out.println("Dog barked " + times + " times.");
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING BCS-452
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India
}
}
public class InheritancePolymorphismDemo
{ public static void main(String[] args) {
Animal myAnimal = new Animal();
Animal myDog = new Dog();
myAnimal.makeSound();
myDog.makeSound();
Dog dog = new Dog();
dog.bark();
dog.bark("loud");
dog.bark(3);
}
}
Experiment No. 5
Objective: Write a Java program that demonstrates exception handling using try, catch,
and finally blocks to handle arithmetic exceptions. Extend the program to implement
multithreading by creating and running two threads that print a message concurrently.
Program:
class ExceptionHandlingDemo
{ void divide(int a, int b) {
try {
int result = a / b;
System.out.println("Result: " + result);
} catch (ArithmeticException e)
{ System.out.println("Error: Cannot divide by
zero.");
} finally {
System.out.println("Execution of divide method completed.");
}
}
}
handler.divide(10, 0);
MyThread1 t1 = new MyThread1();
MyThread2 t2 = new MyThread2();
t1.start();
t2.start();
}
}
Experiment No. 6
Objective: Write a Java program that creates a user-defined package named
studentinfo, containing a class Student with basic details. In another class, import this
package and display the student information, demonstrating the use of Java packages
for modular development.
Program:
package studentinfo;
Experiment No. 7
Objective: Write a Java program that uses Java I/O streams to read data from a text file
and write data to another text file. The program should demonstrate file reading using
FileReader and writing using FileWriter, along with proper exception handling.
Program:
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
try {
reader = new FileReader("input.txt");
writer = new FileWriter("output.txt");
int ch;
while ((ch = reader.read()) != -1) {
writer.write(ch);
}
System.out.println("File has been read from 'input.txt' and written to 'output.txt'
successfully.");
} catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
} finally {
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING BCS-452
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India
try {
if (reader != null) reader.close();
if (writer != null) writer.close();
} catch (IOException e) {
System.out.println("Error while closing resources: " + e.getMessage());
}
}
}
}
Experiment No. 8
Objective: Create a simple Spring-based Java application using annotation-based
configuration. The program should demonstrate dependency injection and include a
service class and a main class to invoke a method through Spring's @Component and
@Autowired annotations.
Program:
CSS:
spring-demo/
│
├── src/
│ └── main/
│ └── java/
│ ├── AppConfig.java
│ ├── MainApp.java
│ └── service/
│ └── GreetingService.java
│
└── pom.xml (for Maven projects)
package service;
import org.springframework.stereotype.Component;
public class GreetingService {
public void greet() {
System.out.println("Hello from Spring Dependency Injection!");
}
}
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
public class AppConfig {
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import service.GreetingService;
Steps to Run:
1. Set up Maven Project (Optional but recommended):
Add Spring Core dependencies to pom.xml:
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.22</version>
</dependency>
</dependencies>
2. Compile and run the application using your IDE (like IntelliJ or Eclipse) or using
Maven from terminal:
mvn compile
mvn exec:java -Dexec.mainClass="MainApp"
Experiment No. 9
Objective: Develop a RESTful web service using Spring Boot. Create a controller that
responds to HTTP GET requests and returns a simple JSON message. Use Spring Boot
annotations like @RestController and @GetMapping to handle requests.
Program:
CSS:
springboot-demo/
│
├── src/
│ └── main/
│ └── java/
│ └── com/example/demo/
│ ├── DemoApplication.java
│ └── controller/
│ └── HelloController.java
│
└── pom.xml
1. DemoApplication.java
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
public class DemoApplication {
public static void main(String[] args)
{ SpringApplication.run(DemoApplication.class,
args);
}}
2. HelloController.java
package com.example.demo.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
@RestController
public class HelloController {
@GetMapping("/greet")
public Map<String, String> greetUser() {
Map<String, String> response = new HashMap<>();
response.put("message", "Hello! Welcome to your first Spring Boot REST API.");
return response;
}
}
Experiment No. 10
Objective: Build a basic frontend web application using Spring Boot and Thymeleaf.
Create a webpage that collects user input from a form and displays the submitted data
back to the user. Demonstrate integration of backend logic with frontend rendering using
@Controller and Model.
Program:
CSS:
thymeleaf-demo/
│
├── src/
│ └── main/
│ ├── java/
│ │ └── com/example/demo/
│ │ ├── ThymeleafDemoApplication.java
│ │ └── controller/
│ │ └── UserController.java
│ └── resources/
│ ├── templates/
│ │ ├── form.html
│ │ └── result.html
│ └── application.properties
│
└── pom.xml
1. ThymeleafDemoApplication.java
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ThymeleafDemoApplication
{ public static void main(String[] args) {
SpringApplication.run(ThymeleafDemoApplication.class, args);
}
}
2. UserController.java
package com.example.demo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
@Controller
public class UserController {
@GetMapping("/form")
public String showForm() {
return "form";
}
@PostMapping("/submit")
public String submitForm(@RequestParam String name, @RequestParam String
email, Model model) {
model.addAttribute("name", name);
model.addAttribute("email", email);
return "result";
}}
3. form.html (Inside resources/templates/)
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>User Form</title>
</head>
<body>
<h2>User Input Form</h2>
<form action="/submit" method="post">
Name: <input type="text" name="name"/><br><br>
Email: <input type="email" name="email"/><br><br>
<button type="submit">Submit</button>
</form>
</body>
</html>
4. result.html (Inside resources/templates/)
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Result Page</title>
</head>
<body>
<h2>Submitted Details</h2>
<p>Name: <span th:text="${name}"></span></p>
Dependencies (pom.xml)
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>