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

OOP Through Java UNIT-5 Material

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

OOP Through Java UNIT-5 Material

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

UNIT-5

Multithreading

Multithreading in java is a process of executing multiple threads simultaneously.


Thread is basically a lightweight sub-process, a smallest unit of processing. 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.
JavaMultithreading ismostly usedin games, animation etc

Advantage of Java Multithreading


 It doesn't block the user because threads are independent and you can perform multiple
operations at sametime.
 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.

Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use multitasking
to utilize the CPU. Multitasking can be achieved by two ways:
 Process-based Multitasking(Multiprocessing)
 Thread-based Multitasking(Multithreading)

1) Process-based Multitasking (Multiprocessing)


 Each process have its own address in memory i.e. each process allocates separate
memory area.
 Process is heavyweight.
 Cost of communication between the process is high.
 Switching from one process to another require some time for saving and loading
registers, memory maps, updating lists etc.
2) Thread-based Multitasking (Multithreading)

 Threads share the same address space.


 Thread is lightweight.
 Cost of communication between the thread is low.

What is Thread in java


A thread is a lightweight sub process, a smallest unit of processing. It is a separate path of
execution.
Threads are independent, if there occurs exception in one thread, it doesn't affect other
threads. It sharesa common memory area.
Life cycle of a Thread (Thread States)
A thread can be in one of the five states. According to sun, there is only 4 states in thread
lifecycleinjavanew,runnable,non-runnableandterminated.Thereisnorunningstate.
But for better understanding the threads, we are explaining it in the 5 states.
The life cycle of the thread in java is controlled by JVM. The java thread states are as follows:
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)z
5. Terminated
1) New
The thread is in new state if you create an instance of Thread class but before the
invocation of start() method.
2) 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.
3) Running
The thread is in running state if the thread scheduler has selected it.
4) Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not eligible to run.
5) Terminated
A thread is in terminated or dead state when its run() method exits.

How to create thread

There are two ways to create a thread:

1. By extending Thread class


2. By implementing Runnable interface.

1. 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)
Commonly used methods of Thread class:
1. public void run(): is used to perform action for a thread.
2. publicvoidstart(): starts the execution ofthe thread.JVM callsthe run() method

on the thread.
3. public void sleep(long miliseconds): Causes the currently executing thread to
sleep (temporarily cease execution) for the specified number ofmilliseconds.
4. public void join(): waits for a thread to die.
5. public void join(long miliseconds): waits for a thread to die for the specified
miliseconds.
6. public int getPriority(): returns the priority of the thread.
7. public int setPriority(int priority): changes the priority of the thread.
8. public String getName(): returns the name of the thread.
9. public void setName(String name): changes the name of the thread.
10. public Thread currentThread(): returns the reference of currently executing
thread.
11. public int getId(): returns the id of the thread.
12. public Thread.State getState(): returns the state of the thread.
13. public boolean isAlive(): tests if the thread is alive.
14. public void yield(): causes the currently executing thread object to temporarily
pause and allow other threads to execute.
15. public void suspend(): is used to suspend the thread(depricated).
16. public void resume(): is used to resume the suspended thread(depricated).
17. public void stop(): is used to stop the thread(depricated).
18. public boolean isDaemon(): tests if the thread is a daemon thread.
19. public void setDaemon(boolean b): marks the thread as daemon or user
thread.
20. public void interrupt(): interrupts the thread.
21. public boolean isInterrupted(): tests if the thread has been interrupted.
22. public static boolean interrupted(): tests if the current thread has been
interrupted.
2. 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.


Starting a thread:start() method of Thread class is used to start a newly created
thread. It performs following tasks:

 A new thread starts(with newcallstack).


 The thread moves from New state to the Runnable state.
 When the thread gets a chance to execute, its target run() method willrun.
1) By extending Thread class:
1. class Multi extends Thread{
2. public void run(){
3. System.out.println("thread is running...");
4. }
5. public static voidmain(String args[]){
6. Multi t1=new Multi();
7. t1.start();
8. }
9. }
Output:thread isrunning...

Who makes your class object as thread object?


Thread class constructor allocates a new thread object.When you create object of
Multi class,your class constructor is invoked(provided by Compiler) fromwhere Thread
class constructor is invoked(by super() as first statement).So your Multi class object is
thread object now.

2) By implementing the Runnable interface:


1. class Multi3 implements Runnable{
2. public void run(){
3. System.out.println("thread is running...");
4. }
5. public static voidmain(String args[]){
6. Multi3 m1=new Multi3();
7. Thread t1 =new Thread(m1);
8. t1.start();
10. }
11. }
Output:thread isrunning...
If you are not extending the Thread class,your class object would not be treated as a
thread object.So you need to explicitely create Thread class object.We are passing the
object of your class that implements Runnable so that your class run() method may
execute.

Priority of a Thread (Thread Priority):

Each thread have a priority. Priorities are represented by a number between 1 and 10.
In most cases, thread schedular schedules the threads according to their priority
(known as preemptive scheduling). But it is not guaranteed because it depends on JVM
specification that which scheduling itchooses. 3 constants defiend in Thread class:
1. public static int MIN_PRIORITY
2. public static int NORM_PRIORITY
3. public static int MAX_PRIORITY

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


the value of MAX_PRIORITY is10.

Example of priority of a Thread:


class TestMultiPriority1 extends Thread
{
public void run()
{
System.out.println("runningthreadnameis:"+Thread.currentThread().getName() );
System.out.println("running thread priority is:"+Thread.currentThread().getPriority());
}
public static voidmain(String args[])
{
TestMultiPriority1 m1=new TestMultiPriority1();
TestMultiPriority1 m2=new TestMultiPriority1();
m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start();
}
}
Output:running thread name is:Thread-0
running thread priority is:10
running thread name is:Thread-1
running thread priority is:1

Joining threads
Sometimes one thread needs to know when another thread is ending. In java,
isAlive() and join() are two different methods to check whether a thread has finished its
execution.

The isAlive() methods return true if the thread upon which it is called is still running
otherwise it return false.
final booleanisAlive()

But, join() method is used more commonly than isAlive(). This method waits until the
thread on which it is called terminates.
final void join() throws InterruptedException

Using join() method, we tell our thread to wait until the specifid thread completes its
execution. There are overloaded versions of join() method, which allows us to specify time
for which you want to wait for the specified thread to terminate.
final void join(long milliseconds) throwsInterruptedException
Example of isAlive method

public class MyThread extends Thread


{
public void run()
{
System.out.println("r1");
try{
Thread.sleep(500);
}
catch(InterruptedException ie)
{
System.out.println("r2 ");
}
}
public static void main(String[] args)
{
MyThread t1=new MyThread(); MyThread t2=new MyThread(); t1.start();

t2.start(); System.out.println(t1.isAlive());

System.out.println(t2.isAlive());

}
}

Output

r1
true
true
r1
r2
r2
Example of thread without join() method

public class MyThread extends Thread


{
public void run()
{
System.out.println("r1 ");
try{
Thread.sleep(500);
}catch(InterruptedException ie){}

System.out.println("r2 ");
}
public static void main(String[] args)
{
MyThread t1=new MyThread();
MyThread t2=new MyThread();
t1.start();
t2.start();
}
}

Output
r1
r1
r2 r1 r1 r2 r2

r2
In this above program two thread t1 and t2 are created. t1 starts first and after printing
"r1" on console thread t1 goes to sleep for 500 mls.At the same time Thread t2 will start its
process and print "r1" on console and then goes into sleep for 500 mls. Thread t1 will
wake up from sleep and print "r2" on console similarly thread t2 will wake up from sleep
and print "r2" on console. So you will get output like
Example of thread with join() method

public class MyThread extends Thread


{
public void run()
{
System.out.println("r1 ");
try{
Thread.sleep(500);
}
catch(InterruptedException ie){}
System.out.println("r2 ");
}
public static void main(String[] args)
{
MyThread t1=new MyThread();
MyThread t2=new MyThread();
t1.start();
try{
t1.join(); //Waiting for t1 tofinish
}
catch(InterruptedException ie){}
t2.start();
}
}

Output
r1
r2
r1
r2
In this above program join() method on thread t1 ensure that t1 finishes it process before
thread t2 starts.
Specifying time with join()

If in the above program, we specify time while using join() with m1, then m1 will execute
for that time, and thenm2 and m3 will join it.
m1.join(1500);
Doing so, initially m1 will execute for 1.5 seconds, after which m2 and m3 will join it.

In the last chapter we have seen the ways of naming thread in java. In this chapter we will
be learning the different priorities that a thread can have.

Java Thread Priority :

1. Logically we can say that threads run simultaneously but practically its not true,
only one Thread can run at a time in such a ways that user feels that concurrent

environment.

2. Fixed priority scheduling algorithm is used to select one thread for execution based

on priority.

Example#1 : Default Thread Priority

getPriority() method is used to get the priority of the thread.


package com.c4learn.thread;
public class ThreadPriority extends Thread
{
public void run() {
System.out.println(Thread.currentThread().getPriority());
}

public static void main(String[] args) throws InterruptedException


{
ThreadPriorityt1 = new ThreadPriority();
ThreadPriority t2 = new ThreadPriority();
t1.start();
t2.start();
}
}

Output :

default priority of the thread is 5.

Each thread has normal priority at the time of creation. We can change or modify the
thread priority in the following example 2.

5
5
Example#2: SettingPriority
package com.c4learn.thread;
public class ThreadPriority extends Thread
{
public void run() {
String tName = Thread.currentThread().getName();
Integer tPrio = Thread.currentThread().getPriority();
System.out.println(tName + " has priority " + tPrio);
}
public static void main(String[] args) throws InterruptedException
{
ThreadPriority t0 = new ThreadPriority();
ThreadPriorityt1 = new ThreadPriority();
ThreadPriority t2 = new ThreadPriority();
t1.setPriority(Thread.MAX_PRIORITY);
t0.setPriority(Thread.MIN_PRIORITY);
t2.setPriority(Thread.NORM_PRIORITY);
t0.start();
t1.start();
t2.start();
}
}

Output :

Thread-0 has priority 1


Thread-2 has priority 5
Thread-1 has priority 10
ExplanationofThread Priority:

1. We can modify the thread priority using the setPriority() method.

2. Thread can have integer priority between 1 to 10

3. Java Thread class defines following constants –

4. At a time many thread can be ready for execution but the thread with highest
priority is selected for execution

5. Thread have default priority equal to5.

Thread:PriorityandConstant

Thread Priority Constant

MIN_PRIORITY 1

MAX_PRIORITY 10

NORM_PRIORITY 5

JavaThreadSynchronization:

 In multi-threading environment, When two or more threads need access to a any


shared resource then their should be some mechanism to ensure that the resource
will be used by only one thread at a time.
 Thread Synchronization is a process by which this synchronization isachieved.

 Thread Synchronization is used to prevent thread interference and consistency


problem.
 Thread Synchronization is achieved through keyword synchronized.
Synchronization in Java
Synchronization in java is the capability to control the access of multiple threads to any shared
resource. Java Synchronization is better option where we want to allow only one thread to
access the shared resource.

Why use Synchronization


The synchronization is mainly used to
1. To prevent thread interference.
2. To prevent consistency problem.

Types of Synchronization
There are two types of synchronization
1. Process Synchronization
2. Thread Synchronization
Here, we will discuss only thread synchronization.

Thread Synchronization
There are two types of thread synchronization mutual exclusive and inter-thread
communication.

1. Mutual Exclusive
1. Synchronized method.
2. Synchronized block.
3. static synchronization.
2. Cooperation (Inter-thread communication injava)

Mutual Exclusive

Mutual Exclusive helps keepthreads frominterfering with one another while sharing data.
This can be done by three ways in java:

1. by synchronized method
2. by synchronized block
3. by static synchronization

Concept of Lock in Java

Synchronization is built around an internal entity known as the lock or monitor. Every
object has an lock associated with it. By convention, a thread that needs consistent access
to an object's fields has to acquire the object's lock before accessing them, and then release
the lock when it's done with them.

From Java 5 the package java.util.concurrent.locks contains several lock implementations.

Understanding the problem without Synchronization


In this example, there is no synchronization, so output is inconsistent. Let's see the
example:
1. ClassTable
2. {
3. void printTable(int n){ //method not synchronized
4. for(int i=1;i<=5;i++){
5. System.out.println(n*i);
6. try{
7. Thread.sleep(400);
8. }catch(Exception e){System.out.println(e);}
9. }
10. }
11. }
12. class MyThread1 extends Thread{
13. Table t;
14. MyThread1(Table t){
15. this.t=t;
16. }
17. public void run(){
18. t.printTable(5);
19. }
20. }
21. class MyThread2 extends Thread{
22. Table t;
23. MyThread2(Table t){
24. this.t=t;
25. }
26. public void run(){
27. t.printTable(100);
28. }
29. }
30. class TestSynchronization1{
31. public static voidmain(String args[]){
32. Table obj = new Table();//only one object
33. MyThread1 t1=new MyThread1(obj);
34. MyThread2 t2=new MyThread2(obj);
35. t1.start();
36. t2.start();
37. }
38. }
Output: 5
100
10
200
15
300
20
400
25
500

Java synchronized method

If you declare any method as synchronized, it is known as synchronized method.


Synchronized method is used to lock an object for any shared resource. When a thread
invokes a synchronized method, it automatically acquires the lock for that object and
releases it when the thread completes its task.

1. //example of java synchronized method


2. class Table{
3. synchronized void printTable(int n){ //synchronized method
4. for(int i=1;i<=5;i++){
5. System.out.println(n*i);
6. try{
7. Thread.sleep(400);
8. }catch(Exception e){System.out.println(e);}
9. }
10.
11. }
12. }
13.
14. class MyThread1 extends Thread{
15. Table t;
16. MyThread1(Table t){
17. this.t=t;
18. }
19. public void run(){
20. t.printTable(5);
21. }
22.
23. }
24. class MyThread2 extends Thread{
25. Table t;
26. MyThread2(Table t){
27. this.t=t;
28. }
29. public void run(){
30. t.printTable(100);
31. }
32. }
33.
34. public class TestSynchronization2{
35. public static voidmain(String args[]){
36. Table obj = new Table();//only one object
37. MyThread1 t1=new MyThread1(obj);
38. MyThread2 t2=new MyThread2(obj);
39. t1.start();
40. t2.start();
41. }
42. }

Output: 5
10
15
20
25
100
200
300
400
500
Example of synchronized method by using annonymous class
In this program, we have created the two threads by annonymous class, so less coding is required.

1. //Program of synchronized method by using annonymous class


2. class Table{
3. synchronized void printTable(int n){//synchronized method
4. for(int i=1;i<=5;i++){
5. System.out.println(n*i);
6. try{
7. Thread.sleep(400);
8. }catch(Exception e){System.out.println(e);}
9. }
10.
11. }
12. }
13.
14. public class TestSynchronization3{
15. public static voidmain(String args[]){
16. finalTableobj = new Table();//only oneobject
17.
18. Thread t1=new Thread(){
19. public void run(){
20. obj.printTable(5);
21. }
22. };
23. Thread t2=new Thread(){
24. public void run(){
25. obj.printTable(100);
26. }
27. };
28. t1.start();
29. t2.start();
31. }
32. }
Output: 5
10
15
20
25
100
200
300
400
500

Synchronized block in java

Synchronized block can be used to perform synchronization on any specific resource of the
method.

Suppose you have 50 lines of code in your method, but you want to synchronize only 5
lines, you can use synchronizedblock.

If you put all the codes of the method in the synchronized block, it will work same as the
synchronized method.

Points to remember for Synchronized block


 Synchronized block is used to lock an object for any shared resource.
 Scope of synchronized block is smaller than the method.

Syntax to use synchronized block


1. synchronized (object reference expression) {
2. //code block
3. }

Example of synchronized block

Let's see the simple example of synchronized block.


Program of synchronized block

1. class Table {
2. void printTable(intn){
3. synchronized(this){//synchronized block
5. for(int i=1;i<=5;i++){
6. System.out.println(n*i);
7. try{
8. Thread.sleep(400);
9. }catch(Exception e){System.out.println(e);}
10. }
11. }
12. }//end of the method
13. }
14.
15. class MyThread1 extends Thread{
16. Table t;
17. MyThread1(Table t){
18. this.t=t;
19. }
20. public void run(){
21. t.printTable(5);
22. }
23.
24. }
25. class MyThread2 extends Thread{
26. Table t;
27. MyThread2(Table t){
28. this.t=t;
29. }
30. public void run(){
31. t.printTable(100);
32. }
33. }
34.
35. public class TestSynchronizedBlock1{
36. public static void main(String args[]){
37. Table obj = new Table();//only one object
38. MyThread1 t1=new MyThread1(obj);
39. MyThread2 t2=new MyThread2(obj);
40. t1.start();
41. t2.start();
42. }
43. }
Output:5
10
15
20
25
100
200
300
400
500

Same Example of synchronized block by using annonymous class:


//Program of synchronized block by using annonymous class

1. class
Table{ 2.
3. void printTable(int n){
4. synchronized(this){//synchronized block
5. for(int i=1;i<=5;i++){
6. System.out.println(n*i);
7. try{
8. Thread.sleep(400);
9. }catch(Exception e){System.out.println(e);}
10. }
11. }
12. }//end of the method
13. }
14. public class TestSynchronizedBlock2{
15. public static void main(String args[]){
16. finalTableobj = new Table();//only oneobject
18.
19. Thread t1=new Thread(){
20. public void run(){
21. obj.printTable(5);
22. }
23. };
24. Thread t2=new Thread(){
25. public void run(){
26. obj.printTable(100);
27. }
28. };
29. t1.start();
30. t2.start();
32. }
33. }
Output:5
10
15
20
25
100
200
300
400
500

Static synchronization
If you make any static method as synchronized, the lock will be on the class not on object.

Problem without static synchronization

Suppose there are two objects of a shared class(e.g. Table) named object1 and object2.In
case of synchronized method and synchronized block there cannot be interference
between t1 and t2 or t3 and t4 because t1 and t2 both refers to a common object that have
a single lock.But there can be interference between t1 and t3 or t2 and t4 because t1
acquires another lock and t3 acquires another lock.I want no interference between t1 and
t3 or t2 and t4.Static synchronization solves this problem.
Example of static synchronization
In this example we are applying synchronized keyword on the static method to perform
static synchronization.
1. class Table{
3. synchronized static void printTable(int){
4. for(int i=1;i<=10;i++){
5. System.out.println(n*i);
6. try{
7. Thread.sleep(400);
8. }catch(Exception e){}
9. }
10. }
11. }
12. class MyThread1 extends Thread{
13. public void run(){
14. Table.printTable(1);
16. }
17. }
18. class MyThread2 extends Thread{
19. public void run(){
20. Table.printTable(10);
22. }
23. }
24. class MyThread3 extends Thread{
25. public void run(){
26. Table.printTable(100);
28. }
29. }
30. class MyThread4 extends Thread{
31. public void run(){
32. Table.printTable(1000);
33. }
34. }
35. public classTestSynchronization4{
36. publicstaticvoid main(String t[]){
37. MyThread1 t1=new MyThread1();
38. MyThread2 t2=new MyThread2();
39. MyThread3 t3=new MyThread3();
40. MyThread4 t4=new MyThread4();
41. t1.start();
42. t2.start();
43. t3.start();
44. t4.start();
46. }
47. }
Output: 1
2
3
4
5
6
7
8
9
10
10
20
30
40
50
60
70
80
90
100
100
200
300
400
500
600
700
800
900
1000
1000
2000
3000
4000
5000
6000
7000
8000
9000
10000
Same example of static synchronization by annonymous class
In this example, we are using annonymous class to create the threads.

1. class Table
2. {
3. synchronized static void printTable(int n){
4. for(int i=1;i<=10;i++){
5. System.out.println(n*i);
6. try{
7. Thread.sleep(400);
8. }catch(Exception e){}
9. }
10. }
11. }
12. public class TestSynchronization5 {
13. public static void main(String[]args){
14. Thread t1=new Thread(){
15. public void run(){
16. Table.printTable(1);
19. }
20. };
21.
22. Thread t2=new Thread(){
23. public void run(){
24. Table.printTable(10);
25. }
26. };
27. Thread t3=new Thread(){
28.
29. public void run(){
30. Table.printTable(100);
31. }
32. };
33.
34. Thread t4=new Thread(){
35. public void run(){
36. Table.printTable(1000);
37. }
38. };
39. t1.start();
40. t2.start();
41. t3.start();
42. t4.start();
43.
44. }
45. }
Output: 1
2
3
4
5
6
7
8
9
10
10
20
30
40
50
60
70
80
90
100
100
200
300
400
500
600
700
800
900
1000
1000
2000
3000
4000
5000
6000
7000
8000
9000
10000
Synchronized block on a class lock:

The block synchronizes on the lock of the object denoted by the reference .class name
.class. A static synchronized method printTable(int n) in class Table is equivalent to the
following declaration:

1. static void printTable(int n){


2. synchronized (Table.class) { // Synchronized block on class A
3. // ...
4. }
5. }

Example Programs of Thead

Write a program to know the currently running Thread


//Currently running thread
class Current
{
public static void main(String args[])
{
System.out.println ("This is first statement");
Thread t = ThreadcurrentThread ();
System.out.println ("Current Thread: " + t);
System.out.println ("Its name: " + t.getName ());
System.out.println ("Its priority:" + t.getPriority ());
}
}

Output:
Write a program to create and run a Thread
//creating and running a Thread

class MyThread extends Thread


{
public void run ()
{
for (int i = 0;i<100;i++)
{
System.out.print (i + "\t");
}
}
}
class TDemo
{
public static void main(String args[])
{
MyThread obj = new MyThread ();
Thread t = new Thread (obj);
t.start ();
}
}
Output:
Write a program to create more than one thread
//using more than one thread is called Multi Threading

class Theatre extends Thread


{
String str; Theatre (String str)
{
this.str = str;
}
public void run()
{
for (int i = 1; i <= 10 ; i++)
{
System.out.println (str + " : " + i);
try
{
Threadsleep (2000);
}
catch (InterruptedException ie) {
ie.printStackTrace ();
}
}
}
}
class TDemo1
{
public static void main(String args[])
{
Theatre obj1 = new Theatre ("Cut Ticket");
Theatre obj2 = new Theatre ("Show Chair");
Thread t1 = new Thread (obj1);
Thread t2 = new Thread (obj2);
t1.start ();
t2.start ();
}
}
Output:

Write a program to create multiple threads and make the threads to act on single object
package Threads;
class Reserve implements Runnable
{
int available = 1;
int wanted;
Reserve (int i)
{
wanted = i;
}
public void run()
{
synchronized(this)
{
System.out.println ("Number of berths available: " + available);
if ( available >= wanted)
{
String name = Thread.currentThread().getName ();
System.out.println (wanted + " berths alloted to: " + name);
try {
Thread.sleep (2000); // wait for priniting the ticket printed
available = available - wanted; //zero
}
catch (InterruptedException ie)
{
ie.printStackTrace ();
}
}
else
{
System.out.println ("Sorry, no berths available");

}
}
}
}

public class Safe {


public static void main(String args[]) {
Reserve obj = new Reserve (1); //wanted =1
Thread t1 =new Thread (obj); //one person from hyd one seat reserve
Thread t2 = new Thread (obj);// 2nd person from ap one seat
t1.setName ("First Person");
t2.setName ("Second Person");
t1.start ();
t2.start ();
}
}

Output:
Write a program to demonstrate the creation of thread group
//Using ThreadGroup import javaio*;
class WhyTGroups
{
public static void main (String args[]) throws IOException
{
Reservation res = new Reservation ();
Cancellation can = new Cancellation (); //Create a
ThreadGroup
ThreadGroup tg = new ThreadGroup ("Reservation Group");
//Create 2 threads and add them to thread group
Thread t1 = new Thread (tg, res, "First Thread");
Thread t2 = new Thread (tg, res, "Second Thread");
//Create another thread group as a child to tg
ThreadGroup tg1 = new ThreadGroup (tg, "Cancellation Group");
Thread t3 = new Thread (tg1, can, "Third Thread");
Thread t4 = new Thread (tg1, can, "Fourth Thread"); //find parent group of tg1

System.out.println ("Parent of tg1 = " + tg1.getParent ());


//set maximum priority
tg1.setMaxPriority (7);
System.out.println ("Thread group of t1 = " + t1.getThreadGroup ());
System.out.println ("Thread group of t3 = " + t3.getThreadGroup ());
t1.start ();
t2.start ();
t3.start ();
t4.start ();
System.out.println ("Number of threads in this group : " + tg.activeCount () );
}
}
class Reservation extends Thread
{
public void run ()
{
System.out.println ("I am Reservation Thread");
}
}
class Cancellation extends Thread
{
public void run ()
{
System.out.println ("I am Cancellation Thread");
}
}
Output:
Java Database Connectivity
Introduction to JDBC:
 Databases are used to store customer information, order information, production information,
even messages.
 Relational databases are commonly used. Several companies offer relational database
products which offer excellent performance on a data server.
 Oracle and Microsoft SQL Server together account for most of the market, with Informix,
SyBase and Ingres offering competing products.
 There are also open source relational database products such as MySQL and PostgreSQL.
 RDB uses Tables consisting of rows of columns. Column holds single value of predefined
data type. SQL is used to access data, which is ANSI standard.
 RDB comes in all shapes & sizes. API used to execute SQL statements different for DB
engines. Java libraries include API called JDBC. JDBC defines set of classes used to execute
SQL.
 The JDBC (Java Database Connectivity) API defines interfaces and classes for writing
database applications in Java by making database connections. Using JDBC you can send
SQL, PL/SQL statements to almost any relational database. JDBC is a Java API for executing
SQL statements and supports basic SQL functionality.

JDBC Environment Setup


Steps to set up a JDBC environment:
1. Install JDK: Ensure Java Development Kit (JDK) is installed.
2. Install MySQL: Download and install MySQL database.
3. Add MySQL JDBC Driver: Download MySQL Connector/J and add it to the Java project
classpath.
4. Configure IDE: Set up your IDE (Eclipse, IntelliJ) to include the MySQL JDBC driver .jar file.
5. Write Java Code: Set up a Java program to connect and interact with the database.

Steps for developing a JDBC program:


1. Loading the drivers.
2. Obtain the connection or specify the URL.
3. Pass the query.
4. Process the result which is obtained from database.
5. Close the connection.
JDBC is the standard specification released by SUN micro systems to develop the applications in
database world. JDBC contains set of interfaces and these interfaces are implemented by various
database vendors and server vendors.
A driver is nothing but a java class which acts as a middle layer between java program and database
program. As on today all the drivers are developed by either database vendors or server vendors.
For example:
class x implements
{
…………;
…………;
…………;
};
Here, x is driver and is JDBC interface. In database world, each and every database vendor
has developed their drivers and released to the market in the form of jar files.
JDBC Drivers:
A JDBC driver translates standard JDBC calls into a network or database protocol or into a
database library API call that facilitates communication with the database. This translation layer
provides JDBC applications with database independence. If the back-end database changes, only
the JDBC driver need be replaced with few code modifications required.

JDBC Drivers Types:


JDBC driver implementations vary because of the wide variety of operating systems and hardware
platforms in which Java operates.
There are four types of JDBC drivers known as:
1. JDBC-ODBC bridge plus ODBC driver, also called Type 1.
2. Native-API, partly Java driver, also called Type 2.
3. JDBC-Net, pure Java driver, also called Type 3.
4. Native-protocol, pure Java driver, also called Type 4.

Loading the drivers:


Loading the drivers is nothing but creating an object of appropriate Driver class. In order to load
the drivers we have two ways, they are:
1) Using Class.forName
For example:
Class.forName (Sun.jdbc.odbc.JdbcOdbcDriver);
Class.forName (oracle.jdbc.driver.OracleDriver);

2) Using DriverManager.registerDriver
DriverManager class contains the following method which will load the driver at runtime.
public static void registerDriver (java.sql.Driver);
Driver is an interface which is implemented by various database vendors and server vendors. If
the appropriate driver object is created that driver object will act as a middle layer between program
and database. If the driver is not found we get an exception called java.sql.SQLException
For example:
DriverManager.registerDriver (new Sun.jdbc.odbc.JdbcOdbcDriver);
[for oracle driver is – classes111.jar]

How to obtain the connection: After loading the drivers, it is required to obtain the connection
from the database.
Syntax or URL for obtaining connection:
Here, jdbc is the main protocol which takes java request and hand over into database environment
through Data Source Name. odbc is the sub protocol which takes the database result and gives to
java environment. Data Source Name is the configuration tool in the current working machine
through which the data is passing from java environment to database and database to java
environment.

Here, jdbc is the main protocol which takes java request and hand over into database environment
through Data Source Name. odbc is the sub protocol which takes the database result and gives to
java environment. Data Source Name is the configuration tool in the current working machine
through which the data is passing from java environment to database and database to java
environment.
In order to obtain the connection from the database, as a part of jdbc we have a predefined
class called java.sql.DriverManager which contains the following methods:
1. public static Connection getConnection (String URL);
2. public static Connection getConnection (String URL, String username, String password);
Method-1, we use to obtain the connection from those databases where there is no
username and password databases. Method-2 is used for those databases where there is username
and password.
For example:
Connection con1=DriverManager.getConnection (“jdbc : odbc : Access”);
Connection con2=DriverManager.getConnection (“jdbc : odbc : oracle”,”scott”,”tiger”);

Pass the query: A query is nothing but a request or question to the database.
Queries are of three types; they are
1. static query,
2. dynamic or pre-compiled query
3. stored procedures

STATIC QUERY: Static query is one in which the data is passed in the query itself.
For example:
1. select * from Student where marks>50;
2. insert into Student values (100, ‘abc’, 90.86);
In order to execute static queries we must obtain an object of java.sql.Statement interface.In the
interface java.sql.Connection we have the following method for obtaining an object of Statement
interface.

