0% found this document useful (0 votes)
13 views35 pages

Lab Manual OOPs With JAVA 2024-25

The document outlines a series of Java programming experiments focusing on various concepts such as command line arguments, object-oriented programming, inheritance, exception handling, threading, and user input methods. Each experiment includes an aim, code snippets, and expected outputs, demonstrating practical applications of Java. Additionally, it covers creating packages, using the Spring framework for application development, and testing RESTful web services with Spring Boot.

Uploaded by

roasterbyte
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)
13 views35 pages

Lab Manual OOPs With JAVA 2024-25

The document outlines a series of Java programming experiments focusing on various concepts such as command line arguments, object-oriented programming, inheritance, exception handling, threading, and user input methods. Each experiment includes an aim, code snippets, and expected outputs, demonstrating practical applications of Java. Additionally, it covers creating packages, using the Spring framework for application development, and testing RESTful web services with Spring Boot.

Uploaded by

roasterbyte
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/ 35

Experiment 1(a)

Create simple java programs using command line arguments


AIM: Write a program that takes input from user through command line argument and then prints whether a number is
prime or not.

CODE:
import java.util.*;
import java.util.Scanner; public
class Main
{
public static void main(String[] args) { int
c=0;
Scanner sc= new Scanner(System.in);
System.out.print("Enter the number: "); int
n=sc.nextInt();
for(int i=1;i<n;i++){
if(n%i==0){
c++;
}
}
if(c==1){
System.out.println("Prime Number");
}
else{
System.out.println("Not a prime number");
}
}
}
OUTPUT:
Experiment 1(b)

AIM: Write a program to enter number through command line and check whether it is palindrome or not.

CODE:
import java.util.*;
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{ int x,rev=0;
Scanner sc= new Scanner(System.in);
System.out.print("Enter the number: ");
int n= sc.nextInt();
int t=n;
while(t>0)
{
x=t%10;
rev=x+rev*10
; t=t/10;
}
if(rev==n){
System.out.println("Palindrome Number");
}
else{
System.out.println("Not a palindrome number");
}
}
}

OUTPUT:
Experiment 2(a)
Use Java compiler and eclipse platform to write and execute java program
AIM: Write a program to print addition of 2 matrices in java

CODE:
package firstproject;import
java.util.*; public class
Second {

public static void main(String[] args) {


// TODO Auto-generated method stub Scanner sc =
new Scanner(System.in);
System.out.print("Enter rows and columns of matrix: ");
int m=sc.nextInt();
int n=sc.nextInt();

int[][] a1= new int[m][n];


int[][] a2= new int[m][n];
int[][] a= new int[m][n];

System.out.print("Enter matrix 1: ");


for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
a1[i][j]=sc.nextInt();
}
}

System.out.print("Enter matrix 2: ");


for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
a2[i][j]=sc.nextInt();
}
}
System.out.println("Resultant matrix:");
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){ a[i][j]=a1[i][j]+a2[i][j];
System.out.print(a[i][j]+" ");
}
System.out.println();
}

OUTPUT:
Experiment 2(b)
AIM: Write a program in java which creates the variable size array (Jagged Array) and print all the values using loop
statement.
CODE:
package firstproject;
import java.util.*; public
class First {

public static void main(String[] args) {


// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
System.out.print("Enter number of rows: ");
int row=sc.nextInt();
int[][] a=new int[row][];
System.out.print("Enter number of elements in each row: ");
for(int i=0;i<row;i++){ a[i]=new
int[sc.nextInt()];
}
System.out.println("Enter the elements:");
for(int i=0;i<row;i++){
for(int j=0;j<a[i].length;j++){
a[i][j]=sc.nextInt();
}
}
System.out.println("Show elements in jagged array");
for(int i=0;i<row;i++){
for(int j=0;j<a[i].length;j++){
System.out.print(a[i][j]+" ");
}
System.out.println();
}

OUTPUT:
Experiment 3(a)
Understand OOP concepts and basics of Java programming
AIM: Write a Java program to create a class called "Person" with a name and age attribute. Create two instances of the
"Person" class, set their attributes using the constructor, and print their name and age.

CODE:
package secondproject;

public class Person {


private String name;
private int age;

public Person(String name, int age) {


this.name=name;
this.age=age;
}

public String getName() {


return name;
}
public int getAge() {
return age;
}

public void setName(String name) {


this.name=name;
}
public void setAge(int age) {
this.age=age;
}
public String toString()
{
return String.format("Name: %s, Age: %d", name,age) ;
}
}

public class PersonTest {

public static void main(String[] args)


{
Person p= new Person("Cindy", 20);

System.out.println(p);
}
}

OUTPUT:
Experiment 3(b)
AIM: Write a Java program to create a class called Person with private instance variables name, age. and country.
Provide public getter and setter methods to access and modify these variables.

CODE:
package student;

public class Person {


private String name; private
int age; private String country;

public Person(String name, int age, String country) {


this.name=name;
this.age=age;
this.country=country;
}

public String getName() {


return name;
}
public int getAge() {
return age;
}
public String getCountry() {
return country;
}

public void setName(String name) {


this.name=name;
}
public void setAge(int age) {
this.age=age;
}
public void setCountry(String country) {
this.country=country;
}
public String toString()
{
return String.format("Name: %s, Age: %d, Country: %s", name,age,country);
}

public class StudentTest {

public static void main(String[] args) {


// TODO Auto-generated method stub
Person p= new Person("Cindy", 20, "Australia");

System.out.println(p);
}
}

OUTPUT:
Experiment 4(a)
Create Java programs using inheritance and polymorphism
AIM: “Java does not support multiple inheritance but we can achieve it by interface”. Write a program to justify the
above statement.

CODE:
import java.util.*;
interface Character {
void attack();
}
interface Weapon {
void use();
}
class Warrior implements Character, Weapon {
public void attack() {
System.out.println("Warrior attacks with a sword.");
}
public void use() {
System.out.println("Warrior uses a sword.");
}
}
class Mage implements Character, Weapon {
public void attack() {
System.out.println("Mage attacks with a wand.");
}
public void use() {
System.out.println("Mage uses a wand.");
}
}
public class MultipleInheritance {
public static void main(String[] args)
{ Warrior warrior = new Warrior();
Mage mage = new Mage();

warrior.attack();
warrior.use();
mage.attack();
mage.use();
}
}

OUTPUT:
Experiment 4(b)
AIM: Write a program in java to implement single inheritance.

CODE:
class Employee{
float salary=40000;
}

public class Programmer extends Employee{


int bonus=10000;
public static void main(String
args[]){ Programmer p=new
Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}

OUTPUT:
Experiment 4(b)
AIM: Write a program in java to implement multi-level inheritance.

CODE:
class Animal{
void eat(){
System.out.println("eating...");
}
}
class Dog
extends
Animal{
void bark(){
System.out.println("barking...");
}
}
class BabyDog
extends Dog{
void weep(){
System.out.println("weeping...");
}
}
public class TestInheritance2{
public static void
main(String args[]){
BabyDog d=new
BabyDog();
d.weep();
d.bark();
d.eat();
}
}

OUTPUT:
Experiment no:5(a)
Write a Java program to implement user defined exception handling for negative
amount entered.
Code:
import java.util.*;

class NewException extends


Exception{ public
NewException(float n)

System.out.println(n + " is a negative value");

public class exception{

public static void main(String args[])

Scanner sc = new Scanner(System.in);


System.out.print("Enter the amount : "); try{
float amt = sc.nextFloat();
if(amt<0)
throw new NewException(amt);
System.out.println("You enter : "+amt);

catch(NewException ex)
System.out.println("Exception");
}

Output:
Experiment no:5(b)
Write a program in java which creates two threads, “Even” thread and “Odd” thread
and print the even no using Even Thread after every two seconds and odd no using
Odd Thread after every five second.
Code:
class odd extends Thread{
public void run(){
for(int i=1;i<10;i+=2)
{
System.out.println("Odd number : "+i);
try{
Thread.sleep(5000);
}
catch(InterruptedException e)
{
System.out.println(e);
}
}
}
}
class even extends Thread{
public void run(){
for(int i=0;i<10;i+=2)
{
System.out.println("Even number : "+i);
try{
Thread.sleep(5000);
}
catch(InterruptedException e)
{
System.out.println(e);
}
}

}
}
class thread{
public static void main(String args[])
{
odd obj1 = new odd(); even
obj2 = new even();

obj1.start();
obj2.start();
}
}

Output:
Experiment no:6
Create a package named “Mathematics” and add a class “Matrix” with methods to add and
subtract matrices (2x2). Write a Java program importing the Mathematics package and use the
classes defined in it.

// Mathematics/Matrix.java
package Mathematics;
public class Matrix {
// Method to add two 2x2 matrices
public int[][] add(int[][] matrix1, int[][] matrix2) {
int[][] result = new int[2][2];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++)
{
result[i][j] = matrix1[i][j] + matrix2[i][j];
}
}
return result;
}

// Method to subtract two 2x2 matrices


public int[][] subtract(int[][] matrix1, int[][] matrix2) {
int[][] result = new int[2][2];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
result[i][j] = matrix1[i][j] - matrix2[i][j];
}
}
return result;
}
}

// Main.java
import Mathematics.Matrix;

public class Main {


public static void main(String[] args) {
Matrix matrix = new Matrix();

int[][] matrix1 = {
{1, 2},
{3, 4}
};

int[][] matrix2 = {
{5, 6},
{7, 8}
};

int[][] resultAdd = matrix.add(matrix1, matrix2);


int[][] resultSubtract = matrix.subtract(matrix1, matrix2);
System.out.println("Addition of matrices:");
printMatrix(resultAdd);

System.out.println("Subtraction of matrices:");
printMatrix(resultSubtract);
}
private static void printMatrix(int[][] matrix) {
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
}
Experiment no:7
Write a program in java to take input from user by using all the following
methods:
• Command Line Arguments
• DataInputStream Class
• BufferedReader Class
• Scanner Class
• Console Class

import java.io.*;
import java.util.Scanner;
public class UserInputDemo {
public static void main(String[] args) {
// Command Line Arguments
System.out.println("Command Line Arguments:");
for (int i = 0; i < args.length; i++) {
System.out.println("Argument " + (i + 1) + ": " + args[i]);
}
// DataInputStream Class
try {
System.out.println("\nDataInputStream:");
DataInputStream dataInputStream = new DataInputStream(System.in);
System.out.print("Enter a string: ");
String dataInputString = dataInputStream.readLine();
System.out.println("You entered: " + dataInputString);
} catch (IOException e) {
System.out.println("Error reading input using DataInputStream: " + e.getMessage());
}
// BufferedReader Class
try {
System.out.println("\nBufferedReader:");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter a string: ");
String bufferedReaderString = bufferedReader.readLine();
System.out.println("You entered: " + bufferedReaderString);
} catch (IOException e) {
System.out.println("Error reading input using BufferedReader: " + e.getMessage());
}

// Scanner Class
System.out.println("\nScanner:");
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String scannerString = scanner.nextLine();
System.out.println("You entered: " + scannerString);

// Console Class
Console console = System.console();
if (console != null) {
System.out.println("\nConsole:");
String consoleString = console.readLine("Enter a string: ");
System.out.println("You entered: " + consoleString);
} else {
System.out.println("\nConsole input is not available in this environment.");
}
}}
Experiment-8
Aim: Create industry-oriented application using Spring Framework.
Code: Pojo Class
package in.abes.CSEDS;

public class Student {


private String Name;
private int rollno;
private String email;
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public int getRollno() {
return rollno;
}
public void setRollno(int rollno) {
this.rollno = rollno;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public void display()
{
System.out.println("Name :" +Name);
System.out.println("Rollno :" +rollno);
System.out.println("Email :" +email);
}
}

XML Configuration:

<?xml version="1.0" encoding="UTF-8"?>


<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

<!-- bean definitions here -->


<bean class= "in.abes.CSEDS.Student" id="stdId">
<property name ="Name" value="Yash" />
<property name= "rollno" value="101" />
<property name="email" value="[email protected]" />
</bean>
</beans>

Main file:

package in.abes.main;

import org.springframework.context.ApplicationContext;
import in.abes.CSEDS.Student;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {


public static void main(String[] args) {
String config_loc= "/in/abes/resources/applicationContext.xml";
ApplicationContext context =new ClassPathXmlApplicationContext(config_loc);
Student s=(Student)context.getBean("stdId");
s.display();
}}
Experiment-9

Aim: Test RESTful web services using Spring Boot.


Code:
Step 1: Add Dependencies to pom.xml
<dependencies>

<!-- Spring Boot Web Starter -->


<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring Boot Test Starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- For JSON processing -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
</dependencies>

Step 2: Create a RESTful Web Service


Employee.java
package com.example.demo.model;

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) {
this.id = id;
this.name = name;
this.role = role;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
}
Step 3: Write Unit Tests for the RESTful Web Service
Create a test class for EmployeeController.

EmployeeControllerTest.java
package com.example.demo.controller;

import com.example.demo.model.Employee;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.BeforeEach;
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.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;

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


import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

@WebMvcTest(EmployeeController.class)
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 {
mockMvc.perform(post("/employees")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(employee)))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").value(employee.getName()))
.andExpect(jsonPath("$.role").value(employee.getRole()));
}
@Test
public void testGetAllEmployees() throws Exception {
mockMvc.perform(get("/employees"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON));
}

@Test
public void testGetEmployeeById() throws Exception {
mockMvc.perform(post("/employees")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(employee)))
.andExpect(status().isOk());
mockMvc.perform(get("/employees/{id}", 1L))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").value(employee.getName()))
.andExpect(jsonPath("$.role").value(employee.getRole()));
}
}
Experiment-10

