0% found this document useful (0 votes)
7 views25 pages

? What is a Java Package

A Java package is a namespace that organizes related classes and interfaces, helping to avoid naming conflicts and control access. There are built-in packages provided by Java and user-defined packages created by developers. Exception handling in Java allows for managing runtime errors, while method overloading and overriding enable polymorphism, and multithreading allows concurrent execution of threads for better performance.

Uploaded by

arul85700
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)
7 views25 pages

? What is a Java Package

A Java package is a namespace that organizes related classes and interfaces, helping to avoid naming conflicts and control access. There are built-in packages provided by Java and user-defined packages created by developers. Exception handling in Java allows for managing runtime errors, while method overloading and overriding enable polymorphism, and multithreading allows concurrent execution of threads for better performance.

Uploaded by

arul85700
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/ 25

� What is a Java Package?

A Java package is a namespace that organizes a set of related classes and interfaces. Think of
it as a folder in a file system that contains Java files grouped based on their purpose or
functionality.
Packages help:
• Avoid class name conflicts
• Organize code logically
• Control access (via public, protected, etc.)
• Make code modular and maintainable

� Types of Packages in Java


1. Built-in Packages (Predefined by Java)
o Provided by the Java API.
o Examples:
 java.lang – fundamental classes (automatically imported)
 java.util – data structures like ArrayList, HashMap
 java.io – input-output operations
 java.sql – database connectivity
 javax.swing – GUI components
2. User-defined Packages
o Created by developers to structure code.

🛠🛠 How to Create and Use a Package


1. Create a Package
// Save this file as MyClass.java
package mypackage;

public class MyClass {


public void display() {
System.out.println("Hello from mypackage!");
}
}
2. Compile with Package
Navigate to the folder where MyClass.java is located, then compile:
bash
javac -d . MyClass.java

• -d . tells the compiler to create the package folder structure starting from the current
directory.
Now, you’ll have:
vbnet
CopyEdit
mypackage/
└── MyClass.class
3. Use the Package in Another File
// Save this as TestPackage.java
import mypackage.MyClass;
public class TestPackage {
public static void main(String[] args) {
MyClass obj = new MyClass();
obj.display();
}
}
Compile and run:
bash
CopyEdit
javac TestPackage.java
java TestPackage

� Package Naming Convention


• Reverse domain name is commonly used:
CopyEdit
com.example.project
org.openai.chat
• Avoid Java reserved keywords.
• All lowercase for consistency.

� Access Modifiers and Packages


Access levels relative to packages:
Modifier Same Class Same Package Subclass Other Package
public � � � �
protected � � � �
(no modifier) � � � �
private � � � �

� Advantages of Packages
• Avoids naming conflicts (two classes with same name in different packages)
• Improves modularity
• Simplifies maintenance
• Access control using modifiers

� Example with Sub-packages


java
CopyEdit
package mypackage.subpackage;

public class SubClass {


public void show() {
System.out.println("Inside subpackage class");
}
}
Sub-packages must be imported explicitly.
p

� What is Exception Handling?


Exception Handling in Java is a mechanism to handle runtime errors so that the normal flow
of the program can be maintained.
An exception is an event that occurs during the execution of a program that disrupts the
normal flow of instructions.

� Types of Exceptions in Java


Java divides exceptions into three categories:
1. Checked Exceptions (Compile-time)
• Must be either caught or declared using throws.
• Examples:
o IOException
o SQLException
o FileNotFoundException
public void readFile() throws IOException {
FileReader fr = new FileReader("file.txt");
}
2. Unchecked Exceptions (Runtime)
• Occur at runtime; not checked at compile-time.
• Subclass of RuntimeException.
• Examples:
o NullPointerException
o ArithmeticException
o ArrayIndexOutOfBoundsException
int a = 10 / 0; // ArithmeticException
3. Errors
• Not meant to be caught (serious problems).
• Examples:
o OutOfMemoryError
o StackOverflowError

� Basic Syntax
try {
// Code that may cause an exception
} catch (ExceptionType1 e1) {
// Handle exception type 1
} catch (ExceptionType2 e2) {
// Handle exception type 2
} finally {
// Code that always executes
}

� Example
public class Example {
public static void main(String[] args) {
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Error: Division by zero.");
} finally {
System.out.println("This block always runs.");
}
}
}
Output:
Error: Division by zero.
This block always runs.

