0% found this document useful (0 votes)
3 views43 pages

Unit 3 - APP

Unit 3 discusses Java Concurrency, highlighting its ability to run multiple operations simultaneously through threads and processes, which enhances performance and resource utilization. It covers key concepts such as multitasking, thread safety, synchronization, and the differences between extending the Thread class and implementing the Runnable interface. Additionally, it introduces JDBC as a means for Java applications to interact with databases, facilitating SQL operations.

Uploaded by

jaintejasva26
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views43 pages

Unit 3 - APP

Unit 3 discusses Java Concurrency, highlighting its ability to run multiple operations simultaneously through threads and processes, which enhances performance and resource utilization. It covers key concepts such as multitasking, thread safety, synchronization, and the differences between extending the Thread class and implementing the Runnable interface. Additionally, it introduces JDBC as a means for Java applications to interact with databases, facilitating SQL operations.

Uploaded by

jaintejasva26
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Unit 3

Concurrent Programming Paradigm

 Java Concurrency is the capability of the Java platform to run


multiple operations simultaneously. The operations could be
multiple Java programs or parts of a single Java program. Java
Concurrency relies on two essential components such as threads
and processes. Of the two components, threads play a significant
role.
 With Java Concurrency or using multiple threads, you can enhance
the performance of processors. You don’t need multiple processors
for running concurrent programs in Java; instead, you can use a
single multi-core processor. Know that a multi-core processor will
have many cores in a single CPU. All these multiple cores can run
many programs or parts of a program simultaneously.
 You are probably familiar with multitasking, which is when
someone tries to perform two or more tasks simultaneously. While
people are not very good at multitasking, it turns out that
computers are! It has become increasingly common place for
computer systems to have multiple processors, or processors with
multiple execution cores, which greatly enhances a system’s
capacity for concurrent execution of processes and threads.
This process is possible even on simple systems, with only one
processor or execution core.
 In software terms, performing multiple tasks at the same time is
called concurrency. Concurrency may also be defined as the ability
to run several programs or several parts of a program in parallel.

Why Concurrent Programming/Benefits/Advantages?


Concurrent programming is essential in modern computing for
several reasons:
1. Performance Improvement: Concurrent programs can utilize
multiple CPU cores efficiently, which can lead to significant
performance improvements for CPU-bound tasks.
2. Responsiveness: For applications with user interfaces,
concurrency ensures that the application remains responsive even
when performing time-consuming operations in the background.
3. Resource Utilization: Concurrent programs can make better use of
system resources, such as CPU time, memory, and I/O devices.
4. Parallelism: Some tasks naturally lend themselves to parallel
execution, like rendering graphics, processing data, or handling
multiple client requests in a server application.

Key Concepts in Concurrent Programming:

1. Thread: A thread is the smallest unit of execution within a


program. It represents an independent flow of control that can
run concurrently with other threads. Most programming
languages, including Java, C++, and Python, provide thread
support.
2. Process: A process is a self-contained program that runs
independently and has its own memory space. Processes can
have multiple threads, and inter-process communication (IPC) is
required for them to communicate.
3. Concurrency vs. Parallelism: These terms are often used
interchangeably, but they have distinct meanings. Concurrency
is about managing multiple tasks in overlapping time periods,
while parallelism is about executing multiple tasks
simultaneously.
4. Synchronization: When multiple threads or processes access
shared resources (like variables, data structures, or files),
synchronization mechanisms are needed to ensure data
consistency and avoid conflicts, such as race conditions.
5. Race Condition: A race condition occurs when two or more
threads or processes access shared data concurrently, leading to
unpredictable and erroneous behavior. Proper synchronization
can prevent race conditions.
6. Mutex (Mutual Exclusion): A mutex is a synchronization
primitive that allows only one thread or process to access a
shared resource at a time. It helps prevent race conditions.
7. Thread Safety: Code is considered thread-safe when it can be
safely executed by multiple threads without causing data
corruption or unexpected behavior. Design patterns and
synchronization mechanisms are used to ensure thread safety.
8. Deadlock: Deadlock occurs when two or more threads or
processes are unable to proceed because each is waiting for the
other to release a resource. Careful design and resource
management are essential to avoid deadlocks.
9. Thread Pool: A thread pool is a collection of pre-initialized
threads that can be reused for executing tasks, which helps
minimize the overhead of thread creation and destruction.
10. Concurrency Control: In database systems, concurrency
control mechanisms ensure that multiple transactions can access
and modify the database concurrently without causing data
inconsistencies.

What is Multitasking in Java?

Multitasking is the process that lets users perform multiples tasks at


the same time. There are two ways to enable multitasking in Java:
1. Process-based multitasking (Multiprocessing): The
processes in this type of multitasking are heavy and a
lot of time is consumed. This is because the program
takes a long time to switch between different processes.
2. Thread-based multitasking (Multithreading): Threads
are light-weight compared to process-based multi
tasking, and the time taken to switch between them is
shorter.
Multithreading:
 Multithreading is a technique that allows for concurrent
(simultaneous) execution of two or more parts of a program for
maximum utilization of a CPU.
 As a really basic example, multithreading allows you to write code
in one program and listen to music in another. Programs are made
up of processes and threads. You can think of it like this:
 A program is an executable file like [Link]
 A process is an executing instance of a program. When you double
click on the Google Chrome icon on your computer, you start a
process which will run the Google Chrome program.
Thread is the smallest executable unit of a process. A process can have
multiple threads with one main thread. In the example, a single thread
could be displaying the current tab you’re in, and a different thread
could be another tab.

1. Thread Class Overview


The fundamental building block for concurrent execution is the Thread
class, which provides constructors and methods for thread creation,
management, and execution.
A Thread in Java is a basic unit of CPU utilization representing a path
of execution within a program. Java lets applications run multiple
threads simultaneously, enabling concurrent programming for improved
performance and responsiveness.
Java's Thread class enables concurrent execution by representing a
thread of control within a program. It extends the Object class and
implements the Runnable interface. Each thread object can be created
and managed using the methods provided by this class.
Main Constructors of Thread Class
The most common constructors used to create thread objects are:
Constructor Description
Thread() Default constructor; creates a
new thread object.
Thread(String name) Creates a thread with a specified
name.
Thread(Runnable target) Creates a thread to execute
the run() method of
a Runnable target.
Thread(Runnable target, Creates a thread with
String name) a Runnable target and a specified
name.
Thread(ThreadGroup group, Creates a thread within a specific
Runnable target) thread group executing
a Runnable.

1. Thread()
Allocates a new thread object with default settings. Typically used when
subclassing Thread and overriding run().
Thread t1 = new Thread();
Creates a new thread object with default name and group.
2. Thread (Runnable target)
Associates the new thread with a specific task defined by the Runnable
interface.
Runnable r = () -> [Link]("Runnable task running...");
Thread t2 = new Thread(r);
[Link]();
Executes the run() method of the provided Runnable when started.
3. Thread (String name)
Names the thread, aiding in debugging and maintenance.
Thread t3 = new Thread("WorkerThread");
[Link]([Link]()); // Outputs: WorkerThread
Useful for custom logging and thread identification.
4. Thread(Runnable target, String name)
Combines task delegation (Runnable) with identification (name).
Runnable r2 = () -> [Link]("Named Runnable running");
Thread t4 = new Thread(r2, "CustomTaskThread");
Executes custom code and assigns a thread name for easier management.
5. Thread(ThreadGroup group, Runnable target)
Places the thread in a specified group (ThreadGroup), executing the
given task.
ThreadGroup tg = new ThreadGroup("PaymentThreads");
Runnable r3 = () -> [Link]("Thread in Payment Group");
Thread t5 = new Thread(tg, r3);
[Link]();

The ThreadGroup class manages a set of threads and thread groups,


allowing collective control over their behavior and states.
Key Features
Hierarchy: ThreadGroups can contain child groups, forming a tree
structure.
Collective Management: Interrupt, enumerate, or set priority for all
member threads with a single operation.
Essential Thread Methods

Method Action

start() Begins thread execution, calls run()

run() Code to execute within thread

sleep(long millis) Thread sleeps for specified ms

join() Waits for thread to die[

interrupt() Interrupts thread

isAlive() Checks if thread is alive

getName()/setName() Get/set thread name

setPriority(int value) Set thread priority

Program of creating threads by extending Thread class:


class MyThread extends Thread {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
[Link]([Link]().getName() + " - Count : " + i);
try {
[Link](500);
} catch (InterruptedException e) {
[Link]("Thread interrupted");
}
}
}
}

public class T {
public static void main(String[] args) {
MyThread thread1 = new MyThread();
MyThread thread2 = new MyThread();

[Link]("Thread 1");
[Link]("Thread 2");

[Link]();
[Link]();
}
}

//Code Analysis Step by Step (This green portion between // is just


for your understanding)
1. Creating a Thread Class
class MyThread extends Thread {
@Override
public void run() {
...
}
}

class MyThread extends Thread:


Here, you are creating a custom thread class by extending the built-in Thread class.
The Thread class in Java has a method called run() which contains the code that the
thread executes.
@Override public void run():
You override the run() method to define what task this thread should perform when
it starts.
2. Defining the Work of the Thread
for (int i = 0; i < 5; i++) {
[Link]([Link]().getName() + " - Count : " + i);
try {
[Link](500);
} catch (InterruptedException e) {
[Link]("Thread interrupted");
}
}

Loop runs 5 times → each iteration prints the thread’s name and a count.
[Link]().getName():
Gets the name of the currently running thread (useful when multiple threads run
together).
[Link](500):
Pauses the current thread for 500 milliseconds (0.5 seconds) before continuing to
the next iteration.
This makes the output more readable and simulates some "work" being done.
catch (InterruptedException e):
Handles a situation where another thread interrupts this one while it is sleeping.

