UNIT - V - STRING HANDLING IN JAVA UPDATED
UNIT - V - STRING HANDLING IN JAVA UPDATED
STRING HANDLING
String Handling in Java
Strings in Java are objects that represent sequences of characters. The String class in Java is used
to create and manipulate strings. Strings are immutable, meaning once a string is created, it
cannot be changed. Various methods are provided by the String class for string manipulation.
Interface CharSequence
The CharSequence interface represents a readable sequence of char values. It is the parent interface
for several classes, including String, StringBuffer, and StringBuilder.
Key Methods:
CharSequence subSequence(int start, int end): Returns a new CharSequence that is a subsequence
of this sequence.
String toString(): Returns a String containing the characters in this sequence.
Class String
The String class implements the CharSequence interface and represents a sequence of characters.
Creating Strings:
java
Copy code
String str1 = "Hello, World!";
Using the new keyword:
java
Copy code
String str2 = new String("Hello, World!");
Example Code
java
Copy code
public class StringExample {
public static void main(String[] args) {
// Creating strings
String str1 = "Hello, World!";
String str2 = new String("Java Programming");
// String length
System.out.println("Length of str1: " + str1.length());
// Substring
System.out.println("Substring from index 7 in str1: " + str1.substring(7));
System.out.println("Substring from index 7 to 12 in str1: " + str1.substring(7, 12));
// Trimming whitespace
String str3 = " Hello, World! ";
System.out.println("str3 after trim: '" + str3.trim() + "'");
// Replacing characters
System.out.println("str1 after replacing 'World' with 'Java': " + str1.replace("World", "Java"));
// Splitting strings
String str4 = "apple,banana,cherry";
String[] fruits = str4.split(",");
for (String fruit : fruits) {
System.out.println(fruit);
}
}
}
Java provides several methods in the String class to extract characters or substrings from a string.
1. charAt(int index)
java
Copy code
public class Main {
public static void main(String[] args) {
String str = "Hello, World!";
char ch = str.charAt(0);
System.out.println("Character at index 0: " + ch); // Output: H
}
}
2. substring(int beginIndex)
Returns a new string that is a substring of the original string, starting from the specified index.
java
Copy code
public class Main {
public static void main(String[] args) {
String str = "Hello, World!";
String substr = str.substring(7);
System.out.println("Substring from index 7: " + substr); // Output: World!
}
}
Returns a new string that is a substring of the original string, starting from beginIndex and ending
at endIndex (exclusive).
java
Copy code
public class Main {
public static void main(String[] args) {
String str = "Hello, World!";
String substr = str.substring(7, 12);
System.out.println("Substring from index 7 to 11: " + substr); // Output: World
}
}
4. toCharArray()
java
Copy code
public class Main {
public static void main(String[] args) {
String str = "Hello, World!";
char[] charArray = str.toCharArray();
System.out.println("Character array: " + Arrays.toString(charArray)); // Output: [H, e, l, l, o, ,, , W, o, r, l, d, !]
}
}
Copies characters from the string into the destination character array.
java
Copy code
public class Main {
public static void main(String[] args) {
String str = "Hello, World!";
char[] dst = new char[5];
str.getChars(7, 12, dst, 0);
System.out.println("Destination array: " + Arrays.toString(dst)); // Output: [W, o, r, l, d]
}
}
Comparing Strings
1. equals(Object obj)
Compares the string to the specified object. Returns true if the object is a string with the same
sequence of characters.
java
Copy code
public class Main {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = "Hello";
String str3 = "World";
System.out.println(str1.equals(str2)); // Output: true
System.out.println(str1.equals(str3)); // Output: false
}
}
2. equalsIgnoreCase(String anotherString)
java
Copy code
public class Main {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = "hello";
System.out.println(str1.equalsIgnoreCase(str2)); // Output: true
}
}
3. compareTo(String anotherString)
Compares two strings lexicographically. Returns a negative integer, zero, or a positive integer if
the string is less than, equal to, or greater than the specified string.
java
Copy code
public class Main {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = "World";
String str3 = "Hello";
System.out.println(str1.compareTo(str2)); // Output: negative value (because "Hello" is lexicographically less
than "World")
System.out.println(str1.compareTo(str3)); // Output: 0 (because "Hello" is equal to "Hello")
}
}
4. compareToIgnoreCase(String str)
java
Copy code
public class Main {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = "hello";
System.out.println(str1.compareToIgnoreCase(str2)); // Output: 0 (because "Hello" is equal to "hello" ignoring
case)
}
}
java
Copy code
public class Main {
public static void main(String[] args) {
String str1 = "Hello, World!";
String str2 = "World";
boolean match = str1.regionMatches(7, str2, 0, 5);
System.out.println("Region matches: " + match); // Output: true
}
}
6. startsWith(String prefix)
java
Copy code
public class Main {
public static void main(String[] args) {
String str = "Hello, World!";
System.out.println(str.startsWith("Hello")); // Output: true
System.out.println(str.startsWith("World")); // Output: false
}
}
7. endsWith(String suffix)
java
Copy code
public class Main {
public static void main(String[] args) {
String str = "Hello, World!";
System.out.println(str.endsWith("World!")); // Output: true
System.out.println(str.endsWith("Hello")); // Output: false
}
}
The StringBuffer class in Java is used to create mutable (modifiable) strings. Unlike String,
StringBuffer objects can be modified without creating new objects.
Example
java
Copy code
public class StringBufferExample {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello");
// Append
sb.append(" World");
System.out.println(sb); // Output: Hello World
// Insert
sb.insert(5, ",");
System.out.println(sb); // Output: Hello, World
// Delete
sb.delete(5, 6);
System.out.println(sb); // Output: Hello World
// Replace
sb.replace(6, 11, "Java");
System.out.println(sb); // Output: Hello Java
// Reverse
sb.reverse();
System.out.println(sb); // Output: avaJ olleH
}
}
Example
java
Copy code
public class StringBufferSearchExample {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello, World");
// Index of
int index = sb.indexOf("World");
System.out.println("Index of 'World': " + index); // Output: 7
// Last Index of
int lastIndex = sb.lastIndexOf("o");
System.out.println("Last index of 'o': " + lastIndex); // Output: 8
}
}
Multithreaded programming involves running multiple threads concurrently, which can improve
the performance of an application by taking advantage of multiple processors.
Parallelism: Threads allow for parallel execution of tasks, making efficient use of multi-
core processors.
Responsiveness: In a GUI application, threads can keep the interface responsive while
performing background tasks.
Resource Sharing: Threads within the same process share resources, making
communication between them easier and more efficient.
Java provides built-in support for multithreaded programming using the Thread class and the
Runnable interface.
java
Copy code
public class MyRunnable implements Runnable {
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("Thread running: " + i);
try {
Thread.sleep(500); // Sleep for 500 milliseconds
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Thread States
Thread Priorities
Each thread has a priority, which helps the thread scheduler decide which thread should run next.
Threads with higher priority are more likely to be executed.
java
Copy code
public class ThreadPriorityExample extends Thread {
public void run() {
System.out.println("Thread running: " + this.getName());
}
t1.setPriority(Thread.MIN_PRIORITY); // Priority 1
t2.setPriority(Thread.MAX_PRIORITY); // Priority 10
t1.start();
t2.start();
}
}
Synchronization
Synchronization is necessary when multiple threads need to access shared resources
concurrently. It prevents race conditions by ensuring that only one thread can access the resource
at a time.
java
Copy code
class Counter {
private int count = 0;
t1.start();
t2.start();
t1.join();
t2.join();
Deadlock: Occurs when two or more threads are blocked forever, each waiting on the
other.
Race Condition: Occurs when two threads try to access and modify shared resources
concurrently, leading to unpredictable results.
Avoiding Deadlock
Inter-Thread Communication
Java provides methods for inter-thread communication using wait(), notify(), and notifyAll()
methods.
Example
java
Copy code
class SharedResource {
private int value;
private boolean available = false;
producer.start();
consumer.start();
}
}
Thread Class
The Thread class in Java is used to represent and control a thread of execution. A thread is a
lightweight subprocess, the smallest unit of processing.
You can create a thread by creating a subclass of Thread and overriding its run method.
Example
java
Copy code
class MyThread extends Thread {
public void run() {
System.out.println("Thread is running...");
}
}
You can create a thread by implementing the Runnable interface and passing an instance of your
class to a Thread object.
Example
java
Copy code
class MyRunnable implements Runnable {
public void run() {
System.out.println("Runnable is running...");
}
}
Main Thread
The main thread is the initial thread that is executed when a Java application starts. It can create
additional threads.
Example
java
Copy code
public class Main {
public static void main(String[] args) {
// Get the reference to the main thread
Thread mainThread = Thread.currentThread();
System.out.println("Main thread name: " + mainThread.getName());
Thread States
4. WAITING: The thread is waiting indefinitely for another thread to perform a particular action.
5. TIMED_WAITING: The thread is waiting for another thread to perform a particular action
within a specified waiting time.
Example
java
Copy code
public class Main {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(() -> {
System.out.println("Thread state: " + Thread.currentThread().getState());
});
Thread Priorities
Thread priorities determine the relative importance of a thread. Threads with higher priority are
executed in preference to threads with lower priority.
Example
java
Copy code
public class Main {
public static void main(String[] args) {
Thread highPriorityThread = new Thread(() -> {
System.out.println("High priority thread is running...");
});
highPriorityThread.setPriority(Thread.MAX_PRIORITY);
lowPriorityThread.setPriority(Thread.MIN_PRIORITY);
highPriorityThread.start();
lowPriorityThread.start();
}
}
Synchronization
Synchronization is used to control the access of multiple threads to shared resources to prevent
data inconsistency and ensure thread safety.
Synchronized Method
A method can be marked as synchronized to ensure that only one thread can execute it at a time.
Example
java
Copy code
class Counter {
private int count = 0;
t1.start();
t2.start();
t1.join();
t2.join();
Example
java
Copy code
class Counter {
private int count = 0;
t1.start();
t2.start();
t1.join();
t2.join();
Deadlock
Deadlock is a situation in concurrent programming where two or more threads are blocked
forever, each waiting for the other to release a resource. This results in a standstill and the
application cannot proceed.
Example of Deadlock
java
Copy code
class Resource {
public synchronized void method1(Resource r) {
System.out.println(Thread.currentThread().getName() + " entered method1");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
r.method2(this);
}
t1.start();
t2.start();
}
}
In the above example, Thread 1 holds the lock on r1 and tries to lock r2, while Thread 2 holds the
lock on r2 and tries to lock r1. This creates a deadlock situation.
Race Conditions
Race conditions occur when the behavior of a program depends on the relative timing of the
execution of threads. If two or more threads modify shared data simultaneously, it can lead to
inconsistent or incorrect results.
java
Copy code
class Counter {
private int count = 0;
public void increment() {
count++;
}
t1.start();
t2.start();
t1.join();
t2.join();
In this example, two threads increment the counter, leading to a race condition where the final
count may not be 2000 due to simultaneous access.
Inter-Thread Communication
Java provides mechanisms to control the execution of threads. However, the use of suspend(),
resume(), and stop() methods is deprecated due to potential deadlocks and inconsistent states.
Instead, proper thread communication and synchronization techniques are recommended.
Example
java
Copy code
class SharedResource {
private boolean available = false;
producer.start();
consumer.start();
}
}
In this example, the producer and consumer threads use wait() and notify() for inter-thread
communication to ensure proper coordination.
The java.util.concurrent.locks package provides Lock and Condition interfaces for more flexible and
modern thread control mechanisms.
Example
java
Copy code
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class SharedResourceWithLock {
private boolean available = false;
private final Lock lock = new ReentrantLock();
private final Condition condition = lock.newCondition();
producer.start();
consumer.start();
}
}
In this example, ReentrantLock and Condition provide a more flexible way to manage inter-thread
communication, avoiding some of the issues with traditional synchronization methods.
Key Points
Deadlock: Occurs when two or more threads are blocked forever, each waiting on the other.
Race Conditions: Occur when the outcome of a program depends on the sequence or timing of
uncontrollable events.
Deprecated Methods: suspend(), resume(), and stop() are deprecated due to safety concerns.
Modern Approach: Use Lock and Condition from java.util.concurrent.locks for better thread
control.
JDBC is an API in Java that enables Java applications to interact with databases. It provides
methods to connect to the database, execute SQL queries, and retrieve results.
JDBC Architecture
1. DriverManager: Manages a list of database drivers. It matches connection requests from the java
application with the proper database driver using communication subprotocol.
2. Driver: Interface that handles the communications with the database server.
5. ResultSet: Interface that represents the set of results returned by executing a statement.
6. SQLException: Exception class that provides information on a database access error or other
errors.
Installing MySQL
1. Download MySQL:
o Visit the MySQL download page.
2. Install MySQL:
o Start the MySQL server from the command line or using the MySQL Workbench.
o If you are using a build tool like Maven, add the dependency to your pom.xml:
xml
Copy code
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.25</version> <!-- Replace with the latest version -->
</dependency>
java
Copy code
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
try {
// Opening database connection
con = DriverManager.getConnection(url, user, password);
// Creating statement object
stmt = con.createStatement();
Steps Explained:
1. Load the JDBC Driver (Optional from JDBC 4.0 onwards as it is automatically loaded):
java
Copy code
Class.forName("com.mysql.cj.jdbc.Driver");
2. Establish a Connection:
java
Copy code
con = DriverManager.getConnection(url, user, password);
3. Create a Statement:
java
Copy code
stmt = con.createStatement();
4. Execute a Query:
java
Copy code
rs = stmt.executeQuery(query);
5. Process the Result Set:
java
Copy code
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
System.out.println("ID: " + id + ", Name: " + name);
}
6. Close the Resources:
java
Copy code
try { if (rs != null) rs.close(); } catch (Exception e) { e.printStackTrace(); }
try { if (stmt != null) stmt.close(); } catch (Exception e) { e.printStackTrace(); }
try { if (con != null) con.close(); } catch (Exception e) { e.printStackTrace(); }
To use JDBC, you need to set up the environment which involves the following steps:
3. Add JDBC Driver to Project: Include the JDBC driver in your project's classpath.
Add the MySQL JDBC driver (JAR file) to your project's classpath. If you are using an IDE like
IntelliJ IDEA or Eclipse, you can add the JAR file through the project settings.
1. Load the JDBC Driver: The JDBC driver must be loaded before you can establish a connection.
2. Establish a Connection: Use DriverManager.getConnection to connect to the database.
3. Create a Statement Object: Use the Connection object to create a Statement object.
4. Execute SQL Query: Use the Statement object to execute SQL queries.
5. Process the ResultSet: If the query returns results, process the ResultSet object.
6. Close the Connection: Close the ResultSet, Statement, and Connection objects to free resources.
Example
java
Copy code
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.SQLException;
try {
// Load the JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver");
// Establish a connection
connection = DriverManager.getConnection(jdbcURL, jdbcUsername, jdbcPassword);
// Execute a query
String sql = "SELECT * FROM users";
resultSet = statement.executeQuery(sql);
System.out.println("ID: " + id + ", Name: " + name + ", Email: " + email);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// Close the ResultSet, Statement, and Connection
try {
if (resultSet != null) resultSet.close();
if (statement != null) statement.close();
if (connection != null) connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
ResultSet Interface
The ResultSet interface represents the result set of a database query. It provides methods to iterate
through the results and retrieve data from the current row.
Example
java
Copy code
public class ResultSetExample {
public static void main(String[] args) {
String jdbcURL = "jdbc:mysql://localhost:3306/mydatabase";
String jdbcUsername = "root";
String jdbcPassword = "password";
while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
String email = resultSet.getString("email");
System.out.println("ID: " + id + ", Name: " + name + ", Email: " + email);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
JavaFX GUI
Introduction to JavaFX
JavaFX is a software platform for creating and delivering desktop applications, as well as rich
internet applications (RIAs). It is intended to replace Swing as the standard GUI library for Java
SE.
Setting Up JavaFX
To use JavaFX, you need to include the JavaFX libraries in your project. This can be done by
downloading the JavaFX SDK and configuring your IDE to use it, or by adding dependencies to
your build file if you are using a build tool like Maven or Gradle.
Introduction
JavaFX Scene Builder is a visual layout tool that lets you design JavaFX application user
interfaces without writing code. You can drag and drop UI components (buttons, labels, etc.) to
build your layout.
4. Save the FXML file and integrate it with your JavaFX application.
<?import javafx.geometry.Insets?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.layout.AnchorPane?>
@FXML
private void initialize() {
button.setOnAction(event -> System.out.println("Button clicked!"));
}
}
Main Components
Displaying Text
You can use various JavaFX controls to display text, such as Label, Text, and TextArea.
java
Copy code
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
Displaying Images
java
Copy code
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
Event handling in JavaFX allows your application to respond to user actions like button clicks,
key presses, and mouse movements.
The most common type of event is the action event, often associated with buttons.
java
Copy code
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
You can also handle key events, such as key presses and key releases.
java
Copy code
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
scene.setOnKeyPressed(event -> {
switch (event.getCode()) {
case UP:
System.out.println("UP key pressed");
break;
case DOWN:
System.out.println("DOWN key pressed");
break;
default:
break;
}
});
JavaFX provides several layout panes to organize UI controls in a scene. Commonly used layout
panes include StackPane, HBox, VBox, BorderPane, and GridPane.
StackPane
java
Copy code
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
primaryStage.setTitle("StackPane Example");
primaryStage.setScene(scene);
primaryStage.show();
}
java
Copy code
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
BorderPane
java
Copy code
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
primaryStage.setTitle("BorderPane Example");
primaryStage.setScene(scene);
primaryStage.show();
}
GridPane
java
Copy code
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
primaryStage.setTitle("GridPane Example");
primaryStage.setScene(scene);
primaryStage.show();
}
Mouse Events
JavaFX provides the MouseEvent class to handle mouse actions such as clicking, pressing,
releasing, and moving the mouse.
scene.setOnMouseMoved(event -> {
text.setText("Mouse Moved: " + event.getSceneX() + ", " + event.getSceneY());
});
primaryStage.setTitle("Mouse Movement Example");
primaryStage.setScene(scene);
primaryStage.show();
}
scene.setOnMouseDragged(event -> {
text.setText("Mouse Dragged: " + event.getSceneX() + ", " + event.getSceneY());
});