0% found this document useful (0 votes)
5 views

oops file

The document is a practical file for the Object Oriented Programming with Java Lab course at GL Bajaj Institute of Technology and Management for the 2024-25 session. It includes a list of experiments covering various Java programming concepts such as basic Java programming, OOP principles, inheritance, polymorphism, exception handling, multithreading, and file I/O operations. Each experiment outlines objectives, required software, theoretical concepts, and sample code for practical implementation.

Uploaded by

omshriansh16
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 views

oops file

The document is a practical file for the Object Oriented Programming with Java Lab course at GL Bajaj Institute of Technology and Management for the 2024-25 session. It includes a list of experiments covering various Java programming concepts such as basic Java programming, OOP principles, inheritance, polymorphism, exception handling, multithreading, and file I/O operations. Each experiment outlines objectives, required software, theoretical concepts, and sample code for practical implementation.

Uploaded by

omshriansh16
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
You are on page 1/ 27

GL BAJAJ INSTITUTE OF TECHNOLOGY AND

MANAGEMENT, GREATER NOIDA

OBJECT ORIENTED PROGRAMMING WITH JAVA LAB


PRACTICAL FILE (BCS 452)
SESSION 2024-25

BACHELOR OF TECHNOLOGY
IN
COMPUTER SCIENCE & ENGINEERING

SUBMITTED BY: SUBMITTED TO:


NAME: Ms. Mitali Bhatt
SECTION: ( Department CSE)
SEMESTER:
ROLL NO.:
List of Experiments

S.No. Name of Experiment Date of Page No. Grade Sign


Experiment
Experiment-1
Objective: Use Java compiler and eclipse platform to write and execute java
program.

Software Required: Eclipse,VS Code


ALGORITHM:
1.Install Eclipse
 Download and install the Eclipse IDE from the official
website (https://www.eclipse.org/downloads/).

 Follow the installation instructions for your operating system.

2.Open Eclipse:
 Launch Eclipse IDE after installation.

3.Create a New Java Project:


 Go to File > New > Java Project.

 Enter a project name (e.g., MyJavaProject) and click Finish.

4.Create a Java Class:


 Right-click on the src folder inside your
project. Go to New > Class.

 Enter a class name (e.g., MyFirstJavaProgram) and check the box for public static
void main (String [] args).

 Click Finish.

5.Write Java Code:


 In the editor window for MyFirst JavaProgram.java, write your Java
code. Below is a simple "Hello World" example:

1
CODE:

public class MyFirstJavaProgram {

public static void main (String [] args) { System.out.println("Hello


World");

6.Save the Java File:


 Press Ctrl + S (Windows/Linux) or Cmd + S (Mac) to save the Java file.

7.Compile the Java Program:


 Eclipse automatically compiles the Java program when you save the
file. Any compilation errors will be shown in the Problems tab.

8.Run the Java Program:


 Right-click on the MyFirst JavaProgram class file in the Package
Explorer. Select Run As > Java Application.

 The program output (Hello World) will be displayed in the Console view at the
Bottom.

OUTPUT:

2
Experiment-2
Objective: Creating simple java program using command line argument.

Software Required: Eclipse,VS Code


Example 1: Star Pyramid Pattern in Java
CODE:

import java.util.Scanner;

public class StarPattern {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Get number of rows from user


System.out.print("Enter the number of rows: ");
int rows = scanner.nextInt();

// Create the pattern


for (int i = 1; i <= rows; i++) {
// Print spaces
for (int j = 1; j <= rows - i; j++) {
System.out.print(" ");
}
// Print stars
for (int k = 1; k <= (2 * i - 1); k++) {
System.out.print("*");
}
System.out.println();
}

3
Example 2: Even Number Series in Java

CODE:

import java.util.Scanner;

public class EvenSeries {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Ask the user how many even numbers to print


System.out.print("Enter the number of even numbers to display: ");
int n = scanner.nextInt();

System.out.println("Even Number Series:");


for (int i = 1; i <= n; i++) {
System.out.print((2 * i) + " ");
}

scanner.close();
}
}

4
[Type text]

Experiment-3
Objective: Understand OOPS Concept and basics of Java Programming.

Software Required: Eclipse,VS Code

Theory:

1) Abstraction:

 Abstraction in Java is an OOP concept that hides complex implementation


details and exposes only essential features to the user, achieved through
abstract classes and interfaces.

2) Polymorphism:

 Allows objects of different classes to be treated as objects of a common


superclass.

3) Inheritance:

 Mechanism where a child class acquires properties/methods of parent


class

4) Classes & Objects:

 Class: Blueprint/template (e.g., class Car { })

 Object: Instance of class (e.g., Car myCar = new Car();)

