CODE:
OUTPUT:
CODE:
OUTPUT:
CODE:
OUTPUT:
CODE:
OUTPUT:
CODE:
OUTPUT:
PRACTICAL : 07(a)
Aim: To write a Java program that takes user input using:
1. DataInputStream class
2. BufferedReader class
Theory:
1. DataInputStream Class
• Part of java.io package.
• Used to read primitive data types from an input stream.
• Works with bytes (low-level stream).
• Disadvantages:
o Requires manual conversion of bytes to strings.
o Less efficient for reading text compared to BufferedReader.
2. BufferedReader Class
• More efficient for reading text input.
• Uses a buffer to reduce I/O operations.
• Works with InputStreamReader to read from System.in.
• Advantages:
o Faster for reading large text.
o Provides readLine() for easy string input.
Implementation Steps
1. Using DataInputStream:
o Create an instance of DataInputStream with System.in.
o Use readLine() (deprecated, but used here for demonstration).
o Convert bytes to a readable string.
2. Using BufferedReader:
o Wrap InputStreamReader around System.in.
o Use readLine() to get user input as a string.
PRACTICAL : 07(b)
Aim: To write a Java program that reads a file and counts: Lines, Words, Sentences,
Characters, Whitespaces
Theory:
1. File Handling in Java
BufferedReader
• High-efficiency reader that buffers input in 8KB chunks to minimize disk
operations
• Wraps FileReader to optimize character reading performance
• Essential for processing large text files with minimal memory overhead
FileReader
• Performs direct file access operations at low level
• Validates file existence and permissions on instantiation
• Typically combined with BufferedReader for production use
2. Key Methods
readLine()
• Returns complete text lines (minus terminators) or null at EOF
• Simplifies text parsing with clean termination condition
split("\s+")
• Powerful regex-based string splitting on whitespace
• Handles irregular spacing and empty entries automatically
3. Counting Logic
• Lines: Increment counter for each readLine().
• Words: Split each line by spaces (\\s+).
• Sentences: Count occurrences of ., !, ?.
• Characters: Sum of all characters in each line.
• Whitespaces: Count spaces, tabs (\\s).
4. Implementation Steps
1. Open a file using BufferedReader.
2. Read line by line and update counters.
3. Close the file after processing.
PRACTICAL : 08(a)
Aim: To write a Java program that reverses the elements of an ArrayList using Collections framework.
Theory:
ArrayList Method:
1. Dynamic array implementation - Resizable array that implements List interface for flexible sizing
2. Automatic growth - Expands capacity automatically when elements exceed current size
3. Insertion order - Maintains elements in the sequence they were added
4. Random access - Allows direct element access via index numbers in constant time
Collections.reverse() Method:
1. Static method - Belongs to Collections class and called without instance
2. In-place modification - Alters the original list rather than returning new one
3. O(n) complexity - Performance scales linearly with list size
4. List compatibility - Works with all List implementations like ArrayList, LinkedList
Implementation Steps:
1. ArrayList creation - Instantiate and fill list using add() method
2. Original print - Display list before reversal using toString()
3. Reverse operation - Apply Collections.reverse() to modify order
4. Reversed print - Display list after reversal to show changes
Key Methods:
1. add() - Appends elements to end of list
2. reverse() - Reverses element sequence in list
3. toString() - Returns string representation of list contents
PRACTICAL : 08(b)
Aim: To search a LinkedList for duplicate elements and return the distance between first and last
occurrence.
Theory:
LinkedList in Java
• Implements both List and Deque interfaces using doubly-linked nodes
• Provides O(1) time complexity for insertions/deletions at both ends
• Requires sequential traversal (O(n)) for element access by index
• Maintains exact insertion order of elements
• More memory-intensive than ArrayList due to node storage overhead
Duplicate Detection Logic
• Leverages List interface methods for position-based searching
• indexOf() scans from head to find first match (forward traversal)
• lastIndexOf() scans from tail to find last match (reverse traversal)
• Distance calculation accounts for zero-based indexing (inclusive count)
• Special case handling for non-existent elements improves robustness
Implementation Steps
1. Initialize LinkedList and populate with test data
2. Validate element existence using contains() before searching
3. Compute positional indices using indexOf()/lastIndexOf() pair
4. Calculate span between first/last occurrences (returns -1 if unique)
5. Include edge case handling for empty lists and null values
Key Methods
• indexOf(): Returns first position of element or -1
• lastIndexOf(): Returns last position or -1
• contains(): Quick existence check before full search
• add(): Populates list during initialization
PRACTICAL : 08(c)
Aim: To compare two Map objects and print the one with greater number of mappings.
Theory:
1. Map Interface Overview
• Stores data as key-value pairs, where each key maps to a single value.
• Common implementations:
o HashMap: Uses hashing for O(1) average-time operations (unsorted).
o TreeMap: Maintains keys in sorted order (natural or custom comparator).
o LinkedHashMap: Preserves insertion order while allowing fast lookups.
• No duplicate keys → Re-adding a key overwrites its previous value.
• size() returns the current number of key-value mappings.
2. Map Comparison Logic
• size() determines the number of entries in each map.
• Comparison checks which map has more entries (or if they are equal).
• Returns the larger map (or handles ties by returning both or a default).
• Useful for analyzing dataset sizes, caching efficiency, or memory usage.
Implementation Steps
I. Initialize Maps
a. Create two Map instances (e.g., HashMap and TreeMap).
b. Populate them using put(key, value).
II. Compare Sizes
a. Retrieve entry counts using size().
b. Determine which map has more entries (or if they are equal).
III. Output Result
a. Print the larger map (or both if sizes match).
IV. Handle Edge Cases
a. Empty maps: Check if either map is empty (isEmpty()).
b. Null values: Ensure keys/values are handled safely.