1. Write a Java program to implement a binary search algorithm.
public class BinarySearch {
public static int binarySearch(int[] array, int target)
{
int left = 0;
int right = array.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (array[mid] == target) {
return mid;
}
if (array[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
}
2. Explain the concept of a deadlock in Java and provide an example of a deadlock situation.
A deadlock occurs when two or more threads are stuck waiting for each other to release resources, and as a result, none of them can make progress. Here’s an example:
A deadlock occurs when two or more threads are stuck waiting for each other to release resources, and as a result, none of them can make progress. Here’s an example:
public class DeadlockExample {
private static final Object lock1 = new Object();
private static final Object lock2 = new Object();
public static void main(String[] args) {
Thread t1 = new Thread(() -> {
synchronized (lock1) {
System.out.println
("Thread 1: Holding lock 1...");
try { Thread.sleep(100); }
catch (InterruptedException e) {}
System.out.println
("Thread 1: Waiting for lock 2...");
synchronized (lock2) {
System.out.println
("Thread 1: Acquired lock 2.");
}
}
});
Thread t2 = new Thread(() -> {
synchronized (lock2) {
System.out.println
("Thread 2: Holding lock 2...");
try { Thread.sleep(100); }
catch (InterruptedException e) {}
System.out.println
("Thread 2: Waiting for lock 1...");
synchronized (lock1) {
System.out.println
("Thread 2: Acquired lock 1.");
}
}
});
t1.start();
t2.start();
}
}
In this example, Thread 1 holds lock1 and waits for lock2, while Thread 2 holds lock2 and waits for lock1, causing a deadlock.
3. Write a program to demonstrate the use of Java’s synchronized keyword for thread synchronization.
public class SynchronizationExample {
private int count = 0;
public synchronized void increment() {
count++;
}
public static void main(String[] args) {
SynchronizationExample example =
new SynchronizationExample();
for (int i = 0; i < 1000; i++) {
example.increment();
}
System.out.println("Count: " + example.count);
}
}
In this program, the synchronized keyword is used to ensure that the increment method is accessed by only one thread at a time, preventing data races.
4. Write a program to demonstrate the usage of Java’s ThreadPoolExecutor for managing a pool of worker threads.
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadPoolExample {
public static void main(String[] args) {
ExecutorService executor =
Executors.newFixedThreadPool(5);
for (int i = 0; i < 10; i++) {
Runnable worker =
new WorkerThread("Task-" + i);
executor.execute(worker);
}
executor.shutdown();
}
}
class WorkerThread implements Runnable {
private String taskName;
public WorkerThread(String taskName) {
this.taskName = taskName;
}
@Override
public void run() {
System.out.println
("Task: "
+ taskName + " is being processed by thread: "
+ Thread.currentThread().getName());
}
}
This program demonstrates how to create a thread pool and execute multiple tasks concurrently using ‘ThreadPoolExecutor’
5. Write a Java program to create and use a custom exception class.
class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
public class CustomExceptionExample {
public static void main(String[] args) {
try {
throw new CustomException
("This is a custom exception.");
} catch (CustomException e) {
System.out.println
("Caught an exception: " + e.getMessage());
}
}
}
This program defines a custom exception class CustomException and demonstrates how to throw and catch instances of this custom exception.
6. Write a program to find the factorial of a number in Java.
public class Factorial {
public static long calculateFactorial(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * calculateFactorial(n - 1);
}
}
public static void main(String[] args) {
int number = 5;
long factorial = calculateFactorial(number);
System.out.println
("Factorial of "
+ number + " is: " + factorial);
}
}
7. Write a Java program to check if a given string is a palindrome.
public class Palindrome {
public static boolean isPalindrome(String str) {
str = str.replaceAll
("[^a-zA-Z0-9]", "").toLowerCase();
int left = 0;
int right = str.length() - 1;
while (left < right) {
if (str.charAt(left) != str.charAt(right)) {
return false;
}
left++;
right--;
}
return true;
}
public static void main(String[] args) {
String input =
"A man, a plan, a canal, Panama";
boolean result = isPalindrome(input);
System.out.println
("Is the input a palindrome? " + result);
}
}
8. Write a program to implement a custom exception in Java.
class MyCustomException extends Exception {
public MyCustomException(String message) {
super(message);
}
}
public class CustomExceptionDemo {
public static void main(String[] args) {
try {
int age = 17;
if (age < 18) {
throw new MyCustomException
("You must be 18 or older to vote.");
}
} catch (MyCustomException e) {
System.out.println
("Exception: " + e.getMessage());
}
}
}
9. Write a Java program to implement a binary search algorithm.
public class BinarySearch {
public static int binarySearch
(int[] arr, int target) {
int left = 0;
int right = arr.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target) {
return mid;
}
if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1; // Not found
}
public static void main(String[] args) {
int[] array =
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int target = 6;
int result = binarySearch(array, target);
if (result != -1) {
System.out.println
("Element found at index " + result);
} else {
System.out.println
("Element not found in the array.");
}
}
}
10.Write a program to generate Fibonacci series in Java.
public class Fibonacci {
public static void generateFibonacci(int n) {
int a = 0, b = 1;
for (int i = 0; i < n; i++) {
System.out.print(a + " ");
int next = a + b;
a = b;
b = next;
}
}
public static void main(String[] args) {
int n = 10;
// Number of Fibonacci numbers to generate
generateFibonacci(n);
}
}