0% found this document useful (0 votes)
4 views

asses2_java_sid

The document contains multiple Java programming tasks, including creating abstract classes with iterative and recursive methods, implementing a banking transaction system with exception handling, and developing multi-threaded applications for matrix operations. Each task includes code snippets and expected outputs, demonstrating the functionality of the programs. Additionally, it emphasizes the importance of proper package structure and error handling in Java applications.
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)
4 views

asses2_java_sid

The document contains multiple Java programming tasks, including creating abstract classes with iterative and recursive methods, implementing a banking transaction system with exception handling, and developing multi-threaded applications for matrix operations. Each task includes code snippets and expected outputs, demonstrating the functionality of the programs. Additionally, it emphasizes the importance of proper package structure and error handling in Java applications.
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/ 21

1.

Create an abstract class NumOperations with two abstract methods sumofDigits() and
calPowofNum(). Derive two subclasses Iterative and Recursion. In Iterative class implement abstract
methods without using recursion concept and Recursion class implement abstract methods using
recursion. Declare objects of both classes and call respective methods.

Program:
package siddarth;
import java.util.Scanner;

abstract class NumOperations {


// Abstract methods
abstract int sumofDigits(int n);
abstract int calPowofNum(int base, int exp);
}

// Iterative implementation
class Iterative extends NumOperations {
@Override
int sumofDigits(int n)
{ int sum = 0;
while (n != 0) {
sum += n %
10; n /= 10;
}
return sum;
}

@Override
int calPowofNum(int base, int exp)
{ int result = 1;
for (int i = 0; i < exp; i++)
{ result *= base;
}
return result;
}
}

