Event Handling
🔹 What is Event Handling?
📘 Definition:
Event Handling in Java is the mechanism that controls the events (user interactions like mouse clicks, key presses) and responds to them.
- An event is an action or occurrence detected by a program (e.g., button click, mouse movement).
- Event handling means writing code to respond to these events.
🔹 Event Sources and Event Listeners
| Term | Description |
|---|---|
| Event Source | Object that generates events (e.g., button) |
| Event Object | Object that encapsulates event details |
| Event Listener | Interface with methods to handle events |
| Event Handler | Code inside listener methods that executes on event |
🔹 Types of Events in Java
- Action Event: User performs an action (click button, press Enter).
- Mouse Event: Mouse actions (click, move, enter, exit).
- Key Event: Keyboard key pressed or released.
- Window Event: Actions related to window (open, close, minimize).
- Focus Event: Component gains or loses focus.
🔹 Event Handling Model (Delegation Model)
Java uses the Delegation Event Model which involves:
- Event Source — generates an event.
- Event Object — holds event info.
- Event Listener — object implementing listener interface to handle event.
- Event Registration — listener registers with source.
When the event occurs, the source sends the event object to the listener, which executes the handler code.
🔹 How to Handle Events in Java?
Step 1: Identify the Event Source (e.g., a Button)
Step 2: Create an Event Listener by implementing the appropriate interface
Step 3: Register the Listener with the Event Source
🔹 Example: Handling Button Click using ActionListener
import java.awt.*;
import java.awt.event.*;
public class ButtonClickExample extends Frame implements ActionListener {
Button btn;
public ButtonClickExample() {
btn = new Button("Click Me");
btn.setBounds(50, 100, 80, 30);
add(btn);
btn.addActionListener(this); // Register listener
setSize(200, 200);
setLayout(null);
setVisible(true);
}
// Override method to handle button click
public void actionPerformed(ActionEvent e) {
System.out.println("Button clicked!");
}
public static void main(String[] args) {
new ButtonClickExample();
}
}
🔹 Common Event Listener Interfaces
| Listener Interface | Event Type | Method(s) to Implement |
|---|---|---|
ActionListener |
Action events (button click) | actionPerformed(ActionEvent e) |
MouseListener |
Mouse events (click, enter, exit) | mouseClicked, mouseEntered, mouseExited, mousePressed, mouseReleased |
KeyListener |
Keyboard events | keyPressed, keyReleased, keyTyped |
WindowListener |
Window events | windowOpened, windowClosing, windowClosed, etc. |
🔹 Event Handling Using Anonymous Inner Classes
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Button clicked (anonymous class)!");
}
});
🔹 Event Handling Using Lambda Expressions (Java 8+)
btn.addActionListener(e -> System.out.println("Button clicked (lambda)!"));
🔹 Event Propagation
- Events are propagated from the source up through the containment hierarchy.
- Allows parent components to listen to events from child components.
🔹 Summary
| Concept | Explanation |
|---|---|
| Event Source | Generates events (button, frame) |
| Event Listener | Handles events by implementing interface |
| Event Object | Contains info about the event |
| Registration | Listener registers with source |
| Delegation Model | Event delivered from source to listener |
📝 Common Exam Questions
- What is event handling in Java?
- Explain the delegation event model.
- How do you handle a button click event?
- Name different event listener interfaces.
- Difference between event source and event listener.
String objects
🔹 What is a String in Java?
📘 Definition:
A String in Java is an object that represents a sequence of characters. It is widely used to store and manipulate text.
- Strings are instances of the
java.lang.Stringclass. - Strings in Java are immutable, meaning once created, their values cannot be changed.
🔹 Creating String Objects
There are two main ways to create strings:
1. Using String Literals
String s1 = "Hello";
- Stored in the String Constant Pool (special memory area).
- If the same literal appears again, Java reuses the same object to save memory.
2. Using new Keyword
String s2 = new String("Hello");
- Creates a new String object in the heap, not in the String Pool.
- Less memory efficient compared to literals.
🔹 Important Characteristics of Strings
| Feature | Description |
|---|---|
| Immutable | String objects cannot be modified after creation. |
| String Pool | Pool that stores string literals to save memory. |
| Interning | Method intern() can be used to store a string in the pool explicitly. |
🔹 Common String Methods
| Method | Description | Example |
|---|---|---|
length() |
Returns length of the string | "Hello".length() -> 5 |
charAt(int index) |
Returns character at given index | "Hello".charAt(1) -> 'e' |
substring(int start, int end) |
Returns substring from start to end-1 | "Hello".substring(1,4) -> "ell" |
equals(Object obj) |
Checks if two strings are equal (case-sensitive) | "Hi".equals("Hi") -> true |
equalsIgnoreCase(String s) |
Checks equality ignoring case | "Hi".equalsIgnoreCase("hi") -> true |
toLowerCase() |
Converts to lowercase | "HELLO".toLowerCase() -> "hello" |
toUpperCase() |
Converts to uppercase | "hello".toUpperCase() -> "HELLO" |
trim() |
Removes leading and trailing whitespace | " hi ".trim() -> "hi" |
concat(String s) |
Concatenates strings | "Hi".concat(" There") -> "Hi There" |
replace(char old, char new) |
Replaces characters | "Hello".replace('l', 'p') -> "Heppo" |
split(String regex) |
Splits string based on regex | "a,b,c".split(",") -> ["a","b","c"] |
🔹 String Immutability Explained
- When you modify a string (e.g., concat), a new String object is created.
- The original string remains unchanged.
Example:
String s = "Hello";
s = s + " World"; // Creates a new string "Hello World"
🔹 String Pool & String Interning
- String literals are stored in the String Pool to optimize memory.
- Using the same literal reuses the same object:
String a = "Test";
String b = "Test";
System.out.println(a == b); // true, both refer to same object
- Using
newcreates separate objects:
String c = new String("Test");
System.out.println(a == c); // false, different objects
- You can add strings created with
newto the pool usingintern():
String d = c.intern();
System.out.println(a == d); // true
🔹 String Concatenation
- Using
+operator concatenates strings. - Internally, Java uses
StringBuilderto optimize concatenation in loops or multiple additions.
🔹 Why Use String Objects?
- Strings are everywhere: user input, file paths, network communication.
- String class provides powerful methods to manipulate text data.
- Being immutable, Strings are thread-safe.
🔹 Summary
| Topic | Description |
|---|---|
| What is String? | Immutable sequence of characters |
| Creation | Literals (String pool) or new operator |
| Immutability | Cannot be changed after creation |
| String Pool | Memory optimization by reusing literals |
| Common Methods | length(), charAt(), substring(), equals(), concat(), etc. |
StringBuffer
🔹 What is StringBuffer?
📘 Definition:
StringBuffer is a mutable sequence of characters in Java. Unlike String, which is immutable, StringBuffer objects can be modified after they are created without creating new objects.
- It is part of the
java.langpackage. - Used when you need to perform many modifications to strings efficiently.
- Thread-safe (synchronized methods) — suitable for multithreaded environments.
🔹 Why Use StringBuffer?
- Since
Stringis immutable, every modification creates a new String object — expensive in performance. StringBufferallows you to change the string content without creating a new object, saving time and memory.- Thread safety is guaranteed because its methods are synchronized.
🔹 Creating a StringBuffer Object
StringBuffer sb1 = new StringBuffer(); // creates empty buffer with default capacity 16
StringBuffer sb2 = new StringBuffer("Hello"); // initializes buffer with "Hello"
🔹 Important Methods of StringBuffer
| Method | Description | Example |
|---|---|---|
append(String s) |
Adds text at the end | sb.append(" World") |
insert(int pos, String s) |
Inserts text at specified position | sb.insert(5, ",") |
replace(int start, int end, String s) |
Replaces substring between start and end | sb.replace(0, 5, "Hi") |
delete(int start, int end) |
Deletes characters from start to end-1 | sb.delete(0, 2) |
reverse() |
Reverses the entire sequence | sb.reverse() |
capacity() |
Returns current buffer capacity | sb.capacity() |
length() |
Returns current length of the string | sb.length() |
toString() |
Converts StringBuffer to String | sb.toString() |
🔹 Example Usage
public class StringBufferExample {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello");
sb.append(" World"); // Hello World
sb.insert(5, ","); // Hello, World
sb.replace(6, 11, "Java"); // Hello, Java
sb.delete(5, 6); // Hello Java
sb.reverse(); // avaJ olleH
System.out.println(sb.toString());
}
}
Output:
avaJ olleH
🔹 Difference Between String, StringBuffer, and StringBuilder
| Feature | String | StringBuffer | StringBuilder |
|---|---|---|---|
| Mutability | Immutable | Mutable | Mutable |
| Thread Safety | N/A | Synchronized (Thread-safe) | Not synchronized (not thread-safe) |
| Performance | Slow on multiple changes | Slower than StringBuilder due to synchronization | Faster than StringBuffer (no synchronization) |
| Use Case | Fixed strings | Strings in multithreaded apps | Strings in single-threaded apps |
🔹 When to Use StringBuffer?
- When you need to modify strings repeatedly in a multithreaded environment.
- When thread safety is required during string modifications.
🔹 Summary
| Topic | Details |
|---|---|
| What is StringBuffer? | Mutable sequence of characters, thread-safe |
| Usage | Efficient string manipulation in multithreaded apps |
| Key Methods | append(), insert(), replace(), delete(), reverse() |
| Difference from String | Mutable vs immutable |
| Difference from StringBuilder | Thread-safe vs not thread-safe |
char arrays in Java.
🔹 What is a Char Array in Java?
📘 Definition:
A char array (char[]) is a primitive array that stores a sequence of characters. It is different from the String class, as it is a basic data structure that holds characters directly.
charis a primitive data type representing a single 16-bit Unicode character.- A
char[]can be used to store text data as a sequence of characters.
🔹 Why Use Char Arrays?
- Sometimes used for low-level manipulation of characters.
- Useful in situations where you want mutable sequences of characters (because
Stringis immutable). - Often used in security contexts (like storing passwords) because you can overwrite the array to clear sensitive data.
🔹 Declaring and Initializing Char Arrays
1. Declare and Initialize with Size
char[] letters = new char[5]; // array of 5 characters, initialized with default '\u0000'
2. Declare and Initialize with Values
char[] vowels = {'a', 'e', 'i', 'o', 'u'};
🔹 Accessing and Modifying Elements
- Use index to access or modify elements (index starts at 0).
char firstVowel = vowels[0]; // 'a'
vowels[2] = 'x'; // changes 'i' to 'x'
🔹 Common Operations on Char Arrays
| Operation | Description | Example |
|---|---|---|
| Iterate through elements | Loop through all chars | for(int i=0; i<letters.length; i++) |
| Convert char array to String | Create a String from char array | String s = new String(vowels); |
| Convert String to char array | Get char array from String | char[] chars = s.toCharArray(); |
| Modify elements | Directly change characters | letters[0] = 'H'; |
🔹 Example: Using Char Array
public class CharArrayExample {
public static void main(String[] args) {
char[] chars = {'J', 'a', 'v', 'a'};
System.out.println("Char array elements:");
for(char c : chars) {
System.out.print(c + " ");
}
System.out.println();
// Convert char array to String
String str = new String(chars);
System.out.println("String from char array: " + str);
// Modify char array
chars[0] = 'L';
System.out.println("Modified char array as String: " + new String(chars));
}
}
Output:
Char array elements:
J a v a
String from char array: Java
Modified char array as String: Lava
🔹 Difference Between Char Array and String
| Feature | Char Array (char[]) |
String |
|---|---|---|
| Mutability | Mutable — individual elements can change | Immutable — cannot be changed after creation |
| Storage | Primitive array of characters | Object of class String |
| Usage | Low-level manipulation, security reasons | General text handling |
| Memory Efficiency | Can be more memory-efficient for small char storage | More overhead due to object structure |
🔹 Why Char Array for Passwords?
- Passwords are sensitive data.
- String objects are immutable and stored in String pool; they can't be cleared from memory.
- Char arrays can be overwritten to clear data after use.
Example:
char[] password = {'s', 'e', 'c', 'r', 'e', 't'};
// Use password
// Clear password from memory after use
Arrays.fill(password, '0');
🔹 Summary
| Topic | Details |
|---|---|
| What is Char Array? | Primitive array storing characters |
| Use Cases | Mutable character storage, security, low-level text manipulation |
| Initialization | Using size or array literals |
| Modification | Direct access via index, mutable |
| Conversion | To/from String |
| Security | Useful for storing sensitive data temporarily |
Java Utilities
🔹 What is Java Utilities?
📘 Definition:
Java Utilities refers primarily to the java.util package, a part of Java's standard library that provides a collection of useful utility classes and interfaces.
- It includes data structures, date/time facilities, random number generation, string tokenizers, and more.
- The package contains classes that simplify everyday programming tasks.
🔹 Key Components of java.util Package
1. Collections Framework
- Provides data structures (called collections) like lists, sets, queues, and maps.
- Common interfaces:
Collection,List,Set,Queue,Map - Implementations:
ArrayList,LinkedList,HashSet,TreeSet,HashMap,LinkedHashMap, etc.
Example:
List<String> list = new ArrayList<>();
list.add("Java");
list.add("Utilities");
2. Utility Classes
Arrays: Methods to manipulate arrays (sorting, searching, filling).Collections: Static methods for operating on collections (sorting, searching, synchronizing).Objects: Utility methods for working with objects (null-safe operations, equals, hashCode).
Example:
int[] arr = {5, 3, 9, 1};
Arrays.sort(arr); // sorts array
3. Date and Time
- Pre-Java 8:
Date,Calendar,TimeZone - Post-Java 8 (in
java.timepackage, but related):LocalDate,LocalTime,LocalDateTime,ZonedDateTime java.util.Daterepresents a specific instant in time.Calendarprovides date/time operations like adding days, months, etc.
Example:
Date date = new Date(); // current date and time
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 5); // add 5 days
4. Random Number Generation
- Class
Randomgenerates pseudo-random numbers. - You can generate integers, floats, booleans, etc.
Example:
Random rand = new Random();
int randomNum = rand.nextInt(100); // random number between 0 and 99
5. String Tokenizer
StringTokenizerclass breaks a string into tokens (words or substrings) based on delimiters.- Less used now in favor of
String.split()but still part ofjava.util.
Example:
StringTokenizer st = new StringTokenizer("Java utilities example", " ");
while(st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
6. Scanner
- The
Scannerclass is used for reading input from various sources like keyboard, files, streams. - Supports parsing different data types (int, float, string).
Example:
Scanner scanner = new Scanner(System.in);
System.out.println("Enter your name:");
String name = scanner.nextLine();
7. Other Utility Classes
Properties: Manage application configuration as key-value pairs.UUID: Generate universally unique identifiers.TimerandTimerTask: Scheduling tasks for future execution.
🔹 Summary Table
| Component | Description | Example Class/Interface |
|---|---|---|
| Collections | Data structures & algorithms | List, Set, HashMap |
| Arrays | Utility methods for arrays | Arrays |
| Date & Time | Represent and manipulate date/time | Date, Calendar |
| Random | Generate random numbers | Random |
| String Tokenizer | Break strings into tokens | StringTokenizer |
| Input Scanner | Read input from user or files | Scanner |
| Configuration | Key-value properties storage | Properties |
| Unique IDs | Generate UUIDs | UUID |
| Task Scheduling | Schedule delayed or repeated tasks | Timer, TimerTask |
🔹 Why Java Utilities Are Important?
- They provide ready-made, tested solutions to common programming needs.
- Using these classes improves productivity and reduces bugs.
- They help you work efficiently with collections, dates, inputs, and many other data types.
Code Documentation in Java
🔹 What is Code Documentation?
📘 Definition:
Code documentation refers to written explanations and descriptions embedded within or alongside source code to help developers understand, maintain, and use the code effectively.
- It improves code readability.
- Helps others (and yourself later) to understand the purpose, design, and usage of code.
- Vital for collaboration, maintenance, and debugging.
🔹 Types of Code Documentation
-
Inline Comments
-
Short comments inside the code explaining specific lines or blocks.
-
Typically use
//for single line or/* ... */for block comments. -
Block Comments
-
Comments placed before classes, methods, or complex logic.
-
Provide summaries or explanations about the code segment.
-
Javadoc Comments
-
Specially formatted comments (
/** ... */) that can be extracted to generate HTML documentation. - Describe classes, methods, parameters, return values, exceptions, etc.
🔹 Why is Code Documentation Important?
- Makes code easier to understand and maintain.
- Helps new developers learn the codebase quickly.
- Serves as a reference without diving into the code logic.
- Facilitates debugging and enhancement.
- Increases code quality and professionalism.
🔹 Java Documentation with Javadoc
What is Javadoc?
- Javadoc is a tool that generates API documentation in HTML format from Java source code with special comments.
- The comments start with
/**and include tags for structured documentation.
Example of Javadoc Comment
/**
* Represents a simple calculator with basic operations.
*/
public class Calculator {
/**
* Adds two integers.
*
* @param a first integer
* @param b second integer
* @return the sum of a and b
*/
public int add(int a, int b) {
return a + b;
}
}
Common Javadoc Tags
| Tag | Description |
|---|---|
@param |
Describes a method parameter |
@return |
Describes the return value of a method |
@throws or @exception |
Describes exceptions a method might throw |
@see |
Refers to related classes or methods |
@author |
Author of the code |
@version |
Version of the class or interface |
🔹 Best Practices for Code Documentation
- Write clear, concise comments.
- Avoid obvious comments like
i = i + 1; // increment i. - Focus on explaining why something is done, not what (the code shows what).
- Keep documentation up to date as code changes.
- Use meaningful names for classes, variables, and methods to reduce the need for excessive comments.
- Use Javadoc for public APIs and library code.
🔹 Tools for Documentation
- Javadoc — generates HTML docs from source code.
- IDE Support — Most IDEs (like IntelliJ IDEA, Eclipse) provide templates and visualization for Javadoc.
- Third-party tools — like Doxygen for multiple languages, or custom markdown documentation.
🔹 Summary
| Aspect | Details |
|---|---|
| What is Documentation | Written info explaining the code’s purpose & usage |
| Types | Inline comments, block comments, Javadoc comments |
| Java Javadoc | Special comments to generate formal API documentation |
| Importance | Improves readability, maintainability, and collaboration |
| Best Practices | Be clear, concise, explain why, keep updated |