Untitled
Untitled
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 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);
}
}
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.*;
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.*;
// 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;
} 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.*;
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;
// Remove the third Key and Value pair from the Map
productMap.remove("P3");
// 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());
}
}
}
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;
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.
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.
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
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;
producer.start();
consumer.start();
}
}
buffer.notifyAll();
}
}
}
}
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.
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:
@Override
public void run() {
myObject.printMessage(message);
}
}
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;
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;
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;
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.
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 T getItem() {
return item;
}
//2
public class ColoredBox<T> extends Box<T> {
private String color;
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);
}
//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;
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);
}
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;
20. With suitable example demonstrate how lambda expressions can be used to create objects for a
generic interface.
21. Write a java program, create two threads with generic class method
Output should be
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;
23. Write a Java code for Creating Thread with Lambda Expression
24. Write a Java code for byte array-to-string constructor using java string class
// Convert the byte array to a string using the byte array-to-string constructor
String str = new String(byteArray);
25. Write a Java program to demonstrate String Buffer and StringBuilder Classes
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;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
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):
thread1.setName("SCOPE");
thread2.setName("SITE");
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);
}
}
}
public T getFirst() {
return first;
}
public U getSecond() {
return second;
}
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);
}