� Multiple Catch Blocks


try {
int[] arr = new int[5];
arr[10] = 50;
} catch (ArithmeticException e) {
System.out.println("Math error.");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array error.");
} catch (Exception e) {
System.out.println("General exception.");
}

� The finally Block


• Always executes after try-catch, regardless of whether an exception occurred.
• Often used for clean-up (like closing files or database connections).
finally {
System.out.println("Closing resources...");
}

� Throwing Exceptions
You can manually throw an exception using the throw keyword.
throw new IllegalArgumentException("Invalid input");
Declaring with throws
public void connect() throws IOException {
// code that may throw IOException
}

� Custom Exceptions
You can create your own exceptions by extending Exception or RuntimeException.
class AgeException extends Exception {
public AgeException(String message) {
super(message);
}
}
Use it:
if (age < 18) {
throw new AgeException("You must be 18 or older.");
}

� Best Practices
1. Catch specific exceptions first, then general ones.
2. Don’t swallow exceptions (avoid empty catch blocks).
3. Use finally or try-with-resources to close resources.
4. Avoid using exceptions for flow control.
5. Log exception details for debugging.
6. Create custom exceptions for domain-specific errors.

� Real-World Use Case: File Handling


import java.io.*;

public class FileReadExample {


public static void main(String[] args) {
try {
BufferedReader reader = new BufferedReader(new FileReader("data.txt"));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
} catch (FileNotFoundException e) {
System.out.println("File not found.");
} catch (IOException e) {
System.out.println("I/O error occurred.");
} finally {
System.out.println("Finished processing the file.");
}
}
}

Would you like a flowchart showing how try-catch-finally works internally?


Sure! Let's go deeper into the theory of method overloading and method overriding in Java,
including their rules, design principles, and under-the-hood behavior.

� 1. Method Overloading – In Depth


� What is it?
Method overloading is a form of static polymorphism, also known as compile-time
polymorphism. It allows a class to have more than one method with the same name, as long
as their parameter lists differ.
This makes your code more readable and easier to maintain. It’s commonly used when similar
operations need to be performed with different inputs.

� Rules of Overloading:
1. Methods must have different parameter lists:
o Different number of parameters, or
o Different types of parameters, or
o Different order of parameters (if types differ).
2. Return type can be different but does not matter in overloading.
3. Can also overload constructors.

