Java Practical File BCS-452

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 20

Lloyd Institute of Engineering & Technology

Greater Noida, Uttar Pradesh


Department of Computer Science & Engineering

B. Tech 2nd Year Section A2

Name: Ravi Chaudhary


Roll No: 2201531530023
Subject: Object Oriented Programming with Java
Code: BCS - 452

Submitted To: Mr. Anuj Mittal Date:13/07/2024


Index
Sr. Program Date Remark
Use of Command Line Arguments
WAP in JAVA to calculate the sum and average of numbers scored by a 05/04/2024
1. student in 5 subjects. Read the values from the command line argument.

WAP in JAVA to concatenate two strings provided by command line 05/04/2024


2.
arguments.
Basic Programs to read values and perform operation on read data
WAP in JAVA to read integer input from Scanner class and perform sum, 05/04/2024
3.
difference, multiplication, division operations.
WAP in JAVA to read integer input from BufferedReader class and calculate 05/04/2024
4.
the factorial using recursion and non-recursion methods.
Write a JAVA program to check whether the given number is a magic 12/04/2024
5.
number or not.
Write a JAVA program to check whether the given number is a Strong 12/04/2024
6.
number or not.
Program based on Loops
WAP in JAVA to print the given pattern using a for loop. 12/04/2024
* *
** **
7.
*** ***
**** ****
**********
WAP in JAVA to print Fibonacci sequence up to a given number (Provided 12/04/2024
8.
by user) using a while loop.
Write a Java program to remove duplicate elements from a given array. 19/04/2024
9.
Sample array: [20, 20, 30, 40, 50, 50, 50]
19/04/2024
Write a Java program to check if the sum of all the 10's in the array is
10.
exactly 25. Return false if the condition does not satisfy, otherwise true.

Encapsulation, Inheritance and Polymorphism


Create a class Employee with private attributes like name, age, salary, and 19/04/2024
11. methods to get and set these attributes... Find the average salary of the
employees of the age of more than 30.
Define a superclass vehicle with attributes like speed and color, and a 19/04/2024
12. subclass Car that inherits from Vehicle and adds attributes like model and
number of seats.
Create an interface Shape with a method calculate Area(). Implement this 17/05/2024
13. interface with classes Rectangle and Circle that calculate their respective
areas.
Implement error-handling techniques using exception handling and
multithreading.
Write a program for user defined exceptions that checks the internal and 17/05/2024
external marks. If the internal marks are greater than 30 it raises the
14.
exception “Marks crossed the Upper Limit”. Else it should print the sum of
internal and external marks.
Write a program that demonstrates the use of multithreading by creating two 17/05/2024
15.
threads that print numbers from 1 to 10 simultaneously.
Create a java program with the use of java packages.
Write a Java program to demonstrate the use of packages. Your program 17/05/2024
should meet the following requirements:

1. Create a package named shapes.


2. Inside the shapes package, define three classes: Circle, Rectangle,
and Triangle.
3. Each class should have the following:
16. • A constructor to initialize the dimensions of the shape.
• A method to calculate and return the area of the shape.
4. In the main package, create a Main class that does the following:
• Imports the shapes package.
• Creates instances of Circle, Rectangle, and Triangle.
• Prints the area of each shape.

Construct a java program using Java I/O package.


Write a JAVA program to create a text file. Create this file in the D folder of 27/05/2024
17.
your drive. Also check whether the file exists at a specified location or not.
Write a Java program to read the contents of a text file and display them on 27/05/2024
18.
the console.
19. Write a Java program to write some text to a file. 27/05/2024
20. Write a Java program to copy the contents of one file to another. 27/05/2024

29/05/2024
21. Write a Java program to merge data from two text files into a single text file.

Create industry-oriented applications using Spring Framework.


22. Write a JAVA program using constructor injection. 29/05/2024

23. Create a signin/ login web page using spring boot. 29/05/2024
Practical – 1
Objective: Use of Command Line Arguments
1. Calculate Sum and Average of Numbers in 5 Subjects.

public class SumAndAverage {


public static void main(String[] args) {
int sum = 0;
for (int i = 0; i < 5; i++) {
sum += Integer.parseInt(args[i]);
}
double average = sum / 5.0;
System.out.println("Sum: " + sum);
System.out.println("Average: " + average);
}
}

2. Concatenate Two Strings


public class ConcatenateStrings {

public static void main(String[] args) {


if (args.length < 2) {
System.out.println("Please provide two strings.");
return;
}
String result = args[0] + args[1];
System.out.println("Concatenated String: " + result);
}
}
Practical - 2
Objective: Basic Programs to read values and perform operation on read data
3. Perform Basic Arithmetic Operations

import java.util.Scanner;

public class ArithmeticOperations {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter two integers: ");
int a = scanner.nextInt();
int b = scanner.nextInt();
System.out.println("Sum: " + (a + b));
System.out.println("Difference: " + (a - b));
System.out.println("Product: " + (a * b));
System.out.println("Quotient: " + (a / b));
}
}

4. Calculate Factorial

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

public class Factorial {


public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter an integer: ");
int number = Integer.parseInt(reader.readLine());
System.out.println("Factorial (recursion): " + factorialRecursion(number));
System.out.println("Factorial (non-recursion): " + factorialNonRecursion(number));
}
public static int factorialRecursion(int n) {
if (n == 0) return 1;
return n * factorialRecursion(n - 1);
}

public static int factorialNonRecursion(int n) {


int result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}
}

5. Check Magic Number

import java.util.Scanner;

public class MagicNumber {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number: ");
int number = scanner.nextInt();
System.out.println(isMagicNumber(number) ? "Magic Number" : "Not a Magic Number");
}

public static boolean isMagicNumber(int number) {


int sum = sumOfDigits(number);
while (sum > 9) {
sum = sumOfDigits(sum);
}
return sum == 1;
}

public static int sumOfDigits(int number) {


int sum = 0;
while (number > 0) {
sum += number % 10;
number /= 10;
}
return sum;
}
}

6. Check Strong Number

import java.util.Scanner;

public class StrongNumber {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number: ");
int number = scanner.nextInt();
System.out.println(isStrongNumber(number) ? "Strong Number" : "Not a Strong Number");
}

public static boolean isStrongNumber(int number) {


int sum = 0, temp = number;
while (temp > 0) {
sum += factorial(temp % 10);
temp /= 10;
}
return sum == number;
}

public static int factorial(int n) {


int result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}
}
Practical - 3
Objective: Program based on Loops
7. Print Pattern Using For Loop

public class Pattern {


public static void main(String[] args) {
int n = 5;
for (int i = 0; i < n; i++) {
for (int j = 0; j <= i; j++) {
System.out.print("*");
}
for (int k = 2 * (n - i - 1); k > 0; k--) {
System.out.print(" ");
}
for (int j = 0; j <= i; j++) {
System.out.print("*");
}
System.out.println();
}
}
}

8. Fibonacci Sequence Using While Loop

import java.util.Scanner;

public class Fibonacci {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number: ");
int n = scanner.nextInt();
int a = 0, b = 1;
System.out.print("Fibonacci Sequence: " + a + " " + b);
while (b < n) {
int next = a + b;
System.out.print(" " + next);
a = b;
b = next;
}
}
}
9. Remove Duplicate Elements from Array

import java.util.Arrays;
public class RemoveDuplicates {
public static void main(String[] args) {
int[] array = {20, 20, 30, 40, 50, 50, 50};
int[] uniqueArray = Arrays.stream(array).distinct().toArray();
System.out.println("Array without duplicates: " + Arrays.toString(uniqueArray));
}
}

10. Check Sum of All 10's in Array

public class SumOfTens {


public static void main(String[] args) {
int[] array = {10, 10, 10, 10, 5, 5};
System.out.println(isSumOfTensTwentyFive(array) ? "True" : "False");
}

public static boolean isSumOfTensTwentyFive(int[] array) {


int sum = 0;
for (int value : array) {
if (value == 10) {
sum += value;
}
}
return sum == 25;
}
}
Practical – 4
Objective: Encapsulation, Inheritance and Polymorphism
11. Employee Class
class Employee {
private String name;
private int age;
private double salary;
public Employee(String name, int age, double salary) {
this.name = name;
this.age = age;
this.salary = salary;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public double getSalary() {
return salary;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public void setSalary(double salary) {
this.salary = salary;
}
public static double averageSalary(Employee[] employees) {
double sum = 0;
int count = 0;
for (Employee emp : employees) {
if (emp.getAge() > 30) {
sum += emp.getSalary();
count++;
}
}
return sum / count;
}
public static void main(String[] args) {
Employee[] employees = {
new Employee("John", 35, 50000),
new Employee("Jane", 28, 60000),
new Employee("Jack", 40, 70000)
};
System.out.println("Average salary of employees over 30: " + averageSalary(employees));
}
}
12. Vehicle and Car Classes
class Vehicle {
private int speed;
private String color;
public Vehicle(int speed, String color) {
this.speed = speed;
this.color = color;
}
public int getSpeed() {
return speed;
}
public String getColor() {
return color;
}
}
class Car extends Vehicle {
private String model;
private int numberOfSeats;

public Car(int speed, String color, String model, int numberOfSeats) {


super(speed, color);
this.model = model;
this.numberOfSeats = numberOfSeats;
}
public String getModel() {
return model;
}
public int getNumberOfSeats() {
return numberOfSeats;
}

public static void main(String[] args) {


Car car = new Car(200, "Red", "Tesla", 4);
System.out.println("Car Model: " + car.getModel());
System.out.println("Car Speed: " + car.getSpeed());
System.out.println("Car Color: " + car.getColor());
System.out.println("Car Seats: " + car.getNumberOfSeats());
}
}
Practical – 5
Objective: Implement error-handling techniques using exception handling and
multithreading.
13. Shape Interface
interface Shape {
double calculateArea();
}
class Rectangle implements Shape {
private double length, width;

public Rectangle(double length, double width) {


this.length = length;
this.width = width;
}
public double calculateArea

() {
return length * width;
}
}

class Circle implements Shape {


private double radius;

public Circle(double radius) {


this.radius = radius;
}

public double calculateArea() {


return Math.PI * radius * radius;
}
}
public class Main {
public static void main(String[] args) {
Shape rectangle = new Rectangle(10, 5);
Shape circle = new Circle(7);
System.out.println("Area of Rectangle: " + rectangle.calculateArea());
System.out.println("Area of Circle: " + circle.calculateArea());
}
}

14. User Defined Exception


class MarksExceededException extends Exception {
public MarksExceededException(String message) {
super(message);
}
}

public class MarksCheck {


public static void main(String[] args) {
try {
checkMarks(35, 40);
} catch (MarksExceededException e) {
System.out.println(e.getMessage());
}
}

public static void checkMarks(int internalMarks, int externalMarks) throws MarksExceededException


{
if (internalMarks > 30) {
throw new MarksExceededException("Marks crossed the Upper Limit");
} else {
System.out.println("Total Marks: " + (internalMarks + externalMarks));
}
}
}
15. Multithreading
class PrintNumbers extends Thread {
public void run() {
for (int i = 1; i <= 10; i++) {
System.out.println(i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class MultiThreadingDemo {
public static void main(String[] args) {
PrintNumbers thread1 = new PrintNumbers();
PrintNumbers thread2 = new PrintNumbers();
thread1.start();
thread2.start();
}
}
Practical - 6
Practical - 6
Objective: Create a java program with the use of java
packages.
16. Use of Packages

// File: Local/ravic/java/shapes/Circle.java
package shapes;

public class Circle {


private double radius;

public Circle(double radius) {


this.radius = radius;
}

public double calculateArea() {


return Math.PI * radius * radius;
}
}

// File: Local/ravic/java/shapes/Rectangle.java
package shapes;

public class Rectangle {


private double length, width;

public Rectangle(double length, double width) {


this.length = length;
this.width = width;
}

public double calculateArea() {


return length * width;
}
}

// File: Local/ravic/java/shapes/Triangle.java
package shapes;

public class Triangle {


private double base, height;

public Triangle(double base, double height) {


this.base = base;
this.height = height;
}

public double calculateArea() {


return 0.5 * base * height;
}
}

// File: Local/ravic/java/ Main.java


import shapes.*;

public class Main {


public static void main(String[] args) {
Circle circle = new Circle(7);
Rectangle rectangle = new Rectangle(10, 5);
Triangle triangle = new Triangle(8, 4);

System.out.println("Area of Circle: " + circle.calculateArea());


System.out.println("Area of Rectangle: " + rectangle.calculateArea());
System.out.println("Area of Triangle: " + triangle.calculateArea());
}
Practical - 7
Objective: Construct a java program using Java I/O package .
17. Create Text File

import java.io.File;
import java.io.IOException;

public class CreateFile {


public static void main(String[] args) {
File file = new File("D:/textfile.txt");
try {
if (file.createNewFile()) {
System.out.println("File created: " + file.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

18. Read Text File

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadFile {


public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new FileReader("D:/textfile.txt"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
19. Write to Text File

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

public class WriteFile {


public static void main(String[] args) {
try (BufferedWriter writer = new BufferedWriter(new FileWriter("D:/textfile.txt"))) {
writer.write("This is a sample text.");
} catch (IOException e) {
e.printStackTrace();
}
}
}

20. Copy Contents of File

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class CopyFile {


public static void main(String[] args) {
try (FileReader fr = new FileReader("D:/source.txt");
FileWriter fw = new FileWriter("D:/destination.txt")) {
int c;
while ((c = fr.read()) != -1) {
fw.write(c);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

21. Merge Data of Two Text Files

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class MergeFiles {


public static void main(String[] args) {
try (BufferedReader br1 = new BufferedReader(new FileReader("D:/file1.txt"));
BufferedReader br2 = new BufferedReader(new FileReader("D:/file2.txt"));
FileWriter fw = new FileWriter("D:/mergedfile.txt")) {
String line;
while ((line = br1.readLine()) != null) {
fw.write(line + "\n");
}
while ((line = br2.readLine()) != null) {
fw.write(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Practical - 8
Objective: Create industry-oriented applications using Spring
Framework.
22. Constructor Injection
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Component;

@Component
public class Example {
private final Dependency dependency;
}
@Autowired
public Example(Dependency dependency) {
this.dependency = dependency;
}
public void show() {
dependency.doSomething();
}

@Component
class Dependency {
public void doSomething() {
System.out.println("Dependency is doing something!");
}

23. Signin/Login Web Page using Spring Boot


// File: Local/ravic/java/com/example/demo/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);
}
}
// File: Local/ravic/java/com/example/demo/controller/LoginController.java
package com.example.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class LoginController {
@GetMapping("/login")
public String login() {
return "login";
}
}

// File: Local/ravic/java/main/resources/templates/login.html
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
</head>
<body>
<h2>Login Page</h2>
<form action="/login" method="post">
<div>
<label>Username:</label>
<input type="text" name="username" required>
</div>
<div>
<label>Password:</label>
<input type="password" name="password" required>
</div>
<div>
<button type="submit">Login</button>
</div>
</form>
</body>
</html>

You might also like