[Go to site: main page, start]

0% found this document useful (0 votes)
9 views28 pages

Java Programs for Common Tasks

The document contains multiple Java programming tasks, including checking for diagonal matrices, determining leap years, creating classes with inheritance, implementing interfaces, managing stacks with exceptions, searching strings in files, and demonstrating thread life cycles and synchronization. Each task is accompanied by a complete Java program that illustrates the required functionality. Additionally, it covers concepts such as thread groups and adapter classes with relevant examples.
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)
9 views28 pages

Java Programs for Common Tasks

The document contains multiple Java programming tasks, including checking for diagonal matrices, determining leap years, creating classes with inheritance, implementing interfaces, managing stacks with exceptions, searching strings in files, and demonstrating thread life cycles and synchronization. Each task is accompanied by a complete Java program that illustrates the required functionality. Additionally, it covers concepts such as thread groups and adapter classes with relevant examples.
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

1.

Develop a java program to check whether the given 2D array has non zero elements in the
diagonal position and zeros in the non-diagonal positions.

Program:
import [Link];
public class DiagonalChecker {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter order of Matrix: ");
int order = [Link]();
int[][] matrix = new int[order][order];
[Link]("enter Matrix Elements: ");
for (int i = 0; i < order; i++) {
for (int j = 0; j <order; j++) {
[Link]("Enter Matrix["+i+"]"+"["+j+"] :");
matrix[i][j] = [Link]();
}
}
[Link]();
if (isDiagonalMatrix(matrix)) {
[Link]("The given matrix satisfies the conditions.");
} else {
[Link]("The given matrix does not satisfy the conditions.");
}
}
private static boolean isDiagonalMatrix(int[][] matrix) {
int rows = [Link];
int cols = matrix[0].length;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (i != j && matrix[i][j] != 0) {
return false;
}
}
}
for (int i = 0; i < rows; i++) {
if (matrix[i][i] == 0) {
return false;
}
}
return true;
}
}
2. Develop a java program which accepts year (Integer) as command line argument and
checks whether the given year is leap or not.
Program:
public class LeapYear {
public static void main(String[] args) {
int year = [Link](args[0]);
if(year%4==0 && year%100!=0){
[Link](year+" is a leap year");
}else{
[Link](year+" is not a leap year");
}
}
}

3. Develop a java program to implement the following (i) Create a class Person with fields’
aadharNo, name, gender and DOB. Create a parameterized constructor to accepts all the
above fields. (ii) Create a class Employee which extends the Person and has following
fields. empId, DOJ, designation and basicSal. Create a constructor which accepts all the
parameters of its super class and its own parameters. Call the base class constructor in the
derived class constructor.
Program:
import [Link];
class Person{
String name;
String gender;
long aadharNo;
String dob;
Person(String name,String gender,long aadharNo,String dob){
[Link] = name;
[Link] = gender;
[Link] = aadharNo;
[Link] = dob;
}
void personDetails(){
[Link]("Person Name: "+[Link]);
[Link]("Gender: "+[Link]);
[Link]("Aadhaar Number: "+[Link]);
[Link]("Date of Birth: "+[Link]);
}
}
class Employee extends Person {
int empid;
String designation,doj;
int basicSal;
Employee(String name,String gender,long aadharNo,String dob,int empId,String doj,String
designation,int basicSal){
super(name,gender,aadharNo,dob);
[Link] = empId;
[Link] = doj;
[Link] = designation;
[Link] = basicSal;
}
void displayEmployee(){
[Link]();
[Link]("Employee id: "+[Link]);
[Link]("Date of Join: "+[Link]);
[Link]("Employee designation: "+[Link]);
[Link]("Employee Basic Salary: "+[Link]);
}
}

public class Example{


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter Name: ");
String name = [Link]();
[Link]("Enter gender: ");
String gender = [Link]();
[Link]("Enter aadhar Number: ");
long aadharNo = [Link]();
[Link]("Enter Date of birth (DD/MM/YYYY) : ");
String dob = [Link]();
[Link]();
[Link]("Enter Empid: ");
int empId = [Link]();
[Link]();
[Link]("Enter Date of Join (DD/MM/YYYY): ");
String doj = [Link]();
[Link]("Enter Designation: ");
String designation = [Link]();
[Link]("Enter Basic Salary: ");
int basicSal = [Link]();
Employee e1 = new Employee(name, gender, aadharNo, dob, empId, doj, designation,
basicSal);
[Link]();
[Link]();
}
}

4. Create an interface Shape with an abstract method draw(). Create two classes, circle and
rectangle which implements interface Shape. Draw() should print the text indicating its
shape. Create reference to shape and object of either circle or rectangle depends on user ‘s
choice and call the method draw().
Program:
import [Link];
interface Shape{
void draw();
}
class Rectangle implements Shape{
public void draw(){
[Link]("Drawing Rectangle.");
}
}
class Circle implements Shape{
public void draw(){
[Link]("Drawing Circle.");
}
}
public class InterfaceExample {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
Shape shape;
while(true){
[Link]("[Link]\[Link]\[Link]");
[Link]("Enter choice: ");
int choice = [Link]();
switch(choice){
case 1:
shape = new Circle();
[Link]();
break;
case 2:
shape = new Rectangle();
[Link]();
break;
case 3:
[Link]("Exiting Program!");
[Link](0);
default:
[Link]("Enter correct choice!");
break;
}
}
}
}

5. Create a java program to implement a stack. Create a user defined exception stackoverflow
and throw it when stack capacity exceeds.
Program:
import [Link];

class StackOverFlowException extends Exception {


StackOverFlowException() {
super("Stack Overflow!! Limit Exceeded.");
}
}

public class Stack {


private static int top = -1;
private static int[] stack;
private static int maxSize;

Stack(int mx) {
maxSize = mx;
stack = new int[maxSize];
}

public static void push(int value) {


try {
if (top == maxSize - 1) {
throw new StackOverFlowException();
} else {
top++;
stack[top] = value;
[Link]("Successfully Pushed.");
}
} catch (StackOverFlowException e) {
[Link]([Link]());
}
}

public static int pop() {


if (top == -1) {
[Link]("Stack underflow");
return -1;
}
int poppedItem = stack[top];
top--;
return poppedItem;
}

public static void display() {


if (top == -1) {
[Link]("Stack is Empty.");
} else {
[Link]("Stack Elements: ");
for (int i = top; i >= 0; i--) {
[Link](stack[i]);
}
[Link]();
}
}
public static void main(String[] args) throws StackOverFlowException {
Scanner sc = new Scanner([Link]);
[Link]("Enter Stack Max size: ");
int maxSize = [Link]();
new Stack(maxSize);
while (true) {
[Link]("\nMenu : \[Link]\[Link]\[Link]\[Link]");
[Link]("\nEnter choice: ");
int choice = [Link]();
switch (choice) {
case 1:
[Link]("Enter element to push: ");
int element = [Link]();
push(element);
break;
case 2:
pop();
break;
case 3:
display();
break;
case 4:
[Link]("Exiting Program!!");
[Link](0);
default:
[Link]("Enter Correct Choice: ");
break;
}
}
}
}

6. Create a java program which accepts file name and a string and prints how many
occurrences of the given string present in the given file.
Program:
import [Link];
import [Link].*;
public class SearchString {
public static void main(String[] args) throws FileNotFoundException, IOException {
Scanner sc = new Scanner([Link]);
[Link]("Enter file name: ");
String fileName = [Link]();
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))){
[Link]("Enter pattern to search: ");
String pattern = [Link]();
String line;
int count = 0;
while(((line = [Link]()) != null)){
for (int i = 0; i <= [Link]() - [Link](); i++) {
if ([Link](i, i +[Link]()).equals(pattern)) {
count++;
}
}
}
[Link]("Occurences of pattern in file: "+ count);
}catch(IOException e){
[Link]();
}
[Link]();
}
}

7. Explain thread life cycle with sample program. How the methods start() and run() are
associated with each other.
Program:
class MyThread extends Thread {
public void run() {
[Link]("Thread is in the Runnable state.");
try {
[Link](500);
[Link]("Thread is in the Timed Waiting state.");
} catch (InterruptedException e) {
[Link]();
}

synchronized (this) {
[Link]("Thread is in the Blocked state.");

try {
wait();
[Link]("Thread is in the Waiting state.");
} catch (InterruptedException e) {
[Link]();
}
}

[Link]("Thread is in the Terminated state.");


}
}
public class ThreadExample {
public static void main(String[] args) {
Thread myThread = new MyThread();
[Link]();
}
}
8. Create java program with two parallel threads accessing the same array and thread1
counts the total number of even numbers present in the array and thread2 counts the total
number of odd numbers present in the array.
Program:
public class EvenOddCountThreads {
static int array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
static int evenCount = 0;
static int oddCount = 0;

public static void main(String[] args) {


EvenThread e1 = new EvenThread();
OddThread o1 = new OddThread();
[Link]();
[Link]();
try {
[Link]();
[Link]();
} catch (InterruptedException e) {
[Link]();
}
[Link]("Even Numbers count in the array: " + evenCount);
[Link]("Odd numbers count in the array: " + oddCount);
}

static class EvenThread extends Thread {


public void run() {
for (int i : array) {
if (i % 2 == 0) {
synchronized ([Link]) {
evenCount++;
}
}
}
}
}
static class OddThread extends Thread {
public void run() {
for (int i : array) {
if (i % 2 != 0) {
synchronized ([Link]) {
oddCount++;
}
}
}
}
}
}
9. What is thread synchronization? Explain with the sample java program.
Program:
class Q {
int n;
boolean valueSet = false;
int count = 0;

synchronized int get() {


while (!valueSet || count >= 12) {
try {
wait();
} catch (InterruptedException e) {
[Link]("Interrupted Exception Occurred");
}
}
[Link]("GET: " + n);
count++;
valueSet = false;
notify();
if (count >= 12) {
[Link](1);
}
return n;
}

synchronized void put(int n) {


while (valueSet || count >= 12) {
try {
wait();
} catch (InterruptedException e) {
[Link]("Interrupted Exception Occurred");
}
}
this.n = n;
valueSet = true;
[Link]("PUT: " + n);
count++;
if (count >= 12) {
[Link](1);
}
notify();
}
}

class Producer implements Runnable {


Q q;

Producer(Q q) {
this.q = q;
new Thread(this, "Producer").start();
}

public void run() {


int i = 0;
while (true) {
[Link](i++);
}
}
}

class Consumer implements Runnable {


Q q;

Consumer(Q q) {
this.q = q;
new Thread(this, "Consumer").start();
}
public void run() {
while (true) {
[Link]();
}
}
}

public class ThreadSynchronization {


public static void main(String[] args) {
Q q = new Q();
new Producer(q);
new Consumer(q);
}
}
10. What is thread synchronization? Explain with the sample java program.
Program:
class Q {
int n;
boolean valueSet = false;
int count = 0;

synchronized int get() {


while (!valueSet || count >= 12) {
try {
wait();
} catch (InterruptedException e) {
[Link]("Interrupted Exception Occurred");
}
}
[Link]("GET: " + n);
count++;
valueSet = false;
notify();
if (count >= 12) {
[Link](1);
}
return n;
}

synchronized void put(int n) {


while (valueSet || count >= 12) {
try {
wait();
} catch (InterruptedException e) {
[Link]("Interrupted Exception Occurred");
}
}
this.n = n;
valueSet = true;
[Link]("PUT: " + n);
count++;
if (count >= 12) {
[Link](1);
}
notify();
}
}

class Producer implements Runnable {


Q q;

Producer(Q q) {
this.q = q;
new Thread(this, "Producer").start();
}

public void run() {


int i = 0;
while (true) {
[Link](i++);
}
}
}

class Consumer implements Runnable {


Q q;
Consumer(Q q) {
this.q = q;
new Thread(this, "Consumer").start();
}

public void run() {


while (true) {
[Link]();
}
}
}