� Why Overload?
• Improves code readability.
• Supports DRY (Don't Repeat Yourself) principle.
• Useful when the same logic applies to different types of input.

� Example Explained:
class Printer {
void print(String s) {
System.out.println("String: " + s);
}

void print(int i) {
System.out.println("Integer: " + i);
}

void print(String s, int i) {


System.out.println("String and Integer: " + s + ", " + i);
}
}
Here, all methods are named print, but Java knows which one to call based on the arguments
provided. This decision is made by the compiler.

� 2. Method Overriding – In Depth


� What is it?
Method overriding is a form of dynamic polymorphism, or runtime polymorphism. It occurs
when a subclass provides a specific implementation of a method that is already defined in its
superclass.
� Rules of Overriding:
1. The method in the child class must have:
o Same name
o Same parameter list
o Same return type (or subtype – called covariant return)
2. The access level cannot be more restrictive.
o For example, if the superclass method is public, the overriding method must
also be public.
3. Only instance methods can be overridden.
o Static methods are hidden, not overridden.
4. The method cannot be private, final, or static in the superclass.
5. Can use @Override annotation for safety and clarity.

� Why Override?
• To customize or extend behavior of a superclass method.
• It supports runtime polymorphism, allowing different behaviors based on the object’s
actual type.

� Example with Theory:


class Vehicle {
void start() {
System.out.println("Vehicle is starting");
}
}

class Car extends Vehicle {


@Override
void start() {
System.out.println("Car is starting with key");
}
}
Vehicle v = new Car();
v.start(); // Outputs: Car is starting with key
Even though v is declared as Vehicle, the actual object is of type Car. At runtime, Java calls the
overridden method in Car.
This is possible because Java uses a mechanism called dynamic dispatch (method lookup at
runtime) for overridden methods.

� Key Differences Between Overloading and Overriding


Feature Method Overloading Method Overriding
Relationship Happens in the same class Happens in parent-child class
Method Signature Must differ in parameter list Must be identical
Return Type Can be different Must be same or covariant
Access Modifier No restriction Cannot be more restrictive
Static/Instance Can be static or instance methods Only instance methods
Polymorphism Type Compile-time polymorphism Runtime polymorphism
Feature Method Overloading Method Overriding
Binding Early (static) binding Late (dynamic) binding

� Additional Notes
� Static Methods:
• Overloading static methods is allowed.
• Overriding static methods is not allowed — it's called method hiding.
� Final Methods:
• Cannot be overridden.
• Can be overloaded.
� Private Methods:
• Cannot be overridden (they are not inherited).
• Can be overloaded within the same class.

� Summary:
Concept Method Overloading Method Overriding
What it does Same method name, different args Same method signature, different class
Purpose Improves usability Changes inherited behavior
Decided at Compile time Runtime
Example use-case Print(), Print(String), etc. Custom toString() in subclass

Would you like me to generate a diagram to visually show the difference or a Java program
example for hands-on understanding?
Multithreaded programming in Java is a powerful concept that allows multiple threads to
execute concurrently. This is essential for tasks like real-time applications, games, file
downloads, or any program where you want better performance or responsiveness.

� What is Multithreading?
Multithreading is a Java feature that allows the concurrent execution of two or more threads
(lightweight subprocesses). It enables the CPU to perform multiple operations simultaneously,
improving the performance of complex or time-consuming programs.

� Thread Basics
� What is a Thread?
A thread is a lightweight unit of a process. A single process can contain multiple threads, all
running in parallel and sharing the same memory space.

� Creating Threads in Java


� 1. By Extending Thread Class:
class MyThread extends Thread {
public void run() {
System.out.println("Thread is running...");
}
}

public class Test {


public static void main(String[] args) {
MyThread t1 = new MyThread();
t1.start(); // starts a new thread, calls run()
}
}
� 2. By Implementing Runnable Interface:
class MyRunnable implements Runnable {
public void run() {
System.out.println("Thread is running...");
}
}

public class Test {


public static void main(String[] args) {
Thread t1 = new Thread(new MyRunnable());
t1.start();
}
}
� Thread.start() vs Thread.run()
• start() launches a new thread and then calls run().
• run() alone just executes like a normal method on the current thread (no
multithreading).

� Thread Life Cycle


A thread in Java goes through these states:
1. New – Thread is created.
2. Runnable – Thread is ready to run but waiting for CPU.
3. Running – Thread is executing.
4. Blocked/Waiting – Thread is paused for a resource or another thread.
5. Terminated/Dead – Thread has completed execution.

� Multithreading Advantages
Benefit Description
Faster execution Threads run concurrently, utilizing multiple cores.
Resource sharing Threads share the same memory, reducing overhead.
Responsive UI Used in GUIs to keep the interface responsive.
Better use of CPU Ideal for modern multi-core processors.

� Thread Methods
Method Purpose
start() Starts the thread and calls run() method
run() Code that is executed in the new thread
sleep(ms) Pauses the thread for given milliseconds
join() Waits for another thread to finish
isAlive() Checks if thread is still running
setPriority() Sets the priority of the thread

� Thread Synchronization
When multiple threads access shared resources, they must be synchronized to avoid race
conditions.
� Synchronized Example:
class Table {
synchronized void printTable(int n) {
for (int i = 1; i <= 5; i++) {
System.out.println(n * i);
}
}
}
Use of synchronized ensures only one thread can access that block of code at a time.

� Real-World Example
class Bank {
int balance = 1000;

synchronized void withdraw(int amount) {


if (balance >= amount) {
System.out.println("Withdrawing: " + amount);
balance -= amount;
System.out.println("Remaining Balance: " + balance);
} else {
System.out.println("Insufficient balance");
}
}
}

class Customer extends Thread {


Bank b;

Customer(Bank b) {
this.b = b;
}

public void run() {


b.withdraw(600);
}
}

public class Main {


public static void main(String[] args) {
Bank bank = new Bank();
Customer c1 = new Customer(bank);
Customer c2 = new Customer(bank);
c1.start();
c2.start();
}
}
Without synchronization, both threads may access and modify the balance at the same time,
causing inconsistent results.

� Common Problems in Multithreading


Problem Description
Race condition Two threads access and change shared data simultaneously
Deadlock Two threads waiting on each other forever
Starvation A thread never gets CPU time
Livelock Threads keep changing states, but never finish work

� Summary
Feature Description
Lightweight Threads share the same memory, more efficient than processes
Concurrent Multiple threads can run in parallel
Java support Java has built-in Thread class and Runnable interface
Control methods start(), sleep(), join(), yield(), wait(), notify(), etc.
Safety Use synchronized, volatile, and thread-safe collections
Certainly! Let's go into greater detail on each topic you asked about in Java I/O Streams,
breaking down concepts, uses, and examples step by step.

� 1. Concept of Streams in Java


➤ What is a Stream?
A stream is a continuous flow of data. In Java:
• An Input Stream is used to read data from a source (keyboard, file, network, etc.).
• An Output Stream is used to write data to a destination (console, file, printer, etc.).
Think of a stream like a pipeline or a tap: Input brings data into your program, and Output sends
data out of it.

� 2. Stream Classes in Java


All stream classes in Java are part of the java.io package. These classes are divided into:
➤ A) Byte Streams
• Handle raw binary data (e.g., images, audio, video).
• Uses 8-bit byte data.
• Useful when you're working with non-text files.
Base Classes:
• Input: InputStream
• Output: OutputStream
Important Byte Stream Classes:
Class Description
FileInputStream Reads data from a file (binary data)
FileOutputStream Writes binary data to a file
BufferedInputStream Adds buffering for better performance
DataInputStream Reads primitive data types
ObjectInputStream Reads serialized objects