3. Main Class
public class T {
public static void main(String[] args) {
MyThread thread1 = new MyThread();
MyThread thread2 = new MyThread();
Two objects of MyThread are created → thread1 and thread2.
Each object represents a separate thread of execution.

4. Naming the Threads


[Link]("Thread 1");
[Link]("Thread 2");
Assigns custom names so we can distinguish their outputs.
If you don’t set a name, Java will give them default names like Thread-0, Thread-
1, etc.

5. Starting the Threads


[Link]();
[Link]();
Very important:
start() method → actually starts a new thread and internally calls the run() method.
If you call run() directly (without start()), it will not run in a new thread, it will run
like a normal method in the main thread.
Now thread1 and thread2 will run concurrently (in parallel).

Program Execution Flow


1. JVM starts executing main() in the main thread.
2. Two MyThread objects are created.
3. Names are assigned to them.
4. [Link]() and [Link]() are called:
5. The JVM schedules both threads and starts executing their run() methods.
Execution order is not fixed because thread scheduling is controlled by the JVM
and OS.
Both threads run their loops, print messages, and sleep for 500ms between
iterations.

Sample Output (may vary each run)


Thread 1 - Count : 0Thread 2 - Count : 0Thread 1 - Count : 1Thread 2 - Count :
1Thread 2 - Count : 2Thread 1 - Count : 2Thread 1 - Count : 3Thread 2 - Count :
3Thread 1 - Count : 4Thread 2 - Count : 4
The order can change each time you run the program because threads
run concurrently and scheduling is unpredictable.
In short:
MyThread defines the task.
start() makes them run in parallel.
sleep() simulates work and makes interleaving visible.
The JVM decides which thread runs when. //

Approaches to create thread (Extending Thread and Implementing


Runnable Interface):
1. Extending Thread Class: Define behavior by overriding its run()
method in a subclass. Direct extension of Thread for more advanced
control over thread states.
2. Implementing Runnable Interface: Define the behavior in a class
implementing the Runnable interface, passing it to a Thread object.
Preferred for resource sharing and loose coupling; implement run()
method.
Runnable is a functional interface with the method:
public void run();

Implement this for classes where a thread's task is defined separately


from thread management.
Program to create Threads by implementing Runnable Interface:
class MyRunnable implements Runnable {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
[Link]([Link]().getName() + " - Count : " + i);
try {
[Link](500);
} catch (InterruptedException e) {
[Link]("Thread interrupted");
}
}
}
}

public class RI {
public static void main(String[] args) {
// Create instances of MyRunnable
MyRunnable runnable1 = new MyRunnable();
MyRunnable runnable2 = new MyRunnable();

// Pass runnable instances to Thread objects


Thread thread1 = new Thread(runnable1, "Thread 1");
Thread thread2 = new Thread(runnable2, "Thread 2");

// Start the threads


[Link]();
[Link]();
}
}
Explanation
 Thread t1 and Thread t2 are created with the same Runnable task.

 Both run concurrently (Java scheduler decides order).


 [Link]().getName() helps you see which thread is
printing.

Let’s compare both approaches side by side.


Using Runnable is preferred over extending Thread because Java
supports only single inheritance, and with Runnable you can extend
another class too.
Why Two Approaches Exist?
 Extending Thread → quick & simple but less flexible (can’t
extend any other class).
 Implementing Runnable → more flexible & reusable, and often
preferred in real-world projects.

How they relate


 A Thread object is-a Runnable, since it implements Runnable.
 But a Runnable object is not a Thread — it’s just the “task”.
 That’s why you usually see:
Runnable r = new MyRunnable(); // task
Thread t = new Thread(r); // thread that executes task
[Link](); // runs [Link]()
So in short:

 Runnable = job description (what needs to be done).


 Thread = worker hired to perform that job.
 You can have many workers (threads) running the same job
(Runnable task) or different ones.

Difference between the two:


Feature Using Runnable Using Thread
Can extend another class Can’t extend another class
Inheritance (since you only implement (Java allows only single
Runnable) inheritance)
Flexibility More flexible, widely used Less flexible
Class implements Runnable
Class directly extends
Implementation and passed to Thread
Thread
constructor

Best Practice: Use Runnable interface in real-world applications,


because it gives more flexibility and is better for designing reusable
classes.
Declarative Programming Paradigm (JDBC)
Introduction to JDBC (Java Database Connectivity)
JDBC is a Java API that allows Java programs to connect and interact
with databases. It provides a standard set of interfaces and classes for
executing SQL queries and retrieving results from any relational
database like MySQL, Oracle, PostgreSQL, SQL Server, etc.

Why use JDBC?


 Java applications often need to store, retrieve, and manipulate data
in a database.
 JDBC acts as a bridge between Java programs and databases,
enabling seamless communication.
 It supports all major SQL operations: SELECT, INSERT,
UPDATE, DELETE.

How does JDBC work?


1. Load Database Driver: The driver translates Java calls to
database-specific calls.
2. Establish Connection: Using [Link](),
connect to the database.
3. Create Statement: Create SQL statements (Statement,
PreparedStatement).
4. Execute Query: Run SQL queries or updates on the database.
5. Process Results: Process data returned in ResultSet for queries.
6. Close Connection: Release resources when done.
Key JDBC Components:
Component Purpose
DriverManager Manages database drivers and connections
Connection Represents the session with the database
Statement Used to send SQL statements to the database
Precompiled SQL statement (more efficient and
PreparedStatement
safe)
ResultSet Holds data returned from a query

Summary:
 JDBC is essential for database-driven Java applications.
 It provides a universal API, so switching databases usually requires
minimal code changes.
 Understanding JDBC is foundational for working with data in
Java.
JDBC Program:
// Importing all classes from [Link] package
// (Connection, Statement, ResultSet, etc.)
import [Link].*;

public class JdbcDemo {


public static void main(String[] args) {

// Database connection details


String url = "jdbc:mysql://localhost:3306/testdb"; // DB URL (host +
port + DB name)
String user = "root"; // Database username
String password = "root"; // Database password

try {
// Step 1: Load MySQL JDBC Driver
// This line ensures the driver is registered with DriverManager
[Link]("[Link]");

// Step 2: Establish connection with the database


// getConnection() returns a Connection object
Connection con = [Link](url, user,
password);

// Step 3: Create a Statement object


// Statement is used to send SQL queries to the database
Statement stmt = [Link]();

// Step 4: Execute an SQL query


// executeQuery() is used for SELECT queries and returns a
ResultSet
ResultSet rs = [Link]("SELECT * FROM student");

// Step 5: Process the result set


// [Link]() moves to the next row in the result
// getInt("id") fetches integer from "id" column
// getString("name") fetches string from "name" column
while ([Link]()) {
[Link]([Link]("id") + " - " + [Link]("name"));
}

// Step 6: Close the connection after use


// Always close to free resources
[Link]();

} catch (Exception e) {
// If any error occurs (e.g., driver not found, SQL error, wrong
password),
// it will be printed here
[Link]();
}
}
}

Code in SQL for creating database and table:

CREATE DATABASE testdb;


USE testdb;

CREATE TABLE students (


id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(50)
);

INSERT INTO students (name) VALUES ('Alice'), ('Bob'), ('Charlie');

Step-by-Step Explanation (This green portion between // is just for your


understanding)

1. Import JDBC package


import [Link].*;
 [Link] contains all the JDBC classes (Connection, Statement, ResultSet,
etc.).

2. Database credentials
String url = "jdbc:mysql://localhost:3306/testdb";
String user = "root";
String password = "root";
 url → tells JDBC how to connect (driver + host + port + database name).
 Format: jdbc:mysql://<host>:<port>/<database>.
 Here: MySQL is on localhost, port 3306, database name testdb.

3. Load JDBC Driver


[Link]("[Link]");
 Registers the MySQL JDBC driver with DriverManager.
 Since Java 6+, JDBC auto-loads driver if in classpath, but writing this makes
it explicit.

4. Create Connection
Connection con = [Link](url, user, password);
 Establishes connection to the database.
 con object is the bridge between Java and MySQL.
5. Create Statement
Statement stmt = [Link]();
 Statement object is used to send SQL queries to the DB.
 There are also PreparedStatement and CallableStatement for advanced cases.

6. Execute Query
ResultSet rs = [Link]("SELECT * FROM student");
 Runs the SQL query and stores results in a ResultSet.
 Here it fetches all rows from the student table.

7. Process Results
while ([Link]()) {
[Link]([Link]("id") + " - " + [Link]("name"));
}
 [Link]() → moves cursor to next row.
 getInt("id") → fetches integer value from column id.
 getString("name") → fetches string value from column name.
Prints each student record in the format:
1 - John
2 - Mary

8. Close Connection
[Link]();
 Releases DB resources.
 Always a good practice to close after use.

9. Error Handling
catch (Exception e) {
[Link]();
}
 Catches exceptions like missing driver, wrong credentials, SQL errors.
 [Link]() prints error details.

In Simple Words
 DriverManager → Connects Java to MySQL.
 Connection → The “pipe” between Java and database.
 Statement → The SQL messenger.
 ResultSet → The table of results.
 close() → Shut down the pipe when done.
JDBC Architecture:

Two Tier Architecture:

In a Two-Tier setup, you have the user interface on one side and the database on
the other with the two communicating directly. This is great for smaller simpler
applications .

Three Tier Architecture:

In the three-tier, the application logic or process lives in the middle tier, it is
separated from the data and the user interface. Three-tier systems are more
scalable, robust and flexible. In addition, they can integrate data from multiple
sources. In the three-tier architecture, a middle tier was added between the user
system interface client environment and the database management server
environment.
Difference between Two-Tier and Three-Tier Database Architecture:

Three-Tier Database
Two-Tier Database Architecture Architecture

It is a Client-Server Architecture. It is a Web-based application.

In two-tier, the application logic is either In three-tier, the application logic or


buried inside the user interface on the process resides in the middle-tier; it is
client or within the database on the separated from the data and the user
server (or both). interface.

Two-tier architecture consists of two Three-tier architecture consists of three


layers: Client Tier and Database (Data layers: Client Layer, Business Layer
Tier). and Data Layer.

It is easy to build and maintain. It is complex to build and maintain.


Three-Tier Database
Two-Tier Database Architecture Architecture

Two-tier architecture runs slower. Three-tier architecture runs faster.

It is less secured as client can It is secured as client is not allowed to


communicate with database directly. communicate with database directly.

It results in performance loss whenever


It results in performance loss whenever the system is run on Internet but gives
the users increase rapidly. more performance than two-tier
architecture.

Example - Contact Management Example - Designing registration form


System created using MS-Access or which contains text box, label, button or
Railway Reservation System, etc. a large website on the Internet, etc.

Advantages of JDBC Architecture

i. It can read any database. The only condition for it to do so is that all of the
drivers be properly installed.
ii. It pulls information from a database and converts it to XML.
iii. It does not necessitate the conversion of the content.
iv. Software maintenance is centralized with no client settings necessary.
Because the driver is built in Java, the JDBC URL or a DataSource object
has all of the information required to establish a connection.
v. It supports queries and stored procedures completely.
vi. The JDBC API contains a DataSource object that can be used to identify and
connect to a data source. This improves the code’s portability and
maintainability.
vii. Both synchronous and asynchronous processing is supported.
viii. The Java API and the JDBC API work together to make application
development simple and cost-effective.
ix. Modules are supported.
x. Even if data is housed on various database management systems, businesses
can continue to use their installed databases and access information.

Graphical User Interface Programming Paradigm


Introduction to GUI in Java
 GUI (Graphical User Interface) in Java allows users to interact with
programs visually using windows, buttons, text fields, menus, etc.
 Instead of typing commands in a console (CLI – Command Line
Interface), users interact with components (widgets).
 Example of GUI components:
o Buttons
o Text Fields
o Labels
o Checkboxes
o Windows/Frames

How GUI Works in Java


Java provides GUI toolkits (libraries) to create graphical applications.
The main ones are:
o Applet → Depreciated, With Java 8: You can compile and run them using
appletviewer, but not in modern browsers.
o AWT (Abstract Window Toolkit) → Oldest, basic GUI package. (Not in
Syllabus)
o Swing → Built on top of AWT, lightweight, more powerful.
o JavaFX → Modern toolkit, rich graphics, used nowadays.(Not in Syllabus)

Event-Driven Programming
 GUI is based on the event-driven model:
o An event happens (like button click, mouse movement, typing text).
o An event listener (handler) is written in Java to respond to that
event.

What is a Java Applet?

 A Java Applet is a small Java program that runs inside a web browser or an
applet viewer.
 It was introduced to create interactive and dynamic content on web pages.
 Unlike normal Java programs (which run standalone), applets run embedded
inside an HTML page.
 Applets can display graphics, accept user input, and respond to events (like
mouse clicks).

Key Features of Applets:


 Run in a sandboxed environment inside the browser (for security).
 Use classes from the [Link] package.
 Have lifecycle methods like init(), start(), stop(), and destroy().
 Typically extend the Applet class or JApplet (Swing applet).
 Use the paint(Graphics g) method to draw graphics.

Lifecycle methods of Applet:


1. init()
 Called once when the applet is first loaded.
 Used to initialize the applet: create UI components, set initial variables, etc.
 Think of it as the constructor for the applet’s UI setup.

2. start()
 Called each time the applet’s web page is displayed or the applet becomes
active again.
 Use it to start animations, threads, or music.
 May be called multiple times (e.g., when user leaves and returns to the
page).

3. paint(Graphics g)
 Called when the applet needs to refresh its display.
 You write code here to draw graphics, text, shapes, etc.
 Automatically called after init() and start(), or whenever repaint() is called.
4. stop()
 Called when the applet is no longer visible or the user navigates away.
 Use it to pause animations, stop threads or music.
 Like a pause for the applet.

5. destroy()
 Called once when the applet is about to be unloaded from memory.
 Used to release resources, close files, stop threads permanently.

Why Are Applets Obsolete?


 Modern browsers have dropped support for the NPAPI plugin, which is
required to run applets.
 From Java 9 onwards, applets are deprecated and removed entirely after Java
10.
 Today, applets are mostly used for historical and educational purposes only.
 Modern Java GUI apps use Swing, JavaFX, or web technologies instead.

Applets were designed to bring Java's "write once, run anywhere" promise to the
web. The idea was to embed platform-independent programs in web browsers,
much like JavaScript today.
However, browser plugin requirements, sandbox restrictions, and frequent security
exploits led to their decline. By 2017, major browsers (Chrome, Firefox, Edge)
stopped supporting them.

Applet class

Applet class provides all necessary support for applet execution, such as
initializing and destroying of applet. It also provides methods that load and display
images and methods that load and play audio clips.

Parameter in Applet
User-define Parameter can be applied in applet using <PARAM…> tags. Each
<PARAM…> tag has a name and value attribute.
Example:
name = color
Value = red
Syntax:
<PARAM name = ……… Value = “………” >
In an applet code, applet can refer to a parameter by its name and then find its
value.
The two most important thing to handle and set up the parameter is the <PARAM>
tag in the HTML document and an applet code to parse this parameter.
init() method is used to get hold of the parameters which is defined in the
<PARAM> tags. And getParameter() method is used for getting the parameters.
In Applet, Parameters are passed on applet when it is loaded.
Example:[Link]
import [Link].*;
import [Link].*;
public class param extends Applet
{
String str;
public void init()
{
str=getParameter("pname");
if (str == null)
str = "Welcome to [Link]";
str = "Hello " + str;
}
public void paint(Graphics g)
{
[Link](str, 200, 200);
}
}

[Link]
<html>
<applet code=[Link] height=300 width=300>
<param Name="pname" value="Welcome to [Link]">
</applet>
</html>
The appletviewer runs an applet in the window. It is usually the fastest and easiest
way to test an applet. Create an applet containing the <applet> tag in the comment,
and compile it. It is for testing purposes only.

Adding image to applet:


/*Java Applet to Load and Display Image*/
import [Link].*;
import [Link].*;
public class Load_Image extends Applet
{
Image image;
//Fucntion to Load the image
public void init()
{
image=getImage(getCodeBase(),"[Link]");
}
//Function to draw the image
public void paint(Graphics g)
{
[Link](image,0,0,this);
}
}
/*
<applet code = Load_Image.class width=500 height=500>
</applet>
*/
Program Explanation
1. The method getImage(getCodeBase(),image file name) is used to get the image.
2. The method drawImage(image file,x,y,component) is used to draw the image
starting from the x and y co-ordinates in the component specified.
The Applet class supplies two getImage() methods:
i. public Image getImage(URL url)
ii. public Image getImage(URL url, String name)
//In a method in an Applet subclass:
Image image1 = getImage(getCodeBase(), "[Link]");
Image image2 = getImage(getDocumentBase(), "[Link]");
Image image3 = getImage(new URL("[Link]
public URL getCodeBase ():

The getCodeBase() method returns the complete URL of the .class file that
contains the applet. This method can be used with the getImage() or the
getAudioClip() methods, described later in this chapter, to load an image or audio
file relative to the .class file location.
public URL getDocumentBase ():

The getDocumentBase() method returns the complete URL of the .html file that
loaded the applet. This can be used with the getImage() or getAudioClip()
methods, described later in this chapter, to load an image or audio file relative to
the .html file.

public String getParameter (String name):

The getParameter() method allows you to get run-time parameters from within the
<APPLET> tag of the .html file that loaded the applet. Parameters are defined by
HTML <PARAM> tags, which have the form:
<PARAM name="parameter" value="value>

Install Java 8 locally and use appletviewer to run an Applet Program:


Write your applet code (e.g., [Link]).
import [Link].*;
import [Link].*;
import [Link].*;

// <applet code="[Link]" width="300" height="200"></applet>


public class MyApplet extends Applet implements ActionListener {
Button btn;
String message = "";

public void init() {


btn = new Button("Click Me");
add(btn);
[Link](this);
}

public void actionPerformed(ActionEvent e) {


message = "Hello from Applet!";
repaint();
}

public void paint(Graphics g) {


[Link](message, 100, 100);
}
}

Compile with:
javac [Link]
Create an HTML file:

<html>
<body>
<applet code="[Link]" width="300" height="200"></applet>
</body>
</html>

Run using:
appletviewer [Link]

This will open a small window showing your applet output.

What is Swing?

Swing in java is part of Java foundation class which is lightweight and platform
independent. It is used for creating window based applications. It includes
components like button, scroll bar, text field etc. Putting together all these
components makes a graphical user interface.

Swing in Java is a lightweight GUI toolkit which has a wide variety of widgets for
building optimized window based applications. It is a part of the JFC( Java
Foundation Classes). It is build on top of the AWT API and entirely written in
java. It is platform independent unlike AWT and has lightweight components.

It becomes easier to build applications since we already have GUI components like
button, checkbox etc. This is helpful because we do not have to start from the
scratch.

Container Class
Any class which has other components in it is called as a container class. For
building GUI applications at least one container class is necessary.

Following are the three types of container classes:

 Panel – It is used to organize components on to a window


 Frame – A fully functioning window with icons and titles
 Dialog – It is like a pop up window but not fully functional like the frame
JButton Class

It is used to create a labelled button. Using the ActionListener it will result in some
action when the button is pushed. It inherits the AbstractButton class and is
platform independent.

Key Features of Swing:


 Lightweight components: Swing components are drawn by Java, offering a
consistent look and feel across platforms.
 Pluggable Look and Feel: Swing supports different “themes” that let you
change the GUI style without changing code (e.g., Metal, Nimbus, Windows
style).
 MVC architecture: Swing follows the Model-View-Controller design,
separating data, UI, and user interaction logic for better flexibility.
 Advanced components: Swing has complex widgets like JTable, JTree,
JTabbedPane, and rich text support.
 Double buffering: Swing uses double buffering to reduce flickering and
provide smooth graphics.

Layout Manager

To arrange the components inside a container we use the layout manager.


Following are several layout managers:

I. Border layout
II. Flow layout
III. GridBag layout
1. Border Layout: The default layout manager for every JFrame is BorderLayout.
It places components in upto five places which is top, bottom, left, right and center.
2. Flow Layout: FlowLayout simply lays the components in a row one after the
other, it is the default layout manager for every JPanel.

3. GridBag Layout: GridBagLayout places the components in a grid which allows


the components to span more than one cell.

Example: Chat Frame

import [Link].*;

import [Link].*;

class Example {

public static void main(String args[]) {

JFrame frame = new JFrame("Chat Frame");

[Link](JFrame.EXIT_ON_CLOSE);

[Link](400, 400);

JMenuBarob = new JMenuBar();

JMenu ob1 = new JMenu("FILE");

JMenu ob2 = new JMenu("Help");

[Link](ob1);

[Link](ob2);

JMenuItem m11 = new JMenuItem("Open");

JMenuItem m22 = new JMenuItem("Save as");

[Link](m11);

[Link](m22);
JPanel panel = new JPanel(); // the panel is not visible in output

JLabel label = new JLabel("Enter Text");

JTextFieldtf = new JTextField(10); // accepts upto 10 characters

JButton send = new JButton("Send");

JButton reset = new JButton("Reset");

[Link](label); // Components Added using Flow Layout

[Link](label); // Components Added using Flow Layout

[Link](tf);

[Link](send);

[Link](reset);

JTextArea ta = new JTextArea();

[Link]().add([Link], panel);

[Link]().add([Link], tf);

[Link]().add([Link], ta);

[Link](true);

Introduction to Swing Components in Java: Swing components are the basic


building blocks of an application. We know that Swing is a GUI widget toolkit for
Java. Every application has some basic interactive interface for the user. For
example, a button, check-box, radio-button, text-field, etc. These together form the
components in Swing.

Top 13 Components of Swing in Java


Below are the different components of swing in java:

1. ImageIcon

The ImageIcon component creates an icon sized-image from an image residing at


the source URL.

Example:

ImageIconhomeIcon = new ImageIcon("src/images/[Link]");

This returns an icon of a home button. The string parameter is the path at which the
source image is present.

2. JButton

JButton class is used to create a push-button on the UI. The button can contain
some display text or image. It generates an event when clicked and double-clicked.
A JButton can be implemented in the application by calling one of its constructors.

Example:

JButtonokBtn = new JButton("Ok");

This constructor returns a button with text Ok on it.

JButtonhomeBtn = new JButton(homeIcon);

It returns a button with a homeIcon on it.

JButton btn2 = new JButton(homeIcon, "Home");

It returns a button with the home icon and text Home.

3. JLabel

JLabel class is used to render a read-only text label or images on the UI. It does not
generate any event.

Example:

JLabeltextLbl = new JLabel("This is a text label.");


This constructor returns a label with text.

JLabelimgLabel = new JLabel(homeIcon);

It returns a label with a home icon.

4. JTextField

JTextField renders an editable single-line text box. A user can input non-formatted
text in the box. To initialize the text field, call its constructor and pass an optional
integer parameter to it. This parameter sets the width of the box measured by the
number of columns. It does not limit the number of characters that can be input in
the box.

Example:

JTextFieldtxtBox = new JTextField(20);

It renders a text box of 20 column width.

5. JTextArea

JTextArea class renders a multi-line text box. Similar to the JTextField, a user can
input non-formatted text in the field. The constructor for JTextArea also expects
two integer parameters which define the height and width of the text-area in
columns. It does not restrict the number of characters that the user can input in the
text-area.

Example:

JTextAreatxtArea = new JTextArea("This text is default text for text area.", 5, 20);

The above code renders a multi-line text-area of height 5 rows and width 20
columns, with default text initialized in the text-area.

6. JPasswordField

JPasswordField is a subclass of JTextField class. It renders a text-box that masks


the user input text with bullet points. This is used for inserting passwords into the
application.

Example:
JPasswordFieldpwdField = new JPasswordField(15);

varpwdValue = [Link]();

It returns a password field of 15 column width. The getPassword method gets the
value entered by the user.

7. JCheckBox

JCheckBox renders a check-box with a label. The check-box has two states –
on/off. When selected, the state is on and a small tick is displayed in the box.

Example:

CheckBoxchkBox = new JCheckBox("Show Help", true);

It returns a checkbox with the label Show Help. Notice the second parameter in the
constructor. It is a boolean value that indicates the default state of the check-box.
True means the check-box is defaulted to on state.

8. JRadioButton

JRadioButton is used to render a group of radio buttons in the UI. A user can select
one choice from the group.

Example:

ButtonGroupradioGroup = new ButtonGroup();

JRadioButton rb1 = new JRadioButton("Easy", true);

JRadioButton rb2 = new JRadioButton("Medium");

JRadioButton rb3 = new JRadioButton("Hard");

[Link](rb1);

[Link](rb2);

[Link](rb3);

The above code creates a button group and three radio button elements. All three
elements are then added to the group. This ensures that only one option out of the
available options in the group can be selected at a time. The default selected option
is set to Easy.

9. JList

JList component renders a scrollable list of elements. A user can select a value or
multiple values from the list. This select behavior is defined in the code by the
developer.

Example:

DefaultListItemcityList = new DefaultListItem();

[Link]("Mumbai"):

[Link]("London"):

[Link]("New York"):

[Link]("Sydney"):

[Link]("Tokyo"):

JList cities = new JList(cityList);

[Link](ListSelectionModel.SINGLE_SELECTION);

The above code renders a list of cities with 5 items in the list. The selection
restriction is set to SINGLE_SELECTION. If multiple selections is to be allowed,
set the behavior to MULTIPLE_INTERVAL_SELECTION.

10. JComboBox

JComboBox class is used to render a dropdown of the list of options.

Example:

String[] cityStrings = { "Mumbai", "London", "New York", "Sydney", "Tokyo" };

JComboBox cities = new JComboBox(cityList);

[Link](3);
The default selected option can be specified through the setSelectedIndex method.
The above code sets Sydney as the default selected option.

11. JFileChooser

JFileChooser class renders a file selection utility. This component lets a user select
a file from the local system.

Example:

JFileChooserfileChooser = new JFileChooser();

JButtonfileDialogBtn = new JButton("Select File");

[Link](new ActionListner()){

[Link]();

varselectedFile = [Link]();

The above code creates a file chooser dialog and attaches it to the button. The
button click would open the file chooser dialog. The selected file is returned
through the getSelectedFile method.

12. JTabbedPane

JTabbedPane is another very useful component that lets the user switch between
tabs in an application. This is a highly useful utility as it lets the user browse more
content without navigating to different pages.

Example:

JTabbedPanetabbedPane = new JTabbedPane();

[Link]("Tab 1", new JPanel());

[Link]("Tab 2", new JPanel());

The above code creates a two tabbed panel with headings Tab 1 and Tab 2.

13. JSlider
JSlider component displays a slider which the user can drag to change its value.
The constructor takes three arguments – minimum value, maximum value, and
initial value.

Example:

JSlidervolumeSlider = new JSlider(0, 100, 50);

varvolumeLevel = [Link]();

The above code creates a slider from 0 to 100 with an initial value set to 50. The
value selected by the user is returned by the getValue method.

Visual hierarchy of above components:

JFrame (window)

└── JPanel (main container, with some layout)

├── JLabel

├── JTextField

├── JButton

Model-View-Controller (MVC):
MVC is a design pattern that separates an application into three interconnected
components:

1. Model — represents the data and business logic. It manages the data, rules,
and state of the application.

2. View — is the user interface. It displays data (from the model) and sends
user actions (like clicks) to the controller.

3. Controller — handles user input, interprets it, updates the model, and often
updates the view accordingly.

Why use MVC?


 Separates concerns: Keeps data, UI, and input logic separate — easier to
maintain and scale.

 Reusability: You can reuse the model with different views or controllers.

 Testability: Easier to test components independently.

 Parallel development: Different team members can work on UI, logic, and
input handling simultaneously.

MVC in Java GUIs (like Swing)

 Model: Java classes or data structures holding the application state. For
example, a Person object, or a list of records. Also, Swing components often
have built-in models, like TableModel for JTable.

 View: Swing components like JFrame, JButton, JLabel that display data and
UI controls.

 Controller: Event listeners (ActionListener, MouseListener, etc.) that


handle user interactions and update model/view.

Simple example breakdown:

Suppose you have a counter app with a button to increase a number shown on
screen:

 Model: a class with an integer counter and methods to get/increment the


count.

 View: a window with a label showing the count and a button to increment.

 Controller: an ActionListener on the button that updates the model and


refreshes the label in the view.
Swing Program Flow
main()  Create JFrame  Add Components  setVisible(true)  Event Loop

Swing Example
(Preferred modern GUI, built on top of AWT)

import [Link].*;
import [Link].*;

public class MySwingApp {


public static void main(String[] args) {
JFrame frame = new JFrame("Swing Example");
JButton btn = new JButton("Click Me");
JLabel label = new JLabel("");

[Link](100, 80, 100, 30);


[Link](100, 120, 200, 30);

[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
[Link]("Hello from Swing!");
}
});

[Link](btn);
[Link](label);

[Link](300, 200);
[Link](null);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}
}
Differences among Applet, AWT and Swing:

Feature Applet AWT Swing


Standalone window Standalone window
Runs inside Browser / appletviewer
(Frame) (JFrame)
Needs Java 8 + Uses native OS components Pure Java components
Dependency
appletviewer (obsolete) (heavyweight) (lightweight, portable)
Look & Feel Old, very basic Depends on OS style Same across OS, modern UI
Preferred for GUI (until
Use Today? ❌ Deprecated & removed Rarely used
JavaFX)

Java program with Swing UI connected to a database


Steps to follow:
1. Create Database & Table in MySQL
CREATE DATABASE testdb;
USE testdb;

CREATE TABLE students (


id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100),
course VARCHAR(50)
);

2. Add MySQL Connector JAR


Download [Link] and add it to your project lib folder.
(Required for JDBC connection).

3. Java Program (Swing + JDBC)


import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;

public class StudentForm extends JFrame {

// UI Components
private JTextField txtName, txtEmail, txtCourse;
private JButton btnSave;
// Constructor
public StudentForm() {
setTitle("Student Registration Form");
setSize(400, 250);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(4, 2, 10, 10));

// Labels
JLabel lblName = new JLabel("Name:");
JLabel lblEmail = new JLabel("Email:");
JLabel lblCourse = new JLabel("Course:");

// Input fields
txtName = new JTextField();
txtEmail = new JTextField();
txtCourse = new JTextField();

// Save button
btnSave = new JButton("Save");

// Add components to Frame


add(lblName);
add(txtName);
add(lblEmail);
add(txtEmail);
add(lblCourse);
add(txtCourse);
add(new JLabel()); // empty placeholder
add(btnSave);

// Action listener for Save


[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
saveToDatabase();
}
});

setVisible(true);
}
// Method to save data into DB
private void saveToDatabase() {
String name = [Link]();
String email = [Link]();
String course = [Link]();

try {
// Load driver
[Link]("[Link]");

// Connection
Connection con = [Link](
"jdbc:mysql://localhost:3306/testdb", "root", "your_password");

// Query
String query = "INSERT INTO students (name, email, course) VALUES
(?, ?, ?)";
PreparedStatement pst = [Link](query);
[Link](1, name);
[Link](2, email);
[Link](3, course);

int rows = [Link]();


if (rows > 0) {
[Link](this, "Record Saved Successfully!");
}

// Close
[Link]();
[Link]();

} catch (Exception ex) {


[Link](this, "Error: " + [Link]());
}
}

// Main method
public static void main(String[] args) {
new StudentForm();
}
}

You might also like