Java Unit 5
Java Unit 5
5.1.1 INTRODUCTION
5.1.2 INTERFACE CHAR SEQUENCE
5.1.3 CLASS STRING
5.1.4 METHODS FOR EXTRACTING CHARACTERS FROM STRINGS
5.1.5 METHODS FOR COMPARISON OF STRINGS
5.1.6 METHODS FOR MODIFYING STRINGS
5.1.7 METHODS FOR SEARCHING STRINGS
5.1.8 DATA CONVERSION AND MISCELLANEOUS METHODS
5.1.9 CLASS STRING BUFFER
5.1.10 CLASS STRING BUILDER.
MULTITHREADED PROGRAMMING:
5.2.1 INTRODUCTION
5.2.2 NEED FOR MULTIPLE THREADS
5.2.3 THREAD CLASS
5.2.4 MAIN THREAD- CREATION OF NEW THREADS
5.2.5 THREAD STATES
5.2.6 THREAD PRIORITY-SYNCHRONIZATION
5.2.7 DEADLOCK AND RACE SITUATIONS
5.2.8 INTER-THREAD COMMUNICATION – SUSPENDING
5.2.9 RESUMING AND STOPPING OF THREADS.
5.3.1 INTRODUCTION
5.3.2 JDBC ARCHITECTURE
5.3.3 INSTALLING MYSQL AND MYSQL CONNECTOR
5.3.4 JDBC ENVIRONMENT SETUP
5.3.5 ESTABLISHING JDBC DATABASE CONNECTIONS
5.3.6 RESULTSET INTERFACE
JAVA FX GUI:
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.
Output:
C:\>javac StringArray.java
Output:
C:\>javac StringUnicode.java
Example: StringArray2.java
public class StringArray2
{
public static void main(String args[]) throws Exception
{
byte []bray = new byte[]{65, 66, 67, 68, 69};String str = new String(bray,1,3,"ascii");
Output:
C:\>javac StringArray2.java
C:\>java StringArray2str =BCD
Example: StringValue.java
C:\>javac StringValue.java
C:\>java StringValues2.valueOf(n) = 70
s2.valueOf(l) = 25674
s3 = 45.76
s2.valueOf(array) = De1his1.toString() = Railways
class StringBufferDemo
{
public static void main (String args[])
{
StringBuffer bufStr = new StringBuffer ("Hello WorldExample" );
System.out.println("bufStr = " + bufStr);System.out.println("Length of bufStr =" +
bufStr.length());
char ch=bufStr.charAt(4);
System.out.println("Character at 4th position = " + ch);
bufStr.setCharAt(7, 'e');
System.out.println(" Now New bufStr =" + bufStr);
}
}
Output:
C:\>javac StringBufferDemo.java
Some computer programs may be divided into segments that can run independent ofeach
other or with minimal interaction between them.
Each segment may be considered as an independent path of execution called athread.
If the computer has multiple processors, the threads may run concurrently on different
processor thus saving computing time.
Threads are useful even if the computer has a single-core processor.
The different processes in a computer take different times.
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.
A. How Single Processor – tasks carried out in Single Sequence is illustrated in thefollowing
diagram.
B. The following diagram shows the Single processor – threads share the time of processor
3. Thread Class
In Java, threads are based on the class Thread belonging to java.lang package, that is,
java.lang.Thread.
A thread is an object of class Thread and can invoke the instance methods defined in theclass.
Even if a thread is not explicitly defined, one thread is automatically created by thesystem for the
execution of the main method. It is generally called main Thread.
A thread does not start working on birth. It has to invoke the start() method that gives itthe life,
otherwise it is a lifeless thread object.
After getting life, a thread executes a code of instructions (target) as specified by the userin the
overloaded method run().
The Thread class has defined several constructors.
i. Thread(): It allocates a new thread object as thread(null, null, generatedname).Every thread
must have a name.
ii. Thread(String threadname): It allocates a thread with name specified by theuser. It is of the
form thread(nall null, name). A thread may be created as
Thread t2 new Thread("MyThread");
iii. Thread(Runnable object) : The constructor allocates a thread with a specified target.The name
by the compiler as Thread-0, Thread-1, and so on.
iv. Thread (Runnable object, String threadName): Thread is allocated with a specifiedtarget and
JAVA PROGRAMMING 12 KKVPRASAD@CSE
user specified name threadnume.
v. Thread (ThreadGroupgroup, Runnable object): It allocates thread with specifiedgroup and
target.
vi. Thread (ThreadGroupgroup, Runnable object, String Threadname): The constructor
allocates thread with specified thread group, target, and thread name.
Thread Group
Every thread is in fact a member of a thread group. The thread groups are useful forinvoking
methods that apply to all the threads.
The thread is made a member of a group at the time of its creation with constructor.
The thread remains the member of the designated group throughout its life.
It cannot become the member of another group.
If a thread's group is not specified in its constructor, as is the usual case, the thread isentered into
the same group as the thread that created it.
The default thread group for a newly executing Java application is the main group.
When a thread dies, its thread group becomes null
The following methods of class Thread have been deprecated because these are either unsafeor are
deadlock pruned.
JAVA PROGRAMMING 13 KKVPRASAD@CSE
stop() : The invoking thread stops executing with clean-up, and thus, exposes sensitiveresources to
other threads.
destroy(): It terminates the thread without clean-up. Deadlock pruned method. suspend(): It
temporarily suspends the execution of thread without clean-up. Deadlockpruned method
resume(): It brings back the suspended thread to runnable state. Used only after suspend().
countStackFrames(): It is not well-defined. Returns number of stack frames in this thread.
4. Main Thread
When we run a program in Java, one thread is automatically created and it executes themain
method. The thread is called main thread. This is the thread from which other threads are created.
The threads created from the main thread are called child threads.
A program keeps running as long as the user threads are running.
The main thread also has the status of a user thread.
The child threads spawned from the main thread also have the status of user thread.
Therefore, main thread should be the last thread to finish so that the program finisheswhen the
main method finishes.
A thread is controlled through its reference like any other object in Java.
The main thread can also be controlled by methods of Thread class through its referencethat can be
obtained by using the static method current Thread(). Its signature is
Thread thread = Thread.currentThread();
sleep() method suspend the execution for the given specified time interval.Ex:
thread.sleep(500);
the avbove statement will suspend the execution of main() method for 500 ms, which is theargument
of the method.
setName() method add the new name to the existing threadEx:
thread.setName("My Thread") Illustration of main thread and methods
setName() and getName()
The new thread is created by creating a new instance of Thread class. The enhancements inJava 8
enables us to create and execute new threads in the following ways
Example: MyClass.java
Output:
C:\>javac MyClass.java
C:\>java MyClassIt is MyThread.
The runnable is an interface that has only one method in it, that is
public interface Runable( public void run());
The full definition of method run() is included in the class. The thread begins with executionof run()
and ends with end of run() method. The step wise procedure is given here.
Example: MyThreadClass.java
Output
This Is Runnable implementation.
iii. Creation of Threads by Lambda Expression, Method Reference, and Anonymous Class
The Lambda expression and method references are simplify the code for creating the thread, asillustrated in the
following program.
}
static void Method1()
{
System.out.println("It method reference thread.");
}
static void Method2()
{
System.out.println("It is Lambda expression methodthread.");
}
static void Method3()
{
System.out.println("It is conventional method thread.");
}
}
Output:
C:\>javac ThreadMethods.java
C:\>java ThreadMethods
It method reference thread.
It is Lambda expression method thread.It is conventional method thread.
The transition from one state to another is shown in the figure. The different states are asfollows
1. New thread state. The thread is just created. It is simply a lifeless object of class Thread.
2. Runnable state: When the thread invokes the method start(), it becomes alive. This state iscalled
runnable state. It is not a running state. It is simply a ready-to-run. The thread has to wait till it is
scheduled, that is, selected from the group of threads waiting in running state for dispatch to the CPU
by the scheduler
3 Running state. If the scheduler chooses the thread from the waiting list of threads and dispatches it
CPU, the thread transits to runnable state, that is, it starts executing the methodrun() meant for it. This
is turning state. If it completes its run() method successfully, its life span is over. The thread is
automatically terminated and it goes to dead state from which it cannot be revived.
4. Sleep state: The code that a thread is executing may require it to relinquish the CPU forsometime
so the other threads can possess CPU. The sleep method may be invoked by the thread. The time
period of them is the argument of sleep() method. It is either long milliseconds
or int nanoseconds. After the sleep the thread returns normally to runnable state.
5. Blocked state. A running thread gets into blocked state if it attempts to execute a task.
6. State wait: A thread gets into wait state on invocation of any of the three methods wait()or wait
(long millisees) or wait (long millisecs, int nanosecs).
7. yield. The use of code Thread yield(), is another method besides the sleep for the thread tocease the
use of CPU. The thread transits to Runnable state.
8. Suspended. The term belongs to legacy code and is defined in Java 1.1. The suspendedthread can
be brought back to normal Runnable state only by method resume(). Both the methods suspend() and
resume() are now deprecated, instead one should use wait()and notify().
All the threads have a priority rating of be When several threads are present, the priorityvalue
determines which thread has the chance to possess the Ofest.
The actual allocation is done by the scheduler. Thus, a thread with higher priority has higherchance
getting the CPU and also a higher share of CPU time. Keeping equal priority for all threads ensures
that each has equal chance to share CPU time, and thus, no thread starves, because when a thread with
higher priority enters the Runnable state, the operating system may pre-empt the scheduling by
allocating CPU to the thread with higher priority.
When this thread returns from sleep or wait state, the same story may be repeated. When several
threads of different priorities are present, it is quite likely that a thread with the lowestpriority may not
get a chance to possess CPU. This is called starvation.
8. 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.
In several multithreaded programs, the different threads are required to access the same resource, for
example, a memory object during the execution. One thread may attempt toupdate it, while the other
wants to read it and a third may try to alter the content of the memory.
Such a situation may give rise to race condition and the result may be quite different if thesequence
of operations actually followed is different from the desired one.
Proper execution requires that at any point of time, only one thread be allowed to use thecritical
resource till it finishes its task.
We are all aware of the computerized banking system. In one branch, money may be deposited in your
account, while you are withdrawing money at another branch. There can bea problem if one thread has
partly finished its task, while the other gets in. It will corrupt the data.
Synchronization solves this problem by allowing only one thread can access the resource.The second
thread should be allowed only when the first has finished its task.
In a multithreaded program, the race and deadlock conditions are common when improperly
synchronized threads have a shared data source as their target.
A race condition may occur when more than one thread tries to execute the codeconcurrently. A
thread partly does the job when the second thread enters.
If the process is atomic, that is, it cannot be subdivided the effect of race condition will belimited.
However, when the process is not atomic and can be subdivided into two or more sub- processes, it
may occur that a thread has done subprocess, and the second thread enters andstarts executing. In such
cases, the results can be far from the desired ones.
Therefore, a race condition is a situation in which two or more threads try to execute code and their
actions get interleaved. The solution for such condition is the synchronization, and therefore, only one
thread should enter code at a time and othersshould wait until the first hasdone its job.
A deadlock condition may lead to program crash. Such a situation occurs when two threads are
attempting to carry out synchronized hods that are inter-dependent, that is, the completionof Method1
needs Method2 and completion of Method2 needs Method1.
These direct methods are very convenient to control the operation of threads in a multithreadenvironment.
However, in some situations, they may crash the program or cause serious damage to critical data.
For example, if a thread has got the lock to a critical synchronized section of code and getssuspended, it
will not release the lock for which other threads may be waiting.
Instead of methods suspend() and resume(), the methods wait() and notify() are used.
JDBC stands for Java Database Connectivity and has been developed by Sun Microsystems.
It is a standard Java API that defines how the front-end application (that may be webapplication or
simple Java application) may access the database.
It provides a standard library for accessing a wide variety of database systems. Previously, Open
Database Connectivity (ODBC) API used to be the database API for connecting and executing query
with the database.
JDBC applications are platform independent, and thus, they can be used for connecting withInternet
applications. JDBC applications are simpler and easier to develop.
JDBC API and JDBC driver form the important components in order to fetch/store theinformation to
the database.
JDBC API is installed at the client side. Therefore, when the user wants to fetch some data from the
database, the user sets up the connection to JDBC manager using JDBC API throughthe Java
application.
JDBC manager needs a medium in order to communicate with the database. JDBC driver provides this
medium and the required information to JDBC manager, JDBC library includesAPIs that define
interfaces and classes for writing database applications in Java.
Through the JDBC API, we can access a wide variety of database systems including relational as well
as non-relational database system. This chapter focuses on using JDBC toaccess data in Relational
Database
Table is a collection of related data entries and consists of columns and rows.
Some of the most widely used relational database systems include Microsoft MySQL server,Oracle,
and IBM's DB2.
Any Java-based application can access a relational database. For this, any RDBM systemneeds to be
installed that provides driver conforming to Java Database Connectivity.
JDBC API enables the programmers to change the underlying DBMS (for example, fromMySQL to
Oracle), without changing the Java code that accesses the database.
2. JDBC Architecture
In this model, Java application communicates directly with the database. For this, JDBCdriver is
required and it can establish direct communication with the database.
As can be seen from the figure, both Java application and JDBC API are located at the clientmachine
and the DBMS and database are located at the database server.
User sends commands to the database. The commands processed and the results of thesestatements are
sent to the user.
Java application and the database may reside on the same machine. Alternatively, databasemay be on
the server machine, while the Java application may be on the client machine, which may be connected
via the network.
In this model, user's commands are first sent to the application server forming the middle tier.
Application server containing the JDBC API sends the SQL statements to the database located on the
database server. The commands are processed and the result is sent to the middle tier, which then
sends it to the user.
Middle tier has often been written in languages such as C or C++ that provide the fastperformance.
However, Java platform has become the standard platform for middle-tier development withthe
advancements made in the optimizing compilers. These compilers translate Java byte code into an
efficient machine specific code.
This model is usually common in web applications in which the client tier is implemented in the web
browser. Web server forms the middle tier and the database management system runs on database
server. This model provides better performance and simplifies the deployment ofapplications.
MySQL is the most widely used open-source relational database management system.
It is considered to be one of the best RDBMS systems for developing web-basedsoftware
applications as it provides speed, flexi bility, and reliability.
Before we can use MySQL with JDBC, we first need to install MySQL.
“MySQL community edition” freely available and can be downloaded from the
MySQL website
http://www.mysql.com .
i. On successful download, click the mySQL icon. MySQL Server 5.6 setup. Click on theNext
button.
ii. License agreement page would appear next. Read the terms and conditions and click on Iaccept
the wizard window would terms in the license Agreement checkbox.
iii. Next, it will ask for the set up type that suits your needs. Click on Typical button inChoose set up
Type screen.
iv. Then click on install button for starting the installation process wizard.
v. Completed MySQL Server 5.6 Setup Wizard would appear. Click on finish to exit the
vi. MySQL Server Instance Configuration screen would appear, and select the Detailed
Configuration.
vii. Following this, MySQL Server Instance Configuration Wizard would open up andchoose the
server as Developer Machine.
viii. Now click on Next button, and select the Dedicated MySQL Server Machine or youmay
choose Developer Machine if other applications and tools are being run on your system.
ix. Thereafter, select multifunctional database for general purpose database, when MySQLServer
Instance Configuration Wizard screen appears. Then, select the drive where the database files
would be stored.
x. Keep the default port as 3306 and specify the root password.
After the successful installation of MySQL, we need to install MySQL Connector/J (where J stands
for Java). This is the JDBC driver that allows Java applications to interact withMySQL.
dev.mysql.com/downloads/connector/j/3,1.html.
SQL Statements
SQL statements are used for performing various actions on the database.
i. SQL select statements :
The select statements are used to select data from the database.
Syntax :
select column_name1, column_name2 from tablename;
Example-1:
select id, stdName from Student;
Here :
id and stdName are the column namesStudent is the table name;
Example-2:
Select * from Student;
The above statement selects all the columns from Student table.
For instance,
example:
delete from Student where firstname="Riya";
This section focuses on how to set up the connection to MySQL database from NetBeans IDE.
NetBeans IDE supports MySQL RDBMS. In order to access MySQL database server inNetBeans IDE,
we have to first configure the MySQL Server properties. This involves the following steps:
1. Open the NetBeans IDE, right click the database node in the services window. Select Register
MySQL Server MySQL server properties dialog box would open. Confirm that theserver host name and
port are correct. The default server host name is localhost and 3306 isthe default server port name.
2. Enter the administrator password. You can give any password and default is set to blankpassword.
3. At the top of dialog box, click on the Admin properties tab. Here, you can enter theinformation for
controlling the MySQL server.
4. In the admin properties dialog box, enter the path/URL to admin tool. This is the locationof MySQL
Administration.
5. Next, you have to enter the path to start the command. For this, look for mysqld in the binfolder
MySQL installation directory of
6. In the path to stop the command field, type or browse to the location of MySQL stop command. This
is the path where mysqladmin the bin folder of MySQL installation directoryis located.
Additional steps that must be checked before starting with the involvement of Java-baseddatabase
connectivity:
1. Before starting, make sure that MySQL Database server is running. If database server isnot
connected, it will show 'disconnected'. For connecting it, right click the Database, and choose 'connect".
This may also prompt to give password to connect to the database server
2. When a new project is created in NetBeans, copy the mysql-connector/java JAR file intothe library
folder.
JDBC Connectivity Model and API
Fig. 27.1 depicts the JDBC connectivity model. JDBC API enables Java applications to be connected to
relational databases through standard API. This makes possible for the user to establish a connection to
a database, create SQL or MySQL statements, execute queries in thedatabase, and so on. JDBC API
comprises the following interfaces and classes:
This class manages a list of database drivers. It matches the connection request from the Javaapplication
with the database driver using communication sub-protocol. It acts as an interface between the user
and the driver and is used to get a Connection object.
Commonly used methods of this class are as followsMethod
Driver
It handles communication with the database server. JDBC drivers are written in Java language in order
to connect with the database. JDBC driver is a software component comprising a set of Java classes that
provides linkage between Java program running on Javaplatform and RDBM system that is residing on
the operating system.
There are basically four different types of JDBC drivers and these implementations varybecause
of the wide variety of operating systems and hardware platforms available in which Java operates
Type 1 JDBC-ODBC bridge driver
Type 1 JDBC driver provides a standard API for accessing SQL on Windows platform. In this type of
the driver, JDBC bridge is used to access ODBC drivers installed on the client machine. For using
ODBC, Data Source Name (DSN) on the client machine is required to beconfigured.
The driver converts JDBC interface calls into ODBC calls. It is, therefore, the least efficientdriver of the
four types. These drivers were mostly used in the beginning and now it is usually used for experimental
purposes when no other alternative is available
Type 3 and 4 drivers are preferably used if the program application does not exist on the same host as
the database. It requires data base-specific coding to be done in the middle tier.
It is installed inside the Java Virtual Machine of the client and most of the JDBC drivers are of Type 4.
iv. javax.sql package provides the required API for server-side data source access and processing. This
package supplements the java.sql package. It is included in the JavaPlatform Standard Edition (Java
SETM).
Connection:
This interface comprises methods for making a connection with the database. All types of
communication with the database is carried out through the connection object only.
Statement
Object created from this interface is used to submit the SQL statements to the database.
ResultSet
It acts as an iterator that enables to move through the data. Object created from interface isused to data
received from the database after executing SQL query.
SQL Exception
This class handles errors that may occur in a database application.