0% found this document useful (0 votes)
58 views31 pages

Untitled

A travel agency offers executive travel packages with discounts for certain age and gender criteria. An exception is thrown if the criteria are not met. The program defines an exception class and calculates discounted prices based on the criteria, throwing the exception if needed. Six threads are used to count student registrations for five events from an array of 1000 random registration numbers. Synchronized methods update shared count variables. The main thread displays final counts and any unregistered students. A program analyzes two text files, counting character types in the first file and writing percentage results to the second file. It calculates percentages of uppercase, lowercase, digits and special characters. An program simulates a mother preparing roti for children using threads

Uploaded by

Dharshika
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)
58 views31 pages

Untitled

A travel agency offers executive travel packages with discounts for certain age and gender criteria. An exception is thrown if the criteria are not met. The program defines an exception class and calculates discounted prices based on the criteria, throwing the exception if needed. Six threads are used to count student registrations for five events from an array of 1000 random registration numbers. Synchronized methods update shared count variables. The main thread displays final counts and any unregistered students. A program analyzes two text files, counting character types in the first file and writing percentage results to the second file. It calculates percentages of uppercase, lowercase, digits and special characters. An program simulates a mother preparing roti for children using threads

Uploaded by

Dharshika
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
You are on page 1/ 31

1.

A travel agency offers executive travel package for a month by giving 15% off on rate for male
above 65 years of age and 20% off for female above 60 years of age and 10% off to couples if female
is above 18 years and male is above 21years . Create a User defined Exception class so that if the
age and gender of the person is not matching with the norms of the agency it throws an exception
else it offers the concession to the customer.
[10 Marks]

import java.util.Scanner;

class InvalidCustomerException extends Exception {


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

class TravelAgency {
public static double calculatePrice(int age, char gender, boolean isCouple) throws
InvalidCustomerException {
double basePrice = 5000; // base price for the executive travel package
double discount = 0;
if (gender == 'M' && age > 65) {
discount = 0.15;
} else if (gender == 'F' && age > 60) {
discount = 0.2;
} else if (isCouple && gender == 'F' && age > 18 && age < 60 && gender=='M' && age > 21 &&
age < 65 ) {
discount = 0.1;
} else {
throw new InvalidCustomerException("Customer does not meet eligibility criteria for discount");
}
return basePrice - (basePrice * discount);
}
}

public class Main {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter age: ");


int age = scanner.nextInt();

System.out.print("Enter gender (M/F): ");


char gender = scanner.next().charAt(0);

System.out.print("Are you a couple (true/false)? ");


boolean isCouple = scanner.nextBoolean();

try {
double price = TravelAgency.calculatePrice(age, gender, isCouple);
System.out.println("Price with discount: $" + price);
} catch (InvalidCustomerException e) {
System.out.println("Error: " + e.getMessage());
}
}
}

2. Five events E1, E2, E3, E4 and E5 are going to be organized for Gravitas in VIT, registration is
open for all B.Techstudents. With the total strength of 1000 students, simulate the registration for
each event by generating 1000 random numbers in the range of 1 – 5. (1 for event E1, 2 for E2… 5
for E5) and store the values in an array. Create six threads to equally share the task of counting the
number of registration details for all the events. Use synchronized method or synchronized block to
update the count variables. The main thread should receive the final registration count for all
events and display the list of students who have not registered in any event.
[10 Marks]

import java.util.*;

class RegistrationThread extends Thread {


private int[] registrations;
private int start;
private int end;
private int[] counts;

public RegistrationThread(int[] registrations, int start, int end, int[] counts) {


this.registrations = registrations;
this.start = start;
this.end = end;
this.counts = counts;
}

public void run() {


for (int i = start; i < end; i++) {
synchronized (counts) {
counts[registrations[i]-1]++;
}
}
}
}

public class Main {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter the number of students: ");


int numStudents = scanner.nextInt();

int[] registrations = new int[numStudents];


Random rand = new Random();
for (int i = 0; i < numStudents; i++) {
registrations[i] = rand.nextInt(5) + 1;
}
int[] counts = new int[5];
int numThreads = 6;
int chunkSize = numStudents / numThreads;
List<RegistrationThread> threads = new ArrayList<>();
for (int i = 0; i < numThreads; i++) {
int start = i * chunkSize;
int end = (i == numThreads-1) ? numStudents : (i+1) * chunkSize;
threads.add(new RegistrationThread(registrations, start, end, counts));
}

for (RegistrationThread thread : threads) {


thread.start();
}

for (RegistrationThread thread : threads) {


try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}

List<Integer> unregistered = new ArrayList<>();


for (int i = 0; i < numStudents; i++) {
if (counts[registrations[i]-1] == 0) {
unregistered.add(i+1);
}
}

System.out.println("Registration counts:");
for (int i = 0; i < counts.length; i++) {
System.out.println("E" + (i+1) + ": " + counts[i]);
}

if (unregistered.size() > 0) {
System.out.println("Students who have not registered:");
for (int id : unregistered) {
System.out.println("Student " + id);
}
} else {
System.out.println("All students have registered for at least one event.");
}
}
}

3. Raj is a teacher who creates a file named “class.txt” with records of his students’ marks. He
checks for invalid entries in his file. The file consists of digits and characters. He needs to find the
percentage of uppercase characters, lowercase characters, digits and special characters present in
the file and write the result into another file named “data.txt” that he can analyse later. Write a
Java program to aid him.
[10 Marks]

import java.io.*;

public class RajFileAnalyzer {


public static void main(String[] args) {
try {
// Open file for reading
BufferedReader reader = new BufferedReader(new FileReader("class.txt"));

// Initialize count variables


int totalChars = 0;
int upperCaseCount = 0;
int lowerCaseCount = 0;
int digitCount = 0;
int specialCharCount = 0;

// Read each line from file


String line;
while ((line = reader.readLine()) != null) {
// Count the characters in the line
for (int i = 0; i < line.length(); i++) {
char ch = line.charAt(i);
if (Character.isUpperCase(ch)) {
upperCaseCount++;
} else if (Character.isLowerCase(ch)) {
lowerCaseCount++;
} else if (Character.isDigit(ch)) {
digitCount++;
} else {
specialCharCount++;
}
totalChars++;
}
}

// Close file
reader.close();

// Calculate percentages
double upperCasePercentage = (double) upperCaseCount / totalChars * 100;
double lowerCasePercentage = (double) lowerCaseCount / totalChars * 100;
double digitPercentage = (double) digitCount / totalChars * 100;
double specialCharPercentage = (double) specialCharCount / totalChars * 100;

// Write results to file


BufferedWriter writer = new BufferedWriter(new FileWriter("data.txt"));
writer.write("Percentage of Uppercase characters: " + upperCasePercentage + "%\n");
writer.write("Percentage of Lowercase characters: " + lowerCasePercentage + "%\n");
writer.write("Percentage of Digits: " + digitPercentage + "%\n");
writer.write("Percentage of Special characters: " + specialCharPercentage + "%\n");
writer.close();

System.out.println("Results written to data.txt file.");

} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
}

4.In a family, Mom prepares roti for her children. Mom makes roti and stacks it up in a vessel, and
Children eats from it. The max capacity of the vessel is 10. If roti empties, Childrenwait for mom to
prepare new roti. Illustrate the given scenario using inter thread communication concept in Java
programming. [10 Marks]

import java.util.concurrent.*;

public class RotiVessel {


private final Object lock = new Object();
private int rotiCount = 0;

public void mom() throws InterruptedException {


while (true) {
synchronized (lock) {
if (rotiCount < 10) {
rotiCount++;
System.out.println("Mom prepared a roti. Roti count: " + rotiCount);
lock.notifyAll();
} else {
lock.wait();
}
}
}
}

public void children() throws InterruptedException {


while (true) {
synchronized (lock) {
if (rotiCount > 0) {
rotiCount--;
System.out.println("Child ate a roti. Roti count: " + rotiCount);
lock.notifyAll();
} else {
System.out.println("No roti available. Child is waiting.");
lock.wait();
}
}
}
}

public static void main(String[] args) {


RotiVessel vessel = new RotiVessel();

ExecutorService executorService = Executors.newFixedThreadPool(2);

executorService.submit(() -> {
try {
vessel.mom();
} catch (InterruptedException e) {
e.printStackTrace();
}
});

executorService.submit(() -> {
try {
vessel.children();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
executorService.shutdown();
}
}
5. Create a map to store Product Id and Product Cost with five sample values with keys associated
with it, like (P1, 100), (P2, 200), (P3, 300), (P4, 400) and (P5, 500). Remove the third Key and Value
pair from the Map, also update the cost of P4 value as 800. Create a new map for the recently
imported products like (P6, 600), (P7, 700), (P8, 800) and then include all these new map elements
to the existing map elements. Traverse through the Map elements using lambda expression before
modification and access the elements using iterator after modification and display all the map’s key
and value pairs. [10 Marks]

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class Main {


public static void main(String[] args) {
// Create a map to store Product Id and Product Cost
Map<String, Integer> productMap = new HashMap<>();
productMap.put("P1", 100);
productMap.put("P2", 200);
productMap.put("P3", 300);
productMap.put("P4", 400);
productMap.put("P5", 500);

// Remove the third Key and Value pair from the Map
productMap.remove("P3");

// Update the cost of P4 value as 800


productMap.put("P4", 800);

// Create a new map for the recently imported products


Map<String, Integer> newProductMap = new HashMap<>();
newProductMap.put("P6", 600);
newProductMap.put("P7", 700);
newProductMap.put("P8", 800);

// Include all these new map elements to the existing map elements
productMap.putAll(newProductMap);

// Traverse through the Map elements using lambda expression before modification
System.out.println("Map elements before modification:");
productMap.forEach((key, value) -> System.out.println(key + ": " + value));

// Access the elements using iterator after modification and display all the map’s key and value pairs
System.out.println("\nMap elements after modification:");
Iterator<Map.Entry<String, Integer>> iterator = productMap.entrySet().iterator();
while(iterator.hasNext()) {
Map.Entry<String, Integer> entry = iterator.next();
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}

Example (Map using Lambda Expression)


import java.util.*;

public class MapIterateLambdaTest {


public static void main(String[] args) {
Map<String, Integer> ranks = new HashMap<String, Integer>();
ranks.put("India", 1);
ranks.put("Australia", 2);
ranks.put("England", 3);
ranks.put("Newzealand", 4);
ranks.put("South Africa", 5);
// Iterating through
forEach using Lambda Expression
ranks.forEach((k,v) -> System.out.println("Team : " + k + ", Rank : " + v));
}
}

6. Write a program to check if two given String is Anagram of each other. Your function should
return true if two Strings are Anagram, false otherwise. A string is said to be an anagram if it
contains the same characters and same length, but in a different order, e.g. army and Mary are
anagrams.

import java.util.Arrays;

public class AnagramChecker {

public static boolean isAnagram(String s1, String s2) {


if (s1.length() != s2.length()) {
return false;
}
char[] c1 = s1.toCharArray();
char[] c2 = s2.toCharArray();
Arrays.sort(c1);
Arrays.sort(c2);
return Arrays.equals(c1, c2);
}

public static void main(String[] args) {


String s1 = "army";
String s2 = "Mary";
boolean result = isAnagram(s1.toLowerCase(), s2.toLowerCase());
if (result) {
System.out.println(s1 + " and " + s2 + " are anagrams.");
} else {
System.out.println(s1 + " and " + s2 + " are not anagrams.");
}
}
}

7. A bank account is operated by a father and his son. The account is opened with an initial deposit
of Rs. 600. Thereafter, the father deposits a random amount between Re. 1 and Rs. 200 each time,
until the account balance crosses Rs. 2,000. The son can start withdrawing the amount only if the
balance exceeds Rs. 2,000. Thereafter, the son withdraws random amount between Re. 1 and Rs.
150, until the balance goes below Rs. 500. Once the balance becomes less than Rs.500, the father
deposits amount till it crosses Rs. 2,000 and the process continues. Write a Father and Son thread
to carry out the above process. Use the multithreading concepts wait, notify, notifyall, sleep and
synchronized.

public class BankAccount {

private int balance = 600;


private boolean isWithdrawalAllowed = false;

public synchronized void fatherDeposits() {


while (balance <= 2000) {
int amount = (int) (Math.random() * 200) + 1;
balance += amount;
System.out.println("Father deposited: Rs." + amount);
if (balance > 2000) {
isWithdrawalAllowed = true;
notifyAll();
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

public synchronized void sonWithdraws() {


while (true) {
while (!isWithdrawalAllowed) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
int amount = (int) (Math.random() * 150) + 1;
balance -= amount;
System.out.println("Son withdrew: Rs." + amount);
if (balance < 500) {
isWithdrawalAllowed = false;
notifyAll();
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

public synchronized void fatherDepositsAgain() {


while (balance < 2000) {
int amount = (int) (Math.random() * 200) + 1;
balance += amount;
System.out.println("Father deposited: Rs." + amount);
if (balance > 2000) {
isWithdrawalAllowed = true;
notifyAll();
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

public class Main {

public static void main(String[] args) {


BankAccount bankAccount = new BankAccount();
Thread fatherThread = new Thread(() -> {
bankAccount.fatherDeposits();
});
Thread sonThread = new Thread(() -> {
bankAccount.sonWithdraws();
});
Thread fatherThread2 = new Thread(() -> {
bankAccount.fatherDepositsAgain();
});
fatherThread.start();
sonThread.start();
fatherThread2.start();
}
}

8. Write a Java program where the Main thread generates an array of 100 random integer and
starts two threads SumOdd and SumEven which calculates the sum of odd and even integers of the
array. The Main thread should finally display the values calculated by the two threads.[Note: The
expression Math.random() * 100 generates a real random number between 0 and 100 which can be
converted to an integer by typecasting.

class SumOdd implements Runnable {


private int[] array;

public SumOdd(int[] array) {


this.array = array;
}

public void run() {


int sum = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] % 2 != 0) {
sum += array[i];
}
}
System.out.println("Sum of odd integers: " + sum);
}
}

class SumEven implements Runnable {


private int[] array;

public SumEven(int[] array) {


this.array = array;
}

public void run() {


int sum = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] % 2 == 0) {
sum += array[i];
}
}
System.out.println("Sum of even integers: " + sum);
}
}

public class Main {


public static void main(String[] args) {
int[] array = new int[100];
for (int i = 0; i < 100; i++) {
array[i] = (int) (Math.random() * 100);
}

SumOdd sumOdd = new SumOdd(array);


SumEven sumEven = new SumEven(array);

Thread t1 = new Thread(sumOdd);


Thread t2 = new Thread(sumEven);

t1.start();
t2.start();

try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

9. (i) Write a Java program that accepts an integer N and creates a count down timer - displaying
numbers from N down to 0 one number every second.
(ii) Write an appropriate method for each of the following functionalities:
i. suspend a thread for a specified time
ii. resume a thread waiting for an object from suspended state
iii. Wait for another thread to complete its execution
iv. check whether a thread is active

public class CountDownTimer extends Thread {


private int count;

public CountDownTimer(int count) {


this.count = count;
}

public void run() {


try {
while (count >= 0) {
System.out.println(count);
count--;
Thread.sleep(1000); // suspends thread for 1 second
}
} catch (InterruptedException e) {
System.out.println("Thread interrupted");
}
}

// Method to suspend a thread for a specified time


public void suspendThread(long timeInMillis) {
try {
Thread.sleep(timeInMillis);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

// Method to resume a thread waiting for an object from suspended state


public synchronized void resumeThread() {
notify();
}

// Method to wait for another thread to complete its execution


public synchronized void waitFor(Thread t) {
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}

// Method to check whether a thread is active


public boolean isActiveThread() {
return this.isAlive();
}

public static void main(String[] args) {


int N = 10;
CountDownTimer countDownTimer = new CountDownTimer(N);
countDownTimer.start();
}
}

10. Write a program that creates Producer and Consumer threads. The producer generates 100
integer random numbers between 0 and 100 and the consumer reads and displays the number.
[Note: The expression Math.random() * 100 generates a real random number between 0 and 100
which can be converted to an integer by typecasting].

import java.util.LinkedList;

public class Main {


public static void main(String[] args) {
LinkedList<Integer> buffer = new LinkedList<>();
int maxSize = 10;

Producer producer = new Producer(buffer, maxSize);


Consumer consumer = new Consumer(buffer, maxSize);

producer.start();
consumer.start();
}
}

class Producer extends Thread {


private LinkedList<Integer> buffer;
private int maxSize;

public Producer(LinkedList<Integer> buffer, int maxSize) {


this.buffer = buffer;
this.maxSize = maxSize;
}

public void run() {


for (int i = 0; i < 100; i++) {
synchronized (buffer) {
while (buffer.size() == maxSize) {
try {
buffer.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}

int num = (int) (Math.random() * 100);


buffer.add(num);
System.out.println("Produced: " + num);

buffer.notifyAll();
}
}
}
}

class Consumer extends Thread {


private LinkedList<Integer> buffer;
private int maxSize;

public Consumer(LinkedList<Integer> buffer, int maxSize) {


this.buffer = buffer;
this.maxSize = maxSize;
}

public void run() {


while (true) {
synchronized (buffer) {
while (buffer.isEmpty()) {
try {
buffer.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}

int num = buffer.removeFirst();


System.out.println("Consumed: " + num);

buffer.notifyAll();
}
}
}
}

11. (i) What are the thread states? Name and brief any 5 functions that can change the state of a
thread in Java.
(ii) Write a program where three threads write to console through a method of a common object.
Demonstrate the impact of synchronized modifier on the method.

(i) Thread states in Java are:

New: A thread is in the new state when it is created but not yet started.
Runnable: A thread is in the runnable state when it has been started and is executing, or is ready to run
but is waiting for the processor to execute it.
Blocked/Waiting: A thread is in the blocked/waiting state when it is waiting for a lock, waiting for
input/output or waiting for some other thread to complete its execution.
Timed Waiting: A thread is in the timed waiting state when it is waiting for a specified amount of time,
such as when it calls the sleep() method or waits for I/O operations to complete.
Terminated: A thread is in the terminated state when it has completed its execution.
Five functions that can change the state of a thread in Java are:

start(): This function starts a new thread, transitioning it from the new state to the runnable state.
sleep(): This function causes the currently executing thread to sleep for a specified amount of time,
transitioning it to the timed waiting state.
join(): This function waits for the specified thread to terminate, transitioning the current thread to the
blocked/waiting state.
wait(): This function causes the current thread to wait for a notify or notifyAll signal from another thread,
transitioning it to the blocked/waiting state.
notify(): This function signals a waiting thread to wake up, transitioning it from the blocked/waiting state
to the runnable state.
(ii) Here's an example program with three threads that write to console through a method of a common
object:

public class MyObject {


public synchronized void printMessage(String message) {
System.out.println(message);
}
}

public class MyThread implements Runnable {


private MyObject myObject;
private String message;

public MyThread(MyObject myObject, String message) {


this.myObject = myObject;
this.message = message;
}

@Override
public void run() {
myObject.printMessage(message);
}
}

public class Main {


public static void main(String[] args) {
MyObject myObject = new MyObject();
MyThread thread1 = new MyThread(myObject, "Thread 1 message");
MyThread thread2 = new MyThread(myObject, "Thread 2 message");
MyThread thread3 = new MyThread(myObject, "Thread 3 message");

Thread t1 = new Thread(thread1);


Thread t2 = new Thread(thread2);
Thread t3 = new Thread(thread3);

t1.start();
t2.start();
t3.start();
}
}

12. Write a Java program that accepts 5 lines from the user and writes it to a file. The name of the
file should be passed to the program using a Command Line argument.
What are streams used for ? Mention and brief types of streams based on data type and access
mode (access to read or write).

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class WriteToFile {


public static void main(String[] args) {
if (args.length == 0) {
System.out.println("Please provide a filename as a command line argument.");
return;
}

String filename = args[0];


try {
BufferedWriter writer = new BufferedWriter(new FileWriter(filename));

Scanner scanner = new Scanner(System.in);


System.out.println("Please enter 5 lines of text:");
for (int i = 0; i < 5; i++) {
String line = scanner.nextLine();
writer.write(line);
writer.newLine();
}

writer.close();
System.out.println("File successfully written.");
} catch (IOException e) {
System.out.println("Error writing to file: " + e.getMessage());
}
}
}
13. Write a Java program that accepts two file names file1.txt and file2.txt. The contents of file1.txt
are copied to file2.txt.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class CopyFile {


public static void main(String[] args) {
if (args.length != 2) {
System.out.println("Please provide two filenames as command line arguments.");
return;
}

String inputFilename = args[0];


String outputFilename = args[1];
try {
BufferedReader reader = new BufferedReader(new FileReader(inputFilename));
FileWriter writer = new FileWriter(outputFilename);

String line;
while ((line = reader.readLine()) != null) {
writer.write(line);
writer.write(System.lineSeparator());
}

reader.close();
writer.close();
System.out.println("File successfully copied.");
} catch (IOException e) {
System.out.println("Error copying file: " + e.getMessage());
}
}
}

14. What are wild cards in a generic method? With a suitable example explain the need and usage
of a bounded wild card in a Java program.
import java.util.List;

public class BoundedWildcardExample {


public static double sumOfList(List<? extends Number> list) {
double sum = 0.0;
for (Number number : list) {
sum += number.doubleValue();
}
return sum;
}

public static void main(String[] args) {


List<Integer> integerList = List.of(1, 2, 3);
List<Double> doubleList = List.of(1.1, 2.2, 3.3);

double integerSum = sumOfList(integerList);


System.out.println("Sum of integer list: " + integerSum);

double doubleSum = sumOfList(doubleList);


System.out.println("Sum of double list: " + doubleSum);
}
}

15. Create a class that can store a generic numeric array along with methods to find the average of
elements in the numeric array and compare the averages of two different generic array objects.

public class NumericArray<T extends Number> {


private T[] array;

public NumericArray(T[] array) {


this.array = array;
}

public double average() {


double sum = 0.0;
for (T element : array) {
sum += element.doubleValue();
}
return sum / array.length;
}

public static <T extends Number> boolean compareAverages(NumericArray<T> array1,


NumericArray<T> array2) {
double avg1 = array1.average();
double avg2 = array2.average();
return avg1 == avg2;
}
}

16. With an example explain creation of new generic and non generic classes deriving an existing
generic class.
public class Box<T> {
private T item;

public Box(T item) {


this.item = item;
}

public T getItem() {
return item;
}

public void setItem(T item) {


this.item = item;
}
}
Now, we can create a new generic class ColoredBox that extends the Box class and adds a color property
to it.

//2
public class ColoredBox<T> extends Box<T> {
private String color;

public ColoredBox(T item, String color) {


super(item);
this.color = color;
}

public String getColor() {


return color;
}

public void setColor(String color) {


this.color = color;
}
}
Here, the ColoredBox class is a generic class with a type parameter T that is inherited from the Box class.
It adds an additional property color to the box.

We can also create a non-generic class StringBox that extends the Box class and restricts the type
parameter to String only.

//3
public class StringBox extends Box<String> {
public StringBox(String item) {
super(item);
}

public void printUpperCase() {


System.out.println(getItem().toUpperCase());
}
}
Here, the StringBox class is a non-generic class that extends the Box class with a type parameter String. It
adds a method printUpperCase that prints the item in uppercase.

//4
Box<Integer> intBox = new Box<>(10);
ColoredBox<String> colorBox = new ColoredBox<>("Hello", "Red");
StringBox strBox = new StringBox("Java");

System.out.println(intBox.getItem()); // Output: 10
System.out.println(colorBox.getItem() + " " + colorBox.getColor()); // Output: Hello Red
strBox.printUpperCase(); // Output: JAVA

17. Write a Java program to check whether the input string is a valid date in DD/MM/YYYY
format. Also validate the values of DD, MM, YYYY. (DD from 1 to 31, MM from 1 to 12, Year
should be greater than 2000).

import java.util.Scanner;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;

public class DateValidator {

public static boolean isValidDate(String input) {


// Define the expected date format
DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("dd/MM/yyyy");
try {
// Try to parse the input string into a LocalDate object
LocalDate date = LocalDate.parse(input, dateFormat);
// Check if the year is greater than 2000
if (date.getYear() < 2000) {
return false;
}
// Check if the month is between 1 and 12
if (date.getMonthValue() < 1 || date.getMonthValue() > 12) {
return false;
}
// Check if the day is between 1 and 31
if (date.getDayOfMonth() < 1 || date.getDayOfMonth() > 31) {
return false;
}
// If all checks pass, the input string is a valid date
return true;
} catch (DateTimeParseException e) {
// If parsing fails, the input string is not a valid date
return false;
}
}

public static void main(String[] args) {


// Create a Scanner object to read input from the user
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a date in DD/MM/YYYY format: ");
String input = scanner.nextLine();
if (isValidDate(input)) {
System.out.println("The input string is a valid date.");
} else {
System.out.println("The input string is not a valid date.");
}
scanner.close();
}

18. a.What is the syntax of lambda expression? How lambda expressions are used in a Java
programming language?
b. Create objects for addition, subtraction, multiplication, division from the following functional
interface using lambda expressions. (Ex: addition.op(a, b) should return the sum of numbers a and
b)
interface Binary
{
int op(int, int);
}

interface Binary {
int op(int a, int b);
}

public class Calculator {


public static void main(String[] args) {
Binary addition = (a, b) -> a + b;
Binary subtraction = (a, b) -> a - b;
Binary multiplication = (a, b) -> a * b;
Binary division = (a, b) -> a / b;

int a = 10, b = 5;
System.out.println("Addition: " + addition.op(a, b));
System.out.println("Subtraction: " + subtraction.op(a, b));
System.out.println("Multiplication: " + multiplication.op(a, b));
System.out.println("Division: " + division.op(a, b));
}
}

19. How lambda expressions can be used in a function call arguments? Explain with an example.

import java.util.Arrays;
import java.util.List;

public class LambdaExample {


public static void main(String[] args) {
List<String> names = Arrays.asList("John", "Mary", "Peter", "Jane");
names.forEach(name -> System.out.println("Hello, " + name + "!"));
}
}

20. With suitable example demonstrate how lambda expressions can be used to create objects for a
generic interface.

interface Transformer<T, R> {


R transform(T input);
}

public class LambdaExample {


public static void main(String[] args) {
Transformer<String, Integer> lengthTransformer = s -> s.length();

String input = "Hello, world!";


Integer output = lengthTransformer.transform(input);

System.out.println("Length of '" + input + "' is " + output);


}
}

21. Write a java program, create two threads with generic class method
Output should be

S.NO. NAME (String) AGE (Float) SALARY


(Int) (Double)

1 VASANTH 26.6 1250000.00

2 SENTHIL 37.5 1350000.00

3 GANESH 45.3 5600000.00

class Employee<T, U, V, W> {


private T id;
private U name;
private V age;
private W salary;

public Employee(T id, U name, V age, W salary) {


this.id = id;
this.name = name;
this.age = age;
this.salary = salary;
}

public void printData() {


System.out.printf("%-10s%-15s%-10s%-10s\n", id, name, age, salary);
}
}

class EmployeeThread<T, U, V, W> extends Thread {


private Employee<T, U, V, W> employee;

public EmployeeThread(Employee<T, U, V, W> employee) {


this.employee = employee;
}

public void run() {


employee.printData();
}
}

public class ThreadExample {


public static void main(String[] args) {
Employee<Integer, String, Float, Double> employee1 = new Employee<>(1, "Vasanth",
26.6f, 1250000.00);
Employee<Integer, String, Float, Double> employee2 = new Employee<>(2, "Senthil",
37.5f, 1350000.00);
Employee<Integer, String, Float, Double> employee3 = new Employee<>(3, "Ganesh",
45.3f, 5600000.00);

System.out.printf("%-10s%-15s%-10s%-10s\n", "S.NO.", "NAME", "AGE", "SALARY");

EmployeeThread<Integer, String, Float, Double> thread1 = new


EmployeeThread<>(employee1);
EmployeeThread<Integer, String, Float, Double> thread2 = new
EmployeeThread<>(employee2);
EmployeeThread<Integer, String, Float, Double> thread3 = new
EmployeeThread<>(employee3);

thread1.start();
thread2.start();
thread3.start();
}
}

22. Write a Java program to demonstrate lambda expressions to implement a user defined
functional interface with multiple parameters.

@FunctionalInterface
interface Calculator<T, U, R> {
R calculate(T a, U b);
}
public class LambdaExample {
public static void main(String[] args) {
// Implementing the functional interface using a lambda expression
Calculator<Integer, Integer, Integer> add = (a, b) -> a + b;
Calculator<Integer, Integer, Integer> subtract = (a, b) -> a - b;
Calculator<Integer, Integer, Integer> multiply = (a, b) -> a * b;
Calculator<Integer, Integer, Double> divide = (a, b) -> (double) a / b;

// Testing the lambda expressions


System.out.println("Addition: " + add.calculate(10, 5));
System.out.println("Subtraction: " + subtract.calculate(10, 5));
System.out.println("Multiplication: " + multiply.calculate(10, 5));
System.out.println("Division: " + divide.calculate(10, 5));
}
}

23. Write a Java code for Creating Thread with Lambda Expression

public class ThreadLambdaExample {


public static void main(String[] args) {
// Create a new thread using a lambda expression
Thread thread = new Thread(() -> {
for (int i = 1; i <= 10; i++) {
System.out.println("Thread: " + Thread.currentThread().getName() + " - " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});

// Start the thread


thread.start();

// Wait for the thread to finish


try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}

// Print a message when the thread is finished


System.out.println("Thread: " + thread.getName() + " finished.");
}
}

24. Write a Java code for byte array-to-string constructor using java string class

public class ByteArrayToStringExample {


public static void main(String[] args) {
// Create a byte array
byte[] byteArray = {72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33};

// Convert the byte array to a string using the byte array-to-string constructor
String str = new String(byteArray);

// Print the string


System.out.println(str);
}
}

25. Write a Java program to demonstrate String Buffer and StringBuilder Classes

public class StringBufferStringBuilderExample {


public static void main(String[] args) {
// Create a new StringBuffer object
StringBuffer stringBuffer = new StringBuffer("Hello");

// Append a string to the buffer


stringBuffer.append(" World!");

// Print the contents of the buffer


System.out.println("StringBuffer: " + stringBuffer.toString());

// Create a new StringBuilder object


StringBuilder stringBuilder = new StringBuilder("Java");

// Append a string to the builder


stringBuilder.append(" is");
stringBuilder.append(" awesome!");

// Print the contents of the builder


System.out.println("StringBuilder: " + stringBuilder.toString());
}
}

26. Write Java program to read input should be “SIVAKUMAR – SCOPE - VIT” from java
console window, print in the console window, simultaneously write in the text file named as
“SCOPE.txt”.
A. Write a Java program to read contents from file into byte array .
B. Write a Java program to read a file content line by line “SCOPE.txt”.
C. Write a Java program to read a plain text file “SCOPE.txt”.
D. Write a java program to read a file “SCOPE.txt” line by line and store it into a
variable.
E. Write a Java program to store text file content line by line into an array.

//A. Java program to read contents from file into byte array:

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class FileToByteArray {


public static void main(String[] args) {
File file = new File("SCOPE.txt");
byte[] bytes = new byte[(int) file.length()];
try (InputStream inputStream = new FileInputStream(file)) {
inputStream.read(bytes);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("File contents as byte array: " + new String(bytes));
}
}
//B. Java program to read a file content line by line:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadFileLineByLine {


public static void main(String[] args) {
String fileName = "SCOPE.txt";
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
String line = reader.readLine();
while (line != null) {
System.out.println(line);
line = reader.readLine();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
//C. Java program to read a plain text file:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadPlainTextFile {


public static void main(String[] args) {
String fileName = "SCOPE.txt";
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
StringBuilder stringBuilder = new StringBuilder();
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line);
line = reader.readLine();
}
System.out.println("File contents: " + stringBuilder.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
//D. Java program to read a file line by line and store it into a variable:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadFileIntoVariable {


public static void main(String[] args) {
String fileName = "SCOPE.txt";
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
String line = reader.readLine();
while (line != null) {
stringBuilder.append(line);
line = reader.readLine();
}
} catch (IOException e) {
e.printStackTrace();
}
String fileContents = stringBuilder.toString();
System.out.println("File contents stored in variable: " + fileContents);
}
}
//E. Java program to store text file content line by line into an array:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class StoreFileContentIntoArray {


public static void main(String[] args) {
String fileName = "SCOPE.txt";
List<String> lines = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
String line = reader.readLine();
while (line != null) {
lines.add(line);
line = reader.readLine();
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("File contents stored in array: " + lines);
}
}

27. Write a java program, Set a Name (SCOPE, SITE) to the thread and fetching name of current
thread in Java using following ways
A. Creating the thread and Passing the thread’s name (Direct method)
B. Using setName() method of Thread class (Indirect Method)

//A. Creating the thread and passing the thread's name (Direct method):

public class ThreadNameDemo1 {


public static void main(String[] args) {
Thread thread1 = new Thread("SCOPE");
Thread thread2 = new Thread("SITE");

System.out.println("Name of thread1: " + thread1.getName());


System.out.println("Name of thread2: " + thread2.getName());
}
}

//B. Using setName() method of Thread class (Indirect method):

public class ThreadNameDemo2 {


public static void main(String[] args) {
Thread thread1 = new Thread();
Thread thread2 = new Thread();

thread1.setName("SCOPE");
thread2.setName("SITE");

System.out.println("Name of thread1: " + thread1.getName());


System.out.println("Name of thread2: " + thread2.getName());
}
}

28. Write a Java program to iterate through all elements in a array list.
import java.util.*;
public class Exercise2 {
public static void main(String[] args) {
// Creae a list and add some colors to the list
List<String> list_Strings = new ArrayList<String>();
list_Strings.add("Red");
list_Strings.add("Green");
list_Strings.add("Orange");
list_Strings.add("White");
list_Strings.add("Black");
// Print the list
for (String element : list_Strings) {
System.out.println(element);
}
}
}

29. Java program to show multiple type parameters in Generics Class

public class Pair<T, U> {


private T first;
private U second;

public Pair(T first, U second) {


this.first = first;
this.second = second;
}

public T getFirst() {
return first;
}

public void setFirst(T first) {


this.first = first;
}

public U getSecond() {
return second;
}

public void setSecond(U second) {


this.second = second;
}

public String toString() {


return "(" + first + ", " + second + ")";
}

public static void main(String[] args) {


Pair<String, Integer> p1 = new Pair<>("John", 25);
Pair<Double, Double> p2 = new Pair<>(3.14, 2.71);

System.out.println(p1);
System.out.println(p2);
}
}

30. Write a Java program to show working of user defined generic method using Element
parameter with generic interface.

interface MyInterface<E> {
void printElement(E element);
}

public class MyClass {


public static <E> void printArray(E[] arr, MyInterface<E> myInterface) {
for (E element : arr) {
myInterface.printElement(element);
}
}

public static void main(String[] args) {


Integer[] intArr = {1, 2, 3, 4, 5};
String[] strArr = {"Hello", "World", "Java", "Program"};

MyInterface<Integer> intInterface = new MyInterface<Integer>() {


public void printElement(Integer element) {
System.out.print(element + " ");
}
};

MyInterface<String> strInterface = new MyInterface<String>() {


public void printElement(String element) {
System.out.print(element + " ");
}
};

System.out.print("Integer Array: ");


printArray(intArr, intInterface);

System.out.print("\nString Array: ");


printArray(strArr, strInterface);
}
}

You might also like