Lab Manual OOPs With JAVA 2024-25
Lab Manual OOPs With JAVA 2024-25
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 {
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 {
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;
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;
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;
}
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.*;
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;
}
// Main.java
import Mathematics.Matrix;
int[][] matrix1 = {
{1, 2},
{3, 4}
};
int[][] matrix2 = {
{5, 6},
{7, 8}
};
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;
XML Configuration:
Main file:
package in.abes.main;
import org.springframework.context.ApplicationContext;
import in.abes.CSEDS.Student;
import org.springframework.context.support.ClassPathXmlApplicationContext;
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;
@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
GET
http://localhost:8080/api/users
PUT
http://localhost:8080/api/users/1
DELETE
http://localhost:8080/api/users/1
Experiment-11
<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:
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
```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;
```java
package com.example.demo.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.example.demo.model.User;
```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;
```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.
{
"name": "John Doe",
"email": "[email protected]"
}
```
{
"name": "Jane Doe",
"email": "[email protected]"
}
```