0% found this document useful (0 votes)
3 views22 pages

Java File Final Exp. (1-10)

The document is a practical file for the OOPS with Java Lab course at Galgotias College of Engineering & Technology, detailing various experiments conducted by a student named Aman Kumar. It includes objectives, problem statements, algorithms, and code examples for each experiment, covering topics such as command line arguments, classes, inheritance, exception handling, file handling, and the Spring Framework. Each experiment is designed to enhance understanding of Java programming concepts and practices.

Uploaded by

akshatgoantiya3
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)
3 views22 pages

Java File Final Exp. (1-10)

The document is a practical file for the OOPS with Java Lab course at Galgotias College of Engineering & Technology, detailing various experiments conducted by a student named Aman Kumar. It includes objectives, problem statements, algorithms, and code examples for each experiment, covering topics such as command line arguments, classes, inheritance, exception handling, file handling, and the Spring Framework. Each experiment is designed to enhance understanding of Java programming concepts and practices.

Uploaded by

akshatgoantiya3
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

Galgotias College of Engineering & Technology, Greater Noida

Affiliated to Dr. A. P. J. AKTU, Lucknow

Department of AI

PRACTICAL FILE
OOPS with Java Lab

(BCS 452)

(Even Semester, 2025-26)

4th Semester

SUBMITTED TO: SUBMITTED BY:


Dr. Sitaram Patel Sir Aman Kumar
Roll No.-2400971520021
Galgotias College of Engineering & Technology
Knowledge Park-II, Greater Noida, Uttar Pradesh, India
Department of AI

Lab Evaluation Record

Student Name: Aman Kumar

Roll No: 2400971520021

Branch/Sem: AI/4th Sem 2rd Year

Exp Name of Experiment C Date Reco EIA Viva Total Faculty


No. O of rd (4) (3) (3) (10) sign
Practi with
cal date

Average Marks:

Faculty Signature with Date: ____________________


Experiment No.- 1
Java Program using Command Line Arguments, Arrays and
Control Structures
Objective: To understand how to use command line arguments and apply arrays and control structures in
Java.

Problem Statement: Write a Java program to take command line input, store values in an array, and
perform control operations (e.g., print even numbers).

Software Required:

 JDK 17+

CO Mapping: CO1

Algorithm:

1. Read command line arguments.


2. Convert them to integers and store in array.
3. Use control structures to print even numbers.

Code:

public class CommandLineArray {


public static void main(String[] args) {
int[] numbers = new int[[Link]];
[Link]("Even numbers:");
for (int i = 0; i < [Link]; i++) {
numbers[i] = [Link](args[i]);
if (numbers[i] % 2 == 0) {
[Link](numbers[i]);
}
}
}
}
Output:
Experiment No.- 2
Java Project Setup using Eclipse IDE - Classes, Constructors,
Comments, and Method Structure
Objective: To demonstrate Java project creation in Eclipse IDE and understand the structure of Java classes,
use of constructors, inline documentation, and method declarations.

Problem Statement: Set up a Java project in Eclipse IDE that defines a class Student with attributes,
constructor, and methods to display student information.

Software Required:

 Eclipse IDE
 JDK 17+

CO Mapping: CO1

Algorithm:

1. Open Eclipse and create a new Java project.


2. Create a new class named Student.
3. Add data members: name, rollNumber.
4. Write a parameterized constructor.
5. Add a method displayInfo() to print the details.
6. In main(), create an object and call the method.

Code:

// [Link]
public class Student {
String name;
int rollNumber;
// Constructor
public Student(String name, int rollNumber) {
[Link] = name;
[Link] = rollNumber;
}
// Method to display student information
public void displayInfo() {
[Link]("Name: " + name);
[Link]("Roll Number: " + rollNumber);
}

public static void main(String[] args) {


Student s1 = new Student("Rahul", 101);
[Link]();
}
}
Output:

Name: Rahul

Roll Number: 101


Experiment No.- 3
Classes and Objects Demonstrating Encapsulation, Constructors,
and Method Overloading
Objective: To understand object-oriented principles like encapsulation and demonstrate the use of
constructors and method overloading.

Problem Statement: Create a class Employee with encapsulated data members. Use constructors to
initialize and overload a method to calculate salary with and without bonuses.

Software Required:

 JDK 17+

CO Mapping: CO1

Algorithm:

1. Define private data members: name, baseSalary.


2. Provide public getter and setter methods.
3. Overload a method calculateSalary() with and without bonus parameter.
4. Create an object and demonstrate functionality.

Code:
public class Employee {
private String name;
private double baseSalary;
// Constructor
public Employee(String name, double baseSalary) {
[Link] = name;
[Link] = baseSalary;
}
// Getter methods
public String getName() {
return name;
}
public double getBaseSalary() {
return baseSalary;
}
// Overloaded method
public double calculateSalary() {
return baseSalary;
}
public double calculateSalary(double bonus) {
return baseSalary + bonus;
}
public static void main(String[] args) {
Employee emp = new Employee("Rohit", 30000);
[Link]("Base Salary: " + [Link]());
[Link]("Salary with Bonus: " +
[Link](5000));
}}
Output:

Base Salary: 30000.0

Salary with Bonus: 35000.0


Experiment No.- 4
Inheritance,Method Overriding, and
Use of super Keyword
Objective: To implement inheritance in Java and understand how method overriding and the super keyword work.

Problem Statement: Create a base class Person and a derived class Student. Override a method in the subclass and
use the super keyword to invoke the parent class method.

Software Required:
 JDK 17+

CO Mapping: CO1

Algorithm:
1. Define a base class Person with a method showDetails().
2. Define a subclass Student that overrides showDetails().
3. Use the super keyword to call the base class version of the method.
4. Instantiate the subclass and invoke the overridden method.

Code:
class Person {
String name = "Deepak";

public void showDetails() {


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

class Student extends Person {


int rollNo = 101;

@Override
public void showDetails() {
[Link]();
[Link]("Roll Number: " + rollNo);
}

public static void main(String[] args) {


Student s = new Student();
[Link]();
}
}

Output:
Experiment 5
User-defined Packages and
Generating JAR Files
Objective: To create user-defined packages in Java and learn how to generate and use JAR files.

Problem Statement: Create a package gcetpack containing a class Greeting. Import this package into another class
and generate a JAR file for reuse.

Software Required:
 JDK 17+
 Command Line / IDE

CO Mapping: CO1

Algorithm:
1. Create a folder structure for the package.
2. Create the Greeting class with a display method.
3. Compile the class using command line with -d option.
4. Create another class to import and use the package.
5. Use jar command to create a JAR file.

Code:
// File: gcetpack/[Link]
package gcetpack;
public class Greeting {
public void sayHello() {
[Link]("Welcome to GCET Java Lab!");
}
}

// File: [Link]
import [Link];
public class TestGreeting {
public static void main(String[] args) {
Greeting g = new Greeting();
[Link]();
}
}
Commands:
javac -d . gcetpack/[Link]
javac -cp . [Link]
java TestGreeting
jar cf [Link] gcetpack/*.class

Output:
Welcome to GCET Java Lab!
Experiment 6
Exception Handling using try, catch, finally,
and Custom Exceptions
Objective: To understand the concept of exception handling in Java using try-catch-finally blocks and creating user-
defined exceptions.

Problem Statement: Write a Java program to handle arithmetic exceptions and create a custom exception class for
invalid age input.

Software Required:
 JDK 17+

CO Mapping: CO2

Algorithm:
1. Create a method that may cause an exception (e.g., division by zero).
2. Use try, catch, and finally blocks to handle the exception.
3. Create a custom exception class named InvalidAgeException.
4. Throw the exception for age < 18.

Code:
// Custom Exception
class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);
}
}

public class ExceptionDemo {


public static void main(String[] args) {
// Built-in exception handling
try {
int a = 10, b = 0;
int c = a / b;
[Link]("Result: " + c);
} catch (ArithmeticException e) {
[Link]("Caught ArithmeticException: " + e);
} finally {
[Link]("Finally block executed");
}

// Custom exception usage


try {
checkAge(16);
} catch (InvalidAgeException e) {
[Link]("Custom Exception: " + [Link]());
}
}

static void checkAge(int age) throws InvalidAgeException {


if (age < 18) {
throw new InvalidAgeException("Age must be 18 or above.");
} else {
[Link]("Age is valid.");
}
}
}

Output:
Caught ArithmeticException: [Link]: / by zero
Finally block executed
Custom Exception: Age must be 18 or above.
Experiment No. 7
Aim: To construct a Java program using Java I/O package for file handling (reading and writing data).

Theory:
Java I/O package is used to perform input and output operations in Java. It is available in [Link] package.
Java uses streams for input and output operations. A stream is a sequence of data. Input Stream is used
to read data from a source and Output Stream is used to write data to a destination.

There are two types of streams in Java:


1. Byte Stream – Used for binary data like images and audio files.
2. Character Stream – Used for text data like files and documents.

Important classes of Java I/O package:


• File – Used to create and manage files.
• FileWriter – Used to write data into file.
• FileReader – Used to read data from file.
• BufferedReader – Used to read text efficiently.
• BufferedWriter – Used to write text efficiently.

Algorithm:
1. Start the program.
2. Create a file using FileWriter.
3. Write data into the file.
4. Close the file.
5. Open the file using FileReader.
6. Read data from the file using BufferedReader.
7. Display the file content.
8. Stop the program.

Program:
import [Link].*;
import [Link];

public class Main {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

try {
// Take input from user
[Link]("Enter Name: ");
String name = [Link]();

[Link]("Enter Course: ");


String course = [Link]();

// Write into file


FileWriter fw = new FileWriter("[Link]");
BufferedWriter bw = new BufferedWriter(fw);

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


[Link]();
[Link]("Course: " + course);
[Link]();
[Link]("\nData written successfully.\n");

// Read from file


FileReader fr = new FileReader("[Link]");
BufferedReader br = new BufferedReader(fr);

String line;
[Link]("Reading from file:\n");

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


[Link](line);
}

[Link]();
}
catch(IOException e) {
[Link]("Error: " + e);
}
}
}
Output:

Result:
The program was successfully executed demonstrating file handling using Java I/O package.
Experiment No. 8
Aim: To create an industry-oriented application using Spring Framework.

Theory:
Spring Framework is a powerful framework used to build enterprise-level Java applications. It provides
features like Dependency Injection (DI), Aspect-Oriented Programming (AOP), Model-View-Controller
(MVC), and database connectivity.

Spring framework is used in industry to develop web applications, REST APIs, microservices, and
enterprise applications. It reduces code complexity and improves performance and scalability.

Main Modules of Spring Framework:


• Spring Core – Provides Dependency Injection.
• Spring MVC – Used to build web applications.
• Spring Boot – Used to create standalone applications.
• Spring Data – Used for database operations.
• Spring Security – Used for authentication and authorization.

Algorithm:
1. Start the program.
2. Create a Spring Boot project.
3. Create a Controller class.
4. Create a Service class.
5. Create a Model class.
6. Run the Spring Boot application.
7. Open browser and test the application.
8. Stop the program.

Program:
import [Link].*;

class Student {
int id;
String name;

Student(int id, String name) {


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

class StudentService {
List<Student> students = new ArrayList<>();

void addStudent(int id, String name) {


[Link](new Student(id, name));
[Link]("Student Added Successfully");
}

void displayStudents() {
[Link]("\nStudent List:");
for(Student s : students) {
[Link]("ID: " + [Link] + " Name: " + [Link]);
}
}
}

public class Main {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
StudentService service = new StudentService();

[Link]("Enter Student ID: ");


int id = [Link]();
[Link]();

[Link]("Enter Student Name: ");


String name = [Link]();

[Link](id, name);
[Link]();
}
}

Output:

Spring Application Running Successfully

Result:
The Spring Framework application was successfully created and executed.
Experiment No. 9
Objective / Aim : Students will learn about how to Test Frontend web application with Spring
Boot.
Apparatus Used : Jdk11, Eclipse, Notepad++, Visual Studio Literature / Theory / Formula :
• Spring Boot is a project that is built on top of the Spring Framework. It provides an
easier and faster way to set up, configure, and run both simple and web-based
applications.
• It is a Spring module that provides the RAD (Rapid Application Development) feature to
the Spring Framework used to create a stand-alone Spring-based application that you
can just run because it needs minimal Spring configuration.
Source Code:

Step 1: Add Dependencies to [Link]


<dependencies>

<!-- Spring Boot Web Starter -->


<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring Boot Test Starter -->
<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- For JSON processing -->
<dependency>
<groupId>[Link]</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
</dependencies>
Step 2: Create a RESTful Web Service [Link]
package [Link]; public class Employee { private
long id; private String name; private String role;
// Constructors, getters, and setters public Employee() {}
public Employee(long id, String name, String role) { [Link] = id; [Link] = name; [Link] =
role;
}
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 getRole() { return role;
}
public void setRole(String role) { [Link] = role;
}
}
Step 3: Write Unit Tests for the RESTful Web Service Create a test class for EmployeeController.
[Link]
package [Link];
import [Link];
import [Link]; import [Link];
import [Link];
import [Link];
import [Link]; import
[Link];
import [Link];

import static [Link].*; import


static [Link].*;

@WebMvcTest([Link]) public class EmployeeControllerTest {


@Autowired
private MockMvc mockMvc; @Autowired private ObjectMapper objectMapper; private Employee
employee; @BeforeEach
public void setup() {
employee = new Employee(1L, "John Doe", "Developer");
}
@Test
public void testCreateEmployee() throws Exception { [Link](post("/employees")
.contentType(MediaType.APPLICATION_JSON)
.content([Link](employee)))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").value([Link]()))
.andExpect(jsonPath("$.role").value([Link]()));
}
@Test
public void testGetAllEmployees() throws Exception { [Link](get("/employees"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON));
}

@Test
public void testGetEmployeeById() throws Exception { [Link](post("/employees")
.contentType(MediaType.APPLICATION_JSON)
.content([Link](employee)))
.andExpect(status().isOk()); [Link](get("/employees/{id}", 1L))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").value([Link]()))
Experiment No. 10

Objective / Aim : Students will learn about how to Test RESTful web services using Spring Boot.

Apparatus Used : Jdk11, Eclipse, Notepad++, Visual Studio Literature / Theory / Formula :

REST stands for Representational State Transfer. It is developed by Roy Thomas Fielding, who also developed HTTP. The main
goal of RESTful web services is to make web services more effective. RESTful web services try to define services using the
different concepts that are already present in HTTP. REST is an architectural approach, not a protocol.

Source Code:

We have used POSTMAN to test Application developed in Experiment 9 as follows

POST

[Link]

GET

[Link]
PUT

[Link]
DELETE

[Link]

You might also like