[go: up one dir, main page]

0% found this document useful (0 votes)
21 views16 pages

Ok Questions

yes it need to be done for a work .

Uploaded by

ag9998
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views16 pages

Ok Questions

yes it need to be done for a work .

Uploaded by

ag9998
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Q - Write a Java Program to implement MULTITHREADED--PRIME AND FIBONACCI NUMBER

Ans - Procedure Steps/Algorithm:

1. Start the program.

2. Read the values for Prime Numbers as isPrime, i, j.

3. Read the values for Fibonacci Numbers as a, b, c, i.

4. Using for and if loops generate the Prime and Fibonacci Numbers

5. Print the Prime and Fibonacci Numbers

6. Stop the program.

Program:

import java.util.concurrent.*;

public class PrimeFibonacciiNo {

public static void main(String[] args) throws InterruptedException,

ExecutionException {

ExecutorService executor = Executors.newFixedThreadPool(2);

Callable<String> primeTask = () -> {

String primeNumbers = "Prime numbers: ";

for (int i = 2; i <= 100; i++) {

boolean isPrime = true;

for (int j = 2; j < i; j++) {

if (i % j == 0) {

isPrime = false;

break;

if (isPrime) {

primeNumbers += i + " ";

return primeNumbers;

};

Callable<String> fibonacciTask = () -> {


String fibonacciNumbers = "Fibonacci numbers: ";

int a = 0, b = 1, c;

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

c = a + b;

fibonacciNumbers += c + " ";

a = b;

b = c;

return fibonacciNumbers;

};

Future<String> primeResult = executor.submit(primeTask);

Future<String> fibonacciResult = executor.submit(fibonacciTask);

System.out.println(primeResult.get());

System.out.println(fibonacciResult.get());

executor.shutdown();

Question - The aim of this program is to create a Java program that generates rational numbers in
reduced form by taking input from the user for the numerator and denominator values, simplifying
the fraction using the greatest common divisor, and displaying the simplified fraction as output.

Procedure Steps:

1. The program imports the java.util package, which contains the Scanner class.

2. A class named "Rational" is defined, with two instance variables n and d

representing the numerator and denominator, respectively.


3. A constructor for the class is defined, which takes in two integers as arguments (x and y) and
assigns them to n and d. The constructor also prints the values of n and d and the original fraction
(n/d) before simplification.

4. A method named "reducedform()" is defined, which simplifies the fraction by dividing the
numerator and denominator by their greatest common divisor (GCD).

5. A method named "display()" is defined, which prints the simplified fraction (n/d).

6. In the main method, a Scanner object is created to take input from the user for the
numerator and denominator values. These values are then passed as arguments to create an object
of the Rational class.

7. The reducedform() and display() methods are called on the object, and the simplified
fraction is printed.

8. The Scanner object is closed.

Answer - import java.util.*;

class Rational

int n,d;

/* This constructor to get Numerator and Denominator value*/ Rational(int x,int y)

n=x; d=y;

System.out.println("NUMERATOR="+n); System.out.println("DENOMINATOR="+d);
System.out.println("BEFORE SIMPLIFICATION="+n+"/"+d);

/* This method finds the reduce form of Numerator and Denominator value*/
public void reducedform()

if(n<d)

for(int i=2;i<=n;i++)

while((n%i)==0 && (d%i)==0)

n=n/i; d=d/i;

else

for(int i=2;i<=d;i++)

while((n%i)==0 && (d%i)==0)

n=n/i; d=d/i;

void display()

System.out.println("Reduced form="+n+"/"+d);

/**

* @param args

*/
public static void main(String args[])

Scanner S=new Scanner(System.in);

System.out.println("***********ENTER NUMERATOR VALUE*****************"); int


A=S.nextInt();

System.out.println("***********ENTER DENOMINATOR VALUE*****************"); int


B=S.nextInt();

final Rational R=new Rational(A,B); R.reducedform();

R.display();

S.close();

Question - program to create user define package date class

PROCEDURE STEPS/ALOGRITHM :

1. Start the program

2. Create the month year day parameters and read it from the imported file

3. Create functions Time and date

4. Create an object of the class, call the function

5. Print the reduced form

6. Stop the program

PROGRAM :

import java.util.GregorianCalendar;

public class CurrentDate{

public static void MDY() {

GregorianCalendar cal = new GregorianCalendar();

int month = cal.get(GregorianCalendar.MONTH);

int year = cal.get(GregorianCalendar.YEAR);


int day = cal.get(GregorianCalendar.DAY_OF_MONTH);

System.out.println("Current date : " + day + "/" + (month + 1) + "/" + year);

public static void HMS() {

GregorianCalendar cal = new GregorianCalendar();

String am_pm;

int hour = cal.get(GregorianCalendar.HOUR);

int minute = cal.get(GregorianCalendar.MINUTE);

int second = cal.get(GregorianCalendar.SECOND);

if (cal.get(GregorianCalendar.AM_PM) == 0)

am_pm = "PM";

else

am_pm = "AM";

System.out.println("Current Time : " + hour + ":" + minute + ":" + second + " " +
am_pm);

public static void main(String[] args) {

CurrentDate D = new CurrentDate();

System.out.println("**");

// D.MDY();

MDY();

System.out.println("**");

// D.HMS();

HMS();

}
Question - Write a Java Program to implement MULTITHREADED--PRIME AND FIBONACCI NUMBER

Procedure Steps/Algorithm:

1. Start the program.

2. Read the values for Prime Numbers as isPrime, i, j.

3. Read the values for Fibonacci Numbers as a, b, c, i.

4. Using for and if loops generate the Prime and Fibonacci Numbers

5. Print the Prime and Fibonacci Numbers

6. Stop the program.

Program:

import java.util.concurrent.*;

public class PrimeFibonacciiNo {

public static void main(String[] args) throws InterruptedException, ExecutionException {

ExecutorService executor = Executors.newFixedThreadPool(2);

Callable<String> primeTask = () -> {

String primeNumbers = "Prime numbers: ";

for (int i = 2; i <= 100; i++) {

boolean isPrime = true;

for (int j = 2; j < i; j++) {

if (i % j == 0) {

isPrime = false;

break;

if (isPrime) {

primeNumbers += i + " ";

return primeNumbers;
};

Callable<String> fibonacciTask = () -> {

String fibonacciNumbers = "Fibonacci numbers: ";

int a = 0, b = 1, c;

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

c = a + b;

fibonacciNumbers += c + " ";

a = b;

b = c;

return fibonacciNumbers;

};

Future<String> primeResult = executor.submit(primeTask);

Future<String> fibonacciResult = executor.submit(fibonacciTask);

System.out.println(primeResult.get());

System.out.println(fibonacciResult.get());

executor.shutdown();

Question - Develop a MultiThreaded Echo Server using Swings and use appropriate Listener.

import java.io.*;

import java.net.*;

import javax.swing.*;

public class EchoServer extends JFrame {

private JTextArea textArea;

public EchoServer() {

super("Echo Server");
textArea = new JTextArea();

add(new JScrollPane(textArea));

setSize(400, 300);

setVisible(true);

public void startServer() {

try {

// Create a server socket

ServerSocket serverSocket = new ServerSocket(8000);

textArea.append("Server started at " + new java.util.Date() + '\n');

// Create a socket for each connection and start a new thread

while (true) {

Socket socket = serverSocket.accept();

textArea.append("New client accepted at " + new java.util.Date() + '\n');

ClientThread thread = new ClientThread(socket);

thread.start();

catch(IOException ex) {

ex.printStackTrace();

public static void main(String[] args) {

EchoServer server = new EchoServer();

server.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

server.startServer();

// Inner class for the client thread

class ClientThread extends Thread {

private Socket socket;

private DataInputStream inputFromClient;


private DataOutputStream outputToClient;

public ClientThread(Socket socket) {

this.socket = socket;

try {

// Create data input and output streams

inputFromClient = new DataInputStream(

socket.getInputStream());

outputToClient = new DataOutputStream(

socket.getOutputStream());

catch(IOException ex) {

ex.printStackTrace();

public void run() {

try {

while (true) {

// Receive message from the client

String message = inputFromClient.readUTF();

// Send the message back to the client

outputToClient.writeUTF(message);

// Display to the text area

textArea.append(message + '\n');

catch(IOException ex) {

ex.printStackTrace();

}
9. Demonstrate the concept of Threads to achieve multitasking program

using Thread class and Runnable Interface (separately) for the below

scenario:

Create an Array of 9 numbers. And create three Threads to split the task evenly

among the three threads. And each thread has to add up and report the answer to the

main thread where the main thread waits for the 3 threads and computes the

summation of all the three threads. Note: Assign names to the threads as well.

Using the Thread class:

import java.util.Arrays;

public class Main {

public static void main(String[] args) throws InterruptedException {

int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9};

int chunkSize = numbers.length / 3;

Thread thread1 = new Thread(new SumThread(numbers, 0, chunkSize, "Thread 1"));

Thread thread2 = new Thread(new SumThread(numbers, chunkSize, 2 * chunkSize, "Thread 2"));

Thread thread3 = new Thread(new SumThread(numbers, 2 * chunkSize, numbers.length, "Thread

3"));

thread1.start();

thread2.start();

thread3.start();

thread1.join();

thread2.join();

thread3.join();

int sum = thread1.getSum() + thread2.getSum() + thread3.getSum();

System.out.println("Sum of all numbers: " + sum);

class SumThread implements Runnable {

private int[] numbers;

private int startIndex;

private int endIndex;


private String name;

private int sum;

public SumThread(int[] numbers, int startIndex, int endIndex, String name) {

this.numbers = numbers;

this.startIndex = startIndex;

this.endIndex = endIndex;

this.name = name;

public int getSum() {

return sum;

@Override

public void run() {

for (int i = startIndex; i < endIndex; i++) {

sum += numbers[i];

System.out.println(name + ": " + sum);

using the Runnable interface:

import java.util.Arrays;

public class Main {

public static void main(String[] args) {

// create an array of 9 numbers

int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9};

// create three threads to split the task evenly among the three threads

Thread thread1 = new Thread(new SumTask(numbers, 0, 3));

thread1.setName("Thread 1");

Thread thread2 = new Thread(new SumTask(numbers, 3, 6));

thread2.setName("Thread 2");

Thread thread3 = new Thread(new SumTask(numbers, 6, 9));


thread3.setName("Thread 3");

// start the threads

thread1.start();

thread2.start();

thread3.start();

// wait for the threads to finish

try {

thread1.join();

thread2.join();

thread3.join();

} catch (InterruptedException e) {

e.printStackTrace();

// compute the summation of all the three threads

int sum = thread1.getSum() + thread2.getSum() + thread3.getSum();

System.out.println("Sum: " + sum);

class SumTask implements Runnable {

private int[] numbers;

private int startIndex;

private int endIndex;

private int sum;

public SumTask(int[] numbers, int startIndex, int endIndex) {

this.numbers = numbers;

this.startIndex = startIndex;

this.endIndex = endIndex;

@Override

public void run() {

for (int i = startIndex; i < endIndex; i++) {


sum += numbers[i];

public int getSum() {

return sum;

8,Write a Java program for user defined exception that checks the internal

and external marks; if the internal marks is greater than 30 it raises the

exception “Internal mark exceeded”; if the external marks is greater than

70 it raises the exception and displays the message “External mark

exceeded”, Create the above exception and test the exceptions.

class MarksException extends Exception {

public MarksException(String message) {

super(message);

public class TestException {

public static void main(String[] args) {

int internalMarks = 35;

int externalMarks = 75;

try {

if (internalMarks > 30) {

throw new MarksException("Internal mark exceeded");

if (externalMarks > 70) {

throw new MarksException("External mark exceeded");

} catch (MarksException e) {

System.out.println(e.getMessage());
}

Question - 4. In this problem, you'll create a program that guesses a secret number!

The program works as follows: you (the user) thinks of an integer between 0

(inclusive) and 100 (not inclusive). The computer makes guesses, and you give it

input - is its guess too high or too low? Using bisection search, the computer will

guess the user's secret number!

Here is a transcript of an example session:

Please think of a number between 0 and 100!

Is your secret number 50?

Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low.

Enter 'c' to indicate I guessed correctly. l

Is your secret number 75?

Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low.

Enter 'c' to indicate I guessed correctly. l

Is your secret number 87?

Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low.

Enter 'c' to indicate I guessed correctly. h

Is your secret number 81?

Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low.

Enter 'c' to indicate I guessed correctly. l

Is your secret number 84?

Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low.

Enter 'c' to indicate I guessed correctly. h

Is your secret number 82?

Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low.

Enter 'c' to indicate I guessed correctly. l

Is your secret number 83?

Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low.

Enter 'c' to indicate I guessed correctly. c


Game over. Your secret number was: 83

Your program should use bisection search. So think carefully what that means. What

will the first guess always be? How should you calculate subsequent guesses? Hint:

Your initial endpoints should be 0 and 100.

import java.util.Scanner;

public class BisectionSearch {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

System.out.println("Please think of a number between 0 and 100!");

int low = 0;

int high = 100;

int guess;

while (true) {

guess = (low + high) / 2;

System.out.printf("Is your secret number %d?\n", guess);

System.out.println("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too

low. Enter 'c' to indicate I guessed correctly.");

char response = input.next().charAt(0);

if (response == 'c') {

System.out.printf("Game over. Your secret number was: %d\n", guess);

break;

} else if (response == 'l') {

low = guess;

} else if (response == 'h') {

high = guess;

} else {

System.out.println("Sorry, I did not understand your input.");

You might also like