Object-Oriented Programming with Java Lab
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
S. No. LIST OF EXPERIMENTS COs BL
1 Use Java compiler and Eclipse platform to write and execute Java CO1 L2
programs.
2 Use Java compiler and Eclipse platform to write and execute Java CO1 L3
programs.
3 Understand OOP concepts and basics of Java programming. CO1 L3
4 Create Java programs using inheritance and polymorphism CO1 L3
5 Implement error-handling techniques using exception handling and CO2 L3
multithreading.
6 Create Java programs with the use of Java packages. CO1 L3
7 Construct Java program using Java I/O package. CO3 L3
8 Create industry-oriented applications using Spring Framework. CO5 L3
9 Test RESTful web services using Spring Boot. CO5 L3
10 Test Frontend web application with Spring Boot CO5 L3
Object-Oriented Programming with Java Lab
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Aim : Use Java compiler and Eclipse platform to write and execute Java programs.
Content: Here's a step-by-step guide on how to write and execute Java programs using the
Eclipse IDE:
1. Download and Install Eclipse**: Visit the official Eclipse website
(https://www.eclipse.org/) and download the latest version of Eclipse IDE for Java
Developers. Follow the installation instructions provided on the website for your
operating system.
2. Install Java Development Kit (JDK) : Before you can start programming in Java, you need
to have the JDK installed on your system. You can download the JDK from the official
Oracle website
(https://www.oracle.com/java/technologies/javase-jdk11-downloads.html). Follow the
installation instructions provided on the website for your operating system.
3. Open Eclipse : After installing Eclipse, launch the IDE.
4. Create a New Java Project :
- Go to File > New > Java Project.
- Enter a name for your project and click "Finish".
5. Create a New Java Class :
- Right-click on the src folder in your project explorer. -
Go to New > Class.
Enter a name for your class and click "Finish".
6. Write Your Java Code:
- Eclipse will open a new file with a `.java` extension.
Object-Oriented Programming with Java Lab
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
- Write your Java code inside the class. -
Save the file.
7. Compile and Run Your Program :
- Right-click on the Java file in the Package Explorer. -
Select "Run As" > "Java Application".
- Eclipse will compile your code and run the program. You'll see the output in the console
view at the bottom of the Eclipse window.
Here's an example of a simple Java program that prints "Hello, World!" to the console:
```java
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
```
Object-Oriented Programming with Java Lab
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Aim: Creating simple Java programs using command line arguments
Content: Here's a simple example of a Java program that takes command-line arguments and
prints them out:
```java
public class CommandLineArguments {
public static void main(String[] args) {
// Check if there are any command-line arguments
if (args.length == 0) {
System.out.println("No command-line arguments provided.");
} else {
System.out.println("Command-line arguments:");
// Loop through each command-line argument and print it
for (int i = 0; i < args.length; i++) {
System.out.println((i + 1) + ": " + args[i]);
}
}
}
}
```
To compile and run this program using command-line tools (assuming you have JDK
installed):
1. Write the code: Save the above code in a file named `CommandLineArguments.java`.
Object-Oriented Programming with Java Lab
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
2. Compile the program: Open your terminal or command prompt and navigate to the
directory containing `CommandLineArguments.java`. Then, run the following command to
compile the program:
```
javac CommandLineArguments.java
```
This will generate a file named `CommandLineArguments.class`.
3. Run the program with command-line arguments: Once the program is compiled, you can
run it with command-line arguments. For example:
```
java CommandLineArguments arg1 arg2 arg3
```
Replace `arg1`, `arg2`, and `arg3` with the command-line arguments you want to pass. The
program will then print out each argument.
If you run the program without providing any command-line arguments, it will display a
message indicating that no arguments were provided.
Object-Oriented Programming with Java Lab
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Aim: Understand OOP concepts and basics of Java programming.
Content: Understanding Object-Oriented Programming (OOP) concepts is fundamental to
Java programming. Here's an overview of key OOP concepts and how they apply to Java:
1. Classes and Objects:
- Classes are blueprints for objects. They define the properties (attributes) and behaviors
(methods) that objects of that type will have.
- Objects are instances of classes. They encapsulate state and behavior.
Example in Java:
```java
public class Car {
// Attributes
String make;
String model;
int year;
// Methods
void drive() {
// Method implementation }
}
```
2. Encapsulation:
- Encapsulation refers to bundling data (attributes) and methods (behaviors) that operate on
the data into a single unit (i.e., class).
- Access to the data is typically controlled through methods.
Example in Java:
```java
public class Car {
Object-Oriented Programming with Java Lab
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
private String make;
private String model;
private int year;
public void setMake(String make) {
this.make = make;
}
public String getMake() {
return make;
}
}
```
3. Inheritance:
- Inheritance allows a class (subclass/child class) to inherit attributes and methods from
another class (superclass/parent class).
- It promotes code reusability and establishes a hierarchy among classes.
Example in Java:
```java
public class ElectricCar extends Car {
// Additional attributes and methods specific to ElectricCar }
```
4. Polymorphism:
- Polymorphism allows objects of different classes to be treated as objects of a common
superclass.
- It enables method overriding and method overloading.
Example in Java (method overriding):
```java
public class Animal {
void makeSound() {
System.out.println("Some generic sound"); }
Object-Oriented Programming with Java Lab
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
public class Dog extends Animal {
@Override
void makeSound() {
System.out.println("Bark");
}
}
```
5. Abstraction:
- Abstraction refers to hiding complex implementation details and showing only the
necessary features of an object.
- Abstract classes and interfaces are used to achieve abstraction.
Example in Java (abstract class):
```java
public abstract class Shape {
abstract double area();
}
public class Circle extends Shape {
double radius;
@Override
double area() {
return Math.PI * radius * radius; }
}
```
These are the fundamental OOP concepts that form the backbone of Java programming.
Understanding them will help you design and develop robust, modular, and maintainable Java
applications.
Object-Oriented Programming with Java Lab
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Rajkiya Engineering College,Pratapgarh
LAB MANUAL
Course Name: Object-Oriented Programming with Experiment No. 4
Java
Branch:
Course Code: BCS- 403 Semester: IV
CSE
Aim: Create Java programs using inheritance and polymorphism.
Content: Create Java programs demonstrating inheritance and polymorphism.
Inheritance Example:
```java
// Parent class
class Vehicle {
void drive() {
System.out.println("Driving the vehicle"); }
}
// Child class inheriting from Vehicle
class Car extends Vehicle {
void drive() { System.out.println("Driving
the car");
}
void accelerate() {
System.out.println("Accelerating the car");
}
}
// Child class inheriting from Vehicle
class Truck extends Vehicle {
void drive() {
System.out.println("Driving the truck"); }
Object-Oriented Programming with Java Lab
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
void load() {
System.out.println("Loading the truck"); }
}
public class InheritanceExample { public
static void main(String[] args) {
Car myCar = new Car();
myCar.drive(); // Output: Driving the car
myCar.accelerate(); // Output: Accelerating the car
Truck myTruck = new Truck(); myTruck.drive();
// Output: Driving the truck myTruck.load(); //
Output: Loading the truck
}
}
```
In this example, `Car` and `Truck` are subclasses of the `Vehicle` class. They inherit the
`drive()` method from the `Vehicle` class, and each has its own specialized method
(`accelerate()` for `Car` and `load()` for `Truck`).
Polymorphism Example:
```java
// Parent class
class Animal {
void makeSound() { System.out.println("Some
generic sound");
}
}
// Child class overriding makeSound() method
class Dog extends Animal {
@Override
void makeSound() {
Object-Oriented Programming with Java Lab
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
System.out.println("Woof"); }
}
// Child class overriding makeSound() method
class Cat extends Animal {
@Override
void makeSound() {
System.out.println("Meow");
}
}
public class PolymorphismExample {
public static void main(String[] args) {
Animal myDog = new Dog();
myDog.makeSound(); // Output: Woof
Animal myCat = new Cat();
myCat.makeSound(); // Output: Meow
}
}
```
In this example, `Dog` and `Cat` are subclasses of the `Animal` class. They override the
`makeSound()` method of the `Animal` class with their own implementations. At runtime, the
appropriate version of the `makeSound()` method is called based on the actual type of the
object (`Dog` or `Cat`) referenced by the `Animal` reference variable.
Object-Oriented Programming with Java Lab
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Aim: Implement error-handling techniques using exception handling and multithreading.
Content: Certainly! Let's first look at exception handling and then move on to multithreading
in Java.
Exception Handling:
Java provides a robust exception handling mechanism to deal with runtime errors or
exceptional situations. Here's an example demonstrating exception handling:
```java
public class ExceptionHandlingExample {
public static void main(String[] args) {
try {
// Attempt to divide by zero
int result = 10 / 0; // This will throw an ArithmeticException
System.out.println("Result: " + result); // This line won't execute
} catch (ArithmeticException e) {
// Handle the exception
System.out.println("Error: Division by zero");
} finally {
// Finally block always executes, whether exception occurs or not
Object-Oriented Programming with Java Lab
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
System.out.println("End of program");
```
In this example:
- We attempt to divide by zero, which results in an `ArithmeticException`.
- The exception is caught by the `catch` block, where we handle it by printing an error
message.
- The `finally` block is used to ensure cleanup tasks are performed, regardless of whether an
exception occurs or not.
Multithreading:
Multithreading in Java allows you to execute multiple threads concurrently. Here's a simple
example illustrating multithreading:
```java
class MyThread extends Thread {
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(Thread.currentThread().getName() + ": " + i);
try {
Object-Oriented Programming with Java Lab
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Thread.sleep(1000); // Pause execution for 1 second
} catch (InterruptedException e) {
System.out.println(e);
public class MultithreadingExample {
public static void main(String[] args) {
MyThread thread1 = new MyThread();
MyThread thread2 = new MyThread();
thread1.setName("Thread 1");
thread2.setName("Thread 2");
thread1.start();
thread2.start();
```
In this example:
Object-Oriented Programming with Java Lab
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
- We create a class `MyThread` that extends the `Thread` class and overrides the `run()`
method.
- Inside the `run()` method, each thread prints numbers from 1 to 5 at intervals of 1 second.
- In the `main()` method, we create two instances of `MyThread`, set their names, and start
them using the `start()` method.
These are basic examples of exception handling and multithreading in Java. Exception
handling helps in gracefully handling errors, while multithreading enables concurrent
execution, which can be useful for tasks that can be performed independently.
Object-Oriented Programming with Java Lab
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Rajkiya Engineering College,Pratapgarh
LAB MANUAL
Course Name: Object-Oriented Programming with Experiment No. 6
Java
Branch:
Course Code: BCS-403 Semester: IV
CSE
Aim: Create Java programs with the use of Java packages.
Content: Certainly! Java packages are used to organize classes into namespaces, which helps
in avoiding naming conflicts and provides a way to group related classes together. Here's an
example of how you can create Java programs with the use of Java packages:
Suppose we have the following directory structure:
```
src
└── com
└── example
├── math
│ └── Calculator.jav
└── app
└── Main.java
```
Here, `com.example` is the package name.
1. **Calculator.java**:
```java
package com.example.math;
public class Calculator {
public static int add(int a, int b) {
return a + b;
}
public static int subtract(int a, int b) {
return a - b;
}
}
```
2. Main.java:
```java
package com.example.app;
import com.example.math.Calculator;
public class Main {
public static void main(String[] args) {
int a = 10;
int b = 5;
System.out.println("Sum: " + Calculator.add(a, b));
System.out.println("Difference: " + Calculator.subtract(a, b));
}
}
```
3. Compile and Run:
To compile and run these Java programs, you can use the following commands from the
root directory of your project:
```
javac src/com/example/math/Calculator.java src/com/example/app/Main.java java
-cp src com.example.app.Main
```
This will compile the `Calculator.java` and `Main.java` files and run the `Main` class. You
should see the output of the sum and difference calculated by the `Calculator` class.
This example demonstrates how to organize classes into packages and access classes from
one package in another package. It's a good practice to organize your Java code into
packages, especially for larger projects, to keep it well-structured and maintainable.
Object-Oriented Programming with Java Lab
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Rajkiya Engineering College,Pratapgarh
LAB MANUAL
Course Name: Object-Oriented Programming with Experiment No. 7
Java
Branch:
Course Code: BCS-403 Semester: IV
CSE
Aim: Construct Java program using Java I/O package.
Content: Sure, here's a simple Java program that demonstrates reading from and writing to a
text file using the Java I/O package:
```java
import java.io.*;
public class FileIOExample {
public static void main(String[] args) { //
Define the file name
String fileName = "sample.txt";
// Write data to the file
try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName))) {
writer.write("Hello, this is a sample text.");
writer.newLine();
writer.write("This text will be written to the file.");
writer.newLine();
System.out.println("Data has been written to the file."); }
catch (IOException e) {
System.out.println("Error writing to the file: " + e.getMessage()); }
// Read data from the file
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
System.out.println("Reading data from the file:");
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (FileNotFoundException e) { System.out.println("File
not found: " + e.getMessage());
} catch (IOException e) {
System.out.println("Error reading from the file: " + e.getMessage()); }
}
}
```
In this program:
- We define a file name `sample.txt`.
- We write some sample text to the file using a `BufferedWriter`.
- We then read the contents of the file using a `BufferedReader` and print them to the console.
Make sure to create a text file named `sample.txt` in the same directory as the Java file or
adjust the file path accordingly. This program demonstrates basic file I/O operations in Java
using the `java.io` package.
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Aim: Create industry-oriented applications using Spring Framework.
Content: Certainly! The Spring Framework is widely used in the industry for building
various types of applications, from web applications to enterprise systems. Here's an example
of a simple web application using Spring Boot, which is a part of the larger Spring
Framework ecosystem:
Simple Web Application with Spring Boot:
```java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@RestController
class HelloWorldController {
@GetMapping("/hello")
public String hello() {
return "Hello, World!"; }
}
```
In this example:
- We use Spring Boot's `@SpringBootApplication` annotation to mark the main class as the
entry point for the Spring Boot application.
- We define a `HelloWorldController` class with a single `hello()` method that returns a
simple "Hello, World!" message.
- We use Spring's `@RestController` annotation to mark the class as a RESTful controller.
To run this application:
1. Make sure you have Spring Boot installed or include it as a dependency in your `pom.xml`
if you're using Maven or `build.gradle` if you're using Gradle.
2. Run the `main()` method of the `Application` class.
3. Access the endpoint `http://localhost:8080/hello` in your web browser or any REST client.
You should see the "Hello, World!" message.
This is a very basic example, but Spring Framework provides a wide range of features and
modules for building complex and scalable applications, including dependency injection,
MVC framework, data access, security, messaging, and more.
Industry-oriented applications often leverage these features to build robust and maintainable
systems.
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Aim: Test RESTful web services using Spring Boot.
Content: Testing RESTful web services in Spring Boot can be done using various testing
frameworks like JUnit, Mockito, and Spring Test. Here's an example of how you can write
integration tests for RESTful web services using Spring Boot's testing support:
```java
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
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.http.MediaType;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
@ExtendWith(SpringExtension.class)
@SpringBootTest
@AutoConfigureMockMvc
public class RestControllerIntegrationTest {
@Autowired
private MockMvc mockMvc;
@Test
public void testHelloEndpoint() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/hello")
.contentType(MediaType.APPLICATION_JSON))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.content().string("Hello, World!"));
}
}
```
In this example:
- We use JUnit 5 (`@ExtendWith(SpringExtension.class)`) as the testing framework. -
`@SpringBootTest` is used to bootstrap the application context.
- `@AutoConfigureMockMvc` automatically configures the `MockMvc` instance.
- We autowire the `MockMvc` instance to perform HTTP requests against our RESTful
endpoints.
- The `testHelloEndpoint()` method tests the `/hello` endpoint by performing a GET request
and asserting that the response status is OK (200) and the response content is "Hello,
World!".
To run this test, you can simply execute it like any other JUnit test. Spring Boot will
automatically start an embedded web server and deploy your application for testing purposes.
The `MockMvc` instance provides a powerful way to test your RESTful endpoints in a
controlled environment. You can further enhance your tests by adding more assertions for
different scenarios and endpoints.
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Aim: Test Frontend web application with Spring Boot.
Content: To test a frontend web application with Spring Boot, you typically use tools and
libraries that specialize in frontend testing, such as Selenium or Cypress for end-to-end
testing, and Jest or Jasmine for unit testing. Spring Boot itself focuses more on backend
development, but you can still integrate frontend testing into your Spring Boot project.
Here's an example of how you can set up and perform end-to-end testing using Selenium for a
simple frontend web application in a Spring Boot project:
1. Add Dependencies:
First, you need to add the necessary dependencies for Selenium and WebDriver. You can
do this by adding the following dependencies to your `pom.xml` if you're using Maven:
```xml
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.141.59</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-chrome-driver</artifactId>
<version>3.141.59</version>
</dependency>
```
Or to your `build.gradle` if you're using Gradle:
```groovy
dependencies {
testImplementation 'org.seleniumhq.selenium:selenium-java:3.141.59'
testImplementation 'org.seleniumhq.selenium:selenium-chrome-driver:3.141.59'
}
```
2. Write Tests:
Create a test class where you can write your Selenium tests. Here's an example:
```java
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class FrontendTest {
private static WebDriver driver;
@BeforeAll
public static void setUp() {
// Set the path to ChromeDriver executable
System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); //
Initialize ChromeDriver instance
driver = new ChromeDriver(); }
@Test
public void testHomePage() { //
Open the homepage URL
driver.get("http://localhost:8080");
// Perform assertions or interactions with the webpage using Selenium APIs //
For example:
// Assert.assertEquals("Expected Title", driver.getTitle());
// Assert.assertTrue(driver.findElement(By.id("someElement")).isDisplayed()); }
@AfterAll
public static void tearDown() {
// Quit the WebDriver instance if
(driver != null) {
driver.quit();
}
}
}
```
Replace `"path/to/chromedriver"` with the actual path to your ChromeDriver executable.
3. **Run Tests**:
Run your tests using your favorite testing tool or IDE. The test class you've created will
open a Chrome browser, navigate to your Spring Boot application's homepage (assuming it's
running locally on port 8080), and perform assertions or interactions as specified.
This is just a basic example of how you can perform end-to-end testing for a frontend web
application integrated with Spring Boot using Selenium. Depending on your application's
complexity and requirements, you may need to write more tests covering different scenarios and
components of your frontend