asses2_java_sid
asses2_java_sid
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;
// 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);
// 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:
i) Develop a Java program by defining a package named find. The package should include two
classes to perform the following operations:
PROGRAM:
package find;
import java.util.Scanner;
sc.close();
}
}
OUTPUT:
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
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;
package check;
File 3: Main.java
import check.CheckPrime;
import check.CheckArmstrong;
import java.util.Scanner;
sc.close();
}
}
Output:
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;
// 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();
}
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));
}
}
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;
2. MatrixTranspose.java:
package multithread;
public class MatrixTranspose extends
Thread { private int[][] matrix;
private int[][] 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);
}
package multithread;
public class MatrixNorm extends
Thread { private int[][] 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;
@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;
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.
(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;
}
2. BankingSystem.java:
package bank;
import java.util.Scanner;
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());
}
}
}
Program:
package siddarth;
import
java.util.Collection;
import java.util.List;
import java.util.Scanner;
// 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:
Program:
package siddarth;
import java.util.ArrayList;
import
java.util.EmptyStackException;
import java.util.Scanner;
public GenericStack() {
stack = new ArrayList<>();
}
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);
}
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: