0% found this document useful (0 votes)
26 views175 pages

OOP JAVA M4 Ktunotes - in

Uploaded by

Sneha Tiwari
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)
26 views175 pages

OOP JAVA M4 Ktunotes - in

Uploaded by

Sneha Tiwari
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/ 175

CST 205 Object Oriented Programming using Java

(As per KTU 2019 Syllabus)

Module 4

Downloaded from Ktunotes.in


Downloaded from Ktunotes.in
Multithreaded Programming
Definition of thread
A thread is a single sequential flow of
control within a program.

The real excitement surrounding


threads is not about a single
sequential thread.

Rather, it's about the use of multiple


threads running at the same time
and performing different tasks in a
single program

Threads are lightweight processes


within a process.
Downloaded from Ktunotes.in
A single threaded program
class ABC
{
….
begin
public void main(..)
{ body
… end
..
}
} Downloaded from Ktunotes.in
4
A Multithreaded Program

Main Thread

start
start start

Thread Thread
A Thread B
C

Threads may switch or exchange data/results


Downloaded from Ktunotes.in
5
Multithreaded Server: For Serving
Multiple Clients Concurrently

Client 1 Process Server Process


Server
Threads
■ Internet

Client 2 Process

Downloaded from Ktunotes.in


6
Web/Internet Applications:
Serving Many Users Simultaneously
PC client

Internet
Server
Local Area Network

PDA
Downloaded from Ktunotes.in
7
Multithreaded programming
● Java is a multithreaded programming language
● A thread is an independent path of execution within a program, most of the
programs are single threaded
● Multithreading refers to two or more tasks executing concurrently within a single
program.
● Many threads can run concurrently within a program.
● Every thread in Java is created and controlled by the java.lang.Thread class.
● A Java program can have many threads, and these threads can run concurrently,
either asynchronously or synchronously.

Downloaded from Ktunotes.in


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.


Downloaded from Ktunotes.in
9
Java Thread Support
■ Java has built in thread support for Multithreading
■ Synchronization
■ Thread Scheduling
■ Inter-Thread Communication:
■ currentThread start setPriority
■ yield run getPriority
■ sleep stop suspend
■ resume
■ Java Garbage Collector is a low-priority thread.
Downloaded from Ktunotes.in
10
Life Cycle of a Thread

Downloaded from Ktunotes.in


States of the thread life cycle
1. Newborn : When a thread is created (by new statement ) but not yet to run, it is
called in Newborn state. In this state, the local data members are allocated and
initialized.
2. Runnable : The Runnable state means that a thread is ready to run and is
awaiting for the control of the processor, or in other words, threads are in this
state in a queue and wait their turns to be executed.
3. Running : Running means that the thread has control of the processor, its code
is currently being executed and thread will continue in this state until it get
preempted by a higher priority thread, or until it relinquishes control.
4. Blocked : A thread is Blocked means that it is being prevented from the
Runnable ( or Running) state and is waiting for some event in order for it to
reenter the scheduling queue.
5. Terminated (Dead) : A thread is Dead when it finishes its execution or is stopped
(killed) by another thread.
Downloaded from Ktunotes.in
Transitions from running state
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.

Downloaded from Ktunotes.in


Thread Priorities
● Every Java thread has a priority that helps the operating system determine
the order in which threads are scheduled.
● Java thread priorities are in the range between MIN_PRIORITY (a constant of
1) and MAX_PRIORITY (a constant of 10).
● Default thread priority is NORM_PRIORITY (a constant of 5).
● Threads with higher priority are more important to a program and should be
allocated processor time before lower-priority threads.
● Thread priorities cannot guarantee the order in which threads execute and
are very much platform dependent.

Downloaded from Ktunotes.in


Main Thread
● When a Java program starts up, one thread begins running immediately.
● This is usually called the main thread of our program, because it is the one
that is executed when our program begins.
● 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
● The main thread is created automatically when our program is started.
● To control it we must obtain a reference to it 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.

Downloaded from Ktunotes.in


Flow diagram of main thread

Downloaded from Ktunotes.in


Thread creation in Java
There are two ways to create a thread:

1. By extending Thread class [ java.lang.Thread ]


2. By implementing Runnable interface. [ java.lang.Runnable ]

What is the need for this dual option?

Remember - Java does not support multiple inheritance

Downloaded from Ktunotes.in


Thread creation in Java
1. Create a class that extends the Thread class
2. Create a class that implements the Runnable
interface
Thread Runnable Thread

MyThread MyClass

(objects are threads) (objects with run() body)


[a] [b]

Downloaded from Ktunotes.in


18
Create a Thread by Extending a Thread Class
Provides more flexibility in handling multiple threads created using available
methods in Thread class.

Create a new class that extends Thread class using the following steps.

● Step 1 - You will need to override run( ) method available in Thread class.
● This method provides an entry point for the thread
● Syntax of run() method − public void run( )

● Step 2 - Once Thread object is created, you can start it by calling start()
method, which executes a call to run( ) method.
● Syntax of start() method − void start( );

Downloaded from Ktunotes.in


Downloaded from Ktunotes.in
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.

Commonly used Constructors of Thread class:

• Thread()

• Thread(String name)

• Thread(Runnable r)

• Thread(Runnable r, String name)

Note: String argument is to assign a thread name.


Downloaded from Ktunotes.in
Thread class methods
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 static void sleep(long milliseconds) : Causes the currently executing
thread to sleep 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.

Downloaded from Ktunotes.in


Thread class methods
• 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 Thread.State 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. Daemon thread
is a low priority thread (in context of JVM) that runs in background to perform tasks
such as garbage collection (gc) etc., they do not prevent the JVM from exiting (even if
the daemon thread itself is running) when all the user threads (non-daemon threads)
finish their execution
Downloaded from Ktunotes.in
Thread.start() & Thread.run()
● In Java’s multithreading 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 multithreading will take place.

Downloaded from Ktunotes.in


Thread.start() & Thread.run()

Downloaded from Ktunotes.in


Thread.start() & Thread.run()

Downloaded from Ktunotes.in


Thread.start() & Thread.run()

Downloaded from Ktunotes.in


By Implementing a Runnable Interface
If the class is intended to be executed as a thread then implement Runnable
interface.

Step 1 - implement a run() method provided by a Runnable interface. This method


provides an entry point for the thread. [ public void run( ) ]

Step 2 - As a second step, you will instantiate a Thread object using the following
constructor − Thread(Runnable threadObj, String threadName);

- threadObj is an instance of a class that implements the Runnable interface.


- threadName is the name given to the new thread[optional].

Step 3 - Once a Thread object is created, you can start it by calling start() method,
which executes a call to run( ) method. [ void start(); ]

Downloaded from Ktunotes.in


Downloaded from Ktunotes.in
1st method: Extending Thread
class
■ Create a class by extending Thread class and override
run() method:
class MyThread extends Thread
{
public void run()
{
// thread body of execution
}
}
■ Create a thread:
MyThread thr1 = new MyThread();
■ Start Execution of threads:
thr1.start();
■ Create and Execute:
new MyThread().start();
Downloaded from Ktunotes.in
30
An example
class MyThread extends Thread {
public void run() {
System.out.println(" this thread is running ... ");
}
}

class ThreadEx1 {
public static void main(String [] args ) {
MyThread t = new MyThread();
t.start();
}
}
Downloaded from Ktunotes.in
31
2nd method: Threads by
implementing Runnable interface
■ Create a class that implements the interface Runnable and
override run() method:
class MyThread implements Runnable
{
.....
public void run()
{
// thread body of execution
}
}
■ Creating Object:
MyThread myObject = new MyThread();
■ Creating Thread Object:
Thread thr1 = new Thread( myObject );
■ Start Execution:
thr1.start();
Downloaded from Ktunotes.in
32
An example
class MyThread implements Runnable {
public void run() {
System.out.println(" this thread is running ... ");
}
}

class ThreadEx2 {
public static void main(String [] args ) {
Thread t = new Thread(new MyThread());
t.start();
}
}
Downloaded from Ktunotes.in
33
Creating Multiple Threads
● This can be done by creating the instances of the classes which are either
extending Thread class or implementing runnable interface.
● TODO: Run a simple program which creates multiple threads and identify the
maximum number of threads possible from your program.
● Join method can join the newly created thread with main thread

Downloaded from Ktunotes.in


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.
• 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 :
synchronized(object identifier)
{
// Access shared variables and other shared resources
} Downloaded from Ktunotes.in
Synchronization
● The keyword synchronized is used by which method (s) or block of
statements can be made protected from the simultaneous access.

Downloaded from Ktunotes.in


Synchronization
● When two or more threads want to (W)access a shared resource, ensure only
one thread has access to that resource at a time to avoid raise condition
● The keyword synchronized is used by which method (s) or block of
statements can be made protected from the simultaneous access.
● The entire time that a thread is inside of a synchronized method, all other
threads that try to call any other synchronized method on the same instance
have to wait.
● 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.

Downloaded from Ktunotes.in


Downloaded from Ktunotes.in
Suspending Thread
• 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()

Downloaded from Ktunotes.in


Suspending Thread

Downloaded from Ktunotes.in


Resuming Thread
• 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()

Downloaded from Ktunotes.in


Resuming Thread

Downloaded from Ktunotes.in


Terminating a Thread
• 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)

Downloaded from Ktunotes.in


Terminating a Thread

Downloaded from Ktunotes.in


Inter-thread Communication
The first is through commonly shared data. All the threads in the same program share the same
memory space.

The second way for threads to communicate is by using thread control methods.

● suspend ( ): A thread can suspend itself and wait till another thread resume it.
● resume ( ): A thread can wake up other waiting thread
● join ( ) :This method can be used for the caller thread to wait for the completion of called thread.

The third way for threads to communicate is the use of three methods; wait(), notify(), and notifyAll();
these are defined in class Object of package java.lang.

● wait ( ): tells the calling thread to give up the monitor and make the calling thread wait until either
a time out occurs or another thread call the same thread's notify() or notifyAll() method.
● notify ( ): will wake up the only one (first) waiting thread called wait() on the same object.
● notifyAll( ): will wake up all the threads that have been called wait( ) on the same object.

Downloaded from Ktunotes.in


Producer Consumer Problem

Downloaded from Ktunotes.in


Strings
• 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.

Downloaded from Ktunotes.in


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:
String s1="Hello";
String s2="Hello"; //It doesn't create a new instance

Downloaded from Ktunotes.in


Create a string object
String s1="Hello";
String s2="Hello"; //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
"Hello" in string constant pool, that is why it will create a new
Object.
• After that it will find the string with the value "Hello" 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".
● string constant pool makes Java more memory efficient (because no new objects
are created if it exists already in the string constant pool).
● Also it makes string literals thread safe.
Downloaded from Ktunotes.in
Create a string object
2. By using 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) in 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).

Downloaded from Ktunotes.in


Create a string object
2. By using 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) in 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).

Downloaded from Ktunotes.in


String sample

Downloaded from Ktunotes.in


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
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.
Downloaded from Ktunotes.in
STRING CONSTRUCTORS
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

Downloaded from Ktunotes.in


STRING CONSTRUCTORS
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.

Downloaded from Ktunotes.in


STRING CONSTRUCTORS
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.

Downloaded from Ktunotes.in


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 value.length;
}
Signature - The signature of the string length() method is given
below:
public int length()

Downloaded from Ktunotes.in


STRING LENGTH

Downloaded from Ktunotes.in


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

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

Downloaded from Ktunotes.in


STRING COMPARISON

Downloaded from Ktunotes.in


STRING COMPARISON
2. String compare by == operator
• The = = operator compares references not values.

Downloaded from Ktunotes.in


STRING COMPARISON
3. 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

Downloaded from Ktunotes.in


STRING SEARCHING
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.

Signature
• The signature of string contains() method is given below:
public boolean contains(CharSequence sequence)

Internal implementation
public boolean contains(CharSequence s)
{
return indexOf(s.toString()) > -1;
}

Downloaded from Ktunotes.in


STRING SEARCHING
public boolean contains(CharSequence sequence)

Downloaded from Ktunotes.in


STRING SEARCHING
public boolean contains(CharSequence sequence)

Downloaded from Ktunotes.in


STRING SEARCHING
The contains() method searches case sensitive char sequence.
If the argument is not case sensitive, it returns false. Let's see an example below.

Downloaded from Ktunotes.in


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.
• The signature of string charAt() method is given below:

public char charAt(int index)

Downloaded from Ktunotes.in


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.

Downloaded from Ktunotes.in


charAt() example
• This example counts the frequency of ‘t’ in given string

Downloaded from Ktunotes.in


MODIFY STRINGS
• The java string replace() method returns a string replacing all the old char or
CharSequence to new char or CharSequence.
• There are two type of replace methods in java string.
public String replace(char oldChar, char newChar)
public String replace(CharSequence target, CharSequence replacement)
• The second replace method is added since JDK 1.5.
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=s1.replace('a','e');
System.out.println(replaceString);
}}
Output: jeve is e very good lenguege
Downloaded from Ktunotes.in
MODIFY STRINGS
• 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 Pattern.compile(regex).matcher(this).replaceAll(replacement);
}
Signature
public String replaceAll(String regex, String replacement)

Regex: Regular Expression


A regular expression is a sequence of characters that define a search pattern. Usually such
patterns are used by string-searching algorithms for "find" or "find and replace" operations
on strings, or for input validation.
Downloaded from Ktunotes.in
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=s1.replaceAll("a","e");//replaces all occurrences
of "a" to "e"
System.out.println(replaceString);
}
}

Output: jeve is e very good lenguege

Downloaded from Ktunotes.in


String replaceAll() example: replace word
• Let's see an example to replace all the occurrences of single word or set of words.

Downloaded from Ktunotes.in


String replaceAll() example: replace whitespace
• Let's see an example to replace all the occurrences of whitespaces

Downloaded from Ktunotes.in


STRING VALUE OF METHOD
• 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" : obj.toString();
}

Downloaded from Ktunotes.in


STRING VALUE OF METHOD
• 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)

Downloaded from Ktunotes.in


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.

Downloaded from Ktunotes.in


valueOf() Method Example

Downloaded from Ktunotes.in


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.

Downloaded from Ktunotes.in


Immutable String in Java
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.

Downloaded from Ktunotes.in


Immutable String in Java
• 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 explicitly assign it to the reference variable, it will refer to "Sachin Tendulkar"
object. For example:

Downloaded from Ktunotes.in


Why string objects are immutable in java
• In Java, String is a final and immutable class, which makes it
the most special. It cannot be inherited, and once created, we
can not alter the object.

• Because java uses the concept of string pool to save memory.


• Suppose there are 5 reference variables,all refers 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.
Downloaded from Ktunotes.in
String and StringBuffer
Java String class objects are immutable.
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.

Downloaded from Ktunotes.in


StringBuffer, StringBuilder
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.

Important constructors of StringBuffer

Downloaded from Ktunotes.in


StringBuffer append() method
append() method is used to add contents at the end of the current string

Downloaded from Ktunotes.in


StringBuffer insert() method
append() method is used to add contents at a particular location(index)

Downloaded from Ktunotes.in


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

Downloaded from Ktunotes.in


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

Downloaded from Ktunotes.in


StringBuffer reverse() method
The reverse() method of StringBuffer class reverses the current string.

Downloaded from Ktunotes.in


COLLECTIONS IN JAVA
● The java.util package contains one of Java’s most powerful subsystems:
● The Collections Framework.
● The Collections Framework is a sophisticated hierarchy of interfaces and classes that
provide state-of-the-art technology(best possible technology) for managing groups of
objects.

● 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 framework provides many interfaces (Set, List, Queue, Deque) and
classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet,
TreeSet).
Downloaded from Ktunotes.in
Interfaces & Classes in Collection Framework

Downloaded from Ktunotes.in


Collections Overview
● The Java Collections Framework standardizes the way in which groups of objects are
handled by our programs.
● The entire Collections Framework is built upon a set of standard interfaces.
● Mechanisms were added that allow the integration of standard arrays into the
Collections Framework.

Downloaded from Ktunotes.in


Collections Overview(contd.)
The Collections Framework was designed to meet several goals.
● – First, the framework had to be high-performance. The implementations for the
fundamental collections (dynamic arrays, linked lists, trees, and hash tables) are highly
efficient.
● – Second, the framework had to allow different types of collections to work in a similar
manner and with a high degree of interoperability.
● – Third, extending and/or adapting a collection had to be easy.

Downloaded from Ktunotes.in


Collections Overview(contd.)
• Algorithms are an important part of the collection mechanism.
– Algorithms operate on collections and are defined as static methods within the Collections
class.
– The algorithms provide a standard means of manipulating collections.
• Java Collections Framework provides algorithm implementations that are commonly used
such as sorting, searching etc.
– void sort(List list)
– int binarySearch(List list, Object value)

Downloaded from Ktunotes.in


Collections Overview(contd.)
● Another item closely associated with the Collections Framework is the Iterator
interface.
● – An iterator offers a general-purpose, standardized way of accessing the elements
within a collection, one at a time.
● – An iterator provides a means of enumerating the contents of a collection.
● – Because each collection implements Iterator, the elements of any collection class
can be accessed through the methods defined by Iterator

Downloaded from Ktunotes.in


Collections Overview(contd.)
• The framework defines several map interfaces and classes.
– Maps store key/value pairs.
• Amap cannot contain duplicate keys.
• Although maps are part of the Collections Framework, they are not “collections” in the
strict use of the term

Downloaded from Ktunotes.in


Recent Changes to Collections
Collections Framework underwent a fundamental change that significantly increased its
power and streamlined its use.
– The changes were caused by the addition of
• generics
• autoboxing/unboxing, and
• for-each style for loop.

Downloaded from Ktunotes.in


Recent Changes to Collections
Generics add the one feature : type safety.
– With generics, it is possible to explicitly state the type of data being stored, and run-time
type mismatch errors can be avoided.
Autoboxing/unboxing facilitates the storing of primitive types in collections.
• IN THE PAST, if we wanted to store a primitive value, such as an int, in a collection, we
had to manually box it into its type wrapper.
• When the value was retrieved, it needed to be manually unboxed (by using an explicit
cast) into its proper primitive type.
– Because of autoboxing/unboxing, Java can automatically perform the proper boxing and
unboxing needed when storing or retrieving primitive types.

Downloaded from Ktunotes.in


COLLECTION FRAMEWORK INTERFACES

Downloaded from Ktunotes.in


Collection interface
• Collection interface helps to work with group of objects
• The Collection interface is at the top of collections hierarchy.
• Collection interface is the foundation upon which the Collections Framework is built
– because it must be implemented by any class that defines a collection.
• Collection is a generic interface that has this declaration: interface Collection<E>
– Here, E specifies the type of objects that the collection will hold.
• Collection extends the Iterable interface.
– This means that all collections can be cycled through by use of the for-each style for loop.

Downloaded from Ktunotes.in


Collection interface

Downloaded from Ktunotes.in


Collection interface

Downloaded from Ktunotes.in


Collection interface (contd.)
• We can check whether a collection contains a specific object by calling contains( ).
• To check whether one collection contains all the members of another, call containsAll( ).
• To determine whether a collection is empty call isEmpty().
• The number of elements currently held in a collection can be determined by calling size( ).
• The toArray( ) methods return an array that contains the elements stored in the invoking
collection.
Object[ ] toArray( ) returns an array of Object.
<T> T[ ] toArray(T array[ ]) returns an array of elements that have the same type as the
array specified as a parameter.

Downloaded from Ktunotes.in


Collection interface (contd.)
Two collections can be compared whether they are equal or not by calling equals( ).
The precise meaning of “equality” may differ from collection to collection.
– equals( ) can be implemented to compare the values of elements stored in the collection.
– equals( ) can be implemented to compare references to those elements.
The method iterator( ) returns an iterator to a collection.
– Iterators help to loop through the collections.

Downloaded from Ktunotes.in


LIST INTERFACE
● The List interface extends Collection interface.
● List declares the behavior of a collection that stores a sequence of elements.
● – In Java, the List interface is an ordered collection that allows us to store and access
elements sequentially.
● Elements can be inserted or accessed by their position in the list, using zero-based
index.
● A list may contain duplicate elements.
● List is a generic interface that has this declaration:
interface List<E>

Downloaded from Ktunotes.in


List Interface (contd.)
List Interface(contd.)
• List supports methods defined by Collection,
• List defines its own methods also.
• Some methods throw exceptions.
• Exceptions that are thrown by List methods are:

Downloaded from Ktunotes.in


Methods in List Interface

Downloaded from Ktunotes.in


Methods in List Interface
• List has many methods:- add(int, E) and addAll(int, Collection)
• These methods insert elements at the specified index.
• The meaning of add(E) and addAll(Collection) defined by Collection are changed by List.
In List they add elements to the end of the list.
• To obtain the object stored at a specific location, call get( ) with the index of the object.
• To assign a value to an element in the list, call set( ), specifying the index of the object to
be changed.
• To find the index of an object, use indexOf( ) or lastIndexOf().
• A sublist of a list can be obtained by calling subList() , specifying the beginning and ending
indexes of the sublist.

Downloaded from Ktunotes.in


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 :
● 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 class - The ArrayList class implements the List interface. It uses a dynamic
array to store the duplicate element of different data types.
Downloaded from Ktunotes.in
LIST INTERFACE
● The ArrayList class maintains the insertion order and is non synchronized.
● The elements stored in the ArrayList class can randomly accessed. Consider the
following example.

Downloaded from Ktunotes.in


ArrayList
● 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 java.util
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.

Downloaded from Ktunotes.in


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

Downloaded from Ktunotes.in


ArrayList Example

Downloaded from Ktunotes.in


Iterating ArrayList using Iterator

Downloaded from Ktunotes.in


The Collection Classes
• The collection classes implement collection
interfaces.
• Some of the collection classes provide full
implementations that can be used as-is.
• Some of the collection classes are abstract,
providing skeletal implementations that are used
as starting points for creating concrete collections.
• Collection classes are not synchronized.
– Two or more threads can access the methods of
collection class at any time

Downloaded from Ktunotes.in


The Collection Classes

Downloaded from Ktunotes.in


ArrayList Class
• The ArrayList class extends AbstractList and implements the List interface.
• ArrayList is a generic class that has declaration:
class ArrayList<E>
– Here, E specifies the type of objects that the list will hold.
• ArrayList supports dynamic arrays that can grow as needed.
– This is needed because in some cases we may not know how large an array we
need precisely until run time.
• An ArrayList is a variable-length array of object references.
– So ArrayList can dynamically increase or decrease in size.
• Array lists are created with an initial size.
– When this size is exceeded, the collection is automatically enlarged.
– When objects are removed, the array can be shrunk.

Downloaded from Ktunotes.in


ArrayList Class

Downloaded from Ktunotes.in


ArrayList Class(contd.)
• ArrayList has following constructors:
ArrayList( )
This constructor builds an empty array list.
ArrayList(Collection<? extends E> c)
– This constructor builds an array list that is initialized with the elements of the collection c.
ArrayList(int capacity)
– This constructor builds an array list that has the specified initial capacity.
– The capacity is the size of the underlying array that is used to store the elements.
– The capacity grows automatically as elements are added to an array list.

Downloaded from Ktunotes.in


ArrayList Class(contd.)

Downloaded from Ktunotes.in


ArrayList Class(contd.)
• The contents of a collection are displayed using the default conversion provided by
toString( ), which was inherited from AbstractCollection.
• We can increase the capacity of an ArrayList object manually by calling ensureCapacity( ).
void ensureCapacity(int cap)
• If we want to reduce the size of the array that of ArrayList object so that it is precisely as
large as the number of items that it is currently holding, call trimToSize( ):
void trimToSize( )

Downloaded from Ktunotes.in


Obtaining an Array from an ArrayList
• To convert a collection into an array, toArray( ), which is defined by Collection can be
called.
– This is needed
• To obtain faster processing times for certain operations
• To pass an array to a method that is not overloaded to accept a collection
• To integrate collection-based code with legacy code that does not understand collections
• Two versions of toArray( ) are:
Object[ ] toArray( )
<T> T[ ] toArray(T array[ ])

Downloaded from Ktunotes.in


ArrayList Sample

Downloaded from Ktunotes.in


Accessing Collections via an Iterator
• To cycle through the elements in a collection (e.g. display each element, sum of elements
etc.), we can use iterator, which is an object that implements either
– Iterator or
– ListIterator

Downloaded from Ktunotes.in


Accessing Collections via an Iterator
• To cycle through the elements in a collection (e.g. display each element, sum of elements
etc.), we can use iterator, which is an object that implements either
– Iterator or
– ListIterator
• Iterator enables you to
– cycle through a collection
– obtaining or removing elements.
• ListIterator extends Iterator to allow
– bidirectional traversal of a list,
– the modification of elements

Iterator and ListIterator are generic interfaces which are declared as :


interface Iterator<E>
interface ListIterator<E>
– Here, E specifies the type of objects being iterated
Downloaded from Ktunotes.in
Accessing Collections via an Iterator

Downloaded from Ktunotes.in


Accessing Collections via an Iterator

Downloaded from Ktunotes.in


Accessing Collections via an Iterator
Exceptions in methods
• Exceptions in the Methods Defined by Iterator

– NoSuchElementException
– IllegalStateException
• Exceptions in the Methods Defined by ListIterator
– NoSuchElementException
– IllegalStateException
– UnsupportedOperationException

Downloaded from Ktunotes.in


Using an Iterator
• Each of the collection classes provides an iterator( ) method that returns an iterator to the
start of the collection.
– By using this iterator object, we can access each element in the collection, one element
at a time.
• To use an iterator to cycle through the contents of a collection,
– 1. Obtain an iterator to the start of the collection by calling the collection’s iterator( )
method.
– 2. Set up a loop that makes a call to hasNext( ).
• Have the loop iterate as long as hasNext( ) returns true.
– 3.Within the loop, obtain each element by calling next( ).

Downloaded from Ktunotes.in


Using an Iterator

Downloaded from Ktunotes.in


Iterator vs Listiterator

Downloaded from Ktunotes.in


The For-Each Alternative to Iterators
• The for loop is substantially shorter and simpler to use than the iterator based approach.

• But for loop can only be used to cycle through a collection in the forward direction, and we
can’t modify the contents of the collection.

• If we don’t want to modify the contents of a collection or obtaining elements in reverse


order, then the for-each version of the for loop is often a more convenient alternative to
cycling through a collection than is using an iterator.

Downloaded from Ktunotes.in


Downloaded from Ktunotes.in
The For-Each Alternative to Iterators
• The for loop is substantially shorter and simpler to use than the iterator based approach.

• But for loop can only be used to cycle through a collection in the forward direction, and we
can’t modify the contents of the collection.

• If we don’t want to modify the contents of a collection or obtaining elements in reverse


order, then the for-each version of the for loop is often a more convenient alternative to
cycling through a collection than is using an iterator.

Downloaded from Ktunotes.in


Program to remove duplicates

Downloaded from Ktunotes.in


Event Handling
For the user to interact with a GUI, the underlying operating system must
support event handling.
1) operating systems constantly monitor events such as keystrokes, mouse
clicks, voice command, etc.
2) operating systems sort out these events and report them to the appropriate
application programs
3) each application program then decides what to do in response to these events
• There are several types of events, – Events can be generated by
• the mouse (click, move, drag mouse etc.)
• the keyboard (type, press, release etc.)
• different GUI controls, such as a – push button – scroll bar – check box
Event Handling is the mechanism that controls the event and decides what
should happen if an event occurs.
Downloaded from Ktunotes.in
What is an Event?
● Change in the state of an object is known as event i.e. event describes the
change in state of source.
● An event is an object that describes a state change in a source.
● Events are generated as result of user interaction with the graphical user
interface components.
● It can be generated as a consequence of a person interacting with the
elements in a graphical user interface.
● Some of the activities that cause events to be generated are pressing a
button, entering a character via the keyboard, selecting an item in a list, and
clicking the mouse.

Downloaded from Ktunotes.in


Types of Event
Foreground Events - Those events which require the direct interaction of user.
They are generated as consequences of a person interacting with the GUI.
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.

Downloaded from Ktunotes.in


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.
● Events are supported by a number of packages, including
○ java.util, java.awt, java.awt.event
● Event handling is an integral part in the creation of applets and other types
of GUI-based programs.
● Applets are event-driven programs that use a GUI to interact with the user.
● Any program that uses a graphical user interface is event driven.
● Thus, we cannot write these types of programs without a solid command of
event handling.
Downloaded from Ktunotes.in
Event Handling Mechanisms
• The two ways in which events are handled changed significantly between the
(Two event handling mechanisms)
– original version of Java (1.0) event handling and
– modern versions of Java (beginning with version 1.1) event handling
• The 1.0 method of event handling is still supported, but it is not recommended
for new programs. As per this Event was propagated up the containment
hierarchy until it was handled by a component.
– Many of the methods that support the old 1.0 event model have been
deprecated.
• The modern approach is the way that events should be handled by all new
programs

Downloaded from Ktunotes.in


The Delegation Event Model
• The modern approach to handling
events is based on the delegation event
model
– It defines standard and consistent
mechanisms to generate and
process events.

• Concept of delegation event model :


– A source generates an event and sends it to one or more registered listeners.
– In this scheme, the listener simply waits until it receives an event.
– Once an event is received, the listener processes the event and then returns.

Downloaded from Ktunotes.in


The Delegation Event Model
The advantage of Delegation Event Model is that the application logic that
processes events is cleanly separated
from the user interface logic that generates those events.
A user interface element is able to “delegate”(entrust) the processing of an event to
a separate piece of code.
In the delegation event model, listeners must register with a source in order to
receive an event notification.
– Benefit: Notifications are sent only to listeners that want to receive them.
In previous models, an event was propagated up the containment hierarchy until it
was handled by a component.
– This required components to receive events that they did not process, and it
wasted valuable time. The delegation event model eliminates this overhead

Downloaded from Ktunotes.in


The Delegation Event Model

Downloaded from Ktunotes.in


The Delegation Event Model

Downloaded from Ktunotes.in


The Delegation Event Model -Event
• In the delegation model, an event is an object that describes a state change in a
source.
• Events can be caused with or without user interaction.
• Some events are caused by interactions with a user interface such as:
– pressing a button, entering a character via the keyboard,
– selecting an item in a list, clicking the mouse.
• Events may also occur that are not directly caused by interactions with a user
interface.
– Example: an event may be generated
• when a timer expires, a counter exceeds a value,
• a software or hardware failure occurs, an operation is completed

Downloaded from Ktunotes.in


The Delegation Event Model – Event Sources
• A event source is an object that generates an event.
– Event occurs when the internal state of that object changes in some way.
• Sources may generate more than one type of event.
• A source must register listeners, then only listeners can receive notifications
about a specific type of event.
• Each type of event has its own registration method.
General form of listener registration is:
public void addTypeListener(TypeListener el)
– Type is the name of the event, and el is a reference to the event listener.
– For example, the method that registers a keyboard event
listener is called addKeyListener( ).
– The method that registers a mouse motion listener is called
addMouseMotionListener( ).
Downloaded from Ktunotes.in
The Delegation Event Model – Event Sources
• A event source is an object that generates an event.
– Event occurs when the internal state of that object changes in some way.
• Sources may generate more than one type of event.
• A source must register listeners, then only listeners can receive notifications
about a specific type of event.
• Each type of event has its own registration method.
General form of listener registration is:
public void addTypeListener(TypeListener el)
– Type is the name of the event, and el is a reference to the event listener.
– For example, the method that registers a keyboard event
listener is called addKeyListener( ).
– The method that registers a mouse motion listener is called
addMouseMotionListener( ).
Downloaded from Ktunotes.in
The Delegation Event Model – Event Sources (contd.)
• When an event occurs, all registered listeners are notified and receive a copy of
the event object. This is known as multicasting the event.
– In all cases, notifications are sent only to listeners that register to receive them.
• Some sources may allow only one listener to register. The general form of such a
method is this:
public void addTypeListener(TypeListener el) throws
java.util.TooManyListenersException
– When such an event occurs, that single registered listener is notified. This is
known as unicasting the event.

