? What is a Java Package
? 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
• -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
� Advantages of Packages
• Avoids naming conflicts (two classes with same name in different packages)
• Improves modularity
• Simplifies maintenance
• Access control using modifiers
� 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.
� 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.
� 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);
}
� 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.
� 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.
� 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;
Customer(Bank b) {
this.b = b;
}
� 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.
➤ 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
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.");
}
}
}
➤ 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();
� 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;
� 2. Writing to a File
➤ A) Using FileWriter (for text)
import java.io.FileWriter;
import java.io.IOException;
� 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.");
}
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.");
}
try {
String content = Files.readString(path);
System.out.println(content);
} catch (IOException e) {
e.printStackTrace();
}
}
}
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.
� 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.
� 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
� 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.
� 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
� 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?