➤ B) Character Streams
• Handle text data (Unicode characters).
• Uses 16-bit char data.
• Better suited for working with text files.
Base Classes:
• Input: Reader
• Output: Writer
Important Character Stream Classes:
Class Description
FileReader Reads characters from a file
FileWriter Writes characters to a file
BufferedReader Reads text efficiently, line by line
BufferedWriter Writes text efficiently
PrintWriter Writes formatted text

� 3. Byte vs Character Stream - Detailed Comparison


Feature Byte Stream Character Stream
Handles Binary data (audio, image) Text data
Base classes InputStream, OutputStream Reader, Writer
Data type byte (8-bit) char (16-bit)
Example classes FileInputStream, FileOutputStream FileReader, FileWriter
Use case Reading MP3, PDF, etc. Reading .txt, .java files

� 4. Reading Console Input and Writing Console Output


➤ A) Reading Console Input
i. Using Scanner Class
import java.util.Scanner;

public class InputExample {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = sc.nextLine();
System.out.println("Hello, " + name);
}
}
ii. Using BufferedReader Class
import java.io.*;

public class BufferedReaderExample {


public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter age: ");
String age = reader.readLine();
System.out.println("You entered: " + age);
}
}
Note: BufferedReader is older, but efficient for line-by-line reading. Scanner is more flexible.

➤ B) Writing Console Output


Always done using:
System.out.print(); // Prints without newline
System.out.println(); // Prints with newline
System.out.printf(); // Formatted output
Example:
int marks = 95;
System.out.println("Marks: " + marks);
System.out.printf("Marks (formatted): %.2f", (float)marks);

� 5. File Handling in Java


Java provides several classes to work with files — read, write, delete, create, etc.
➤ A) Working with File Class
Used for file metadata and manipulation (check if file exists, size, permissions, etc.).
import java.io.File;

public class FileExample {


public static void main(String[] args) {
File file = new File("test.txt");

if (file.exists()) {
System.out.println("File name: " + file.getName());
System.out.println("Absolute path: " + file.getAbsolutePath());
System.out.println("Writable: " + file.canWrite());
System.out.println("Readable: " + file.canRead());
System.out.println("File size: " + file.length() + " bytes");
} else {
System.out.println("The file does not exist.");
}
}
}

➤ B) Reading from a File


i. Using FileReader (Character Stream)
import java.io.*;

public class ReadFileExample {


public static void main(String[] args) throws IOException {
FileReader fr = new FileReader("input.txt");
int i;
while ((i = fr.read()) != -1) {
System.out.print((char) i);
}
fr.close();
}
}
ii. Using BufferedReader (Efficient)
BufferedReader br = new BufferedReader(new FileReader("input.txt"));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();

➤ C) Writing to a File
i. Using FileWriter
FileWriter fw = new FileWriter("output.txt");
fw.write("Welcome to Java File Handling");
fw.close();
ii. Using BufferedWriter (Efficient)
BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"));
bw.write("This is written using BufferedWriter.");
bw.newLine(); // Moves to next line
bw.write("Second line");
bw.close();

� BONUS: Best Practices


1. Always close streams using .close() or use try-with-resources.
2. Use buffered classes (BufferedReader, BufferedWriter) for performance.
3. Use Scanner for simple console input.
4. Use PrintWriter for formatted file output.

� Summary Diagram (Text Format)


+--------------------+
| Java I/O |
+--------------------+
|
+---------------+---------------+
| |
Byte Streams Character Streams
(InputStream/OutputStream) (Reader/Writer)
| |
FileInputStream FileReader
FileOutputStream FileWriter
BufferedInputStream BufferedReader
BufferedOutputStream BufferedWriter
Would you like a visual version of this diagram or any real-world examples added?
Sure! Let’s dive in detail into File Handling in Java — how to create, read, write, and delete files
using Java's java.io and java.nio.file packages.

� What is File Handling?


File Handling in Java is the process of:
• Creating files
• Reading data from files
• Writing data into files
• Deleting or checking properties of files
Java provides these capabilities through classes in:
• java.io package (traditional)
• java.nio.file package (newer, more modern)

� 1. Creating a File
To create a file in Java, use the File class from java.io.
import java.io.File;
import java.io.IOException;

public class CreateFileExample {


public static void main(String[] args) {
try {
File file = new File("example.txt");
if (file.createNewFile()) {
System.out.println("File created: " + file.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}

� 2. Writing to a File
➤ A) Using FileWriter (for text)
import java.io.FileWriter;
import java.io.IOException;

public class WriteToFile {


public static void main(String[] args) {
try {
FileWriter writer = new FileWriter("example.txt");
writer.write("Hello, Java file handling!\n");
writer.write("This is a second line.");
writer.close();
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
FileWriter overwrites by default. Use new FileWriter("file.txt", true) to append.

� 3. Reading from a File


➤ A) Using FileReader and BufferedReader:
import java.io.*;

public class ReadFromFile {


public static void main(String[] args) {
try {
BufferedReader reader = new BufferedReader(new FileReader("example.txt"));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
BufferedReader is preferred over FileReader alone because it's more efficient for reading large
files.

� 4. Appending to a File
Use FileWriter with the second argument as true.
FileWriter writer = new FileWriter("example.txt", true);
writer.write("\nAppended content.");
writer.close();

� 5. Deleting a File
Use the File.delete() method.
File file = new File("example.txt");
if (file.delete()) {
System.out.println("Deleted the file: " + file.getName());
} else {
System.out.println("Failed to delete the file.");
}

� 6. File Properties and Checks


File file = new File("example.txt");

if (file.exists()) {
System.out.println("File name: " + file.getName());
System.out.println("Absolute path: " + file.getAbsolutePath());
System.out.println("Readable: " + file.canRead());
System.out.println("Writable: " + file.canWrite());
System.out.println("File size: " + file.length() + " bytes");
} else {
System.out.println("The file does not exist.");
}

� 7. Working with java.nio.file (Optional, Modern API)


import java.nio.file.*;

public class NioExample {


public static void main(String[] args) {
Path path = Paths.get("example.txt");

try {
String content = Files.readString(path);
System.out.println(content);
} catch (IOException e) {
e.printStackTrace();
}
}
}

� Summary of Classes Used


Class Purpose
File Create, delete, and check file properties
FileWriter Write characters to a file
BufferedWriter Efficiently write characters
FileReader Read characters from a file
BufferedReader Efficiently read characters
Scanner Read file content easily
Files (from java.nio.file) modern way to handle files

Would you like this content in a PDF study sheet or visual diagram?
Absolutely! Here's a more in-depth theoretical explanation of all the concepts related to
Event Handling in Java, suitable for understanding, revising for exams, or preparing notes.

� EVENT HANDLING IN JAVA — THEORY

� 1. What is Event Handling?


Event handling is a mechanism that allows Java programs to respond to user interactions or
other occurrences (called events) at runtime. This includes actions like:
• Clicking a button
• Pressing a key
• Moving or clicking a mouse
• Selecting a checkbox
• Opening or closing a window
Java uses the Event Delegation Model (EDM) to handle these events.

� 2. Components of Event Handling


Event handling in Java is composed of the following parts:
Component Description
Event An object that represents the occurrence of an action
Event Source The component that generates the event (e.g., Button, TextField)
Event
An interface that listens and responds to events
Listener
An instance of a class like ActionEvent, KeyEvent, etc., carrying information
Event Object
about the event

� 3. Event Classes (Event Objects)


Java provides a set of event classes in the java.awt.event package. These classes define
different types of events:
Event Class Description
ActionEvent Generated when a button is clicked
ItemEvent Generated when an item is selected (e.g., in a combo box)
KeyEvent Generated when a key is pressed, released, or typed
MouseEvent Generated when mouse actions occur
WindowEvent Generated for window operations (open, close, minimize, etc.)
FocusEvent Generated when a component gains or loses focus
TextEvent Generated when text changes in a text component

� 4. Event Sources
Any GUI component that can fire an event is an event source. When an interaction happens on
these components, it triggers the event.
➤ Common Event Sources:
• Button
• TextField
• Checkbox
• List
• MenuItem
• Window
Example: Clicking a Button generates an ActionEvent.

� 5. Event Listeners
An event listener is an interface that defines one or more methods to be implemented in order
to respond to an event.
You register a listener to a source using addXListener() methods.
➤ Common Event Listener Interfaces:
Listener Interface Description Main Method(s)
ActionListener Handles action events actionPerformed()
KeyListener Handles key events keyPressed(), keyReleased(), keyTyped()
MouseListener Handles mouse button events mouseClicked(), mousePressed(), etc.
MouseMotionListener Handles mouse movement mouseMoved(), mouseDragged()
WindowListener Handles window events windowClosing(), windowOpened(), etc.
ItemListener Handles item selection itemStateChanged()
You must implement the interface and override the required methods.

� 6. Event Delegation Model (EDM)


➤ Definition:
The Event Delegation Model is Java’s standard mechanism to handle events. It follows a
producer-consumer model:
• Event Source: The object that generates the event.
• Event Listener: The object that listens and handles the event.
➤ Steps:
1. User performs an action on a component (e.g., clicks a button).
2. That component (source) creates an Event object.
3. It sends the event object to all registered Listener objects.
4. The listener executes the appropriate method to respond to the event.
➤ Advantages:
• Clean separation between event generation and handling
• Easier to manage complex user interactions
• Reusable event-handling code

� 7. Handling Mouse and Keyboard Events


➤ Mouse Events:
Handled using MouseListener and MouseMotionListener.
• Example: mouseClicked(), mouseEntered(), etc.
➤ Keyboard Events:
Handled using KeyListener.
• Example: keyTyped(), keyPressed(), keyReleased()
Each method receives an event object (MouseEvent, KeyEvent) that contains:
• Event source
• Mouse/Key position or character
• Modifiers (e.g., Ctrl, Shift pressed)

� 8. Adapter Classes
➤ What is an Adapter Class?
Some listener interfaces have multiple abstract methods (like MouseListener has 5). If you
only want to use one or two, it becomes tedious to implement all.
Adapter classes solve this by providing empty implementations of all methods, so you can
override only what you need.
➤ Examples:
Adapter Class Corresponding Listener
MouseAdapter MouseListener
KeyAdapter KeyListener
WindowAdapter WindowListener
➤ Benefits:
• Cleaner, shorter code
• Only override needed methods

� 9. Inner Classes in Event Handling


➤ What is an Inner Class?
A class declared inside another class. In GUI programming, inner classes are often used to
handle events.
➤ Types Used in Event Handling:
• Anonymous Inner Classes: No class name; declared and instantiated on the spot.
• Named Inner Classes: Regular inner class with a name.
➤ Why Use Inner Classes?
• Easier access to outer class variables and components
• Keeps the code organized and localized
• Reduces the need for multiple .java files
➤ Example:
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Button clicked!");
}
});

� Conclusion
Event handling is a core concept in GUI programming, allowing Java applications to interact
dynamically with the user. It uses an efficient Event Delegation Model, supported by
powerful tools like:
• Listener interfaces
• Adapter classes
• Inner classes
By mastering event handling, developers can build interactive, responsive, and user-friendly
desktop applications.
Here is a complete theoretical explanation of I/O Streams in Java, including all the key
concepts you're likely to need for understanding, assignments, or exams.

� What Are I/O Streams?


In Java, I/O Streams are used to read data from and write data to different input and output
sources such as:
• Files
• Memory
• Keyboard (Console)
• Network
• Other programs
The term stream refers to a flow of data, either input (into a program) or output (from a
program).

� 1. Types of Streams in Java


Java provides two types of streams based on the data they handle:
Stream Type Used For Main Classes
Byte Streams Binary data (images, videos, etc.) InputStream, OutputStream
Character Streams Text data (letters, symbols) Reader, Writer

� Byte Streams
• Superclass for Input: InputStream
• Superclass for Output: OutputStream
These streams deal with raw 8-bit binary data.
InputStream Classes OutputStream Classes
FileInputStream FileOutputStream
BufferedInputStream BufferedOutputStream
DataInputStream DataOutputStream
ObjectInputStream ObjectOutputStream

� Character Streams
• Superclass for Input: Reader
• Superclass for Output: Writer
These streams deal with 16-bit Unicode characters (text data).
Reader Classes Writer Classes
FileReader FileWriter
BufferedReader BufferedWriter
InputStreamReader OutputStreamWriter
PrintWriter CharArrayWriter

� 2. Stream Classes Overview


➤ InputStream (abstract class)
• Reads one byte at a time.
• Subclasses: FileInputStream, BufferedInputStream, ObjectInputStream, etc.
➤ OutputStream (abstract class)
• Writes one byte at a time.
• Subclasses: FileOutputStream, BufferedOutputStream, ObjectOutputStream
➤ Reader & Writer
• Reader: reads character data.
• Writer: writes character data.

� 3. Reading Console Input


Java uses the System.in stream for console input, but it's a byte stream.
To read text, you can wrap it using:
➤ Option 1: BufferedReader with InputStreamReader
import java.io.*;

BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));


System.out.print("Enter your name: ");
String name = reader.readLine();
System.out.println("Hello " + name);
➤ Option 2: Scanner (simpler)
import java.util.Scanner;

Scanner sc = new Scanner(System.in);


System.out.print("Enter age: ");
int age = sc.nextInt();
System.out.println("Your age: " + age);

� 4. Writing Console Output


Use the standard output stream System.out:
System.out.println("This is output");
For error output:
System.err.println("This is an error message");

� 5. File Handling with Streams


Java uses stream classes to handle files:
➤ Writing Bytes to File:
FileOutputStream fos = new FileOutputStream("file.txt");
fos.write("Hello World".getBytes());
fos.close();
➤ Reading Bytes from File:
FileInputStream fis = new FileInputStream("file.txt");
int i;
while ((i = fis.read()) != -1) {
System.out.print((char) i);
}
fis.close();
➤ Writing Characters to File:
FileWriter fw = new FileWriter("file.txt");
fw.write("Hello Java");
fw.close();
➤ Reading Characters from File:
FileReader fr = new FileReader("file.txt");
int i;
while ((i = fr.read()) != -1) {
System.out.print((char) i);
}
fr.close();

� 6. Buffered Streams (High Performance)


Buffered streams use memory buffers to read/write data in chunks, improving speed.
➤ BufferedReader:
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
➤ BufferedWriter:
BufferedWriter bw = new BufferedWriter(new FileWriter("file.txt"));
bw.write("Buffered writing is fast!");
bw.close();

� 7. Object Streams (Serialization)


Used to read/write entire Java objects.
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("obj.dat"));
oos.writeObject(myObject);
oos.close();
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("obj.dat"));
MyClass obj = (MyClass) ois.readObject();
ois.close();

� Summary Table
Category Byte Stream Character Stream
Input Superclass InputStream Reader
Output
OutputStream Writer
Superclass
Read from File FileInputStream FileReader
Write to File FileOutputStream FileWriter
BufferedInputStream / BufferedReader /
Buffering
BufferedOutputStream BufferedWriter
Console Input System.in + InputStreamReader Scanner or BufferedReader
Console Output System.out System.out

� Conclusion
Java’s I/O system is flexible and powerful. It abstracts hardware and stream differences and
allows programs to easily:
• Read/write text and binary data
• Process user input/output
• Work with files using character or byte streams
Mastering I/O streams is essential for any file-based or interactive Java application.

Would you like a flow diagram of how different stream classes connect, or a note-ready PDF of
this explanation?

You might also like