0% found this document useful (0 votes)
5 views24 pages

Java Practical

The document outlines a series of practical exercises for learning Java programming, covering topics such as basic Java syntax, object-oriented programming concepts, exception handling, multithreading, and the use of Java packages. It also includes instructions for creating a simple industry-oriented application using the Spring Framework. Each section provides step-by-step guidance on writing and executing Java programs, along with example code snippets.

Uploaded by

rajputananya238
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 views24 pages

Java Practical

The document outlines a series of practical exercises for learning Java programming, covering topics such as basic Java syntax, object-oriented programming concepts, exception handling, multithreading, and the use of Java packages. It also includes instructions for creating a simple industry-oriented application using the Spring Framework. Each section provides step-by-step guidance on writing and executing Java programs, along with example code snippets.

Uploaded by

rajputananya238
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/ 24

INDEX

Sno. Practical Name Date Faculty’s


Signature

1. Use Java compiler and eclipse platform to write


and execute java program.

2. Creating simple java programs using command line


arguments

3. Understand OOP concepts and basics of Java


programming.

4. Create Java programs using inheritance and


polymorphism.

5. Implement error-handling techniques using exception


handling and multithreading.

6. Create java program with the use of java packages.

Construct java program using Java I/O package.


7.

8. Create industry-oriented application using Spring


Framework.

9. Test RESTful web services using Spring Boot.

10. Test Frontend web application with Spring Boot


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

Requirements:

• Eclipse IDE installed (Download from https://www.eclipse.org/downloads/)


• Java JDK installed and configured in Eclipse

▶ Steps to Write and Run Java Program:

1. Open Eclipse
2. Go to File > New > Java Project
o Name it (e.g., MyFirstProject) → Click Finish
3. Right-click the src folder → New > Class
o Name: HelloWorld
o Check the box: public static void main (String[] args)
o Click Finish
4. In the editor, type your code:

java
CopyEdit
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}

5. Click the green run button (▶) on the toolbar

6. Console Output:

Hello, World!
2- Creating simple java programs using command line arguments

Requirements:

• Java JDK installed (check using java -version and javac -version)
• A text editor (e.g., Notepad, VS Code)

Sample Java Program (HelloWorld.java)

java
CopyEdit
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}

▶ Steps to Compile and Run:

1. Save the above code in a file named HelloWorld.java


2. Open Command Prompt (Windows) or Terminal (macOS/Linux)
3. Navigate to the folder where your file is saved:

cd path\to\your\file

4. Compile the program:

javac HelloWorld.java

This creates HelloWorld.class

5. Run the program:

java HelloWorld

Output:

Hello, World!
3- Understand OOPs concepts and basics of Java programming.
Java is a pure object-oriented programming language, which means everything revolves around
classes and objects.

1. Class and Object

• Class: Blueprint for creating objects.


• Object: Instance of a class.

java
CopyEdit
// Class
public class Car {
String color = "Red";

void drive() {
System.out.println("The car is driving.");
}
}

// Main method to create object


public class Main {
public static void main(String[] args) {
Car myCar = new Car(); // Object
System.out.println(myCar.color); // Access attribute
myCar.drive(); // Call method
}
}

2. Encapsulation

• Wrapping data (variables) and code (methods) into a single unit (class).
• Achieved using private variables and public getters/setters.

java
CopyEdit
public class Person {
private String name; // Private data

public String getName() {


return name;
}

public void setName(String newName) {


name = newName;
}
}
3. Inheritance

• One class inherits the fields and methods of another.


• Use extends keyword.

java
CopyEdit
class Animal {
void sound() {
System.out.println("Animal makes sound");
}
}

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.sound(); // Inherited
d.bark(); // Own method
}
}

4. Polymorphism

• One interface, many implementations.


• Achieved via method overloading and overriding.

a. Method Overloading (same method name, different parameters)

class Math {
int add(int a, int b) {
return a + b;
}

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


return a + b + c;
}
}
b. Method Overriding (subclass provides specific implementation)
c.

class Animal {
void sound() {
System.out.println("Some sound");
}
}

class Cat extends Animal {


void sound() {
System.out.println("Meow");
}
}

5. Abstraction

• Hiding internal details and showing only essential information.


• Achieved using abstract classes and interfaces.

a. Abstract Class

java
CopyEdit
abstract class Shape {
abstract void draw();
}

class Circle extends Shape {


void draw() {
System.out.println("Drawing Circle");
}
}

b. Interface

interface Vehicle {
void move();
}

class Bike implements Vehicle {


public void move() {
System.out.println("Bike moves");
}
}
4- Create Java programs using inheritance and polymorphism.

1. Java Program Using Inheritance

