0% found this document useful (0 votes)
81 views56 pages

Java Record

Uploaded by

23102208
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)
81 views56 pages

Java Record

Uploaded by

23102208
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/ 56

R.M.K.

ENGINEERING COLLEGE
(An Autonomous Institution)
R.S.M. Nagar, Kavaraipettai -601 206

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

22CS305
Advanced Java Programming Laboratory

LAB MANUAL
R2022

ACADEMIC YEAR: 2024-25

3rd SEMESTER

B.E. COMPUTER SCIENCE AND ENGINEERING


R.M.K. ENGINEERING COLLEGE
(An Autonomous Institution)
R.S.M. Nagar, Kavaraipettai -601 206

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

22CS305
Advanced Java Programming Laboratory

LAB MANUAL
R2022

2024-25 ODD SEMESTER

B.E. COMPUTER SCIENCE AND ENGINEERING

Prepared by Approved by Approved by

Dr. S.D. Lalitha,ASP/CSE Dr.T. Sethukarasi Dr. K. A. Mohamed Junaid

Ms. A. Jasmine Gilda, AP/CSE Professor & Head / CSE Principal

Ms. P. Baby Shamini, AP/CSE

Mr. J. Joel, AP/CSE


R.M.K. ENGINEERING COLLEGE
(An Autonomous Institution)
R.S.M. Nagar, Kavaraipettai -601 206

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


Vision
To evolve as a Centre of Academic Excellence and Advanced Research in the field of Computer
Science and Engineering and develop professionals who can meet with the societal issues.
Mission
M1: To provide a good environment with latest technological infrastructure facilities, teaching-
learning ambience and interaction with industry in the area of Computer Science and Engineering.
M2: To develop graduates of world class technical competence, entrepreneurial skill and to encourage
for higher education in the area of Computer Science and Engineering, with necessary skills to solve
real world problems.
M3:To inculcate graduates with high social responsibility, right attitude, discipline and an inclination
towards offering their professional expertise in serving the society.
Programme Educational Objectives
PEO 1. Apply the principles and practices of Computer Science and Engineering encompassing
Mathematics, Science and Basic Engineering and to employ the modern engineering tools effectively
in their profession with their world class technical competence.
PEO 2. Possess expertise to function as members of multi-disciplinary teams and implement software
technology solutions for real world problems of international standards and will be achievers at global
level.
PEO 3. Excel in the field of software industry or in higher studies endowed with the spirit of
innovation and entrepreneurship by evolving their professional knowledge on a lifelong basis.
PEO 4. Practice the profession with ethics, integrity, leadership and social responsibility with a good
insight of the changing societal needs for the benefit of humanity.
Program Specific Outcome
PSO 1: Apply knowledge acquired from the basic hardware design and software core areas of
Computer Science and Engineering for solving real world problems.
PSO 2: Apply cutting edge technologies and strong analytical skills to develop quality software in
scientific and business applications for the betterment of society and Industry.
PSO 3: Employ modern computer languages, environments and platforms in creating innovative
career paths to be an entrepreneur and with a zeal for higher studies.
R.M.K. ENGINEERING COLLEGE
(An Autonomous Institution)

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


SYLLABUS

UNIT I COLLECTIONS FRAMEWORK AND UTILITY CLASSES 9+6


Introduction to Collections Framework - Collection Interface- Methods in Collection Interface -
Iterable and Iterator Interfaces - List Interface- ArrayList - LinkedList - Set Interface - HashSet-
LinkedHashSet - TreeSet - Map Interface - HashMap -LinkedHashMap- TreeMap - Queue
Interface -PriorityQueue - Deque Interface - Utility Classes.
List of Experiments
1. Write a program that measures the time taken for insertion, deletion, and search
operations on ArrayList, LinkedList, HashSet, and TreeSet for varying sizes of input
data.
2. Implement a custom data structure that combines features of a list and a set.
3. Write a Java program to create a HashMap where the keys are strings, and the values
are integers Add five key-value pairs to the map. Print all the keys and values in the
map. Remove an entry by key. Update the value associated with a specific key. Check

if the map contains a specific key and a specific value.

UNIT II I/O OPERATIONS, SERIALIZATION, AND DATE HANDLING 9+6


Date – Calendar – Comparable interface – Observer Interface – Streams - Types of Streams - The
Byte-stream I/O hierarchy - Character Stream Hierarchy – Random Access File class – the java.io.
Console Class – Serialization – Dates - Numbers, and Currency - Working with Dates - Numbers
and Currencies.
List of Experiments
1. Create a class representing a complex object with nested data structures. Serialize the object to a
file, then deserialize it back and verify that the object remains intact.
2. Write a program that formats dates and currencies according to different locales.
3. Implement a java program that allows users to open a text file, navigate through it using random
access, insert, delete, and modify text at specific positions within the file.
UNIT III STREAM API AND FUNCTIONAL PROGRAMMING PARADIGMS 9+6

Overview of Stream API - Importance of Stream API in Java 8 and Beyond – Functional
Programming Concepts - Creating Streams - Stream Interface Methods - Stream Operations -
Intermediate Filtering (filter)-Mapping (map, flatMap)-Sorting (sorted)-Distinct (distinct) - Limit
and Skip (limit, skip) - Terminal Operations -Collecting Results (collect) - Reducing and
Summarizing (reduce, summaryStatistics)-Iterating (forEach) - Matching and Finding (anyMatch,
allMatch, noneMatch, findFirst, findAny) -Counting (count).
List of Experiments
1. Write a program that performs stream operations like filtering, mapping, and reducing.
2. Create an infinite stream generator that generates prime numbers. Implement methods
to check for primality and generate the next prime number.
3. Write a program that reads a text file containing sentences. Tokenize each sentence into words,
filter out stopwords, and print the remaining words.
R.M.K. ENGINEERING COLLEGE
(An Autonomous Institution)

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


SYLLABUS

ADVANCED STRING PROCESSING, OBJECT SERIALIZATION,


UNIT IV 9+6
AND I/O TECHNIQUES
String Tokenizer – Parsing - Tokenizing and Formatting - Locating Data via Pattern Matching,
Tokenizing - Object Serialization - Serializable Interface - Writing and Reading Serializable
Objects -Transient Keyword- SerialVersionUID - Advanced I/O - Piped Streams
(PipedInputStream and PipedOutputStream) – SequenceInputStream -PushbackInputStream and
PushbackReader.
List of Experiments
1. Write a program that reads a text file and tokenizes it into sentences using the
StringTokenizer class.
2. Create a class hierarchy representing different types of objects (e.g., Person,
Employee). Serialize instances of these classes to a file using object serialization.
3. Implement a program that uses advanced I/O techniques like PipedInputStream,
1. PipedOutputStream, SequenceInputStream, and PushbackInputStream.
UNIT V ADVANCED STREAM FEATURES AND REGULAR EXPRESSIONS 9+6
Importance and Use Cases of Advanced Stream Features - Creating Custom Streams -Stream
Generators (Stream.generate, Stream.iterate) - Infinite Streams - Using Spliterators – Advanced
Stream Operations - FlatMapping - Chaining Stream Operations - Stream Peeking (peek) -
Advanced Filtering Techniques - Introduction to Regular Expressions - Character Classes -
Quantifiers - Pattern Matching - Groups and Capturing - Regex in Java - java.util.regex Package
Pattern Class - Matcher Class - String Manipulation with Regex - Splitting Strings - Replacing
Text (replaceAll, replaceFirst) - Replacing with Backreferences.
List of Experiments
1. Implement custom stream generators using Stream.generate and Stream.iterate
methods.
2. Write a program that demonstrates advanced stream operations like flatMapping,
chaining stream operations, and peeking.
3. Develop a program that utilizes regular expressions to perform string manipulation
tasks such as splitting strings, replacing text, and extracting specific patterns.

TOTAL: 45+30=75 PERIODS


R.M.K. ENGINEERING COLLEGE
(An Autonomous Institution)
R.S.M. Nagar, Kavaraipettai -601 206

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


22CS202 – JAVA PROGAMMING SYLLABUS

OBJECTIVES

The Course will enable learners to:

• Gain a comprehensive understanding of the Java Collections Framework and its various
interfaces and implementations.

• Learn the details of Java I/O streams and utility classes for managing dates, numbers, and
currencies.

• Develop a thorough understanding of the Stream API introduced in Java 8 and its various
operations.

• Explore advanced object serialization and string tokenizing techniques, including pattern
matching with regular expressions.

• Understand advanced Stream API features and gain proficiency in using regular expressions
for text processing.

OUTCOMES

At the end of this course, the students will be able to:

CO1: Utilize the Java Collections Framework to solve complex data structure problems.
CO2: Demonstrate proficiency in Java I/O operations and manage data efficiently.
CO3: Learn to utilize the Stream API for complex data processing by applying functional
programming techniques.
CO4: Understand and implement advanced object serialization techniques.
CO5: Effectively use regular expressions for advanced text processing tasks.
CO6: Build simple applications using advanced java programming concepts.
Ex. No. Date Title Pg.no.
Unit I : 1 Basic Operations On Different Data Structures Arraylist,
Linkedlist, Hashset And Treeset.

2 Implement a custom data structure that combines features of a


list and a set.

A Java program to create a HashMap.


3

Unit II : 1 Complex Object with Nested Data Structures.

2 Formatting dates and currencies.

3 Implement A Java Program To Do File Operations

Unit III : 1 Stream Operations - Filtering, Mapping, And Reducing.

2 Stream Generator For Prime Numbers.

3 String Tokenize and Filter using Stream API.

Unit IV : 1 Read And Write Using StringTokenizer Class

Object Serialization
2
3 Implement a program that uses advanced I/O techniques
Implement Custom Stream Generators Using Stream.Generate
Unit V : 1 And Stream.Iterate Methods
2 Advanced Stream Operations

3 Regular Expressions
Unit I
Ex 1: Basic Operations On Different Data Structures Arraylist, Linkedlist, Hashset And Treeset

Single File Programming Question


writing a Java program to perform basic operations on different data structures: ArrayList, LinkedList, Hashset
and Treeset.
Input format :
First line: An integer n representing the number of different sizes to test.
Next n lines: Each line contains an integer size, which specifies the number of integers to follow.
For each size: size integers follow, representing the integers to be used in operations.

Output format :
For each size, print the data structure type and the results of the operations:
• Inserting elements: Print the list/set after all elements have been inserted.
• Searching elements: Print whether each element was found or not.
• Deleting elements: Print the list/set after all elements have been deleted.

Sample test cases :


Input 1 :
1
4
1234
Output 1 :
Testing with size: 4
Enter 4 integers:
ArrayList:
Inserting elements:
[1, 2, 3, 4]
Searching elements:
1 found
2 found
3 found
4 found
Deleting elements:
[]
LinkedList:
Inserting elements:
[1, 2, 3, 4]
Searching elements:
1 found
2 found
3 found
4 found
Deleting elements:
[]
HashSet:
Inserting elements:
[1, 2, 3, 4]
Searching elements:
1 found
2 found
3 found
4 found
Deleting elements:
[]
TreeSet:
Inserting elements:
[1, 2, 3, 4]
Searching elements:
1 found
2 found
3 found
4 found
Deleting elements:
[]
Input 2 :
2
34
44 33 22
11 22 33 44
Output 2 :
Testing with size: 3
Enter 3 integers:
ArrayList:
Inserting elements:
[44, 33, 22]
Searching elements:
44 found
33 found
22 found
Deleting elements:
[]
LinkedList:
Inserting elements:
[44, 33, 22]
Searching elements:
44 found
33 found
22 found
Deleting elements:
[]
HashSet:
Inserting elements:
[33, 22, 44]
Searching elements:
44 found
33 found
22 found
Deleting elements:
[]
TreeSet:
Inserting elements:
[22, 33, 44]
Searching elements:
44 found
33 found
22 found
Deleting elements:
[]
Testing with size: 4
Enter 4 integers:
ArrayList:
Inserting elements:
[11, 22, 33, 44]
Searching elements:
11 found
22 found
33 found
44 found
Deleting elements:
[]
LinkedList:
Inserting elements:
[11, 22, 33, 44]
Searching elements:
11 found
22 found
33 found
44 found
Deleting elements:
[]
HashSet:
Inserting elements:
[33, 22, 11, 44]
Searching elements:
11 found
22 found
33 found
44 found
Deleting elements:
[]
TreeSet:
Inserting elements:
[11, 22, 33, 44]
Searching elements:
11 found
22 found
33 found
44 found
Deleting elements:
[]

Algorithm

1. Input Handling:
o Read an integer n representing the number of different sizes to test.
o For each size:
▪ Read the integer size size which specifies the number of integers that will follow.
▪ Read size integers into a list.
2. Processing Each Data Structure:
o For each data structure (ArrayList, LinkedList, HashSet, TreeSet):
1. Insertion:
▪ Insert the integers into the data structure.
▪ Print the state of the data structure after insertion.
2. Searching:
▪ For each integer, check if it is present in the data structure.
▪ Print whether each element was found or not.
3. Deletion:
▪ Clear the data structure.
▪ Print the state of the data structure after deletion.
3. Output:
o Print the results as specified in the output format.
Pseudocode

BEGIN
READ n

FOR i FROM 1 TO n DO
PRINT "Testing with size: " + size
READ size
CREATE a list `elements` to store the size integers

FOR j FROM 1 TO size DO


READ integer
ADD integer to `elements`

DECLARE data structures: ArrayList, LinkedList, HashSet, TreeSet

FOR each data structure in [ArrayList, LinkedList, HashSet, TreeSet] DO


PRINT data structure type

// Inserting elements
FOR each integer in `elements` DO
INSERT integer into the data structure
PRINT the data structure

// Searching elements
FOR each integer in `elements` DO
IF integer is found in the data structure THEN
PRINT integer + " found"
ELSE
PRINT integer + " not found"

// Deleting elements
CLEAR the data structure
PRINT the data structure

END FOR
END
EX 2: Implement A Custom Data Structure That Combines Features Of A List And A Set
Single File Programming Question
You have a Java program that manages a custom data structure called UniqueList. This data structure behaves
like a combination of a list and a set, ensuring all elements are unique while maintaining their insertion order.
Input format :
Input strings are added and removed them to the "UniqueList" and Input an integer to specify the index for
retrieving the element from the "UniqueList".The input terminates when the user types "done".
Output format :
The output of the program is String itself, After entering "done", the program prints the contents of the list.
Sample test cases :
Input 1 :
Red
white
Blue
done
black
done
1
Output 1 :
Red
Added: Red
white
Added: white
Blue
Added: Blue
done
UniqueList: [Red, white, Blue]
Element not found: black
UniqueList after removals: [Red, white, Blue]
Element at index 1: white
Algorithm
1. Initialization:
o Create a custom data structure called UniqueList, which is a list that maintains unique elements
in their order of insertion.
2. Input Handling:
o Continuously read input strings from the user until the user types "done".
o For each input:
▪ If the input is a string, check if the string is already in the UniqueList.
▪ If not, add the string to the UniqueList and print a message confirming the
addition.
▪ If the input is "done", print the contents of the UniqueList.
▪ If the input is an integer, attempt to retrieve the element at that index from the
UniqueList and print the element.
▪ If the input is a string and does not match any current element in UniqueList, print a
message stating the element was not found and that no removal occurred.
3. Edge Cases:
o Handle cases where an integer input is out of bounds of the UniqueList.
o Handle cases where a string to be removed is not present in the UniqueList
Pseudocode

BEGIN
INITIALIZE UniqueList as an empty list

WHILE true DO
READ input from the user

IF input is "done" THEN


PRINT "UniqueList: " + UniqueList
BREAK

ELSE IF input is an integer THEN


PARSE input as an integer index
IF index is valid THEN
PRINT "Element at index " + index + ": " + UniqueList[index]
ELSE
PRINT "Index out of bounds"

ELSE IF input is a string THEN


IF input is in UniqueList THEN
REMOVE input from UniqueList
PRINT "Element not found: " + input
PRINT "UniqueList after removals: " + UniqueList
ELSE
ADD input to UniqueList
PRINT "Added: " + input

END
EX3: A Java Program To Create A HashMap
Single File Programming Question
Write a Java program to create a HashMap where the keys are strings, and the values are integers Add five
key-value pairs to the map. Print all the keys and values in the map. Remove an entry by key. Update the value
associated with a specific key. Check if the map contains a specific key and a specific value.
Input format :
Get the 5 key value pairs and enter a key to remove,update and check the value.
Output format :
The program outputs whether the key and value is found.
Sample test cases :
Input 1 :
M
10
N
20
O
30
P
40
Q
50
R
S
20
T
505
Output 1 :

Initial map:
P : 40
Q : 50
M : 10
N : 20
O : 30
P : 40
Q : 50
M : 10
N : 20
O : 30
P : 40
Q : 50
S : 20
M : 10
N : 20
O : 30
The map does not contain the key 'T'.
The map does not contain the value 505.
Algorithm
1. Initialization:
o Create a HashMap<String, Integer> to store the key-value pairs.
2. Input Handling:
o Read 5 key-value pairs (string-integer pairs) from the user and add them to the HashMap.
3. Output Initial Map:
o Print all keys and values in the HashMap.
4. Key Removal:
o Read a key from the user to be removed from the HashMap.
o Remove the key and print the updated map.
5. Update Value:
o Read a key and a new value from the user.
o Update the value associated with the key and print the updated map.
6. Check for Specific Key and Value:
o Read a key to check if it exists in the HashMap.
o Print whether the key is found.
o Read a value to check if it exists in the HashMap.
o Print whether the value is found.
Pseudocode
BEGIN
INITIALIZE HashMap<String, Integer> map

// Step 1: Add 5 key-value pairs to the map


FOR i FROM 1 TO 5 DO
READ key as string
READ value as integer
PUT key, value INTO map

// Step 2: Print all key-value pairs in the map


PRINT "Initial map:"
FOR each entry in map DO
PRINT entry.key + " : " + entry.value

// Step 3: Remove an entry by key


READ keyToRemove as string
REMOVE keyToRemove from map
PRINT "Map after removing " + keyToRemove + ":"
FOR each entry in map DO
PRINT entry.key + " : " + entry.value

// Step 4: Update the value associated with a specific key


READ keyToUpdate as string
READ newValue as integer
IF keyToUpdate is in map THEN
UPDATE map[keyToUpdate] with newValue
PRINT "Map after updating " + keyToUpdate + ":"
FOR each entry in map DO
PRINT entry.key + " : " + entry.value
ELSE
PRINT "The key " + keyToUpdate + " does not exist in the map."

// Step 5: Check if the map contains a specific key


READ keyToCheck as string
IF map.containsKey(keyToCheck) THEN
PRINT "The map contains the key '" + keyToCheck + "'."
ELSE
PRINT "The map does not contain the key '" + keyToCheck + "'."

// Step 6: Check if the map contains a specific value


READ valueToCheck as integer
IF map.containsValue(valueToCheck) THEN
PRINT "The map contains the value " + valueToCheck + "."
ELSE
PRINT "The map does not contain the value " + valueToCheck + "."

END
Unit 2:
Ex 1: Complex Object with Nested Data Structures
Single File Programming Question
Problem description:
Create a Java program that allows users to input details of students in a specific format, serializes this data into
a byte array, and then deserializes it back to verify the integrity of the data.
Implement a StudentDatabase class that contains nested Student objects.
Each Student should have attributes for name (String), age (int), and courses (List of Strings).
The program should allow users to input student details in the format: "Name", Age, "Course1,Course2,..."
(e.g., "John Doe", 20, "Math,Science").
Use Scanner to read input from the user and split the input correctly, handling commas within quoted sections
of the input.
Serialize the StudentDatabase object into a byte array using Java serialization.
Deserialize the byte array back into a StudentDatabase object and print out the details of each student to verify
that the deserialization was successful.
Handle any potential exceptions that may occur during serialization and deserialization.
Input format :
Input consists of Name, Age & Courses
Example:-
"John Doe", 25, "Full stack, Cloud computing"
Output format :
Student{name='John Doe', age=25, courses=[ "Full stack, Cloud computing]}

Sample test cases :


Input 1 :
"Test",35,"Data science, Cloud"
Output 1 :
Student{name='Test', age=35, courses=[Data science, Cloud]}
Input 2 :
"Ram",67,"DevOps, CyberSecurity, Data Science, Java & Python, C++, C#, Ruby"
Output 2 :
Student{name='Ram', age=67, courses=[DevOps, CyberSecurity, Data Science, Java & Python, C++, C#,
Ruby]}
Algorithm
1. Define the Student Class:
o The Student class will contain:
▪ A String for the name.
▪ An int for the age.
▪ A List<String> for the courses.
2. Define the StudentDatabase Class:
o The StudentDatabase class will contain:
▪ A List<Student> to store multiple Student objects.
▪ Methods to add a student to the list, serialize the list, and deserialize it.
3. Input Parsing:
o Use Scanner to read input from the user.
o The input will be in the format "Name", Age, "Course1,Course2,...".
o Split the input based on commas, handling commas inside quotes correctly using regex.
4. Serialization:
o Serialize the StudentDatabase object into a byte array using Java's ObjectOutputStream.
5. Deserialization:
o Deserialize the byte array back into a StudentDatabase object using ObjectInputStream.
o Verify the integrity of the data by printing out the details of each student.
6. Exception Handling:
o Handle exceptions that may occur during serialization and deserialization.

Pseudocode

CLASS Student IMPLEMENTS Serializable


PRIVATE String name
PRIVATE int age
PRIVATE List<String> courses

CONSTRUCTOR Student(String name, int age, List<String> courses)


INITIALIZE name, age, courses

OVERRIDE toString() : String


RETURN "Student{name='" + name + "', age=" + age + ", courses=" + courses + "}"

CLASS StudentDatabase IMPLEMENTS Serializable


PRIVATE List<Student> students = new ArrayList<>()

METHOD addStudent(Student student)


ADD student TO students

METHOD serialize() : byte[]


TRY
CREATE ByteArrayOutputStream byteStream
CREATE ObjectOutputStream objStream = new ObjectOutputStream(byteStream)
WRITE students TO objStream
RETURN byteStream.toByteArray()
CATCH IOException e
PRINT "Serialization error: " + e.getMessage()

METHOD deserialize(byte[] data) : StudentDatabase


TRY
CREATE ByteArrayInputStream byteStream = new ByteArrayInputStream(data)
CREATE ObjectInputStream objStream = new ObjectInputStream(byteStream)
RETURN (StudentDatabase) objStream.readObject()
CATCH IOException | ClassNotFoundException e
PRINT "Deserialization error: " + e.getMessage()

METHOD main(String[] args)


CREATE Scanner scanner = new Scanner(System.in)
CREATE StudentDatabase database = new StudentDatabase()

PRINT "Enter student details (type 'done' when finished):"

WHILE true
READ input from scanner
IF input equals "done"
BREAK

PARSE input using regex to handle commas within quotes


SPLIT input into name, age, courses
CREATE List<String> courseList by splitting courses on commas

CREATE Student student = new Student(name, age, courseList)


ADD student to database

PRINT "Serializing data..."


byte[] serializedData = database.serialize()

PRINT "Deserializing data..."


StudentDatabase deserializedDatabase = database.deserialize(serializedData)

FOR each student in deserializedDatabase.students


PRINT student

END
Ex. 2: Formatting dates and currencies
Single File Programming Question
Problem description:
Create a Java program that formats dates and currencies according to different locales based on user input.

• Implement a Java program that allows users to input a date and a currency amount.
• The program should format:
• The date according to different locales (US, UK, Germany) using java.time.LocalDate and
java.time.format.DateTimeFormatter.
• The currency amount according to the same locales using java.text.NumberFormat and
java.math.BigDecimal.
• A date in the format YYYY-MM-DD.
• A numeric currency amount (e.g., 1000.50).
• Display an error message if the date input format is incorrect (YYYY-MM-DD).
• Display an error message if the currency amount input is not numeric.
• Print the formatted date and currency for each locale in the specified format.
• Ensure the program closes the Scanner object to release resources properly.
Input format :
Input consists of date and amount
Eg:-
2024-06-18
YYYY-MM-DD
Output format :
Formatted Date:
English (United States): June 18, 2024
English (United Kingdom): June 18, 2024
German (Germany): Juni 18, 2024
Formatted Currency:
English (United States): $1.00
English (United Kingdom): £1.00
German (Germany): 1,00 €
Sample test cases :
Input 1 :
2001-08-03
10000
Output 1 :

Formatted Date:
English (United States): August 3, 2001
English (United Kingdom): August 3, 2001
German (Germany): August 3, 2001

Formatted Currency:
English (United States): $10,000.00
English (United Kingdom): £10,000.00
German (Germany): 10.000,00 €
Input 2 :
2023-01-12
88
Output 2 :

Formatted Date:
English (United States): January 12, 2023
English (United Kingdom): January 12, 2023
German (Germany): Januar 12, 2023

Formatted Currency:
English (United States): $88.00
English (United Kingdom): £88.00
erman(Germany):88,00 €

Algorithm
1. Initialize Scanner:
o Create a Scanner object to read input from the user.
2. Input Handling:
o Read a date string in the format YYYY-MM-DD.
o Read a currency amount as a string.
3. Validate Date Input:
o Attempt to parse the date string using LocalDate.parse with the
DateTimeFormatter.ISO_LOCAL_DATE.
o If parsing fails, print an error message and exit.
4. Validate Currency Input:
o Attempt to parse the currency amount as a BigDecimal.
o If parsing fails, print an error message and exit.
5. Format and Print Date:
o Define DateTimeFormatter instances for formatting the date in the US, UK, and Germany
locales.
o Format and print the date for each locale.
6. Format and Print Currency:
o Use NumberFormat for formatting the currency amount according to the US, UK, and Germany
locales.
o Format and print the currency for each locale.
7. Close Scanner:
o Close the Scanner object to release resources.
Pseudocode
BEGIN
// Step 1: Initialize Scanner
CREATE Scanner scanner = new Scanner(System.in)

// Step 2: Read input


PRINT "Enter date (YYYY-MM-DD):"
READ dateInput as String
PRINT "Enter currency amount:"
READ amountInput as String

// Step 3: Validate and parse date input


TRY
PARSE dateInput using LocalDate.parse(dateInput, DateTimeFormatter.ISO_LOCAL_DATE)
CATCH DateTimeParseException e
PRINT "Error: Invalid date format. Please use YYYY-MM-DD."
EXIT

// Step 4: Validate and parse currency input


TRY
PARSE amountInput as BigDecimal
CATCH NumberFormatException e
PRINT "Error: Invalid currency amount. Please enter a numeric value."
EXIT

// Step 5: Format and print date in different locales


PRINT "Formatted Date:"

DEFINE DateTimeFormatter usFormatter = DateTimeFormatter.ofPattern("MMMM d, yyyy", Locale.US)


DEFINE DateTimeFormatter ukFormatter = DateTimeFormatter.ofPattern("MMMM d, yyyy", Locale.UK)
DEFINE DateTimeFormatter deFormatter = DateTimeFormatter.ofPattern("d. MMMM yyyy",
Locale.GERMANY)

PRINT "English (United States): " + dateInput.format(usFormatter)


PRINT "English (United Kingdom): " + dateInput.format(ukFormatter)
PRINT "German (Germany): " + dateInput.format(deFormatter)

// Step 6: Format and print currency in different locales


PRINT "Formatted Currency:"

DEFINE NumberFormat usCurrency = NumberFormat.getCurrencyInstance(Locale.US)


DEFINE NumberFormat ukCurrency = NumberFormat.getCurrencyInstance(Locale.UK)
DEFINE NumberFormat deCurrency = NumberFormat.getCurrencyInstance(Locale.GERMANY)

PRINT "English (United States): " + usCurrency.format(amountInput)


PRINT "English (United Kingdom): " + ukCurrency.format(amountInput)
PRINT "German (Germany): " + deCurrency.format(amountInput)

// Step 7: Close Scanner


scanner.close()

END
Ex. 3: Implement A Java Program To Do File Operations
Single File Programming Question
Problem description:
You are developing a command-line task management system to help users organize their tasks efficiently.
The system allows users to perform CRUD operations (Create, Read, Update, Delete) on a list of tasks stored
in memory. Each task is represented as a string.

• 1. Create (Insert): Allow the user to add a new task to the task list.
• 2. Update: Allow the user to update an existing task in the list.
• 3. Delete: Allow the user to delete a task from the list.
• 4. Display: Display all tasks currently in the list.
• 0. Exit: Exit the program.
Input format :
Input consists of the menu option and data
option - 1
insert data - "iamNeo"
option - 2
update data - "neoColab"
option - 3
Deleted!
option - 0
Exiting...
Output format :
1. Create (Insert)
2. Update
3. Delete
0. Exit
Enter your choice: Inserted data: hello world
1. Create (Insert)
2. Update
3. Delete
0. Exit
Enter your choice: Updated data: iamneo
1. Create (Insert)
2. Update
3. Delete
0. Exit
Enter your choice: Deleted!
1. Create (Insert)
2. Update
3. Delete
0. Exit
Enter your choice: Exiting...
Sample test cases :
Input 1 :
1
webpage
2
website
3
0
Output 1 :
1. Create (Insert)
2. Update
3. Delete
0. Exit
Inserted data: webpage
1. Create (Insert)
2. Update
3. Delete
0. Exit
Updated data: website
1. Create (Insert)
2. Update
3. Delete
0. Exit
Deleted!
1. Create (Insert)
2. Update
3. Delete
0. Exit
Exiting...
Input 2 :
1
hello world
2
iamneo
3
0
Output 2 :
1. Create (Insert)
2. Update
3. Delete
0. Exit
Inserted data: hello world
1. Create (Insert)
2. Update
3. Delete
0. Exit
Updated data: iamneo
1. Create (Insert)
2. Update
3. Delete
0. Exit
Deleted!
1. Create (Insert)
2. Update
3. Delete
0. Exit
Exiting...
Algorithm
1. Initialize the Task List:
o Create a List<String> to store tasks.
2. Display Menu Options:
o Print the menu with options:
1. Create (Insert)
2. Update
3. Delete
4. Exit
3. User Input:
o Use Scanner to read the user's choice from the menu.
4. Perform Operations Based on User Choice:
o Option 1: Create (Insert)
▪ Prompt the user to enter the task to be added.
▪ Add the task to the task list.
▪ Print a confirmation message.
o Option 2: Update
▪ Check if the task list is not empty.
▪ Prompt the user to enter the new task.
▪ Replace the last task with the new task.
▪ Print a confirmation message.
o Option 3: Delete
▪ Check if the task list is not empty.
▪ Remove the last task from the list.
▪ Print a confirmation message.
o Option 0: Exit
▪ Print an exit message.
▪ Terminate the program.
5. Loop Until Exit:
o Continuously display the menu and perform operations until the user chooses to exit.
6. Handle Edge Cases:
o Handle cases where the user tries to update or delete a task when the task list is empty.
Pseudocode
BEGIN
// Step 1: Initialize the Task List
CREATE List<String> taskList = new ArrayList<>()
CREATE Scanner scanner = new Scanner(System.in)
int choice
DO
// Step 2: Display Menu Options
PRINT "1. Create (Insert)"
PRINT "2. Update"
PRINT "3. Delete"
PRINT "0. Exit"
PRINT "Enter your choice: "

// Step 3: User Input


choice = scanner.nextInt()
scanner.nextLine() // Consume the newline character

// Step 4: Perform Operations Based on User Choice


IF choice == 1 THEN
PRINT "Enter task to insert: "
String newTask = scanner.nextLine()
taskList.add(newTask)
PRINT "Inserted data: " + newTask

ELSE IF choice == 2 THEN


IF taskList.isEmpty() THEN
PRINT "No tasks available to update!"
ELSE
PRINT "Enter updated task: "
String updatedTask = scanner.nextLine()
taskList.set(taskList.size() - 1, updatedTask)
PRINT "Updated data: " + updatedTask

ELSE IF choice == 3 THEN


IF taskList.isEmpty() THEN
PRINT "No tasks available to delete!"
ELSE
taskList.remove(taskList.size() - 1)
PRINT "Deleted!"

ELSE IF choice == 0 THEN


PRINT "Exiting..."

ELSE
PRINT "Invalid choice, please try again."

END IF
WHILE choice != 0
// Step 5: Close Scanner
scanner.close()
END
Unit 3:
Ex. 1: Stream Operations - Filtering, Mapping, And Reducing
Single File Programming Question
You are working as a data engineer for a company that processes large datasets of customer transactions. Your
task is to create a program that performs various stream operations like filtering, mapping, and reducing on a
list of transaction data. Each transaction is represented as an object with the following fields: transactionId,
customerId, amount, and status.
Your task is to perform the following operations:

1. Filter: Extract only the completed transactions.

2. Map: Create a list of transaction amounts for the completed transactions.

3. Reduce: Calculate the total amount of completed transactions.


Input format :
The first line contains an integer nnn, the number of transactions.
The next nnn lines each contain four values: transaction_id, customer_id, amount, and status separated by
spaces.
Output format :
A single line that outputs the total amount of completed transactions.

Sample test cases :


Input 1 :
1
1 101 250.0 completed
Output 1 :
Total amount of completed transactions: 250.0
Input 2 :
5
1 101 250.0 completed
2 102 450.0 pending
3 101 150.0 completed
4 103 300.0 failed
5 104 600.0 completed
Output 2 :
Total amount of completed transactions: 1000.0
Algorithm
1. Define a Transaction Class:
o Create a Transaction class with the following attributes:
▪ transactionId (String)
▪ customerId (String)
▪ amount (double)
▪ status (String)
2. Read Input:
o Initialize a Scanner to read the input.
o Read the first integer n, which represents the number of transactions.
o Create an empty list to store the transactions.
3. Parse Transactions:
o For the next n lines, read each transaction's details (transactionId, customerId, amount, status).
o Create a Transaction object for each line and add it to the list.
4. Filter Completed Transactions:
o Use a stream to filter out the transactions where the status is "completed".
5. Map to Amounts:
o Use a stream to map the filtered transactions to their amounts (i.e., extract the amount field).
6. Reduce to Calculate Total:
o Use the reduce method to sum up all the amounts of the completed transactions.
7. Print the Result:
o Print the total amount of completed transactions.

Pseudocode
CLASS Transaction
ATTRIBUTES
String transactionId
String customerId
double amount
String status

CONSTRUCTOR
Transaction(String transactionId, String customerId, double amount, String status)
this.transactionId = transactionId
this.customerId = customerId
this.amount = amount
this.status = status

BEGIN
// Step 1: Initialize Scanner and List
CREATE Scanner scanner = new Scanner(System.in)
CREATE List<Transaction> transactions = new ArrayList<>()

// Step 2: Read input


PRINT "Enter number of transactions: "
int n = scanner.nextInt()
scanner.nextLine() // consume newline character

FOR i FROM 0 to n-1 DO


READ line as String
SPLIT line by space into transactionId, customerId, amount, status
PARSE amount as double
CREATE Transaction transaction = new Transaction(transactionId, customerId, amount, status)
transactions.add(transaction)
END FOR

// Step 3: Filter, Map, and Reduce


double totalAmount = transactions.stream()
.FILTER(transaction -> transaction.getStatus().equals("completed"))
.MAP(transaction -> transaction.getAmount())
.REDUCE(0.0, (sum, amount) -> sum + amount)

// Step 4: Print the result


PRINT "Total amount of completed transactions: " + totalAmount

// Step 5: Close Scanner


scanner.close()
END
Ex.2. Stream Generator For Prime Numbers

Single File Programming Question


You are a software developer working on a project that requires generating a large set of prime numbers for
encryption purposes. Your task is to implement a Java program that generates an infinite stream of prime
numbers. You need to use the Java Streams API to create this infinite stream. Additionally, you must implement
methods to:
Retrieve prime numbers until a specified number is reached (inclusive if it's a prime).
Requirements:
• Implement a method to generate an infinite stream of prime numbers.
Input format :
The program should prompt the user to enter the number of prime numbers to generate.
Output format :
A single line containing the prime numbers up to the specified limit in a list format.
Sample test cases :
Input 1 :
10
Output 1 :
Generated 10 prime numbers: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29
Input 2 :
20
Output 2 :
Generated 20 prime numbers: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71
Note :
The program will be evaluated only after the “Submit Code” is clicked.
Extra spaces and new line characters in the program output will result in the failure of the test case.
Algorithm
1. Create a Method to Generate an Infinite Stream of Prime Numbers:
o Use Java Streams API to create an infinite stream of numbers starting from 2.
o Use a helper method isPrime to check if a number is prime.
o Filter the stream to retain only prime numbers.
2. Create a Method to Collect Prime Numbers Up to a Specified Limit:
o Use the limit method to restrict the number of primes generated from the infinite stream.
3. Read User Input:
o Prompt the user to enter the number of prime numbers they want to generate.
o Use Scanner to read the input.
4. Generate and Collect Primes:
o Generate the specified number of prime numbers using the infinite stream and collect them into
a list.
5. Output the Prime Numbers:
o Print the list of generated prime numbers in the required format.
Pseudocode
BEGIN
// Step 1: Create a method to check if a number is prime
FUNCTION isPrime(n: int): boolean
IF n <= 1 THEN
RETURN false
END IF
FOR i FROM 2 TO sqrt(n) DO
IF n % i == 0 THEN
RETURN false
END IF
END FOR
RETURN true

// Step 2: Create a method to generate an infinite stream of prime numbers


FUNCTION generatePrimeStream(): Stream<Integer>
RETURN Stream.iterate(2, n -> n + 1)
.FILTER(n -> isPrime(n))

// Step 3: Read user input


CREATE Scanner scanner = new Scanner(System.in)
PRINT "Enter the number of prime numbers to generate: "
int limit = scanner.nextInt()

// Step 4: Generate and collect primes


List<Integer> primes = generatePrimeStream()
.limit(limit)
.collect(Collectors.toList())

// Step 5: Output the prime numbers


PRINT "Generated " + limit + " prime numbers: " + primes

// Step 6: Close scanner


scanner.close()
END
Ex.3: String Tokenize and Filter using Stream API
Single File Programming Question
Imagine you are an investigator working on a fraud case. You have a text file containing witness statements
that might hold crucial clues. The statements are full of common words like "the," "a," and "an" that don't
contain much meaning. To focus on the important details, you want to write a program that can analyze these
statements and remove the stopwords.

Example:
Assume the input text file (sentences.txt) contains the following content:

This is a sample sentence.

The quick brown fox jumps over the lazy dog.

Hello world! How are you today?

Output:

sample

sentence

quick

brown

fox

jumps

lazy

dog

Hello

world!

today?

Input format :
The input consists of a text file containing multiple sentences.

Each sentence is separated by a newline.

Output format :
The output should display the remaining words after stopwords have been filtered out from each sentence.

Each word should be printed on a new line.

Sample test cases :


Input 1 :
This is a sample sentence.
Output 1 :
Remaining words after processing sentence: [sample sentence.]
Input 2 :
The cat is on the mat.
Output 2 :
Remaining words after processing sentence: [cat mat.]

Algorithm
1. Load Stopwords:
o Create a list or set of stopwords like "the," "a," "an," "is," "on," etc.
2. Read the Input File:
o Open and read the contents of the text file (sentences.txt).
o Split the file content into sentences using newline characters.
3. Process Each Sentence:
o For each sentence, split it into words.
o Filter out the stopwords from the list of words.
o Join the remaining words back into a sentence.
4. Output the Results:
o For each processed sentence, print the remaining words.
Pseudocode
BEGIN
// Step 1: Load the stopwords
SET stopwords = ["the", "a", "an", "is", "on", "and", "of", "in", "to", "with", ...]

// Step 2: Read the input file


OPEN file "sentences.txt"
CREATE a list sentences = []

WHILE file has more lines DO


READ a line from file
ADD line to sentences list
END WHILE

// Step 3: Process each sentence


FOR each sentence in sentences DO
SPLIT sentence into words using spaces as delimiter
CREATE a list filtered_words = []

FOR each word in words DO


IF word.lower() is not in stopwords THEN
ADD word to filtered_words
END IF
END FOR

JOIN filtered_words into a string filtered_sentence


PRINT "Remaining words after processing sentence: " + filtered_sentence
END FOR

// Step 4: Close the file


CLOSE file
END
Unit 4:
Ex.1: Read And Write Using StringTokenizer Class

Single File Programming Question


Scenario:
You are working on a project that involves text analysis and processing. As part of this project, you need to
read the contents of a text file and break it down into individual sentences for further analysis. To achieve this,
you will use Java's StringTokenizer class to tokenize the text into sentences. This task will involve handling
various sentence delimiters and ensuring that sentences are correctly extracted even if they span multiple lines
or contain complex punctuation.

Task:
Write a Java program that reads the contents of a text file, tokenizes the text into sentences using the
StringTokenizer class, and prints each sentence on a new line. Your program should handle different types of
sentence delimiters such as periods (.), exclamation marks (!), and question marks (?). Additionally, ensure
that the program can handle multiple lines of text and extra whitespaces gracefully.
Input format :
The program should read the contents of a text file specified by the user.
The program should handle the file not being found or any other I/O exceptions gracefully.
Output format :
Each sentence should be printed on a new line after being tokenized.
Trim any leading or trailing whitespace from each sentence before printing.
Sample test cases :
Input 1 :
Is this a question? Yes, it is! This is a statement.
Output 1 :
Is this a question
Yes, it is
This is a statement

Input 2 :
This is the first line. This is the second line! Is this the third line?
Output 2 :
This is the first line
This is the second line
Is this the third line
Algorithm
1. Load and Open the Text File:
o Prompt the user for the file path of the text file.
o Attempt to open the file and read its contents.
o Handle any potential I/O exceptions (e.g., file not found) gracefully.
2. Initialize StringTokenizer:
o Create a StringTokenizer instance to tokenize the text.
o Specify the delimiters as periods (.), exclamation marks (!), and question marks (?).
3. Tokenize the Text into Sentences:
o Use the StringTokenizer to extract sentences.
o For each token (sentence), trim leading and trailing whitespace.
4. Output the Sentences:
o Print each sentence on a new line.
5. Handle Exceptions:
o Ensure that any I/O exceptions are caught and a meaningful error message is displayed to the
user.
Pseudocode
BEGIN
TRY
// Step 1: Load and open the text file
PROMPT user for the file path
OPEN file with the specified path

// Step 2: Read the file contents


READ the contents of the file into a string 'text'

// Step 3: Initialize StringTokenizer with delimiters


SET delimiters = ".!?"
CREATE StringTokenizer tokenizer = new StringTokenizer(text, delimiters)

// Step 4: Tokenize the text into sentences and print each sentence
WHILE tokenizer has more tokens DO
SET sentence = tokenizer.nextToken().trim()
PRINT sentence
END WHILE

// Step 5: Close the file


CLOSE the file

CATCH IOException
PRINT "An error occurred while reading the file. Please check the file path and try again."
END TRY
END
Ex. 2: Object Serialization
Single File Programming Question
Scenario:
Imagine you are tasked with developing a Java application that manages serialization and deserialization of
Person and Employee objects. Your application needs to read input data from standard input, create
corresponding objects based on the input format, serialize these objects to a file named objects.ser, and finally
deserialize them to verify the process.

Tasks:

1. Implement the Person and Employee classes with appropriate constructors and toString() methods to
represent individuals with basic details.
2. Develop a Java class SerializationExample with methods to parse input, serialize objects, and
deserialize objects from a file.
3. Ensure that the program handles input dynamically from standard input (System.in), splitting input
lines by commas to distinguish between Person and Employee objects.
4. Serialize the objects into a file objects.ser and print a confirmation message upon successful
serialization.
5. Deserialize the objects from objects.ser and print each object to verify successful deserialization.
Input format :
1. Input will consist of multiple lines, each containing a comma-separated string.
2. Each line represents an object of either Person or Employee.
3. For Person: "Person,Name,Age"
4. For Employee: "Employee,Name,Age,EmployeeId,Department"
5. Age should be an integer value. EmployeeId and Department may be optionally null.
Output format :
1. Upon successful execution, the program should output the serialized objects confirmation message.
2. For each object deserialized, print its details formatted as specified in toString() methods
of Person and Employee
Sample test cases :
Input 1 :
Person,John Doe,30
Employee,Jane Smith,40,E123,HR
Output 1 :
Objects have been serialized to objects.ser
Deserialized Object: Person [name=John Doe, age=30]
Deserialized Object: Employee [employeeId=E123, department=HR, Person [name=Jane Smith, age=40]]
Input 2 :
Employee,Jane Smith,40,null,null
Output 2 :
Objects have been serialized to objects.ser
Deserialized Object: Employee [employeeId=null, department=null, Person [name=Jane Smith, age=40]]
Note :
The program will be evaluated only after the “Submit Code” is clicked.
Extra spaces and new line characters in the program output will result in the failure of the test case.

Algorithm
1. Define Classes:
o Person Class:
▪ Attributes: name, age
▪ Methods: Constructor, toString()
o Employee Class (extends Person):
▪ Additional Attributes: employeeId, department
▪ Methods: Constructor, toString()
2. Read and Parse Input:
o Read multiple lines of input from standard input.
o Parse each line to determine if it represents a Person or Employee and extract attributes.
3. Create Objects:
o Create instances of Person or Employee based on parsed input.
4. Serialize Objects:
o Serialize the created objects to a file named objects.ser.
o Print a confirmation message upon successful serialization.
5. Deserialize Objects:
o Read the serialized objects from objects.ser.
o Print each deserialized object's details using their toString() methods.
6. Handle Exceptions:
o Ensure that any I/O or serialization/deserialization exceptions are handled gracefully.
Pseudocode
BEGIN
// Step 1: Define classes
CLASS Person
Attributes: name, age
CONSTRUCTOR(name, age)
METHOD toString() RETURNS "Person [name=name, age=age]"

CLASS Employee EXTENDS Person


Attributes: employeeId, department
CONSTRUCTOR(name, age, employeeId, department)
METHOD toString() RETURNS "Employee [employeeId=employeeId, department=department, Person
[name=name, age=age]]"

// Step 2: Read and parse input


OPEN Scanner to read input from System.in
CREATE a list objects = []

WHILE there are more lines of input DO


READ line from input
SPLIT line by commas into parts
IF parts[0] is "Person" THEN
CREATE Person with parts[1], parts[2]
ADD Person to objects
ELSE IF parts[0] is "Employee" THEN
CREATE Employee with parts[1], parts[2], parts[3], parts[4]
ADD Employee to objects
END IF
END WHILE

// Step 3: Serialize objects


TRY
OPEN file "objects.ser" for writing
CREATE ObjectOutputStream for the file
WRITE objects to ObjectOutputStream
CLOSE file
PRINT "Objects have been serialized to objects.ser"
CATCH IOException
PRINT "Error during serialization"

// Step 4: Deserialize objects


TRY
OPEN file "objects.ser" for reading
CREATE ObjectInputStream for the file
READ objects from ObjectInputStream
CLOSE file

PRINT each deserialized object using toString()


CATCH IOException
PRINT "Error during deserialization"
CATCH ClassNotFoundException
PRINT "Error: Class not found"
END
Ex.3: Implement a program that uses advanced I/O techniques

Single File Programming Question


Scenario:
You are required to implement a program that demonstrates the usage of advanced I/O techniques in Java.
Your task is to handle multiple types of input streams, including PipedInputStream, SequenceInputStream,
PushbackInputStream, and combinations thereof. The program should be able to read specific test cases from
standard input and execute the corresponding test case to show the output.

Tasks:
1. Implement a method testPipedStreams that reads a string from a PipedInputStream after writing it to a
PipedOutputStream.
2. Implement a method testSequenceInputStream that concatenates the contents of two byte arrays using
SequenceInputStream.
3. Implement a method testPushbackInputStream that demonstrates the pushback functionality by reading
a byte, pushing it back, and reading it again.
4. Implement a method testMultiplePushbackInputStream that demonstrates the pushback functionality
with multiple pushbacks and reads.
5. Implement a method testMultipleSequenceInputStream that concatenates the contents of multiple byte
arrays using SequenceInputStream.
Input format :
1. First line: the name of the test case to run
(testPipedStreams, testSequenceInputStream, testPushbackInputStream, testMultiplePushbackInputSt
ream, testMultipleSequenceInputStream).
2. Subsequent lines: inputs required for the specified test case.
Output format :
1. The result of the executed test case, printed to the console.
Sample test cases :
Input 1 :
testPipedStreams
Hello World
Output 1 :
Read from PipedInputStream: Hello World
Input 2 :
testMultipleSequenceInputStream
Advanced
Java
IO
Techniques
Output 2 :
Concatenated Stream: AdvancedJavaIOTechniques
Note :
The program will be evaluated only after the “Submit Code” is clicked.
Extra spaces and new line characters in the program output will result in the failure of the test case.
Algorithm
1. Read the Test Case:
o Read the first line to determine which test case to execute.
o Read subsequent lines as required by the selected test case.
2. Implement Test Methods:
o testPipedStreams:
▪ Create a PipedOutputStream and a PipedInputStream.
▪ Connect them using PipedInputStream and PipedOutputStream.
▪ Write the input string to PipedOutputStream.
▪ Read from PipedInputStream and print the result.
o testSequenceInputStream:
▪ Create two byte arrays from the input lines.
▪ Create a SequenceInputStream with these byte arrays.
▪ Read from the SequenceInputStream and concatenate the results.
▪ Print the concatenated string.
o testPushbackInputStream:
▪ Create a PushbackInputStream with a byte array.
▪ Read a byte from the PushbackInputStream.
▪ Push the byte back and read it again.
▪ Print the results of both reads.
o testMultiplePushbackInputStream:
▪ Create a PushbackInputStream with a byte array.
▪ Perform multiple pushbacks and reads.
▪ Print the results of the reads.
o testMultipleSequenceInputStream:
▪ Create multiple byte arrays from the input lines.
▪ Use SequenceInputStream to concatenate these byte arrays.
▪ Read from the SequenceInputStream and concatenate the results.
▪ Print the concatenated string.
3. Handle Exceptions:
o Ensure that any I/O or stream-related exceptions are caught and handled.
Pseudocode
BEGIN
FUNCTION main()
READ first line as testCase
READ subsequent lines as inputs

IF testCase is "testPipedStreams" THEN


CALL testPipedStreams(inputs)
ELSE IF testCase is "testSequenceInputStream" THEN
CALL testSequenceInputStream(inputs)
ELSE IF testCase is "testPushbackInputStream" THEN
CALL testPushbackInputStream(inputs)
ELSE IF testCase is "testMultiplePushbackInputStream" THEN
CALL testMultiplePushbackInputStream(inputs)
ELSE IF testCase is "testMultipleSequenceInputStream" THEN
CALL testMultipleSequenceInputStream(inputs)
ELSE
PRINT "Invalid test case"
END IF
END FUNCTION

FUNCTION testPipedStreams(inputs)
CREATE PipedOutputStream
CREATE PipedInputStream connected to PipedOutputStream
WRITE inputs[0] to PipedOutputStream
READ from PipedInputStream
PRINT "Read from PipedInputStream: " + data
END FUNCTION

FUNCTION testSequenceInputStream(inputs)
CREATE byte arrays from inputs
CREATE SequenceInputStream with byte arrays
READ from SequenceInputStream
CONCATENATE and PRINT the result
END FUNCTION

FUNCTION testPushbackInputStream(inputs)
CREATE PushbackInputStream with byte array from inputs
READ a byte
PUSH byte back
READ the byte again
PRINT results of both reads
END FUNCTION

FUNCTION testMultiplePushbackInputStream(inputs)
CREATE PushbackInputStream with byte array from inputs
PERFORM multiple pushbacks and reads
PRINT results of reads
END FUNCTION

FUNCTION testMultipleSequenceInputStream(inputs)
CREATE byte arrays from inputs
CREATE SequenceInputStream with byte arrays
READ from SequenceInputStream
CONCATENATE and PRINT the result
END FUNCTION
END
Unit 5:
Ex. 1: Implement Custom Stream Generators Using Stream.Generate And Stream.Iterate Methods
Single File Programming Question
Develop a program to generate a custom sequence of numbers for two purposes: generating the Fibonacci
sequence. Implement these using Stream.iterate methods in Java.
Input format :
Line 1 : Input for Fibonacci sequence limit
10

Output format :
Line 1 : Fibonacci Sequence: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

Sample test cases :


Input 1 :
5
Output 1 :
Fibonacci Sequence: [0, 1, 1, 2, 3]
Input 2 :
10
Output 2 :
Fibonacci Sequence: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
Algorithm
1. Read Input:
o Read an integer n from the input, which specifies the number of Fibonacci numbers to generate.
2. Generate Fibonacci Sequence Using Streams:
o Use Stream.iterate to create an infinite stream of Fibonacci numbers.
o The Fibonacci sequence can be generated by maintaining two state variables: the previous two
numbers in the sequence.
3. Limit the Stream:
o Use limit(n) to restrict the stream to the first n Fibonacci numbers.
4. Collect and Format Output:
o Collect the numbers into a list.
o Print the list in the required format.
Pseudocode
BEGIN
FUNCTION main()
READ integer n from input

GENERATE Fibonacci sequence using Stream.iterate


INITIALIZE stream with starting values (0, 1)
USE Stream.iterate to generate subsequent Fibonacci numbers
APPLY function to generate next Fibonacci number
USE limit(n) to restrict the stream to the first n numbers
COLLECT the results into a list

PRINT "Fibonacci Sequence: " followed by the list of Fibonacci numbers


END FUNCTION

FUNCTION generateFibonacciStream(n)
RETURN Stream.iterate(
Tuple2(0, 1),
previous -> Tuple2(previous[1], previous[0] + previous[1]),
tuple -> tuple[0]
)
.limit(n)
END FUNCTION
END
Ex.2: Advanced Stream Operations
Single File Programming Question
Develop a program where we have a list of employees, each associated with multiple projects they have
worked on. take input from the user for creating employees and their projects, then demonstrate various stream
operations like flatMap, chaining of stream operations, and using peek for debugging purposes.
Output :
FlatMapping to get all projects across all employees
Chaining stream operations: Filter employees who worked on projects with budget over 10000 and calculate
total budget
Input format :
Input line 1 : Enter number of employees
line 2 : Enter employee ID
line 3 : Enter employee name
line 4 :Enter number of projects for this employee
line 5 : Enter project name
line 6 : Enter project duration in months
line 7 : Enter project budget
Output format :
The output prints the project details with budget and duration.
Sample test cases :
Input 1 :
1
12
Ram
1
ABCD
6
6000
Output 1 :
Project 1:

All Projects:
Project{projectName='ABCD', durationMonths=6, projectBudget=6000.0}
Total budget for projects with budget over 10000: 0.0

Projects with duration less than 6 months:


Input 2 :
1
21
Ramesh
1
XYZ
8
8000
Output 2 :
Project 1:

All Projects:
Project{projectName='XYZ', durationMonths=8, projectBudget=8000.0}

Total budget for projects with budget over 10000: 0.0

Projects with duration less than 6 months:


Note :
The program will be evaluated only after the “Submit Code” is clicked.
Extra spaces and new line characters in the program output will result in the failure of the test case.
Algorithm
1. Read Input:
o Read the number of employees.
o For each employee, read their ID, name, number of projects, and details of each project (name,
duration, budget).
2. Create Employee and Project Classes:
o Define a Project class with attributes: projectName, durationMonths, and projectBudget.
o Define an Employee class with attributes: employeeId, employeeName, and a list of Project
objects.
3. FlatMap Operation:
o Use flatMap to extract and display all projects from the list of employees.
4. Chaining Stream Operations:
o Filter employees who have worked on projects with a budget over 10,000.
o Calculate the total budget for such projects.
5. Peek for Debugging:
o Use peek to debug the intermediate results if necessary.
6. Output Results:
o Print all projects.
o Print total budget for projects with a budget over 10,000.
o Print projects with a duration of less than 6 months.
Pseudocode
BEGIN
FUNCTION main()
READ integer numEmployees from input

INITIALIZE an empty list of Employee objects

FOR each employee from 1 to numEmployees


READ employeeId from input
READ employeeName from input
READ integer numProjects from input

INITIALIZE an empty list of Project objects

FOR each project from 1 to numProjects


READ projectName from input
READ durationMonths from input
READ projectBudget from input

CREATE a new Project object with the given details


ADD the Project object to the list of projects

CREATE a new Employee object with the given details and project list
ADD the Employee object to the list of employees

FLATMAP the list of employees to get all projects


PRINT all projects

CHAIN stream operations to:


FILTER projects with budget over 10,000
CALCULATE total budget

PRINT total budget

FILTER and PRINT projects with duration less than 6 months

END FUNCTION
END
Ex. 3: Regular Expressions
Single File Programming Question
Demonstrate how to use regular expressions in Java to perform common string manipulation tasks such as
splitting strings, replacing text, and extracting specific patterns.
Input format :
Input line 1: Enter a comma-separated list of names
Input line 2:Enter the name to replace
Input line 3:Enter the replacement name
Input line 4:Enter the starting letter to extract names (case-sensitive)
Output format :
Splitting string into names:
Harshit
Shyam
Ravi
Virat
Replacing 'Ravi' with 'Harshit':
Harshit,Shyam,Harshit,Virat
Sample test cases :
Input 1 :
Harshit,Shyam,Ravi,Virat
Ravi
Harshit
H
Output 1 :

Splitting string into names:


Harshit
Shyam
Ravi
Virat
Replacing 'Ravi' with 'Harshit':
Harshit,Shyam,Harshit,Virat
Extracting names starting with 'H':
Harshit
Input 2 :
Roma,Roja,Ravi,Vamika
Roma
Roja
R
Output 2 :
Splitting string into names:
Replacing 'Roma,Roja,Ravi,Vamika' with 'Roma':
Extracting names starting with 'R':
Note :
The program will be evaluated only after the “Submit Code” is clicked.
Extra spaces and new line characters in the program output will result in the failure of the test case.
Algorithm
1. Read Input:
o Read the comma-separated list of names.
o Read the name to be replaced.
o Read the replacement name.
o Read the starting letter for extracting names.
2. Splitting String:
o Use regular expressions to split the string by commas.
o Print each name on a new line.
3. Replacing Text:
o Replace occurrences of the specified name with the replacement name using regular
expressions.
o Print the modified list of names as a comma-separated string.
4. Extracting Names:
o Extract names starting with the specified letter using regular expressions.
o Print the extracted names.
Pseudocode
BEGIN
FUNCTION main()
READ inputLine1 from standard input // Comma-separated list of names
READ inputLine2 from standard input // Name to replace
READ inputLine3 from standard input // Replacement name
READ inputLine4 from standard input // Starting letter for extraction

// Splitting string into names


SPLIT inputLine1 by comma using regular expressions
PRINT "Splitting string into names:"
FOR each name in splitNames
PRINT name

// Replacing specified name with the replacement name


REPLACE occurrences of inputLine2 with inputLine3 in inputLine1 using regular expressions
PRINT "Replacing '" + inputLine2 + "' with '" + inputLine3 + "':"
PRINT updatedNamesList

// Extracting names starting with the specified letter


EXTRACT names starting with inputLine4 using regular expressions
PRINT "Extracting names starting with '" + inputLine4 + "':"
FOR each name in extractedNames
PRINT name

END FUNCTION
END

You might also like