[go: up one dir, main page]

0% found this document useful (0 votes)
47 views42 pages

Ooptj r23 Unit 5

Uploaded by

rahulswarna027
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)
47 views42 pages

Ooptj r23 Unit 5

Uploaded by

rahulswarna027
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/ 42

1

ST. ANN’S COLLEGE OF ENGINEERING &TECHNOLOGY :: CHIRALA


DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
OBJECT ORIENTED THROUGH JAVA (UNIT-5)
SYLLABUS
String Handling in Java: Introduction, Interface CharSequence, Class String, Methods for
Extracting Characters from Strings, Comparison, Modifying, Searching; Class String Buffer.
Multithreaded Programming: Introduction, Need for MultipleThreads, Multithreaded
Programming for Multi-core Processor,Thread Class, MainThread, 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,
Result Set Interface
Java FX GUI: Java FX Scene Builder, Java FX App Window Structure, displaying text and
image, event handling, laying out nodes in scene graph, mouse events (Text Book 3)
---------------------------------------------------------------------------------------------------------------
1. String Handling in Java –Introduction
Strings are most commonly used objects in java language. Java implements strings as
objects of type String. A String is a sequence of characters enclosed within double quotes such as
“abcd” or “Hello”. Strings are treated differently in Java compared to C language; In the latter
case, it represents an array of characters terminated by null character. 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 can create strings and process them with nearly similar methods. All
the three classes are part of java.lang package
i. class String
ii. class StringBuffer
iii. class StringBuilder
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 in any one of the following three ways:
String str=“abcd”;
char s1[]={‘a’,’b’,’c’,’d’};
String s1=new String(“abcd”);
In the case of StringBuffer, an object is created using the new operator as follow:
StringBuffer strbuf=new StringBuffer(“abcd”);
In the case of StringBuilder, an object is created using the new operator as follow:
StringBuilder strbuil=new StringBuilder(“abcd”);

Storage of Strings :
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 memory allocated to a
Java program is divided into two segments:
i. Stack
ii. Heap
2

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”);
The strings that are defined with String strx=“abcd”; are stored in “String Constant Pool”, where
as the strings created String strz=new String(“abcd”); are stored in heap portion as shown in the
following figure 1.

The String Constant Pool stores only the unique strings. If you define another string as:
String stry=“abcd”;
Then no duplicate String object is created, but a reference is assigned to stry, since the “abcd” is
already existing in the pool. This is not the case with outside the pool. If we create string with
new operator with same value that is already existing then memory is allocated to this new object
being created.

Example, Illustration of storage of strings


class StringTest {
public static void main(String arg[])
{
String strx="abcd";
String stry="abcd";
String strz=new String("abcd");
String str1=new String("abcd");
String s2=new String();
String s1="";
System.out.println("Are references of strx and stry same?"+(strx==stry));
System.out.println("Are references of stry and strz same?"+(stry==strz));
System.out.println("Are references of strz and str1 same?"+(strz==str1));
System.out.println("Are references of s1 and s2 same?"+(s1==s2));
}
}
3

Output:
D:\CSE>javac StringTest.java
D:\CSE>java StringTest
Are references of strx and stry same?true
Are references of stry and strz same?false
Are references of strz and str1 same?false
Are references of s1 and s2 same?false

Immutability & Mutable Strings:


The string objects created by class String are immutable(unchangeable). 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. New
String objects can always be created and assigned to older String object references.
Example, String s1=“hello”;
String s2=s1;
Thus, when you change the content of a string by defining a new string, the old and new remain
in the memory. The immutable objects are thread safe and so they are the String objects.
The objects created by class StringBuffer are mutable(changeable). 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. 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. Therefore, if multithreads are not being used, then StringBuilder class
should be used to avoid memory loss.

Properties of String, StringBuffer, and StringBuilder objects

2. Interface CharSequence
CharSequence is an interface in java.lang package. It is implemented by several classes
including the classes String, StringBuffer, and StringBuilder. It has the following four methods.

i). charAt(int index): The method returns character value at specified index value.
ii). int length(): This method returns the length of this (invoking) character sequence.
iii).CharSequence subSequence(int startIndex, endIndex): The method returns a subsequence
from start index to end index of this sequence. Throws IndexOutOfBoundsException.
4

iv). String toString(): The method returns a string containing characters of the sequence in the
same.

Example program for CharSequence Interface


class CharSeq
{
public static void main(String arg[])
{
CharSequence cs="Java Program";
System.out.println("The character at position 2 is:"+cs.charAt(2));
System.out.println("The length of the string is:"+cs.length());
System.out.println("Sub sequence of the string from index 3 to 7
is:"+cs.subSequence(3,7));
CharSequence cs2=new StringBuffer("One Step Ahead");
System.out.println("The length of cs2 is:"+cs2.length());
}
}
Output :
D:\CSE> javac CharSeq.java
D:\CSE>java CharSeq
The character at position 2 is:v
The length of the string is:12
Sub sequence of the string from index 3 to 7 is:a Pr
The length of cs2 is:14

3. String class
The String, StringBuffer, and StringBuilder classes are defined in java.lang package. Java
implements strings as objects of type String.
String represents fixed-length, immutable character sequences. The class String is used to
represent strings in Java.
It is declared as:
public final class String extends Object implements serializable, comparable<String>,
charSequence

The String Constructors:


The String class is final, it cannot be extended. The String class has several constructors as
follow:

String() - The String class supports several constructors. This constructor creates a string
without any characters. To create an empty String, call the default constructor. See the following
examples.
String str = new String();
String str1 = “”;

String (byte [] barray) - It constructs a new string by decoding the specified byte[] barray by
using a computer’s default character set. The following code
5

byte []barray = new byte[]{65, 66, 67, 68, 69};


String str2 = new String(barray);

String (byte [] barray, Charset specifiedset) -It constructs a new string by decoding the
specified byte array (bray) by using specified character set. Some of the Charsets supported by
Java are UTF8, UTF16, UTF32, and ASCII. These may be written in lower case such as utf8,
utf16, utf32, and ascii.

String(byte[] bray, int offset, int length, String charsetName) -The constructor constructs
String object by decoding the specified part of byte array using specified Charset.
For example, String str4 = new String(barray,1, 3, “ascii”);

String (byte[] barray, string charsetName) -The constructor constructs a string by decoding
the byte array using specified Charset. String str3 = new String(barray, “UTF8”);

Example program for String Constructors


class StrConstructor
{
public static void main(String arg[])
{
String str1=new String();
System.out.println("str1="+str1);
byte []barray={66,67,68,69};
String str2=new String(barray);
System.out.println("str2="+str2); Output:
byte []uray={'\u0041','\u0042','\u0043'}; D:\CSE>javac StrConstructor.java
String str3=new String(uray); D:\CSE>java StrConstructor
System.out.println("str3="+str3); str1=
String str4=new String(“ Java One Step Ahead"); str2=BCDE
System.out.println("str4="+str4); str3=ABC
} str4=Java One Step Ahead
}

3.1 Methods for Extracting Characters from Strings (or) Character Extraction
The String class provides a number of ways in which characters can be extracted from a
String object. Although the characters that comprise a string within a String object cannot be
indexed as if they were a character array, many of the String methods employ an index (or offset)
into the string for their operation. Like arrays, the string indexes begin at zero.

i) charAt( ) - To extract a single character from a String, you can refer directly to an individual
character via the charAt( ) method. It returns the character at the specified index location. It has
this general form: char charAt(int where) Here, where is the index of the character that you want
to obtain. The value of where must be nonnegative and specify a location within the string.
For example, char ch;
ch = "abc".charAt(1); assigns the value b to ch.
6

ii) getChars( )
If you need to extract more than one character at a time, you can use the getChars( ) method. The
general form is: void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart)
Here, sourceStart specifies the index of the beginning of the substring, and sourceEnd specifies
an index that is one past the end of the desired substring. The array that will receive the
characters is specified by target. The index within target at which the substring will be copied is
passed in targetStart.

iii) getBytes( )
There is an alternative to getChars( ) that stores the characters in an array of bytes. This
method is called getBytes( ), and it uses the default character-to-byte conversions provided by
the platform. Here is its simplest form: byte[ ] getBytes( )

iv) toCharArray( )
If you want to convert all the characters in a String object into a character array, the easiest way
is to call toCharArray( ). It returns an array of characters for the entire string.
It has this general form: char[ ] toCharArray( )
This function is provided as a convenience, since it is possible to use getChars( ) to achieve the
same result.

Example Program for Extracting Characters from Strings


class ExtractingChars
{
public static void main(String arg[])
{
String str1="Vijayawada";
String str2="Vizag";
String str3="We are going from Vijayawada to Vizag";
System.out.println("The Character at 3 is:"+str1.charAt(3)); Output:
int begin=14;
int end=20; D:\CSE>javac ExtractingChars.java
char []c=new char[end-begin]; D:\CSE>java ExtractingChars
str3.getChars(begin,end,c,0); The Character at 3 is:a
System.out.println(c);
rom Vi
}
}

3.2 Methods for Comparison of Strings (or) String Comparison


The String class includes a number of methods that compare strings or substrings within strings.

i) equals( )
To compare two strings for equality, use equals( ). It has this general form:
boolean equals(Object str) Here, str is the String object being compared with the invoking
String object. It returns true if the strings contain the same characters in the same order, and
false otherwise. The comparison is case-sensitive.
7

ii) equalsIgnoreCase( )
To perform a comparison that ignores case differences, call equalsIgnoreCase( ). When it
compares two strings, it considers A-Z to be the same as a-z. It has this general form: boolean
equalsIgnoreCase(String str) Here, str is the String object being compared with the invoking
String object. It, too, returns true if the strings contain the same characters in the same order, and
false otherwise.

iii) regionMatches( )
The regionMatches( ) method compares a specific region inside a string with another specific
region in another string. There is an overloaded form that allows you to ignore case in such
comparisons.
Here are the general forms for these two methods:
boolean regionMatches(int startIndex, String str2, int str2StartIndex, int numChars)
boolean regionMatches(boolean ignoreCase,int startIndex, String str2, int str2StartIndex,
int numChars)
For both versions, startIndex specifies the index at which the region begins within the
invoking String object. The String being compared is specified by str2. The index at which the
comparison will start within str2 is specified by str2StartIndex. The length of the substring being
compared is passed in numChars. In the second version, if ignoreCase is true, the case of the
characters is ignored. Otherwise, case is significant.

iv) startsWith( ) and endsWith( )


The startsWith( ) method determines whether a given String begins with a specified string.
Conversely, endsWith( ) determines whether the String in question ends with a specified string.
They have the following general forms: boolean startsWith(String str) boolean endsWith(String
str) Here, str is the String being tested. If the string matches, true is returned. Otherwise, false is
returned. For example, "Foobar".endsWith("bar") and "Foobar".startsWith("Foo") are both true.
v) equals( ) Versus = =
It is important to understand that the equals( ) method and the == operator perform two different
operations. The equals( ) method compares the characters inside a String object. The == operator
compares two object references to see whether they refer to the same instance.

vi) compareTo( )
For sorting applications, you need to know which is less than, equal to, or greater than the
next. A string is less than another if it comes before the other in dictionary order. A string is
greater than another if it comes after the other in dictionary order.
The method compareTo( ) serves this purpose. It is specified by the Comparable<T>
interface, which String implements. It has this general form: int compareTo(String str) Here, str
is the String being compared with the invoking String. The result of the comparison is returned
and is interpreted as shown here:
8

If you want to ignore case differences when comparing two strings, use compareToIgnoreCase( )
method, as shown here: int compareToIgnoreCase(String str) This method returns the same
results as compareTo( ), except that case differences are ignored.

Example , Demonstrate Methods for Comparison of Strings


class EqualsandcompareToDemo {
public static void main(String args[]) {
String s1 = "Hello";
String s2 = "Hello";
String s3 = "Good-bye";
String s4 = "HELLO";
System.out.println(s1 + " equals " + s2 + " -> " + s1.equals(s2));
System.out.println(s1 + " equals " + s3 + " -> " +s1.equals(s3));
System.out.println(s1 + " equals " + s4 + " -> " + s1.equals(s4));
//To perform a comparison that ignores case differences, call equalsIgnoreCase( ).
System.out.println(s1 + " equalsIgnoreCase " + s4 + " -> " + s1.equalsIgnoreCase(s4));
System.out.println(s1 + " compareTo " + s2 + " -> " + s1.compareTo(s2));
System.out.println(" Length of s2 : -> " + s2.length());
}
}

3.3 Methods for Modifying Strings (or) Modifying a Strings


String objects are immutable, whenever you want to modify a String, you must either
copy it into a StringBuffer or StringBuilder, or use a String method that constructs a new copy of
the string with your modifications complete.

i) substring( )
You can extract a substring using substring( ). It has two forms. The first is String
substring(int startIndex) Here, startIndex specifies the index at which the substring will begin.
This form returns a copy of the substring that begins at startIndex and runs to the end of the
invoking string. The second form of substring( ) allows you to specify both the beginning and
ending index of the substring: String substring(int startIndex, int endIndex) Here, startIndex
specifies the beginning index, and endIndex specifies the stopping point. The string returned
contains all the characters from the beginning index, up to, but not including, the ending index.

ii) concat( )
You can concatenate two strings using concat( ), shown here: String concat(String str)
This method creates a new object that contains the invoking string with the contents of str
appended to the end. concat( ) performs the same function as +.
For example, String s1 = "one"; String s2 = s1.concat("two"); puts the string "onetwo" into s2.

iii) replace( )
The replace( ) method has two forms. The first replaces all occurrences of one character
in the invoking string with another character. It has the following general form: String
replace(char original, char replacement) Here, original specifies the character to be replaced
by the character specified by replacement. The resulting string is returned.
9

For example, String s = "Hello".replace('l', 'w'); puts the string "Hewwo" into s.
The second form of replace( ) replaces one character sequence with another. It has this
general form: String replace(CharSequence original, CharSequence replacement)

iv) trim( )
The trim( ) method returns a copy of the invoking string from which any leading and trailing
whitespace has been removed. It has this general form: String trim( ) For example,
String s = " Hello World ".trim(); This puts the string "Hello World" into s.

Example program for illustration of Methods for Modifying Strings


class ModifyStrings
{
public static void main ( String args [ ] )
{
String str1 ="Belhi";
String mstr1 = str1.replace('B','D' );
System.out.println ("Modified string mstr1 = " + mstr1) ;
String str2 = " WELCOME ";
String mstr2 = str2.trim( );
System.out.println ("mstr2 = " + mstr2) ;
String str3 = " I am going to Delhi and from there to Mumbai."; Output:
String mstr3 = str3.substring( 0, 19);
System.out.println (" mstr3 = " + mstr3);
String mstr4 = str3.substring (19);
System.out.println ("mstr4 = " + mstr4);
String mstr5 =mstr2.concat(mstr1);
System.out.println("mstr5 = "+mstr5);
}
}

3.4 Methods for Searching Strings (or) Searching Strings


The String class provides two methods that allow you to search a string for a specified character
or substring.
 indexOf( ) Searches for the first occurrence of a character or substring.
 lastIndexOf( ) Searches for the last occurrence of a character or substring.
These two methods are overloaded in several different ways. In all cases, the methods return the
index at which the character or substring was found, or –1 on failure.
To search for the first occurrence of a character, use int indexOf(int ch)
To search for the last occurrence of a character, use int lastIndexOf(int ch) Here, ch is the
character being sought.
To search for the first or last occurrence of a substring, use
int indexOf(String str)
int lastIndexOf(String str) Here, str specifies the substring.
You can specify a starting point for the search using these forms:
int indexOf(int ch, int startIndex)
int lastIndexOf(int ch, int startIndex)
10

int indexOf(String str, int startIndex)


int lastIndexOf(String str, int startIndex) Here, startIndex specifies the index at which
point the search begins. For indexOf( ), the search runs from startIndex to the end of the string.
For lastIndexOf( ), the search runs from startIndex to zero.
The following example shows how to use the various index methods to search inside of a String:

Example program for illustration of Methods for Searching Strings


class indexOfDemo {
public static void main(String args[])
{
String s = "Now is the time for all good men " +"to come to the aid of their
country.";
System.out.println(s);
System.out.println("indexOf(t) = " +s.indexOf('t'));
System.out.println("lastIndexOf(t) = " + s.lastIndexOf('t'));
System.out.println("indexOf(the) = " +s.indexOf("the"));
System.out.println("lastIndexOf(the) = " +s.lastIndexOf("the"));
System.out.println("indexOf(t, 10) = " +s.indexOf('t', 10));
System.out.println("lastIndexOf(t, 60) = " +s.lastIndexOf('t', 60));
System.out.println("indexOf(the, 10) = " +s.indexOf("the", 10));
System.out.println("lastIndexOf(the, 60) = " + s.lastIndexOf("the", 60));
}
}
Output:
Now is the time for all good men to come to the aid of their country.
indexOf(t) = 7
lastIndexOf(t) = 65
indexOf(the) = 7
lastIndexOf(the) = 55
indexOf(t, 10) = 11
lastIndexOf(t, 60) = 55
indexOf(the, 10) = 44
lastIndexOf(the, 60) = 55

3.5 Data Conversion and Miscellaneous Methods


The valueOf( ) method converts data from its internal format into a human-readable form. It is a
static method that is overloaded within String for all of Java’s built-in types so that each type can
be converted properly into a string. valueOf( ) is also overloaded for type Object, so an object of
any class type you create can also be used as an argument. Here are a few of its forms:
static String valueOf(double num)
static String valueOf(long num)
static String valueOf(Object ob)
static String valueOf(char chars[ ])
There is a special version of valueOf( ) that allows you to specify a subset of a char array. It has
this general form: static String valueOf(char chars[ ], int startIndex, int numChars) Here,
11

chars is the array that holds the characters, startIndex is the index into the array of characters at
which the desired substring begins, and numChars specifies the length of the substring.

Example program for Data Conversion and Miscellaneous Methods


class DataConversionMethods
{
public static void main(String arg[]) Output:
{
String str1=new String("James Gosling");
System.out.println("The value of n is :"+str1.valueOf(4));
System.out.println("To string :"+str1.toString());
System.out.println("The Canonical form is:"+str1.intern());
System.out.println("The Hash code is:"+str1.hashCode());
}
}

3.6 Chsanging the Case of Characters within a String


The method toLowerCase( ) converts all the characters in a string from uppercase to lowercase.
The toUpperCase( ) method converts all the characters in a string from lowercase to uppercase.
Here are the simplest forms of these methods:
12

String toLowerCase( )
String toUpperCase( ) Both methods return a String object that contains the uppercase
or lowercase equivalent of the invoking String. The default locale governs the conversion in both
cases.
// Example, Demonstrate toUpperCase() and toLowerCase().
class ChangeCase
{
public static void main(String args[])
{
String s = "This is a test.";
System.out.println("Original: " + s);
String upper = s.toUpperCase();
String lower = s.toLowerCase();
System.out.println("Uppercase: " + upper);
System.out.println("Lowercase: " + lower);
}
}

The output produced by the program is shown here:


Original: This is a test.
Uppercase: THIS IS A TEST.
Lowercase: this is a test.

4. Class StringBuffer
StringBuffer supports a modifiable string. StringBuffer represents growable and writable
character sequences. StringBuffer may have characters and substrings inserted in the middle or
appended to the end. It defines the strings that can be modified as well as the number of
characters that may be changed, replaced by another, a string that may be appended, etc. The
strings are also thread safe. For the strings created by class StringBuffer, the compiler allocates
extra capacity for 16 more characters so that small modifications do not involve relocation of the
string. The class is declared as follows:
public final class StringBuffer extends Object implements Serializable, CharSequence

Constructors of Class Stringbuffer


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.

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

Methods of Class StringBuffer


Modifier and Type Method Description
13

public synchronized append(String s) is used to append the specified string with this string. The
StringBuffer append() method is overloaded like append(char),
append(boolean),append(int),append(float),append(double
) etc.
public synchronized insert(int offset, String s) is used to insert the specified string with this string at the
StringBuffer 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 synchronized replace(int startIndex, int is used to replace the string from specified startIndex and
StringBuffer endIndex, String str) endIndex.
publicsynchronized delete(int startIndex, int is used to delete the string from specified startIndex and
StringBuffer endIndex) endIndex.
public synchronized reverse() is used to reverse the string.
StringBuffer
public int capacity() is used to return the current capacity.

public void ensureCapacity(int is used to set the minimum size of the buffer.
minimumCapacity)
public char charAt(int index) is used to return the character at the specified position.
public int length() is used to return the length of the string i.e. total number
of characters.
public String substring(int beginIndex, is used to return the substring from the specified
int endIndex) beginIndex and endIndex.

Example program for Stringbuffer Clas


class StringBufferDemo
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello "); Output:
sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java
sb.insert(10," Programming");//inserting from a given position
System.out.println(sb);
sb.replace(0,5,"1 Step");
System.out.println(sb);//prints 1 step before string and modifies
sb.delete(0,1);
System.out.println(sb);
sb.reverse();
System.out.println(sb);
System.out.println("Current capacity is:"+sb.capacity());
}
}
14

5. Class StringBuilder
The StringBuilder class is the subclass of Object in java.lang package. StringBuilder is
similar to StringBuffer except for one important difference: it is not synchronized, which means
that it is not thread-safe. The advantage of StringBuilder is faster performance. This class is used
for creating and modifying strings.
Its declaration is as follows: public final class StringBuilder extends Object implements
Serializable, CharSequence
Constructors of Class StringBuilder:
The four constructors of the class are described as follows:
StringBuilder() -- Creates a StringBuilder object with no characters but with initial capacity of
16 characters.
StringBuilder(CharSequence chSeq) -- Creates a StringBuilder object with characters as
specified in CharSequence chSeq.
StringBuilder(int capacity) -- Creates a StringBuilder object with specified capacity. It throws
NegativeArraySizeException.
StringBuilder(String str) -- Creates a StringBuilder object initialized with contents of a
specified string. It throws NullPointException if str is null.

Method of StringBuilder Class


Method Description

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

public StringBuilder insert(int offset, is used to insert the specified string with this string at the
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 is used to replace the string from specified startIndex and
startIndex, int endIndex, String str) endIndex.
public StringBuilder delete(int is used to delete the string from specified startIndex and
startIndex, int endIndex) endIndex.

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


public int capacity() is used to return the current capacity.
public void ensureCapacity(int is used to set the size of the buffer.
minimumCapacity)
public char charAt(int index) is used to return the character at the specified position.
public int length() is used to return the length of the string i.e. total number of
characters.
15

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

Example program for StringBuilder class


class StringBuilderDemo
{
public static void main(String args[])
{
StringBuilder sb=new StringBuilder("Hello ");
sb.append("Java"); //now original string is changed
System.out.println(sb); //prints Hello Java
sb.insert(10," Programming"); //inserting from a given position
System.out.println(sb);
sb.replace(0,5,"1 Step");
System.out.println(sb); //prints 1 step before string and modifies
sb.delete(0,1);
System.out.println(sb);
sb.reverse();
System.out.println(sb);
System.out.println("Current capacity is:"+sb.capacity());
}
}

6. Multithreaded Programming –Introduction


Some program may be divide into segments that run concurrently. Each segment is
considered as an independent path of execution, which is called “Thread”. If computers have
multiple processors then these threads run concurrently on different processors. The threads are
useful even if the computer has single-core processor. The program in execution is called
process. The different processes take different times on processor.
The input reading task and output task are generally slow, and hence the CPU will be idle in that
time. The CPU can be usefully employed to run another thread at that idle time. In such cases,
CPU can be usefully employed by time sharing systems to reduce the idle time of CPU to
minimum.
7. Need of Multiple Threads
Numerous efforts have been put to increase the throughput of computers. For single-core
processors, the transistors are reduced to allow high performance. The present speed of 3.5GHz
is highest possible, because beyond this the cooling problems will come to picture. The increase
in the throughput is possible by dividing the program into segments that are data independent can
be run by number of processors simultaneously. This is the basis on which supercomputers are
built. In supercomputer, thousands of processors are used process data concurrently. A CPU may
have two, four, or more processors. The advancement in the hardware are forcing software to
utilize the processors optimally.
Each task involves 3 processes such as reading, processing and printing output. These three
processes can be executed in three ways:
16

1. Single-core Processor- The tasks are executed one after the other in the queue.
2. Time-sharing of CPU –Thread1 starts first, after few seconds, Thread2 starts, and
Thread1 sleeps, and after few milliseconds Thread3 starts, Thread2 goes to sleep.
Similarly Thread1 wakes up, and Thread3 sleeps. This way CPU time is shared.
3. Four-core CPU- Core 0, loads the program, and forwards the three independent threads to
other three cores –one to each. All the tasks are executed simultaneously.
8. Multi-process programming Vs Multithreaded Programming

Multi-process programming Multithreaded Programming


This deals with "BigPicture " This deals with Details
These are Heavyweight tasks These are Lightweight tasks/processes
Inter-process communication is expensive and Inter-Thread communication is inexpensive.
limited
Context switching from one process to another Context switching is low cost in terms of
is costly in terms of memory memory, because they run on the same
address space
This is not under the control of Java This is controlled by Java

9.Thread class
In java, threads are based on the class ‘Thread” that belongs to the java.lang package. It
has number of methods. One thread will be always running and is created by the system for
executing the main() method. That is called ‘main’ Thread. A thread will not work up on
creation, but it has to be called explicitly using the start() method. This start() method makes a
call to the run() method automatically which is the entry point for thread execution.
Constructors of Thread class:
 Thread ()-without arguments, default constructor
 Thread(String str)- Thread contains name given as argument
 Thread(Thread obj, String str) -takes thread object and string
 Thread(class Obj) – takes the runnable class as target object
 Thread(ThreadGroup group, String name) –Every thread belongs to a group, it can be
made as group using this constructor.

Methods of Thread class:


 public void run(): is used to perform action for a thread.
 public void start(): starts the execution of the thread. JVM calls the run() method on the
thread.
 public void sleep(long miliseconds): Causes the currently executing thread to sleep
(temporarily cease execution) for the specified number of milliseconds.
 public void join(): waits for a thread to die.
 public void join(long miliseconds): waits for a thread to die for the specified
milliseconds.
 public int getPriority(): returns the priority of the thread.
 public int setPriority(int priority): changes the priority of the thread.
 public String getName(): returns the name of the thread.
 public void setName(String name): changes the name of the thread.
17

 public Thread currentThread(): returns the reference of currently executing


 public int getId(): returns the id of the thread.
 public Thread.State getState(): returns the state of the thread.
 public boolean isAlive(): tests if the thread is alive.
 public void yield(): causes the currently executing thread object to temporarily pause and
allow other threads to execute.
 public void suspend(): is used to suspend the thread(depricated).
 public void resume(): is used to resume the suspended thread(depricated).
 public void stop(): is used to stop the thread(depricated).
 public boolean isDaemon(): tests if the thread is a daemon thread.
 public void setDaemon(boolean b): marks the thread as daemon or user thread.
 public void interrupt(): interrupts the thread.
 public boolean isInterrupted(): tests if the thread has been interrupted.
 public static boolean interrupted(): tests if the current thread has been interrupted.
 notif()- is calls the thread that is waiting for resource
 notifyAll()-is calls the all threads that are waiting for resource

10. The Main Thread


 Every java program has a thread called "main" thread.
 When the program execution starts, the JVM creates "main" Thread and calls the
"main()" method from within that thread.
 Along with this JVM also creates other threads for the purpose of the Housekeeping task
or cleanup operations such as "garbage" collection.
 The "main" thread Spawns the other Threads. These spawned threads are called "Child
Threads".
 The main thread is always is the last thread to finish execution.
 We, as Programmer can also take control of the main thread, using the method
"currentThread()".
 The main thread can be controlled by this method. We can also change the name of the
Thread using the method "setName(String name)".
class MainThread Output:
{
public static void main(String args[]) D:\CSE>javac MainThread.java
{ D:\CSE>java MainThread
Name of the Thread is:Thread[main,5,main]
Thread t=Thread.currentThread();
System.out.println("Name of the Thread is:"+t); Name of the Thread is:Thread[CSE,5,main]
Is thread alive? :true
t.setName("CSE");
Thread[CSE,5,main]i=1
System.out.println("Name of the Thread is:"+t);
Thread[CSE,5,main]i=2
try
Thread[CSE,5,main]i=3
{
Thread[CSE,5,main]i=4
boolean b=t.isAlive(); Thread[CSE,5,main]i=5
System.out.println("Is thread alive? :"+b);
for(int i=1;i<=5;i++)
{
System.out.println(t.currentThread()+"i="+i);
Thread.sleep(2000); //prints the next line after 2 seconds
18

}
}
catch(InterruptedException e)
{
System.out.println("Interruption raised");
}
}
}

11. Life cycle of a Thread or Thread States


During the life time of the thread, there are many states it can enter. They include the following:
i) Newborn State
ii) Runnable State
iii) Running State
iv) Blocked State
v) Dead State

Major milestones in the Thread life


 The Thread will be in the new state, when an instance of thread is created.
 The Thread will be started by calling with start() method.
 When start() method is called, it makes a call to run() method, which is an entry point for
the thread execution.
 When the Thread execution is over the resources are reclaimed by an underground thread
called “Daemon” Thread.

i) Newborn State
When we create a thread it is said to be in the new born state. At this state we can do the
following:
 Schedule it for running using the start() method.
 Kill it using stop() method.
19

ii) Runnable State


A runnable state means that a thread is ready for execution and waiting for the
availability of the processor. That is the thread has joined the queue of the threads for execution.
If all the threads have equal priority, then they are given time slots for execution in the round
rabin fashion, first-come first-serve manner. The thread that relinquishes the control will join the
queue at the end and again waits for its turn. This is known as time slicing.
iii) Running State
Running state means that the processor has given its time to the thread for it execution.
The thread runs until it relinquishes the control or it is preempted by the other higher priority
thread. As shown in the Figure, a running thread can be preempted using the suspend(), or wait(),
or sleep() methods.
iv) Blocked State
A thread is said to be in the blocked state when it is prevented from entering into
runnable state and subsequently the running state.
v) Dead State
Every thread has a life cycle. A running thread ends its life when it has completed
execution. It is a natural death. However we also can kill the thread by sending the stop()
message to it at any time.

12. Creation of new Threads


A thread is a small segment code in a given program. A thread is a lightweight sub-process, the
smallest unit of processing. Threads can be created by using two mechanisms:
1. Extending the Thread class
2. Implementing the Runnable Interface
1. Creating Multiple threads using Thread class
A multithreaded program contains two or more parts that can run concurrently. Each part
of such a program is called a thread, and each thread defines a separate path of execution. Java
provides Thread class to achieve thread programming. Thread class provides constructors and
methods to create and perform operations on a thread. To create threads by extending Thread
class first of all we need to extend Thread class by extends keyword then create an instance of
that class. The extending class must be override the run() method which is the entry point for
every new thread and it should also call start() method to start execution of thread.
// Program for creating Multiple threads using Thread class
class Thread1 extends Thread
{
public void run()
{
for(int i=0;i<10;i++)
{
System.out.println("Hello World ");
try
{
sleep(1000);
}
catch(InterruptedException e)
{
20

}
}
}
class Thread2 extends Thread
{
public void run()
{
for(int i=0;i<10;i++)
{
System.out.println("Welcome ");
try
{
sleep(500);
}
catch(InterruptedException e)
{

}
}
}

class Multi1
{
public static void main(String[]args)
{
Thread1 t1=new Thread1();
Thread2 t2=new Thread2();
t1.start();
t2.start();
}
}

OUTPUT:
Hello World
Welcome
Welcome
Hello World
Welcome
Welcome
Hello World
Welcome
Welcome
Hello World
21

Welcome
Welcome
Hello World
Welcome
Welcome
Hello World
Hello World
Hello World
Hello World
Hello World

2. Creating Multiple threads using Runnable interface


The easiest way to create a thread is to create a class that implements the Runnable
interface. In order to implement Runnable, a class requires to implement a single method called
run(). Inside this method, we can define the code which constitutes the new thread. Then we
instantiate a Thread object and call start() method on this object.

// Program for creating Multiple threads using Runnable interface


class Run1 implements Runnable
{
public void run()
{
for(int i=0;i<10;i++)
{
System.out.println("Hello World ");
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{

}
}
}
class Run2 implements Runnable
{
public void run()
{
for(int i=0;i<10;i++)
{
System.out.println("Welcome ");
try
{
Thread.sleep(500);
}
catch(InterruptedException e)
{

}
22

}
}
}

class Multi2
{
public static void main(String[]args)
{
Run1 r1=new Run1();
Run2 r2=new Run2();
Thread t1=new Thread(r1);
Thread t2=new Thread(r2);
t1.start();
t2.start();
}
}

13. Thread Priorities


The Thread priority is an important factor among the others. The Priority helps the
scheduler to decide which Thread to dispatch to CPU from the group of waiting Threads in the
Runnable state. All the Threads have a priority rating or a value. This helps the thread to acquire
the processor first. The thread with higher priority has the higher chance to get the CPU first.
When a higher priority thread is ready to execute, the processor pre-empts the low priority thread
and allows higher priority thread to run. When there are multiple threads with different priorities,
the CPU always gives it time to the higher priority thread. In this context, it is likely that a low
priority thread may not get a chance to use CPU. This situation is called “Starvation”.
The priority is the static field of Thread. It varies from 1 to 10. The class also defines Three
priority constants: MIN_PRIORITY which has value 1, MAX_PRIORITY which has value 10,
and NORM_PRIORITY which has value 5 which is considered as default priority.

We have two method to set and get priorities as follow:


public final void setPriority(int newPriority) – sets the priority of invoking of invoking thread
to newPriority.
public final int getPriority() – Returns the priority of invoking thread.

// Program for Thread Priorities


class Thread1 extends Thread {
public void run() {
System.out.println(" Child 1 is started");
}
}
class Thread2 extends Thread
{
public void run()
{
System.out.println(" Child 2 is started");
}
}
class Thread3 extends Thread
23

{
public void run()
{
System.out.println(" Child 3 is started");
}
}
class PriorityTest
{
public static void main(String args[])
{
Thread1 t1=new Thread1(); //setting the priorities using the setPriority() method
t1.setPriority(1);
Thread2 t2=new Thread2();
t2.setPriority(9);
Thread3 t3=new Thread3();
t3.setPriority(6);
t1.start();
t2.start();
t3.start();
System.out.println("The t1 thread priority is :"+t1.getPriority()); //getting the priority
}
}

14. Synchronization
 In multithreaded programming threads require to access a same resource, for example a
memory object. One thread wants to update it, while the other thread wants to read it.
 In this situation the result may not be as expected when the sequence of operations
followed are different then desired.
 Only one thread must be allowed to use the critical resource at a time to avoid this race
condition. The second thread must be allowed after the first thread has finished its work.
 When two or more threads need access to a shared resource, they need some way to
ensure that the resource will be used by only one thread at a time. The process by which
this is achieved is called synchronization.
 Thread synchronization is important in multithreaded programming in order to maintain
the data consistency. In Java, synchronization is achieved using synchronized keyword.
 Every thread object has a monitor associated with it, which is the key to the
synchronization, and when it enters the synchronized method it suspends the other
threads from entering the synchronized method.

 A monitor is an object that is used as a mutually exclusive lock, or mutex. Only one
thread can own a monitor at a given time. When a thread acquires a lock, it is said to have
24

entered the monitor. All other threads attempting to enter the locked monitor will be
suspended until the first thread exits the monitor. These other threads are said to be
waiting for the monitor.
 The general form of the synchronized method is:
synchronized type method_name(para_list)
{
//body of the method
}

// Program for create a Bank application to illustrate the multithreading using Synchronization
class BankAccount
{
int accountNumber;
double balance;
BankAccount(int n, double y)
{
accountNumber=n;
balance =y;
}
synchronized boolean deposit(int amount)
{
if(amount<0.0)
return false;
else
{
balance=balance+amount;
System.out.println("Balance after deposit="+balance);
return true;
}
}
synchronized boolean withDraw(int amount)
{
if(amount<0.0)
return false;
else
{
balance =balance - amount;
System.out.println("Balance after withdrawal ="+balance);
return true;
}
}
public static void main(String[]args)
{
BankAccount ba=new BankAccount(2345,1000.0);
System.out.println("Initial balance ="+balance);
new Thread(()->deposit(500)).start();
new Thread(()->withDraw(400)).start();
25

}
}
Disadvantages of Synchronization:
 This way of communications between the threads competing for same resource is called
implicit communication.
 This has one disadvantage due to polling. The polling wastes the CPU time.
 To save the CPU time, it is preferred to go to the inter-thread communication (explicit
communication).

15. Deadlock and Race Condition


 Race Condition – It is a situation where two or more threads are trying to (access same
resource) execute a code and their actions get interleaved. To avoid this threads must be
properly synchronized.
 Deadlock – It is 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.

16. Inter-Thread Communication


Pooling is usually implemented by a loop that is used to check some condition
repeatedly. Once the condition is true, appropriative action is taken. This wastes CPU time. To
avoid pooling, Java includes an inter process communication mechanism via the wait(), notify()
and notifyAll() methods. These methods are implemented as final methods in Object class. All
three methods can be called only from within a synchronized context.
If two or more Threads are communicating with each other, it is called "inter thread"
communication. Using the synchronized method, two or more threads can communicate
indirectly, which is called “implicit communication”. Through, synchronized method, each
thread always competes for the resource.

Method of inter-thread communication :


wait( ) - tells the calling thread to give up the monitor and go to sleep until some other thread
enters the same monitor and calls notify( ).
notify( ) - wakes up a thread that called wait( ) on the same object.
notifyAll( ) - wakes up all the threads that called wait( ) on the same object.

Inter-Thread Communication for Producer – Consumer Problem:

Producer-Consumer Problem:
26

The producer should produce data only when the buffer is not full. In case it is found that
the buffer is full, the producer is not allowed to store any data into the memory buffer. Data can
only be consumed by the consumer if and only if the memory buffer is not empty. In case it is
found that the buffer is empty, the consumer is not allowed to use any data from the memory
buffer.

Solution for Producer - Consumer Problem :


The producer is waiting until the consumer remove the data from the buffer. When the
consumer consumed the data from the buffer, then producer stores the data into the buffer.
The consumer is waiting until the producer produce the data into the buffer. When the
producer stores the data into the buffer then consumer remove the data from the buffer.

//Program to implement Producer and Consumer problem using Inter-Thread


Communication
Consider the following sample program that implements a simple form of the
producer/consumer problem. It consists of four classes: Q, the queue that you’re trying to
synchronize; Producer, the threaded object that is producing queue entries; Consumer, the
threaded object that is consuming queue entries; and PC, the tiny class that creates the single Q,
Producer, and Consumer.

class Q
{
int n;
boolean valueSet = false;
synchronized int get()
{
while(!valueSet)
try
{
wait();
}
catch(InterruptedException e)
{
System.out.println("InterruptedException caught");
}
System.out.println("Got: " + n);
valueSet = false;
notify();
return n;
}

synchronized void put(int n)


{ Output:
while(valueSet)
try
{
27

wait();
}
catch(InterruptedException e)
{
System.out.println("InterruptedException caught");
}
this.n = n;
valueSet = true;
System.out.println("Put: " + n);
notify();
}
}

class Producer implements Runnable


{
Q q;
Producer(Q q)
{
this.q = q;
new Thread(this, "Producer").start();
}
public void run()
{
int i = 0;
while(true)
{
q.put(i++);
}
}
}
class Consumer implements Runnable
{
Q q;
Consumer(Q q)
{
this.q = q;
new Thread(this, "Consumer").start();
}
public void run()
{
while(true)
{
q.get();
}
}
}
28

class PCFixed
{
public static void main(String args[])
{
Q q = new Q();
new Producer(q);
new Consumer(q);
System.out.println("Press Control-C to stop.");
}
}

17. Suspending, Resuming and Stopping of Threads


 Whenever we want stop a thread we can stop from running using "stop()" method of
thread class. It's general form will be as follows: Thread.stop();
 This method causes a thread to move from running to dead state. A thread will also move
to dead state automatically when it reaches the end of its method.
 Blocking Thread
 A thread can be temporarily suspended or blocked from entering into the runnable
and running state by using the following methods:
 sleep() -- blocked for specified time
 suspend() -- blocked until further orders
 wait() -- blocked until certain condition occurs
 resume() -- used to resume (start) suspended thread
 notify() -- used to alert the waiting thread
 notifyAll() -- used to alert all the waiting threads
 stop() -- it is used to stop or kill the running thread.

18. Daemon Threads


Daemon thread in Java is a low-priority thread that runs in the background to perform
tasks such as garbage collection. Daemon thread in Java is also a service provider thread that
provides services to the user thread. A daemon thread will come into execution when the
microprocessor is idle. i.e) when no other thread is executing.
A thread can be set to daemon thread by calling setDaemon() method to true. This
method marks the current thread as a daemon thread or user thread. A thread must be set to
daemon before a call to start() method is made. Otherwise, it throws an
IllegalThreadStateException. isDaemon() method marks the current thread as a daemon thread
or user thread. There are many java daemon threads running automatically. Example, garbage
collection, finalizer etc.
// Java program to illustrate the Daemon Threads
class DaemonThread extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
29

System.out.println(this.getName()+" "+i); // this method returns the current


thread name.
//currentThread() returns the currently executing thread object.
//isDaemon() method checking for daemon thread
if(Thread.currentThread().isDaemon())
{
System.out.println("Daemon Thread Execution");
}
else
{
System.out.println("Normal Thread Execution");
}
}
public static void main(String[] args)
{
DaemonThread t1=new DaemonThread();
DaemonThread t2=new DaemonThread();
t1.setName("Daemon Thread"); // This method is used to give name to a thread
// setPriority( ) metod is used to set the minimum priority to given thread.
t1.setPriority(MIN_PRIORITY);
System.out.println("Thread1 Name:"+t1);
t2.setName("Normal Thread"); // t2 is normal thread
System.out.println("Thread2 Name:"+t2);
t1.setDaemon(true); //now t1 is daemon thread
t1.start(); // starting t1 and t2 threads execution
t2.start();
}
}

19. Java Database Connectivity- Introduction


JDBC stands for Java Database Connectivity and has been developed by sun micro-
systems. It is a standard Java API that defines how the front-end applications may access
Database. It provides a standard library for accessing a wide variety of database systems. ODBC
(Open Database Connectivity) API used to be the Database API and executing query with
Database. This uses the ODBC driver that is written in C language, which is platform dependent.
On the other hand, JDBC applications are platform independent, and thus, and can be used to
connect with internet applications. The JDBC applications are simpler, secure and easer to
develop when compared with ODBC. The JDBC API uses JDBC Drivers that are written in java
language in order to connect with Database.
30

JDBC API and JDBC Driver form important components to fetch and store the
information in the Database. The JDBC API is installed in the client side. Therefore, when the
user wants to fetch some data from the Database, the user sets up the connection to the JDBC
Driver Manager using the JDBC JDBC API through Java Application. The JDBC Manager needs
a medium to communicate with Database. The JDBC Driver provides this medium and required
information to the JDBC Manager. Through JDBC API we can connect to different types of
Database systems including Relational and Non-relational Database system. Some of the most
widely used RDBMS are MySQL Server, Oracle, and IBM’s DB2.

20. JDBC Architecture


JDBC API supports both two-tier and three-tier processing models for Database access. This
implies that Java Application can directly communicate with Database or through a middle-tier
element. 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 Architecture for Data Access: In this model java application directly communicates
with Database. Both Java Application and JDBC API are located on the Client Machine. The
Database is located on the Database Server. User sends the commands to the Database. The
Commands are processed and the results of these statements are sent to the user.

Figure: Two-tier Architecture

Three-tier Architecture for Data Access: In this model user commands are first sent to the
application server forming the middle tier. The applications server containing the JDBC API
sends the SQL statements to the database located on the database server. The commands are
processed and result is sent to the middle tier, which then sends it to the user.

Figure: Three-tier Architecture


21. Installing MySQL and MySQL Connector/J
 MySQL is the most widely used open-source relational database management system.
31

 It is considered to be one of the best RDBMS systems for developing web-based software
applications as it provides speed, flexibility, and reliability.
 The MySQL comes with two variations such as MySQL Community, and MySQL Web
Community and can be downloaded from www.mysql.com.
 MySQL database system can operate on many platforms including Linux, Windows, Mac
OS, Sun Solaris and so on. We can select appropriate platform and download. Here we
are going to learn installing on windows platform.
Steps to download and Install MySQL :
 Go to the web site www.mysql.com
 Select the appropriate platform / operating system.
 Select mysql-installer-community or mysql-installer-web-community
 Click on download.
 The following installer will be downloaded: mysql-installer-web-community-8.0.25.0
 Double click on the above installer to start installation.

 Step 1: After downloading the setup, unzip it anywhere and double click the MSI
installer .exe file.
 Step 2: In the next wizard, choose the Setup Type. There are several types available, and
you need to choose the appropriate option to install MySQL product and features. Here,
we are going to select the Full option and click on the Next button.
 Step 3: Once we click on the Next button, it may give information about some features
that may fail to install on your system due to a lack of requirements. We can resolve them
by clicking on the Execute button that will install all requirements automatically or can
skip them. Now, click on the Next button.
 Step 4: In the next wizard, we will see a dialog box that asks for our confirmation of a
few products not getting installed. Here, we have to click on the Yes button.
 Step 5: Once we click on the Execute button, it will download and install all the
products. After completing the installation, click on the Next button.
 Step 6: In the next wizard, we need to configure the MySQL Server and Router. Here, I
am not going to configure the Router because there is no need to use it with MySQL. We
are going to show you how to configure the server only. Now, click on the Next button.
32

 Step 7: As soon as you will click on the Next button, you can see the screen below. Here,
we have to configure the MySQL Server. Now, choose the Standalone MySQL
Server/Classic MySQL Replication option and click on Next. Here, you can also choose
the InnoDB Cluster based on your needs.
 Step 8: In the next screen, the system will ask you to choose the Config Type and other
connectivity options. Here, we are going to select the Config Type as 'Development
Machine' and Connectivity as TCP/IP, and Port Number is 3306, then click on Next.
 Step 9: Now, select the Authentication Method and click on Next. Here, I am going to
select the first option.
 Step 10: The next screen will ask you to mention the MySQL Root Password. After
filling the password details, click on the Next button.
 Step 11: The next screen will ask you to configure the Windows Service to start the
server. Keep the default setup and click on the Next button.
 Step 12: In the next wizard, the system will ask you to apply the Server Configuration. If
you agree with this configuration, click on the Execute button.
 Step 13: Once the configuration has completed, you will get the screen below. Now,
click on the Finish button to continue.
 Step 14: In the next screen, you can see that the Product Configuration is completed.
Keep the default setting and click on the Next-> Finish button to complete the MySQL
package installation.
 Step 15: In the next wizard, we can choose to configure the Router. So click on Next-
>Finish and then click the Next button.
 Step 16: In the next wizard, we will see the Connect to Server option. Here, we have to
mention the root password, which we had set in the previous steps.
 Step 17: In the next wizard, select the applied configurations and click on the Execute
button.
 Step 18: After completing the above step, we will get the following screen. Here, click
on the Finish button.

Installing MySQL Connector/J


 To install MySQL Connector go to the following website:
https://mvnrepository.com/artifact/mysql/mysql-connector-java/8.0.25
 Click on the jar file (2.3 MB) and save it in any folder.
 Set the “CLASSPATH” with above jar file as follow at command prompt while
compiling and running java program that contains code to fetch the data from the table
that is present on the Database.
 set CLASSPATH=.;C:\Users\91970\Documents\mysqljar\mysql-connector-java-
8.0.25.jar; %CLASSPATH%
SQL Statements:
 SQL statements are used to perform various statements on the database.
 Some of the SQL Statements are described here such as : create, select, insert into, where
clause, delete statement and son on.
 Create the table named “student” in the database named “college”.
33

22. Establishing JDBC Database Connections


There are some standard steps to be followed for connecting to the database and execute queries.
The JDBC Driver class handles the connection to a database.The steps are as follows:
 Load and register the JDBC Driver
 Define the Connection URL
 Establish the Connection to a database
 Create a statement object
 Execute a query
 Process the results
 Disconnect from the database

i) Load and Register the JDBC Driver


The JDBC driver is a software component that interacts with the database server. In order
to load the driver the class name of the database driver is specified that automatically creates an
instance and registers with Driver Manager. Driver Manager class manages a list of database
drivers. The Driver interface handles the communication with the database server. This could be
done as follow:
Class.forName(“drivername”); // Driver name is loaded with a call to
Class.forName(drivername).

// JDBC Driver Names & Database URL


RDBS JDBC DRIVERNAME URL FORMAT

MySQL com.mysql.jdbc.Driver jdbc:mysql://hostname:portnumber/databasename

ORACLE oracle.jdbc.driver.OracleDriver jdbc:oracle:thin:@hostname:portnumber:database


name
DB2 com.ibm.db2.jdbc.net.DB2Driver jdbc:db2:hostname:portnumber/databasename
34

ii) Defining the URL Connection


After loading the JDBC Driver, URL address of the Database need to be specified for
connecting with the Database. URL identifies the location of the database server and type of
database. String url=“jdbc:mysql://localhost:3306/college“;

iii) Establishing the Connection


 In order to establish the connection, the database URL, user name, password are passed
as arguments to the getConnection() method of DriverManager class.
 The Connection interface provides methods for creating statements and contacting a
database.
Syntax: Connection con=DriverManager.getConnection(url,“username",“password");
For example: Connection con=DriverManager.getConnection(url,"root","root");

Some of the methods of the Connection interface are as follow:


public Statement createStatement(): creates a statement object that can be used to execute
SQL queries.
public Statement createStatement(int resultSetType,int resultSetConcurrency): Creates a
Statement object that will generate ResultSet objects with the given type and concurrency.
public void setAutoCommit(boolean status): is used to set the commit status.By default it is
true.
public void commit(): saves the changes made since the previous commit/rollback permanent.
public void rollback(): Drops all changes made since the previous commit/rollback.
public void close(): closes the connection and Releases a JDBC resources immediately.

iv) Create a Statement object


After Connection is established, the statement object is created to send queries to the
database.

o Statement: Executes simple SQL queries without parameters.

Statement stmt = connection.createStatement();

ResultSet rs = stmt.executeQuery("SELECT * FROM


yourTable");

o PreparedStatement: Precompiled SQL statement that allows parameterized


queries.

PreparedStatement pstmt =
Connection.prepareStatement("SELECT * FROM
yourTable");

ResultSet rs = pstmt.executeQuery();

Commonly used methods of Statement interface:


35

public ResultSet executeQuery(String sql): is used to execute SELECT query. It returns the
object of ResultSet.
public int executeUpdate(String sql): is used to execute specified query, it may be create, drop,
insert, update, delete etc.
public boolean execute(String sql): is used to execute queries that may return multiple results.
public int[] executeBatch(): is used to execute batch of commands.

v) Execute a query or Update Query


After getting the statement object, we need to execute the queries. This is shown in the
example:
ResultSet rs=stmt.executeQuery("select * from student");

vi) Process the results - The results are processed using the while loop as shown in the java
example program.

vii) Closing the Connection- After completion of the task the connection is closed with close()
method of Connection interface.

23. ResultSet Interface


The ResultSet interface manages access to data returned from a query. It retrieve and update the
results of a query. The data returned equals one row in a database table. A ResultSet consists of
records. Each record consists of columns. The ResultSet can be created by executing a Statement
or PreparedStatement as shown below:
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery(“select *from student”); or
PreparedStatement st=con.preparedStatement(“select *from student”);
ResultSet rs=st. executeUpdate();
The following syntax is used to iterate over the ResultSet using the next() method:
while(rs.next())
{
statement(s);
}
Commonly used methods of ResultSet interface
public boolean next() is used to move the cursor to the one row next from the current
position.
public boolean previous() is used to move the cursor to the one row previous from the
current position.
public boolean first() is used to move the cursor to the first row in result set object.

public boolean last() is used to move the cursor to the last row in result set object.
public boolean absolute(int row) is used to move the cursor to the specified row number in the
ResultSet object.
public boolean relative(int row) is used to move the cursor to the relative row number in the
ResultSet object, it may be positive or negative.
36

public int getInt(int is used to return the data of specified column index of the current
columnIndex) row as int.
public int getInt(String is used to return the data of specified column name of the current
columnName) row as int.
public String getString(int is used to return the data of specified column index of the current
columnIndex) row as String.
public String getString(String is used to return the data of specified column name of the current
columnName) row as String.

24. Creating a JDBC Application with MySQL Database


//MysqlCon.java

import java.sql.*;
class MysqlCon{
public static void main(String args[])
{
try{
Class.forName("com.mysql.jdbc.Driver"); //loading and registering
String url="jdbc:mysql://localhost:8080/college"; //Defining URL
Connection con=DriverManager.getConnection(url,"root","root"); //Establishing
connection
//here url is database name, root is username and password
Statement stmt=con.createStatement(); //create statement
ResultSet rs=stmt.executeQuery("select * from student"); //Execute Query
while(rs.next()) //process result
System.out.println(rs.getInt("id")+" "+rs.getString("fname")+"
"+rs.getInt("marks"));
con.close(); //closing the connection
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Compiling and Running MysqlCon.java
D:/CSE> javac MysqlCon.java
D:/CSE> java MysqlCon
345 Riya 60
346 Rohit 75
346 Rohit 75
348 preethi 84
400 divya 90
37

24.1 Creating Table using JDBC


import java.sql.*; CreateTable.java
class CreateTable{
public static void main(String args[])
{
try{
Class.forName("com.mysql.cj.jdbc.Driver"); //loading and registering
String url="jdbc:mysql://localhost:3306/college";
Connection con=DriverManager.getConnection(url,"root","root");
//here college is database name, root is username and password
Statement stmt=con.createStatement();
System.out.println("Creating Table in the Database");
String q="create table subject(name varchar(20),author varchar(20),edition varchar(10))";
stmt.executeUpdate(q); //is used to execute specified query, it may be create, drop, insert,
update, delete etc.
} mysql> describe subject;
catch(Exception e) +---------+-------------+------+-----+---------+-------+
{ System.out.println(e);} | Field | Type | Null | Key | Default | Extra |
} +---------+-------------+------+-----+---------+-------+
} | name | varchar(20) | YES | | NULL | |
| author | varchar(20) | YES | | NULL | |
| edition | varchar(10) | YES | | NULL | |
+---------+-------------+------+-----+---------+-------+

24.2 Insert into Table using JDBC


import java.sql.*; InsertToTable.java
class InsertToTable{
public static void main(String args[])
{
try{
Class.forName("com.mysql.cj.jdbc.Driver"); //loading and registering
String url="jdbc:mysql://localhost:3306/college";
Connection con=DriverManager.getConnection(url,"root","root");
//here college is database name, root is username and password
Statement stmt=con.createStatement();
String q2="insert into subject values"+"('Complete Reference','Herbet','8thEdition')";
stmt.executeUpdate(q2);
}
catch(Exception e)
{ System.out.println(e);}
}
}
Output:
mysql> select *from subject;
+--------------------+--------+------------+
38

| name | author | edition |


+--------------------+--------+------------+
| Complete Reference | Herbet | 8thEdition |
+--------------------+--------+------------+

24.3 Delete and Update records using JDBC


 Deleting records
 String q3=“delete from subject where author=‘Herbet’ ”;
 st.executeUpdate(q3);
 Updating records
 String q4=“update subject set author=‘Anitha Seth’ where name=‘One Step
Ahead’ ”;
 st.executeUpdate(q4);

JAVAFX GUI
25. 1. JavaFX Scene Builder
Definition: JavaFX Scene Builder is a visual layout tool for designing JavaFX application
interfaces. It allows you to drag and drop UI components, set properties, and generate FXML
files.

Usage:
 Download and install JavaFX Scene Builder.
 Open Scene Builder and create a new FXML file.
 Design the layout by dragging UI components like buttons, labels, and text fields.
 Save the design, which generates an FXML file to be loaded into your JavaFX
application.

Integrating with JavaFX:


1. Load FXML files using FXMLLoader to create the UI in a JavaFX application.
2. JavaFX App Window Structure
Primary Components:
Stage: The main window of a JavaFX application.
Scene: A container for all visual content; a stage can display only one scene at a time.
Nodes: Elements in the scene graph, such as UI controls and layout panes.

Structure Example:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
39

public class JavaFXAppStructure extends Application {


@Override
public void start(Stage primaryStage) {
// Create the root node
StackPane root = new StackPane();

// Create a Scene
Scene scene = new Scene(root, 400, 300);

// Set the Scene on the Stage


primaryStage.setTitle("JavaFX App Structure Example");
primaryStage.setScene(scene);
primaryStage.show();
}

public static void main(String[] args) {


launch(args);
}
}
3. Displaying Text and Images

Displaying Text:

Use the Text or Label class to display text.

Example:

import javafx.scene.text.Text;

Text text = new Text("Hello, JavaFX!");


root.getChildren().add(text);

Displaying Images:
Use Image and ImageView classes to display an image.

Example:
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;

Image image = new Image("file:yourImagePath.jpg");


ImageView imageView = new ImageView(image);
root.getChildren().add(imageView);

4. Event Handling
40

Definition: Event handling in JavaFX enables responding to user interactions such as clicks, key
presses, and mouse movements.

Using Event Handlers:


Attach event handlers to UI controls, like buttons, to define actions on events.

Example:
import javafx.scene.control.Button;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;

Button button = new Button("Click Me");


button.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
System.out.println("Button Clicked!");
}
});
root.getChildren().add(button);

5. Laying Out Nodes in Scene Graph


Layout Panes:
JavaFX provides layout panes for organizing nodes in a scene, such as VBox, HBox, GridPane,
and BorderPane.

Example Layout with VBox:


import javafx.scene.layout.VBox;
import javafx.scene.control.Label;
import javafx.scene.control.Button;

VBox vbox = new VBox(10); // 10px spacing


vbox.getChildren().addAll(new Label("Label 1"), new Button("Button 1"));
root.getChildren().add(vbox);

Layout with GridPane:


import javafx.scene.layout.GridPane;
import javafx.scene.control.TextField;

GridPane gridPane = new GridPane();


gridPane.add(new Label("Username:"), 0, 0);
gridPane.add(new TextField(), 1, 0);
gridPane.add(new Label("Password:"), 0, 1);
gridPane.add(new TextField(), 1, 1);
root.getChildren().add(gridPane);
41

6. Mouse Events
Definition: Mouse events detect and respond to mouse actions, such as clicks, movements, and
drags.

Common Mouse Events:


setOnMouseClicked: Handles mouse clicks.
setOnMouseEntered: Triggers when the mouse enters a node’s area.
setOnMouseExited: Triggers when the mouse exits a node’s area.

Example Program Handling Mouse Events:

import javafx.scene.input.MouseEvent;
import javafx.scene.shape.Rectangle;

Rectangle rectangle = new Rectangle(100, 100);


rectangle.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
System.out.println("Rectangle clicked!");
}
});
root.getChildren().add(rectangle);

Putting It All Together: Full JavaFX Example


Here’s a small JavaFX program that incorporates text, images, layout, and event handling.
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.VBox;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.input.MouseEvent;

public class FullJavaFXExample extends Application {


@Override
public void start(Stage primaryStage) {
// Create layout
VBox root = new VBox(10);

// Add Text
Text text = new Text("Welcome to JavaFX!");
42

root.getChildren().add(text);

// Add Image
Image image = new Image("file:yourImagePath.jpg");
ImageView imageView = new ImageView(image);
root.getChildren().add(imageView);

// Add Button with Action Event


Button button = new Button("Click Me");
button.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
System.out.println("Button clicked!");
}
});
root.getChildren().add(button);

// Rectangle with Mouse Event


javafx.scene.shape.Rectangle rectangle = new javafx.scene.shape.Rectangle(100, 100);
rectangle.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
System.out.println("Rectangle clicked!");
}
});
root.getChildren().add(rectangle);

// Set up Scene and Stage


Scene scene = new Scene(root, 400, 400);
primaryStage.setTitle("JavaFX Full Example");
primaryStage.setScene(scene);
primaryStage.show();
}

public static void main(String[] args) {


launch(args);
}
}

You might also like