Java Lab Manual Aky
Java Lab Manual Aky
LABORATORY MANUAL
COMPUTER SCIENCE
&
ENGINEERING
MANUAL CONTENTS
This manual is intended for the 2nd year students of Computer Science &
Engineering in the subject of Object Oriented programming with Java. This manual
typically contains practical/lab sessions related Object Oriented programming with
Java.
Students are advised to thoroughly go through this manual rather than only topics
mentioned in the syllabus as practical aspects are the key to understanding and
conceptual visualization of theoretical aspects covered in the books.
Object-Oriented Programming with Java Lab
HOD, CSE
PREFACE
M2. To develop technocrats with creative skills and leadership qualities, to solve local
and global challenges.
M3. To impart human values and ethics in students, to make them socially and
eco-friendly responsible.
“To produce globally competent professionals having social values and commitment to
serve the global needs with the ability to work in an interdisciplinary environment."
M1. "To impart quality education to the students to enhance their ethical,
professional and leadership qualities to make them globally competitive."
M2. "To create a conducive environment in which students can explore computational
problems and analyze them to identify the optimal solutions."
M3. "To strive for continual enhancement of technical knowledge & innovation through
industry interface to accomplish global needs."
Object-Oriented Programming with Java Lab
PEO2: Students must be able to analyze, design, and implement the latest
technology-driven projects.
PSO 1: Able to design and implement the data structures and algorithms to deliver
quality software products.
PSO 2: Able to apply Artificial Intelligence and Machine Learning concepts to solve
society-related needs.
Object-Oriented Programming with Java Lab
Bloom's
Course Outcomes:
Level (BL)
CO Develop object-oriented programming concepts using Java L2
1
CO Implement exception handling, file handling, and multi-threading in Java L3
2
CO Apply new Java features to build Java programs L3
3
CO Analyse Java programs with the Collection Framework L3
4
CO L3
5 Test web and RESTful Web Services with Spring Boot using Spring K
Framework concepts
Object-Oriented Programming with Java Lab
INDEX
Object-Oriented Programming with Java Lab
INTRODUCTION
Aim
Object-Oriented Programming with Java Lab
This course aims to introduce the concepts of operating systems, designing principles of
operating systems, and implementation of operating systems, with a particular focus on
solving real problems related to various services/ functions provided by operating
systems. Practical experimentation with the programming language is strongly
encouraged.
Course Objectives
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:
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.
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!");
}
}
```
Once you've written this code in Eclipse, you can follow the steps above to compile and
run it. You should see "Hello, World!" printed in the console view.
```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
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
```
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.
Branch:
Course Code: BCS-403 Semester: IV
CSE
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
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.
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.
@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
Inheritance Example:
```java
// Parent class
class Vehicle {
void drive() {
System.out.println("Driving the vehicle");
}
}
void accelerate() {
System.out.println("Accelerating the car");
}
}
void load() {
System.out.println("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");
}
}
System.out.println("Woof");
}
}
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.
Branch:
Course Code: BAC-403 Semester: IV
CSE
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
try {
} catch (ArithmeticException e) {
} finally {
System.out.println("End of program");
```
In this example:
- 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:
```java
try {
Object-Oriented Programming with Java Lab
} catch (InterruptedException e) {
System.out.println(e);
thread1.setName("Thread 1");
thread2.setName("Thread 2");
thread1.start();
thread2.start();
```
In this example:
Object-Oriented Programming with Java Lab
- 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.
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:
```
src
└── com
└── example
├── math
│ └── Calculator.java
Object-Oriented Programming with Java Lab
└── app
└── Main.java
```
1. **Calculator.java**:
```java
package com.example.math;
2. Main.java:
```java
package com.example.app;
import com.example.math.Calculator;
```
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.
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.*;
Object-Oriented Programming with Java Lab
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.
Object-Oriented Programming with Java Lab
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.
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:
```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 {
@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.
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.
Object-Oriented Programming with Java Lab
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")
Object-Oriented Programming with Java Lab
.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.
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>
```
```groovy
dependencies {
testImplementation 'org.seleniumhq.selenium:selenium-java:3.141.59'
testImplementation 'org.seleniumhq.selenium:selenium-chrome-driver:3.141.59'
}
```
2. Write Tests:
Object-Oriented Programming with Java Lab
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;
@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();
}
Object-Oriented Programming with Java Lab
}
}
```
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.