For example:
Statement st = con1.createStatement ();

On database three categories of operations takes place, they are insertion, deletion and updation.
In order to perform these operations we must use the following method which is present in
statement interface.
Here, String represents either static insertion or static deletion or static updation. The return type
int represents the status of the query. If the query is not successful it returns zero and if the query
is successful it returns non-zero.

Processing the query result:


In order to execute the select statement or in order to retrieve the data from database we must use
the following method which is present in java.sql.Statement interface.

Here, String represents a query which contains select statement. executeQuery returns an object
of ResultSet to hold the number of records returned by select statement. ResultSet is an interface
whose object contains all the records returned by a query and it will point to just before the first
record.
For example:
ResultSet rs=st.executeQuery (“select * from Student”);
The ResultSet object is pointing by default just before the first record, in order to bring first
record we must use the below given method. Method returns true when rs contains next record
otherwise it returns false.
public boolean next ();
In order to obtain the data of the record (collection of field values) we must use the following
method:
public String getString (int colno);

Whatever the data retrieving from the record that data will be treated as string data.
For example:
String s1=rs.getString (1);
String s1=rs.getString (2);
String s1=rs.getString (3);

ResultSet:
1. An object of ResultSet allows us to retrieve the data by default only in forward direction but not
in backward direction and random retrieval.
2. Whenever we get the database data in ResultSet object which will be temporarily disconnected
from the database.
3. ResultSet object does not allows us to perform any modifications on ResultSet object.
4. Hence, the ResultSet is by default non-scrollable disconnected ResultSet.

DYNAMIC or PRE-COMPILED QUERIES:


1. Dynamic queries are those for which the data is passed at runtime.
2. To execute dynamic queries we must obtain an object of PreparedStatement.
Here, the ‘?’ is known as dynamic substitution operator or positional parameter. The position of
the positional parameters must always starts from left to right with the numbers 1, 2……n.

In order to set the values to the positional parameters, we must use the following methods which are
present in prepared statement interface.
public void setByte (int, byte);
public void setShort (int, short);
public void setInt (int, int);
public void setLong (int, long);
public void setFloat (int, float);
public void setDouble (int, double);
public void setChar (int, char);
public void setString (int, string);

In general PreparedStatement interface contains the following generalized method to set the
values for positional parameters.
public void setXXX (int, XXX);

Here, int represents position number of the positional parameter. XXX represents value of
either fundamental data type or string or date.

For example:
ps.setInt (1, 10);
In order to execute the DCL statements (select) and DML statements (insert, delete and update)
we must use the following methods which are present in PreparedStatement interface.
public int executeUpdate (); _ Dynamic DML/DDL
public ResultSet executeQuery (); _ Dynamic DCL (select)
For example:
ResultSet rs=ps.executeQuery ();
Close connection
For example:
con.close ();

Type 1 JDBC-ODBC Bridge ;


Type 1 drivers act as a "bridge" between JDBC and another database connectivity mechanism such
as ODBC. The JDBC- ODBC bridge provides JDBC access using most standard ODBC drivers.
This driver is included in the Java 2 SDK within the sun.jdbc.odbc package. In this driver the java
statements are converted to a jdbc statements. JDBC statements calls the ODBC by using the
JDBC-ODBC Bridge. And finally the query is executed by the database. This driver has serious
limitation for many applications.
Functions:
 Translates query obtained by JDBC into corresponding ODBC query, which is then handled
by the ODBC driver.
 Sun provides a JDBC-ODBC Bridge driver. sun.jdbc.odbc.JdbcOdbcDriver. This driver is
native code and not Java, and is closed source.
 Client -> JDBC Driver -> ODBC Driver -> Database
There is some overhead associated with the translation work to go from JDBC to ODBC.

Type 1 JDBC Architecture

Advantages:
Almost any database for which ODBC driver is installed, can be accessed.
Disadvantages:
1. Performance overhead since the calls have to go through the JDBC overhead bridge to the
ODBC driver, then to the native database connectivity interface.
2. The ODBC driver needs to be installed on the client machine.
3. Considering the client-side software needed, this might not be suitable for applets.
Type 2 Driver:
Type 2 drivers use the Java Native Interface (JNI) to make calls to a local database library API.
This driver converts the JDBC calls into a database specific call for databases such as SQL,
ORACLE etc. This driver communicates directly with the database server. It requires some native
code to connect to the database. Type 2 drivers are usually faster than Type 1 drivers. Like Type
1 drivers, Type 2 drivers require native database client libraries to be installed and configured on
the client machine.
Functions:
1. This type of driver converts JDBC calls into calls to the client API for that database.
2. Client -> JDBC Driver -> Vendor Client DB Library -> Database

Type 2 JDBC Architecture

Advantage:
Better performance than Type 1 since no jdbc to odbc translation is needed.
Disadvantages
1. The vendor client library needs to be installed on the client machine.
2. Cannot be used in internet due the client side software needed
3. Not all databases give the client side library.

Type 3 Java to Network Protocol Or All- Java Driver:


Type 3 drivers are pure Java drivers that use a proprietary network protocol to communicate with
JDBC middleware on the server. The middleware then translates the network protocol to database-
specific function calls. Type 3 drivers are the most flexible JDBC solution because they do not
require native database libraries on the client and can connect to many different databases on the
back end.
Type 3 drivers can be deployed over the Internet without client installation.
(Java-------> JDBC statements------> SQL statements ------ > databases.
Functions:
1. Follows a three tier communication approach.
2. Can interface to multiple databases - Not vendor specific.
3. The JDBC Client driver written in java, communicates with a middleware-net-server using a
database independent protocol, and then this net server translates this request into database
commands for that database.
4. Thus the client driver to middleware communication is database independent.
5. Client -> JDBC Driver -> Middleware-Net Server -> Any Database

Type 3 JDBC Architecture:

Advantages
1. Since the communication between client and the middleware server is database independent,
there is no need for the vendor db library on the client machine. Also the client to middleware
needn’t be changed for a new database.
2. The Middleware Server (Can be a full-fledged J2EE Application server) can provide typical
middleware services like caching (connections, query results, and so on), load balancing, logging,
auditing etc.
3. eg. For the above include jdbc driver features in WebLogic.
4. Can be used in internet since there is no client side software needed.
5. At client side a single driver can handle any database. (It works provided the middleware
supports that database!!)

Disadvantages
1. Requires database-specific coding to be done in the middle tier.
2. An extra layer added may result in a time-bottleneck. But typically this is overcome by providing
efficient middleware services described above.

Type 4 Java to Database Protocol.


Type 4 drivers are pure Java drivers that implement a proprietary database protocol (like Oracle's
SQL*Net) to communicate directly with the database. Like Type 3 drivers, they do not require
native database libraries and can be deployed over the Internet without client installation. One
drawback to Type 4 drivers is that they are database specific.
Unlike Type 3 drivers, if your back-end database changes, you may save to purchase and deploy
a new Type 4 driver (some Type 4 drivers are available free of charge from the database
manufacturer). However, because Type drivers communicate directly with the database engine
rather than through middleware or a native library, they are usually the fastest JDBC drivers
available. This driver directly converts the java statements to SQL statements.

Functions
1. Type 4 drivers are entirely written in Java that communicate directly with a vendor's database
through socket connections. No translation or middleware layers, are required, improving
performance.
2. The driver converts JDBC calls into the vendor-specific database protocol so that client
applications can communicate directly with the database server.
3. Completely implemented in Java to achieve platform independence.
4. e.g include the widely used Oracle thin driver - oracle.jdbc.driver. OracleDriver which connect
to jdbc:oracle:thin URL format.
5. Client Machine -> Native protocol JDBC Driver -> Database server

Type 4 JDBC Architecture

Advantages
These drivers don't translate the requests into db request to ODBC or pass it to client API for the
db, nor do they need a middleware layer for request indirection. Thus the performance is
considerably improved.
Disadvantage
At client side, a separate driver is needed for each database

Architecture and components of JDBC:


JDBC Architecture:
The JDBC API supports both two-tier and three-tier processing models for database access but in
general JDBC Architecture consists of two layers:
1. JDBC API: This provides the application-to-JDBC Manager connection.
2. 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. The
driver manager is capable of supporting multiple concurrent drivers connected to multiple
heterogeneous databases.
Following is the architectural diagram, which shows the location of the driver manager with
respect to the JDBC drivers and the Java application:

Common JDBC Components:


The JDBC API provides the following interfaces and classes:
 DriverManager: This interface manages a list of database drivers. Matches connection
requests from the java application with the proper database driver using communication
subprotocol. The first driver that recognizes a certain subprotocol under JDBC will be
used to establish a database Connection.
 Driver: This interface handles the communications with the database server. You will
interact directly with Driver objects very rarely. Instead, you use DriverManager objects,
which manages objects of this type. It also abstracts the details associated with working
with Driver objects
 Connection: Interface with all methods for contacting a database. The connection
objectrepresents communication context, i.e., all communication with database is through
connection object only.
 Statement: You use objects created from this interface to submit the SQL statements to
the database. Some derived interfaces accept parameters in addition to executing stored
procedures.
 ResultSet: These objects hold data retrieved from a database after you execute an SQL
 query using Statement objects. It acts as an iterator to allow you to move through its data.
 SQLException: This class handles any errors that occur in a database application.

An Example Diagram

Java JDBC: Interaction of the core JDBC components during the execution of a database query.
JDBC Driver
A JDBC driver translates standard JDBC calls into a network or database protocol or into a
database library API call that facilitates communication with the database. This translation layer
provides JDBC applications with database independence. If the back-end database changes, only
the JDBC driver need be replaced with few code modifications required.

Topic 4: MS-Access/ORACLE/MySQL for (Type-3 and Type-4) connection


Which Driver should be used?
So, you may be asking yourself, "Which is the right type of driver for your application?" Well,
that depends on the requirements of your particular project
 If you are accessing one type of database, such as Oracle, Sybase, or IBM, the preferred driver
type is 4.
 If your Java application is accessing multiple types of databases at the same time, type 3 is the
preferred driver.
 Type 2 drivers are useful in situations where a type 3 or type 4 driver is not available yet for
your database.
 The type 1 driver is not considered a deployment-level driver and is typically used for
development and testing purposes only.

Connecting MS Access Using ucanacess Driver:


Download the ucanaccess driver from the internet by clicking the below link
ucanaccess jar file download

Creating a table in MS-Access:


Step: 1 - Go to Search open ms-access and create a blank database
Step: 2 – save the database name and create a table in the database.
Step: 3 – Create columns to the table by right clicking on table
design view
Step: 4 – Insert rows into the table by assigning values.

Java Program:
import java.sql.*;
public class DBExample
{
public static void main(String[] args) throws SQLException
{
String url="jdbc:ucanaccess://C://Users//Ajay007//Desktop//JAVA
PROGRAMS//DBProject//GIET.accdb";
Connection con=DriverManager.getConnection(url);
System.out.println("Connected to MS Access Database");
Statement s=con.createStatement();
ResultSet rs=s.executeQuery("Select * from Student");
while(rs.next())
{
System.out.println(rs.getInt(1)+"\t\t"+rs.getString(2)+"\t\t
"+rs.getString(3)+"\t\t"+rs.getString(4));
}
}

Output:

Connecting MySQL Database:

Creating a table in MySQL Database:


Step: 1 – Download and Install Xampp Software Tool.
Step: 2 – Start Apache server and MySQL database in Xampp Control panel.
Step: 3 – Create a table in test database.
Step: 4 – Insert rows into the table by assigning values.

Design the GUI Components by using Palette:


Create a MySQL database and create a user table as bellow:

Java Program to connect to MySQL Database:


import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.JButton;
import java.sql.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Registration extends JFrame
{

private JPanel contentPane;


private JTextField user;
private JTextField email;
private JTextField pass;
private JTextField uid;

public static void main(String[] args)


{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
try
{
Registration frame = new Registration();
frame.setVisible(true);
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
}
public Registration()
{
setDefaultCloseOperation(3);
setFont(new Font("Tahoma", Font.PLAIN, 16));
setBounds(232, 251, 551, 462);
contentPane =new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(null);
setContentPane(contentPane);

JLabel ul = new JLabel("USER NAME ");


ul.setFont(new Font("Tahoma", Font.PLAIN, 16));
ul.setBounds(87, 57, 117, 28);
contentPane.add(ul);

user = new JTextField();


user.setBounds(202, 64, 200, 21);
contentPane.add(user);
user.setColumns(10);

JLabel eml = new JLabel("EMAIL ");


eml.setFont(new Font("Tahoma", Font.PLAIN, 16));
eml.setBounds(119, 112, 85, 19);
getContentPane().add(eml);

email = new JTextField();


email.setBounds(202, 112, 200, 21);
contentPane.add(email);
email.setColumns(10);

JLabel pl = new JLabel("Password");


pl.setFont(new Font("Tahoma", Font.PLAIN, 16));
pl.setBounds(103, 155, 73, 28);
getContentPane().add(pl);

pass = new JTextField();


pass.setBounds(202, 162, 200, 19);
contentPane.add(pass);
pass.setColumns(10);

JButton b1 = new JButton("REGISTER");


b1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","");
PreparedStatement ps=con.prepareStatement("insert into user(user_id,user_name,user_email,user_pass)
values(?,?,?,?)");
ps.setString(1, uid.getText());
ps.setString(2, user.getText());
ps.setString(3, email.getText());
ps.setString(4, pass.getText());
int x=ps.executeUpdate();
if(x>0)
{
System.out.println("Registeration Done Successfully");
}
else
{
System.out.println("Registration Failed");
}
}
catch(Exception e1)
{
System.out.println(e1);
}

}
});
b1.setFont(new Font("Tahoma", Font.PLAIN, 16));
b1.setBounds(256, 233, 200, 29);
contentPane.add(b1);

JLabel idl = new JLabel("USER ID");


idl.setFont(new Font("Tahoma", Font.PLAIN, 16));
idl.setBounds(103, 28, 73, 19);
contentPane.add(idl);

uid = new JTextField();


uid.setBounds(202, 30, 200, 19);
contentPane.add(uid);
uid.setColumns(10);

JButton b2 = new JButton("RESET");


b2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
uid.setText("");
user.setText("");
email.setText("");
pass.setText("");
}
});
b2.setFont(new Font("Tahoma", Font.PLAIN, 16));
b2.setBounds(71, 234, 133, 27);
contentPane.add(b2);
}
}
Connecting to Oracle Database:

Java Program:
Output:
Oracle Database Query:
Unit-5
Java FX GUI: Java FX Scene Builder, Java FX App Window Structure, displaying text and image,
event handling.
1. JavaFX GUI: Introduction
JavaFX is a framework for building graphical user interfaces (GUIs) in Java. It is used to create modern,
feature-rich applications with a wide range of components like buttons, text fields, images, and event-driven
functionalities. JavaFX has replaced the older Swing framework for building GUIs in Java.

2. JavaFX Scene Builder


JavaFX Scene Builder is a visual design tool that allows developers to design JavaFX application interfaces
without writing code manually.
• Drag-and-Drop Interface: Developers can drag and drop UI components (buttons, text fields, etc.)
into the layout.
• FXML Support: Generates FXML files (XML-based language) that describe the UI structure. Java
code can load and use these FXML files.
• Easy Integration: Scene Builder can be used alongside an IDE like Eclipse or IntelliJ, making it
easier to integrate into projects.
Steps:
1. Download and install Scene Builder.
2. Create an FXML file.
3. Design the interface by dragging UI components in Scene Builder.
4. Save the FXML file and integrate it with Java code.

3. JavaFX App Window Structure


A JavaFX application consists of several important components:
• Stage: The main window or container for a JavaFX application. It represents the outer window of
the application.
• Scene: The container inside the Stage that holds all the visual components (UI elements). A Stage
can only have one Scene at a time, but the scene can be switched.
• UI Controls: Individual components like buttons, text fields, labels, etc., that are added to the scene.
Typical Application Structure:
public class MainApp extends Application {
@Override
public void start(Stage primaryStage) {
// Create a root node (e.g., VBox or BorderPane)
VBox root = new VBox();
// Create a Scene
Scene scene = new Scene(root, 300, 250);
// Set the Scene to the Stage
primaryStage.setScene(scene);
// Set stage title and show the stage
primaryStage.setTitle("JavaFX Application");
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
In this example:
• Stage: The main application window.
• Scene: Contains all UI components (VBox, buttons, etc.).

4. Displaying Text and Images in JavaFX


JavaFX makes it easy to display both text and images using the built-in Label and ImageView controls.
a) Displaying Text:
To display text, use the Label class:
Label label = new Label("Hello, JavaFX!");
root.getChildren().add(label); // Adding label to the layout
b) Displaying Images:
To display an image, use the Image and ImageView classes:
Image image = new Image("file:src/images/sample.png"); // Load image
ImageView imageView = new ImageView(image); // Display image
root.getChildren().add(imageView); // Adding image view to the layout
• Image: Holds the image data.
• ImageView: Renders the image in the UI.

5. Event Handling in JavaFX


Event handling in JavaFX is used to make the application interactive by responding to user inputs (like
button clicks, key presses, etc.).
• Event: Any action triggered by the user (e.g., mouse clicks, key presses).
• EventHandler: An interface that handles the events triggered by user interaction.
Example: Button Click Event
Button button = new Button("Click Me");
button.setOnAction(event -> {
System.out.println("Button clicked!");
});
root.getChildren().add(button);
• setOnAction(): Registers an event handler for the button click event.
• event -> {}: This is a lambda expression that acts as the event handler, which is triggered when the
button is clicked.
Other Event Types:
• Mouse Events: Mouse click, hover, etc. (setOnMouseClicked(), setOnMouseEntered(), etc.)
• Keyboard Events: Key presses, releases (setOnKeyPressed(), setOnKeyReleased()).
JavaFX provides a comprehensive event handling system, making it possible to react to various user actions
in an intuitive way.

This brief overview covers essential aspects of working with JavaFX GUIs, including building interfaces
with Scene Builder, displaying content like text and images, and handling events to make applications
interactive.

You might also like