Downloaded from Ktunotes.in


The Delegation Event Model – Event Sources (contd.)
A source must also provide a method that allows a listener to unregister an interest
in a specific type of event. The general form of such a method is this:
public void removeTypeListener(TypeListener el)
• Here, Type is the name of the event, and el is a reference to the event listener.

– For example, to remove a keyboard listener, call


removeKeyListener( ).
• The methods that add or remove listeners are provided by the source that
generates events.
– For example, the Component class provides methods to add and remove
keyboard and mouse event listeners.

Downloaded from Ktunotes.in


The Delegation Event Model – Event Listeners
● A listener is an object that is notified when an event occurs.
● It has two major requirements.
● First, it must have been registered with one or more sources to receive
notifications about specific types of events.
● Second, it must implement methods to receive and
● process these notifications
● The methods that receive and process events are defined in a set of interfaces
found in java.awt.event.
● – For example, the MouseMotionListener interface defines two methods to
receive notifications when the mouse is dragged or moved.
● Any object may receive and process one or both of these events if it provides
an implementation of this interface.

Downloaded from Ktunotes.in


Downloaded from Ktunotes.in
The Delegation Event Model

Downloaded from Ktunotes.in


Downloaded from Ktunotes.in
Component vs Container
● In Java, a component is the basic user interface object and is found in all Java
applications.
● The main difference between them is that a Container is a subclass of
Component.
● Container can contain other components and containers.
● Frame, Panel and Applet are examples of Container
● Button, TextField etc are examples of Component.

Downloaded from Ktunotes.in


Event Classes
● The classes that represent events(Event classes) are at the core of Java’s event
handling mechanism.
● The most widely used events are those defined by the AWT and those defined by
Swing.
● At the root of the Java event class hierarchy is EventObject, which is in java.util.
● – EventObject is the superclass for all events.
● – Its one constructor is : EventObject(Object src)
● – Here, src is the object that generates this event

Downloaded from Ktunotes.in


Event Classes(contd.)
● EventObject contains two methods: getSource( ) , toString( ).
● The getSource( ) method returns the source of the event.
● Its general form is : Object getSource( )
● - toString( ) returns the string equivalent of the event.

The class AWTEvent, defined within the java.awt package, is a subclass of


EventObject.

● – It is the superclass (either directly or indirectly) of all AWT-based events used


by the delegation event model.
● – Its getID( ) method can be used to determine the type of the event.
● – The signature of getID( ) method is int getID( )

Downloaded from Ktunotes.in


Event Classes(contd.)

Downloaded from Ktunotes.in


Event Classes(contd.)

Downloaded from Ktunotes.in


Event Classes(contd.)

Downloaded from Ktunotes.in


The ActionEvent Class
● An ActionEvent is generated when
● – a button is pressed,
● – a list item is double-clicked,
● – menu item is selected.
● The ActionEvent class defines four integer constants that can be used to
identify any modifiers associated with an action event:
● – ALT_MASK
● – CTRL_MASK
● – META_MASK
● – SHIFT_MASK.
● Integer constant ACTION_ PERFORMED, can be used to identify action
events.

Downloaded from Ktunotes.in


The ActionEvent Class(contd.)
● ActionEvent has these three constructors:
● ActionEvent(Object src, int type, String cmd)
● ActionEvent(Object src, int type, String cmd, int modifiers)
● ActionEvent(Object src, int type, String cmd, long when,int modifiers)
● – Here, src is a reference to the object that generated this event.
● – The type of the event is specified by type, and its command string is cmd.
● – The argument modifiers indicates which modifier keys (ALT, CTRL, META,
and/or SHIFT) were pressed when the event was generated.
● – The when parameter specifies when the event occurred.
● To obtain the command name for the invoking ActionEvent
● object getActionCommand( ) method can used:
● For example, when a button is pressed, an action event is generated that has a
command name equal to the label on that button.
Downloaded from Ktunotes.in
The ActionEvent Class(contd.)
● The getModifiers( ) method
● – returns a value that indicates which modifier keys (ALT,CTRL, META, and/or
SHIFT) were pressed when the event was generated.
● Its form is : int getModifiers( )
● The method getWhen( ) method
● – returns the time at which the event took place. This is called the event’s
timestamp. The getWhen( ) method is :
● long getWhen( )

Downloaded from Ktunotes.in


The AdjustmentEvent Class
● An AdjustmentEvent is generated by a scroll bar.
● There are five types of adjustment events.
● The AdjustmentEvent class defines integer constants that can be used to identify
them.

Downloaded from Ktunotes.in


The AdjustmentEvent Class
● The getAdjustable( ) method returns the object that generated the event.
● Its form is; Adjustable getAdjustable( )
● The type of the adjustment event may be obtained by the getAdjustmentType( )
method.
● It returns one of the constants defined by AdjustmentEvent.
● The general form is : int getAdjustmentType( )
● The amount of the adjustment can be obtained from the getValue( ) method is:
● int getValue( )
● – For example, when a scroll bar is manipulated, this method returns the value
represented by that change.

Downloaded from Ktunotes.in


The ComponentEvent Class
● A ComponentEvent is generated when the size, position, or visibility of a
component is changed.
● There are four types of component events.
● – The ComponentEvent class defines integer constants for this.

Downloaded from Ktunotes.in


The ComponentEvent Class(contd.)
● ComponentEvent has the constructor: ComponentEvent(Component src, int type)
● – Here, src is a reference to the object that generated this event.
● The type of the event is specified by type.
● ComponentEvent is the superclass either directly or indirectly of ContainerEvent,
FocusEvent, KeyEvent, MouseEvent, and WindowEvent.
● The getComponent( ) method returns the component that generated the event
● Component getComponent( )

Downloaded from Ktunotes.in


The ContainerEvent Class
● • A ContainerEvent is generated when a component is added to or removed from a
container.
● • There are two types of container events.
● • The ContainerEvent class defines int constants that can be used to identify them:
● – COMPONENT_ADDED
● – COMPONENT_REMOVED.
● ContainerEvent is a subclass of ComponentEvent.
● Constructor: ContainerEvent(Component src, int type, Component comp)
● – Here, src is a reference to the container that generated this event.
● The type of the event is specified by type, and the component that has been added
to or removed from the container is comp.

Downloaded from Ktunotes.in


The ContainerEvent Class
• A reference to the container that generated this event by using the getContainer( )
method.

Container getContainer( )

• The getChild( ) method returns a reference to the component that was added to or
removed from the container.

Component getChild( )

Downloaded from Ktunotes.in


The FocusEvent Class
● • A FocusEvent is generated when a component gains or loses input focus.
● • These events are identified by the integer constants
● – FOCUS_GAINED
● – FOCUS_LOST.
● • FocusEvent is a subclass of ComponentEvent and has these constructors:
● FocusEvent(Component src, int type)
● FocusEvent(Component src, int type, boolean temporaryFlag)
● FocusEvent(Component src, int type, boolean temporaryFlag, Component other)
● The argument temporaryFlag is set to true if the focus event is temporary.
● Otherwise, it is set to false.
● The other component involved in the focus change, called the opposite component,
is passed in other.

Downloaded from Ktunotes.in


The FocusEvent Class(contd.)
● A temporary focus event occurs as a result of another user interface operation.
● – For example, assume that the focus is in a text field. If the user moves the mouse
to adjust a scroll bar, the focus is temporarily lost.
● if a FOCUS_GAINED event occurred, other will refer to the component that lost
focus.
● • Conversely, if a FOCUS_LOST event occurred, other will refer to the component
that gains focus.
● • To determine the other component call getOppositeComponent( ):
● Component getOppositeComponent( )
● – The opposite component is returned.
● • The isTemporary( ) method indicates if this focus change is temporary.
● boolean isTemporary( )
● – The method returns true if the change is temporary.
● – Otherwise, it returns false.
Downloaded from Ktunotes.in
The InputEvent Class
● The abstract class InputEvent is a subclass of ComponentEvent and is the
superclass for component input events.
● – Its subclasses are KeyEvent and MouseEvent.
● • InputEvent defines several integer constants that represent any modifiers, such as
the control key being pressed.
● InputEvent class defined the following eight values to represent the modifiers:
● ALT_MASK
● •ALT_GRAPH_MASK
● •BUTTON1_MASK
● •BUTTON2_MASK
● •BUTTON3_MASK
● •CTRL_MASK
● •META_MASK
● •SHIFT_MASK
Downloaded from Ktunotes.in
The InputEvent Class
● The abstract class InputEvent is a subclass of ComponentEvent and is the
superclass for component input events.
● – Its subclasses are KeyEvent and MouseEvent.
● • InputEvent defines several integer constants that represent any modifiers, such as
the control key being pressed.
● InputEvent class defined the following eight values to represent the modifiers:
● ALT_MASK, ALT_GRAPH_MASK ,BUTTON1_MASK, BUTTON2_MASK
● BUTTON3_MASK, CTRL_MASK, META_MASK, SHIFT_MASK
● The extended modifier values to avoid conflict between keyboard and mouse event
modifiers are:
● •ALT_DOWN_MASK, •ALT_GRAPH_DOWN_MASK, •BUTTON1_DOWN_MASK
● •BUTTON2_DOWN_MASK, •BUTTON3_DOWN_MASK, •CTRL_MASK
● •META_DOWN_MASK, •SHIFT_DOWN_MASK
Downloaded from Ktunotes.in
The ItemEvent Class
● • An ItemEvent is generated when
● – a check box or a list item is clicked or
● – when a checkable menu item is selected or deselected.
● • There are two types of item events, which are identified by the following integer
constants:
● DESELECTED - The user deselected an item.
● SELECTED - The user selected an item.

Downloaded from Ktunotes.in


References
● Herbert Schildt, Java: The Complete Reference, 8/e, Tata McGraw Hill, 2011.

● GeeksforGeeks - www.geeksforgeeks.org

● Wikipedia - www.wikipedia.org

● Tutorialspoint - www.tutorialspoint.com

● Java Zone - https://dzone.com

● https://itsmeebin.wordpress.com/

● https://renethajb.wordpress.com/
Disclaimer - This document contains images/texts from various internet sources. Copyright belongs to the
respective content creators. Document is compiled exclusively for study purpose and shall not be used for
commercial purpose.
Downloaded from Ktunotes.in

You might also like