public class ThreadSynchronization {


public static void main(String[] args) {
Q q = new Q();
new Producer(q);
new Consumer(q);
}
}
11. Illustrate thread group with sample program.
Program:
public class ThreadGroupExample {
public static void main(String[] args) {
ThreadGroup myThreadGroup = new ThreadGroup("MyThreadGroup");
MyThread thread1 = new MyThread(myThreadGroup, "Thread1");
MyThread thread2 = new MyThread(myThreadGroup, "Thread2");
[Link]();
[Link]();
[Link]();
}

static class MyThread extends Thread {


public MyThread(ThreadGroup group, String name) {
super(group, name);
}

public void run() {


for (int i = 0; i < 5; i++) {
[Link]([Link]().getName() + " is running...");
try {
[Link](1000);
} catch (InterruptedException e) {
[Link]();
}
}
}
}
}
12. What are adapter classes? When they should be used. Illustrate with example.
Program:
interface Calculator {
int add(int a, int b);

int subtract(int a, int b);

int multiply(int a, int b);

int divide(int a, int b);


}

class CalculatorAdapter implements Calculator {


public int add(int a, int b) {
return 0;
}

public int subtract(int a, int b) {


return 0;
}

public int multiply(int a, int b) {


return 0;
}

public int divide(int a, int b) {


return 0;
}
}

class MyCalculator extends CalculatorAdapter {


public int add(int a, int b) {
return a + b;
}
public int subtract(int a, int b) {
return a - b;
}
}

public class AdapterClassExample {


public static void main(String[] args) {
Calculator calculator = new MyCalculator();

int resultAdd = [Link](5, 3);


int resultSubtract = [Link](10, 4);

[Link]("Result of addition: " + resultAdd);


[Link]("Result of subtraction: " + resultSubtract);
}
}
13. Write an AWT program with a ComboBox showing three colors to choose. Set the back
ground of the frame to the colors choosen by the user. ( If user chooses green color,
background should display green by calling setBackground([Link]) ).
Program:
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class ColorChooserAWT extends Frame implements ItemListener {


private Choice colorChoice;
public ColorChooserAWT() {
setLayout(null);
colorChoice = new Choice();
[Link]("Red");
[Link]("Green");
[Link]("Blue");
setBackground([Link]);
[Link](20, 20, 100, 20);
[Link](this);
add(colorChoice);
setSize(300, 200);
setTitle("Color Chooser");
setVisible(true);
setLocationRelativeTo(null);
addWindowListener(new [Link]() {
public void windowClosing([Link] windowEvent) {
[Link](0);
}
});
}
public void itemStateChanged(ItemEvent e) {
String selectedColor = [Link]();
switch (selectedColor) {
case "Red":
setBackground([Link]);
break;
case "Green":
setBackground([Link]);
break;
case "Blue":
setBackground([Link]);
break;
default:
break;
}
}
public static void main(String[] args) {
new ColorChooserAWT();
}
}

14. Develop an application to illustrate hiding of data members from outside world.
Program:
class MyClass {
public int publicVariable = 10;
private int privateVariable = 20;
protected int protectedVariable = 30;
public int getPrivateVariable() {
return privateVariable;
}
public void setPrivateVariable(int value) {
privateVariable = value;
}
}

public class HidingDataMembers {


public static void main(String[] args) {
MyClass myObject = new MyClass();
[Link]("Public Variable: " + [Link]);
[Link]("Private Variable: " + [Link]());
[Link](25);
[Link]("Modified Private Variable: " + [Link]());
[Link]("Protected Variable: " + [Link]);
}
}

15. Explain the use of static keyword with suitable example.


Program:
public class StaticKeywordExample {
static int staticVar = 0;
static void staticMethod() {
[Link]("This is a static method.");
}
static {
staticVar = 42;
[Link]("Static block executed.");
}

public static void main(String[] args) {


[Link]("Static variable: " + [Link]);
[Link]();
}
}

[Link] Bubble sort algorithm to sort collection of strings supplied as command line
arguments.

