You are on page 1of 36

Unit 3

Concurrent Programming:
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
commonplace 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?
Concurrent programming is essential in modern computing for several reasons:
i. Performance Improvement: Concurrent programs can utilize multiple CPU
cores efficiently, which can lead to significant performance improvements
for CPU-bound tasks.
ii. Responsiveness: For applications with user interfaces, concurrency
ensures that the application remains responsive even when performing
time-consuming operations in the background.
iii. Resource Utilization: Concurrent programs can make better use of system
resources, such as CPU time, memory, and I/O devices.
iv. 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:
➢ 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.
➢ 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.
➢ 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.
➢ 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.
➢ 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.
➢ 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.
➢ 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.
➢ 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.
➢ 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.
➢ Concurrency Control: In database systems, concurrency control
mechanisms ensure that multiple transactions can access and modify the
database concurrently without causing data inconsistencies.
Thread Class in Java
A thread is a program that starts with a method() frequently used in this class only
known as the start() method. This method looks out for the run() method which
is also a method of this class and begins executing the body of the run() method.
Syntax:
public class Thread extends Object implements Runnable
Constructors of this class are as follows:
• Thread():Allocates a new Thread object.
• Thread(Runnable target): Allocates a new Thread object.
• Thread(Runnable target, String name) :Allocates a new Thread object.
• Thread(String name):Allocates a new Thread object.
• Thread(ThreadGroup group, Runnable target):Allocates a new Thread
object.
• Thread(ThreadGroup group, Runnable target, String name):Allocates a
new Thread object so that it has targeted as its run object, has the specified
name as its name, and belongs to the thread group referred to by a group.
• Thread(ThreadGroup group, Runnable target, String name, long
stackSize):Allocates a new Thread object so that it has targeted as its run
object, has the specified name as its name, and belongs to the thread group
referred to by group, and has the specified stack size.
• Thread(ThreadGroup group, String name):Allocates a new Thread object.

What are Thread Objects?


Know that each thread is connected with an instance of the Thread class. Java
Concurrency offers two methods through which you can create concurrency in
applications with thread objects. If you want to control thread creation and
management directly, you have to instantiate the Thread class whenever the
application requires initiating an asynchronous task. Similarly, if you want to
abstract the thread creation and management from the rest of the application, you
must pass the applications' tasks to executors.
Let’s discuss the use of thread objects below:
1) Starting and Pausing Threads: Applications can create instances of Threads
and run codes in the threads. It is achieved in two ways – providing a
Runnable object and using a subclass Thread. When it comes to pausing
threads, the Thread.sleep object is used to suspend the current thread's
execution for a defined period. During this pause period, other threads can
use processors. Even other applications can use the processors during this
pause period.
2) Interrupts and Joins: In Java Concurrency, you can apply interrupts to stop
the operations of threads and direct them to perform other tasks. When an
interrupt is applied, it enables an interrupt flag to communicate the
interrupt status. Here, the object Thread.interrupt is used to set the flag. If
you want to clear the flag status, you need to invoke Thread.interrupted,
which is a static method. Similarly, isInterrupted is the non-static method
used by one thread to query the interrupt status of another thread.
Moreover, you can use the join method to make one thread wait for another
until it completes its task.
How to Define and Start a Thread in Java Concurrency?
Generally, applications can create instances of threads seamlessly, but they should
provide codes to run on the threads. It can be done in two methods in Java
Concurrency:
a. Providing a Runnable object.
b. Using a Subclass Thread.
A)Provide a Runnable object: The Runnable interface defines a single method –
run – that is meant to contain the code executed in the thread. The Runnable object
is passed to the Thread constructor, as in the following example:
public class HelloWorldRunnableExample implements Runnable {
public void run() {
System.out.println("Hello from a thread!");
}
public static void main(String args[]) {
(new Thread(new HelloWorldRunnableExample())).start();
}
}
Another program:
public class DemoThread implements Runnable{
public void run() {
for(int i=0;i<1000;i++) {
System.out.println("hey thread1 started");
}
}
public static void main(String[] args) {
DemoThread d=new DemoThread();
Thread t1=new Thread(d);
t1.start();
DownloadThread down =new DownloadThread();
Thread t2=new Thread(down);
t2.start();
}
B)Subclass Thread: The Thread class itself implements Runnable, though its run
method does nothing. An application can subclass Thread, providing its own
implementation of run, as shown in the code example below:
public class HelloWorldThreadExample extends Thread {
public void run() {
System.out.println("Hello from a thread!");
}
public static void main(String args[]) {
(new HelloWorldThreadExample()).start();
}
}
Another program:
public class PlayMusic extends Thread {
public void run() {
for(int i=0;i<1000;i++) {
System.out.println("Music Playing ...... ");
}
}
public static void main(String Args[])
{
PlayMusic p=new PlayMusic();
p.start();
for(int i=0;i<1000;i++) {
System.out.println("coding");
}
}
}
In both cases, the programs invoke Thread.start() to start the new thread.
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:
A. Process-based multitasking: 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.
B. Thread-based multi tasking: Threads are light-weight compared to process-
based multi tasking, and the time taken to switch between them is shorter.
Java Example: Executing multiple tasks by multiple threads – Multitasking
Now let’s see an example of multitasking in Java where multiple threads execute
multiple tasks simultaneously by extending the Thread class. Here, each run()
method denotes a different task. Each thread executes a single task which means
t1 executes the run() method of Task1 class and t2 executes the run() method of
Task2 class.
class Task1 extends Thread {
public void run() {
System.out.println("Executing task 1");
}
}
class Task2 extends Thread {
public void run() {
System.out.println("Executing task 2");
}
}
public class MultitaskingDemo{

public static void main(String[] args) {


Task1 t1 = new Task1();
Task2 t2 = new Task2();
t1.start();
t2.start();
}
}

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 chrome.exe
• 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.
Example of multithreading
Think about a single processor that is running your IDE. Say you edit one of your
code files and click save. When you click save, it will initiate a workflow which
will cause bytes to be written out to the underlying physical disk. However, IO is
an expensive operation, and the CPU will be idle while bytes are being written
out to the disk.
While IO takes place, the idle CPU could work on something useful and here is
where threads come in - the IO thread is switched out and the UI thread gets
scheduled on the CPU so that if you click elsewhere on the screen, your IDE is
still responsive and does not appear hung or frozen.
Threads can give the illusion of multitasking even though at any given point in
time the CPU is executing only one thread. Each thread gets a slice of time on the
CPU and then gets switched out either.
It initiates a task, which requires waiting and not utilizing the CPU or it completes
its time slot on the CPU. There are many more nuances and intricacies on how
thread scheduling works but this forms the basis of it.
With advances in hardware technology, it is now common to have multi-core
machines. Applications can take advantage of these and have a dedicated CPU
run each thread.

Benefits of multithreading
• Higher throughput, or the ability to process more units of information in a
given amount of time. (This assumes that the throughput ‘cost’ associated
with dealing with multiple threads is lower than the efficiency it creates.
This is usually, but not always, the case.)
• More responsive applications that provide user seamless experiences and
the illusion of multitasking. For example, an app’s UI will still be
functional and responsive even while IO activity is happening in the
background of an image processing app.
• More efficient utilization of resources. Generally speaking, thread creation
is less ‘costly’ compared to creating a brand new process. Web servers that
use threads instead of creating a new process when fielding web requests
consume far fewer resources.
Problems with multithreading
• More difficult to find bugs. The reasons for a process not executing
successfully may now be external to the process itself. The execution order
and prioritization of threads can’t always be predicted and is up to the
operating system itself.
• Higher cost of code maintenance, since the code has now had multiple
levels of complexity added to it.
• More demand on the system. The creation of each thread consumes
additional memory, CPU cycles for book-keeping and time spent on
switching ‘contexts.’ Additionally, keep in mind if a processor is going to
run 5 threads simultaneously it will also need to keep information about
each of those processes around and accessible while the other ones execute,
requiring more registers.