// Recursive implementation
class Recursion extends NumOperations {
@Override
int sumofDigits(int n)
{ if (n == 0) {
return 0;
}
return n % 10 + sumofDigits(n / 10);
}

@Override
int calPowofNum(int base, int exp)
{ if (exp == 0) {
return 1;
}
return base * calPowofNum(base, exp - 1);
}
}
// Main class to test the
implementation public class numoper {
public static void main(String[] args)
{ Scanner sc = new
Scanner(System.in);

System.out.print("Enter a number for sum of digits:


"); int num = sc.nextInt();

System.out.print("Enter base for power calculation:


"); int base = sc.nextInt();

System.out.print("Enter exponent for power calculation:


"); int exp = sc.nextInt();

NumOperations it = new Iterative();


NumOperations rec = new
Recursion();

// Iterative calls
System.out.println("Iterative Sum of Digits of " + num + ": " +
it.sumofDigits(num));
System.out.println("Iterative Power of " + base + "^" + exp + ": " +
it.calPowofNum(base, exp));

// Recursive calls
System.out.println("Recursive Sum of Digits of " + num + ": " +
rec.sumofDigits(num));
System.out.println("Recursive Power of " + base + "^" + exp + ": " +
rec.calPowofNum(base, exp));

sc.close();
}

OUTPUT:

Enter a number for sum of digits:


234 Enter base for power
calculation: 3 Enter exponent for
power calculation: 4 Iterative Sum
of Digits of 234: 9 Iterative Power
of 3^4: 81
Recursive Sum of Digits of 234: 9
Recursive Power of 3^4: 81
2.

i) Develop a Java program by defining a package named find. The package should include two
classes to perform the following operations:

 Calculating the factorial of a number and

 Finding the nth Fibonacci number.

PROGRAM:

package find;
import java.util.Scanner;

// Class for factorial


calculation class Factorial {
public int calculateFactorial(int n)
{ if (n == 0 || n == 1) {
return 1;
}
int fact = 1;
for (int i = 2; i <= n; i++) {
fact *= i;
}
return fact;
}
}

// Class for Fibonacci


calculation class Fibonacci {
public int calculateFibonacci(int n)
{ if (n <= 1) {
return n;
}
int a = 0, b = 1, fib = 0;
for (int i = 2; i <= n; i+
+) {
fib = a + b;
a = b;
b = fib;
}
return fib;
}
}

// Main class to test the


implementation public class finding {
public static void main(String[] args)
{ Scanner sc = new
Scanner(System.in);

System.out.print("Enter a number to calculate factorial:


"); int numFactorial = sc.nextInt();
Factorial factorial = new Factorial();
System.out.println("Factorial of " + numFactorial + "
is: " +
factorial.calculateFactorial(numFactorial));

System.out.print("Enter the position to find Fibonacci number:


System.out.println("Fibonacci number at position " + numFibonacci +
" is: " + fibonacci.calculateFibonacci(numFibonacci));

sc.close();
}
}

OUTPUT:

Enter a number to calculate


factorial: 5 Factorial of 5 is: 120
Enter the position to find Fibonacci number: 7
Fibonacci number at position 7 is: 13

ii) Develop a Java program to create a user-defined package named check. The package should
contain following two classes:  CheckPrime -> to check whether the number is prime or not. 
CheckArmstrong -> to check whether the number is Armstrong number or not. Import these
classes and use them to access their functionality

(don’t write this)

The error in the program arises because Java does not allow more than one public class in the same
file unless each class resides in its separate .java file within the same package. Additionally,
importing classes from the check package in the same file will not work.

Fixes:

Separate CheckPrime and CheckArmstrong into their own files named CheckPrime.java and
CheckArmstrong.java inside the check package.

Ensure the Main class is in a different file outside the check package or in the same package

PROGRAM:

File 1: CheckPrime.java

package check;

public class CheckPrime {


public boolean isPrime(int n) {
if (n <= 1) {
return false;
}
for (int i = 2; i <= Math.sqrt(n); i++)
{ if (n % i == 0) {
return false;
}
}
return true;
}
}
File 2: CheckArmstrong.java

package check;

public class CheckArmstrong {


public boolean isArmstrong(int n) {
int original = n, sum = 0;
while (n > 0) {
int digit = n % 10;
sum += Math.pow(digit, 3);
n /= 10;
}
return sum == original;
}
}

File 3: Main.java

import check.CheckPrime;
import check.CheckArmstrong;
import java.util.Scanner;

public class Main {


public static void main(String[] args)
{ Scanner sc = new Scanner(System.in);

System.out.print("Enter a number to check if it is prime: ");


int numPrime = sc.nextInt();
CheckPrime checkPrime = new CheckPrime();
if (checkPrime.isPrime(numPrime)) {
System.out.println(numPrime + " is a prime number.");
} else {
System.out.println(numPrime + " is not a prime number.");
}

System.out.print("Enter a number to check if it is an Armstrong


number: ");
int numArmstrong = sc.nextInt();
CheckArmstrong checkArmstrong = new CheckArmstrong();
if (checkArmstrong.isArmstrong(numArmstrong)) {
System.out.println(numArmstrong + " is an Armstrong number.");
} else {
System.out.println(numArmstrong + " is not an Armstrong
number.");
}

sc.close();
}
}

Output:

Enter a number to check if it is prime: 34


34 is not a prime number.
Enter a number to check if it is an Armstrong number: 153
153 is an Armstrong number.
3

i) Write a Java program that implements a multi-thread application that has three threads.
First thread randomly generates n elements, second thread finds the sum of all the
elements and third thread sort those elements in ascending order.

package siddarth;
import
java.util.Arrays;
import
java.util.Random;

public class MultiThreadApp {

public static void main(String[] args)


{ int n = 10; // Number of elements

// Create threads
Thread t1 = new Thread(new
NumberGenerator(n)); Thread t2 = new
Thread(new SumCalculator()); Thread t3 = new
Thread(new ArraySorter());

// Start threads
t1.start();
try {
t1.join(); // Wait for t1 to finish
} catch (InterruptedException e)
{ e.printStackTrace();
}
t2.start();
t3.start();
}

static class NumberGenerator implements


Runnable { private int n;
private static int[] numbers;

public NumberGenerator(int n)
{ this.n = n;
}

@Override
public void run() {
numbers = new int[n];
Random random = new
Random(); for (int i = 0;
i < n; i++) {
numbers[i] = random.nextInt(100);
}
System.out.println("Generated numbers: " +
Arrays.toString(numbers));
}
}

static class SumCalculator implements Runnable {


@Override
public void run()
System.out.println("Sum of numbers: " + sum);
}
}

static class ArraySorter implements Runnable {


@Override
public void run() {
Arrays.sort(NumberGenerator.numbers);
System.out.println("Sorted numbers: " +
Arrays.toString(NumberGenerator.numbers));
}
}
}

Output:

Generated numbers: [66, 60, 69, 44, 56, 83, 74, 32, 1]
89,
Sorted numbers: [1, 32, 44, 56, 60, 66, 69, 83, 89]
74,
Sum of numbers: 574

ii) Write a Java program that implements a multi-thread application that has four threads. First
thread generates MXN dimensional matrix elements, second thread finds the transpose of
the matrix, and third thread print the norm of the matrix and fourth thread determines the
trace of the matrix.

Don’t write this: create one separate package for this program then create separate classes
then run main .java file

Program:

1. MatrixGenerator.java:

package multithread;
import
java.util.Random;

public class MatrixGenerator extends Thread {


private int[][] matrix;
private int
rows; private
int cols;

public MatrixGenerator(int rows, int cols)


{ this.rows = rows;
this.cols = cols;
this.matrix = new int[rows][cols];
}

public int[][] getMatrix() {


return matrix;
}
public void run() {
Random rand = new Random();
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
matrix[i][j] = rand.nextInt(100); // Generate
random numbers between 0 and 99
}
}
System.out.println("Matrix generated:");
printMatrix(matrix);
}

private void printMatrix(int[][] matrix)


{ for (int[] row : matrix) {
for (int elem : row) {
System.out.print(elem + " ");
}
System.out.println();
}
}
}

2. MatrixTranspose.java:

package multithread;
public class MatrixTranspose extends
Thread { private int[][] matrix;
private int[][] transpose;

public MatrixTranspose(int[][] matrix)


{ this.matrix = matrix;
this.transpose = new int[matrix[0].length][matrix.length];
}

public int[][] getTranspose() {


return transpose;
}

@Override
public void run() {
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
transpose[j][i] = matrix[i][j];
}
}
System.out.println("Transpose of the matrix:");
printMatrix(transpose);
}