Program:
public class BubbleSort {
public static void print(int [] array){
for (int i = 0; i < [Link] ; i++) {
[Link](array[i]+" ");
}
[Link]();
}
public static void bubbleSort(int[] array){
for(int i=0;i<[Link];i++){
for(int j=0;j<[Link]-1-i;j++ ){
if(array[j]>array[j+1]){
int temp = array[j];
array[j]=array[j+1];
array[j+1]=temp;
}
}
}
}
public static void main(String[] args) {
// first command line is size of the array
// remaining are array elements
if([Link] <0){
[Link]("No arguments passed");
}else{
int size = [Link](args[0]);
int [] array = new int [size];
for(int i=1;i<=size;i++){
array[i-1]=[Link](args[i]);
}
[Link]("Original array: ");
print(array);
bubbleSort(array);
[Link]("Sorted array: ");
print(array);
}
}
}
17. Develop an user defined Number Utilities package and provide following classes.

Program:
Com\arrSoft\Number\Util
[Link]
package [Link];
public class Armstrong {
public static boolean isArmstrong(int num){
int num2=num;
int sum = 0,temp = 0;
while(num>0){
temp = num % 10;
sum += [Link](temp, 3);
num /= 10;
}
return sum == num2;
}
}
[Link]
package [Link];

public class Factorial {


public static int factorial(int n){
if (n == 0){
return 1;
}else{
return n * factorial(n-1);
}
}
}
[Link]
package [Link];

public class Palindrome {


public static boolean isPalindrome(int num){
int reverse = 0, temp = num;
while (temp != 0) {
reverse = reverse * 10 + temp % 10;
temp /= 10;
}
return reverse == num;
}
}
[Link]
import [Link].*;

import [Link];
public class NumberUtilTest {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Menu\[Link]\[Link]\[Link]\[Link]");
while(true){
[Link]("Enter choice: ");
int choice = [Link]();
switch (choice) {
case 1:
[Link]("Enter Number: ");
int number = [Link]();
if([Link](number)){
[Link]("%d is Armstrong number\n", number);
}else{
[Link]("%d is not Armstrong number\n", number);
}
break;
case 2:
[Link]("Enter number: ");
int number2 = [Link]();
if([Link](number2)){
[Link]("%d is Palindrome number\n", number2);
}else{
[Link]("%d is not Palindrome number\n", number2);
}
break;
case 3:
[Link]("Enter number: " );
int number3 = [Link]();
if(number3<=0){
[Link]("Enter positive number: ");
break;
}else{
long fact= [Link](number3);
[Link]("Factorial of %d is : %d \n", number3,fact);
break;
}
case 4:
[Link]("Exiting Program!!");
[Link](0);
default:
[Link]("Enter valid choice!!");
break;
}
}
}
}

18.

Program:
import [Link];
class NegativeArraySizeException extends Exception{
public NegativeArraySizeException(){
super("Invalid array size.");
}
}
public class DeviationFromMean {
public static void main(String[] args) throws NegativeArraySizeException {
Scanner sc = new Scanner([Link]);
int size = getSize(sc);
double [] array = new double[size];
getArrayElements(array, size, sc);
double mean = mean(array, size);
[Link]("Mean: "+mean);
displayingDeviations(array, size, mean);

}
public static int getSize(Scanner sc) throws NegativeArraySizeException{
int size = 0;
while(true){
[Link]("Enter array size: ");
try{
size = [Link]([Link]());
if(size<=0){
throw new NegativeArraySizeException();
}else if(size>15){
[Link]("Initializing size to 15.");
size = 15;
}
break;
}catch(NumberFormatException e){
[Link]("Enter valid input!");
}catch(NegativeArraySizeException e){
[Link]([Link]());
}
}
return size;
}
public static void getArrayElements(double [] array,int size,Scanner sc){
for (int i = 0; i < size; i++) {
while (true) {
try {
[Link]("Enter value for index " + i + ": ");
array[i] = [Link]([Link]());
break;
} catch (NumberFormatException e) {
[Link]("Invalid input. Please enter a valid double value.");
}
}
}
}
public static double mean(double[] array,int size){
double sum = 0;
for(double i : array){
sum+=i;
}
return sum/size;
}
public static void displayingDeviations(double[] array,int size,double mean){
[Link]("Element Deviation");
for(double i : array){
double d = i - mean;
[Link](i+" "+d);
}
}
}

