0% found this document useful (0 votes)
3 views19 pages

OOP With Java Lab - Bcs 452 - 2023-24

The document is a laboratory manual for Object Oriented Programming with Java, detailing various experiments for B.Tech students at IMS Engineering College. It includes examples of exception handling, Java packages, file operations, Spring Framework applications, and RESTful web services using Spring Boot. Each experiment is accompanied by code snippets, expected outputs, and instructions for using software like Visual Studio Code.

Uploaded by

tomardipanshu07
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views19 pages

OOP With Java Lab - Bcs 452 - 2023-24

The document is a laboratory manual for Object Oriented Programming with Java, detailing various experiments for B.Tech students at IMS Engineering College. It includes examples of exception handling, Java packages, file operations, Spring Framework applications, and RESTful web services using Spring Boot. Each experiment is accompanied by code snippets, expected outputs, and instructions for using software like Visual Studio Code.

Uploaded by

tomardipanshu07
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

IMS ENGINEERING COLLEGE

LABORATORY MANUAL
Object Oriented Programming with JAVA
(BCS-452)

B.TECH – II YEAR
(EVEN SEM 2024-
2025)

Name

Roll No.

Section-Batch

DEPARTMENT OF INFORMATION TECHNOLOGY

IMS ENGINEERING COLLEGE


(Affiliated to Dr A P J Abdul Kalam Technical University, Lucknow )
Approved by AICTE - Accredited by NAAC – ‘A’ Grade
NH#24, Adhyatmik Nagar, Ghaziabad, UP, India
www.imsec.ac.in
Experiment-8
Implement error-handling techniques using exception handling and multithreading.

Software Used: Visual Studio Code

public class JavaExceptionProgram


{
public static void main(String args[])
{
Try {
int data=100/0;
}
Catch (ArithmeticException e)
{
System.out.println (e);
}
//rest code of the program
System.out.println ("rest of the code...");
}
}

Output:-
Arithmetic divide by zero
rest of the code..
Public class exception1
{
public static void main(String[] args)
{try
{
int data=50/0; //may throw exception
}
// handling the exception
catch(Exception e)
{
// displaying the custom message
System.out.println ("Can't divided by zero");
}
}
}

Output:
Divided by arithmetic’s error
Can't divided by zero
Experiment-9

Create java program with the use of java packages.

Software Used: Visual Studio Code

public class CS2


{ public void show()
{

System.out.println("Hi Everyone");

public void view()


{
/ System.out.println("Hello");
}
}
import data.*;
class CS1 {

public static void main(String arg[])


{

CS2 d = new CS2();


d.show();
d.view();
}
}}
}}

Output:

1. To generate the output from the above


program Command: javac CS2.java

2. This Command Will Give Us a Class File

3 .So This Command Will Create a New Folder Called data.

Note: In data Demo.java & Demo.class File should be present


Experiment-10

Construct java program using Java I/O package.

Software Used: Visual Studio Code

import java.io.*;
public class class_file1
{
public static void main(String[] args) throws IOException{
File f;
f=new File("myfile.txt");
if(!f.exists()){
f.createNewFile();
System.out.println("New file \"myfile.txt\" has been created
to the current directory");
}
}
}
Output of the Program
C:\pankaj>javac C:\pankaj>javac class_file1.java C:\
pankaj>java class_file1
New file "myfile.txt" has been created to the current directory

C:\pankaj>1.java C:\
pankaj>java CreateFile1
New file "myfile.txt" has been created to the current directory
C:\pankaj>

java - Copying one file to another

copyfile(String srFile, String dtFile)

File f1 = new File(srFile);


File f2 = new File(dtFile);

InputStream in = new FileInputStream(f1);


OutputStream out = new FileOutputStream(f2);
import java.io.*;
public class
CopyFile
{
private static void copyfile(String srFile, String
dtFile){try{
File f1 = new File(srFile);
File f2 = new File(dtFile);
InputStream in = new FileInputStream(f1);

//For Append the file.


OutputStream out = new FileOutputStream(f2,true);

//For Overwrite the file.


OutputStream out = new FileOutputStream(f2);

byte[] buf = new byte[1024];


int len;
while ((len = in.read(buf)) >
0){out.write(buf, 0,
len);
}
in.close();
out.close();
System.out.println("File copied.");
}
catch(FileNotFoundException ex)
{
System.out.println(ex.getMessage() + " in the specified
directory."); System.exit(0);
}
catch(IOException e){
System.out.println(e.getMessage());
}
}
public static void main(String[]
args){switch(args.length){
case 0: System.out.println("File has not mentioned.");System.exit(0);
case 1: System.out.println("Destination file has not mentioned.");
System.exit(0);
case 2: copyfile(args[0],args[1]);
System.exit(0);
default : System.out.println("Multiple files are not allow.");
System.exit(0);
}
}
}

Output :
C:\pankaj>javac C:\pankaj>javac CopyFile.java C:\
pankaj>java CopyFile
New file "myfile.txt" has been created to the current directory

C:\pankaj>1.java C:\
pankaj>java CopyFile 1
New file "myfile.txt" has been created to the current directory
C:\pankaj>

import java.io.*;

class class1{
public static void main(String[] args)
{

System.out.print("ims engineering college! ");


System.out.print("ims engineering college! ");
System.out.print("ims engineering college! ");
}
}

Output: ims engineering college!


ims engineering college!
ims engineering college!

Construct java program using FileOutputStream

import java.io.FileOutputStream;
public class FileOutputStreamExample

{
public static void main(String args[])
{
try
{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
fout.write(65);
fout.close();
System.out.println("successfully uploaded data");
}
catch(Exception e){System.out.println(e);}
}
}

Output:
Successfully uploaded data

Construct java program using File Input Stream.

import java.io.FileInputStream;

public class DataStreamExample {

public static void main(String args[]){

try{

FileInputStream fin=new FileInputStream("D:\\testout.txt");

int i=fin.read();

System.out.print((char)i);

fin.close();

}catch(Exception e){System.out.println(e);}

Output:
Successfully upload data
Experiment-11
Create industry oriented application using Spring Framework.

Software Used: Visual Studio Code

1) Create Java
class package
com.javatpoint; public
class Student
{ private String name;
public String getName()
{return name;
}
public void setName(String name) {
this.name = name;
}
public void
displayInfo(){ System.out.println("
Hello: "+name);
}
}

2) Create the xml file


<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<bean id="studentbean" class="com.javatpoint.Student">


<property name="name" value="pankaj kumar"></property>
</bean>
3) Create the test class

Create the java class e.g. Test. Here we are getting the object of Student class from the IOC container using
the getBean() method of BeanFactory. Let's see the code of test class.

package com.javatpoint;
import org.springframework.beans.factory.BeanFactory;

import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

public class Test


{
public static void main(String[] args)
{
Resource resource=new ClassPathResource("applicationContext.xml");
BeanFactory factory=new XmlBeanFactory(resource);
Student student=(Student)factory.getBean("studentbean");
student.displayInfo();
}
}

4) Load the jar files required for spring framework

There are mainly three jar files required to run this application.

o org.springframework.core-3.0.1.RELEASE-A
o com.springsource.org.apache.commons.logging-1.1.1
o org.springframework.beans-3.0.1.RELEASE-A

5) Run the test class

Now run the Test class. You will get the output Hello: Vimal Jaiswal.

Output:-

You will get the output Hello: Pankaj Kumar.


Experiment-12

Create Test RESTful web services using Spring Boot.

Software Used: Visual Studio Code

package net.codejava;

// ...

@RestController
@RequestMapping("/users")
public class UserApiController {
private UserService service;
private ModelMapper modelMapper;

// ...

@PostMapping
public ResponseEntity<?> add(@RequestBody @Valid User user)
{ User persistedUser = service.add(user);
UserDTO userDto = entity2Dto(persistedUser);

URI uri = URI.create("/users/" + userDto.getId());

return ResponseEntity.created(uri).body(userDto);
}
}

1. Unit Testing REST APIs with Spring

public class UserApiControllerTests

{ @Autowired private MockMvc

mockMvc;

@Autowired private ObjectMapper objectMapper;

@MockBean private UserService service;

@Test
public void testAddUserAPI() throws Exception {

// create a new User object

// serialize User object to JSON string using ObjectMapper

// use Mockito APIs to mock method calls on UserService object

// use MockMVC to perform request (make API call)


// use MockMvcResultMatchers to assert the response (status code, content type, JSON fields,...)
}

package net.codejava;

// ...

@RestController
@RequestMapping("/users")
public class UserApiController
{private UserService service;
private ModelMapper modelMapper;

// ...

@PostMapping
public ResponseEntity<?> add(@RequestBody @Valid User user)
{User persistedUser = service.add(user);
UserDTO userDto = entity2Dto(persistedUser);

URI uri = URI.create("/users/" + userDto.getId());

return ResponseEntity.created(uri).body(userDto);
}

// ...
}

@WebMvcTest(UserApiController.class)
public class UserApiControllerTests {

@Autowired private MockMvc mockMvc;

@Autowired private ObjectMapper objectMapper;

@MockBean private UserService service;

@Test
public void testAddUserAPI() throws Exception {

// create a new User object

// serialize User object to JSON string using ObjectMapper


// use Mockito APIs to mock method calls on UserService object

// use MockMVC to perform request (make API call)

// use MockMvcResultMatchers to assert the response (status code, content type, JSON fields,...)
}

package net.codejava;

import jakarta.persistence.*;

import jakarta.validation.constraints.*;

@Entity @Table(name = "users")


public class User {

@Id @GeneratedValue(strategy = GenerationType.IDENTITY)


private Long id;

@Column(length = 50, nullable = false, unique = true)


@NotBlank(message = "E-mail address must not be
empty") @Email(message = "User must have valid email
address") private String email;

@Column(length = 20, nullable = false)


private String firstName;

@Column(length = 20, nullable = false)


private String lastName;

@Column(length = 10, nullable = false)


private String password;

// getters and setters...

// equals() and hashCode() based on field id...


}

We use ModelMapper for mapping between entity and DTO, so below is code of the UserDTO class:

package net.codejava;

public class UserDTO {


private Long id;

private String email;

private String

firstName; private
String lastName;
// getters and setters...

Spring Data JPA is used for the persistence layer, so below is code of the UserRepository interface:

package net.codejava;

import org.springframework.data.repository.CrudRepository;

public interface UserRepository extends CrudRepository<User, Long> {

package net.codejava;

import java.net.URI;
import java.util.List;
import java.util.stream.Collectors;

import org.modelmapper.ModelMapper;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;

@RestController
@RequestMapping("/users")
public class UserApiController {
private UserService service;
private ModelMapper modelMapper;

protected UserApiController(UserService service, ModelMapper mapper)


{this.service = service;
this.modelMapper = mapper;
}

@PostMapping
public ResponseEntity<?> add(...) {
// ...
}

@GetMapping("/{id}")
public ResponseEntity<?> get(@PathVariable("id") Long id) {
// ...
}

@GetMapping
public ResponseEntity<?> list() {
// ...
}

@PutMapping("/{id}")
public ResponseEntity<?> update(...) {
// ...
}

@DeleteMapping("/{id}")
public ResponseEntity<?> delete(...) {
// …

private UserDTO entity2Dto(User entity) {


return modelMapper.map(entity, UserDTO.class);
}

private List<UserDTO> list2Dto(List<User> listUsers)


{return
listUsers.stream().map( enti
ty -> entity2Dto(entity))
.collect(Collectors.toList());
}
}
So, as you can see, this RES

Test Add User API


Let’s write a couple of unit tests for the Add User API. The implementation code in the controller is as
follows:
@PostMapping

public ResponseEntity<?> add(@RequestBody @Valid User user)


{

User persistedUser = service.add(user);


UserDTO userDto =
entity2Dto(persistedUser);

URI uri = URI.create("/users/" + userDto.getId());

return ResponseEntity.created(uri).body(userDto);
}

Test Get User API


Below code is the implementation of the Get User API, which returns details of a user found by the
given ID:

@GetMapping("/{id}")
public ResponseEntity<?> get(@PathVariable("id") Long id)
{try {
User user = service.get(id);
return ResponseEntity.ok(entity2Dto(user));
}

catch (UserNotFoundException e)
{e.printStackTrace();
return ResponseEntity.notFound().build();
}
}

Output:

You might also like