private void printMatrix(int[][] matrix)


{ for (int[] row : matrix) {
for (int elem : row) {
System.out.print(elem + " ");
}
System.out.println();
}
}
}
3. MatrixNorm.java:

package multithread;
public class MatrixNorm extends
Thread { private int[][] matrix;

public MatrixNorm(int[][] matrix)


{ this.matrix = matrix;
}

@Override
public void run() {
double norm = 0;
for (int[] row : matrix) {
for (int elem : row) {
norm += elem * elem;
}
}
norm = Math.sqrt(norm);
System.out.println("Norm of the matrix: " + norm);
}
}

4. MatrixTrace.java:

package multithread;
public class MatrixTrace extends
Thread { private int[][] matrix;

public MatrixTrace(int[][] matrix)


{ this.matrix = matrix;
}

@Override
public void run()
{ int trace =
0;
for (int i = 0; i < Math.min(matrix.length, matrix[0].length); i++)
{ trace += matrix[i][i];
}
System.out.println("Trace of the matrix: " + trace);
}
}
5. Main.java:

package multithread;
public class Main {
public static void main(String[] args)
{ int rows = 3;
int cols = 3;

MatrixGenerator generator = new MatrixGenerator(rows, cols);


generator.start();
try {
generator.join()
;
} catch (InterruptedException e)
{ e.printStackTrace();
}

int[][] matrix = generator.getMatrix();

MatrixTranspose transpose = new MatrixTranspose(matrix);


MatrixNorm norm = new MatrixNorm(matrix);
MatrixTrace trace = new MatrixTrace(matrix);

transpose.start();
try {
transpose.join();
} catch (InterruptedException e)
{ e.printStackTrace();
}

norm.start();
trace.start();
}
}

Output:

Matrix generated:
61 51 30
83 85 77
32 84 71
Transpose of the matrix:
61 83 32
51 85 84
30 77 71
Trace of the matrix: 217
Norm of the matrix: 200.96268310310748
4. Develop a Banking Transaction System that allows users to perform basic banking operations such
as checking their balance, depositing money, withdrawing money, and transferring funds. The
system should handle following predefined exceptions to ensure smooth operation.

 IllegalArgumentException: For invalid input (e.g., negative deposit/withdrawal).

 ArithmeticException: For insufficient funds.

 NullPointerException: For null recipient in fund transfers.

 NumberFormatException: For invalid input formats when reading numbers.

(same create an separate package then create two class files then run main class file)

Program:

1. BankAccount.java:

package bank;
public class BankAccount {
private double balance;

public BankAccount(double
initialBalance) { if (initialBalance
< 0) {
throw new IllegalArgumentException("Initial balance cannot be
negative.");
}
this.balance = initialBalance;
}

public double getBalance() {


return balance;
}

public void deposit(double amount)


{ if (amount <= 0) {
throw new IllegalArgumentException("Deposit amount must be
positive.");
}
balance += amount;
}

public void withdraw(double


amount) { if (amount <= 0) {
throw new IllegalArgumentException("Withdrawal amount must be
positive.");
}
if (amount > balance) {
throw new ArithmeticException("Insufficient funds.");
}
balance -= amount;
}

public void transfer(BankAccount recipient, double


amount) { if (recipient == null) {
throw new NullPointerException("Recipient account cannot be
}
if (amount <= 0) {
throw new IllegalArgumentException("Transfer amount must be
positive.");
}
if (amount > balance) {
throw new ArithmeticException("Insufficient funds.");
}
this.withdraw(amount);
recipient.deposit(amount);
}
}

2. BankingSystem.java:

package bank;
import java.util.Scanner;

public class BankingSystem {


public static void main(String[] args) {
Scanner scanner = new
Scanner(System.in);

System.out.print("Enter initial balance for Account 1:


"); double initialBalance1 = readDouble(scanner);
BankAccount account1 = new BankAccount(initialBalance1);

System.out.print("Enter initial balance for Account 2:


"); double initialBalance2 = readDouble(scanner);
BankAccount account2 = new BankAccount(initialBalance2);

while (true) {
System.out.println("\nBanking System Menu:");
System.out.println("1. Check Balance");
System.out.println("2. Deposit Money");
System.out.println("3. Withdraw Money");
System.out.println("4. Transfer Funds");
System.out.println("5. Exit");
System.out.print("Choose an option: ");
int choice = readInt(scanner);

try {
switch (choice) {
case 1:
System.out.println("Account 1 Balance: " +
account1.getBalance());
System.out.println("Account 2 Balance: " +
account2.getBalance());
break
; case 2:
System.out.print("Enter account number (1 or
2): "); int accountNumber = readInt(scanner);
System.out.print("Enter deposit amount: ");
double depositAmount =
readDouble(scanner); if (accountNumber
== 1) {
account1.deposit(depositAmount);
} else if (accountNumber == 2) {
account2.deposit(depositAmount);
} else {
}
break;
case 3:
System.out.print("Enter account number (1 or
2): "); accountNumber = readInt(scanner);
System.out.print("Enter withdrawal amount: ");
double withdrawalAmount = readDouble(scanner);
if (accountNumber == 1) {
account1.withdraw(withdrawalAmount);
} else if (accountNumber == 2) {
account2.withdraw(withdrawalAmount);
} else {
System.out.println("Invalid account number.");
}
break;
case 4:
System.out.print("Enter transfer amount:
"); double transferAmount =
readDouble(scanner);
account1.transfer(account2,
transferAmount); break;
case 5:
System.out.println("Exiting...");
scanner.close();
return;
default:
System.out.println("Invalid choice. Please try
again.");
}
} catch (IllegalArgumentException | ArithmeticException |
NullPointerException e) {
System.out.println("Error: " + e.getMessage());
}
}
}

private static double readDouble(Scanner


scanner) { while (true) {
try {
return Double.parseDouble(scanner.nextLine());
} catch (NumberFormatException e) {
System.out.print("Invalid input. Please enter a valid number:
");
}
}
}

private static int readInt(Scanner


scanner) { while (true) {
try {
return Integer.parseInt(scanner.nextLine());
} catch (NumberFormatException e) {
System.out.print("Invalid input. Please enter a valid number:
");
}
}
}
}
Output:

Enter initial balance for Account 1:


100 Enter initial balance for Account
2: 100

Banking System Menu:


1. Check Balance
2. Deposit Money
3. Withdraw Money
4. Transfer Funds
5. Exit
Choose an option: 1
Account 1 Balance:
100.0
Account 2 Balance: 100.0

Banking System Menu:


1. Check Balance
2. Deposit Money
3. Withdraw Money
4. Transfer Funds
5. Exit
Choose an option: 2
Enter account number (1 or
2): 1 Enter deposit amount:
100

Banking System Menu:


1. Check Balance
2. Deposit Money
3. Withdraw Money
4. Transfer Funds
5. Exit
Choose an option: 1
Account 1 Balance:
200.0
Account 2 Balance: 100.0

Banking System Menu:


1. Check Balance
2. Deposit Money
3. Withdraw Money
4. Transfer Funds
5. Exit
Choose an option: 3
Enter account number (1 or
2): 1 Enter withdrawal
amount: 50

Banking System Menu:


1. Check Balance
2. Deposit Money
3. Withdraw Money
4. Transfer Funds
5. Exit
Choose an option: 1
Account 1 Balance:
150.0
Account 2 Balance: 100.0

Banking System Menu:


1. Check Balance
2. Deposit Money
3. Withdraw Money
4. Transfer Funds
5. Exit
Choose an option: 4
Enter transfer amount:
30

Banking System Menu:


1. Check Balance
2. Deposit Money
3. Withdraw Money
4. Transfer Funds
5. Exit
Choose an option: 1
Account 1 Balance:
120.0
Account 2 Balance: 130.0

Banking System Menu:


1. Check Balance
2. Deposit Money
3. Withdraw Money
4. Transfer Funds
5. Exit
Choose an option: 5

i) Write a Java program to implement a generic method to search an element in a collection of


various data types.

Program:

package siddarth;
import
java.util.Collection;
import java.util.List;
import java.util.Scanner;

public class GenericSearch {


public static <T> boolean containsElement(Collection<T> collection, T
element)
{
for (T item : collection) {
if (item.equals(element))
{ return true;
}
}
return false;
}

public static void main(String[] args) {


Scanner scanner = new
Scanner(System.in);

// Example collections
Collection<Integer> intCollection = List.of(1, 2, 3, 4, 5);
Collection<String> stringCollection = List.of("apple", "banana",
System.out.println("Choose collection type (1 for Integer, 2 for
String):
");
int choice = Integer.parseInt(scanner.nextLine());

if (choice == 1) {
System.out.println("Enter an integer to search:
"); int element =
Integer.parseInt(scanner.nextLine());
boolean found = containsElement(intCollection, element);
System.out.println("Does intCollection contain " + element + "?
" +
found);
} else if (choice == 2) {
System.out.println("Enter a string to search:
"); String element = scanner.nextLine();
boolean found = containsElement(stringCollection, element);
System.out.println("Does stringCollection contain '" + element +
"'? "
+ found);
} else {
System.out.println("Invalid choice.");
}

Output:

Choose collection type (1 for Integer, 2 for


String): 2
Enter a string to search:
bag
Does stringCollection contain 'bag'? false

Choose collection type (1 for Integer, 2 for


String): 1
Enter an integer to
search: 4
Does intCollection contain 4? true

Choose collection type (1 for Integer, 2 for


String): 2
Enter a string to search:
banana
Does stringCollection contain 'banana'? true

Choose collection type (1 for Integer, 2 for


String): 2
Enter a string to search:
cap
Does stringCollection contain 'cap'? false
ii) Write a Java program to implement a generic class to perform stack operations on various
data types.

Program:

package siddarth;
import java.util.ArrayList;
import
java.util.EmptyStackException;
import java.util.Scanner;

public class GenericStack<T>


{ private ArrayList<T>
stack;

public GenericStack() {
stack = new ArrayList<>();
}

public void push(T element) {


stack.add(element);
}

public T pop() {
if (stack.isEmpty()) {
throw new EmptyStackException();
}
return stack.remove(stack.size() - 1);
}

public T peek() {
if (stack.isEmpty()) {
throw new EmptyStackException();
}
return stack.get(stack.size() - 1);
}

public boolean isEmpty() {


return
stack.isEmpty();
}

public int size() {


return
stack.size();
}

public static void main(String[] args) {


Scanner scanner = new
Scanner(System.in);

GenericStack<Integer> intStack = new GenericStack<>();


GenericStack<String> stringStack = new GenericStack<>();

while (true) {
System.out.println("\nStack Operations Menu:");
System.out.println("1. Push Integer");
System.out.println("2. Pop Integer");
System.out.println("3. Peek Integer");
System.out.println("4. Push String");
System.out.println("5. Pop String");
System.out.println("6. Peek String");
System.out.println("7. Exit");
System.out.print("Choose an option: ");
int choice = Integer.parseInt(scanner.nextLine());

try {
switch (choice) {
case 1:
System.out.print("Enter an integer to push: ");
int intElement =
Integer.parseInt(scanner.nextLine());
intStack.push(intElement);
System.out.println("Pushed " + intElement + " onto
the
integer stack.");
break
; case 2:
System.out.println("Popped " + intStack.pop() + "
from the
integer stack.");
break
; case 3:
System.out.println("Top element of the integer stack:
" +
intStack.peek());
break
; case 4:
System.out.print("Enter a string to push:
"); String strElement =
scanner.nextLine();
stringStack.push(strElement);
System.out.println("Pushed " + strElement + " onto
the
string stack.");
break
; case 5:
System.out.println("Popped " + stringStack.pop() + "
from
the string stack.");
break
; case 6:
System.out.println("Top element of the string stack:
" +
stringStack.peek());
break
; case 7:
System.out.println("Exiting...");
scanner.close();
return
; default:
System.out.println("Invalid choice. Please try
again.");
}
Output:

Stack Operations Menu:


1. Push Integer
2. Pop Integer
3. Peek Integer
4. Push String
5. Pop String
6. Peek String
7. Exit
Choose an option: 1
Enter an integer to push: 20
Pushed 20 onto the integer
stack.

Stack Operations Menu:


1. Push Integer
2. Pop Integer
3. Peek Integer
4. Push String
5. Pop String
6. Peek String
7. Exit
Choose an option: 2
Popped 20 from the integer stack.

Stack Operations Menu:


1. Push Integer
2. Pop Integer
3. Peek Integer
4. Push String
5. Pop String
6. Peek String
7. Exit
Choose an option: 3
Error: Stack is empty.

Stack Operations Menu:


1. Push Integer
2. Pop Integer
3. Peek Integer
4. Push String
5. Pop String
6. Peek String
7. Exit
Choose an option: 4
Enter a string to push: sid
Pushed sid onto the string
stack.

Stack Operations Menu:


1. Push Integer
2. Pop Integer
3. Peek Integer
4. Push String
5. Pop String
6. Peek String
7. Exit
Choose an option: 5
Popped sid from the string stack.

Stack Operations Menu:


1. Push Integer
2. Pop Integer
3. Peek Integer
4. Push String
5. Pop String
6. Peek String
7. Exit
Choose an option: 6
Error: Stack is empty.

Stack Operations Menu:


1. Push Integer
2. Pop Integer
3. Peek Integer
4. Push String
5. Pop String
6. Peek String
7. Exit
Choose an option: 7
Exiting...

You might also like