We'll create a basic program where a Vehicle class is inherited by a Car class.

Example: Vehicle.java and Car.java

java
CopyEdit
// Base class (superclass)
class Vehicle {
String brand = "Generic Vehicle";

void start() {
System.out.println("Vehicle is starting...");
}
}

// Derived class (subclass)


class Car extends Vehicle {
String model = "Sedan";

void drive() {
System.out.println("Car is driving...");
}
}

// Main class
public class Main {
public static void main(String[] args) {
Car myCar = new Car();
System.out.println("Brand: " + myCar.brand); // Inherited property
System.out.println("Model: " + myCar.model);
myCar.start(); // Inherited method
myCar.drive(); // Own method
}
}
Output:

Brand: Generic Vehicle


Model: Sedan
Vehicle is starting...
Car is driving...
2. Java Program Using Polymorphism

Part A: Method Overriding

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

class Dog extends Animal {


@Override
void sound() {
System.out.println("Dog barks");
}
}

class Cat extends Animal {


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

public class Main {


public static void main(String[] args) {
Animal a1 = new Dog(); // Polymorphism
Animal a2 = new Cat();

a1.sound(); // Output: Dog barks


a2.sound(); // Output: Cat meows
}
}
Part B: Method Overloading

class Calculator {
int add(int a, int 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("Add 2 numbers: " + calc.add(5, 10)); // 15 }}
5- Implement error-handling techniques using exception handling
and multithreading

Part 1: Exception Handling in Java

Java provides try-catch-finally blocks and custom exceptions for robust error-handling.

Example: Division with Exception Handling

java
CopyEdit
import java.util.Scanner;

public class ExceptionExample {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
System.out.print("Enter numerator: ");
int a = scanner.nextInt();
System.out.print("Enter denominator: ");
int b = scanner.nextInt();

int result = a / b; // May throw ArithmeticException


System.out.println("Result: " + result);

} catch (ArithmeticException e) {
System.out.println("Error: Cannot divide by zero!");
} catch (Exception e) {
System.out.println("An error occurred: " + e.getMessage());
} finally {
System.out.println("This block always executes.");
scanner.close();
}
}
}

Output Example:

Enter numerator: 10
Enter denominator: 0
Error: Cannot divide by zero!
This block always executes.
Part 2: Multithreading in Java

Multithreading allows multiple threads to run concurrently. You can create threads by:

• Extending the Thread class


• Implementing the Runnable interface

Example: Using Thread Class

java
CopyEdit
class MyThread extends Thread {
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println("From MyThread: " + i);
try {
Thread.sleep(500); // Pause for 0.5 seconds
} catch (InterruptedException e) {
System.out.println("Thread interrupted.");
}
}
}
}

Example: Using Runnable Interface

java
CopyEdit
class MyRunnable implements Runnable {
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println("From MyRunnable: " + i);
try {
Thread.sleep(700); // Pause for 0.7 seconds
} catch (InterruptedException e) {
System.out.println("Runnable thread interrupted.");
}
}
}
}

Main Program to Run Both:

java
CopyEdit
public class ThreadDemo {
public static void main(String[] args) {
MyThread t1 = new MyThread();
Thread t2 = new Thread(new MyRunnable());

t1.start(); // Start thread by extending Thread


t2.start(); // Start thread using Runnable
}
}

Handling Exceptions Inside Threads

Always handle exceptions inside the run() method, as uncaught exceptions can crash a thread.

Feature What It Does Example Used

try-catch-finally Catch runtime errors safely Division example

extends Thread Simple way to create a thread MyThread class

implements Runnable Preferred for multithreaded class sharing MyRunnable class

Thread.sleep() Pause execution of a thread Inside loop


6- Create java program with the use of java packages.

What Are Java Packages?

• Packages group related classes and interfaces.


• Two types:
o Built-in: java.util, java.io
o User-defined: Custom packages you create

Step-by-Step Example of a User-Defined Package

We'll create a program that:

• Defines a package mypackage


• Contains a class Greeting inside the package
• Uses the Greeting class from another file

Step 1: Create the Package and Class

File: mypackage/Greeting.java

package mypackage;

public class Greeting {


public void sayHello() {
System.out.println("Hello from the mypackage!");
}
}

Step 2: Create the Main Program to Use the Package

File: MainApp.java

import mypackage.Greeting; // Import the class from package

public class MainApp {


public static void main(String[] args) {
Greeting g = new Greeting();
g.sayHello(); // Call method from package
}
}
How to Compile and Run

1. Open a terminal and go to the ProjectFolder


2. Compile the package class:

javac mypackage/Greeting.java

3. Compile the main class:

javac MainApp.java

4. Run the program:

java MainApp

Output:

Hello from the mypackage!

Concept Description

package keyword Declares a class as part of a package

import keyword Brings in classes from a package

Folder = Package Java requires folder structure to match package names


7- Construct java program using Java I/O package.
Writing to a file
Reading from a file

We’ll use the following classes from java.io:

• FileWriter and BufferedWriter for writing


• FileReader and BufferedReader for reading

1. Writing to a File

File: FileWriteExample.java

java
CopyEdit
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class FileWriteExample {


public static void main(String[] args) {
String fileName = "example.txt";

try {
BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));
writer.write("Hello, this is a sample file.\n");
writer.write("This content was written using Java I/O.");
writer.close(); // Always close streams
System.out.println("File written successfully.");
} catch (IOException e) {
System.out.println("An error occurred while writing to the file.");
e.printStackTrace();
}
}
}

2. Reading from a File

File: FileReadExample.java

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class FileReadExample {
public static void main(String[] args) {
String fileName = "example.txt";

try {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String line;
System.out.println("Reading from file:");
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close(); // Always close streams
} catch (IOException e) {
System.out.println("An error occurred while reading the file.");
e.printStackTrace();
}
}
}

How to Compile and Run


javac FileWriteExample.java
javac FileReadExample.java

java FileWriteExample
java FileReadExample

Output:
File written successfully.
Reading from file:
Hello, this is a sample file.
This content was written using Java I/O.
8- Create industry-oriented application using Spring Framework

Project Name: EmployeeManagementSystem


Tech Stack:
• Spring Boot (Spring Framework core)
• Spring Web (REST APIs)
• Spring Data JPA (Database access)
• H2 Database (for testing; can be replaced with MySQL/PostgreSQL)
• Maven or Gradle

Features
• Add employee
• View all employees
• Get employee by ID
• Delete employee

Project Structure
css
CopyEdit
src/
└── main/
├── java/com/example/employeemanagement/
│ ├── controller/
│ ├── service/
│ ├── repository/
│ ├── model/
│ └── EmployeeManagementSystemApplication.java
└── resources/
└── application.properties

Step-by-Step Implementation
1. Create Spring Boot Project
Use https://start.spring.io:
• Project: Maven
• Dependencies:
o Spring Web
o Spring Data JPA
o H2 Database
o Lombok (optional)

2. Model Class
File: model/Employee.java

package com.example.employeemanagement.model;

import jakarta.persistence.*;

@Entity
public class Employee {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

private String name;


private String email;
private String department;

// Getters and setters


}

3. Repository Interface
File: repository/EmployeeRepository.java

package com.example.employeemanagement.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import com.example.employeemanagement.model.Employee;

public interface EmployeeRepository extends JpaRepository<Employee, Long> {


}

4. Service Layer
File: service/EmployeeService.java
package com.example.employeemanagement.service;

import com.example.employeemanagement.model.Employee;
import com.example.employeemanagement.repository.EmployeeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class EmployeeService {

@Autowired
private EmployeeRepository repo;

public Employee addEmployee(Employee e) {


return repo.save(e);
}

public List<Employee> getAllEmployees() {


return repo.findAll();
}

public Employee getEmployeeById(Long id) {


return repo.findById(id).orElse(null);
}

public void deleteEmployee(Long id) {


repo.deleteById(id);
}
}

5. Controller Layer
File: controller/EmployeeController.java
package com.example.employeemanagement.controller;

import com.example.employeemanagement.model.Employee;
import com.example.employeemanagement.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/employees")
public class EmployeeController {

@Autowired
private EmployeeService service;

@PostMapping
public Employee add(@RequestBody Employee e) {
return service.addEmployee(e);
}

@GetMapping
public List<Employee> getAll() {
return service.getAllEmployees();
}

@GetMapping("/{id}")
public Employee getById(@PathVariable Long id) {
return service.getEmployeeById(id);
}

@DeleteMapping("/{id}")
public void delete(@PathVariable Long id) {
service.deleteEmployee(id);
}
}

6. Main Class
File: EmployeeManagementSystemApplication.java

package com.example.employeemanagement;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

7. Configuration File
File: resources/application.properties
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.h2.console.enabled=true
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update

Run and Test the API


Use Postman or curl:
• POST /employees
{
"name": "John Doe",
"email": "[email protected]",
"department": "Engineering"
}
• GET /employees
• GET /employees/1
• DELETE /employees/1
9- Test RESTful web services using Spring Boot.

1. Unit Tests with @WebMvcTest

Tests the controller layer in isolation (no service/database logic).

2. Integration Tests with @SpringBootTest

Tests the entire Spring context — controller, service, and repository.

Example: Employee REST API

Assuming you already have this endpoint in your controller:

java
CopyEdit
@RestController
@RequestMapping("/employees")
public class EmployeeController {

@Autowired
private EmployeeService service;

@GetMapping("/{id}")
public Employee getById(@PathVariable Long id) {
return service.getEmployeeById(id);
}
}

1. Unit Test Using @WebMvcTest

File: EmployeeControllerTest.java

package com.example.employeemanagement;

import com.example.employeemanagement.controller.EmployeeController;
import com.example.employeemanagement.model.Employee;
import com.example.employeemanagement.service.EmployeeService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.web.servlet.MockMvc;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

@WebMvcTest(EmployeeController.class)
public class EmployeeControllerTest {

@Autowired
private MockMvc mockMvc;

@MockBean
private EmployeeService employeeService;

@Test
void testGetEmployeeById() throws Exception {
Employee emp = new Employee();
emp.setId(1L);
emp.setName("John Doe");
emp.setEmail("[email protected]");
emp.setDepartment("HR");

when(employeeService.getEmployeeById(1L)).thenReturn(emp);

mockMvc.perform(get("/employees/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").value("John Doe"))
.andExpect(jsonPath("$.email").value("[email protected]"));
}
}

2. Integration Test Using @SpringBootTest

File: EmployeeIntegrationTest.java

package com.example.employeemanagement;

import com.example.employeemanagement.model.Employee;
import com.example.employeemanagement.repository.EmployeeRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;

import static org.assertj.core.api.Assertions.assertThat;

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class EmployeeIntegrationTest {

@LocalServerPort
private int port;

@Autowired
private TestRestTemplate restTemplate;

@Autowired
private EmployeeRepository repo;

@BeforeEach
void setUp() {
Employee emp = new Employee();
emp.setName("Alice");
emp.setEmail("[email protected]");
emp.setDepartment("Finance");
repo.save(emp);
}

@Test
void testGetEmployee() {
String url = "http://localhost:" + port + "/employees/1";
Employee emp = restTemplate.getForObject(url, Employee.class);
assertThat(emp.getName()).isEqualTo("Alice");
}
}

Maven Dependencies (if not already present)

Add to your pom.xml:

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

Test Type Annotation Purpose

Unit Test @WebMvcTest Tests only controller logic

Integration Test @SpringBootTest Tests full app with DB

HTTP mocking MockMvc Simulate HTTP calls without server

Real calls TestRestTemplate Real HTTP calls with full Spring Boot context
10- Test Frontend web application with Spring Boot
1. Spring MVC with JSP or Thymeleaf (server-side rendering)
2. Spring Boot REST API + separate frontend (React, Angular, Vue, etc.)

1. Testing Server-Side Rendered Frontend (e.g., Thymeleaf)

Tools You Can Use:

• MockMvc (for simulating HTTP requests)


• HtmlUnit (headless browser to test rendered HTML)
• Selenium (UI testing with actual browser)

Example: Test Thymeleaf Page with MockMvc

Suppose you have a simple controller:


@Controller
public class HomeController {

@GetMapping("/")
public String home(Model model) {
model.addAttribute("message", "Welcome to Spring Boot!");
return "home"; // Thymeleaf template: home.html
}
}

Test Using MockMvcava

@WebMvcTest(HomeController.class)
public class HomeControllerTest {

@Autowired
private MockMvc mockMvc;

@Test
void testHomePageLoads() throws Exception {
mockMvc.perform(get("/"))
.andExpect(status().isOk())
.andExpect(view().name("home"))
.andExpect(model().attributeExists("message"));
}
}
2. Testing REST API + JS Frontend (React, Angular, Vue)

Here, the frontend is usually tested independently using JavaScript test frameworks, and the Spring
Boot backend is tested using:

• ✅ MockMvc or TestRestTemplate
• ✅ Integration testing of REST endpoints
• ✅ UI end-to-end testing via Selenium, Cypress, or Playwright

Option A: UI End-to-End Test with Selenium (Spring Boot + HTML)

Add Selenium dependency (Maven):


xml
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.20.0</version>
</dependency>
Example Selenium Test:
import org.junit.jupiter.api.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import static org.junit.jupiter.api.Assertions.*;

public class FrontendSeleniumTest {

@Test
public void testHomePageTitle() {
System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver");
WebDriver driver = new ChromeDriver();
driver.get("http://localhost:8080/");
String title = driver.getTitle();
assertEquals("Home Page", title); // Assuming title in <title> tag
driver.quit();
}
}

Setup Recommended Testing Tools

Spring Boot + Thymeleaf MockMvc, HtmlUnit, Selenium

Spring Boot + REST + JS MockMvc + frontend tools (Jest, Cypress)

Full-stack E2E Selenium, Cypress, Playwright

You might also like