Unit 4 and Unit 5 First Part
Unit 4 and Unit 5 First Part
Strings in Java are represented by the String class, and strings are immutable. Once a String object
is created, its value cannot be changed.
Parameterized Constructor: Creates a string by copying the value from another string or a character
array.
java
Copy code
String str1 = new String("Hello World");
String str2 = new String(new char[] {'H', 'e', 'l', 'l', 'o'});
String from Bytes: You can also create a string from byte arrays.
java
Copy code
byte[] byteArray = {72, 101, 108, 108, 111}; // ASCII values for 'Hello'
String str = new String(byteArray);
You can concatenate strings using the + operator or the concat() method.
java
Copy code
String s1 = "Hello ";
String s2 = "World";
String result = s1 + s2; // Concatenation using '+'
String result2 = s1.concat(s2); // Concatenation using 'concat()'
Length of String
To find the length of a string, use the length() method.
java
Copy code
String str = "Hello";
int len = str.length(); // Output: 5
String to Uppercase/Lowercase
java
Copy code
String str = "Hello";
String upper = str.toUpperCase(); // "HELLO"
String lower = str.toLowerCase(); // "hello"
Trimming Whitespace
java
Copy code
String str = " Hello ";
String trimmedStr = str.trim(); // "Hello"
3. Character Extraction
Accessing Individual Characters
You can extract individual characters from a string using the charAt() method:
java
Copy code
String str = "Hello";
char ch = str.charAt(1); // 'e' (Characters are indexed starting from 0)
java
Copy code
String str = "Hello, World!";
int index = str.indexOf('o'); // First occurrence of 'o' -> index 4
int substringIndex = str.indexOf("World"); // Index of "World" -> 7
4. String Comparison
Using equals()
java
Copy code
String str1 = "Hello";
String str2 = "Hello";
boolean isEqual = str1.equals(str2); // true
Using equalsIgnoreCase()
java
Copy code
String str1 = "hello";
String str2 = "HELLO";
boolean isEqual = str1.equalsIgnoreCase(str2); // true
Using compareTo()
java
Copy code
String str1 = "apple";
String str2 = "banana";
int result = str1.compareTo(str2); // Negative value since "apple" < "banana"
StringBuffer is mutable (i.e., it allows modification of its contents) and is used when you need to
modify strings frequently.
Creating a StringBuffer:
java
Copy code
StringBuffer sb = new StringBuffer("Hello");
Appending Strings:
java
Copy code
sb.append(" World"); // Adds " World" to the current string
Inserting a String:
java
Copy code
sb.insert(5, " Java"); // Inserts " Java" at position 5
Reversing a String:
java
Copy code
sb.reverse(); // Reverses the string
Replacing a Substring:
java
Copy code
sb.replace(6, 11, "Universe"); // Replaces "World" with "Universe"
Deleting a Substring:
java
Copy code
sb.delete(5, 11); // Deletes the substring from index 5 to 11
StringBuilder
StringBuilder is similar to StringBuffer but is not synchronized, meaning it’s more efficient for
use in single-threaded environments.
java
Copy code
StringBuilder sb = new StringBuilder("Hello");
sb.append(" World");
sb.insert(5, " Java");
sb.reverse();
String result = sb.toString(); // " WorldJava Hello"
// Character extraction
char ch = str.charAt(0);
System.out.println(ch); // 'H'
// String comparison
String str2 = "HELLO JAVA WORLD";
System.out.println(str.equals(str2)); // true
// Using StringBuffer
StringBuffer sb = new StringBuffer("Good Morning");
sb.append(" Everyone");
sb.insert(4, " Beautiful");
sb.reverse();
System.out.println(sb.toString()); // "enoyrevE lufituaeB gninroM
dooG"
}
}
1. Collection Interfaces
The Collection Framework consists of the following core interfaces:
Collection Interface
This is the root interface of the collection hierarchy. It represents a group of objects. Some of the common
methods provided by Collection are:
List Interface
A List is an ordered collection that allows duplicate elements. It provides methods to access elements
by their position (index) in the list.
Set Interface
A Set is a collection that does not allow duplicate elements. It is useful when you need to ensure that an
element appears only once in a collection.
Queue Interface
A Queue is a collection used to store elements for processing, typically following FIFO (First In First Out)
order.
Map Interface
A Map is an object that maps keys to values. It does not extend Collection. It is used for storing key-
value pairs, where each key is unique.
2. Collection Classes
ArrayList
Example:
java
Copy code
List<Integer> list = new ArrayList<>();
list.add(10);
list.add(20);
list.add(30);
LinkedList
HashSet
Example:
java
Copy code
Set<String> set = new HashSet<>();
set.add("apple");
set.add("banana");
set.add("orange");
HashMap
Example:
java
Copy code
Map<String, Integer> map = new HashMap<>();
map.put("Apple", 10);
map.put("Banana", 20);
TreeSet
Example:
java
Copy code
Set<Integer> set = new TreeSet<>();
set.add(20);
set.add(10);
set.add(30); // Sorted automatically
● hasNext(): Returns true if the collection has more elements to iterate over.
● next(): Returns the next element in the collection.
● remove(): Removes the last element returned by the iterator (optional operation).
java
Copy code
List<String> list = new ArrayList<>();
list.add("One");
list.add("Two");
list.add("Three");
java
Copy code
Map<String, Integer> map = new HashMap<>();
map.put("Apple", 5);
map.put("Banana", 3);
map.put("Orange", 7);
Example:
java
Copy code
Map<String, Integer> map = new HashMap<>();
map.put("Apple", 10);
map.put("Banana", 5);
map.put("Orange", 8);
System.out.println(map.get("Apple")); // Output: 10
map.remove("Banana");
if (map.containsKey("Banana")) {
System.out.println("Banana is present.");
} else {
System.out.println("Banana is not present.");
}
5. Generics in Collections
Java collections are generic and can work with any type of object. Generics allow you to specify the type
of objects that a collection will store, making it type-safe and avoiding ClassCastException.
Wildcards (?) allow you to specify a parameterized type that can be any type. They are useful for
methods that work with collections of unknown types.
java
Copy code
public void printNumbers(List<? extends Number> list) {
for (Number num : list) {
System.out.println(num);
}
}
java
Copy code
public void addToList(List<? super Integer> list) {
list.add(10); // Can safely add Integer
// list.add(1.5); // Compile-time error: incompatible types
}
The event handling mechanism is built around the Observer Design Pattern, where the source of an
event notifies the registered listeners.
1. Events in Java
An event represents some kind of action or occurrence that is triggered by the user or the system.
Examples of events include:
● A mouse click
● A key press or release
● A window being opened or closed
● A button being pressed
Events are generally represented by event classes, and Java provides a rich set of event classes for
different types of events.
2. Event Source
An event source is an object that generates an event. It could be a GUI component, such as a button,
text field, or window, or it could be a system event, such as a timer or a network connection.
In Java, the event source typically fires an event when an action occurs (like a button being clicked or a
key being pressed). To handle such events, the source object must register one or more event listeners.
Example:
A Button can be an event source, and the event that it generates is a ActionEvent.
3. Event Listeners
An event listener is an object that listens to and handles events generated by event sources. To handle
an event, the listener must implement a specific interface that defines methods to process the event.
Listeners must be registered with the event source to start receiving events.
Example: ActionListener
The ActionListener interface is used to handle events triggered by actions such as button clicks.
● Methods:
○ actionPerformed(ActionEvent e): This method is invoked when an action occurs.
java
Copy code
import java.awt.*;
import java.awt.event.*;
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Button clicked!");
}
});
frame.add(button);
frame.setSize(200, 200);
frame.setVisible(true);
}
}
In this example, the ActionListener listens for button clicks and responds by printing a message when
the button is clicked.
5. Event Handling Clauses
addEventListener():
This is the method used to register event listeners to event sources. Event listeners are registered by
calling a method like addActionListener() for a button, addMouseListener() for a mouse event,
etc.
java
Copy code
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Button clicked!");
}
});
removeEventListener():
java
Copy code
button.removeActionListener(listener);
MouseListener Methods:
Example: MouseListener
java
Copy code
import java.awt.*;
import java.awt.event.*;
frame.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
System.out.println("Mouse clicked at: " + e.getX() + ", " +
e.getY());
}
});
frame.setSize(300, 300);
frame.setVisible(true);
}
}
In this example, the mouseClicked() method is invoked when the mouse is clicked within the frame.
MouseMotionListener Methods:
Keyboard events are handled using the KeyListener interface, which provides methods to handle key
press and key release events.
KeyListener Methods:
Example: KeyListener
java
Copy code
import java.awt.*;
import java.awt.event.*;
frame.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
System.out.println("Key pressed: " + e.getKeyChar());
}
});
frame.setSize(300, 300);
frame.setVisible(true);
frame.setFocusable(true); // Important to focus to receive key events
}
}
In this example, the program prints the character of the key pressed on the keyboard.
By using these adapter classes, you only need to implement the relevant methods, rather than the entire
interface.
frame.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
System.out.println("Mouse pressed at: " + e.getX() + ", " +
e.getY());
}
});
frame.setSize(300, 300);
frame.setVisible(true);
}
}
This example uses the MouseAdapter class to handle only the mousePressed() method, avoiding the
need to implement the other methods in MouseListener.
● Event Source: Objects that generate events (like buttons, text fields, etc.).
● Event Listener: Objects that handle events by implementing specific listener interfaces (e.g.,
ActionListener, MouseListener, KeyListener).
● Adapter Classes: Convenience classes that provide empty implementations of listener interfaces
(e.g., MouseAdapter, KeyAdapter).
● Event Handling: Involves registering listeners to event sources using methods like
addActionListener(), addMouseListener(), etc.
● Event-Listener Interface: An interface defines the methods required to handle specific events,
such as actionPerformed() for ActionEvent or mouseClicked() for MouseEvent.