19. Develop a ScoreTest class to display a series of five Student ID numbers and asks the
user to enter a numeric test scores of three subjects and to display the average. Develop a
ScoreException class and throw it when the user enters an invalid score (greater than 100
and less than 0).

Program:
import [Link];

class ScoreException extends Exception {


public ScoreException(String message) {
super(message);
}
}

class Student {
private int studentID;
private double[] scores;

Student(int studentID) {
[Link] = studentID;
[Link] = new double[3];
}

void setScore(int subjectIndex, double score) throws ScoreException {


if (score < 0 || score > 100) {
throw new ScoreException("Invalid score. Score must be between 0 and 100.");
}
scores[subjectIndex] = score;
}

double getAverage() {
double sum = 0;
for (double score : scores) {
sum += score;
}
return sum / [Link];
}

int getStudentID() {
return studentID;
}
}

public class ScoreTest {


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

for (int i = 0; i < 5; i++) {


[Link]("Enter Student ID (like 1 or 2 or 3): ");
int studentID = [Link]();

Student student = new Student(studentID);

for (int j = 0; j < 3; j++) {


double score = getValidScore(sc, j);
try {
[Link](j, score);
} catch (ScoreException e) {
[Link]([Link]());
j--;
}
}

[Link]("Average score for student " + [Link]() + ": " +


[Link]());
[Link]();
}

[Link]();
}

public static double getValidScore(Scanner sc, int subjectIndex) {


double score = -1;

while (true) {
try {
[Link]("Enter score for Subject " + (subjectIndex + 1) + ": ");
score = [Link]([Link]());
if (score < 0 || score > 100) {
throw new ScoreException("Invalid score. Score must be between 0 and 100.");
}

break;
} catch (NumberFormatException | ScoreException e) {
[Link]([Link]());
}
}

return score;
}
}

20. Exemplify Random access file operations.


Program:
import [Link];

public class RandomAccessFileExample {

public static void main(String[] args) {


String fileName = "[Link]";
writeDataToFile(fileName);
readDataFromFile(fileName);
}

private static void writeDataToFile(String fileName) {


try (RandomAccessFile randomAccessFile = new RandomAccessFile(fileName, "rw")) {
[Link](100);
[Link](45.67);
[Link]("Random Access File Example");

[Link]("Data written to the file successfully.");

} catch (Exception e) {
[Link]();
}
}

private static void readDataFromFile(String fileName) {


try (RandomAccessFile randomAccessFile = new RandomAccessFile(fileName, "r")) {
int intValue = [Link]();
double doubleValue = [Link]();
String stringValue = [Link]();

[Link]("Read Data:");
[Link]("Integer Value: " + intValue);
[Link]("Double Value: " + doubleValue);
[Link]("String Value: " + stringValue);

} catch (Exception e) {
[Link]();
}
}
}

21. Develop a multithreaded program to find whether given numbers are prime or not.
Thread 1: Take the input from the user. Thread 2: Determine whether input is prime or not.
** Thread 1 and Thread 2 is repeated at least 10 cycles. Main Thread: Print each number
and its status of prime as either PRIME or NOT PRIME. Make ensure that Thread 2 should
execute after Thread 1 in each cycle and Main Thread should be terminated only after
completion of all cycles.

Program:
import [Link];
public class TwoThreads {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
TakeInput t1 = new TakeInput(sc);
[Link]();

}
}
class TakeInput extends Thread{
Scanner sc ;
TakeInput(Scanner sc){
[Link] = sc;
}
public void run(){
while(true){
[Link]("Enter n(n>=2): ");
int n = [Link]();
if(n<2){
[Link]("Program Terminating...");
[Link](0);
}
isPrime t2 = new isPrime(n);
[Link]();
try{
[Link]();
}catch(InterruptedException e){
[Link]([Link]());
}
}
}
}
class isPrime extends Thread{
int n;
isPrime(int n){
this.n = n;
}
public void run(){
boolean prime = true;
for(int i=2;i<n/2;i++){
if(n%i==0){
prime = false;
break;
}
}
if(prime){
[Link](n+" is prime");
}else{
[Link](n+" is not prime");
}
}
}

