0% found this document useful (0 votes)
10 views

Unit 4 and Unit 5 First Part

notes

Uploaded by

durgabhavani60
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Unit 4 and Unit 5 First Part

notes

Uploaded by

durgabhavani60
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

Unit 4

. String Handling in Java

Strings in Java are represented by the String class, and strings are immutable. Once a String object
is created, its value cannot be changed.

String Class Constructor


Default Constructor: Creates an empty string.
java
Copy code
String str = new String(); // Creates an empty string

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);

2. Special String Operations


Concatenation

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

To convert a string to uppercase or lowercase:

java
Copy code
String str = "Hello";
String upper = str.toUpperCase(); // "HELLO"
String lower = str.toLowerCase(); // "hello"

Trimming Whitespace

Use trim() to remove leading and trailing 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)

Finding the Index of a Character or Substring

To find the position of a character or substring within a string, use indexOf():

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()

To compare the contents of two strings, use equals():

java
Copy code
String str1 = "Hello";
String str2 = "Hello";
boolean isEqual = str1.equals(str2); // true

Using equalsIgnoreCase()

To compare two strings ignoring case sensitivity, use equalsIgnoreCase():

java
Copy code
String str1 = "hello";
String str2 = "HELLO";
boolean isEqual = str1.equalsIgnoreCase(str2); // true

Using compareTo()

compareTo() compares strings lexicographically:

● Returns 0 if the strings are equal.


● Returns a negative number if the first string is lexicographically smaller.
● Returns a positive number if the first string is lexicographically greater.

java
Copy code
String str1 = "apple";
String str2 = "banana";
int result = str1.compareTo(str2); // Negative value since "apple" < "banana"

5. Modifying Strings (StringBuffer and StringBuilder)


StringBuffer

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

Converting StringBuffer to String:


java
Copy code
String result = sb.toString(); // Converts StringBuffer back to String

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"

6. Example: Combining All Operations


java
Copy code
public class StringExample {
public static void main(String[] args) {
// String creation
String str = " Hello Java World ";

// Trim and toUpperCase


str = str.trim().toUpperCase();
System.out.println(str); // "HELLO JAVA WORLD"

// 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"
}
}

Java Collection Framework Overview


The Java Collection Framework provides a set of classes and interfaces to handle and manipulate
collections of objects, such as lists, sets, and maps. The framework is designed to handle data structures
and provide efficient ways to store and retrieve data.

The key components of the Collection Framework include:

● Interfaces: Define the structure of collections.


● Implementations: Provide concrete implementations of those interfaces.
● Algorithms: Static methods that perform various operations on collections (e.g., sorting,
searching).

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:

● add(E e): Adds an element to the collection.


● remove(Object o): Removes an element from the collection.
● size(): Returns the number of elements in the collection.
● isEmpty(): Checks if the collection is empty.
● contains(Object o): Checks if the collection contains a specific element.

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.

Common Implementations: ArrayList, LinkedList, Vector.


java
Copy code
List<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Orange");

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.

Common Implementations: HashSet, TreeSet, LinkedHashSet.


java
Copy code
Set<String> set = new HashSet<>();
set.add("Apple");
set.add("Banana");
set.add("Apple"); // Duplicate, won't be added.

Queue Interface
A Queue is a collection used to store elements for processing, typically following FIFO (First In First Out)
order.

Common Implementations: LinkedList, PriorityQueue.


java
Copy code
Queue<String> queue = new LinkedList<>();
queue.add("Task1");
queue.add("Task2");

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.

Common Implementations: HashMap, TreeMap, LinkedHashMap.


java
Copy code
Map<String, Integer> map = new HashMap<>();
map.put("Apple", 5);
map.put("Banana", 3);

2. Collection Classes

ArrayList

● Implements List interface.


● Resizable array implementation.
● Allows fast access and modification by index, but slower inserts and deletes (except at the end).

