OOPJ [Link]
com/c/EDULINEFORCSE
STUDENTS
MODULE 4
ADVANCED FEATURES OF JAVA
CHAPTER 1
Java Library & Collections framework
Prepared By Mr. EBIN PM, AP, IESCE 1
STRING
• In Java, string is basically an object that represents sequence of
char values. An array of characters works same as Java string. For
example:
char[ ] ch={‘h','a',‘i',‘j',‘a',‘v',‘a'};
String s=new String(ch);
is same as:
String s = “haijava";
• 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.
Prepared By [Link] PM, AP, IESCE EDULINE 2
Prepared By Mr. EBIN PM, AP, IESCE 1
OOPJ [Link]
STUDENTS
Create a string object
There are two ways to create String object:
• By string literal
• By new keyword
1) String Literal
Java String literal is created by using double quotes. For Example:
String s = "welcome";
• Each time you create a string literal, the JVM checks the "string constant
pool" first.
• If the string already exists in the pool, a reference to the pooled
instance is returned.
• If the string doesn't exist in the pool, a new string instance is created
and placed in the pool. For example:
Prepared By [Link] PM, AP, IESCE EDULINE 3
String s1="Welcome";
String s2="Welcome"; //It doesn't create a new instance
• In the above example, only one object will be created.
• Firstly, JVM will not find any string object with the value
"Welcome" in string constant pool, that is why it will create a new
object.
• After that it will find the string with the value "Welcome" in the
pool, it will not create a new object but will return the reference to
the same instance.
• Note: String objects are stored in a special memory area known as
the "string constant pool".
Prepared By [Link] PM, AP, IESCE EDULINE 4
Prepared By Mr. EBIN PM, AP, IESCE 2
OOPJ [Link]
STUDENTS
Why Java uses the concept of String literal
To make Java more memory efficient (because no new objects are
created if it exists already in the string constant pool).
Prepared By [Link] PM, AP, IESCE EDULINE 5
2) By new keyword
String s=new String("Welcome"); //creates two objects and one
reference variable
• In such case, JVM will create a new string object in normal (non-
pool) heap memory, and the literal "Welcome" will be placed in the
string constant pool.
• The variable s will refer to the object in a heap (non-pool).
Prepared By [Link] PM, AP, IESCE EDULINE 6
Prepared By Mr. EBIN PM, AP, IESCE 3
OOPJ [Link]
STUDENTS
String Example
OUTPUT
Prepared By [Link] PM, AP, IESCE EDULINE 7
STRING CONSTRUCTORS
• The string class supports several types of constructors in Java APIs.
The most commonly used constructors of String class are as
follows:
1. String() : To create an empty String, we will call a default
constructor. For example:
String s = new String();
• It will create a string object in the heap area with no value
Prepared By [Link] PM, AP, IESCE EDULINE 8
Prepared By Mr. EBIN PM, AP, IESCE 4
OOPJ [Link]
STUDENTS
2. String(String str) : It will create a string object in the heap area
and stores the given value in it. For example:
String s2 = new String(“Hello Java“);
Now, the object contains Hello Java.
3. String(char chars[ ]) : It will create a string object and stores the
array of characters in it. For example:
char chars[ ] = { ‘a’, ‘b’, ‘c’, ‘d’ };
String s3 = new String(chars);
The object reference variable s3 contains the address of the value
stored in the heap area.
Prepared By [Link] PM, AP, IESCE EDULINE 9
Let’s take an example program where we will create a string object
and store an array of characters in it
Prepared By [Link] PM, AP, IESCE EDULINE 10
Prepared By Mr. EBIN PM, AP, IESCE 5
OOPJ [Link]
STUDENTS
4. String(char chars[ ], int startIndex, int count)
• It will create and initializes a string object with a subrange of a
character array.
• The argument startIndex specifies the index at which the subrange
begins and count specifies the number of characters to be copied.
For example:
char chars[ ] = { ‘w’, ‘i’, ‘n’, ‘d’, ‘o’, ‘w’, ‘s’ };
String str = new String(chars, 2, 3);
• The object str contains the address of the value ”ndo” stored in the
heap area because the starting index is 2 and the total number of
characters to be copied is 3
Prepared By [Link] PM, AP, IESCE EDULINE 11
EXAMPLE
Prepared By [Link] PM, AP, IESCE EDULINE 12
Prepared By Mr. EBIN PM, AP, IESCE 6
OOPJ [Link]
STUDENTS
• In this example program, we will construct a String object that
contains the same characters sequence as another string object.
As you can see the output, s1 and
s2 contain the same string.
Thus, we can create one string
from another string.
Prepared By [Link] PM, AP, IESCE EDULINE 13
5. String(byte byteArr[ ]) : It constructs a new string object by
decoding the given array of bytes (i.e, by decoding ASCII values into
the characters) according to the system’s default character set.
Prepared By [Link] PM, AP, IESCE EDULINE 14
Prepared By Mr. EBIN PM, AP, IESCE 7
OOPJ [Link]
STUDENTS
6. String(byte byteArr[ ], int startIndex, int count)
This constructor also creates a new string object by decoding the
ASCII values using the system’s default character set.
Prepared By [Link] PM, AP, IESCE EDULINE 15
STRING LENGTH
• The java string length() method gives length of the string. It returns
count of total number of characters.
• Internal implementation
public int length() {
return [Link];
}
Signature - The signature of the string length() method is given
below:
public int length()
Prepared By [Link] PM, AP, IESCE EDULINE 16
Prepared By Mr. EBIN PM, AP, IESCE 8
OOPJ [Link]
STUDENTS
String length() method example - 1
Output
Prepared By [Link] PM, AP, IESCE EDULINE 17
String length() method example - 2
Output
Prepared By [Link] PM, AP, IESCE EDULINE 18
Prepared By Mr. EBIN PM, AP, IESCE 9
OOPJ [Link]
STUDENTS
STRING COMPARISON
• We can compare string in java on the basis of content and reference
• There are three ways to compare string in java:
By equals() method
By = = operator
By compareTo() method
String compare by equals() method
• The String equals() method compares the original content of the
string.
• It compares values of string for equality. String class provides two
methods
Prepared By [Link] PM, AP, IESCE EDULINE 19
public boolean equals(Object another) compares this string to the
specified object.
public boolean equalsIgnoreCase(String another) compares this
String to another string, ignoring case.
Prepared By [Link] PM, AP, IESCE EDULINE 20
Prepared By Mr. EBIN PM, AP, IESCE 10
OOPJ [Link]
STUDENTS
Example 2
Output
Prepared By [Link] PM, AP, IESCE EDULINE 21
String compare by == operator
• The = = operator compares references not values.
Prepared By [Link] PM, AP, IESCE EDULINE 22
Prepared By Mr. EBIN PM, AP, IESCE 11
OOPJ [Link]
STUDENTS
String compare by compareTo() method
• The String compareTo() method compares values lexicographically
and returns an integer value that describes if first string is less than,
equal to or greater than second string.
Suppose s1 and s2 are two string variables. If:
s1 == s2 : 0
s1 > s2 : positive value
s1 < s2 : negative value
Prepared By [Link] PM, AP, IESCE EDULINE 23
Prepared By [Link] PM, AP, IESCE EDULINE 24
Prepared By Mr. EBIN PM, AP, IESCE 12
OOPJ [Link]
STUDENTS
Eg:
Output
Prepared By [Link] PM, AP, IESCE EDULINE 25
SEARCHING STRINGS
String contains()
• The java string contains() method searches the sequence of
characters in this string.
• It returns true if sequence of char values are found in this string
otherwise returns false.
Internal implementation
public boolean contains(CharSequence s) {
return indexOf([Link]()) > -1;
}
Prepared By [Link] PM, AP, IESCE EDULINE 26
Prepared By Mr. EBIN PM, AP, IESCE 13
OOPJ [Link]
STUDENTS
Signature
• The signature of string contains() method is given below:
public boolean contains(CharSequence sequence)
Output
Prepared By [Link] PM, AP, IESCE EDULINE 27
Eg 2 - The contains() method searches case sensitive char sequence.
If the argument is not case sensitive, it returns false. Let's see an
example below.
Output
Prepared By [Link] PM, AP, IESCE EDULINE 28
Prepared By Mr. EBIN PM, AP, IESCE 14
OOPJ [Link]
STUDENTS
Eg 3 -The contains() method is helpful to find a char-sequence in the
string. We can use it in control structure to produce search based
result. Let us see an example below.
Prepared By [Link] PM, AP, IESCE EDULINE 29
CHARACTER EXTRACTION
String charAt()
• The java string 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 length
of the string.
• It returns StringIndexOutOfBoundsException if given index number
is greater than or equal to this string length or a negative number.
• Signature - The signature of string charAt() method is given below:
public char charAt(int index)
Prepared By [Link] PM, AP, IESCE EDULINE 30
Prepared By Mr. EBIN PM, AP, IESCE 15
OOPJ [Link]
STUDENTS
Example:
Output
t
Prepared By [Link] PM, AP, IESCE EDULINE 31
StringIndexOutOfBoundsException with charAt()
• Let's see the example of charAt() method where we are passing
greater index value.
• In such case, it throws StringIndexOutOfBoundsException at run
time.
Prepared By [Link] PM, AP, IESCE EDULINE 32
Prepared By Mr. EBIN PM, AP, IESCE 16
OOPJ [Link]
STUDENTS
Java String charAt() Example 3
• Let's see a simple example where we are accessing first and last
character from the provided string.
Prepared By [Link] PM, AP, IESCE EDULINE 33
Prepared By [Link] PM, AP, IESCE EDULINE 34
Prepared By Mr. EBIN PM, AP, IESCE 17
OOPJ [Link]
STUDENTS
Java String charAt() Example 4
• Let's see an example where we are accessing all the elements
present at odd index.
Prepared By [Link] PM, AP, IESCE EDULINE 35
Java String charAt() Example 5
• Let's see an example where we are counting frequency of a
character in the string.
Prepared By [Link] PM, AP, IESCE EDULINE 36
Prepared By Mr. EBIN PM, AP, IESCE 18
OOPJ [Link]
STUDENTS
MODIFY STRINGS
• The java string replace() method returns a string replacing all the
old char or CharSequence to new char or CharSequence.
Signature
• There are two type of replace methods in java string.
public String replace(char oldChar, char newChar)
and
public String replace(CharSequence target, CharSequence
replacement)
• The second replace method is added since JDK 1.5.
Prepared By [Link] PM, AP, IESCE EDULINE 37
String replace(char old, char new) method example
public class ReplaceExample1{
public static void main(String args[]){
String s1="java is a very good language";
// replaces all occurrences of 'a' to 'e'
String replaceString=[Link]('a','e');
[Link](replaceString);
}}
Output
jeve is e very good lenguege
Prepared By [Link] PM, AP, IESCE EDULINE 38
Prepared By Mr. EBIN PM, AP, IESCE 19
OOPJ [Link]
STUDENTS
String replace(CharSequence target, CharSequence
replacement) method example
Output
my name was khan my name was java
Prepared By [Link] PM, AP, IESCE EDULINE 39
String replace() Method Example 3
Output
Prepared By [Link] PM, AP, IESCE EDULINE 40
Prepared By Mr. EBIN PM, AP, IESCE 20
OOPJ [Link]
STUDENTS
• The java string replaceAll() method returns a string replacing all the
sequence of characters matching regex and replacement string.
Internal implementation
public String replaceAll(String regex, String replacement) {
return [Link](regex).matcher(this).replaceAll(replacement);
}
Signature
public String replaceAll(String regex, String replacement)
Prepared By [Link] PM, AP, IESCE EDULINE 41
String replaceAll() example: replace character
• Let's see an example to replace all the occurrences of a single
character.
public class ReplaceAllExample1{
public static void main(String args[]){
String s1="java is a very good language";
String replaceString=[Link]("a","e");//replaces all occurrences
of "a" to "e"
[Link](replaceString);
}}
Output jeve is e very good lenguege
Prepared By [Link] PM, AP, IESCE EDULINE 42
Prepared By Mr. EBIN PM, AP, IESCE 21
OOPJ [Link]
STUDENTS
String replaceAll() example: replace word
• Let's see an example to replace all the occurrences of single word
or set of words.
Output
My name was Khan. My name was Bob. My name was Sonoo.
Prepared By [Link] PM, AP, IESCE EDULINE 43
String replaceAll() example: remove white spaces
• Let's see an example to remove all the occurrences of white spaces.
Output
[Link].
Prepared By [Link] PM, AP, IESCE EDULINE 44
Prepared By Mr. EBIN PM, AP, IESCE 22
OOPJ [Link]
STUDENTS
STRING VALUE OF ( )
• The java string valueOf() method converts different types of values
into string.
• By the help of string valueOf() method, we can convert int to
string, long to string, boolean to string, character to string, float to
string, double to string, object to string and char array to string.
Internal implementation
public static String valueOf(Object obj) {
return (obj == null) ? "null" : [Link]();
}
Prepared By [Link] PM, AP, IESCE EDULINE 45
Signature
• The signature or syntax of string valueOf() method is given below:
public static String valueOf(boolean b)
public static String valueOf(char c)
public static String valueOf(char[] c)
public static String valueOf(int i)
public static String valueOf(long l)
public static String valueOf(float f)
public static String valueOf(double d)
public static String valueOf(Object o)
Prepared By [Link] PM, AP, IESCE EDULINE 46
Prepared By Mr. EBIN PM, AP, IESCE 23
OOPJ [Link]
STUDENTS
valueOf() method example
Output
3010
Prepared By [Link] PM, AP, IESCE EDULINE 47
valueOf(boolean bol) Method Example
This is a boolean version of overloaded valueOf() method. It takes
boolean value and returns a string. Let's see an example.
Output
true
false
Prepared By [Link] PM, AP, IESCE EDULINE 48
Prepared By Mr. EBIN PM, AP, IESCE 24
OOPJ [Link]
STUDENTS
valueOf(char ch) Method Example
This is a char version of overloaded valueOf() method. It takes
char value and returns a string. Let's see an example.
Output
A
B
Prepared By [Link] PM, AP, IESCE EDULINE 49
valueOf(float f) and valueOf(double d) Example
This is a float version of overloaded valueOf() method. It takes
float value and returns a string. Let's see an example.
Output
10.05
10.02
Prepared By [Link] PM, AP, IESCE EDULINE 50
Prepared By Mr. EBIN PM, AP, IESCE 25
OOPJ [Link]
STUDENTS
String valueOf() Complete Examples
Output
Prepared By [Link] PM, AP, IESCE EDULINE 51
Immutable String in Java
• In java, string objects are immutable. Immutable simply means
unmodifiable or unchangeable. Once string object is created its
data or state can't be changed but a new string object is created.
Example
Output Sachin
Prepared By [Link] PM, AP, IESCE EDULINE 52
Prepared By Mr. EBIN PM, AP, IESCE 26
OOPJ [Link]
STUDENTS
It can be understood by the diagram given below. Here Sachin is not
changed but a new object is created with sachintendulkar. That is
why string is known as immutable.
Prepared By [Link] PM, AP, IESCE EDULINE 53
• As you can see in the figure that two objects are created but s
reference variable still refers to "Sachin" not to "Sachin Tendulkar".
• But if we explicitely assign it to the reference variable, it will refer
to "Sachin Tendulkar" object. For example:
Output
Sachin Tendulkar
In such case, s points to the
"Sachin Tendulkar". Please notice
that still sachin object is not
modified.
Prepared By [Link] PM, AP, IESCE EDULINE 54
Prepared By Mr. EBIN PM, AP, IESCE 27
OOPJ [Link]
STUDENTS
Why string objects are immutable in java
• Because java uses the concept of string literal.
• Suppose there are 5 reference variables,all referes to one object
"sachin".
• If one reference variable changes the value of the object, it will be
affected to all the reference variables.
• That is why string objects are immutable in java.
Prepared By [Link] PM, AP, IESCE EDULINE 55
String and StringBuffer
• Java StringBuffer class is used to create mutable (modifiable)
string. The StringBuffer class in java is same as String class except
it is mutable i.e. it can be changed.
Prepared By [Link] PM, AP, IESCE EDULINE 56
Prepared By Mr. EBIN PM, AP, IESCE 28
OOPJ [Link]
STUDENTS
Important Constructors of StringBuffer class
Mutable string - A string that can be modified or changed is known
as mutable string. StringBuffer and StringBuilder classes are used
for creating mutable string.
Prepared By [Link] PM, AP, IESCE EDULINE 57
StringBuffer append() method
Prepared By [Link] PM, AP, IESCE EDULINE 58
Prepared By Mr. EBIN PM, AP, IESCE 29
OOPJ [Link]
STUDENTS
StringBuffer insert() method
The insert() method inserts the given string with this string at the
given position.
Prepared By [Link] PM, AP, IESCE EDULINE 59
StringBuffer replace() method
The replace() method replaces the given string from the specified
beginIndex and endIndex.
Prepared By [Link] PM, AP, IESCE EDULINE 60
Prepared By Mr. EBIN PM, AP, IESCE 30
OOPJ [Link]
STUDENTS
StringBuffer delete() method
The delete() method of StringBuffer class deletes the string from
the specified beginIndex to endIndex.
Prepared By [Link] PM, AP, IESCE EDULINE 61
StringBuffer reverse() method
The reverse() method of StringBuffer class reverses the current
string.
Prepared By [Link] PM, AP, IESCE EDULINE 62
Prepared By Mr. EBIN PM, AP, IESCE 31
OOPJ [Link]
STUDENTS
COLLECTIONS IN JAVA
The Collection in Java is a framework that provides an architecture
to store and manipulate the group of objects.
Java Collections can achieve all the operations that you perform on
a data such as searching, sorting, insertion, manipulation, and
deletion.
Java Collection means a single unit of objects. Java Collection
framework provides many interfaces (Set, List, Queue, Deque) and
classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet,
LinkedHashSet, TreeSet).
Prepared By [Link] PM, AP, IESCE EDULINE 63
Collection in Java - Represents a single unit of objects, i.e., a
group.
framework in Java
• It provides readymade architecture.
• It represents a set of classes and interfaces.
• It is optional.
Collection framework
The Collection framework represents a unified architecture for
storing and manipulating a group of objects. It has:
• Interfaces and its implementations, i.e., classes
• Algorithm
Prepared By [Link] PM, AP, IESCE EDULINE 64
Prepared By Mr. EBIN PM, AP, IESCE 32
OOPJ [Link]
STUDENTS
Hierarchy of Collection Framework
Prepared By [Link] PM, AP, IESCE EDULINE 65
The [Link] package contains all the classes and interfaces for the
Collection framework.
Collection Interface
• The Collection interface is the interface which is implemented by all
the classes in the collection framework.
• It declares the methods that every collection will have. In other
words, we can say that the Collection interface builds the
foundation on which the collection framework depends.
• Some of the methods of Collection interface are Boolean add (
Object obj), Boolean addAll ( Collection c), void clear(), etc. which
are implemented by all the subclasses of Collection interface.
Prepared By [Link] PM, AP, IESCE EDULINE 66
Prepared By Mr. EBIN PM, AP, IESCE 33
OOPJ [Link]
STUDENTS
LIST INTERFACE
• List interface is the child interface of Collection interface.
• It inhibits a list type data structure in which we can store the
ordered collection of objects.
• It can have duplicate values.
• List interface is implemented by the classes ArrayList,
LinkedList, Vector, and Stack.
• To instantiate the List interface, we must use :
Prepared By [Link] PM, AP, IESCE EDULINE 67
List <data-type> list1= new ArrayList();
List <data-type> list2 = new LinkedList();
List <data-type> list3 = new Vector();
List <data-type> list4 = new Stack();
There are various methods in List interface that can be used to
insert, delete, and access the elements from the list.
The classes that implement the List interface are given below.
ArrayList
The ArrayList class implements the List interface. It uses a dynamic
array to store the duplicate element of different data types.
Prepared By [Link] PM, AP, IESCE EDULINE 68
Prepared By Mr. EBIN PM, AP, IESCE 34
OOPJ [Link]
STUDENTS
• The ArrayList class maintains the insertion order and is non-
synchronized. The elements stored in the ArrayList class can be
randomly accessed. Consider the following example.
Prepared By [Link] PM, AP, IESCE EDULINE 69
Java ArrayList class uses a dynamic array for storing the elements.
It is like an array, but there is no size limit. We can add or remove
elements anytime.
So, it is much more flexible than the traditional array. It is found in
the [Link] package. It is like the Vector in C++.
The ArrayList in Java can have the duplicate elements also. It
implements the List interface so we can use all the methods of List
interface here.
The ArrayList maintains the insertion order internally.
It inherits the AbstractList class and implements List interface.
Prepared By [Link] PM, AP, IESCE EDULINE 70
Prepared By Mr. EBIN PM, AP, IESCE 35
OOPJ [Link]
STUDENTS
The important points about Java ArrayList class are:
• Java ArrayList class can contain duplicate elements.
• Java ArrayList class maintains insertion order.
• Java ArrayList class is non synchronized.
• Java ArrayList allows random access because array works at the
index basis.
• In ArrayList, manipulation is little bit slower than the LinkedList in
Java because a lot of shifting needs to occur if any element is
removed from the array list.
Prepared By [Link] PM, AP, IESCE EDULINE 71
ArrayList Example
Prepared By [Link] PM, AP, IESCE EDULINE 72
Prepared By Mr. EBIN PM, AP, IESCE 36
OOPJ [Link]
STUDENTS
Iterating ArrayList using Iterator
Prepared By [Link] PM, AP, IESCE EDULINE 73
Prepared By Mr. EBIN PM, AP, IESCE 37
OOPJ [Link]
STUDENTS
MODULE 4
CHAPTER 2
MULTITHREADED PROGRAMMING
Prepared By Mr. EBIN PM, AP, IESCE 1
THREAD
• JAVA is a multi-threaded programming language which means we
can develop multi-threaded program using Java.
• A multi-threaded program contains two or more parts that can run
concurrently and each part can handle a different task at the same
time making optimal use of the available resources specially when
your computer has multiple CPUs.
• Each part of such program is called a thread. So, threads are light-
weight processes within a process.
Prepared By [Link] PM, AP, IESCE EDULINE 2
Prepared By Mr. EBIN PM, AP, IESCE 1
OOPJ [Link]
STUDENTS
• Multiprocessing and multithreading, both are used to achieve
multitasking But we use multithreading than multiprocessing
because threads share a common memory area.
• They don't allocate separate memory area so saves memory, and
context-switching between the threads takes less time than
process.
• Java Multithreading is mostly used in games, animation etc..
• A thread is a lightweight sub process, a smallest unit of processing.
• It is a separate path of execution.
• They are independent, if there occurs exception in one thread, it
doesn't affect other threads.
Prepared By [Link] PM, AP, IESCE EDULINE 3
At least one process is required for each thread.
Prepared By [Link] PM, AP, IESCE EDULINE 4
Prepared By Mr. EBIN PM, AP, IESCE 2
OOPJ [Link]
STUDENTS
Advantages of Java Multithreading
It doesn't block the user because threads are independent and you
can perform multiple operations at same time.
You can perform many operations together so it saves time.
Threads are independent so it doesn't affect other threads if
exception occur in a single thread.
Note: At a time one thread is executed only.
Prepared By [Link] PM, AP, IESCE EDULINE 5
LIFE CYCLE OF THREAD
• A thread can be in one of the five states.
• According to sun, there is only 4 states in thread life cycle in java
new, runnable, non-runnable and terminated.
• There is no running state. But for better understanding the
threads, we can explain it in the 5 states.
New
Runnable
Running
Non-Runnable (Blocked)
Terminated
Prepared By [Link] PM, AP, IESCE EDULINE 6
Prepared By Mr. EBIN PM, AP, IESCE 3
OOPJ [Link]
STUDENTS
Life Cycle
Prepared By [Link] PM, AP, IESCE EDULINE 7
New - The thread is in new state if you create an instance of
Thread class but before the invocation of start() method.
Runnable - The thread is in runnable state after invocation of
start() method, but the thread scheduler has not selected it to be
the running thread.
Running - The thread is in running state if the thread scheduler
has selected it.
Non-Runnable (Blocked) - This is the state when the thread is still
alive, but is currently not eligible to run.
Terminated - A thread is in terminated or dead state when its
run() method exits.
Prepared By [Link] PM, AP, IESCE EDULINE 8
Prepared By Mr. EBIN PM, AP, IESCE 4
OOPJ [Link]
STUDENTS
A Running Thread transit to one of the non-runnable states,
depending upon the circumstances.
• Sleeping: The Thread sleeps for the specified amount of time.
• Blocked for I/O: The Thread waits for a blocking operation to
complete.
• Blocked for join completion: The Thread waits for completion of
another Thread.
• Waiting for notification: The Thread waits for notification another
Thread.
• Blocked for lock acquisition: The Thread waits to acquire the lock
of an object.
JVM executes the Thread, based on their priority and scheduling.
Prepared By [Link] PM, AP, IESCE EDULINE 9
CREATING THREAD
There are two ways to create a thread:
• By extending Thread class
• By implementing Runnable interface.
Extending Thread class:
• Thread class provide constructors and methods to create and
perform operations on a thread.
• Thread class extends Object class and implements Runnable
interface.
Prepared By [Link] PM, AP, IESCE EDULINE 10
Prepared By Mr. EBIN PM, AP, IESCE 5
OOPJ [Link]
STUDENTS
Commonly used Constructors of Thread class:
• Thread()
• Thread(String name)
• Thread(Runnable r)
• Thread(Runnable r, String name)
Prepared By [Link] PM, AP, IESCE EDULINE 11
Thread Methods - Following is the list of important methods
available in the 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 int getPriority() : returns the priority of the thread.
• public int setPriority(int priority) : changes the priority of the
thread.
Prepared By [Link] PM, AP, IESCE EDULINE 12
Prepared By Mr. EBIN PM, AP, IESCE 6
OOPJ [Link]
STUDENTS
• public String getName(): returns the name of the thread.
• public Thread currentThread() : returns the reference of currently
executing thread.
• public int getId() : returns the id of the thread.
• public [Link] getState() : returns the state of the thread.
• public boolean isAlive() : tests if the thread is alive.
• public void suspend() : is used to suspend the thread(depricated).
• public void resume() : is used to resume the suspended thread
• public void stop() : is used to stop the thread(depricated).
• public boolean isDaemon() : tests if the thread is a daemon thread.
Prepared By [Link] PM, AP, IESCE EDULINE 13
[Link]() & [Link]()
In Java’s multi-threading concept, start() and run() are the two
most important methods.
• When a program calls the start() method, a new thread is created
and then the run() method is executed.
• But if we directly call the run() method then no new thread will be
created and run() method will be executed as a normal method call
on the current calling thread itself and no multi-threading will take
place.
Prepared By [Link] PM, AP, IESCE EDULINE 14
Prepared By Mr. EBIN PM, AP, IESCE 7
OOPJ [Link]
STUDENTS
Let us understand it with an example:
Output
Prepared By [Link] PM, AP, IESCE EDULINE 15
start ()
when we call the start() method of our thread class instance, a
new thread is created with default name Thread-0 and then run()
method is called and everything inside it is executed on the newly
created thread.
run ()
when we called the run() method of our MyThread class, no new
thread is created and the run() method is executed on the current
thread i.e. main thread. Hence, no multi-threading took place.
The run() method is called as a normal function call.
Prepared By [Link] PM, AP, IESCE EDULINE 16
Prepared By Mr. EBIN PM, AP, IESCE 8
OOPJ [Link]
STUDENTS
Let us try to call run() method directly instead of start() method:
Output
Prepared By [Link] PM, AP, IESCE EDULINE 17
Difference
Prepared By [Link] PM, AP, IESCE EDULINE 18
Prepared By Mr. EBIN PM, AP, IESCE 9
OOPJ [Link]
STUDENTS
Implementing Runnable interface:
• The Runnable interface should be implemented by any class whose
instances are intended to be executed by a thread.
• Runnable interface have only one method named run().
public void run(): is used to perform action for a thread.
Steps to create a new Thread using Runnable :
• Create a Runnable implementer and implement run() method.
• Instantiate Thread class and pass the implementer to the Thread,
Thread has a constructor which accepts Runnable instance.
• Invoke start() of Thread instance, start internally calls run() of the
implementer. Invoking start(), creates a new Thread which executes
the code written in run().
Prepared By [Link] PM, AP, IESCE EDULINE 19
Thread Example by implementing Runnable interface
Prepared By [Link] PM, AP, IESCE EDULINE 20
Prepared By Mr. EBIN PM, AP, IESCE 10
OOPJ [Link]
STUDENTS
MAIN THREAD
Every java program has a main method. The main method is the
entry point to execute the program.
So, when the JVM starts the execution of a program, it creates a
thread to run it and that thread is known as the main thread.
Each program must contain at least one thread whether we are
creating any thread or not.
The JVM provides a default thread in each program.
A program can’t run without a thread, so it requires at least one
thread, and that thread is known as the main thread.
Prepared By [Link] PM, AP, IESCE EDULINE 21
If you ever tried to run a Java program with compilation errors you
would have seen the mentioning of main thread. Here is a simple
Java program that tries to call the non-existent getValue() method.
As you can see in the error when the program is executed, main
thread starts running and that has encountered a compilation
problem.
Prepared By [Link] PM, AP, IESCE EDULINE 22
Prepared By Mr. EBIN PM, AP, IESCE 11
OOPJ [Link]
STUDENTS
Properties
• It is the thread from which other
“child” threads will be spawned.
• Often, it must be the last
thread to finish execution
because it performs various
shutdown actions
Prepared By [Link] PM, AP, IESCE EDULINE 23
How to control Main thread
• The main thread is created automatically when our program is
started.
• To control it we must obtain a reference to it.
• This can be done by calling the method currentThread( ) which is
present in Thread class.
• This method returns a reference to the thread on which it is called.
• The default priority of Main thread is 5 and for all remaining user
threads priority will be inherited from parent to child.
Prepared By [Link] PM, AP, IESCE EDULINE 24
Prepared By Mr. EBIN PM, AP, IESCE 12
OOPJ [Link]
STUDENTS
Output
Prepared By Mr. EBIN PM, AP, IESCE EDULINE 25
• The program first creates a Thread object called 't' and assigns the
reference of current thread (main thread) to it. So now main
thread can be accessed via Thread object 't'.
• This is done with the help of currentThread() method of Thread
class which return a reference to the current running thread.
• The Thread object 't' is then printed as a result of which you see
the output Current Thread : Thread [main,5,main].
• The first value in the square brackets of this output indicates the
name of the thread, the name of the group to which the thread
belongs.
Prepared By [Link] PM, AP, IESCE EDULINE 26
Prepared By Mr. EBIN PM, AP, IESCE 13
OOPJ [Link]
STUDENTS
• The program then prints the name of the thread with the help of
getName() method.
• The name of the thread is changed with the help of setName()
method.
• The thread and thread name is then again printed.
• Then the thread performs the operation of printing first 10
numbers.
• When you run the program you will see that the system wait for
sometime after printing each number.
• This is caused by the statement [Link] (1000).
Prepared By [Link] PM, AP, IESCE EDULINE 27
CREATING MULTIPLE THREADS
EDULINE 28
Prepared By Mr. EBIN PM, AP, IESCE 14
OOPJ [Link]
STUDENTS
Output
ThreadA i = -1 ThreadA i = -4
ThreadB j=2 ThreadB j = 8
ThreadC k =1 ThreadC k =7
ThreadA i = -5
ThreadA i = -2
ThreadB j = 10
ThreadB j=4 ThreadC k =9
ThreadC k =3 Exiting ThreadA
ThreadA i = -3 Exiting ThreadB
ThreadB j=6 Exiting ThreadC
ThreadC k =5
Prepared By [Link] PM, AP, IESCE EDULINE 29
THREAD SYNCHRONIZATION
• When we start two or more threads within a program, there may
be a situation when multiple threads try to access the same
resource and finally they can produce unforeseen result due to
concurrency issues.
• For example, if multiple threads try to write within a same file then
they may corrupt the data because one of the threads can override
data or while one thread is opening the same file at the same time
another thread might be closing the same file.
Prepared By [Link] PM, AP, IESCE EDULINE 30
Prepared By Mr. EBIN PM, AP, IESCE 15
OOPJ [Link]
STUDENTS
• So there is a need to synchronize the action of multiple threads
and make sure that only one thread can access the resource at a
given point in time.
Following is the general form of the synchronized statement :
Syntax
synchronized(object identifier) {
// Access shared variables and other shared resources
}
Understanding the problem without Synchronization
• In this example, we are not using synchronization and creating
multiple threads that are accessing display method and produce
the random output.
Prepared By [Link] PM, AP, IESCE EDULINE 31
Eg.
In the above program, object fnew of class First is shared
by all the three running threads(ss, ss1 and ss2) to call the
shared method(void display). Hence the result is
nonsynchronized and such situation is called Race
condition
Prepared By [Link] PM, AP, IESCE EDULINE 32
Prepared By Mr. EBIN PM, AP, IESCE 16
OOPJ [Link]
STUDENTS
Synchronized Keyword
• To synchronize above program, we must synchronize access to the
shared display() method, making it available to only one thread at
a time. This is done by using keyword synchronized with display()
method.
• With a synchronized method, the lock is obtained for the duration
of the entire method.
• So if you want to lock the whole object, use a synchronized
method
synchronized void display (String msg)
Example : implementation of synchronized method
Prepared By [Link] PM, AP, IESCE EDULINE 33
Eg.
Prepared By [Link] PM, AP, IESCE EDULINE 34
Prepared By Mr. EBIN PM, AP, IESCE 17
OOPJ [Link]
STUDENTS
Using Synchronized block
• If we want to synchronize access to an object of a class or only a
part of a method to be synchronized then we can use synchronized
block for it.
• It is capable to make any part of the object and method
synchronized.
• With synchronized blocks we can specify exactly when the lock is
needed. If you want to keep other parts of the object accessible to
other threads, use synchronized block.
Example
• In this example, we are using synchronized block that will make the
display method available for single thread at a time.
Prepared By [Link] PM, AP, IESCE EDULINE 35
Eg.
Prepared By [Link] PM, AP, IESCE EDULINE 36
Prepared By Mr. EBIN PM, AP, IESCE 18
OOPJ [Link]
STUDENTS
Which is more preferred - Synchronized method or Synchronized
block?
• In Java, synchronized keyword causes a performance cost.
• A synchronized method in Java is very slow and can degrade
performance.
• So we must use synchronization keyword in java when it is
necessary else, we should use Java synchronized block that is used
for synchronizing critical section only.
Prepared By [Link] PM, AP, IESCE EDULINE 37
Thread suspend() method
• The suspend() method of thread class puts the thread from
running to waiting state.
• This method is used if you want to stop the thread execution and
start it again when a certain event occurs.
• This method allows a thread to temporarily cease execution.
• The suspended thread can be resumed using the resume()
method.
Syntax
public final void suspend()
Prepared By [Link] PM, AP, IESCE EDULINE 38
Prepared By Mr. EBIN PM, AP, IESCE 19
OOPJ [Link]
STUDENTS
Example
Prepared By [Link] PM, AP, IESCE EDULINE 39
Output
Prepared By [Link] PM, AP, IESCE EDULINE 40
Prepared By Mr. EBIN PM, AP, IESCE 20
OOPJ [Link]
STUDENTS
Thread resume() method
• The resume() method of thread class is only used with suspend()
method.
• This method is used to resume a thread which was suspended
using suspend() method.
• This method allows the suspended thread to start again.
Syntax
public final void resume()
Prepared By [Link] PM, AP, IESCE EDULINE 41
Example
Prepared By [Link] PM, AP, IESCE EDULINE 42
Prepared By Mr. EBIN PM, AP, IESCE 21
OOPJ [Link]
STUDENTS
Output
Prepared By [Link] PM, AP, IESCE EDULINE 43
Thread stop() method
• The stop() method of thread class terminates the thread
execution.
• Once a thread is stopped, it cannot be restarted by start()
method.
Syntax
public final void stop()
public final void stop(Throwable obj)
Prepared By [Link] PM, AP, IESCE EDULINE 44
Prepared By Mr. EBIN PM, AP, IESCE 22
OOPJ [Link]
STUDENTS
Example
Prepared By [Link] PM, AP, IESCE EDULINE 45
Prepared By Mr. EBIN PM, AP, IESCE 23
OOPJ [Link]
STUDENTS
MODULE 4
CHAPTER 3
EVENT HANDLING
Prepared By Mr. EBIN PM, AP, IESCE 1
EVENT
• Change in the state of an object is known as event i.e. event
describes the change in state of source.
• Events are generated as result of user interaction with the
graphical user interface components.
• For example, clicking on a button, moving the mouse, entering a
character through keyboard, selecting an item from list, scrolling
the page are the activities that causes an event to happen.
Types of Event
The events can be broadly classified into two categories:
Prepared By [Link] PM, AP, IESCE EDULINE 2
Prepared By Mr. EBIN PM, AP, IESCE 1
OOPJ [Link]
STUDENTS
Foreground Events
• Those events which require the direct interaction of user. They are
generated as consequences of a person interacting with the
graphical components in Graphical User Interface. For example,
clicking on a button, moving the mouse, entering a character
through keyboard, selecting an item from list, scrolling the page
etc.
Background Events
• Those events that require the interaction of end user are known as
background events. Operating system interrupts, hardware or
software failure, timer expires, an operation completion are the
example of background events.
Prepared By [Link] PM, AP, IESCE EDULINE 3
EVENT HANDLING
• Event Handling is the mechanism that controls the event and
decides what should happen if an event occurs.
• This mechanism have the code which is known as event handler
that is executed when an event occurs.
• Java Uses the Delegation Event Model to handle the events.
• This model defines the standard mechanism to generate and
handle the events.
• Let's have a brief introduction to this model.
Prepared By [Link] PM, AP, IESCE EDULINE 4
Prepared By Mr. EBIN PM, AP, IESCE 2
OOPJ [Link]
STUDENTS
The Delegation Event Model has the following key participants
namely:
Source - The source is an object on which event occurs. Source is
responsible for providing information of the occurred event to it's
handler. Java provide as with classes for source object.
Listener - It is also known as event handler. Listener is responsible
for generating response to an event. From java implementation
point of view the listener is also an object. Listener waits until it
receives an event. Once the event is received , the listener process
the event and then returns.
Prepared By [Link] PM, AP, IESCE EDULINE 5
• The benefit of this approach is that the user interface logic is
completely separated from the logic that generates the event.
• The user interface element is able to delegate the processing of an
event to the separate piece of code.
• In this model ,Listener needs to be registered with the source
object so that the listener can receive the event notification.
• This is an efficient way of handling the event because the event
notifications are sent only to those listener that want to receive
them.
Prepared By [Link] PM, AP, IESCE EDULINE 6
Prepared By Mr. EBIN PM, AP, IESCE 3
OOPJ [Link]
STUDENTS
How Events are handled
• A source generates an Event and send it to one or more listeners
registered with the source.
• Once event is received by the listener, they process the event and
then return.
• Events are supported by a number of Java packages, like [Link],
[Link] and [Link]
Prepared By [Link] PM, AP, IESCE EDULINE 7
Event classes and interface
Prepared By [Link] PM, AP, IESCE EDULINE 8
Prepared By Mr. EBIN PM, AP, IESCE 4
OOPJ [Link]
STUDENTS
Steps to handle events:
Implement appropriate interface in the class.
Register the component with the listener.
Prepared By [Link] PM, AP, IESCE EDULINE 9
Steps involved in event handling
The User clicks the button and the event is generated.
Now the object of concerned event class is created automatically
and information about the source and the event get populated
with in same object.
Event object is forwarded to the method of registered listener
class.
The method is now get executed and returns.
Prepared By [Link] PM, AP, IESCE EDULINE 10
Prepared By Mr. EBIN PM, AP, IESCE 5
OOPJ [Link]
STUDENTS
Points to remember about listener
• In order to design a listener class we have to develop some listener
interfaces.
• These Listener interfaces forecast some public abstract callback
methods which must be implemented by the listener class.
• If we do not implement the predefined interfaces then your class
can not act as a listener class for a source object.
Prepared By [Link] PM, AP, IESCE EDULINE 11
SOURCES OF EVENT
Prepared By Mr. EBIN PM, AP, IESCE EDULINE 12
Prepared By Mr. EBIN PM, AP, IESCE 6
OOPJ [Link]
STUDENTS
EVENT LISTENER INTERFACES
Prepared By Mr. EBIN PM, AP, IESCE EDULINE 13
Key Event Handling
Initial output of the program
Prepared By [Link] PM, AP, IESCE EDULINE 14
Prepared By Mr. EBIN PM, AP, IESCE 7
OOPJ [Link]
STUDENTS
After the user enters a character into the text field, the same
character is displayed in the label beside the text field as shown in
the below image:
Prepared By [Link] PM, AP, IESCE EDULINE 15
Prepared By Mr. EBIN PM, AP, IESCE 8
OOPJ [Link]
STUDENTS
MODULE 5
CHAPTER 2
JDBC
Prepared By Mr. EBIN PM, AP, IESCE 1
Java DataBase Connectivity (JDBC)
JDBC stands for Java Database Connectivity, which is a standard
Java API for database-independent connectivity between the Java
programming language and a wide range of databases.
The JDBC library includes APIs for each of the tasks mentioned
below that are commonly associated with database usage.
• Making a connection to a database
• Creating SQL or MySQL statements
• Executing SQL or MySQL queries in the database
• Viewing & Modifying the resulting records
Prepared By [Link] PM, AP, IESCE EDULINE 2
Prepared By Mr. EBIN PM, AP, IESCE 1
OOPJ [Link]
STUDENTS
JDBC Architecture
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.
The JDBC API uses a driver manager and database-specific drivers
to provide transparent connectivity to heterogeneous databases.
The JDBC driver manager ensures that the correct driver is used to
access each data source.
Prepared By [Link] PM, AP, IESCE EDULINE 3
• Following is the architectural diagram, which shows the location of
the driver manager with respect to the JDBC drivers and the Java
application
Prepared By [Link] PM, AP, IESCE EDULINE 4
Prepared By Mr. EBIN PM, AP, IESCE 2
OOPJ [Link]
STUDENTS
Java Database Connectivity with 5 Steps
There are 5 steps to connect any java application with the
database using JDBC. These steps are as follows:
1. Register the Driver class
2. Create connection
3. Create statement
4. Execute queries
5. Close connection
Prepared By [Link] PM, AP, IESCE EDULINE 5
The forName() method is used to register the driver class.
The getConnection() method of DriverManager class is used to
establish connection with the database
The createStatement() method of Connection interface is used to
create statement. The object of statement is responsible to execute
queries with the database.
The executeQuery() method of Statement interface is used to
execute queries to the database. This method returns the object of
ResultSet that can be used to get all the records of a table.
By closing connection object statement and ResultSet will be
closed automatically. The close() method of Connection interface is
used to close the connection.
Prepared By [Link] PM, AP, IESCE EDULINE 6
Prepared By Mr. EBIN PM, AP, IESCE 3
OOPJ [Link]
STUDENTS
Java Database Connectivity with MySQL
• To connect Java application with the MySQL database, we need to
follow 5 following steps.
• In this example we are using MySql as the database. So we need to
know following informations for the mysql database:
1. Driver class: The driver class for the mysql database is
[Link].
2. Connection URL: The connection URL for the mysql database is
jdbc:mysql://localhost:3306/sonoo where jdbc is the API, mysql is
the database, localhost is the server name on which mysql is
running, we may also use IP address, 3306 is the port number
and sonoo is the database name. We may use any database, in
such case, we need to replace the sonoo with our database
name.
Prepared By [Link] PM, AP, IESCE EDULINE 7
3. Username: The default username for the mysql database is root.
4. Password: It is the password given by the user at the time of
installing the mysql database. In this example, we are going to use
root as the password.
Let's first create a table in the mysql database, but before creating
table, we need to create database first.
create database sonoo;
use sonoo;
create table emp(id int(10),name varchar(40),age int(3));
Prepared By [Link] PM, AP, IESCE EDULINE 8
Prepared By Mr. EBIN PM, AP, IESCE 4
OOPJ [Link]
STUDENTS
Example to Connect Java Application with mysql database
This example will
fetch all the records of
emp table.
Prepared By [Link] PM, AP, IESCE EDULINE 9
Creating a sample MySQL database
create database SampleDB;
use SampleDB;
CREATE TABLE `users` (
`user_id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(45) NOT NULL,
`password` varchar(45) NOT NULL,
`fullname` varchar(45) NOT NULL,
`email` varchar(45) NOT NULL,
PRIMARY KEY (`user_id`)
);
Prepared By [Link] PM, AP, IESCE EDULINE 10
Prepared By Mr. EBIN PM, AP, IESCE 5
OOPJ [Link]
STUDENTS
Connecting to the database
String dbURL = "jdbc:mysql://localhost:3306/sampledb";
String username = "root";
String password = "secret";
try {
Connection conn = [Link](dbURL, username,
password);
if (conn != null) {
[Link]("Connected");
}
} catch (SQLException ex)
{
[Link]();
}
Prepared By [Link] PM, AP, IESCE EDULINE 11
• Once the connection was established, we have a Connection object
which can be used to create statements in order to execute SQL queries.
• In the above code, we have to close the connection explicitly after finish
working with the database:
[Link]();
INSERT Statement Example
Let’s write code to insert a new record into the table Users with
following details:
username: bill
password: secretpass
fullname: Bill Gates
email: [Link]@[Link]
Prepared By [Link] PM, AP, IESCE EDULINE 12
Prepared By Mr. EBIN PM, AP, IESCE 6
OOPJ [Link]
STUDENTS
String sql = "INSERT INTO Users (username, password, fullname,
email) VALUES (?, ?, ?, ?)";
PreparedStatement statement = [Link](sql);
[Link](1, "bill");
[Link](2, "secretpass");
[Link](3, "Bill Gates");
[Link](4, "[Link]@[Link]");
int rowsInserted = [Link]();
if (rowsInserted > 0) {
[Link]("A new user was inserted successfully!");
}
Prepared By [Link] PM, AP, IESCE EDULINE 13
SELECT Statement Example
Output
User #1: bill - secretpass - Bill Gates - [Link]@[Link]
Prepared By [Link] PM, AP, IESCE EDULINE 14
Prepared By Mr. EBIN PM, AP, IESCE 7
OOPJ [Link]
STUDENTS
UPDATE Statement Example
Prepared By [Link] PM, AP, IESCE EDULINE 15
DELETE Statement Example
• The following code snippet will delete a record whose username
field contains “bill”
Prepared By [Link] PM, AP, IESCE EDULINE 16
Prepared By Mr. EBIN PM, AP, IESCE 8
OOPJ [Link]
STUDENTS
MODULE 5
Graphical User Interface & Database
support of Java
CHAPTER 1
SWING
Prepared By Mr. EBIN PM, AP, IESCE 1
SWING FUNDAMENTALS
• Java Swing is a GUI Framework that contains a set of classes to
provide more powerful and flexible GUI components than AWT.
• Swing provides the look and feel of modern Java GUI.
• Swing library is an official Java GUI tool kit released by Sun
Microsystems.
• It is used to create graphical user interface with Java.
• Swing classes are defined in [Link] package and its sub-
packages.
• Java Swing provides platform-independent and lightweight
components.
Prepared By [Link] PM, AP, IESCE EDULINE 2
Prepared By Mr. EBIN PM, AP, IESCE 1
OOPJ [Link]
STUDENTS
Java Swing is a part of Java Foundation Classes (JFC) that is used to
create window-based applications.
It is built on the top of AWT (Abstract Windowing Toolkit) API and
entirely written in java
JFC
• The Java Foundation Classes (JFC) are a set of GUI components which
simplify the development of desktop applications.
The [Link] package provides classes for java swing API such as
JButton, JTextField, JTextArea, JRadioButton, JCheckbox, JMenu,
JColorChooser etc.
Prepared By [Link] PM, AP, IESCE EDULINE 3
Features of Swing
Platform Independent:
• It is platform independent, the swing components that are used to
build the program are not platform specific.
• It can be used at any platform and anywhere.
Lightweight:
• Swing components are lightweight which helps in creating the UI
lighter.
• Swings component allows it to plug into the operating system user
interface framework that includes the mappings for screens or
device and other user interactions like key press and mouse
movements.
Prepared By [Link] PM, AP, IESCE EDULINE 4
Prepared By Mr. EBIN PM, AP, IESCE 2
OOPJ [Link]
STUDENTS
Plugging:
• It has a powerful component that can be extended to provide the
support for the user interface that helps in good look and feel to
the application.
• It refers to the highly modular-based architecture that allows it to
plug into other customized implementations and framework for
user interfaces.
Manageable: It is easy to manage and configure. Its mechanism and
composition pattern allows changing the settings at run time as
well. The uniform changes can be provided to the user interface
without doing any changes to application code.
Prepared By [Link] PM, AP, IESCE EDULINE 5
MVC:
• They mainly follows the concept of MVC that is Model View
Controller.
• With the help of this, we can do the changes in one component
without impacting or touching other components.
• It is known as loosely coupled architecture as well.
Customizable:
• Swing controls can be easily customized. It can be changed and the
visual appearance of the swing component application is
independent of its internal representation.
Rich Controls :
• Swing provides a rich set of advanced controls like Tree,
TabbedPane, slider, colorpicker, and table controls.
Prepared By [Link] PM, AP, IESCE EDULINE 6
Prepared By Mr. EBIN PM, AP, IESCE 3
OOPJ [Link]
STUDENTS
Difference between AWT and Swing
Prepared By [Link] PM, AP, IESCE EDULINE 7
Hierarchy of Java Swing classes
Prepared By [Link] PM, AP, IESCE EDULINE 8
Prepared By Mr. EBIN PM, AP, IESCE 4
OOPJ [Link]
STUDENTS
The Model-View-Controller Architecture
• Swing uses the model-view-controller architecture (MVC) as the
fundamental design behind each of its components
• Essentially, MVC breaks GUI components into three elements. Each
of these elements plays a crucial role in how the component
behaves.
• The Model-View-Controller is a well known software architectural
pattern ideal to implement user interfaces on computers by
dividing an application intro three interconnected parts
Prepared By [Link] PM, AP, IESCE EDULINE 9
• Main goal of Model-View-Controller, also known as MVC, is to
separate internal representations of an application from the ways
information are presented to the user.
• Initially, MVC was designed for desktop GUI applications but it’s
quickly become an extremely popular pattern for designing web
applications too.
• MVC pattern has the three components :
Model that manages data, logic and rules of the application
View that is used to present data to user
Controller that accepts input from the user and converts it to
commands for the Model or View.
Prepared By [Link] PM, AP, IESCE EDULINE 10
Prepared By Mr. EBIN PM, AP, IESCE 5
OOPJ [Link]
STUDENTS
• the MVC pattern defines the interactions between these three
components like you can see in the following figure :
Prepared By [Link] PM, AP, IESCE EDULINE 11
• The Model receives commands and data from the Controller. It
stores these data and updates the View.
• The View lets to present data provided by the Model to the user.
• The Controller accepts inputs from the user and converts it to
commands for the Model or the View.
Prepared By [Link] PM, AP, IESCE EDULINE 12
Prepared By Mr. EBIN PM, AP, IESCE 6
OOPJ [Link]
STUDENTS
COMPONENTS & CONTAINERS
• A component is an independent visual control, such as a push
button or slider.
• A container holds a group of components. Thus, a container is a
special type of component that is designed to hold other
components.
• Swing components inherit from the [Link] class,
which is the root of the Swing component hierarchy.
Prepared By [Link] PM, AP, IESCE EDULINE 13
COMPONENTS
• Swing components are derived from the JComponent class.
• JComponent provides the functionality that is common to all
components. For example, JComponent supports the pluggable
look and feel.
• JComponent inherits the AWT classes Container and Component.
Thus, a Swing component is built on and compatible with an AWT
component.
• All of Swing’s components are represented by classes defined
within the package [Link].
• The following table shows the class names for Swing components
Prepared By [Link] PM, AP, IESCE EDULINE 14
Prepared By Mr. EBIN PM, AP, IESCE 7
OOPJ [Link]
STUDENTS
• JApplet
• JColorChooser • JTogglebutton
• JDialog • JViewport
• JFrame • JButton
• JLayeredPane • JComboBox
• JMenuItem • JEditorPane
• JPopupMenu • JInternalFrame
• JRootPane • JList
• JSlider • JOptionPane
• JTable • JProgressBar
Prepared By [Link] PM, AP, IESCE EDULINE 15
• Notice that all component classes begin with the letter J.
• For example, the class for a label is JLabel; the class for a push
button is JButton; and the class for a scroll bar is JScrollBar
CONTAINERS
• Swing defines two types of containers. The first are top-level
containers: JFrame, JApplet, JWindow, and JDialog. These
containers do not inherit JComponent. They inherit the AWT
classes Component and Container.
• The second type container are lightweight and the top-level
containers are heavyweight. This makes the top-level containers a
special case in the Swing component library.
Prepared By [Link] PM, AP, IESCE EDULINE 16
Prepared By Mr. EBIN PM, AP, IESCE 8
OOPJ [Link]
STUDENTS
In Java, Containers are divided into two types as shown below:
Prepared By [Link] PM, AP, IESCE EDULINE 17
Following is the list of commonly used containers while designed
GUI using SWING.
Prepared By [Link] PM, AP, IESCE EDULINE 18
Prepared By Mr. EBIN PM, AP, IESCE 9
OOPJ [Link]
STUDENTS
Swing Example : A window on the screen.
Output
Prepared By [Link] PM, AP, IESCE EDULINE 19
EVENT HANDLING IN SWINGS
• The functionality of Event Handling is what is the further step if an
action performed.
• Java foundation introduced “Delegation Event Model” i.e describes
how to generate and control the events.
• The key elements of the Delegation Event Model are as source and
listeners.
• The listener should have registered on source for the purpose of
alert notifications.
• All GUI applications are event-driven
Prepared By [Link] PM, AP, IESCE EDULINE 20
Prepared By Mr. EBIN PM, AP, IESCE 10
OOPJ [Link]
STUDENTS
Java Swing event object
• When something happens in the application, an event object is
created.
• For example, when we click on the button or select an item from a
list.
• There are several types of events, including ActionEvent, TextEvent,
FocusEvent, and ComponentEvent.
• Each of them is created under specific conditions.
• An event object holds information about an event that has
occurred.
Prepared By [Link] PM, AP, IESCE EDULINE 21
SWING LAYOUT MANAGERS
• Layout refers to the arrangement of components within the
container.
• Layout is placing the components at a particular position within the
container. The task of laying out the controls is done automatically
by the Layout Manager.
• The layout manager automatically positions all the components
within the container.
• Even if you do not use the layout manager, the components are
still positioned by the default layout manager. It is possible to lay
out the controls by hand, however, it becomes very difficult
Prepared By [Link] PM, AP, IESCE EDULINE 22
Prepared By Mr. EBIN PM, AP, IESCE 11
OOPJ [Link]
STUDENTS
• Java provides various layout managers to position the controls.
Properties like size, shape, and arrangement varies from one layout
manager to the other.
• There are following classes that represents the layout managers:
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link] etc.
Prepared By [Link] PM, AP, IESCE EDULINE 23
BorderLayout GridLayout
Prepared By [Link] PM, AP, IESCE 24
Prepared By Mr. EBIN PM, AP, IESCE 12
OOPJ [Link]
STUDENTS
FlowLayout BoxLayout
Prepared By [Link] PM, AP, IESCE 25
CardLayout GroupLayout
Prepared By [Link] PM, AP, IESCE 26
Prepared By Mr. EBIN PM, AP, IESCE 13
OOPJ [Link]
STUDENTS
Example of JButton
Prepared By [Link] PM, AP, IESCE EDULINE 27
Example of JTextField
Prepared By [Link] PM, AP, IESCE EDULINE 28
Prepared By Mr. EBIN PM, AP, IESCE 14
OOPJ [Link]
STUDENTS
Example of Jlabel - It is used for placing text in a box
Prepared By [Link] PM, AP, IESCE EDULINE 29
Prepared By Mr. EBIN PM, AP, IESCE 15