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

VND Openxmlformats-Officedocument Wordprocessingml Document&rendition 1-1

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

VND Openxmlformats-Officedocument Wordprocessingml Document&rendition 1-1

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

UNIT-5

String Handling in Java


String is a sequence of characters. But in Java, string is an object that represents a sequence
of characters. The java.lang.String class is used to create a string object.

n Java, string is basically an object that represents sequence of char values. An array of
characters works same as Java string. For example:

1. char[] ch={'j','a','v','a','t','p','o','i','n','t'};
2. String s=new String(ch);

is same as:

1. String s="javatpoint";

There are two ways to create String object:

1. By string literal
2. By new keyword

1) String Literal

Java String literal is created by using double quotes. For Example:

1. String s="welcome";

By new keyword

1. String s=new String("Welcome");//creates two objects and one reference variable

Java String Example

StringExample.java

1. public class StringExample{


2. public static void main(String args[]){
3. String s1="java";//creating string by Java string literal
4. char ch[]={'s','t','r','i','n','g','s'};
5. String s2=new String(ch);//converting char array to string
6. String s3=new String("example");//creating Java string by new keyword
7. System.out.println(s1);
8. System.out.println(s2);
9. System.out.println(s3);
10. }}

Java String class provides a lot of methods to perform operations on strings such as
compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring()
etc.

Java String class methods

The java.lang.String class provides many useful methods to perform operations on sequence
of char values.

No Method Description
.

1 char charAt(int index) It returns char value for the


particular index

2 int length() It returns string length

3 static String format(String format, Object... args) It returns a formatted string.

4 static String format(Locale l, String format, It returns formatted string with


Object... args) given locale.

5 String substring(int beginIndex) It returns substring for given begin


index.

6 String substring(int beginIndex, int endIndex) It returns substring for given begin
index and end index.

7 boolean contains(CharSequence s) It returns true or false after


matching the sequence of char
value.

8 static String join(CharSequence delimiter, It returns a joined string.


CharSequence... elements)

9 static String join(CharSequence delimiter, It returns a joined string.


Iterable<? extends CharSequence> elements)
10 boolean equals(Object another) It checks the equality of string with
the given object.

11 booleanisEmpty() It checks if string is empty.

12 String concat(String str) It concatenates the specified string.

13 String replace(char old, char new) It replaces all occurrences of the


specified char value.

14 String replace(CharSequence old, CharSequence It replaces all occurrences of the


new) specified CharSequence.

15 static String equalsIgnoreCase(String another) It compares another string. It


doesn't check case.

16 String[] split(String regex) It returns a split string matching


regex.

17 String[] split(String regex, int limit) It returns a split string matching


regex and limit.

18 String intern() It returns an interned string.

19 int indexOf(int ch) It returns the specified char value


index.

20 int indexOf(int ch, int fromIndex) It returns the specified char value
index starting with given index.

21 int indexOf(String substring) It returns the specified substring


index.

22 int indexOf(String substring, int fromIndex) It returns the specified substring


index starting with given index.

23 String toLowerCase() It returns a string in lowercase.

24 String toLowerCase(Locale l) It returns a string in lowercase


using specified locale.

25 String toUpperCase() It returns a string in uppercase.

26 String toUpperCase(Locale l) It returns a string in uppercase


using specified locale.

27 String trim() It removes beginning and ending


spaces of this string.

28 static String valueOf(int value) It converts given type into string. It


is an overloaded method.

Methods for extracting characters from strings


Java String charAt()

The Java String class charAt() method returns a char value at the given index number.

The index number starts from 0 and goes to n-1, where n is the length of the string. It
returns StringIndexOutOfBoundsException, if the given index number is greater than or
equal to this string length or a negative number.

Syntax

1. public char charAt(int index)


2. public class CharAtExample{
3. public static void main(String args[]){
4. String name="javatpoint";
5. char ch=name.charAt(4);//returns the char value at the 4th index
6. System.out.println(ch);
7. }}

Methods for comparison of strings

We can compare String in Java on the basis of content and reference.

It is used in authentication (by equals() method), sorting (by compareTo()


method), reference matching (by == operator) etc.

There are three ways to compare String in Java:

1. By Using equals() Method


2. By Using == Operator
3. By compareTo() Method

1) By Using equals() Method

The String class equals() method compares the original content of the string. It compares
values of string for equality. String class provides the following two methods:

o public boolean equals(Object another) compares this string to the specified object.
o public booleanequalsIgnoreCase(String another) compares this string to another
string, ignoring case.

Teststringcomparison1.java
1. class Teststringcomparison1{
2. public static void main(String args[]){
3. String s1="Sachin";
4. String s2="Sachin";
5. String s3=new String("Sachin");
6. String s4="Saurav";
7. System.out.println(s1.equals(s2));//true
8. System.out.println(s1.equals(s3));//true
9. System.out.println(s1.equals(s4));//false
10. }
11. }
Methods for searching strings
Java String indexOf()

The Java String class indexOf() method returns the position of the first occurrence of the
specified character or string in a specified string.

There are four overloaded indexOf() method in Java. The signature of indexOf() methods are
given below:

No. Method Description

1 int indexOf(int ch) It returns the index position for the given char value

2 int indexOf(int ch, int fromIndex) It returns the index position for the given char value
and from index

3 int indexOf(String substring) It returns the index position for the given substring

4 int indexOf(String substring, int It returns the index position for the given substring
fromIndex) and from index

Parameters

ch: It is a character value, e.g. 'a'

fromIndex: The index position from where the index of the char value or substring is
returned.

data conversion and miscellaneous methods


Data conversion in Java
 Converting Java int to String.
 Converting Java byte to String.
 Converting Java short to String.
 Converting Java long to String.
 Converting Java double to String.
 Converting Java float to String.
 Converting Java boolean to String.
Java StringBuffer Class

Java StringBuffer class is used to create mutable (modifiable) String objects. The
StringBuffer class in Java is the same as String class except it is mutable i.e. it can be
changed.

Important Constructors of StringBuffer Class

Constructor Description

StringBuffer() It creates an empty String buffer with the initial capacity of 16.

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

StringBuffer(int capacity) It creates an empty String buffer with the specified capacity as length.

Important methods of StringBuffer class

Modifier and Method Description


Type

public append(String s) It is used to append the specified string with this string.
synchronized The append() method is overloaded like append(char),
StringBuffer append(boolean), append(int), append(float),
append(double) etc.

public insert(int offset, String s) It is used to insert the specified string with this string at
synchronized the specified position. The insert() method is overloaded
StringBuffer like insert(int, char), insert(int, boolean), insert(int, int),
insert(int, float), insert(int, double) etc.

public replace(int startIndex, It is used to replace the string from specified startIndex
synchronized int endIndex, String str) and endIndex.
StringBuffer

public delete(int startIndex, int It is used to delete the string from specified startIndex
synchronized endIndex) and endIndex.
StringBuffer

public reverse() is used to reverse the string.


synchronized
StringBuffer

public int capacity() It is used to return the current capacity.

public void ensureCapacity(int It is used to ensure the capacity at least equal to the given
minimumCapacity) minimum.

public char charAt(int index) It is used to return the character at the specified position.

public int length() It is used to return the length of the string i.e. total
number of characters.

public String substring(int It is used to return the substring from the specified
beginIndex) beginIndex.

public String substring(int beginIndex, It is used to return the substring from the specified
int endIndex) beginIndex and endIndex

1) StringBuffer Class append() Method

The append() method concatenates the given argument with this String.

StringBufferExample.java

1. class StringBufferExample{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello ");
4. sb.append("Java");//now original string is changed
5. System.out.println(sb);//prints Hello Java
6. }
7. }

StringBuffer insert() Method

The insert() method inserts the given String with this string at the given position.

StringBufferExample2.java

1. class StringBufferExample2{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello ");
4. sb.insert(1,"Java");//now original string is changed
5. System.out.println(sb);//prints HJavaello
6. }
7. }

Output:

HJavaello

3) StringBuffer replace() Method

The replace() method replaces the given String from the specified beginIndex and endIndex.

StringBufferExample3.java

1. class StringBufferExample3{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello");
4. sb.replace(1,3,"Java");
5. System.out.println(sb);//prints HJavalo
6. }
7. }

StringBuffer delete() Method

The delete() method of the StringBuffer class deletes the String from the specified
beginIndex to endIndex.

StringBufferExample4.java

1. class StringBufferExample4{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello");
4. sb.delete(1,3);
5. System.out.println(sb);//prints Hlo
6. }
7. }

Class string builder


Java StringBuilder Class

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. It is available since
JDK 1.5.

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

StringBuilder(int It creates an empty String Builder with the specified capacity as


length) length.

Important methods of StringBuilder class


Method Description

public StringBuilder It is used to append the specified string with this string. The
append(String s) append() method is overloaded like append(char),
append(boolean), append(int), append(float), append(double) etc.

public StringBuilder insert(int It is used to insert the specified string with this string at the
offset, String s) specified position. The insert() method is overloaded like
insert(int, char), insert(int, boolean), insert(int, int), insert(int,
float), insert(int, double) etc.

public StringBuilder replace(int It is used to replace the string from specified startIndex and
startIndex, int endIndex, String endIndex.
str)

public StringBuilder delete(int It is used to delete the string from specified startIndex and
startIndex, int endIndex) endIndex.

public StringBuilder reverse() It is used to reverse the string.

public int capacity() It is used to return the current capacity.

public void ensureCapacity(int It is used to ensure the capacity at least equal to the given
minimumCapacity) minimum.

public char charAt(int index) It is used to return the character at the specified position.

public int length() It is used to return the length of the string i.e. total number of
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.

Java StringBuilder Examples

Let's see the examples of different methods of StringBuilder class.

1) StringBuilder append() method

The StringBuilder append() method concatenates the given argument with this String.

StringBuilderExample.java

1. class StringBuilderExample{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder("Hello ");
4. sb.append("Java");//now original string is changed
5. System.out.println(sb);//prints Hello Java
6. }
7. }

Multithreaded Programming

Multithreading is a Java feature that allows concurrent execution of two or more parts of a
program for maximum utilization of CPU. Each part of such program is called a thread. So,
threads are light-weight processes within a process.
Threads can be created by using two mechanisms :
1. Extending the Thread class
2. Implementing the Runnable Interface
Thread creation by extending the Thread class
We create a class that extends the java.lang.Thread class. This class overrides the run()
method available in the Thread class. A thread begins its life inside run() method. We
create an object of our new class and call start() method to start the execution of a thread.
Start() invokes the run() method on the Thread object.

// Java code for thread creation by extending


// the Thread class
classMultithreadingDemoextendsThread {
publicvoidrun()
{
try{
// Displaying the thread that is running
System.out.println(
"Thread "+ Thread.currentThread().getId()
+ " is running");
}
catch(Exception e) {
// Throwing an exception
System.out.println("Exception is caught");
}
}
}

// Main Class
publicclassMultithread {
publicstaticvoidmain(String[] args)
{
intn = 8; // Number of threads
for(inti = 0; i< n; i++) {
MultithreadingDemo object
= newMultithreadingDemo();
object.start();
}
}
}

Thread creation by implementing the Runnable Interface


We create a new class which implements java.lang.Runnable interface and override run()
method. Then we instantiate a Thread object and call start() method on this object.

// Java code for thread creation by implementing


// the Runnable Interface
classMultithreadingDemoimplementsRunnable {
publicvoidrun()
{
try{
// Displaying the thread that is running
System.out.println(
"Thread "+ Thread.currentThread().getId()
+ " is running");
}
catch(Exception e) {
// Throwing an exception
System.out.println("Exception is caught");
}
}
}

// Main Class
classMultithread {
publicstaticvoidmain(String[] args)
{
intn = 8; // Number of threads
for(inti = 0; i< n; i++) {
Thread object
= newThread(newMultithreadingDemo());
object.start();
}
}
}

Thread States in Java

A thread is a program in execution created to perform a specific task. Life cycle of a Java
thread starts with its birth and ends on its death.

The start() method of the Thread class is used to initiate the execution of a thread and it goes
into runnable state and the sleep() and wait() methods of the Thread class sends the thread
into non runnable state.

After non runnable state, thread again comes into runnable state and starts its execution. The
run() method of thread is very much important. After executing the run() method, the
lifecycle of thread is completed.

All these phases of threads are the states of thread in Java.


Thread States in Java

A thread is a path of execution in a program that goes through the following states of a
thread. The five states are as follows:

1. New
2. Runnable
3. Running
4. Blocked (Non-runnable state)
5. Dead

New (Newborn State)

When an instance of the Thread class is created a new thread is born and is known to be in
New-born state. That is, when a thread is born, it enters into new state but its execution phase
has not been started yet on the instance.

In simpler terms, Thread object is created but it cannot execute any program statement
because it is not in an execution state of the thread. Only start() method can be called on a
new thread; otherwise, an IllegalThreadStateException will be thrown.

Runnable State

The second phase of a new-born thread is the execution phase. When the start() method is
called on a the new instance of a thread, it enters into a runnable state.
In the runnable state, thread is ready for execution and is waiting for availability of the
processor (CPU time). There are many threads that are ready for execution, they all are
waiting in a queue (line).

If all threads have equal priority, a time slot is assigned for each thread execution on the basis
of first-come, first-serve manner by CPU. The process of allocating time to threads is known
as time slicing. A thread can come into runnable state from running, waiting, or new states.

Running State
Running means Processor (CPU) has allocated time slot to thread for its execution. When
thread scheduler selects a thread from the runnable state for execution, it goes into running
state. Look at the above figure.

In running state, processor gives its time to the thread for execution and executes its run
method. It is the state where thread performs its actual functions. A thread can come into
running state only from runnable state.

A running thread may give up its control in any one of the following situations and can enter
into the blocked state.

1. When sleep() method is invoked on a thread to sleep for specified time period, the
thread is out of queue during this time period. The thread again reenters into the
runnable state as soon as this time period is elapsed.
2. When a thread is suspended using suspend() method for some time in order to satisfy
some conditions. A suspended thread can be revived by using resume() method.
3. When wait() method is called on a thread to wait for some time. The thread in wait
state can be run again using notify() or notifyAll() method.

Blocked State

A thread is considered to be in the blocked state when it is suspended, sleeping, or waiting for
some time in order to satisfy some condition.

Dead State

A thread dies or moves into dead state automatically when its run() method completes the
execution of statements. That is, a thread is terminated or dead when a thread comes out of
run() method. A thread can also be dead when the stop() method is called.

During the life cycle of thread in Java, a thread moves from one state to another state in a
variety of ways. This is because in multithreading environment, when multiple threads are
executing, only one thread can use CPU at a time.

All other threads live in some other states, either waiting for their turn on CPU or waiting for
satisfying some conditions. Therefore, a thread is always in any of the five states.

Priority of a Thread (Thread Priority)

Each thread has a priority. Priorities are represented by a number between 1 and 10. In most
cases, the thread scheduler schedules the threads according to their priority (known as
preemptive scheduling). But it is not guaranteed because it depends on JVM specification that
which scheduling it chooses. Note that not only JVM a Java programmer can also assign the
priorities of a thread explicitly in a Java program.

Setter & Getter Method of Thread Priority


Let's discuss the setter and getter method of the thread priority.

public final int getPriority(): The java.lang.Thread.getPriority() method returns the priority
of the given thread.

public final void setPriority(int newPriority): The java.lang.Thread.setPriority() method


updates or assign the priority of the thread to newPriority. The method throws
IllegalArgumentException if the value newPriority goes out of the range, which is 1
(minimum) to 10 (maximum).

3 constants defined in Thread class:


1. public static int MIN_PRIORITY
2. public static int NORM_PRIORITY
3. public static int MAX_PRIORITY

Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1


and the value of MAX_PRIORITY is 10.

Example of priority of a Thread:

FileName: ThreadPriorityExample.java

1. // Importing the required classes


2. import java.lang.*;
public class ThreadPriorityExample extends Thread
3. {

4. // Method 1
5. // Whenever the start() method is called by a thread
6. // the run() method is invoked
7. public void run()
8. {
9. // the print statement
10. System.out.println("Inside the run() method");
11. }
12.
13. // the main method
14. public static void main(String argvs[])
15. {
16. // Creating threads with the help of ThreadPriorityExample class
17. ThreadPriorityExample th1 = new ThreadPriorityExample();
18. ThreadPriorityExample th2 = new ThreadPriorityExample();
19. ThreadPriorityExample th3 = new ThreadPriorityExample();
20.
21. // We did not mention the priority of the thread.
22. // Therefore, the priorities of the thread is 5, the default value
23.
24. // 1st Thread
25. // Displaying the priority of the thread
26. // using the getPriority() method
27. System.out.println("Priority of the thread th1 is : " + th1.getPriority());
28.
29. // 2nd Thread
30. // Display the priority of the thread
31. System.out.println("Priority of the thread th2 is : " + th2.getPriority());
32.
33. // 3rd Thread
34. // // Display the priority of the thread
35. System.out.println("Priority of the thread th2 is : " + th2.getPriority());
36.
37. // Setting priorities of above threads by
38. // passing integer arguments
39. th1.setPriority(6);
40. th2.setPriority(3);
41. th3.setPriority(9);
42.
43. // 6
44. System.out.println("Priority of the thread th1 is : " + th1.getPriority());
45.
46. // 3
47. System.out.println("Priority of the thread th2 is : " + th2.getPriority());
48.
49. // 9
50. System.out.println("Priority of the thread th3 is : " + th3.getPriority());
51.
52. // Main thread
53.
54. // Displaying name of the currently executing thread
55. System.out.println("Currently Executing The Thread : " + Thread.currentThread().get
Name());
56.
57. System.out.println("Priority of the main thread is : " + Thread.currentThread().getPrio
rity());
58.
59. // Priority of the main thread is 10 now
60. Thread.currentThread().setPriority(10);
61.
62. System.out.println("Priority of the main thread is : " + Thread.currentThread().getPrio
rity());
63. }
64. }
Deadlock in Java

Deadlock in Java is a part of multithreading. Deadlock can occur in a situation when a thread
is waiting for an object lock, that is acquired by another thread and second thread is waiting
for an object lock that is acquired by first thread. Since, both threads are waiting for each
other to release the lock, the condition is called deadlock.

Example of Deadlock in Java

TestDeadlockExample1.java

1. public class TestDeadlockExample1 {


2. public static void main(String[] args) {
3. final String resource1 = "ratan jaiswal";
4. final String resource2 = "vimal jaiswal";
5. // t1 tries to lock resource1 then resource2
6. Thread t1 = new Thread() {
7. public void run() {
8. synchronized (resource1) {
9. System.out.println("Thread 1: locked resource 1");
10.
11. try { Thread.sleep(100);} catch (Exception e) {}
12.
13. synchronized (resource2) {
14. System.out.println("Thread 1: locked resource 2");
15. }
16. }
17. }
18. };
19.
20. // t2 tries to lock resource2 then resource1
21. Thread t2 = new Thread() {
22. public void run() {
23. synchronized (resource2) {
24. System.out.println("Thread 2: locked resource 2");
25.
26. try { Thread.sleep(100);} catch (Exception e) {}
27.
28. synchronized (resource1) {
29. System.out.println("Thread 2: locked resource 1");
30. }
31. }
32. }
33. };
34.
35.
36. t1.start();
37. t2.start();
38. }
39. }
Inter-thread Communication in Java

Inter-thread communication or Co-operation is all about allowing synchronized threads to


communicate with each other.

Cooperation (Inter-thread communication) is a mechanism in which a thread is paused


running in its critical section and another thread is allowed to enter (or lock) in the same
critical section to be executed.It is implemented by following methods of Object class:

o wait()
o notify()
o notifyAll()

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

The current thread must own this object's monitor, so it must be called from the synchronized
method only otherwise it will throw exception.

Method Description

public final void wait()throws InterruptedException It waits until object is notified.

public final void wait(long timeout)throws It waits for the specified amount of
InterruptedException time.

2) 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. The choice is
arbitrary and occurs at the discretion of the implementation.

Syntax:

1. public final void notify()

3) notifyAll() method

Wakes up all threads that are waiting on this object's monitor.

Syntax:

1. public final void notifyAll()


2. Difference between wait and sleep?
3. Let's see the important differences between wait and sleep methods.

wait() sleep()

The wait() method releases the lock. The sleep() method doesn't release the lock.

It is a method of Object class It is a method of Thread class

It is the non-static method It is the static method


It should be notified by notify() or notifyAll() After the specified amount of time, sleep is
methods completed.

Example of Inter Thread Communication in Java

Let's see the simple example of inter thread communication.

Test.java

1. class Customer{
2. int amount=10000;
3.
4. synchronized void withdraw(int amount){
5. System.out.println("going to withdraw...");
6.
7. if(this.amount<amount){
8. System.out.println("Less balance; waiting for deposit...");
9. try{wait();}catch(Exception e){}
10. }
11. this.amount-=amount;
12. System.out.println("withdraw completed...");
13. }
14.
15. synchronized void deposit(int amount){
16. System.out.println("going to deposit...");
17. this.amount+=amount;
18. System.out.println("deposit completed... ");
19. notify();
20. }
21. }
22.
23. class Test{
24. public static void main(String args[]){
25. final Customer c=new Customer();
26. new Thread(){
27. public void run(){c.withdraw(15000);}
28. }.start();
29. new Thread(){
30. public void run(){c.deposit(10000);}
31. }.start();
32.
33. }}
Java 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
1. public final void suspend()
Return

This method does not return any value.

Exception

SecurityException: If the current thread cannot modify the thread.

Example
1. public class JavaSuspendExp extends Thread
2. {
3. public void run()
4. {
5. for(int i=1; i<5; i++)
6. {
7. try
8. {
9. // thread to sleep for 500 milliseconds
10. sleep(500);
11. System.out.println(Thread.currentThread().getName());
12. }catch(InterruptedException e){System.out.println(e);}
13. System.out.println(i);
14. }
15. }
16. public static void main(String args[])
17. {
18. // creating three threads
19. JavaSuspendExp t1=new JavaSuspendExp ();
20. JavaSuspendExp t2=new JavaSuspendExp ();
21. JavaSuspendExp t3=new JavaSuspendExp ();
22. // call run() method
23. t1.start();
24. t2.start();
25. // suspend t2 thread
26. t2.suspend();
27. // call run() method
28. t3.start();
29. }
30. }
Java 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
1. public final void resume()
Return value

This method does not return any value.

Exception

SecurityException: If the current thread cannot modify the thread.

Example
1. public class JavaResumeExp extends Thread
2. {
3. public void run()
4. {
5. for(int i=1; i<5; i++)
6. {
7. try
8. {
9. // thread to sleep for 500 milliseconds
10. sleep(500);
11. System.out.println(Thread.currentThread().getName());
12. }catch(InterruptedException e){System.out.println(e);}
13. System.out.println(i);
14. }
15. }
16. public static void main(String args[])
17. {
18. // creating three threads
19. JavaResumeExp t1=new JavaResumeExp ();
20. JavaResumeExp t2=new JavaResumeExp ();
21. JavaResumeExp t3=new JavaResumeExp ();
22. // call run() method
23. t1.start();
24. t2.start();
25. t2.suspend(); // suspend t2 thread
26. // call run() method
27. t3.start();
28. t2.resume(); // resume t2 thread
29. }
30. }
Java 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
1. public final void stop()
2. public final void stop(Throwable obj)
Parameter

obj : The Throwable object to be thrown.

Return

This method does not return any value.

Exception

SecurityException: This exception throws if the current thread cannot modify the thread.

Example
1. public class JavaStopExp extends Thread
2. {
3. public void run()
4. {
5. for(int i=1; i<5; i++)
6. {
7. try
8. {
9. // thread to sleep for 500 milliseconds
10. sleep(500);
11. System.out.println(Thread.currentThread().getName());
12. }catch(InterruptedException e){System.out.println(e);}
13. System.out.println(i);
14. }
15. }
16. public static void main(String args[])
17. {
18. // creating three threads
19. JavaStopExp t1=new JavaStopExp ();
20. JavaStopExp t2=new JavaStopExp ();
21. JavaStopExp t3=new JavaStopExp ();
22. // call run() method
23. t1.start();
24. t2.start();
25. // stop t3 thread
26. t3.stop();
27. System.out.println("Thread t3 is stopped");
28. }
29. }

Java Database Connectivity

Definition of JDBC(Java Database Connectivity)

JDBC is an API(Application programming interface) used in java programming to interact


with databases. The classes and interfaces of JDBC allow the application to
send requests made by users to the specified database.
Purpose of JDBC
Enterprise applications created using the JAVA EE technology need to interact with
databases to store application-specific information. So, interacting with a database requires
efficient database connectivity, which can be achieved by using the ODBC(Open database
connectivity) driver. This driver is used with JDBC to interact or communicate with various
kinds of databases such as Oracle, MS Access, Mysql, and SQL server database.
Components of JDBC
There are generally four main components of JDBC through which it can interact with a
database. They are as mentioned below:
1. JDBC API: It provides various methods and interfaces for easy communication with the
database. It provides two packages as follows, which contain the java SE and Java EE
platforms to exhibit WORA(write once run anywhere) capabilities.
java.sql.*;
It also provides a standard to connect a database to a client application.
2. JDBC Driver manager: It loads a database-specific driver in an application to establish
a connection with a database. It is used to make a database-specific call to the database to
process the user request.
3. JDBC Test suite: It is used to test the operation(such as insertion, deletion, updation)
being performed by JDBC Drivers.
4. JDBC-ODBC Bridge Drivers: It connects database drivers to the database. This bridge
translates the JDBC method call to the ODBC function call. It makes use of
the sun.jdbc.odbc package which includes a native library to access ODBC characteristics.

Architecture of JDBC

Architecture of JDBC

Description:
1. Application: It is a java applet or a servlet that communicates with a data
source.
2. The JDBC API: The JDBC API allows Java programs to execute SQL
statements and retrieve results. Some of the important classes and interfaces
defined in JDBC API are as follows:
3. DriverManager: It plays an important role in the JDBC architecture. It uses
some database-specific drivers to effectively connect enterprise applications to
databases.
4. JDBC drivers: To communicate with a data source through JDBC, you need a
JDBC driver that intelligently communicates with the respective data source.
JDBC Drivers
JDBC drivers are client-side adapters (installed on the client machine, not on the server)
that convert requests from Java programs to a protocol that the DBMS can understand.
There are 4 types of JDBC drivers:
1. Type-1 driver or JDBC-ODBC bridge driver
2. Type-2 driver or Native-API driver
3. Type-3 driver or Network Protocol driver
4. Type-4 driver or Thin driver

JDBC Drivers
JDBC drivers are client-side adapters (installed on the client machine, not on the server)
that convert requests from Java programs to a protocol that the DBMS can
understand. JDBC drivers are the software components which implements interfaces in
JDBC APIs to enable java application to interact with the database. Now we will learn how
many JDBC driver types does Sun defines? There are four types of JDBC drivers defined
by Sun Microsystem that are mentioned below:
1. Type-1 driver or JDBC-ODBC bridge driver
2. Type-2 driver or Native-API driver
3. Type-3 driver or Network Protocol driver
4. Type-4 driver or Thin driver
1. JDBC-ODBC bridge driver – Type 1 driver
Type-1 driver or JDBC-ODBC bridge driver uses ODBC driver to connect to the database.
The JDBC-ODBC bridge driver converts JDBC method calls into the ODBC function
calls. Type-1 driver is also called Universal driver because it can be used to connect to any
of the databases.
Advantages
 This driver software is built-in with JDK so no need to install separately.
 It is a database independent driver.
Disadvantages
 As a common driver is used in order to interact with different databases, the data
transferred through this driver is not so secured.
 The ODBC bridge driver is needed to be installed in individual client machines.
 Type-1 driver isn’t written in java, that’s why it isn’t a portable driver.
2. Native-API driver – Type 2 driver ( Partially Java driver)
The Native API driver uses the client -side libraries of the database. This driver converts
JDBC method calls into native calls of the database API. In order to interact with different
database, this driver needs their local API, that’s why data transfer is much more secure as
compared to type-1 driver. This driver is not fully written in Java that is why it is also
called Partially Java driver.

Advantage
 Native-API driver gives better performance than JDBC-ODBC bridge driver.
Disadvantages
 Driver needs to be installed separately in individual client machines
 The Vendor client library needs to be installed on client machine.
 Type-2 driver isn’t written in java, that’s why it isn’t a portable driver
 It is a database dependent driver.
3. Network Protocol driver – Type 3 driver (fully Java driver)
The Network Protocol driver uses middleware (application server) that converts JDBC
calls directly or indirectly into the vendor-specific database protocol. Here all the database
connectivity drivers are present in a single server, hence no need of individual client-side
installation.

Advantages
 Type-3 drivers are fully written in Java, hence they are portable drivers.
 No client side library is required because of application server that can perform many
tasks like auditing, load balancing, logging etc.
 Switch facility to switch over from one database to another database.
Disadvantages
 Network support is required on client machine.
 Maintenance of Network Protocol driver becomes costly because it requires database-
specific coding to be done in the middle tier.
4. Thin driver – Type 4 driver (fully Java driver)
Type-4 driver is also called native protocol driver. This driver interact directly with
database. It does not require any native database library, that is why it is also known as
Thin Driver.
Advantages
 Does not require any native library and Middleware server, so no client-side or server-
side installation.
 It is fully written in Java language, hence they are portable drivers.
Disadvantage
 If the database varies, then the driver will carry because it is database dependent.

Tpes of JDBC Architecture(2-tier and 3-tier)

The JDBC architecture consists of two-tier and three-tier processing models to access
a database. They are as described below:

1. Two-tier model: A java application communicates directly to the data source.


The JDBC driver enables the communication between the application and the
data source. When a user sends a query to the data source, the answers for those
queries are sent back to the user in the form of results.
The data source can be located on a different machine on a network to which a
user is connected. This is known as a client/server configuration, where the
user’s machine acts as a client, and the machine has the data source running acts
as the server.

2. Three-tier model: In this, the user’s queries are sent to middle-tier services,
from which the commands are again sent to the data source. The results are sent
back to the middle tier, and from there to the user.
This type of model is found very useful by management information system
directors.
Interfaces of JDBC API
A list of popular interfaces of JDBC API is given below:
 Driver interface
 Connection interface
 Statement interface
 PreparedStatement interface
 CallableStatement interface
 ResultSet interface
 ResultSetMetaData interface
 DatabaseMetaData interface
 RowSet interface

PreparedStatement interface
The PreparedStatement interface is a subinterface of Statement. It is used to execute
parameterized query.

Let's see the example of parameterized query:

1. String sql="insert into emp values(?,?,?)";


As you can see, we are passing parameter (?) for the values. Its value will be set by calling
the setter methods of PreparedStatement.

1. import java.sql.*;
2. class InsertPrepared{
3. public static void main(String args[]){
4. try{
5. Class.forName("oracle.jdbc.driver.OracleDriver");
6.
7. Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","syste
m","oracle");
8.
9. PreparedStatement stmt=con.prepareStatement("insert into Emp values(?,?)");
10. stmt.setInt(1,101);//1 specifies the first parameter in the query
11. stmt.setString(2,"Ratan");
12.
13. int i=stmt.executeUpdate();
14. System.out.println(i+" records inserted");
15.
16. con.close();
17.
18. }catch(Exception e){ System.out.println(e);}
19.
20. }
21. }

ResultSet interface

The object of ResultSet maintains a cursor pointing to a row of a table. Initially, cursor points
to before the first row

But we can make this object to move forward and backward direction by passing either
TYPE_SCROLL_INSENSITIVE or TYPE_SCROLL_SENSITIVE in
createStatement(int,int) method as well as we can make this object as updatable by:
1. Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
2. ResultSet.CONCUR_UPDATABLE);

Commonly used methods of ResultSet interface

is used to move the cursor to the one row next from


1) public boolean next():
the current position.

is used to move the cursor to the one row previous


2) public boolean previous():
from the current position.

is used to move the cursor to the first row in result


3) public boolean first():
set object.

1. import java.sql.*;
2. class FetchRecord{
3. public static void main(String args[])throws Exception{
4.
5. Class.forName("oracle.jdbc.driver.OracleDriver");
6. Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","syste
m","oracle");
7. Statement stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CO
NCUR_UPDATABLE);
8. ResultSet rs=stmt.executeQuery("select * from emp765");
9.
10. //getting the record of 3rd row
11. rs.absolute(3);
12. System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3));
13.
14. con.close();
15. }}

Classes of JDBC API


A list of popular classes of JDBC API is given below:
 DriverManager class
 Blob class
 Clob class
 Types class
Working of JDBC
Java application that needs to communicate with the database has to be programmed using
JDBC API. JDBC Driver supporting data sources such as Oracle and SQL server has to be
added in java application for JDBC support which can be done dynamically at run time.
This JDBC driver intelligently communicates the respective data source.
Creating a simple JDBC application
Java

packagecom.vinayak.jdbc;

importjava.sql.*;

publicclassJDBCDemo {

publicstaticvoidmain(String args[])
throwsSQLException, ClassNotFoundException
{
String driverClassName
= "sun.jdbc.odbc.JdbcOdbcDriver";
String url = "jdbc:odbc:XE";
String username = "scott";
String password = "tiger";
String query
= "insert into students values(109, 'bhatt')";

// Load driver class


Class.forName(driverClassName);

// Obtain a connection
Connection con = DriverManager.getConnection(
url, username, password);

// Obtain a statement
Statement st = con.createStatement();

// Execute the query


intcount = st.executeUpdate(query);
System.out.println(
"number of rows affected by this query= "
+ count);

// Closing the connection as per the


// requirement with connection is completed
con.close();
}
} // class

The above example demonstrates the basic steps to access a database using JDBC. The
application uses the JDBC-ODBC bridge driver to connect to the database. You must
import java.sql package to provide basic SQL functionality and use the classes of the
package.
steps For Connectivity Between Java Program and Database
1. Import the Packages
2. Load the drivers using the forName() method
3. Register the drivers using DriverManager
4. Establish a connection using the Connection class object
5. Create a statement
6. Execute the query
7. Close the connections
Let us discuss these steps in brief before implementing by writing suitable code to illustrate
connectivity steps for JDBC/
Step 1: Import the Packages
Step 2: Loading the drivers
In order to begin with, you first need to load the driver or register it before using it in the
program. Registration is to be done once in your program. You can register a driver in one
of two ways mentioned below as follows:
2-A Class.forName()
Here we load the driver’s class file into memory at the runtime. No need of using new or
create objects. The following example uses Class.forName() to load the Oracle driver as
shown below as follows:
Class.forName(“oracle.jdbc.driver.OracleDriver”);
2-B DriverManager.registerDriver()
DriverManager is a Java inbuilt class with a static member register. Here we call the
constructor of the driver class at compile time. The following example uses
DriverManager.registerDriver()to register the Oracle driver as shown below:
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver())
Step 3: Establish a connection using the Connection class object
After loading the driver, establish connections as shown below as follows:
Connection con = DriverManager.getConnection(url,user,password)
 user: Username from which your SQL command prompt can be accessed.
 password: password from which the SQL command prompt can be accessed.
 con: It is a reference to the Connection interface.
 Url: Uniform Resource Locator which is created as shown below:
String url = “ jdbc:oracle:thin:@localhost:1521:xe”
Where oracle is the database used, thin is the driver used, @localhost is the IP Address
where a database is stored, 1521 is the port number and xe is the service provider. All 3
parameters above are of String type and are to be declared by the programmer before
calling the function. Use of this can be referred to form the final code.
Step 4: Create a statement
Once a connection is established you can interact with the database. The JDBCStatement,
CallableStatement, and PreparedStatement interfaces define the methods that enable you to
send SQL commands and receive data from your database.
Use of JDBC Statement is as follows:
Statement st = con.createStatement();
Note: Here, con is a reference to Connection interface used in previous step .
Step 5: Execute the query
Now comes the most important part i.e executing the query. The query here is an SQL
Query. Now we know we can have multiple types of queries. Some of them are as follows:
 The query for updating/inserting a table in a database.
 The query for retrieving data.
The executeQuery() method of the Statement interface is used to execute queries of
retrieving values from the database. This method returns the object of ResultSet that can be
used to get all the records of a table.
The executeUpdate(sql query) method of the Statement interface is used to execute queries
of updating/inserting.
Pseudo Code:
int m = st.executeUpdate(sql);
if (m==1)
System.out.println("inserted successfully : "+sql);
else
System.out.println("insertion failed");
Here sql is SQL query of the type String
Java

// This code is for establishing connection with MySQL


// database and retrieving data
// from db Java Database connectivity
/*
*1. import --->java.sql
*2. load and register the driver --->com.jdbc.
*3. create connection
*4. create a statement
*5. execute the query
*6. process the results
*7. close
*/

importjava.io.*;
importjava.sql.*;

classGFG {
publicstaticvoidmain(String[] args) throwsException
{
String url
= "jdbc:mysql://localhost:3306/table_name"; // table details
String username = "rootgfg"; // MySQL credentials
String password = "gfg123";
String query
= "select *from students"; // query to be run
Class.forName(
"com.mysql.cj.jdbc.Driver"); // Driver name
Connection con = DriverManager.getConnection(
url, username, password);
System.out.println(
"Connection Established successfully");
Statement st = con.createStatement();
ResultSetrs
= st.executeQuery(query); // Execute query
rs.next();
String name
= rs.getString("name"); // Retrieve name from db

System.out.println(name); // Print result on console


st.close(); // close statement
con.close(); // close connection
System.out.println("Connection Closed....");
}
}

You might also like