1.
factorial number:
public class Factorial1 {
public static void main(String[] args) {
int num = 10;
long factorial = 1;
for(int i = 1; i <= num; ++i)
{
// factorial = factorial * i;
factorial *= i;
}
[Link]("Factorial of %d = %d", num, factorial);
}
}
2. fibonacci number.
class fibonacci {
public static void main(String[] args) {
int n = 10, firstTerm = 0, secondTerm = 1;
[Link]("Fibonacci Series till " + n + " terms:");
for (int i = 1; i <= n; ++i) {
[Link](firstTerm + ", ");
// compute the next term
int nextTerm = firstTerm + secondTerm;
firstTerm = secondTerm;
secondTerm = nextTerm;
}
}
}
[Link] of two numbers.
class gcd {
public static void main(String[] args) {
// find GCD between n1 and n2
int n1 = 81, n2 = 153;
// initially set to gcd
int gcd = 1;
for (int i = 1; i <= n1 && i <= n2; ++i) {
// check if i perfectly divides both n1 and n2
if (n1 % i == 0 && n2 % i == 0)
gcd = i;
}
[Link]("GCD of " + n1 +" and " + n2 + " is " + gcd);
}
}
[Link] bubble sort
class BubbleSort {
void bubbleSort(int arr[])
{
int n = [Link];
for (int i = 0; i < n - 1; i++)
for (int j = 0; j < n - i - 1; j++)
if (arr[j] > arr[j + 1]) {
// swap temp and arr[i]
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
// Driver method to test above
public static void main(String args[])
{
BubbleSort ob = new BubbleSort();
int a[] = { 64, 34, 25, 12 };
[Link](a);
int n = [Link];
for (int i = 0; i < n; ++i)
[Link](a[i] + " ");
[Link]();
}
}
[Link] in string .
class palindrome{
public static void main(String args[]){
String s = "ARORA";
String rev = "";
for(int i=[Link]()-1;i>=0;i--){
rev = rev+[Link](i);
}
if([Link]().equals([Link]())){
[Link](s + " is a palindrome");
}
else{
[Link](s + "is not a palindrome");
}
}
}
[Link] search
class BinarySearch {
// Binary Search Function (Iterative)
public static int binarySearch(int[] arr, int target) {
int left = 0, right = [Link] - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
// Check if target is at mid
if (arr[mid] == target)
return mid;
// If target is greater, ignore left half
if (arr[mid] < target)
left = mid + 1;
else // If target is smaller, ignore right half
right = mid - 1;
}
return -1; // Element not found
}
public static void main(String[] args) {
int[] sortedArray = {10, 20, 30, 40, 50, 60, 70};
int target = 40;
int result = binarySearch(sortedArray, target);
if (result != -1)
[Link]("Element found at index: " + result);
else
[Link]("Element not found.");
}
}
[Link] a program to detect a cycle in a graph
import [Link];
import [Link];
public class SimpleCycleDetection {
static class Graph {
int vertices;
List<List<Integer>> adjList;
// Constructor
public Graph(int vertices) {
[Link] = vertices;
adjList = new ArrayList<>();
for (int i = 0; i < vertices; i++) {
[Link](new ArrayList<>());
}
}
// Add edge to the graph
public void addEdge(int source, int destination) {
[Link](source).add(destination);
}
// Detect cycle
public boolean hasCycle() {
boolean[] visited = new boolean[vertices];
boolean[] recStack = new boolean[vertices];
for (int i = 0; i < vertices; i++) {
if (dfs(i, visited, recStack)) {
return true;
}
}
return false;
}
// DFS helper
private boolean dfs(int node, boolean[] visited, boolean[] recStack) {
if (recStack[node]) return true;
if (visited[node]) return false;
visited[node] = true;
recStack[node] = true;
for (int neighbor : [Link](node)) {
if (dfs(neighbor, visited, recStack)) {
return true;
}
}
recStack[node] = false;
return false;
}
}
public static void main(String[] args) {
Graph graph = new Graph(3);
[Link](0, 1);
[Link](1, 2);
[Link](2, 0);
if ([Link]()) {
[Link]("Cycle detected.");
} else {
[Link]("No cycle detected.");
}
}
}
[Link] a program to perform depth-first search (DFS).
import [Link];
import [Link];
public class DepthFirstSearch {
static class Graph {
private int vertices; // Number of vertices
private List<List<Integer>> adjList; // Adjacency list
// Constructor
public Graph(int vertices) {
[Link] = vertices;
adjList = new ArrayList<>();
for (int i = 0; i < vertices; i++) {
[Link](new ArrayList<>());
}
}
// Add an edge to the graph
public void addEdge(int source, int destination) {
[Link](source).add(destination);
}
// Perform DFS
public void dfs(int start) {
boolean[] visited = new boolean[vertices];
[Link]("Depth-First Search starting from vertex " + start +
":");
dfsUtil(start, visited);
}
// Recursive DFS utility function
private void dfsUtil(int vertex, boolean[] visited) {
visited[vertex] = true;
[Link](vertex + " ");
for (int neighbor : [Link](vertex)) {
if (!visited[neighbor]) {
dfsUtil(neighbor, visited);
}
}
}
}
public static void main(String[] args) {
Graph graph = new Graph(6);
// Add edges to the graph
[Link](0, 1);
[Link](0, 2);
[Link](1, 3);
[Link](1, 4);
[Link](2, 5);
// Perform DFS starting from vertex 0
[Link](0);
}
}
[Link] a binary tree in Java.
// Binary Tree Implementation in Java
class BinaryTree {
// Node class representing a single node in the tree
static class Node {
int value;
Node left;
Node right;
Node(int value) {
[Link] = value;
left = null;
right = null;
}
}
// Root of the binary tree
Node root;
// Constructor
public BinaryTree() {
root = null;
}
// Insert a new value into the binary tree
public void insert(int value) {
root = insertRec(root, value);
}
// Recursive helper function for insertion
private Node insertRec(Node root, int value) {
if (root == null) {
root = new Node(value);
return root;
}
if (value < [Link]) {
[Link] = insertRec([Link], value);
} else if (value > [Link]) {
[Link] = insertRec([Link], value);
}
return root;
}
// Inorder traversal of the tree
public void inorder() {
inorderRec(root);
}
// Recursive helper function for inorder traversal
private void inorderRec(Node root) {
if (root != null) {
inorderRec([Link]);
[Link]([Link] + " ");
inorderRec([Link]);
}
}
public static void main(String[] args) {
BinaryTree tree = new BinaryTree();
// Insert nodes
[Link](50);
[Link](30);
[Link](70);
[Link](20);
[Link](40);
[Link](60);
[Link](80);
// Print inorder traversal
[Link]("Inorder traversal of the binary tree:");
[Link]();
}
}
[Link] a queue using two stacks
import [Link];
public class QueueStacks {
static class Queue {
Stack<Integer> stack1; // Primary stack
Stack<Integer> stack2; // Auxiliary stack
// Constructor
public Queue() {
stack1 = new Stack<>();
stack2 = new Stack<>();
}
// Enqueue operation
public void enqueue(int value) {
[Link](value);
}
// Dequeue operation
public int dequeue() {
if ([Link]()) {
if ([Link]()) {
throw new RuntimeException("Queue is empty");
}
// Transfer all elements from stack1 to stack2
while (![Link]()) {
[Link]([Link]());
}
}
return [Link]();
}
// Check if the queue is empty
public boolean isEmpty() {
return [Link]() && [Link]();
}
// Peek the front element
public int peek() {
if ([Link]()) {
if ([Link]()) {
throw new RuntimeException("Queue is empty");
}
// Transfer all elements from stack1 to stack2
while (![Link]()) {
[Link]([Link]());
}
}
return [Link]();
}
}
public static void main(String[] args) {
Queue queue = new Queue();
// Enqueue elements
[Link](1);
[Link](2);
[Link](3);
// Dequeue and display elements
[Link]("Dequeued: " + [Link]()); // 1
[Link]("Peek: " + [Link]()); // 2
[Link]("Dequeued: " + [Link]()); // 2
// Enqueue more elements
[Link](4);
[Link](5);
// Dequeue remaining elements
while (![Link]()) {
[Link]("Dequeued: " + [Link]());
}
}
}
___________________________________________________________________________________
------- multi threading---------------
11. Implement a thread-safe Singleton design pattern
class Singleton {
// Volatile keyword ensures visibility of changes to variables across threads
private static volatile Singleton instance;
// Private constructor to prevent instantiation from outside
private Singleton() {
// Prevent instantiation via reflection
if (instance != null) {
throw new IllegalStateException("Instance already created");
}
}
// Public method to provide access to the Singleton instance
public static Singleton getInstance() {
if (instance == null) { // First check (no locking)
synchronized ([Link]) {
if (instance == null) { // Second check (with locking)
instance = new Singleton();
}
}
}
return instance;
}
}
public class Singleton1 {
public static void main(String[] args) {
Singleton singleton1 = [Link]();
Singleton singleton2 = [Link]();
[Link](singleton1 == singleton2); // true
}
}
12. Write a program to implement a producer-consumer problem using semaphores.
import [Link];
import [Link];
import [Link];
public class ProducerConsumer {
// Shared buffer
private static final int BUFFER_SIZE = 5;
private static final Queue<Integer> buffer = new LinkedList<>();
// Semaphores
private static final Semaphore empty = new Semaphore(BUFFER_SIZE); // Tracks
empty slots
private static final Semaphore full = new Semaphore(0); // Tracks
filled slots
private static final Semaphore mutex = new Semaphore(1); // Mutual
exclusion
public static void main(String[] args) throws InterruptedException {
Thread producerThread = new Thread(new Producer());
Thread consumerThread = new Thread(new Consumer());
// Start threads
[Link]();
[Link]();
// Keep main thread alive
[Link]();
[Link]();
}
static class Producer implements Runnable {
@Override
public void run() {
while (true) {
produce();
}
}
private void produce() {
try {
int item = (int) ([Link]() * 100); // Produce an item
[Link](); // Wait if no empty slots
[Link](); // Enter critical section
[Link](item); // Add item to buffer
[Link]("Producer produced: " + item + ", Buffer: " +
buffer);
[Link](); // Exit critical section
[Link](); // Signal that a slot is filled
[Link]((int) ([Link]() * 1000)); // Simulate time to
produce
} catch (InterruptedException e) {
[Link]().interrupt();
}
}
}
static class Consumer implements Runnable {
@Override
public void run() {
while (true) {
consume();
}
}
private void consume() {
try {
[Link](); // Wait if buffer is empty
[Link](); // Enter critical section
int item = [Link](); // Remove item from buffer
[Link]("Consumer consumed: " + item + ", Buffer: " +
buffer);
[Link](); // Exit critical section
[Link](); // Signal that a slot is empty
[Link]((int) ([Link]() * 1000)); // Simulate time to
consume
} catch (InterruptedException e) {
[Link]().interrupt();
}
}
}
}
13. Implement the Readers-Writers problem
import [Link];
public class ReadersWriters {
// Semaphores
private static final Semaphore mutex = new Semaphore(1); // For reader count
access
private static final Semaphore rwMutex = new Semaphore(1); // For resource
access
private static int readerCount = 0; // Tracks the number of readers
public static void main(String[] args) {
// Create multiple readers and writers
Thread reader1 = new Thread(new Reader(), "Reader 1");
Thread reader2 = new Thread(new Reader(), "Reader 2");
Thread writer1 = new Thread(new Writer(), "Writer 1");
Thread writer2 = new Thread(new Writer(), "Writer 2");
// Start threads
[Link]();
[Link]();
[Link]();
[Link]();
}
static class Reader implements Runnable {
@Override
public void run() {
while (true) {
try {
// Entering critical section to update readerCount
[Link]();
readerCount++;
if (readerCount == 1) {
[Link](); // First reader locks the resource
}
[Link]();
// Reading (non-critical section)
[Link]([Link]().getName() + " is
reading...");
[Link]((int) ([Link]() * 1000)); // Simulate reading
time
// Leaving critical section
[Link]();
readerCount--;
if (readerCount == 0) {
[Link](); // Last reader unlocks the resource
}
[Link]();
// Simulate delay between reads
[Link]((int) ([Link]() * 1000));
} catch (InterruptedException e) {
[Link]().interrupt();
}
}
}
}
static class Writer implements Runnable {
@Override
public void run() {
while (true) {
try {
[Link](); // Lock resource for writing
// Writing (critical section)
[Link]([Link]().getName() + " is
writing...");
[Link]((int) ([Link]() * 1000)); // Simulate writing
time
[Link](); // Unlock resource
// Simulate delay between writes
[Link]((int) ([Link]() * 1000));
} catch (InterruptedException e) {
[Link]().interrupt();
}
}
}
}
}
14. Design a thread-safe bounded blocking queue
import [Link];
import [Link];
import [Link];
public class BoundedBlockingQueue<T> {
private final Queue<T> queue;
private final int capacity;
private final Semaphore enqueueSemaphore; // Tracks available space
private final Semaphore dequeueSemaphore; // Tracks available items
private final Semaphore mutex; // Mutual exclusion for queue
operations
public BoundedBlockingQueue(int capacity) {
[Link] = capacity;
[Link] = new LinkedList<>();
[Link] = new Semaphore(capacity); // Initially, the queue
has all slots available
[Link] = new Semaphore(0); // Initially, no items in
the queue
[Link] = new Semaphore(1); // Ensures thread-safe
operations
}
public void enqueue(T item) throws InterruptedException {
[Link](); // Wait if the queue is full
[Link](); // Enter critical section
try {
[Link](item);
[Link]("Enqueued: " + item);
} finally {
[Link](); // Exit critical section
}
[Link](); // Signal that an item is available
}
public T dequeue() throws InterruptedException {
[Link](); // Wait if the queue is empty
[Link](); // Enter critical section
try {
T item = [Link]();
[Link]("Dequeued: " + item);
return item;
} finally {
[Link](); // Exit critical section
}
[Link](); // Signal that space is available
}
public int size() {
[Link]();
try {
return [Link]();
} finally {
[Link]();
}
}
public static void main(String[] args) {
BoundedBlockingQueue<Integer> queue = new BoundedBlockingQueue<>(5);
// Producer thread
Thread producer = new Thread(() -> {
try {
for (int i = 1; i <= 10; i++) {
[Link](i);
[Link]((int) ([Link]() * 500)); // Simulate work
}
} catch (InterruptedException e) {
[Link]().interrupt();
}
});
// Consumer thread
Thread consumer = new Thread(() -> {
try {
for (int i = 1; i <= 10; i++) {
[Link]();
[Link]((int) ([Link]() * 500)); // Simulate work
}
} catch (InterruptedException e) {
[Link]().interrupt();
}
});
[Link]();
[Link]();
}
}
15. Write a program to solve the dining philosophers problem
import [Link];
public class DiningPhilosophers {
// Number of philosophers
private static final int NUM_PHILOSOPHERS = 5;
// Array of semaphores, one for each fork
private static final Semaphore[] forks = new Semaphore[NUM_PHILOSOPHERS];
// Semaphore to limit the number of philosophers trying to eat (prevent
deadlock)
private static final Semaphore table = new Semaphore(NUM_PHILOSOPHERS - 1);
public static void main(String[] args) {
// Initialize fork semaphores
for (int i = 0; i < NUM_PHILOSOPHERS; i++) {
forks[i] = new Semaphore(1);
}
// Create and start philosopher threads
for (int i = 0; i < NUM_PHILOSOPHERS; i++) {
new Thread(new Philosopher(i)).start();
}
}
static class Philosopher implements Runnable {
private final int id;
private final int leftFork;
private final int rightFork;
public Philosopher(int id) {
[Link] = id;
[Link] = id;
[Link] = (id + 1) % NUM_PHILOSOPHERS;
}
@Override
public void run() {
try {
while (true) {
think();
pickUpForks();
eat();
putDownForks();
}
} catch (InterruptedException e) {
[Link]().interrupt();
}
}
private void think() throws InterruptedException {
[Link]("Philosopher " + id + " is thinking...");
[Link]((int) ([Link]() * 1000)); // Simulate thinking time
}
private void pickUpForks() throws InterruptedException {
[Link](); // Limit the number of philosophers trying to eat
forks[leftFork].acquire(); // Pick up the left fork
[Link]("Philosopher " + id + " picked up left fork " +
leftFork);
forks[rightFork].acquire(); // Pick up the right fork
[Link]("Philosopher " + id + " picked up right fork " +
rightFork);
}
private void eat() throws InterruptedException {
[Link]("Philosopher " + id + " is eating...");
[Link]((int) ([Link]() * 1000)); // Simulate eating time
}
private void putDownForks() {
forks[leftFork].release(); // Put down the left fork
[Link]("Philosopher " + id + " put down left fork " +
leftFork);
forks[rightFork].release(); // Put down the right fork
[Link]("Philosopher " + id + " put down right fork " +
rightFork);
[Link](); // Allow another philosopher to try eating
}
}
}
16. Implement a cyclic barrier.
import [Link];
import [Link];
import [Link];
public class CyclicBarrier {
private final int parties; // Total number of threads to wait for
private int count; // Tracks the current number of waiting threads
private final Runnable barrierAction; // Optional action to execute when
barrier is tripped
private final Lock lock = new ReentrantLock();
private final Condition condition = [Link]();
public CyclicBarrier(int parties, Runnable barrierAction) {
if (parties <= 0) {
throw new IllegalArgumentException("Number of parties must be greater
than 0");
}
[Link] = parties;
[Link] = parties;
[Link] = barrierAction;
}
public CyclicBarrier(int parties) {
this(parties, null);
}
public void await() throws InterruptedException {
[Link]();
try {
count--;
if (count == 0) {
// All threads have reached the barrier
if (barrierAction != null) {
[Link](); // Execute the optional barrier action
}
// Reset the barrier for reuse
count = parties;
[Link](); // Wake up all waiting threads
} else {
// Wait for other threads to reach the barrier
while (count > 0) {
[Link]();
}
}
} finally {
[Link]();
}
}
}
//example of cyclic barrier
public class CyclicBarrierExample {
public static void main(String[] args) {
final int NUM_THREADS = 3;
// CyclicBarrier with an action to execute when the barrier is tripped
CyclicBarrier barrier = new CyclicBarrier(NUM_THREADS,
() -> [Link]("All threads reached the barrier. Barrier
tripped!"));
Runnable task = () -> {
try {
[Link]([Link]().getName() + " is
performing work...");
[Link]((int) ([Link]() * 1000)); // Simulate work
[Link]([Link]().getName() + " is waiting
at the barrier...");
[Link]();
[Link]([Link]().getName() + " has crossed
the barrier.");
} catch (InterruptedException e) {
[Link]().interrupt();
}
};
// Create and start threads
for (int i = 0; i < NUM_THREADS; i++) {
new Thread(task).start();
}
}
}
17. Write a program to implement a custom thread pool.
import [Link];
import [Link];
public class CustomThreadPool {
private final int poolSize;
private final WorkerThread[] workers;
private final BlockingQueue<Runnable> taskQueue;
private volatile boolean isShutdown = false;
public CustomThreadPool(int poolSize) {
[Link] = poolSize;
[Link] = new LinkedBlockingQueue<>();
[Link] = new WorkerThread[poolSize];
// Initialize and start worker threads
for (int i = 0; i < poolSize; i++) {
workers[i] = new WorkerThread();
workers[i].start();
}
}
public void submit(Runnable task) {
if (isShutdown) {
throw new IllegalStateException("Thread pool is shutting down, cannot
accept new tasks.");
}
[Link](task); // Add task to the queue
}
public void shutdown() {
isShutdown = true; // Mark the thread pool for shutdown
for (WorkerThread worker : workers) {
[Link](); // Interrupt each worker thread
}
}
private class WorkerThread extends Thread {
@Override
public void run() {
while (!isShutdown || ![Link]()) {
try {
Runnable task = [Link](); // Take task from the queue
[Link](); // Execute the task
} catch (InterruptedException e) {
// Allow thread to exit if interrupted during shutdown
if (isShutdown) {
break;
}
}
}
}
}
public static void main(String[] args) {
CustomThreadPool threadPool = new CustomThreadPool(3); // Create a pool of
3 threads
// Submit tasks to the thread pool
for (int i = 1; i <= 10; i++) {
final int taskId = i;
[Link](() -> {
[Link]("Task " + taskId + " is being executed by " +
[Link]().getName());
try {
[Link](500); // Simulate task execution time
} catch (InterruptedException e) {
[Link]().interrupt();
}
});
}
[Link](); // Shut down the thread pool
}
}
18. Implement a parallel merge sort algorithm
import [Link];
import [Link];
public class ParallelMergeSort {
public static void parallelMergeSort(int[] array) {
if (array == null || [Link] <= 1) {
return; // Already sorted or empty
}
ForkJoinPool pool = new ForkJoinPool(); // Create ForkJoinPool
[Link](new MergeSortTask(array, 0, [Link] - 1));
}
private static class MergeSortTask extends RecursiveAction {
private final int[] array;
private final int left;
private final int right;
public MergeSortTask(int[] array, int left, int right) {
[Link] = array;
[Link] = left;
[Link] = right;
}
@Override
protected void compute() {
if (left < right) {
int mid = left + (right - left) / 2;
// Split the task into two subtasks
MergeSortTask leftTask = new MergeSortTask(array, left, mid);
MergeSortTask rightTask = new MergeSortTask(array, mid + 1, right);
// Invoke the subtasks in parallel
invokeAll(leftTask, rightTask);
// Merge the results
merge(array, left, mid, right);
}
}
private void merge(int[] array, int left, int mid, int right) {
int n1 = mid - left + 1;
int n2 = right - mid;
// Create temporary arrays
int[] leftArray = new int[n1];
int[] rightArray = new int[n2];
// Copy data into temporary arrays
[Link](array, left, leftArray, 0, n1);
[Link](array, mid + 1, rightArray, 0, n2);
int i = 0, j = 0, k = left;
// Merge the temporary arrays
while (i < n1 && j < n2) {
if (leftArray[i] <= rightArray[j]) {
array[k++] = leftArray[i++];
} else {
array[k++] = rightArray[j++];
}
}
// Copy any remaining elements from leftArray
while (i < n1) {
array[k++] = leftArray[i++];
}
// Copy any remaining elements from rightArray
while (j < n2) {
array[k++] = rightArray[j++];
}
}
}
public static void main(String[] args) {
int[] array = {38, 27, 43, 3, 9, 82, 10};
[Link]("Original array:");
printArray(array);
parallelMergeSort(array);
[Link]("\nSorted array:");
printArray(array);
}
private static void printArray(int[] array) {
for (int num : array) {
[Link](num + " ");
}
[Link]();
}
}
//Input: {38, 27, 43, 3, 9, 82, 10}
//Output: {3, 9, 10, 27, 38, 43, 82}
19. Write a program to simulate a bank transaction system with multiple threads.
class BankAccount {
private int balance;
public BankAccount(int initialBalance) {
[Link] = initialBalance;
}
// Synchronized deposit method
public synchronized void deposit(int amount) {
balance += amount;
[Link]([Link]().getName() + " deposited $" +
amount + ". Current balance: $" + balance);
notifyAll(); // Notify waiting threads
}
// Synchronized withdraw method
public synchronized void withdraw(int amount) {
while (balance < amount) {
[Link]([Link]().getName() + " wants to
withdraw $" + amount + " but only $" + balance + " is available. Waiting...");
try {
wait(); // Wait until there is enough balance
} catch (InterruptedException e) {
[Link]().interrupt();
}
}
balance -= amount;
[Link]([Link]().getName() + " withdrew $" +
amount + ". Current balance: $" + balance);
}
public synchronized int getBalance() {
return balance;
}
}
public class BankTransactionSystem {
public static void main(String[] args) {
BankAccount account = new BankAccount(100); // Initial balance is $100
// Runnable for deposit transactions
Runnable depositTask = () -> {
for (int i = 0; i < 5; i++) {
[Link]((int) ([Link]() * 100) + 1); // Deposit a
random amount
try {
[Link](500); // Simulate processing time
} catch (InterruptedException e) {
[Link]().interrupt();
}
}
};
// Runnable for withdrawal transactions
Runnable withdrawTask = () -> {
for (int i = 0; i < 5; i++) {
[Link]((int) ([Link]() * 100) + 1); // Withdraw a
random amount
try {
[Link](700); // Simulate processing time
} catch (InterruptedException e) {
[Link]().interrupt();
}
}
};
// Create threads for deposit and withdrawal
Thread depositor1 = new Thread(depositTask, "Depositor-1");
Thread depositor2 = new Thread(depositTask, "Depositor-2");
Thread withdrawer1 = new Thread(withdrawTask, "Withdrawer-1");
Thread withdrawer2 = new Thread(withdrawTask, "Withdrawer-2");
// Start all threads
[Link]();
[Link]();
[Link]();
[Link]();
// Wait for all threads to finish
try {
[Link]();
[Link]();
[Link]();
[Link]();
} catch (InterruptedException e) {
[Link]().interrupt();
}
// Final balance
[Link]("Final balance: $" + [Link]());
}
}
20. Design a concurrent cache using ConcurrentHashMap.
import [Link].*;
public class ConcurrentCache<K, V> {
private final ConcurrentHashMap<K, V> cache;
private final int cacheSize;
// Constructor for cache with a specified maximum size
public ConcurrentCache(int cacheSize) {
[Link] = cacheSize;
[Link] = new ConcurrentHashMap<>();
}
// Add or update an item in the cache
public void put(K key, V value) {
if ([Link]() >= cacheSize) {
evictCache(); // Evict an item if cache exceeds size
}
[Link](key, value);
}
// Get an item from the cache
public V get(K key) {
return [Link](key);
}
// Remove an item from the cache
public void remove(K key) {
[Link](key);
}
// Evict an item from the cache (simple approach: remove first item)
private void evictCache() {
// For simplicity, we just remove one entry. A better strategy could be an
LRU (Least Recently Used) eviction policy.
for (K key : [Link]()) {
[Link](key);
break; // Evict only one element for this simple example
}
}
// Print the cache (just for demonstration)
public void printCache() {
[Link](cache);
}
// Test the cache with concurrent threads
public static void main(String[] args) {
ConcurrentCache<Integer, String> cache = new ConcurrentCache<>(5);
// Runnable to simulate cache operations
Runnable cacheTask = () -> {
for (int i = 0; i < 10; i++) {
int key = (int) ([Link]() * 10); // Random key
String value = "Value-" + key;
[Link](key, value); // Put new value in cache
[Link]([Link]().getName() + " put " + key
+ ": " + value);
// Randomly get value
String retrievedValue = [Link](key);
[Link]([Link]().getName() + " got " + key
+ ": " + retrievedValue);
}
};
// Create multiple threads to access the cache concurrently
Thread thread1 = new Thread(cacheTask, "Thread-1");
Thread thread2 = new Thread(cacheTask, "Thread-2");
Thread thread3 = new Thread(cacheTask, "Thread-3");
[Link]();
[Link]();
[Link]();
// Wait for threads to finish
try {
[Link]();
[Link]();
[Link]();
} catch (InterruptedException e) {
[Link]().interrupt();
}
// Final cache state
[Link]("Final Cache State:");
[Link]();
}
}
_________________________________________________________________________________
--------------data structure and algorithms------------
1. Implement a Trie data structure with insert, search, and delete operations.
class Trie {
// TrieNode definition
static class TrieNode {
TrieNode[] children = new TrieNode[26]; // Array for 26 lowercase letters
boolean isEndOfWord = false; // Flag to mark the end of a word
}
private final TrieNode root;
// Constructor to initialize the Trie
public Trie() {
root = new TrieNode();
}
// Insert a word into the Trie
public void insert(String word) {
TrieNode node = root;
for (char ch : [Link]()) {
int index = ch - 'a'; // Find index of the character
if ([Link][index] == null) {
[Link][index] = new TrieNode(); // Create a new TrieNode if
not already present
}
node = [Link][index];
}
[Link] = true; // Mark the end of the word
}
// Search for a word in the Trie
public boolean search(String word) {
TrieNode node = root;
for (char ch : [Link]()) {
int index = ch - 'a';
if ([Link][index] == null) {
return false; // Word not found
}
node = [Link][index];
}
return [Link]; // Check if the word ends correctly
}
// Delete a word from the Trie
public boolean delete(String word) {
return delete(root, word, 0);
}
private boolean delete(TrieNode node, String word, int depth) {
if (node == null) {
return false; // Word not found
}
if (depth == [Link]()) {
if (![Link]) {
return false; // Word not found
}
[Link] = false; // Unmark the end of the word
return isEmpty(node); // Check if node has no children
}
int index = [Link](depth) - 'a';
if (delete([Link][index], word, depth + 1)) {
[Link][index] = null; // Remove the child reference
return ![Link] && isEmpty(node); // Check if the current node
can be deleted
}
return false;
}
// Helper method to check if a node has any children
private boolean isEmpty(TrieNode node) {
for (TrieNode child : [Link]) {
if (child != null) {
return false; // Node has children
}
}
return true; // Node has no children
}
// Main method for testing
public static void main(String[] args) {
Trie trie = new Trie();
// Insert words
[Link]("hello");
[Link]("world");
[Link]("help");
[Link]("heap");
// Search for words
[Link]([Link]("hello")); // true
[Link]([Link]("hell")); // false
[Link]([Link]("heap")); // true
// Delete words
[Link]([Link]("heap")); // true
[Link]([Link]("heap")); // false
[Link]([Link]("help")); // true
}
}
------------------------------------------------------------------------------
------ string manipulation -----------
31. Write a program to find all permutations of a string.
public class StringPermutations {
// Method to generate permutations
public static void generatePermutations(String str, int left, int right) {
if (left == right) {
[Link](str);
} else {
for (int i = left; i <= right; i++) {
str = swap(str, left, i); // Swap characters
generatePermutations(str, left + 1, right); // Recursive call
str = swap(str, left, i); // Backtrack
}
}
}
// Utility method to swap characters in a string
private static String swap(String str, int i, int j) {
char[] charArray = [Link]();
char temp = charArray[i];
charArray[i] = charArray[j];
charArray[j] = temp;
return [Link](charArray);
}
public static void main(String[] args) {
String input = "ABC";
[Link]("All permutations of the string: " + input);
generatePermutations(input, 0, [Link]() - 1);
}
}
32. Implement a program to find the longest palindromic substring.
public class LongestPalindromicSubstring {
// Method to expand around center and find longest palindrome
private static String expandAroundCenter(String s, int left, int right) {
while (left >= 0 && right < [Link]() && [Link](left) ==
[Link](right)) {
left--;
right++;
}
return [Link](left + 1, right); // Extract palindromic substring
}
// Main method to find the longest palindromic substring
public static String findLongestPalindrome(String s) {
if (s == null || [Link]() < 1) return "";
String longestPalindrome = "";
for (int i = 0; i < [Link](); i++) {
// Check for odd-length palindrome (single center)
String oddPalindrome = expandAroundCenter(s, i, i);
// Check for even-length palindrome (two-character center)
String evenPalindrome = expandAroundCenter(s, i, i + 1);
// Update the longest palindrome found
if ([Link]() > [Link]()) {
longestPalindrome = oddPalindrome;
}
if ([Link]() > [Link]()) {
longestPalindrome = evenPalindrome;
}
}
return longestPalindrome;
}
public static void main(String[] args) {
String input = "babad";
[Link]("Longest Palindromic Substring: " +
findLongestPalindrome(input));
}
}
33. Write a program to perform wildcard pattern matching.
public class WildcardMatching {
// Function to check if text matches pattern
public static boolean isMatch(String text, String pattern) {
int m = [Link]();
int n = [Link]();
boolean[][] dp = new boolean[m + 1][n + 1];
// Base case: Empty pattern and empty text match
dp[0][0] = true;
// Handle patterns with '*' at the start (can match empty text)
for (int i = 1; i <= m; i++) {
if ([Link](i - 1) == '*') {
dp[i][0] = dp[i - 1][0]; // '*' can represent empty sequence
}
}
// Fill DP table
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if ([Link](i - 1) == [Link](j - 1) || [Link](i
- 1) == '?') {
dp[i][j] = dp[i - 1][j - 1]; // Match character or '?'
} else if ([Link](i - 1) == '*') {
dp[i][j] = dp[i - 1][j] || dp[i][j - 1]; // '*' matches empty
or any char
}
}
}
return dp[m][n];
}
public static void main(String[] args) {
String text = "abcd";
String pattern = "a*d";
[Link]("Pattern matches string: " + isMatch(text, pattern)); //
Output: true
}
}
________________________________________________________________________
file handling
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class file{
public static void main(String args[]){
File newFile = new File("[Link]");
[Link]("file created...");
try(FileWriter myWrite = new FileWriter(newFile)){
[Link]("hello file\n");
[Link]("adding extra information...");
[Link]("file have some content");
}
catch(IOException e){
[Link]("error occured");
[Link]();
}
try(FileReader myRead = new FileReader(newFile);
BufferedReader buff = new BufferedReader(myRead)){
String line;
while(line = [Link]() != null);
[Link]("read the data" +line);
}
catch(IOException e){
[Link]("error occured");
[Link]();
}
}
}
111. reader writer in mutlithreading .
class SharedResource {
private int data = 0; // Shared variable
// Writer Method
public synchronized void write(int value) {
[Link]([Link]().getName() + " is Writing: " +
value);
data = value;
try {
[Link](1000);
} catch (InterruptedException e) {}
[Link]([Link]().getName() + " finished
Writing.");
}
// Reader Method
public synchronized void read() {
[Link]([Link]().getName() + " is Reading: " +
data);
try { [Link](500); } catch (InterruptedException e) {}
}
}
// Reader Thread using Runnable
class Reader implements Runnable {
private SharedResource resource;
public Reader(SharedResource resource) {
[Link] = resource;
}
public void run() {
for (int i = 0; i < 3; i++) {
[Link]();
}
}
}
// Writer Thread using Runnable
class Writer implements Runnable {
private SharedResource resource;
public Writer(SharedResource resource) {
[Link] = resource;
}
public void run() {
for (int i = 1; i <= 2; i++) {
[Link](i * 10);
}
}
}
// Main Class
public class ReaderWriterRunnable {
public static void main(String[] args) {
SharedResource resource = new SharedResource();
Thread reader1 = new Thread(new Reader(resource), "Reader-1");
Thread reader2 = new Thread(new Reader(resource), "Reader-2");
Thread writer = new Thread(new Writer(resource), "Writer");
[Link]();
[Link]();
[Link]();
}
}
[Link] consumer in multithread
import [Link];
import [Link];
class Producer implements Runnable {
private BlockingQueue<Integer> queue;
public Producer(BlockingQueue<Integer> queue) {
[Link] = queue;
}
@Override
public void run() {
for (int i = 1; i <= 5; i++) {
try {
[Link]("Produced: " + i);
[Link](i); // Put item in the queue
[Link](1000); // Simulate time-consuming task
} catch (InterruptedException e) {
[Link]().interrupt();
}
}
}
}
class Consumer implements Runnable {
private BlockingQueue<Integer> queue;
public Consumer(BlockingQueue<Integer> queue) {
[Link] = queue;
}
@Override
public void run() {
while (true) {
try {
Integer item = [Link](); // Take item from queue
[Link]("Consumed: " + item);
[Link](1500); // Simulate processing time
} catch (InterruptedException e) {
[Link]().interrupt();
break;
}
}
}
}
public class ProducerConsumerExample {
public static void main(String[] args) {
BlockingQueue<Integer> queue = new LinkedBlockingQueue<>(3); // Max size 3
Thread producerThread = new Thread(new Producer(queue));
Thread consumerThread = new Thread(new Consumer(queue));
[Link]();
[Link]();
}
}
-----------------------------------------
bank details
import [Link];
class BankAcc{
private String name;
private double accno;
private double balance;
public BankAcc(String name, double accno, double balance){
[Link] = name;
[Link] = accno;
[Link] = balance;
}
public void deposit(double amount){
if(amount>0){
balance = balance + amount;
[Link]("after deposit the balance is:" +balance);
}
else{
[Link]("invalid deposit:");
}
}
public void withdraw(double amount){
if(amount>0 && amount<=balance){
balance = balance - amount;
[Link]("balance after withdraw:" +balance);
}
else{
[Link]("insufient amount you eneter:");
}
}
public void display(){
[Link]("account holde name:" +name);
[Link]("account number:" +accno);
[Link]("balance is:" +balance);
}
}
public class BankDetails{
public static void main(String args[]){
Scanner sc = new Scanner([Link]);
[Link]("enter the account holder name:");
String accName = [Link]();
[Link]("enter the account number:");
double accNo = [Link]();
[Link]("enter initial balance:");
double initialBalance = [Link]();
BankAcc account = new BankAcc(accName, accNo, initialBalance);
int choice;
do{
[Link]("\n1. Deposit");
[Link]("2. Withdraw");
[Link]("3. Display Account Details");
[Link]("4. Exit");
[Link]("Enter your choice: ");
choice = [Link]();
switch(choice){
case 1:
[Link]("enter the amount of deposit:");
double depositAmount = [Link]();
[Link](depositAmount);
break;
case 2:
[Link]("enter amount you withdraw:");
double withdrawAmount = [Link]();
[Link](withdrawAmount);
break;
case 3:
[Link]();
break;
case 4:
[Link]("exit.. Thank u");
break;
default:
[Link](" invalid choice");
}
}
while(choice != 4);
[Link]();
}
}