22. A Father and son went to a hotel and observed that it was very crowdy. Since they are
very hungry they ordered two lunch packs. They waited for half an hour and finally they
took their lunch order. But hotel management placed only one spoon and forget to put two
spoons. Now father and son not interested to go back and they want to adjust and share
the available spoon. They want to eat alternatively with one spoon.
Sample Output:
Father holding the spoon and son is waiting.
Son holding the spoon and father is waiting.
Father holding the spoon and son is waiting.
Son holding the spoon and father is waiting.
……………….

Program:
public class FatherSon {
private static boolean father = true;
private static boolean son = false;

public static void main(String[] args) {


Father fatherThread = new Father();
Son sonThread = new Son();

[Link]();
[Link]();
}

static class Father extends Thread {


public void run() {
while (true) {
synchronized (this) {
if (father) {
[Link]("Father is holding. Son is waiting");
father = false;
son = true;
try {
[Link]();
} catch (InterruptedException e) {
[Link]();
}
}
}
}
}
}

static class Son extends Thread {


@Override
public void run() {
while (true) {
synchronized ([Link]) {
if (son) {
[Link]("Son is holding. Father is waiting");
father = true;
son = false;
}
try {
[Link](1000);
synchronized ([Link]) {
[Link]();
}
} catch (InterruptedException e) {
[Link]();
}
}
}
}
}
}

23. Develop a Menu Bar using Swings with the following items:
-- Operations (Menu) has following Sub Menus:
--Arithmetic (Sub Menu) has following Menu Items
--ADD (Menu Item)
--SUB
--MUL
--DIV
--Logical (Sub Menu) has following Menu Items
--AND
--OR
--NOT
Whenever a user clicks any menu item display description about the operation in the
application window.

Program:
import [Link].*;
import [Link];
import [Link];

class MenuExample {
MenuExample(){
JFrame f= new JFrame("Operations Menu");
JMenuBar mb=new JMenuBar();
JMenu menu=new JMenu("Operations");
JMenu submenu1=new JMenu("Arithmetic");
JMenu submenu2=new JMenu("Logical");
JMenuItem i1=new JMenuItem("ADD");
JMenuItem i2=new JMenuItem("SUB");
JMenuItem i3=new JMenuItem("MUL");
JMenuItem i4=new JMenuItem("DIV");
JMenuItem i5=new JMenuItem("AND");
JMenuItem i6=new JMenuItem("OR");
JMenuItem i7=new JMenuItem("NOT");
[Link](new MenuActionListener("Addition operation selected."));
[Link](new MenuActionListener("Subtraction operation selected."));
[Link](new MenuActionListener("Multiplication operation selected."));
[Link](new MenuActionListener("Division operation selected."));
[Link](new MenuActionListener("Logical AND operation selected."));
[Link](new MenuActionListener("Logical OR operation selected."));
[Link](new MenuActionListener("Logical NOT operation selected."));

[Link](i1);
[Link](i2);
[Link](i3);
[Link](i4);
[Link](i5);
[Link](i6);
[Link](i7);

[Link](submenu1);
[Link](submenu2);
[Link](menu);
[Link](mb);
[Link](400,400);
[Link](null);
[Link](true);
[Link](JFrame.EXIT_ON_CLOSE);
}

public static void main(String args[]) {


new MenuExample();
}

static class MenuActionListener implements ActionListener {


private String description;

public MenuActionListener(String description) {


[Link] = description;
}

@Override
public void actionPerformed(ActionEvent e) {
[Link](null, description, "Operation Selected",
JOptionPane.INFORMATION_MESSAGE);
}
}
}

You might also like