R.M. D ENGINEERING COLLEGE (An Autonomous Institution) R.S.M. Nagar, Kavaraipettai - 601 206 DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING 2 4 CS30 2 Advanced Java Programming Laboratory LAB MANUAL R202 4 ACADEMIC YEAR : 202 5 - 2 6 3 rd SEMESTER B. TECH ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING R.M. D ENGINEERING COLLEGE (An Autonomous Institution) R.S.M Nagar, Kavaraipettai - 601 206 DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING 2 4 CS30 2 Advanced Java Programming Laboratory LAB MANUAL R202 4 202 5 - 2 6 ODD SEMESTER COMMON TO ALL BRANCHES Prepared by K. GAYATHRI DEVI Asst. Prof / AIML & R.M.D. Faculties Approved by Dr. C. S. ANITA Professor & Head / AIML Approved by Dr.N.ANBUCHEZHIAN Principal R.M. D ENGINEERING COLLEGE (An Autonomous Institution) R.S.M. Nagar, Kavaraipettai - 601 206 DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING 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 M 1 : 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 M 2 : 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 M 3 : 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. D ENGINEERING COLLEGE (An Autonomous Institution) DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING 24CS302 – ADVANCED JAVA PROGRAMMING SYLLABUS UNIT I COLLECTIONS FRAMEWORK AND UTILITY CLASSES 9+ 9 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 DATE HANDLING AND SERIALIZATION 9+ 9 Date – Calendar – Comparable interface – Observer Interface –– Serialization – Dates - Numbers, and Currency - Working with Dates - Numbers and Currencies - Object Serialization - Serializable Interface - Writing and Reading Serializable Objects - Transient Keyword - SerialVersionUID 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. Create a class hierarchy representing different types of objects (e.g., Person, Employee). Serialize instances of these classes to a file using object serialization UNIT III STREAM API AND FUNCTIONAL PROGRAMMING PARADIGMS 9+ 9 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. D ENGINEERING COLLEGE (An Autonomous Institution) DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND SYLLABUS UNIT IV ADVANCED STRING PROCESSING AND I/O TECHNIQUES 9+ 9 String Tokenizer – Parsing - Tokenizing and Formatting - Locating Data via Pattern Matching, Tokenizing - Streams - Types of Streams - The Byte - stream I/O hierarchy - Character Stream Hierarchy – Random Access File class – the java.io. Console Class - 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. 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. 3. Implement a program that uses advanced I/O techniques like PipedInputStream , PipedOutputStream , SequenceInputStream , and PushbackInputStream UNIT V ADVANCED STREAM FEATURES AND REGULAR EXPRESSIONS 9+ 9 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+ 45 = 90 PERIODS Ex. No. Date Title Pg.no. Unit I : 1 Basic Operations On Different Data Structures Arraylist, Linkedlist, Hashset And Treeset. 8 2 Implement a custom data structure that combines features of a list and a set. 14 3 A Java program to create a HashMap. 16 Unit II : 1 Complex Object with Nested Data Structures. 19 2 Formatting dates and currencies. 22 3 Object Serialization 26 Unit III : 1 Stream Operations - Filtering, Mapping, And Reducing. 29 2 Stream Generator For Prime Numbers. 32 3 String Tokenize and Filter using Stream API. 34 Unit IV : 1 Read And Write Using StringTokenizer Class 37 2 Implement A Java Program To Do File Operations 40 3 Implement a program that uses advanced I/O techniques 45 Unit V : 1 Implement Custom Stream Generators Using Stream.Generate And Stream.Iterate Methods 49 2 Advanced Stream Operations 51 3 Regular Expressions R.M. D ENGINEERING COLLEGE (An Autonomous Institution) R.S.M. Nagar, Kavaraipettai - 601 206 DEPARTMENT OF ARTIFICIAL INTELLIGENCE & MACHINE LEARNING 2 4 CS 3 02 – ADVANCED 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 : CO 1 : Implement various data structures by utilizing core Java features and libraries CO 2 : Demonstrate proficiency in handling Java I/O operations, including file manipulation for efficient data storage and retrieval CO 3 : Apply and Analyze the Stream API for functional programming and data processing CO 4 : Implement advanced object serialization for complex data structures CO 5 : Utilize regular expressions for text parsing and string manipulation CO 6 : Build applications using advanced Java programming techniques 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 1 2 3 4 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 3 4 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 : 1. Insert the integers into the data structure. 2. Print the state of the data structure after insertion. 2. Searching : 1. For each integer, check if it is present in the data structure. 2. Print whether each element was found or not. 3. Deletion : 1. Clear the data structure. 2. 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 EX 3 : 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)