5) Constructor :

 Special method that initializes objects when created (new


keyword).

Types of Constructors in Java

1. Default Constructor
 Created automatically by Java if no constructor is defined.

 Has no parameters.

2. Parameterized Constructor
 Accepts parameters to initialize objects with specific values.

5
[Type text]

3.Copy Constructor

 Creates an object by copying values from another object.

6) this Keyword:

 Refers to current class instance

7) Constructor Overloading:

 Having multiple constructors with different methods.

Code:

class Student {
// Instance variables
String name;
int age;
double gpa;

// 1. Default Constructor (no parameters)


Student() {
name = "Unknown";
age = 18;
gpa = 3.0;
System.out.println("Default constructor called");
}

// 2. Parameterized Constructor
Student(String name, int age) {
this.name = name;
this.age = age;
System.out.println("Parameterized constructor (name, age) called");
}

// 3. Another Parameterized Constructor (overloaded)


Student(String name, int age, double gpa) {
this.name = name;
this.age = age;
this.gpa = gpa;
System.out.println("Parameterized constructor (name, age, gpa) called");
}

// 4. Copy Constructor
Student(Student other) {
this.name = other.name;
this.age = other.age;
6
[Type text]

this.gpa = other.gpa;

void display() {
System.out.println("Name: " + name + ", Age: " + age + ", GPA: " + gpa);
}
}

public class Main {


public static void main(String[] args) {
// Creating objects using different constructors

// 1. Default constructor
Student s1 = new Student();
s1.display();

// 2. Parameterized constructor (2 args)


Student s2 = new Student("Alice", 20);
s2.display();

// 3. Parameterized constructor (3 args) - overloaded


Student s3 = new Student("Bob", 21, 3.8);
s3.display();
// 4. Copy constructor
Student s4 = new
Student(s3); s4.display();
}
}

7
Experiment- 4
Objective: Create java program using inheritance and polymorphism.

SOFTWARE REQUIRED: Eclipse,VS Code

THEORY:

1)Inheritance:

 Mechanism where a child class acquires properties/methods of parent


class

ypes of Inheritance
1. Single Inheritance

A subclass inherits from one superclass.

CODE:

class Animal
{ void
eat() {
System.out.println("This animal eats food");
}
}

class Dog extends


Animal { void bark() {
System.out.println("Dog barks");
}
}

public class Main {


public static void main(String[]
args) { Dog d = new Dog();
d.eat();
d.bark();
}
}

8
2. Multilevel Inheritance

 A class inherits from a class which itself inherits from another class.

CODE:

class Grandparent
{ void
display1() {
System.out.println("Grandparent");
}
}

class Parent extends Grandparent


{ void display2() {
System.out.println("Parent");
}
}

class Child extends


Parent { void
display3() {
System.out.println("Child");
}
}

public class Test {


public static void main(String[]
args) { Child c = new Child();
c.display1();
c.display2();
c.display3();
}

9
3.Hierarchical Inheritance

 Multiple classes inherit from the same parent class.

CODE:
class Animal{
void sound() {
System.out.println("Animal makes a sound");
}
}

class Cat extends


Animal { void
meow() {
System.out.println("Cat meows");
}
}

class Dog extends


Animal { void
bark() {
System.out.println("Dog barks");
}
}

public class Main {


public static void main(String[]
args) { Cat c = new Cat();
Dog d = new Dog();

c.sound();
c.meow();

d.sound();
d.bark();
}
}

10
2)Polymorphism
It allows objects to behave differently based on their context, even if they share the same
interface or method name.

Types of Polymorphism in Java

1. Compile-time polymorphism(Method Overloading):

 When multiple methods in the same class have the same name but different
parameters.

CODE:
class Calculator {
int add(int a, int b) {
return a + b;
}

double add(double a, double


b) { return a + b;
}

int add(int a, int b, int c) {


return a + b + c;
}
}

public class Main {


public static void main(String[] args) {
Calculator calc = new Calculator();
System.out.println(calc.add(2, 3)); // int version
System.out.println(calc.add(2.5, 3.5)); // double version
System.out.println(calc.add(1, 2, 3)); // 3-arg version
}
}

2. Runtime Polymorphism (Method Overriding)


11
When a subclass provides a specific implementation of a method already defined in its
superclass.

CODE:
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}

class Dog extends Animal {


void sound() {
System.out.println("Animal makes a sound");
}
}

class Cat extends


Animal { void
sound() {
System.out.println("Cat meows");
}
}

public class Main {


public static void main(String[] args)
{ Animal a;

a = new Dog();
a.sound();

a = new Cat();
a.sound();
}
}

12
[

Experiment-5
Objective: Implement user handling technique using exception handling and
multithreading.

Software Required: Eclipse,VS Code

Theory: Here are common java exceptions:

Arithmetic Exception Divide by zero, etc.


Null Pointer Exception Accessing members of a null object
Array Index Out Of Bounds Exception Invalid index in an array
IO Exception Input/output operation fails
Class Not Found Exception Class not found while loading

In java exception can be handle using:

try Defines a block of code to test for exceptions.


catch Catches and handles exceptions thrown in the try block.
finally Executes code after try/catch, whether or not an exception occurred.
throw Manually throws a specific exception.
throws Declares exceptions a method might throw to the caller.

Code:
//1.Arithmetic Exception
public class ExceptionHandling {
public class ExceptionHandling{
public static void main(String[] args) {
try{
int a=5/0;
}
catch(ArithmeticException e){
System.out.println("Exception caught:"+e.getMessage());
}
}
}

//2.Null Pointer Exception Handling

try{
String str=null;
System.out.print(str.length());
}
catch(NullPointerException e){
System.out.println("Exception
caught:"+e.getMessage());
}

13
[

//3.Number Formal Exception Handling


try{
String Number="abc";
int b=Integer.parseInt(Number);
}
catch(NumberFormatException e){
System.out.println("Exception caught:"+e.getMessage());
}

//4.Array Index out of Exception Handling


try {
int[] arr = {1, 2, 3};
System.out.print(arr[5]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception caught: " + e.getMessage());
}

//multithreading

class A extends Thread {


public void run() {
for (int i = 1; i <= 10; i++) {
System.out.println("2 * " + i + " = " + (2 * i));
}
}
}

class B extends Thread {


public void run() {
for (int i = 1; i <= 10; i++) {
System.out.println("5 * " + i + " = " + (5 * i));
}
}
}

public class C {
public static void main(String[] args) {
A t1 = new A();
B t2 = new B();
t1.start();
t2.start();
}
}

14
[Type text]

Example 2:
class MyTask implements Runnable {
public void run() {
try {
System.out.println("Task started.");

// Simulate some work


for (int i = 1; i <= 3; i++) {
System.out.println("Step " + i);
if (i == 2) {
throw new RuntimeException("Error at step 2");
}
}

System.out.println("Task completed.");
} catch (Exception e) {
System.out.println("Caught exception: " + e.getMessage());
}
}
}

public class Main {


public static void main(String[] args) {
Runnable task = new MyTask();
Thread thread = new Thread(task);
thread.start();
}
}

15
[]
Experiment-6

Experiment-6
Objective:Create a java program using java packages.

Software Required: Eclipse,VS Code

Theory:
Package Class Used Purpose
java.util ArrayList, Date Lists, date-time
java.text Simple Date Format Formatting Date objects
java.io File, I O Exception Creating/handling files
java.time Local Date Time Current date and time
java.math Big Decimal High-precision arithmetic

Code:
import java.math.BigInteger;
import java.util.Scanner;

public class PowerAndMod {


public static void main(String[ ] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter base: ");


BigInteger base = new BigInteger(scanner.nextLine());

System.out.print("Enter exponent: ");


BigInteger exponent = new BigInteger(scanner.nextLine());

System.out.print("Enter modulus: ");


BigInteger modulus = new BigInteger(scanner.nextLine());

BigInteger result = base.modPow(exponent, modulus);

System.out.println(base + "^" + exponent + " mod " + modulus + " = " + result);

scanner.close();
}
}

16
[Type text]

Experiment-7
Objective:Create a java program using java I/O packages.

Software Required: Eclipse,VS Code

Code:
import java.io.FileWriter;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;

public class SimpleFileIO {


public static void main(String[] args) {
String filename = "sample.txt";
String content = "Hello";

try {

FileWriter writer = new FileWriter(filename);


writer.write(content);
writer.close();
System.out.println("Successfully wrote to the file.");

FileReader reader = new FileReader(filename);


BufferedReader bufferedReader = new BufferedReader(reader);

System.out.println("Reading from the file:");


String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}

bufferedReader.close();
reader.close();

} catch (IOException e) {
System.out.println("An error occurred:");
e.printStackTrace();
}
}
}

17
Experiment-8
Objective:Create industry oriented application using Spring Framework

Student Management System with Spring Boot

Project Structure:
src/
├── main/
│ ├── java/com/example/studentmgmt/
│ │ ├── controller/
│ │ ├── model/
│ │ ├── repository/
│ │ └── StudentMgmtApplication.java
│ └── resources/
│ ├── application.properties
│ └── templates/
└── test/

Student entity:
@Entity
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Column(nullable = false)
private String name;

@Column(nullable = false, unique = true)


private String email;

private String department;

// Constructors, getters, setters


}

Student Repository:
public interface StudentRepository extends JpaRepository<Student, Long> {
List<Student> findByDepartment(String department);
}

Student Controller:
@Controller
@RequestMapping("/students")
public class StudentController {

@Autowired
private StudentRepository studentRepository;

@GetMapping
public String listStudents(Model model) {
model.addAttribute("students", studentRepository.findAll());
return "students";
}

@GetMapping("/new")
18
public String showForm(Model model) {
model.addAttribute("student", new Student());
return "add-student";
}

@PostMapping("/add")
public String addStudent(@ModelAttribute Student student) {
studentRepository.save(student);
return "redirect:/students";
}
}

Students.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Students</title>
</head>
<body>
<h1>Student List</h1>
<table>
<tr th:each="student : ${students}">
<td th:text="${student.id}"></td>
<td th:text="${student.name}"></td>
<td th:text="${student.email}"></td>
<td th:text="${student.department}"></td>
</tr>
</table>
<a href="/students/new">Add Student</a>
</body>
</html>

Add-student form.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Add Student</title>
</head>
<body>
<h1>Add New Student</h1>
<form th:action="@{/students/add}" th:object="${student}" method="post">
Name: <input type="text" th:field="*{name}"><br>
Email: <input type="email" th:field="*{email}"><br>
Department: <input type="text" th:field="*{department}"><br>
<button type="submit">Submit</button>
</form>
</body>
</html>

Application.properties
# Database (using H2 for simplicity)
spring.datasource.url=jdbc:h2:mem:studentdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=

# H2 Console (access at http://localhost:8080/h2-console)


spring.h2.console.enabled=true
spring.h2.console.path=/h2-console
19
# JPA/Hibernate
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.format_sql=true

main application class


@SpringBootApplication
public class StudentMgmtApplication {
public static void main(String[] args) {
SpringApplication.run(StudentMgmtApplication.class, args);
}
}

Run the project:

1. Run StudentMgmt application.


2. Access at http://localhost:8080/students

Technologies used:

Component Technology
Backend Spring Boot 3.x
Database H2 Database
ORM Spring Data JPA
Templating Thymeleaf
Build Tool Maven / Gradle

Key Features

- Create, Read student records


Core Student Management - Simple department-based filtering
- Basic form validation (email format, required fields)

20
Experiment-9
Objective: Test restful web services using springboot.

Theory: pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.example</groupId>
<artifactId>simple-rest</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.0.6</version>
</parent>

<dependencies>
<!-- Web starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<!-- Testing starter -->


<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<properties>
<java.version>17</java.version>
</properties>

</project>

Application.java
package com.example.simplerest;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);

21
}
}

HelloController.java
package com.example.simplerest;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

@GetMapping("/hello")
public String hello() {
return "Hello, World!";
}
}

HelloControllerTest.java
package com.example.simplerest;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.web.servlet.MockMvc;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;


import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@SpringBootTest
@AutoConfigureMockMvc
public class HelloControllerTest {

@Autowired
private MockMvc mockMvc;

@Test
public void testHello() throws Exception {
mockMvc.perform(get("/hello"))
.andExpect(status().isOk())
.andExpect(content().string("Hello, World!"));
}
}

Run at browser:
https://localhost:8080/hello

22
Running the project:

Testing at browser:

Running Test:

23
Experiment-10
Objective: Test Frontened Web application with springboot.

Spring Boot Backend (Java)

backend/pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

HelloController.java
@RestController
@RequestMapping("/api")
public class HelloController {
@GetMapping("/hello")
public String sayHello() {
return "Hello from Spring Boot!";
}
}

Backened Test Example


@SpringBootTest
@AutoConfigureMockMvc
class HelloControllerTest {
@Autowired
private MockMvc mockMvc;

@Test
void helloEndpointReturnsMessage() throws Exception {
mockMvc.perform(get("/api/hello"))
.andExpect(status().isOk())
.andExpect(content().string("Hello from Spring Boot!"));
}
}
React Frontend with Testing

App.js

import React, { useEffect, useState } from 'react';


import axios from 'axios';

function App() {
const [msg, setMsg] = useState('');

useEffect(() => {
axios.get('http://localhost:8080/api/hello')
.then(res => setMsg(res.data));
24
}, []);

return <h1>{msg}</h1>;
}

export default App;

App.test.js
import { render, screen } from '@testing-library/react';
import App from './App';
import axios from 'axios';

jest.mock('axios');

test('shows message from backend', async () => {


axios.get.mockResolvedValue({ data: 'Hello from Spring Boot!' });

render(<App />);
const msg = await screen.findByText('Hello from Spring Boot!');
expect(msg).toBeInTheDocument();
});

Run at:
http://localhost:3000

Start Backened:

Start Frontend:

25

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy