Object Oriented Programming using JAVA
Comprehensive exam revision notes for BCA-201N Unit 5 (Managing Input/Output Files, Streams & Java Utilities). Includes Section A (2M), Section B (5M), and Section C (15M) questions, answers, and diagrams.
Object Oriented Programming using JAVA
Managing Input/Output Files, Streams & Java Utilities
Core Definitions & Key Concepts
What is a 'Stream' in Java I/O
A logical sequence of data connected to an I/O channel. In Java, streams are unidirectional: an InputStream/Reader reads data from a source; an OutputStream/Writer sends data to a destination.
Byte Streams and Character Streams
- Byte Streams: Process raw 8-bit bytes (binary data like images, audio, compiled
.classfiles); rooted inInputStreamandOutputStream. - Character Streams: Process 16-bit Unicode characters (text files); rooted in
ReaderandWriter, handling character encoding automatically.
What is the role of FileInputStream and FileOutputStream
FileInputStream: Reads raw bytes from a physical file on disk.FileOutputStream: Writes raw bytes to a physical file on disk, supporting append or overwrite modes.
Why is BufferedReader used for reading text files instead of FileReader alone
FileReader issues a disk read for every character requested. BufferedReader reads a large chunk (default 8 KB) into a memory buffer and provides readLine() to read entire text lines efficiently, minimizing expensive disk head operations.
What is 'Serialization' in Java
The process of converting the in-memory state of an object into a sequence of bytes that can be saved to disk or transmitted across a network. A class must implement java.io.Serializable to be serializable.
What is 'Deserialization'
The reverse process of Serialization: reading a serialized byte stream from storage or network and reconstructing the original live Java object in memory using ObjectInputStream.
What is the transient keyword in Java Serialization
A modifier applied to instance variables indicating that they should NOT be serialized. During serialization, transient fields are skipped, and upon deserialization they are reset to default values (0, null) to protect sensitive data (passwords, encryption keys).
What is serialVersionUID and why is it important
A unique version identifier associated with each serializable class. During deserialization, the JVM compares the sender's serialVersionUID with the receiver's class version; if they mismatch, an InvalidClassException is thrown, preventing incompatible class schema corruption.
What is the Java Collections Framework (JCF)
A unified architecture in java.util for representing and manipulating collections of objects, providing core interfaces (List, Set, Queue, Map) and high-performance algorithms (sorting, searching).
ArrayList and LinkedList
ArrayList: Backed by a dynamic array. Fast random access O(1), slow insertions/deletions in the middle O(n) due to element shifting.LinkedList: Backed by a doubly-linked list. Fast insertions/deletions O(1), slow sequential access O(n).
Conceptual & Architectural Analysis
The Java Collection Interface Hierarchy with a Structured Diagram
+-------------------+
| Iterable<E> |
+-------------------+
^
|
+-------------------+
| Collection<E> | +-------------+
+-------------------+
^ | Map<K, V> |
+--------------------------+----------+ +-------------+
| | | ^
+-----------------+ +-----------------+ | |
| List<E> | | Set<E> | | |
+-----------------+ +-----------------+ | +--------------+
| | | | | | HashMap |
+-----------+ +--------+ +---------+ +-------+ | | TreeMap |
| ArrayList | | Linked | | HashSet | | Tree | | +--------------+
| Vector | | List | | Linked | | Set | |
+-----------+ +--------+ | HashSet | +-------+ |
+---------+ |
+-----------------+
| Queue<E> |
+-----------------+
| |
+--------+ +-------------+
| Priority| | Deque / |
| Queue | | ArrayDeque |
+--------+ +-------------+HashMap and TreeMap
| Feature | HashMap | TreeMap |
|---|---|---|
| Underlying Data Structure | Hash Table (Bucket array + Linked List/Red-Black Tree) | Red-Black Tree (Self-balancing BST) |
| Ordering | No guaranteed order | Sorted by natural key order or Comparator |
| Performance | O(1) average for get() / put() | O(\log n) guaranteed for all operations |
| Null Keys | Allows 1 null key | Does NOT allow null keys (throws NullPointerException) |
| Interfaces | Implements Map | Implements NavigableMap, SortedMap |
The File class in java.io and its Common Methods
The File class represents abstract file and directory pathnames:
createNewFile(): Creates empty file on disk.exists(): Tests existence.isDirectory()/isFile(): Tests type.length(): Returns file size in bytes.delete(): Deletes file/empty directory.mkdir()/mkdirs(): Creates directory path.list()/listFiles(): Returns directory contents.
The Difference between Comparable and Comparator Interfaces
Comparable<T>(java.lang): Defines natural ordering of a class. The class implementscompareTo(T o). Modifies the original class; single sorting sequence.Comparator<T>(java.util): Defines custom, external sorting logic. Implementscompare(T o1, T o2). Separate class without modifying the target class; multiple sorting sequences.
Scanner vs BufferedReader for Console and File Input
BufferedReader: Synchronized, fast, reads character streams with an 8 KB buffer, reads line-by-line (readLine()), requires manual parsing (Integer.parseInt()).Scanner: Non-synchronized, slower, tokenizes input using regular expressions, provides utility methods (nextInt(),nextDouble()), convenient for interactive input.
In-Depth Analysis & Implementation
Develop a Complete Student Record Management Program in Java Demonstrating File I/O, Serialization, and Deserialization
/**
* University Examination Model Solution: BCA-201N Unit 5
* Object Serialization and Persistent File Storage
*/
import java.io.*;
class StudentRecord implements Serializable {
private static final long serialVersionUID = 1002345L;
private int rollNo;
private String name;
private double marks;
private transient String confidentialPin; // Skipped during serialization
public StudentRecord(int rollNo, String name, double marks, String pin) {
this.rollNo = rollNo;
this.name = name;
this.marks = marks;
this.confidentialPin = pin;
}
public void display() {
System.out.printf("Roll: %d | Name: %-15s | Marks: %.2f | PIN: %s%n",
rollNo, name, marks, confidentialPin);
}
}
public class SerializationApplication {
private static final String DATA_FILE = "student_data.ser";
public static void main(String[] args) {
StudentRecord s1 = new StudentRecord(2401, "Rohan Gupta", 91.5, "9876");
// 1. Serialization
System.out.println("Serializing student object to disk...");
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(DATA_FILE))) {
oos.writeObject(s1);
System.out.println("Object serialized successfully!");
} catch (IOException e) {
System.err.println("Serialization error: " + e.getMessage());
}
// 2. Deserialization
System.out.println("\nDeserializing student object from disk...");
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(DATA_FILE))) {
StudentRecord restored = (StudentRecord) ois.readObject();
System.out.println("Object restored successfully! Record details:");
restored.display(); // Notice PIN will be null due to transient!
} catch (IOException | ClassNotFoundException e) {
System.err.println("Deserialization error: " + e.getMessage());
}
}
}How HashMap Works Internally in Java (Hashing, Buckets, Collision Resolution, and Java 8 Treeification)
1. Internal Storage Structure
A HashMap is an array of Node<K, V> instances (buckets). Default initial capacity is 16, with a load factor of 0.75.
2. The put(K, V) Operation
- Computes the hash:
int hash = (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16). - Computes the bucket index:
index = (n - 1) & hash. - If bucket is empty, a new
Nodeis placed. - If occupied, collision resolution executes:
- It iterates through the linked list comparing
key.equals(). - If matching key found, old value is replaced.
- Otherwise, new node is appended to the tail.
3. Java 8 Treeification Optimization
When a single bucket's linked list length reaches 8 (TREEIFY_THRESHOLD) and the total table capacity is at least 64, the linked list is dynamically transformed into a Red-Black Balanced Binary Search Tree. This upgrades the worst-case collision lookup time from O(n) to O(\log n).
Write a Program to Copy a Binary Image File from Source to Destination using Buffered Streams
1import java.io.*;2
3public class BinaryFileCopy {4 public static void main(String[] args) {5 File src = new File("source_image.png");6 File dest = new File("copy_image.png");7
8 // Using Buffered Byte Streams for high-speed block copying9 try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(src));10 BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(dest))) {11 12 byte[] buffer = new byte[4096]; // 4 KB transfer block13 int bytesRead;14 while ((bytesRead = bis.read(buffer)) != -1) {15 bos.write(buffer, 0, bytesRead);16 }17 bos.flush();18 System.out.println("Binary file copied successfully with zero data loss!");19 } catch (IOException e) {20 System.err.println("File I/O Error: " + e.getMessage());21 }22 }23}Important Exam Points & Quick Revision
Serialization with transient keyword, HashMap internal working, and Collection interface hierarchy are guaranteed high-scoring questions.
100% left on this page — finishing it closes the gap for Managing Input/Output Files, Streams & Java Utilities.
Managing Input/Output Files, Streams & Java Utilities still counts as a weak topic until you finish this note and answer its questions.
Practise this unitTest Your Understanding
Now that you've read through these notes, practice unit MCQs to identify weak points and solidify your learning before exams.