Aim: Test Frontend web application with Spring Boot.

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


POST
http://localhost:8080/api/users

GET
http://localhost:8080/api/users

PUT

http://localhost:8080/api/users/1
DELETE
http://localhost:8080/api/users/1
Experiment-11

AIM: CRUD Operations using REST API using ArrayList or Map.


DemoApplication.java:
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
BookController.Java:
package com.example.demo.Controllers;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
@RestController
@RequestMapping("/books")
public class BookController {
private List<String> books = new ArrayList<>();
// Handler method to return a string (GET)
@GetMapping
public List<String> getBooks() {
if (books.isEmpty()) {
books.add("Sample Book");
}
return books;
}

// Handler method to add a book (POST)


@PostMapping
public String addBook(@RequestBody String book) {
books.add(book);
return "Book added successfully: " + book;
}

// Handler method to delete a book (DELETE)


@DeleteMapping("/{book}")
public String deleteBook(@PathVariable String book) {
if (books.remove(book)) {
return "Book removed successfully: " + book;
} else {
return "Book not found: " + book;
}
}
}
Controllers:
package Controllers;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class BookController {
//handler method return string
@GetMapping(path= "/books")
public String getBooks()
{
return "this is testing book first";
}
}
Pom.Xml:
<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-
4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.3.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<url/>
<licenses>
<license/>
</licenses>
<developers>
<developer/>
</developers>
<scm>
<connection/>
<developerConnection/>
<tag/>
<url/>
</scm>
<properties>
<java.version>17</java.version>
</properties>
<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>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

</project>

Experiment-12
Aim: CRUD Operations using H2 Database.
Code:
CRUD (Create, Read, Update, Delete) operations using an H2 in-memory database in a Spring Boot application can be
implemented by following these steps:

Step 1: Set Up Spring Boot Project


Create a new Spring Boot project using Spring Initializr with dependencies:
- Spring Web
- Spring Data JPA
- H2 Database
Step 2: Configure H2 Database

Add the following configuration to your `application.properties` file to set up the H2 database:

```properties
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console
```
Step 3: Create Entity Class

Create a `User` entity class to represent the data model:

```java
package com.example.demo.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
private String email;

// Getters and Setters


public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
```
Step 4: Create Repository Interface
Create a `UserRepository` interface that extends `JpaRepository`:

```java
package com.example.demo.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import com.example.demo.model.User;

public interface UserRepository extends JpaRepository<User, Long> {


}
```
Step 5: Create Service Class

Create a `UserService` class to handle business logic:

```java
package com.example.demo.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.demo.model.User;
import com.example.demo.repository.UserRepository;
import java.util.List;

@Service
public class UserService {

@Autowired
private UserRepository userRepository;

public User createUser(User user) {


return userRepository.save(user);
}

public User getUserById(Long id) {


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

public List<User> getAllUsers() {


return userRepository.findAll();
}

public User updateUser(Long id, User userDetails) {


User user = userRepository.findById(id).orElse(null);
if (user != null) {
user.setName(userDetails.getName());
user.setEmail(userDetails.getEmail());
return userRepository.save(user);
}
return null;
}

public void deleteUser(Long id) {


userRepository.deleteById(id);
}
}
```
Step 6: Create Controller Class

Create a `UserController` class to handle HTTP requests:

```java
package com.example.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import com.example.demo.model.User;
import com.example.demo.service.UserService;
import java.util.List;

@RestController
@RequestMapping("/api/users")
public class UserController {

@Autowired
private UserService userService;

@PostMapping
public User createUser(@RequestBody User user) {
return userService.createUser(user);
}

@GetMapping("/{id}")
public ResponseEntity<User> getUserById(@PathVariable Long id) {
User user = userService.getUserById(id);
if (user != null) {
return ResponseEntity.ok(user);
} else {
return ResponseEntity.notFound().build();
}
}

@GetMapping
public List<User> getAllUsers() {
return userService.getAllUsers();
}

@PutMapping("/{id}")
public ResponseEntity<User> updateUser(@PathVariable Long id, @RequestBody User userDetails) {
User updatedUser = userService.updateUser(id, userDetails);
if (updatedUser != null) {
return ResponseEntity.ok(updatedUser);
} else {
return ResponseEntity.notFound().build();
}
}

@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteUser(@PathVariable Long id) {
userService.deleteUser(id);
return ResponseEntity.noContent().build();
}
}
```
Step 7: Test the Application

Run the Spring Boot application and test the CRUD operations using a tool like Postman or curl.

#### Create a User


```bash
POST /api/users
Content-Type: application/json

{
"name": "John Doe",
"email": "[email protected]"
}
```

#### Get a User by ID


```bash
GET /api/users/{id}
```

#### Get All Users


```bash
GET /api/users
```

#### Update a User


```bash
PUT /api/users/{id}
Content-Type: application/json

{
"name": "Jane Doe",
"email": "[email protected]"
}
```

#### Delete a User


```bash
DELETE /api/users/{id}
```

You might also like