Thread Methods:
What are thread methods in Java?
Thread methods in Java are very important while you're working with a multi-
threaded application. The thread class has some important methods which are
described by the thread itself.
Now let's learn about each of these methods:
1) public void start(): you use this method to start the thread in a separate path
of execution. Then it invokes the run() method on the thread object.
2) public void run(): this method is the starting point of the thread. The
execution of the thread begins from this process.
3) public final void setName(): this method changes the name of the thread
object. There is also a getName() method for retrieving the name of the
current context.
4) public final void setPriority(): you use this method to set the values of the
thread object.
5) public void sleep(): you use this method to suspend the thread for a
particular amount of time.
6) public void interrupt(): you use this method to interrupt a particular thread.
It also causes it to continue execution if it was blocked for any reason.
7) public final boolean isAlive(): this method returns true if the thread is alive.

Applet in Java
An applet is a special kind of Java program that runs in a Java enabled browser.
This is the first Java program that can run over the network using the browser.
Applet is typically embedded inside a web page and runs in the browser.
In other words, we can say that Applets are small Java applications that can be
accessed on an Internet server, transported over Internet, and can be automatically
installed and run as apart of a web document.
After a user receives an applet, the applet can produce a graphical user interface.
It has limited access to resources so that it can run complex computations without
introducing the risk of viruses or breaching data integrity.
To create an applet, a class must class extends java.applet.Applet class.
An Applet class does not have any main() method. It is viewed using JVM. The
JVM can use either a plug-in of the Web browser or a separate runtime
environment to run an applet application.

JVM creates an instance of the applet class and invokes init() method to initialize
an Applet.
Note: Java Applet is deprecated since Java 9. It means Applet API is no longer
considered important.
Program:
import java.awt.*;
import java.applet.*;
public class Simple extends Applet
{
public void paint(Graphics g)
{
g.drawString("A simple Applet", 20, 20);
}
}
Every Applet application must import two packages - java.awt and java.applet.
java.awt.* imports the Abstract Window Toolkit (AWT) classes. Applets interact
with the user (either directly or indirectly) through the AWT. The AWT contains
support for a window-based, graphical user interface. java.applet.* imports the
applet package, which contains the class Applet. Every applet that you create
must be a subclass of Applet class.
The class in the program must be declared as public, because it will be accessed
by code that is outside the program.Every Applet application must declare a
paint() method. This method is defined by AWT class and must be overridden by
the applet. The paint() method is called each time when an applet needs to
redisplay its output. Another important thing to notice about applet application is
that, execution of an applet does not begin at main() method. In fact an applet
application does not have any main() method.

Advantages of Applets
1. It takes very less response time as it works on the client side.
2. It can be run on any browser which has JVM running in it.

Applet life cycle:


The lifecycle of an applet through its methods-
init()- This is the first method called during the lifecycle of an applet. This method
kickstarts the execution of an applet. In this method, we usually initialize
variables that are going to be needed throughout the life of an applet.
start() - Method start() is called automatically by init() method. This method is a
place where the actual work begins and it is called right after an appLet us
resuming its execution after being in a suspended position when its window was
minimized.
paint(): The paint() method is named whenever your applet’s output must be
redrawn. This example can occur for several reasons. paint() is additionally called
when the applet begins execution. The paint() method has a parameter of type
Graphics. This parameter will contain the graphics context, which describes the
graphics environment during which the applet is running. This context is
employed whenever output to the applet is required.
stop() - This method is called when an applet's execution has been stopped or
suspended for a while because the user has minimized the applet window.
destroy()- This is the last method to be called in the lifecycle of an applet as this
method is called only when an applet has finally terminated its execution. This
method is a place for clean-up operation in order to free the memory from the
resources consumed during the lifetime of an applet.
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.*;
/*<applet code="AppletLifeCycle.class" width="350" height="150">
</applet>*/
public class AppletLifeCycle extends Applet {
// This method is called when the applet is initialized
public void init() {
setBackground(Color.BLUE); // Set the background color to blue
System.out.println("init() is invoked"); // Print a message to the
console
}

// This method is called when the applet is started


public void start() {
System.out.println("Start() is invoked"); // Print a message to the
console
}
// This method is called when the applet needs to be painted
public void paint(Graphics g) {
System.out.println("Paint() is invoked"); // Print a message to the
console
}
// This method is called when the applet is stopped
public void stop() {
System.out.println("Stop() is invoked"); // Print a message to the
console
}
// This method is called when the applet is destroyed
public void destroy() {
System.out.println("Destroy() is invoked"); // Print a message to the
console
}
}
Explanation: As soon as the program is executed, the window pops up and
instance of each applet class is created. As a result of this, the method init() is
called which displays command in the window. After this, the start method is
invoked, and the message is displayed followed by paint() method. Now when
the user clicks on the minimize button on window, the stop() method is triggered
and for restoring the window, start() method is invoked again. When the window
is closed, the destroy() method is invoked, closing the window.
Applet class
Applet class provides all necessary support for applet execution, such as
initializing and destroying of applet. It also provide methods that load and display
images and methods that load and play audio clips.
import java.applet.*;
import java.awt.*;
public class MyApplet extends Applet
{
int height, width;
public void init()
{
height = getSize().height;
width = getSize().width;
setName("MyApplet");
}
public void paint(Graphics g)
{
g.drawRoundRect(10, 30, 120, 120, 2, 3);
}
}
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: param.java
import java.applet.*;
import java.awt.*;
public class param extends Applet
{
String str;
public void init()
{
str=getParameter("pname");
if (str == null)
str = "Welcome to studytonight.com";
str = "Hello " + str;
}
public void paint(Graphics g)
{
g.drawString(str, 200, 200);
}
}

param.html
<html>
<applet code=param.class height=300 width=300>
<param Name="pname" value="Welcome to studytonight.com">
</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.
Using html:
c:\>javac param.java
c:\>appletviewer param.html
Using appletviewer: To run an applet using the appletviewer tool, write in the
command prompt:
c:\>javac First.java
c:\>appletviewer First.java
javac is the compiler that compiles java codes using a command line.
First.java is the applet class to be tested.
appletviewer is a tool that tests the applet class.
Adding image to applet:
/*Java Applet to Load and Display Image*/
import java.awt.*;
import java.applet.*;
public class Load_Image extends Applet
{
Image image;
//Fucntion to Load the image
public void init()
{
image=getImage(getCodeBase(),"logo.jpeg");
}
//Function to draw the image
public void paint(Graphics g)
{
g.drawImage(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(), "imageFile.gif");
Image image2 = getImage(getDocumentBase(), "anImageFile.jpeg");
Image image3 = getImage(new URL("http://java.sun.com/graphics/people.gif"));
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>

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.
Example:
import javax.swing.*;
public class example{
public static void main(String args[]) {
JFrame a = new JFrame("example");
JButton b = new JButton("click me");
b.setBounds(40,90,85,20);
a.add(b);
a.setSize(300,300);
a.setLayout(null);
a.setVisible(true);
}
}
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
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.
Flow Layout: FlowLayout simply lays the components in a row one after the
other, it is the default layout manager for every JPanel.
GridBag Layout: GridBagLayout places the components in a grid which allows
the components to span more than one cell.
Example: Chat Frame
import javax.swing.*;
import java.awt.*;
class Example {
public static void main(String args[]) {
JFrame frame = new JFrame("Chat Frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);

JMenuBar ob = new JMenuBar();


JMenu ob1 = new JMenu("FILE");
JMenu ob2 = new JMenu("Help");
ob.add(ob1);
ob.add(ob2);
JMenuItem m11 = new JMenuItem("Open");
JMenuItem m22 = new JMenuItem("Save as");
ob1.add(m11);
ob1.add(m22);
JPanel panel = new JPanel(); // the panel is not visible in output
JLabel label = new JLabel("Enter Text");
JTextField tf = new JTextField(10); // accepts upto 10 characters
JButton send = new JButton("Send");
JButton reset = new JButton("Reset");
panel.add(label); // Components Added using Flow Layout
panel.add(label); // Components Added using Flow Layout
panel.add(tf);
panel.add(send);
panel.add(reset);
JTextArea ta = new JTextArea();
frame.getContentPane().add(BorderLayout.SOUTH, panel);
frame.getContentPane().add(BorderLayout.NORTH, tf);
frame.getContentPane().add(BorderLayout.CENTER, ta);
frame.setVisible(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:
ImageIcon homeIcon = new ImageIcon("src/images/home.jpg");
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:
JButton okBtn = new JButton("Ok");
This constructor returns a button with text Ok on it.
JButton homeBtn = 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:
JLabel textLbl = new JLabel("This is a text label.");
This constructor returns a label with text.
JLabel imgLabel = 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:
JTextField txtBox = 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:
JTextArea txtArea = 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:
JPasswordField pwdField = new JPasswordField(15);
var pwdValue = pwdField.getPassword();
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:
CheckBox chkBox = 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:
ButtonGroup radioGroup = new ButtonGroup();
JRadioButton rb1 = new JRadioButton("Easy", true);
JRadioButton rb2 = new JRadioButton("Medium");
JRadioButton rb3 = new JRadioButton("Hard");
radioGroup.add(rb1);
radioGroup.add(rb2);
radioGroup.add(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:
DefaultListItem cityList = new DefaultListItem();
cityList.addElement("Mumbai"):
cityList.addElement("London"):
cityList.addElement("New York"):
cityList.addElement("Sydney"):
cityList.addElement("Tokyo"):
JList cities = new JList(cityList);
cities.setSelectionModel(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);
cities.setSelectedIndex(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:
JFileChooser fileChooser = new JFileChooser();
JButton fileDialogBtn = new JButton("Select File");
fileDialogBtn.AddEventListner(new ActionListner()){
fileChooser.showOpenDialog();
}
var selectedFile = fileChooser.getSelectedFile();
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:
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab("Tab 1", new JPanel());
tabbedPane.addTab("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:
JSlider volumeSlider = new JSlider(0, 100, 50);
var volumeLevel = volumeSlider.getValue();
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.

JDBC ODBC CONNECTIVITY


What is JDBC?
JDBC (Java Database Database Connectivity) is a Sun Microsystems
specification. It is the Java API that is responsible for connecting to a database,
issuing queries and commands, and processing database result sets. To access
spreadsheets and databases, JDBC and database drivers operate together. The
components of JDBC that are utilized to connect to the database are defined by
the design of JDBC. The JDBC API classes and interfaces enable an application
to send a request to a specific database.
JDBC stands for Java Database Connectivity is a Java API(Application
Programming Interface) used to interact with databases. JDBC is a specification
from Sun Microsystems and it is used by Java applications to communicate with
relational databases. We can use JDBC to execute queries on various databases
and perform operations like SELECT, INSERT, UPDATE and DELETE.

JDBC API helps Java applications interact with different databases like MSSQL,
ORACLE, MYSQL, etc. It consists of classes and interfaces of JDBC that allow
the applications to access databases and send requests made by users to the
specified database.
Why JDBC?
Before it was created, we utilized the ODBC API database to connect to the
database and run queries against it. The ODBC API, on the other hand, uses the
ODBC drive in C. Furthermore, it is platform-dependent and unprotected. This is
why Java created the JDBC API, which uses JDBC drivers and is written in the
Java programming language.

Applications of JDBC
JDBC enables you to create Java applications that handle the following three
programming tasks:
• Make a connection to a data source, such as a database.
• Send database queries and update statements.
• Retrieve and process the database results that were returned in response to
your query.
Let’s discuss a real-world example that uses JDBC.
When you search for a movie on a specific date, the database retrieves the number
of tickets available on that day, and if you purchase a ticket, the database is
updated accordingly.
In addition to this domain, JDBC is used in a variety of other fields such as
banking, reservation systems, online retail websites, government portals, and so
on.
It is used in almost every Java programme that connects to an SQL database
management system. Java developers will almost probably utilize JDBC at the
lowest level, regardless of any higher-level libraries, frameworks, object-
relational mappers, or database-access layers they use.

JDBC Architecture and Components: There are two architectures of JDBC:


Two-Tier Architecture :A Java applet and application communicates directly with
the data source in the two-tier paradigm. This necessitates the use of a JDBC
driver that can interface with the data source in question. The user’s commands
are transmitted to the database or other data source, and the statements’ results
are returned to the user. The data source could be on another machine to which
the user has a network connection. A client/server configuration is one in which
the user’s machine acts as the client and the system that houses the data source
acts as the server. An intranet, for example, can connect people within a company,
or the Internet can be used as a network.
Three-Tier Architecture: Commands are sent to a “middle tier” of services in the
three-tier paradigm, which subsequently transmits the commands to the data
source. The data source interprets the commands and provides the results to the
middle tier, which ultimately passes them on to the user. The three-tier
architecture appeals to MIS directors because the intermediate tier allows them
to maintain control over access and the types of changes that can be made to
company data. Another benefit is that it makes application deployment easier.
Finally, the three-tier architecture can bring performance benefits in many
circumstances.

The components of JDBC are listed below. These elements assist us in interacting
with a database. The following are the JDBC components:
1) JDBC Driver Manager: In a JDBC application, the Driver Manager loads
database-specific drivers. This driver manager makes a database
connection. To handle the user request, it additionally makes a database-
specific call to the database.
2) Driver: A driver is an interface that manages database server connectivity.
Communication is handled using DriverManager objects.
3) JDBC-ODBC Bridge Drivers: They are used to link database drivers to the
database. The JDBC method calls are translated into ODBC method calls
by the bridge. To access the ODBC (Open Database Connectivity)
characteristics, it uses the sun.jdbc.odbc package, which includes the
native library.
4) JDBC API: Sun Microsystem has provided JDBC API, which allows you
to write a Java program that talks with any database without modifying the
code. The JDBC API is implemented by the JDBC Driver.
5) JDBC Test Suite: The JDBC Test Suite aids in the testing of JDBC Driver
operations such as insertion, deletion, and updating. It aids in determining
whether or not the JDBC Drivers will run the program. It ensures that the
program will be run by JDBC Drivers with confidence and conformity.
6) Database Server: This is the database server that the JDBC client wants to
communicate with, such as Oracle, MySQL, SQL Server, and so on.
7) Statement: To send SQL statements to the database, you use objects built
using this interface. In addition to performing stored procedures, certainly
derived interfaces accept parameters.
8) RuleSet: These objects retain data retrieved from a database when you use
Statement objects to conduct a SQL query. It functions as an iterator,
allowing you to cycle through the data it contains.
9) SQL Exception: This class is responsible for any errors that occur in a
database application.

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.

Working of JDBC
Java applications need to be programmed for interacting with data sources. JDBC
Drivers for specific databases are to be loaded in a java application for JDBC
support which can be done dynamically at run time. These JDBC drivers
communicate with the respective data source.
Steps to connect a Java program using JDBC API.
1. Load Driver: Load JDBC Driver for specific databases using forName()
method of class Class. Syntax: Class.forName("com.mysql.jdbc.Driver")
2. Create Connection: Create a connection with a database using DriverManager
class. Database credentials are to be passed while establishing the connection.
Syntax: DriverManager.getConnection()
3. Create Query: To manipulate the database we need to create a query using
commands like INSERT, UPDATE, DELETE, etc. These queries are created and
stored in string format. Syntax: String sql_query = "INSERT INTO
Student(name, roll_no) values('ABC','XYZ')"
4. Create Statement: The query we have created is in form of a string. To perform
the operations in the string on a database we need to fire that query on the
database. To achieve this we need to convert a string object into SQL statements.
This can be done using createStatement() and prepareStatement() interfaces.
Syntax: Statement St = con.createStatement();
5. Execute Statement: To execute SQL statements on the database we can use two
methods depending on which type of query we are executing.
• Execute Update: Execute update method is used to execute queries like
insert, update, delete, etc. Return type of executeUpdate() method is int.
Syntax: int check = st.executeUpdate(sql);
• Execute Query: Execute query method is used to execute queries used to
display data from the database, such as select. Return type of
executeQuery() method is result set. Syntax: Resultset =
st.executeUpdate(sql);
6. Closing Statement: After performing operations on the database, it is better to
close every interface object to avoid further conflicts. Synatx: con.close();
Let's see how to connect a Java program using JDBC API.
import java.sql.*;
public class JDBCEx {
public static void main(String args[])
{
Connection con = null;
Statement st = null;
try
{
// Load driver class
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver Loaded");
// Obtain a connection
con = DriverManager.getConnection("","","");
System.out.println("Database Connected Successfully!");
//Create Query
String sql = "INSERT INTO Student(sname, scity) values('ABC','Pune')";
// Obtain a statement
st = con.createStatement();
// Execute the query
int check = st.executeUpdate(sql);
if (check > 0)
{
System.out.println("Insert Done");
}
}
catch(Exception e)
{
System.out.println(e);
}
finally
{
//Close Connection
st.close();
con.close();
}
}
}

