0% found this document useful (0 votes)
5 views27 pages

Unit 5 Notes

The document covers various aspects of Java programming, including string handling, multithreaded programming, and Java Database Connectivity (JDBC). It details the concepts of threads, their life cycle, creation methods, synchronization, and inter-thread communication, as well as the differences between threads and processes. Additionally, it discusses the String, StringBuffer, and StringBuilder classes, highlighting their characteristics and memory management.

Uploaded by

naveenbora06
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views27 pages

Unit 5 Notes

The document covers various aspects of Java programming, including string handling, multithreaded programming, and Java Database Connectivity (JDBC). It details the concepts of threads, their life cycle, creation methods, synchronization, and inter-thread communication, as well as the differences between threads and processes. Additionally, it discusses the String, StringBuffer, and StringBuilder classes, highlighting their characteristics and memory management.

Uploaded by

naveenbora06
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

UNIT-5

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 and each thread
defines a separate path of execution.
 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.
Multitasking
 Multitasking is a process of performing multiple tasks simultaneously.
 Computer system that perform multiple tasks like: writing data to a file, playing music,
downloading file from remote server at the same time.
 Multitasking can be achieved either by using multiprocessing or multithreading.
 Multitasking by using multiprocessing involves multiple processes to execute multiple tasks
simultaneously whereas Multithreading involves multiple threads to execute multiple tasks.

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 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, it decreases the total time
of computation.
 This is the basis on which supercomputers are built.
 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.
Thus, now, we have multi-core 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.
Thread life cycle
 New : A thread begins its life cycle in the new state. It remains in this state until the start() method is called on
it.
 Runnable: After invocation of start() method on new thread, the thread becomes runnable.
 Running: A thread is in running state if the thread scheduler has selected it.
 Waiting: A thread is in waiting state if it waits for another thread to perform a task. In this stage the thread is
still alive.
 Terminated: A thread enter the terminated state when it complete its task.
Daemon Thread
 Daemon threads are a low priority thread that provides supports to user threads.
 These threads can be user defined and system defined as well.
 Garbage collection thread is one of the system generated daemon thread that runs in background.
 These threads run in the background to perform tasks such as garbage collection.
 Daemon thread does allow JVM from existing until all the threads finish their execution.
Concept-4 Creation of New Threads
 Create a thread by instantiating or creating an object of type Thread class.
 Java defines two ways in which this can be accomplished
1. By implementing the Runnable interface.
2. By extending the Thread class.
By extending the Thread class
 This is the way to create a thread by a new class that extends Thread class and create an instance of
that class.
 The extending class must override run() method which is the entry point of new thread.
 Create the thread object and use the start() method to initiate the thread execution.
 Declaring a class: Any new class can be declared to extends the thread class, thus inheriting all the
functionalities of the Thread class.
Class NewThread extends Thread {
------
------
}
 Overriding the run() Method: The run() Method has to be overridden by writing codes required for the
thread. Specify the code that your thread will execute inside run() method.
 Starting New Thread: The Start() Method which is required to create and initiate an instance of our Thread
class. NewThread thread1=new NewThread();
thread1.start();
 The first line creates an instance of the class NewThread, where the object is just created. The thread is in
newborn state.
 Second line which calls the start() method, moves the thread to runnable state, where the JVM will schedule
the thread to run by invoking the run() method. Now the thread is said to be in running state.
Program:

Methods of Thread Class

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
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
 Java Runnable is an interface used to execute code on a concurrent thread.
 It is an interface which is implemented by any class, that the instances of that class should be executed by a
thread class.
 The Runnable interface has an undefined method run() with void as return type, and it takes in no arguments.
 This interface is present in java.lang package.
Method Description
This method takes in no arguments. When the object of a class implementing Runnable
public void run() interface is used to create a thread, then the run method is invoked in the thread which
executes separately.
 Runnable interface is when we want only to override the run method.
 When a thread is started by the object of any class which is implementing Runnable, then it invokes the run
method in the separately executing thread.
 The class that implements Runnable, you will instantiate an object of type Thread from that class.
 Thread defines several constructors
Thread(Runnable threadOb, String threadName)
 ThreadOb is an instance of a class that implements the Runnable interface.
 This defines where execution of the thread will begin.
 The name of the new thread is specified by threadName.
 After the new thread is created, it will not start running until you call its start() method, which is declared
within Thread class.
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

1. wait() 2. notify() 3.notifyAll()

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

 The two declarations are equivalent to the following


char s1[]={‘a’,’b’,’c’,’d’};
char s2[]={‘E’,’e’,’1’,’l’};
 Object of class string may also be created by operator new-like object of any other class.
String str=new String(“abcd”);
 In the case of other two classes, the objects can be created only by the operator new as
StringBuffer burstr=new StringBuffer(“abcd”);
StringBuilder buildstr=new StringBuilder(“abcd”);
Storage of Strings
 The memory allocated to a Java program is divided into two segments
(i) Stack
(ii) Heap
 The objects of class String have a special storage facility, which is not available to objects of other two String
classes or to objects of any other class.
 The variables are stored on heap, whereas the program is stored on stack.
 Within the heap, there is a memory segment called ‘String constant pool’.
 The String class objects can be created in two different ways:
String strx = "abcd"; String strz = new String("abcd");
Immutability
String class
 The string objects created by class String are immutable.
 By immutable implies that once an object is created, its value or contents cannot be changed.
 Neither the characters in the String object once created nor their case (upper or lower) can be changed.
 The immutable objects are thread safe and so are the String objects.
StringBuffer class
 The objects created by class StringBuffer are mutable.
 These are stored on the heap segment of memory outside the String constant pool.
 The contents of StringBuffer strings may be changed without creating new objects.
 The methods of StringBuffer are synchronized, and hence, they are thread safe
StringBuilder class
 The objects of class StringBuilder are also mutable but are not thread safe.
 The operations are fast as compared to StringBuffer and there is no memory loss as is the case with String
class.
 The class StringBuilder has the same methods as the class StringBuffer.

Program:
Output:

Concept-9 Interface Char Sequence


 It is an interface in java.lang package.
 It is implemented by several classes including the classes like String, StringBuffer, and StringBuilder.
 It has the following four methods.
Method Description
char charAt(int index) The method returns character value at specified index value.
int length() This method returns the length of this (invoking) character sequence.
CharSequence subsequence
The method returns a subsequence from start index to end index of this sequence
(int startIndex, endIndex)
String toString() The method returns a string containing characters of the sequence in the same
Program:

Output:
Concept-10 Methods for Extracting Characters from Strings
Method Description
char charAt(int index) It is used to extract a single character at an index
void getChars(int stringStart, int
It is used to extract more than one character
stringEnd, char arr[], int arrStart)
It is used extract characters from String object and then convert the
byte [] getBytes()
characters in a byte array
It is used to convert all the characters in a String object into an array of
char [] toCharArray()
characters.
int length() It is used extract the length of the string
Program:

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:

Concept-12 Methods for Modifying Strings


Method Description
Using this method, you can extract a part of originally declared string/string
String substring()
object
String substring(int startIndex) Using the startIndex, you specify the index from where your modified string
should start.
String substring(int startIndex, In this method, you give the starting point as well as the ending point of the
int endIndex) new string.
String concat() Using this function you can concatenate two strings.
char replace() This method is used to modify the original string by replacing some
characters from it
String replace(char original,
This method replaces one and only character from the original string.
char replacement)
This method is used to removes the extra white spaces at ending of the string
String trim()
and beginning of the string
Program:

Output:
Concept-13 Methods for Searching Strings
Method Description
int indexOf(int ch) Returns the index within this string of the first occurrence of the specified character.
int indexOf(int ch, int
Returns the index within this string of the first occurrence of the specified character,
fromIndex) starting the search at the specified index.
int indexOf(String str) Returns the index within this string of the first occurrence of the specified substring.
int indexOf(String str,
Returns the index within this string of the first occurrence of the specified substring,
int fromIndex) starting at the specified index.
Program:

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:

Concept-15 Class String Buffer


 Java StringBuffer class is used to create mutable (modifiable) string.
 The StringBuffer class in java is same as String class except it is mutable i.e. it can be
changed. Object Creation using StringBuffer
StringBuffer sb=new StringBuffer();
StringBuffer sb=new StringBuffer("Hello");
StringBuffer sb=new StringBuffer(20);
What is mutable string
 A string that can be modified or changed is known as mutable string.
 StringBuffer and StringBuilder classes are used for creating mutable string.
Constructors of StringBuffer class
Constructor Description
StringBuffer() creates an empty string buffer with the initial capacity of 16.

StringBuffer(String str) creates a string buffer with the specified string.


creates an empty string buffer with the specified capacity as
StringBuffer(int capacity)
length.
Inbuilt Methods in the StringBuffer Class
Method Description
reverse() It is used to reverse the string.
capacity() It is used to return the current capacity.
It is used to return the length of the string i.e. total
length()
number of characters.
substring(int beginIndex, int It is used to return the substring from the specified
endIndex) beginIndex and endIndex.
replace(int startIndex, int endIndex, It is used to replace the string from specified
String str) startIndex and endIndex.
It is used to delete the string from specified
delete(int startIndex, int endIndex)
startIndex and endIndex.
insert(int offset, String s) It is used to insert the specified string with this string
at the specified position.
Programs:
Concept-16 Class String Builder
 Java StringBuilder class is used to create mutable (modifiable) String.
 The Java StringBuilder class is same as StringBuffer class except that it is non-synchronized.
Constructors of StringBuilder Class
Constructor Description
StringBuilder() It creates an empty String Builder with the initial capacity of 16.
StringBuilder(String str) It creates a String Builder with the specified string.
It creates an empty String Builder with the specified capacity as
StringBuilder(int length)
length.
Inbuilt Methods in the StringBuilder Class
Method Description
public StringBuilder reverse() It is used to reverse the string.
public int capacity() It is used to return the current capacity.
public char charAt(int index) It is used to return the character at the specified position.
It is used to return the length of the string i.e. total number of
public int length()
characters.
public String substring(int It is used to return the substring from the specified beginIndex.
beginIndex)
public String substring(int It is used to return the substring from the specified beginIndex
beginIndex, int endIndex) and endIndex.
public StringBuilder
It is used to append the specified string with this string.
append(String s)
public StringBuilder insert(int It is used to insert the specified string with this string at the
offset, String s) specified position.
Programs:
Concept-17 Java Database Connectivity: Introduction
 JDBC stands for Java Database Connectivity, which is a standard Java API for database independent
connectivity between the Java programming language and a wide range of databases.
 It is a part of JavaSE (Java Standard Edition). JDBC API uses JDBC drivers to connect with the database.
 It is plat independent technology
 The JDBC library includes APIs for each of the tasks commonly associated with database usage:
1. Making a connection to a database
2. Creating SQL or MySQL statements
3. Executing that SQL or MySQL queries in the database
4. Viewing & Modifying the resulting records
Concept-18 JDBC Architecture
The JDBC API supports
1. two-tier processing model
2. three-tier processing model for database access but in general JDBC Architecture consists of two layers·
JDBC API: This provides the application-to-JDBC Manager connection.
JDBC Driver API: This supports the JDBC Manager-to-Driver Connection.
Two Tier Processing Model:
 Here java applications communicates directly with Data base so it requires JDBC Driver to communicate with
Particular database being accessed User sends a QUERY to Data Base then Data Base Sends response to user.
 In this Database is not necessary to present in single machine it can locate on different machines so called
Client-Server Configuration i.e., user machine acts as client and machine having data base acts as server
machine
 Advantages: Easy to maintain & Modification also easy.
 Disadvantages: App performance reduces when no.of clients increases.
Three Tier Processing Model
 Here User sends Queries to middle tier server from middle tier server Queries are send to DB server
 Data Base server takes Queries from middle tier server and process those queries and then sends the response
to middle tier server
 After that Middle tier server sends results back to user
 Advantages: High performance & Security.
 Disadvantages: More complex to maintain.

Concept-19 JDBC Environment Setup


 To start developing with JDBC, you should setup your JDBC environment by following the steps shown
below. We assume that you are working on a Windows platform
 Install Java
 Install JDK from Oracle website
 JAVA_HOME: This environment variable should point to the directory where you installed
 CLASSPATH: This environment variable should have appropriate paths set
 PATH: This environment variable should point to appropriate JRE bin
Install Database (Ex: MySql and MySql Connector J)
 MySQL DB: MySQL is an open source database. You can download it from MySQL Official
Site.(mysql.com)
 We recommend downloading the Default Option because it will download all default softwares. It includes
MySql Connector J Which is useful for JDBC for MySql
 Install the driver at C:\Program Files\MySQL\mysql-connector-java-5.1.8. Accordingly, set
 CLASSPATH variable to C:\Program Files\MySQL\mysql-connector-java5.1.8\mysqlconnector-java-
5.1.8-bin.jar.
 Your driver version may vary based on your installation.
Concept-20 Establishing Data Base Connections
 To Connect java Application to data base we need following steps
 Here we are using Mysql data base instead you can use other data base also like Oracle
Step 1: Driver class: Diver class is com.mysql.jdbc.Driver
Step 2: Connection to URL :
Jdbc:mysql://localhost:3306/rcee
Jdbc= is an API
Mysql= data base
Localhost= servername
3306= port number (When installing Mysql we used)
rcee= database name
Step 3: User name : the default user name for mysql data base is root
Step 4: Password : it is the pass word given by the user at the time of installing mysql database
Create a table in database
SQL> create table emp(id int, name varchar(30), age int );
Insert Values into Table
SQL> insert into emp values ( (102,”Tej”,24); (103,”Ram”,26); );
SQL > select * from emp;
Concept-21 ResultSet interface
 Object of ResultSet maintains a cursor priority to row of table
Commonly Used Methods:
boolean next(): it returns true if row is present
boolean previous(): it returns true if previous row is present
boolean first(): first row in result set object
boolean last(): last row in result set object
boolean absolute(int row): it results row if available
Program:
import java.sql.*;
public class MysqlCon {
public static void main(String args[]){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection( "jdbc:mysql://localhost:3306/rcee","root","root");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
con.close();
}
catch(Exception e){
System.out.println(e);
}
}
}
Output:
102 Tej 24
103 Ram 23
Concept-22 JDBC Batch Processing
 Instead of executing a single query , we can execute a batch(group) of queries .
 Advantage : it makes performance fast
 The java.sql.Statement and java.sql.PreparedStatement interfaces provide methods for batch processing
 Methods:
public void addBatch(Query) : it adds query to batch
int[] executeBatch() : it executes batch of queries
Steps:
Load the Driver class
Create connection
Create a statement
Add Query to batch
Execute batch
Close connection
Concept-23 JDBC Transaction Management
 Transaction represents a single unit of work.
 The ACID properties describe the transaction management well.
 ACID stands for Atomicity, Consistency, isolation and durability.
 Atomicity means either all successful or none.
 Consistency ensures bringing the database from one consistent state to another consistent state.
 Isolation ensures that transaction is isolated from other transaction.
 Durability means once a transaction has been committed, it will remain so, even in the event of errors, power
loss etc.
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?

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy