Set-A
Program01:
==========
Program Statement: Sum of Prime Numbers Calculation using Multithreading
==================
Objective:
===========
Implement a Java program that calculates the sum of all prime numbers up to a given
limit using multiple threads.
Requirements:
=============
The program should take a user-defined limit as input.
Implement a multithreaded solution to concurrently find and sum prime numbers
within the given limit.
Display the calculated sum of prime numbers.
Program Steps:
==============
User Input:
------------
Prompt the user to enter a positive integer as the upper limit for prime number
calculation.
Ensure proper input validation to handle non-positive or invalid inputs.
Multithreaded Prime Number Calculation:
---------------------------------------
Create a class PrimeCalculator that extends Thread.
The PrimeCalculator class should have fields to represent the lower and upper
bounds of the range for prime number calculation.
Implement the run method to find prime numbers within the specified range.
Use multiple instances of PrimeCalculator to divide the range among threads for
parallel computation.
Sum Calculation:
================
Create a class PrimeSumCalculator that implements Runnable.
The PrimeSumCalculator class should have fields to store the sums calculated by
individual threads.
Implement the run method to calculate the sum of prime numbers concurrently.
Main Program:
=============
In the main program, instantiate multiple PrimeCalculator threads with appropriate
ranges.
Start all the threads to concurrently find prime numbers.
Create an instance of PrimeSumCalculator to calculate the sum of prime numbers.
Start the sum calculator thread.
Wait for all prime calculator threads to complete using proper synchronization
mechanisms.
Retrieve the sums calculated by individual threads and calculate the total sum.
Output:
-------
Display the total sum of prime numbers up to the given limit.
Example Output:
--------------
Enter the upper limit for prime number calculation: 50
Sum of prime numbers up to 50 is: 328
Solution:
=========
package thread;
public class PrimeCalculator extends Thread{
static int lower=2;static int upper=50,c;static int k=0;static int i;
static int a[]=new int[upper];
public void run()
{
for(i=lower;i<=upper;i++)
{
c=0;
for(int j=1;j<=i;j++)
{
if(i%j==0)
c++;
}
if(c==2)
{
a[k]=i;
k++;
}
lower=i;
//System.out.println(i);
}
}
}
-----------------
package thread;
import java.util.Arrays;
public class PrimeSumCalculator implements Runnable{
int sum=0;
@Override
public void run() {
for(int i=0;i<PrimeCalculator.k;i++)
{
sum+=PrimeCalculator.a[i];
System.out.println(PrimeCalculator.a[i]);
}
System.out.println("sum="+sum);
}
}
------------------
package thread;
public class PrimeMain {
public static void main(String[] args) throws InterruptedException {
PrimeCalculator pc1=new PrimeCalculator();
PrimeCalculator pc2=new PrimeCalculator();
PrimeCalculator pc3=new PrimeCalculator();
PrimeCalculator pc4=new PrimeCalculator();
pc1.start();
pc2.start();
pc3.start();
pc4.start();
PrimeSumCalculator psm=new PrimeSumCalculator();
Thread t1=new Thread(psm);
t1.start();
Program : 2
============
Write a program to find the the percentage of Characters,digits,special
characters from the given String.
Method name : percentageOfCharacters
Argument : String
Return Type : String
Example :
input : "Nacre@123%"
output :
character : 50.00%
digit : 30.00%
special character : 20.00%
NOTE : If input String is null or empty then return "invalid String
input".
===================================================================================
=========
Set-B
Program01:
==========
Program Statement: Printing Odd and Even Numbers Using wait() and notify()
Objective:
==========
Implement a Java program with two threads, one for printing odd numbers and the
other for printing even numbers. Use the wait() and notify() mechanisms to ensure
that the threads print the numbers alternatively.
Requirements:
==============
Create a NumberPrinter class with methods printOdd() and printEven() to handle the
printing of odd and even numbers.
The NumberPrinter class should have a limit on the maximum number to print.
Use synchronization mechanisms such as wait() and notify() to coordinate the
printing of odd and even numbers.
Create two threads, one for printing odd numbers and the other for printing even
numbers.
Start the threads and ensure that they print numbers alternatively until the
specified limit is reached.
Program Components:
====================
NumberPrinter Class:
---------------------
Create a class named NumberPrinter.
Include fields to keep track of the current number and the maximum limit.
Implement the printOdd() and printEven() methods, which will print odd and even
numbers respectively.
Use wait() and notify() to coordinate the execution of the two threads.
Main Class (OddEvenPrinter):
=============================
In the main class, create an instance of the NumberPrinter class with a specified
limit.
Create two threads, one for printing odd numbers and the other for printing even
numbers.
Start both threads to execute concurrently.
Thread Execution:
The odd thread should print odd numbers and then wait for the even thread to notify
it.
The even thread should print even numbers and then wait for the odd thread to
notify it.
Ensure that the threads print numbers alternatively until the specified limit is
reached.
Example Output:
---------------
Odd Thread: 1
Even Thread: 2
Odd Thread: 3
Even Thread: 4
... (alternating odd and even numbers until the specified limit)
Solution:
==========
package thread;
class NumberPrinter {
private int count = 1;
private final int maxCount;
public NumberPrinter(int maxCount) {
this.maxCount = maxCount;
}
public synchronized void printOdd() {
while (count <= maxCount) {
if (count % 2 == 0) {
try {
wait(); // Wait for even thread to notify
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
} else {
System.out.println(Thread.currentThread().getName() + ": " +
count);
count++;
notify(); // Notify the even thread to resume
}
}
}
public synchronized void printEven() {
while (count <= maxCount) {
if (count % 2 != 0) {
try {
wait(); // Wait for odd thread to notify
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
} else {
System.out.println(Thread.currentThread().getName() + ": " +
count);
count++;
notify(); // Notify the odd thread to resume
}
}
}
}
public class OddEvenPrinter {
public static void main(String[] args) {
NumberPrinter numberPrinter = new NumberPrinter(10); // You can set the
maximum count as needed
Thread oddThread = new Thread(() -> {
Thread.currentThread().setName("OddThread");
numberPrinter.printOdd();
});
Thread evenThread = new Thread(() -> {
Thread.currentThread().setName("EvenThread");
numberPrinter.printEven();
});
oddThread.start();
evenThread.start();
}
}
program02:
==========
sum of digits in string
String array is given as input string may contain digits and alphabets(“3ab2d”).
extract digits from each string and find the sum(if the string is ab312sd then take
3+1+2=6 and not as 312 as digit)
Input1:{ca21,la3df,21cd,8c}
Output:2+1+3+2+1+8=17
method name:encryptedString()
Argument String
Return Type int
Example:
Input1:abc123xyz4
Output1:10
Input2:xyz45jk8l9
output2:26
==================================================================================
Set-C
Program01:
==========
Program Statement: Bank Account with Concurrent Deposits and Withdrawals
Objective:
===========
Implement a Java program that simulates a bank account with concurrent deposits and
withdrawals using threads.
Requirements:
==============
Create a BankAccount class that represents a bank account.
The BankAccount class should have methods to deposit and withdraw money.
Implement a Customer class that extends the Thread class, representing a bank
customer.
Each customer should perform a series of deposits and withdrawals concurrently on
the same bank account.
Ensure proper synchronization to avoid race conditions when depositing or
withdrawing money.
Display the balance of the bank account after each deposit and withdrawal
operation.
Program Components:
====================
BankAccount Class:
-------------------
Create a class named BankAccount to represent a bank account.
Include methods such as deposit() and withdraw() to handle money transactions.
Use synchronization mechanisms to ensure thread safety during deposits and
withdrawals.
Include a method to get the current balance of the account.
Customer Class:
---------------
Create a class named Customer that extends the Thread class.
Include fields to represent the customer's name and the BankAccount object
associated with the customer.
Implement the run() method to perform a series of deposits and withdrawals on the
bank account.
Display the customer's name, transaction type (deposit or withdrawal), and the
updated balance after each operation.
Main Class:
------------
In the main class, create an instance of the BankAccount class to represent the
bank account.
Create multiple instances of the Customer class, each associated with the bank
account.
Start all customer threads to execute concurrent transactions.
Example Output:
---------------
Customer Alice: Deposit $100. Updated Balance: $100
Customer Bob: Deposit $50. Updated Balance: $150
Customer Alice: Withdraw $30. Updated Balance: $120
Customer Bob: Withdraw $20. Updated Balance: $100
... (concurrent deposits and withdrawals by multiple customers)
Program02:
===========
A company transmits its String data over the network as encrypted data. The
encryption logic is as shown given below.
For a String ad the logic is as given
a=a+9=j
d=d+9=m
Method Description:
--------------------
method name:encryptedString()
Argument String
Return Type String
Example:
Input1:abc
Output1:jkl
Input2:xyz
output2:ghi
Solution:
=========
package batch25;
import java.util.Scanner;
public class StringEncryption {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
System.out.println("Enter a String:");
String str=s.nextLine();
String s1="";
for(int i=0;i<str.length();i++)
{
if(str.charAt(i)>='A'&&str.charAt(i)<='Q'||
str.charAt(i)>='a'&&str.charAt(i)<='q')
{
s1+=(char)(str.charAt(i)+9);
}
else
{
s1+=(char)((str.charAt(i))+9-26);
}
}
System.out.println(s1);