What Is ODBC?
Open Database Connectivity, commonly known as ODBC, was developed by
Microsoft in 1992. Different applications use it as a general API to access and
manipulate databases. ODBC development used numerous essential
programming languages like Java, Perl, and C# to ensure broad usability across
other platforms.
Since the platform used is Windows, it is program based. It provides a standard
for businesses and developers to access databases. The latest version of ODBC is
Version 17.10.3, released on January 26, 2023. For example, Microsoft Office
supports ODBC.

Features Of ODBC :The main unique feature of ODBC is:


1. Interoperability: You may quickly switch/migrate your application from
one database to another using the ODBC driver.
2. Rich metadata: ODBC supports metadata well. It includes functions for
obtaining information about both processes and data types.
3. Attributes: ODBC additionally offers methods for obtaining information
about the characteristics and practices utilized by the drivers.
4. Error code: It has an error code method for indicating problems
encountered while executing SQL statements.
Working of ODBC:
ODBC is a framework made up of four components that function together. ODBC
enables programs to use SQL queries to connect to databases without knowing
the databases' specific interfaces. The SQL query is handled by ODBC, which
turns it into a request that each database system recognizes.
The four different components of ODBC are:
Application: The user sends its query to the database. Here the ODBC functions
are called, and SQL queries are sent.
Data Manager: Loads drivers for each application.
Driver: It handles ODBC function calls before submitting each SQL request to a
data source.
Data Sources: The data source comprises the information that needs to be
accessed and the operating system, DBMS, and network platform used in
communication with the DBMS.

Advantages of JDBC
a) Pure Java: It is purely dedicated to Java. It can work on any platform which
supports Java Programming language.
b) Better performance : It performs better than ODBC in some cases. It can
reuse the used statements and support batch updates.
c) Object-oriented: Since it is Object Oriented, it enables it to work with Java
more easily.
d) Standardized : JDBC is a standard API that supports all major relational
databases.
Disadvantages of JDBC
1) Complexity: JDBC is more complex to use than ODBC. It needs to manage
the database manually.
2) Limited Functionality: Less functionality than other APIs like JPA or
Hibernate, which provide a higher level of abstraction.
3) Platform-specific Driver: It is platform-specific. It can work on any
platform which supports Java Programming language.
Advantages of ODBC
a) Cross-Platform : ODBC works on multiple platforms like Linux, Windows,
and Linux.
b) Compatibility : ODBC provides compatibility with different data sources
like relational databases, files, etc.
c) Support for non-Java languages : ODBC supports Java and different
languages like C, C++, C#, Perl, etc.
d) Widely used : Since it is more flexible and compatible with other
languages, that make it such a widely used API.
Disadvantages of ODBC
1. Performance: ODBC is much slower than JDBC since it has an additional
layer for abstraction.
2. Complicated to construct: ODBC drivers are difficult to create and
maintain.
3. Slow with Large databases: It can not handle large databases like JDBC.
However, it is easy to use.
4. Does not provide standardized: ODBC needs to be sufficiently
standardized as it is mainly used by clients

JDBC Drivers: JDBC drivers are client-side adapters (installed on the client
machine, not on the server) that convert requests from Java programs to a protocol
that the DBMS can understand. There are 4 types of JDBC drivers:
• Type-1 driver or JDBC-ODBC bridge driver
• Type-2 driver or Native-API driver
• Type-3 driver or Network Protocol driver
• Type-4 driver or Thin driver
Type-1 driver : Type-1 driver or JDBC-ODBC bridge driver uses ODBC driver
to connect to the database. The JDBC-ODBC bridge driver converts JDBC
method calls into the ODBC function calls. Type-1 driver is also called Universal
driver because it can be used to connect to any of the databases.
➢ As a common driver is used in order to interact with different databases,
the data transferred through this driver is not so secured.
➢ The ODBC bridge driver is needed to be installed in individual client
machines.
➢ Type-1 driver isn’t written in java, that’s why it isn’t a portable driver.
➢ This driver software is built-in with JDK so no need to install separately.
➢ It is a database independent driver.
Type-2 driver : The Native API driver uses the client -side libraries of the
database. This driver converts JDBC method calls into native calls of the database
API. In order to interact with different database, this driver needs their local API,
that’s why data transfer is much more secure as compared to type-1 driver.
➢ Driver needs to be installed separately in individual client machines
➢ The Vendor client library needs to be installed on client machine.
➢ Type-2 driver isn’t written in java, that’s why it isn’t a portable driver
➢ It is a database dependent driver.
Type-3 driver : The Network Protocol driver uses middleware (application server)
that converts JDBC calls directly or indirectly into the vendor-specific database
protocol. Here all the database connectivity drivers are present in a single server,
hence no need of individual client-side installation.
➢ Type-3 drivers are fully written in Java, hence they are portable drivers.
➢ No client side library is required because of application server that can
perform many tasks like auditing, load balancing, logging etc.
➢ Network support is required on client machine.
➢ Maintenance of Network Protocol driver becomes costly because it
requires database-specific coding to be done in the middle tier.
➢ Switch facility to switch over from one database to another database.
Type-4 driver : Type-4 driver is also called native protocol driver. This driver
interact directly with database. It does not require any native database library, that
is why it is also known as Thin Driver.
➢ Does not require any native library and Middleware server, so no client-
side or server-side installation.
➢ It is fully written in Java language, hence they are portable drivers.

Which Driver to use When?


1. If you are accessing one type of database, such as Oracle, Sybase, or IBM,
the preferred driver type is type-4.
2. If your Java application is accessing multiple types of databases at the same
time, type 3 is the preferred driver.
3. Type 2 drivers are useful in situations, where a type 3 or type 4 driver is
not available yet for your database.
4. The type 1 driver is not considered a deployment-level driver, and is
typically used for development and testing purposes only.
Difference Between AWT and Swing in Java

S.No. AWT SWING

1. The full form of It has no full version.


AWT is Abstract
Window Toolkit.

2. It is an API used Swing is a graphical user interface (GUI) and a part of


to develop Oracle’s Java Foundation Classes that are used to design
window-based different applications.
applications in
Java.

3. Its components Its components are light weighted.


are heavy
weighted.

4. In Java AWT, the In Java swing, the components are independent.


components
are platform
dependent.

5. The The functionality of the JAVA swing is higher than AWT.


functionality of
JAVA AWT is
less as
compared to
the Java swing.

6. It requires more It requires less time for execution.


time for
execution.

7. It has less It has more powerful components than Java AWT.


powerful
components
compared to
the Java swing.

8. It does not It supports the MVC pattern.


support the
MVC pattern.

You might also like