←Back to Subject
Notes
Notes
Study material and explanations
Diagrams
Diagrams
Visualize concepts easily
Mnemonics
Mnemonics
Tricks to remember faster
One Night Prep
One Night Prep
Short and focused revision
Revision
Revision
Quick summary and key points
Important Questions
Important Questions
Practice most relevant questions
Revision

Java Programming · Unit 5 Revision

Quick summary and key points for Unit 5

Input/Output: Exploring java.io, Directories (File Class) & Stream Classes

Overview: A directory entry tells you that a file exists, while a stream lets you read its contents.

Exploring the java.io Package

  • Almost every real-world program needs to read input data (from a keyboard, a disk file, or a network socket) and write output data (to the…
  • Inspecting and managing Files and Directories on the hard disk (File class).
  • Reading and writing raw binary data using Byte Streams (InputStream, OutputStream).
  • Reading and writing 16-bit Unicode text using Character Streams (Reader, Writer).
  • Saving and restoring complete Java objects using Object Serialization (Serializable).

The File Class and Working with Directories

  • The java.io.File class is an abstract representation of file and directory (folder) pathnames on your computer’s hard disk.
  • Important Exam Fact: Creating a File object (File f = new File("notes.txt");) does NOT read or write data inside the file!
  • Constructors of the File Class: File f1 = new File("C:/BCA/notes.txt"); — Points to a specific file or directory path.
  • File f2 = new File("C:/BCA", "syllabus.pdf"); — Specifies parent directory path and child filename separately.
  • exists(): boolean
  • getName(): String
  • getAbsolutePath(): String
  • length(): long

What is a Stream in Java?

  • A Stream is a continuous, ordered flow (pipeline) of data between a Source (keyboard, file, network) and a Destination (screen,…
    • Input Stream: Water flowing into your house (Reading data into your Java program from an external source).
    • Output Stream: Water flowing out of your house (Writing data out of your Java program to an external destination).
  • Standard Built-in Streams in java.lang.System: Java automatically opens three ready-to-use streams inside the System class for every program:
  • System.in (InputStream): Standard Input Stream — connected to the Keyboard by default.
  • System.out (PrintStream): Standard Output Stream — connected to the Console Screen by default.
  • System.err (PrintStream): Standard Error Stream — used to display error messages on the screen.

View diagram · Figure 5.1: Concept of Input Stream and Output Stream in Java

Classification of Java Stream Classes (Byte vs Character Streams)

  • All stream classes in java.io are divided into two major hierarchies based on the type of data they handle:
  • 1. Byte Streams (8-Bit Raw Binary) Root Classes: InputStream & OutputStream
  • 2. Character Streams (16-Bit Unicode Text) Root Classes: Reader & Writer
  • 1. Data Unit: Operates on 8-bit bytes (1 byte at a time).
  • 2. Abstract Root Classes: InputStream (for reading) and OutputStream (for writing).
  • 3. Naming Convention: Class names always end with InputStream or OutputStream.
  • 4. Best Used For: Binary files: Images (.jpg, .png), MP3 audio, videos, .class files, .zip.
  • 5. Core File Classes: FileInputStream and FileOutputStream.

View diagram · Figure 5.2: Hierarchy of Java I/O Stream Classes (java.io)

The Byte Stream: InputStream, OutputStream, File I/O, PrintStream & RandomAccessFile

Overview: A byte stream can copy an image without interpreting its bytes as text.

Abstract Superclasses of Byte Streams: InputStream & OutputStream

  • All byte stream classes in java.io descend from two abstract superclasses that handle 8-bit raw bytes:
  • A. InputStream (Abstract Root Class for Reading Bytes): Defines the fundamental methods that every byte input stream must implement:
  • int read(): Reads the next single byte of data from the input stream (returns an int between 0 and 255), or returns -1…
  • int read(byte[] b): Reads a chunk of bytes into the byte array b and returns the number of bytes actually read.
  • int available(): Returns the number of bytes currently available for reading without blocking.
  • void close(): Closes the input stream and releases any OS file locks.
  • B. OutputStream (Abstract Root Class for Writing Bytes): Defines the fundamental methods that every byte output stream must implement:
  • void write(int b): Writes a single byte to the output stream.

FileInputStream and FileOutputStream

  • These are the two most commonly used concrete byte stream classes for reading from and writing to actual files on your computer’s hard disk.
  • A. FileOutputStream (Writing Bytes to a File): Used to create a file and write raw byte data into it.
  • If the specified file does not exist on disk, FileOutputStream automatically creates a new file!
  • Constructors:
  • FileOutputStream fos = new FileOutputStream("data.txt"); (Overwrites existing file)
  • FileOutputStream fos = new FileOutputStream("data.txt", true); (Appends to the end of the file because append = true)
  • B. FileInputStream (Reading Bytes from a File): Used to read raw bytes from an existing file on disk (such as a text file, image, or audio file).
  • Throws FileNotFoundException if the file does not exist.

The PrintStream Class

  • Have you ever wondered how System.out.println() works?
  • What is PrintStream? PrintStream is a byte output stream (subclass of FilterOutputStream) that adds convenient methods to print **any data…
  • 2 Unique Features of PrintStream:
  • Never Throws IOException! Unlike other streams, PrintStream catches IOException internally and sets an internal error flag that can be checked via…
  • Auto-Flushing: Can be configured to flush the output buffer automatically whenever a newline character (\n) is written.
  • Key Methods: print(), println(), printf(), format(), checkError().

RandomAccessFile in Java

  • All standard streams (FileInputStream, FileOutputStream, FileReader) are Sequential Access Streams—meaning you must start at byte 0…
  • Key Features of RandomAccessFile: Supports Both Reading and Writing: Implements both DataInput and DataOutput interfaces in a single class!
  • Movable File Pointer (seek): Maintains an internal cursor called the File Pointer (like the cursor in Notepad) that you can move forward or backward…
  • Access Modes in Constructor (new RandomAccessFile(file, mode)):
  • "r" (Read-Only): Opens the file for reading only.
  • "rw" (Read and Write): Opens the file for both reading and writing (creates the file if it doesn’t exist).
  • Important Methods of RandomAccessFile: void seek(long pos): Moves the file-pointer offset to byte position pos from the beginning of the file.
  • long getFilePointer(): Returns the current byte offset location of the file pointer.

View diagram · Figure 5.3: Sequential Stream vs RandomAccessFile (seek() Pointer)

Character Streams, BufferedReader, BufferedWriter, PrintWriter & Serialization

Overview: A reader decodes bytes into characters using an encoding.

The Character Streams (Reader and Writer)

  • While Byte Streams (InputStream / OutputStream) read and write 8-bit raw bytes, Character Streams are designed specifically for reading…
  • Abstract Root Classes of Character Streams: java.io.Reader (For Reading Characters):
  • int read(): Reads a single character (returns -1 at End of File).
  • int read(char[] cbuf): Reads characters into a char array.
  • void close(): Closes the stream.
  • Concrete File Subclass: FileReader (new FileReader("notes.txt")).
  • java.io.Writer (For Writing Characters):
  • void write(int c): Writes a single character.

BufferedReader and BufferedWriter (High-Speed Buffered Text I/O)

  • Reading or writing a file one single character at a time directly from the hard disk (FileReader / FileWriter) is slow because every…
  • A. BufferedReader: Wraps around any Reader (like FileReader or InputStreamReader) to buffer input and provide the super-useful readLine() method!
  • Star Method — String readLine(): Reads an entire line of text at once and returns it as a String (returns null when the End of File is reached).
  • B. BufferedWriter: Wraps around any Writer (like FileWriter) to buffer characters in RAM before writing them in bulk to the disk.
  • Star Method — void newLine(): Writes a platform-independent line separator (\r\n on Windows, \n on Linux/Mac).

View diagram · Figure 5.4: How BufferedReader Speeds Up File Reading Using a RAM Buffer

The PrintWriter Class

  • PrintWriter is the Character-Stream equivalent of PrintStream!
  • Just like PrintStream, PrintWriter provides convenient print(), println(), and printf() methods for all primitive…
  • Why is PrintWriter preferred over PrintStream for text files? Because PrintWriter is a Character Stream (Writer) that properly supports 16-bit Unicode characters and…

Serialization in Java (Saving & Restoring Objects)

  • Normally, when your Java program terminates, all objects living in Heap memory are wiped out.
  • Serialization: The process of converting the state of a live Java Object into a linear sequence of bytes (Byte Stream) so that it can…
  • Deserialization: The reverse process of reconstructing the live Java Object in memory from the saved Byte Stream.
  • Key Components of Serialization: java.io.Serializable Interface (Marker Interface):
  • A class MUST implement the Serializable interface to allow its objects to be serialized (class Student implements Serializable).
  • What is a Marker Interface? An empty interface with zero methods!
  • ObjectOutputStream & writeObject(Object obj):
  • ObjectInputStream & readObject():

View diagram · Figure 5.5: Object Serialization and Deserialization in Java

JDBC: JDBC-ODBC Bridge, Connectivity Model, DriverManager & java.sql Package

Overview: JDBC gives Java code a common way to request a connection and issue SQL.

What is JDBC (Java Database Connectivity)?

  • JDBC is a standard Java API (Application Programming Interface) provided in the java.sql package that enables a Java program to…
  • Why do we need JDBC?
  • Every database vendor (Oracle, MySQL, Microsoft) writes their database server using different internal protocols.

The JDBC Connectivity Model (Architecture)

  • The JDBC Connectivity Model defines how a Java application communicates with a database through two layers:
  • JDBC API Layer (java.sql): Provides application-to-JDBC Manager communication (used by the Java programmer).
  • JDBC Driver API Layer: Supports JDBC Manager-to-Driver communication (implemented by database vendors like MySQL or Oracle).
  • Two-Tier vs Three-Tier Connectivity Models: Two-Tier Model (Client-Server): The Java application (Client) talks directly to the Database Server using a JDBC Driver.
  • Three-Tier Model (Web/Enterprise): The Client browser talks to an Application Server (Middle Tier) running Java, which in turn uses JDBC to talk to the…

View diagram · Figure 5.6: The JDBC Connectivity Model (Architecture)

JDBC-ODBC Bridge & The 4 Types of JDBC Drivers

  • To connect a Java application to a database, we need a JDBC Driver.
  • Type-1 Driver: The JDBC-ODBC Bridge Driver (sun.jdbc.odbc.JdbcOdbcDriver): How it Works: In the early days of Java, Microsoft’s ODBC (Open Database Connectivity) was already widely installed on Windows…
  • Advantages of JDBC-ODBC Bridge:
  • Allows Java to connect to almost any database (like MS Access or Excel) for which an ODBC driver is installed on the computer.
  • Disadvantages of JDBC-ODBC Bridge:
  • Platform Dependent: Requires native C/C++ ODBC drivers and a DSN (Data Source Name) configured on the client OS.
  • Slow Performance: Every SQL query must undergo two translations (Java JDBC → C ODBC → Native DB protocol).
  • (Removed in Java 8+ in favor of Type-4 Pure Java Drivers).

View diagram · Figure 5.7: How the Type-1 JDBC-ODBC Bridge Driver Works

The DriverManager Class

  • java.sql.DriverManager is the central management class of JDBC that sits between the Java application and the registered JDBC Drivers.
  • Role of DriverManager: It maintains a list of all loaded Driver classes.
  • Key Static Methods of DriverManager: static Connection getConnection(String url, String user, String password):
  • static void registerDriver(Driver driver):
  • static void setLoginTimeout(int seconds):

Exploring the java.sql Package (Core Interfaces & Classes)

  • The java.sql package contains the core interfaces and classes that every BCA student uses in JDBC programs:
  • 1. DriverManager: Class
  • 2. Connection: Interface
  • 3. Statement: Interface
  • 4. PreparedStatement: Interface
  • 5. CallableStatement: Interface
  • 6. ResultSet: Interface

JDBC: Navigating ResultSet, JDBC Exception Classes & Connecting to a Remote Database

Overview: A ResultSet begins before its first row.

  • When you execute a SQL SELECT query using ResultSet rs = stmt.executeQuery("SELECT * FROM students");, the database returns a virtual table…
  • How the ResultSet Cursor Works: A ResultSet object maintains an internal pointer called a Cursor, which initially points just BEFORE the first row (Row 0).
  • Calling rs.next() moves the cursor forward to the first row and returns true.
  • A. Forward-Only vs Scrollable ResultSet: By default, a ResultSet is TYPE_FORWARD_ONLY and CONCUR_READ_ONLY (meaning the cursor can only move downward from top…
  • boolean next(): Moves the cursor forward one row from its current position.
  • boolean previous(): Moves the cursor backward one row (Requires Scrollable ResultSet).
  • boolean first(): Moves the cursor directly to the very first row of the ResultSet.
  • boolean last(): Moves the cursor directly to the very last row of the ResultSet.

View diagram · Figure 5.8: Navigating Rows Inside a Scrollable ResultSet Object

The JDBC Exception Classes (SQLException & Subclasses)

  • Whenever an error occurs while interacting with a database (such as wrong database password, invalid SQL syntax, duplicate primary key, or lost…
  • 1. java.sql.SQLException: The core exception class that provides information on any database access error.
  • String getMessage(): Returns a human-readable description of the error (e.g., "Table 'college.students' doesn't exist").
  • String getSQLState(): Returns a 5-character standard X/Open or SQL:2003 code identifying the error category (e.g., "42S02" for missing table,…
  • int getErrorCode(): Returns the database vendor’s specific integer error code (e.g., MySQL Error 1045 for Access Denied).
  • SQLException getNextException(): Chains to the next SQLException if multiple errors occurred together.
  • 2. SQLWarning: A subclass of SQLException that represents non-fatal database warnings.
  • 3. BatchUpdateException: Thrown when an error occurs during a batch update operation (stmt.executeBatch()).

View diagram · Figure 5.9: Hierarchy of JDBC Exception Classes (java.sql.SQLException)

Connecting to a Remote Database (The 7 Standard JDBC Steps)

  • Connecting a Java program to a Remote Database (a MySQL or Oracle database server hosted on another machine over a LAN or the Internet,…
  • Format of a Remote JDBC Connection URL: A JDBC URL begins with jdbc and a driver-specific subprotocol.
  • The 7 Steps to Connect to a Database in Java (Memorize in Order!): Step 1: Import the java.sql.* package (import java.sql.*;).
  • Step 2: Load and Register the JDBC Driver (Class.forName("com.mysql.cj.jdbc.Driver");).
  • Step 3: Establish the Connection to the Remote Database using DriverManager.getConnection(url, user, password).
  • Step 4: Create a Statement or PreparedStatement object (conn.createStatement()).
  • Step 5: Execute the SQL Query (stmt.executeQuery(...) or stmt.executeUpdate(...)).
  • Step 6: Process and Navigate the ResultSet (`while (rs.next()) { …

View diagram · Anatomy of a JDBC Connection URL