Example:
java
Copy code
List<Integer> list = new ArrayList<>();
list.add(10);
list.add(20);
list.add(30);

LinkedList

● Implements both List and Deque interfaces.


● Stores elements as doubly-linked nodes (each node points to the next and previous element).
● Faster inserts and deletes compared to ArrayList, but slower access by index.
Example:
java
Copy code
List<String> list = new LinkedList<>();
list.add("One");
list.add("Two");
list.add("Three");

HashSet

● Implements Set interface.


● Backed by a hash table (hashing-based implementation).
● Does not allow duplicate elements and offers constant time complexity (O(1)) for basic
operations like add, remove, and contains.

Example:
java
Copy code
Set<String> set = new HashSet<>();
set.add("apple");
set.add("banana");
set.add("orange");

HashMap

● Implements Map interface.


● Backed by a hash table.
● Allows key-value pairs where keys are unique.
● Provides constant-time complexity (O(1)) for basic operations (get, put).

Example:
java
Copy code
Map<String, Integer> map = new HashMap<>();
map.put("Apple", 10);
map.put("Banana", 20);

TreeSet

● Implements Set interface.


● Stores elements in a sorted order, based on natural ordering or a specified comparator.
● Slower than HashSet but ensures ordering.

Example:
java
Copy code
Set<Integer> set = new TreeSet<>();
set.add(20);
set.add(10);
set.add(30); // Sorted automatically

3. Accessing a Collection via Iterator


An Iterator is an object that allows you to traverse through a collection, element by element. The
Iterator interface provides the following methods:

● 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).

Example: Iterating through a List using Iterator:

java
Copy code
List<String> list = new ArrayList<>();
list.add("One");
list.add("Two");
list.add("Three");

Iterator<String> iterator = list.iterator();


while (iterator.hasNext()) {
String item = iterator.next();
System.out.println(item);
}

Example: Iterating through a Map using an Iterator:

java
Copy code
Map<String, Integer> map = new HashMap<>();
map.put("Apple", 5);
map.put("Banana", 3);
map.put("Orange", 7);

Iterator<Map.Entry<String, Integer>> iterator = map.entrySet().iterator();


while (iterator.hasNext()) {
Map.Entry<String, Integer> entry = iterator.next();
System.out.println(entry.getKey() + ": " + entry.getValue());
}

4. Working with Maps


Maps store key-value pairs and offer methods for adding, removing, and accessing values based on keys.

Common Map Operations

● put(K key, V value): Adds a key-value pair to the map.


● get(Object key): Returns the value associated with a key.
● containsKey(Object key): Checks if the map contains the specified key.
● remove(Object key): Removes the key-value pair by the key.

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.

Example of Generic Collection


java
Copy code
List<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
// numbers.add("String"); // Compile-time error: incompatible types

Generic Map Example


java
Copy code
Map<String, Integer> map = new HashMap<>();
map.put("Apple", 5);
map.put("Banana", 3);
// map.put(1, "One"); // Compile-time error: incompatible types
Wildcards in Generics

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.

● Upper-bounded wildcard (? extends T): Represents any type that is a subtype of T.


● Lower-bounded wildcard (? super T): Represents any type that is a supertype of T.

Example: Upper-bounded wildcard:

java
Copy code
public void printNumbers(List<? extends Number> list) {
for (Number num : list) {
System.out.println(num);
}
}

List<Integer> integers = Arrays.asList(1, 2, 3);


List<Double> doubles = Arrays.asList(1.1, 2.2, 3.3);
printNumbers(integers); // Works with List<Integer>
printNumbers(doubles); // Works with List<Double>

Example: Lower-bounded wildcard:

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
}

List<Number> numberList = new ArrayList<>();


addToList(numberList); // Works with List<Number>
Unit 5

Event Handling in Java


Event handling in Java is a mechanism that allows programs to respond to user interactions (such as
mouse clicks, keyboard presses, and window actions) and other system-generated events (such as timer
ticks or network status changes). Java provides a rich set of event-handling classes and interfaces for
building interactive graphical user interfaces (GUIs) and handling various system events.

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.

Java provides several listener interfaces, such as:

● ActionListener for handling button clicks.


● MouseListener for handling mouse events.
● KeyListener for handling keyboard events.
● WindowListener for handling window events.

Listeners must be registered with the event source to start receiving events.

4. Event Listener Interface


To handle an event in Java, you implement the corresponding listener interface. Each listener interface
defines one or more methods that must be implemented to process 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.*;

public class ButtonExample {


public static void main(String[] args) {
Frame frame = new Frame("Event Listener Example");
Button button = new Button("Click Me");

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():

This method can be used to remove a previously registered event listener.

java
Copy code
button.removeActionListener(listener);

6. Handling Mouse Events

Mouse events are handled by implementing the MouseListener or MouseMotionListener interface.


These interfaces provide methods to handle different types of mouse events such as mouse clicks,
mouse movements, and mouse drags.

MouseListener Methods:

● mouseClicked(MouseEvent e): Invoked when the mouse button is clicked.


● mousePressed(MouseEvent e): Invoked when a mouse button is pressed.
● mouseReleased(MouseEvent e): Invoked when a mouse button is released.
● mouseEntered(MouseEvent e): Invoked when the mouse enters a component.
● mouseExited(MouseEvent e): Invoked when the mouse exits a component.

Example: MouseListener
java
Copy code
import java.awt.*;
import java.awt.event.*;

public class MouseExample {


public static void main(String[] args) {
Frame frame = new Frame("Mouse Event Example");

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:

● mouseDragged(MouseEvent e): Invoked when the mouse is dragged.


● mouseMoved(MouseEvent e): Invoked when the mouse is moved.

7. Handling Keyboard Events

Keyboard events are handled using the KeyListener interface, which provides methods to handle key
press and key release events.

KeyListener Methods:

● keyTyped(KeyEvent e): Invoked when a key is typed (character input).


● keyPressed(KeyEvent e): Invoked when a key is pressed.
● keyReleased(KeyEvent e): Invoked when a key is released.

Example: KeyListener
java
Copy code
import java.awt.*;
import java.awt.event.*;

public class KeyEventExample {


public static void main(String[] args) {
Frame frame = new Frame("Key Event Example");

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.

8. Event Adapter Classes


Java provides adapter classes for each event listener interface. These adapter classes are empty
implementations of the listener interfaces, allowing you to override only the methods you need. This is
especially useful if you don’t need to implement every method in the listener interface.

● MouseAdapter (extends MouseListener and MouseMotionListener).


● KeyAdapter (extends KeyListener).
● WindowAdapter (extends WindowListener).
● ActionAdapter (extends ActionListener).

By using these adapter classes, you only need to implement the relevant methods, rather than the entire
interface.

Example: Using MouseAdapter


java
Copy code
import java.awt.*;
import java.awt.event.*;

public class MouseAdapterExample {


public static void main(String[] args) {
Frame frame = new Frame("Mouse Adapter Example");

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.

9. Event Listener Interfaces


Here is a list of common event listener interfaces in Java:

Event Type Listener Interface Common Event Methods

Action Event ActionListener actionPerformed(ActionEvent e)

Mouse Event MouseListener mouseClicked(), mousePressed(),


mouseReleased(), mouseEntered(), mouseExited()

Key Event KeyListener keyPressed(), keyReleased(), keyTyped()

Window Event WindowListener windowOpened(), windowClosing(), windowClosed()

Focus Event FocusListener focusGained(), focusLost()

Item Event ItemListener itemStateChanged(ItemEvent e)

Text Event TextListener textValueChanged(TextEvent e)

Adjustment AdjustmentListen adjustmentValueChanged(AdjustmentEvent e)


Event er

● 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.

You might also like