UNIT-5 Notes
UNIT-5 Notes
String Handling in Java: Introduction, Interface Char Sequence, Class String, Methods for
Extracting Characters from Strings, Methods for Comparison of Strings, Methods for
Modifying Strings, Methods for Searching Strings, Data Conversion and Miscellaneous
Methods, Class String Buffer, Class String Builder.
Multithreaded Programming: Introduction, Need for Multiple Threads Multithreaded
Programming for Multi-core Processor, Thread Class, Main Thread, Creation of New Threads,
Thread States, Thread Priority, Synchronization, Deadlock and Race Situations, Inter-thread
Communication - Suspending, Resuming, and Stopping of Threads.
Java Database Connectivity: Introduction, JDBC Architecture, Installing MySQL and MySQL
Connector/J, JDBC Environment Setup, Establishing JDBC Database Connections, ResultSet
Interface, Creating JDBC Application, JDBC Batch Processing, JDBC Transaction
Management
Multithreaded Programming
Concept-1 Introduction
The process of executing multiple threads simultaneously is known as multithreading.
Thread is a lightweight unit of a process that executes in multithreading environment.
A program can be divided into a number of small processes.
Each small process can be addressed as a single thread (a lightweight process).
Multithreaded programs contain two or more threads that can run concurrently.
This means that a single program can perform two or more tasks simultaneously.
For example, one thread is writing content on a file at the same time another thread is
performing spelling check.
Process is the execution of a program that performs the actions specified in that program.
When program is loaded into the memory it automatically converting in to the process.
JAVA every program that we have been writing has at least one thread that is the MAIN
thread.
A Program starts executing the JVM is responsible for creating the main thread and calling the
main() Method.
Threads are executed by the processor according to the scheduling done by the java runtime
system by priority to every thread.
It simply means the higher priority as given preference for getting executed over the threads
having lower priority.
Advantage of Multithreading
Multithreading reduces the CPU idle time that increase overall performance of the system.
Since thread is lightweight process then it takes less memory.
Switching as well that helps to share the memory and reduce time of switching between
threads.
Thread vs Process
Parameter Process Thread
Definition Process means a program is in execution. Thread means a segment of a process.
Lightweight The process is not Lightweight. Threads are Lightweight.
Termination
The process takes more time to terminate. The thread takes less time to terminate.
time
Creation time It takes more time for creation. It takes less time for creation.
Communication between threads
Communication between processes needs
Communication requires less time compared to
more time compared to thread.
processes.
Context
It takes more time for context switching. It takes less time for context switching.
switching time
Resource Process consumes more resources. Thread consumes fewer resources.
Memory The process is mostly isolated. Threads share memory.
Sharing It does not share data Threads share data with each other.
Concept-2 Need for Multiple Threads & Multithreaded Programming for Multi-core
Multi Processor
To increase in throughput of computer is possible only by dividing the program into segments that are data
dependent and can be processed simultaneously by more than one processor. Thus,
Thus it decreases the total time
of computation.
In a supercomputer, thousands of processors are employed to concurrently process the data.
Hardware developers have gone a step further by placing more than one core processor in the same CPU chip.
chi
Thus, now, we have multi-core
core CPUs.
CPUs
Multithreaded Programming for Multi-core Processor
A CPU may have two cores - dual core or four cores - quad, six cores, or more.
CPUs having as many as 50 cores have also been developed. Moreover, computers with multi-core CPU are
affordable and have become part of common man's desktop computer.
Advancements in hardware are forcing the development of suitable software for optimal utilization of the
processor capacity. Multithread processing is the solution.
Multithread programming is inbuilt in Java and CPU capacity utilization may be improved by having multiple
threads that concurrently execute different parts of a program.
Concept-3 Thread life cycle (or) Thread States
Define a Thread:
Thread is a lightweight unit of a small process that executes in multithreading environment.
A program can be divided into a number of small processes.
Each small process can be addressed as a single thread (a lightweight process).
When program is load in to the main memory it is automatically converted as process.
Thread has its life cycle that includes various phases like: new, running, runnable, blocked, terminated etc.
Methods Description
static Thread currentThread() Returns a reference to the currently executing thread
static int activeCount() Returns the current number of active threads
long getID() Returns the identification of thread
final String getName() Returns the thread’s name
final void join() Wait for a thread to terminate
void run() Entry point for the thread
final void setDaemon(boolean how) If how is true, the invoking thread is set to daemon status.
final boolean isDaemon() Returns true if the invoking thread is a daemon thread
final boolean isAlive() Returns boolean value stating whether a thread is still running
Methods Description
void interrupt() Interrupts a thread
Thread.State getState() Returns the current state of the thread
final int getPriority() Returns the priority of the thread
static boolean interrupted() Returns true if the invoking thread has been interrupted
final void setName(String thrdName) Sets a thread’s name to thrdName.
final void setPriority(int newPriority) Sets a thread’s priority to new priority
static void sleep(long milliseconds) Suspend a threads for a specified period of milliseconds
void start() Start a thread by calling its run() Method.
void destroy() Destroy the thread
Cause the current executing thread to pause and allow the other
static void yield()
threads to execute
Constructors of Thread Class
Constructors Description
It has no arguments, which simply means it uses the default name
Thread()
and the thread group
Thread(String threadName) The name of the thread can be specified as in threadName
Thread(ThreadGroup threadGroup,
Can specify the thread group and thread name.
String threadName)
Thread(Runnable threadOb, String ThreadOb is an instance of a class that implements the Runnable
threadName) interface.
By implementing the Runnable interface
This interface is present in java.lang package.
Create a class that implements the Runnable interface.
Implement the run() method, which contains the code to be executed in the new thread.
Create an instance of the class implementing Runnable.
Pass the Runnable instance to the Thread constructor.
Start the thread using the start() method.
Program
Concept-5 Thread Priority
Thread priorities are used by the thread scheduler to decide when each thread should be allowed to run.
higher-priority threads get more CPU time than lower-priority threads.
A higher-priority thread can also preempt a lower-priority one when a lower-priority thread is running and a
higher-priority thread resumes (from sleeping or waiting on I/O, for example), it will preempt the lower-
priority thread.
To set a thread’s priority, use the setPriority( ) method, which is a method of Thread class.
This is its general form: final void setPriority(int level)
level specifies the new priority setting for the calling thread.
The value of level must be within the range MIN_PRIORITY and MAX_PRIORITY.
Currently, these values are 1 and 10, respectively.
To return a thread to default priority, specify NORM_PRIORITY, which is currently 5.
These priorities are defined as static final variables within Thread class.
To obtain the current priority setting by calling the getPriority( ) method of Thread final int getPriority( ).
Program:
Concept-6 Synchronization
Synchronization in java is the capability to control the access of multiple threads to any shared resource.
Java Synchronization is better option where we want to allow only one thread to access the shared resource.
The synchronization is mainly used to
1. To prevent thread interference. 2. To prevent inconsistency problem.
Synchronization is built around an internal entity known as the lock or monitor.
Every object has a lock associated with it.
There are two types of thread synchronization
1. Synchronized method. 2. Synchronized block.
Synchronized method
If you declare any method as synchronized, it is known as synchronized method.
Synchronized method is used to lock an object for any shared resource.
When a thread invokes a synchronized method, it automatically acquires the lock for that object and releases it
when the thread completes its task.
Program: Output
Synchronized block
Synchronized block can be used to perform synchronization on any specific resource of the method.
Suppose you have 50 lines of code in your method, but you want to synchronize only 5 lines, you can use
synchronized block.
If you put all the codes of the method in the synchronized block, it will work same as the synchronized
method.
Points to remember for Synchronized block
Synchronized block is used to lock an object for any shared resource.
Scope of synchronized block is smaller than the method.
Program: Output
Concept-7 Inter-thread Communication
Inter-thread communication or Co-operation is all about allowing synchronized threads to communicate with
each other.
Inter-thread communication is a mechanism in which a thread gets into wait state until another thread sends a
notification.
It is implemented by following methods
wait() method
The wait() method causes current thread to release the lock and wait until either another thread invokes the
notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.
notify() method
The notify() method wakes up a single thread that is waiting on this object's monitor. If any threads are
waiting on this object, one of them is chosen to be awakened.
notifyAll() method
Wakes up all threads that are waiting on this object's monitor.
Concept-9 Suspending, Resuming, and Stopping of Threads
Thread suspend() method
The suspend() method of thread class puts the thread from running to waiting state.
This method is used if you want to stop the thread execution and start it again when a certain event occurs.
This method allows a thread to temporarily cease execution.
The suspended thread can be resumed using the resume() method.
Syntax:- public final void suspend()
Thread resume() method
The resume() method of thread class is only used with suspend() method.
This method is used to resume a thread which was suspended using suspend() method.
This method allows the suspended thread to start again.
Syntax:- public final void resume()
Program
Output:-
Thread stop() method
The stop() method of thread class terminates the thread execution. Once a thread is stopped, it cannot be
restarted by start() method.
Syntax:- public final void stop()
Program
Concept-8 String Handling in Java: Introduction & String Class
A String is a sequence of character such as “abcdef” or “bell”.
In Java, a String is an object representing a sequence of characters.
In Java, a string is an object of a class, and there is no automatic appending of null character
by the system.
In Java, there are three classes that we can create strings and process them with methods.
(i) class String (ii) class StringBuffer (iii) class StringBuilder
All the three classes are part of java.lang package.
All the three classes have several constructors that can be used for constructing strings.
In the case of String class, an object may be created as String str1 = "abcd";
Here: String is a Predefined class of java.lang package str1 is an object not a variable. "abcd" is string literal
Output:
Output:
Output:
Concept-11 Methods for Comparison of Strings
Method Description
It is used to know whether or not strings are identical. equals 0:, means the
int compareTo(String str) strings are equal. greater than 0: the caller string is greater than the argument
string. less than 0: the caller string is less than the argument string.
int compareToIgnoreCase It is used to know whether or not string are identical by ignoring the case
(String str) difference
It is used to compare the equality of both the strings. This comparison is case
boolean equals()
sensitive
boolean equalsIgnoreCase() If we want to compare two strings irrespective of their case differences
boolean startsWith(String str) Returns true if a string starts with the given substring
boolean endswith(String str) Returns true if a string ends with the given substring
Program: Output:
Output:
Output:
Concept-14 Data Conversion and Miscellaneous Methods
Method Description
boolean contains(CharSequence sequence) It is used to searches the sequence of characters in this string.
It is used to searches a string to find out if it contains the exact
boolean contentEquals(CharSequence chars)
same charsequence of characters in the specified string
It is used to searches a string to find out if it contains the exact
boolean contentEquals(StringBuffer chars)
same Stringbuffer of characters in the specified string
It is used to method converts different types of values into
static String valueOf(int i)
string.
Program:
Output:
Useful Methods:
void setAutoCommit(boolean status) : It is true by default means each transaction is committed by default
void commit(): commits the transaction
void rollback() : cancels the transaction
Program on Batch processing and Transaction management
import java.sql.*;
public class BpTmEx {
public static void main(String args[]) throws Exception {
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/cse","root","root");
con.setAutoCommit(false);
Statement stmt=con.createStatement();
stmt.addBatch("insert into student values(45,'rohith',33)");
stmt.addBatch("insert into student values(17,'ABD',40)");
stmt.addBatch("insert into student values(3,'Raina',34)");
stmt.addBatch("insert into student values(36,'Jadeja',32)");
int[] result =stmt.executeBatch();
System.out.println(result.length+" values are inserted ");
con.commit();
con.close();
}
catch(Exception e){
System.out.println(e);
}
}
}
Important Question
1. Write a java Program that finds number of vowles, number of characters, and digits in the String
2. Explain about different type of string creation class String class, Stringbuffer class, & StringBuilder class
3. Explain about Methods for Extracting Characters from Strings.
4. Explain about Methods for Comparison of Strings.
5. Explain about Methods for Modifying Strings.
6. Explain about Methods for Searching Strings.
7. Explain about Data Conversion and Miscellaneous Methods
8. Write a java program for comparison of Strings?
9. Write a java program for modification of Strings?
10. What is multi-Threading and need for multi-threading in java? Explain with a java program?
11. Explain states of Threads and Synchronization of Threads?
12. Explain the concept of Inter Thread communication in java?
13. Explain JDBC Architecture and also explain Steps to establish connection to data base using java program?
14. Explain JDBC Batch processing concepts with a java program?
15. Explain concept of JDBC Transaction management?