ProgramminginJava-StudentGuide
ProgramminginJava-StudentGuide
KA
R
SA
A
R
IT
R
-A
01
02
30
52
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
R
KA
R
SA
A
R
IT
R
-A
01
02
30
52
00
19
R
Programming in Java
Student Guide
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
R
KA
R
SA
Trademark Acknowledgements
A
R
IT
All products are registered trademarks of their respective organizations.
R
Programming in Java/SG/18-M08-V1.0
Copyright ©NIIT. All rights reserved.
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
COURSE DESIGN - STUDENT GUIDE
Table of Contents
Chapter Description
Objectives Rationale
R
Content Objectives
KA
Text Entry Profile
R
SA
Graphics Exit Profile
Tables Conventions
A
Note
R
IT
Just a minute
R
-A
Practice Questions
01
Summary
02
Glossary
30
52
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Table of Contents
Prologue ----------------------------------------------------------------------------------- ii
Description --------------------------------------------------------------------------- ii
Rationale ------------------------------------------------------------------------------ ii
Objectives ----------------------------------------------------------------------------- ii
Entry Profile ------------------------------------------------------------------------- iii
R
Exit Profile--------------------------------------------------------------------------- iii
KA
Conventions -------------------------------------------------------------------------------iv
R
SA
Chapter 1 – Designing a User Interface and Handling Events
A
R
Exploring UI Components ------------------------------------------------------------ 1.3
Identifying UI Components ------------------------------------------------------- 1.4
IT
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Chapter 3 – Working with Localization
R
Chapter 4 – Working with Generics
KA
R
Creating User-defined Generic Classes and Methods --------------------------- 4.3
SA
Creating Generic Classes ---------------------------------------------------------- 4.3
Creating a Generic Method -------------------------------------------------------- 4.4
Implementing Type-safety ------------------------------------------------------------ 4.6
A
Using a Generic Type Inference -------------------------------------------------- 4.6
R
Using Wildcards -------------------------------------------------------------------- 4.7
IT
Practice Questions --------------------------------------------------------------------- 4.11
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Implementing Sorting ----------------------------------------------------------------- 5.29
Using the Comparable Interface ------------------------------------------------- 5.29
Using the Comparator Interface -------------------------------------------------- 5.31
Practice Questions --------------------------------------------------------------------- 5.35
Summary -------------------------------------------------------------------------------- 5.36
R
Advantages and Disadvantages of Multithreading ----------------------------- 6.4
KA
The Thread Class ------------------------------------------------------------------- 6.4
The Life Cycle of a Thread -------------------------------------------------------- 6.6
R
SA
Creating Threads ----------------------------------------------------------------------- 6.8
Creating a Thread by Extending the Thread Class ----------------------------- 6.8
Creating a Thread by Implementing the Runnable Interface ----------------- 6.10
A
Creating Multiple Threads -------------------------------------------------------- 6.12
R
Identifying the Thread Priorities ------------------------------------------------- 6.21
IT
Practice Questions --------------------------------------------------------------------- 6.24
R
Concurrency
30
52
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Chapter 8 – Working with NIO Classes and Interfaces
R
KA
Identifying the Layers in the JDBC Architecture -------------------------------- 9.3
R
JDBC Architecture ----------------------------------------------------------------- 9.3
SA
Identifying the Types of JDBC Drivers--------------------------------------------- 9.5
The JDBC-ODBC Bridge Driver ------------------------------------------------- 9.5
The Native-API Driver ------------------------------------------------------------- 9.6
A
The Network Protocol Driver ----------------------------------------------------- 9.7
R
The Native Protocol Driver -------------------------------------------------------- 9.8
IT
Using JDBC API ------------------------------------------------------------------------ 9.9
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Implementing Batch Updates in JDBC ------------------------------------------- 10.10
Exception Handling in Batch Updates ----------------------------------------- 10.11
Creating and Calling Stored Procedures in JDBC ----------------------------- 10.14
Creating Stored Procedures ------------------------------------------------------ 10.14
Calling a Stored Procedure Without Parameters ------------------------------ 10.15
Calling a Stored Procedure with Parameters ---------------------------------- 10.16
Using Metadata in JDBC ------------------------------------------------------------ 10.19
Using the DatabaseMetaData Interface ---------------------------------------- 10.19
Using the ResultSetMetaData Interface ---------------------------------------- 10.21
Practice Questions -------------------------------------------------------------------- 10.23
Summary ------------------------------------------------------------------------------- 10.24
R
KA
Glossary
R
SA
Glossary --------------------------------------------------------------------------------- G.1
A
R
IT
R
-A
01
02
30
52
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
R
ABOUT THIS COURSE
KA
R
SA
A
R
IT
R
-A
01
02
30
52
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Prologue
Description
The Programming in Java course helps the students to develop efficient and robust applications by using the
Java programming language. It also describes how to create inner classes and generic classes. In addition,
this course discusses the implementation of type casting, localization, threads, thread synchronization, and
concurrency. Further, it discusses the various classes of the java.util, java.io and java.nio packages.
The course also explains how to work with regular expressions and how to create multithread applications.
R
Further, it discusses the Java Database Connectivity architecture and implementation of database
KA
connectivity.
R
SA
Rationale
Today, there are varied electronic devices available in the market. To work with these electronic devices,
A
different applications are used. These applications are developed by using different programming languages,
R
such as C, C++, Java, and C#. However, the applications developed by using programming languages like C
IT
and C++ do not support cross-platform portability.
R
Java is an object oriented programming language that helps to develop real-life portable applications. We can
-A
create both, CUI-based application and GUI-based application, by using Java. The code reusability feature of
Java enables software developers to upgrade the existing applications without rewriting the entire code of the
01
application.
02
30
Objectives
52
Explore UI components
19
Manage layouts
Explore Java event model
R
Implement events
Create inner classes
Implement localization
Create user-defined generic classes and methods
Implement type-safety
Use the Set interface
Use the List interface
Use the Map interface
Use the Deque interface
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Implement sorting
Use threads in Java
Create threads
Implement thread synchronization
Implement concurrency
Get familiar with NIO
Perform the read and write operations on a file
Identify the layers in the JDBC architecture
Identify the types of JDBC drivers
Use JDBC API
R
Access result sets
KA
Create applications using the PreparedStatement object
Manage database transactions
R
Implement batch updates in JDBC
SA
Create and call stored procedures in JDBC
Use metadata in JDBC
A
R
IT
Entry Profile
R
-A
The students who want to take this course should have basic knowledge of logic building and effective
problem solving.
01
02
Exit Profile
30
After completing this course, the students will be able to develop object-based applications in Java.
52
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Conventions
Convention Indicates…
Note
Just a minute
R
KA
R
SA
Placeholder for an activity. The steps to complete the
activity are included in the book, Programming in
Java – Lab Guide.
A
R
IT
R
-A
01
02
30
52
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
R
KA
R
SA
A
R
IT
R
-A
01
02
30
52
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
An interface is the layer between a user and an application. It helps the user to interact with the application.
The application can contain the Graphical User Interface (GUI) that consists of images, texts, and graphics.
To create the windows-based applications, you need to understand the features of GUI for creating an
interactive and effective interface. For this, Java provides the Swing toolkit and Abstract Window Toolkit
(AWT). The Swing toolkit and AWT contain the various classes and interfaces to create the GUI-based
applications.
This chapter discusses how to create User Interface (UI) by using the Swing toolkit. In addition, it focuses on
the various layout managers and components provided by the Swing toolkit.
GUI provides an interface through which a user interacts with the application. Therefore, it is necessary that
the application must respond to the actions performed by the user. The user’s actions are represented through
events in the Java programming language. To handle these events, Java provides a mechanism known as
R
event model.
KA
An event is handled by defining and associating a handler for the event. Defining a handler enables the
R
application to respond to the event, and associating a handler enables the application to bind the handler with
SA
the event.
This chapter discusses how to create User Interface (UI) by using the Swing toolkit. In addition, it focuses on
the various layout managers and components provided by the Swing toolkit. It further focuses on the Java
event model. In addition, it discusses the implementation of events. A
R
IT
R
Objectives
-A
01
Explore UI components
Manage layouts
30
Implement events
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Exploring UI Components
You have created the Classic Jumble Word game. This game expects a user to enter an input, such as play
game, view instructions, and exit game. The following figure shows the sample output of the Character User
Interface (CUI) of the Classic Jumble Word game.
R
KA
R
The Sample Output
SA
In a CUI application, a user needs to remember all the commands to work with the application. The user
enters the commands by using the keyboard, and the application displays the result of the commands. A
notification is displayed to the user if the user enters a wrong command. On the other hand, the GUI provides
A
a graphical way of interacting with the application. The user provides an input most of the time by using a
R
mouse and sometimes by using a keyboard. The following figure shows the GUI of the Classic Jumble Word
IT
game.
R
-A
01
02
30
52
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Identifying UI Components
Consider the following figure of the Classic Jumble Word game’s menu screen.
R
KA
R
SA
The Menu Screen of the Game
The preceding figure contains the GUI components, such as a frame, panel, label, and button. Java defines
these components according to the following class hierarchy. A
R
IT
R
-A
01
02
30
52
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
The most commonly used containers and components are:
JFrame: It works as a window that is used to place other components of an application. It contains the
title, border, and minimize, maximize, and close buttons. The following figure shows the JFrame
window.
R
KA
R
SA
A
R
IT
R
-A
JDialog: It works as a dialog box that is used to display information to the user or to prompt the user
for a response. It enables you to create the modal and modeless dialog boxes. The following figure
02
Note
The modal dialog box does not allow you to work with other windows while the dialog
box is open. Whereas, the modeless dialog box allows you to work with other windows
while the dialog box is open.
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
JPanel: It is an intermediate component that is used to organize or to group other components within a
window. The following figure shows JPanel within the frame.
R
KA
R
SA
A
R
IT
R
can switch between these panes by clicking the respective tab. The following figure shows
01
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
JMenuBar: Is used to display a menu bar on the frame. The following figure shows JMenuBar within
the frame.
R
KA
R
SA
A
R
IT
R
Note
02
By default, a menu bar is not visible on the frame. To make it visible, you need to add
30
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
JMenu: Is used to add the menus on the menu bar. The following figure shows JMenu on the menu bar.
R
KA
R
SA
A
R
IT
The Frame with JMenu
R
JMenuItem: Is used to add the menu items on menu. The following figure shows JMenuItem of the
-A
menu.
01
02
30
52
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
JLabel: Is used to display a text or an image. By default, a label that displays the text is left aligned and
a label that displays the image is horizontally cantered. The following figure shows JLabel within the
frame.
R
KA
R
SA
A
R
IT
R
JTextField: Is used to insert or edit a single line of text. The following figure shows JTextField
01
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
JTextArea: Is used to insert or edit multiple lines of text. The following figure shows JTextArea
within the frame.
R
KA
R
SA
A
R
IT
R
following figure shows JCheckBox within the frame.
01
02
30
52
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
JRadioButton: Is used to accept only one value from the predefined set of options. The following
figure shows JRadioButton within the frame.
R
KA
R
SA
A
R
IT
R
JList: Is used to provide a list of items that enables a user to select one or more items from the list. The
01
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
JComboBox: Is used to display a combination of a text field and a drop-down list. It enables you to type
or select a value from the list. The following figure shows JComboBox within the frame.
R
KA
R
SA
A
R
IT
R
JButton: Is used to provide the clickable functionality that enables you to initiate a command. The
following figure shows JButton within the frame.
01
02
30
52
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
JOptionPane: Is used to display the dialog boxes that prompt users for a value or giving information.
The following figure shows the Confirmation Message dialog box created using the JOptionPane
class.
R
The Confirmation Message Dialog Box
KA
R
Creating UI
SA
Once you have identified the various Swing containers and components, you can use them to create the UI of
the applications. For this, you need to import the classes and the interfaces available in the javax.swing
package. You can create the following components:
A
R
JFrame
IT
JDialog
R
JPanel
-A
JTabbedPane
01
JMenuBar
02
JMenu
JMenuItem
30
JLabel
52
JTextField
JTextArea
00
JCheckBox
19
JRadioButton
JList
R
JComboBox
JButton
JOptionPane
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
JFrame
The following table lists the most commonly used constructors of the JFrame class with their description.
Constructor Description
R
You can create JFrame by using the following code snippet:
KA
class FrameDemo extends JFrame
{
R
SA
}
In addition, you can create JFrame by using the following code snippet:
class FrameDemo
A
R
{
IT
JFrame obj;
R
public FrameDemo()
-A
{
01
The following table lists the most commonly used methods of the JFrame class with their description.
30
52
Method Description
00
19
void setSize(int width, int height) Is used to resize the frame with the specified
width and height.
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Consider the following code to create JFrame:
import javax.swing.JFrame;
public FrameDemo()
{
obj = new JFrame();
obj.setTitle("JFrame Demo");
obj.setVisible(true);
obj.setSize(300,300);
R
}
KA
public static void main(String[] args)
R
{
FrameDemo fobj = new FrameDemo();
SA
}
}
A
After executing the preceding code, the output is displayed, as shown in the following figure.
R
IT
R
-A
01
02
30
52
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
JDialog
The following table lists the most commonly used constructors of the JDialog class with their description.
Constructor Description
JDialog(Frame owner) Creates a modeless dialog box with the specified frame
on which the dialog box is dependent, but without a title.
R
Creates a dialog box with the specified frame that will be
modal) set as the host of the dialog, with the type of the
KA
modality, such as modeless or modal, but without a title.
R
JDialog(Frame owner, String Creates a modeless dialog box with the specified frame
SA
title) that will be set as the host of the dialog and with the
specified title.
{
01
In addition, you can create JDialog by using the following code snippet:
02
30
class DialogDemo
{
52
JDialog obj;
00
public DialogDemo()
{
19
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
The following table lists the most commonly used methods of the JDialog class with their description.
Method Description
void add(Component comp) Is used to add components on the dialog box.
void setSize(int width, int height) Is used to resize the dialog box with the specified
width and height.
void setVisible(boolean b) Is used to show or hide the dialog box according
to the passed parameter.
void setTitle(String title) Is used to set the title of the dialog box.
R
KA
The Methods of the JDialog Class
Consider the following code to create JDialog:
R
SA
import javax.swing.JDialog;
public class DialogDemo
{
A
JDialog obj; R
public DialogDemo()
IT
{
R
obj.setTitle("JDialog Demo");
obj.setVisible(true);
01
obj.setSize(300,150);
02
}
30
}
}
19
After executing the preceding code, the output is displayed, as shown in the following figure.
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Note
To display information to the user or to prompt the user for a response, you need to
design the dialog box with various components, such as a button, text field, and label,
in the preceding code.
JPanel
The following table lists the most commonly used constructors of the JPanel class with their description.
R
Constructor Description
KA
JPanel() Creates an instance with a default panel.
R
JPanel(LayoutManager layout) Creates an instance of a panel with the
SA
specified layout manager.
{
-A
}
01
In addition, you can create JPanel by using the following code snippet:
02
class PanelDemo
30
{
JPanel obj;
52
public PanelDemo()
{
00
The following table lists the most commonly used methods of the JPanel class with their description.
R
Method Description
void add(Component comp) Is used to add components on the panel.
void setSize(int width, int height) Is used to resize the panel with the specified
width and height.
void setVisible(boolean b) Is used to show or hide the panel according to the
passed parameter.
The Methods of the JPanel Class
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Consider the following code to create JPanel:
import javax.swing.JFrame;
import javax.swing.JPanel;
public PanelDemo()
{
obj = new JPanel();
setTitle("JPanel Demo");
R
setVisible(true);
KA
setSize(300,200);
add(obj);
R
}
SA
public static void main(String[] args)
{
PanelDemo pobj = new PanelDemo();
}
A
}
R
IT
After executing the preceding code, the output is displayed, as shown in the following figure.
R
-A
01
02
30
52
00
19
R
Note
By default, a panel is not visible on the frame. To make it visible, you need to set the
properties, such as background color or border.
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
JTabbedPane
The following table lists the most commonly used constructors of the JTabbedPane class with their
description.
Constructor Description
R
JTabbedPane.BOTTOM, JTabbedPane.LEFT,
KA
or JTabbedPane.RIGHT.
R
The Constructors of the JTabbedPane Class
SA
The following table lists the most commonly used methods of the JTabbedPane class with their description.
Method
A
Description
R
IT
void add(Component comp) Is used to add components on the tabbed pane.
R
-A
void setSize(int width, int Is used to resize the tabbed pane with the
02
import javax.swing.JFrame;
import javax.swing.JTabbedPane;
public TabbedPaneDemo()
{
obj = new JTabbedPane(JTabbedPane.BOTTOM);
obj.addTab("Tab1", null);
obj.addTab("Tab2", null);
obj.setSize(100,100);
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
this.setTitle("JTabbedPane Demo");
this.setVisible(true);
this.setSize(300,200);
this.add(obj);
}
R
KA
R
SA
A
R
IT
R
-A
01
JMenuBar
30
The following table lists the most commonly used constructor of the JMenuBar class with their description.
52
Constructor Description
00
19
Method Description
JMenu getMenu(int index) Is used to get the menu at the specified position in
the menu bar.
int getMenuCount() Is use to get the number of items in the menu bar.
The Methods of the JMenuBar Class
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Consider the following code to create JMenuBar:
import javax.swing.JFrame;
import javax.swing.JMenuBar;
public MenuBarDemo()
{
menuBar=new JMenuBar();
setJMenuBar(menuBar);
R
setTitle("JMenuBar Demo");
KA
setSize(300, 300);
setVisible(true);
R
}
SA
public static void main(String[] args)
{
MenuBarDemo mobj = new MenuBarDemo();
}
A
}
R
IT
After executing the preceding code, the output is displayed, as shown in the following figure.
R
-A
01
02
30
52
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
JMenu
The following table lists the most commonly used constructors of the JMenu class with their description.
Constructor Description
R
KA
Method Description
R
SA
Component add(Component c) Is used to add a component at the end of the
menu.
void addSeparator()
A
Is used to add a separator at the end of the menu.
R
IT
The Methods of the JMenu Class
R
import javax.swing.JFrame;
01
import javax.swing.JMenu;
import javax.swing.JMenuBar;
02
{
JMenu fileMenu, editMenu, exitMenu;
52
JMenuBar menuBar;
00
public MenuDemo()
{
19
menuBar.add(fileMenu);
menuBar.add(editMenu);
menuBar.add(exitMenu);
setJMenuBar(menuBar);
setTitle("JMenu Demo");
setSize(300, 300);
setVisible(true);
}
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
public static void main(String[] args)
{
MenuDemo mobj = new MenuDemo();
}
}
After executing the preceding code, the output is displayed, as shown in the following figure.
R
KA
R
SA
A
R
IT
R
-A
01
JMenuItem
30
The following table lists the most commonly used constructors of the JMenuItem class with their
52
description.
00
19
Constructor Description
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
The following table lists the most commonly used methods of the JMenuItem class with their description.
Method Description
void setMnemonic(int mnemonic) Is used to assign the shortcut key to the menu
item.
R
import javax.swing.JFrame;
KA
import javax.swing.JMenu;
import javax.swing.JMenuBar;
R
import javax.swing.JMenuItem;
SA
public class MenuItemDemo extends JFrame
{
JFrame menuFrame;
A
R
JMenu fileMenu, editMenu, exitMenu;
IT
JMenuItem itemNew, itemOpen, itemCopy, itemPaste, itemClose;
R
JMenuBar menuBar;
-A
public MenuItemDemo()
01
{
menuBar = new JMenuBar();
02
fileMenu.add(itemNew);
fileMenu.add(itemOpen);
editMenu.add(itemCopy);
editMenu.add(itemPaste);
exitMenu.add(itemClose);
menuBar.add(fileMenu);
menuBar.add(editMenu);
menuBar.add(exitMenu);
setJMenuBar(menuBar);
setTitle("JMenuItem Demo");
setSize(300, 300);
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
setVisible(true);
}
R
KA
R
SA
A
R
IT
R
-A
01
02
30
JLabel
00
The following table lists the most commonly used constructors of the JLabel class with their description.
19
R
Constructor Description
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
The following table lists the most commonly used methods of the JLabel class with their description.
Method Description
void setText(String text) Is used to define the text that will be displayed by
the label.
void setSize(int width, int Is used to resize the label with the specified width
height) and height.
R
KA
The Methods of the JLabel Class
Consider the following code to create JLabel:
R
SA
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
A
public class LabelDemo extends JFrame
R
IT
{
JPanel jPanel;
R
public LabelDemo()
01
{
jPanel = new JPanel();
02
jPanel.add(firstName);
jPanel.add(lastName);
19
R
setTitle("JLabel Demo");
setVisible(true);
setSize(300,200);
add(jPanel);
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
After executing the preceding code, the output is displayed, as shown in the following figure.
R
KA
The Output of the LabelDemo Class
R
SA
JTextField
The following table lists the most commonly used constructors of the JTextField class with their
description.
A
R
IT
Constructor Description
R
-A
The following table lists the most commonly used methods of the JTextField class with their description.
19
R
Method Description
void setText(String text) Is used to define the text that will be displayed in
the text box.
void setSize(int width, int Is used to resize the text box with the specified
height) width and height.
void setVisible(boolean b) Is used to show or hide the text box according to
the passed parameter.
String getText() Is used to retrieve the text from the text box.
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Consider the following code to create JTextField:
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public TextFieldDemo()
{
jp = new JPanel();
R
KA
firstname = new JTextField();
firstname.setText("Peter");
R
secondname = new JTextField();
SA
secondname.setText("Jones");
jp.add(firstname);
jp.add(secondname);
A
R
IT
setTitle("JTextField Demo");
setVisible(true);
R
setSize(300,200);
-A
add(jp);
01
}
02
}
00
After executing the preceding code, the output is displayed, as shown in the following figure.
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
JTextArea
The following table lists the most commonly used constructors of the JTextArea class with their
description.
Constructor Description
JTextArea(int rows, int columns) Creates an instance with the specified rows
R
and columns.
KA
The Constructors of the JTextArea Class
R
The following table lists the most commonly used methods of the JTextArea class with their description.
SA
Method Description
A
R
void setText(String text) Is used to define the text that will be displayed in
IT
the text area.
R
String getText() Is used to retrieve the text from the text area.
52
import javax.swing.JFrame;
R
import javax.swing.JPanel;
import javax.swing.JTextArea;
public TextAreaDemo()
{
jp = new JPanel();
about = new JTextArea(5,20);
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
jp.add(about);
setTitle("JTextArea Demo");
setVisible(true);
setSize(500,200);
add(jp);
R
KA
R
SA
A
R
IT
R
-A
JCheckBox
02
The following table lists the most commonly used constructors of the JCheckBox class with their
description.
30
52
Constructor Description
00
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
The following table lists the most commonly used methods of the JCheckBox class with their description.
Method Description
void setText(String text) Is used to define the text that will be displayed by
the check box.
void setSize(int width, int Is used to resize the check box with the specified
height) width and height.
R
KA
String getText() Is used to retrieve the text of the checkbox.
R
boolean isSelected() Is used to get the state of the check box.
SA
The Methods of the JCheckBox Class
Consider the following code to create JCheckBox:
A
R
import javax.swing.JCheckBox;
IT
import javax.swing.JFrame;
import javax.swing.JPanel;
R
-A
JPanel jp;
02
public CheckBoxDemo()
{
52
jp = new JPanel();
00
h1 = new JCheckBox(“Music”);
h2 = new JCheckBox("Sports");
19
h3 = new JCheckBox("Painting");
R
jp.add(h1);
jp.add(h2);
jp.add(h3);
setTitle("JCheckBox Demo");
setVisible(true);
setSize(300,200);
add(jp);
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
public static void main(String[] args)
{
CheckBoxDemo cobj = new CheckBoxDemo();
}
}
After executing the preceding code, the output is displayed, as shown in the following figure.
R
KA
R
SA
A
R
The Output of the CheckBoxDemo Class
IT
R
JRadioButton
-A
The following table lists the most commonly used constructors of the JRadioButton class with their
01
description.
02
Constructor Description
30
52
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
The following table lists the most commonly used methods of the JRadioButton class with their
description.
Method Description
void setText(String text) Is used to define the text that will be displayed by
the radio button.
void setSize(int width, int Is used to resize the radio button with the
height) specified width and height.
R
according to the passed parameter.
KA
String getText() Is used to retrieve the text of the radio button.
R
SA
boolean isSelected() Is used to get the state of the radio button.
The Methods of the JRadioButton Class
Consider the following code to create JRadioButton:
A
R
IT
import javax.swing.JFrame;
R
import javax.swing.JPanel;
import javax.swing.JRadioButton;
-A
import javax.swing.ButtonGroup;
01
{
JPanel jp;
30
public RadioButtonDemo()
00
{
jp = new JPanel();
19
bg = new ButtonGroup();
bg.add(male);
bg.add(female);
jp.add(male);
jp.add(female);
setTitle("JRadioButton Demo");
setVisible(true);
setSize(300,200);
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
add(jp);
Note
R
ButtonGroup is the class that is used to group radio buttons so that only one radio
KA
button can be selected at a time.
R
SA
After executing the preceding code, the output is displayed, as shown in the following figure.
A
R
IT
R
-A
01
02
30
52
00
JList
R
The following table lists the most commonly used constructors of the JList class with their description.
Constructor Description
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
The following table lists the most commonly used methods of the JList class with their description.
Method Description
Object getSelectedValue() Is used to retrieve the selected value from the list.
void setSelectedIndex(int index) Is used to set the selected index for the selected
R
value in the list.
KA
void setSelectedValue(Object Is used to set the selected value in the list.
R
anObject, boolean shouldScroll)
SA
The Methods of the JList Class
Consider the following code to create JList:
A
import javax.swing.DefaultListModel;
R
IT
import javax.swing.JFrame;
import javax.swing.JList;
R
import javax.swing.JPanel;
-A
{
JPanel jp;
02
JList list;
DefaultListModel dlist;
30
public ListDemo()
52
{
jp = new JPanel();
00
19
jp.add(list);
setTitle("JList Demo");
setVisible(true);
setSize(300,200);
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
add(jp);
Note
R
DefaultListModel is a class that is used to create a default list of items. The items
KA
can be added to the default list model by using the addElement() method.
R
SA
After executing the preceding code, the output is displayed, as shown in the following figure.
A
R
IT
R
-A
01
02
30
52
JComboBox
19
The following table lists the most commonly used constructors of the JComboBox class with their
R
description.
Constructor Description
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
The following table lists the most commonly used methods of the JComboBox class with their description.
Method Description
void addItem(Object anObject) Is used to add items to the list.
void setSize(int width, int Is used to resize the combo box with the specified width
height) and height.
void setVisible(boolean b) Is used to show or hide the combo box according to the
passed parameter.
Object getItemAt(int index) Is used to retrieve the item at the specified index from the
R
list.
KA
The Methods of the JComboBox Class
R
Consider the following code to create JComboBox:
SA
import javax.swing.JComboBox;
import javax.swing.JFrame;
A
import javax.swing.JPanel; R
public class ComboBoxDemo extends JFrame
IT
{
R
JPanel jp;
-A
JComboBox city;
01
public ComboBoxDemo()
{
02
jp = new JPanel();
30
city.addItem("Florida");
city.addItem("Montanan");
00
city.addItem("New York");
city.addItem("Oklahoma");
19
jp.add(city);
R
setTitle("JComboBox Demo");
setVisible(true);
setSize(300,200);
add(jp);
}
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
After executing the preceding code, the output is displayed, as shown in the following figure.
R
KA
The Output of the ComboBoxDemo Class
R
SA
JButton
The following table lists the most commonly used constructors of the JButton class with their description.
A
R
IT
Constructor Description
R
JButton()
-A
The following table lists the most commonly used methods of the JButton class with their description.
00
Method Description
19
R
void setText(String text) Is used to define the text that will be displayed by the
button.
void setSize(int width, int Is used to resize the button with the specified width
height) and height.
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Consider the following code to create JButton:
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public ButtonDemo()
{
jp = new JPanel();
R
KA
submit = new JButton(“Submit”);
R
cancel = new JButton(“Cancel”);
SA
jp.add(submit);
jp.add(cancel);
A
setTitle("JButton Demo");
R
IT
setVisible(true);
setSize(300,200);
R
add(jp);
-A
}
01
{
ButtonDemo bobj = new ButtonDemo();
30
}
52
}
00
After executing the preceding code, the output is displayed, as shown in the following figure.
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
JOptionPane
The following table lists the most commonly used constructors of the JOptionPane class with their
description.
Constructor Description
R
JOptionPane(Object message, int Creates an instance to display a message with the
messageType)
KA
specified message type, such as ERROR_MESSAGE or
QUESTION_MESSAGE, and with the default button,
R
OK.
SA
The Constructors of the JOptionPane Class
The following table lists the most commonly used methods of the JOptionPane class with their description.
A
R
IT
Method Description
R
specified icon.
52
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Consider the following code to create JOptionPane:
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public OptionPaneDemo()
{
setVisible(true);
setSize(100,100);
JOptionPane.showConfirmDialog(this, "Do you want to save it?",
"Confirmation Message", JOptionPane.YES_NO_CANCEL_OPTION,
R
JOptionPane.WARNING_MESSAGE);
KA
}
R
public static void main(String[] args)
{
SA
OptionPaneDemo oobj = new OptionPaneDemo();
}
}
A
After executing the preceding code, the output is displayed, as shown in the following figure.
R
IT
R
-A
01
02
30
52
Just a minute:
Which one of the following classes is the sub class of the Window class?
1. JPanel
2. JFrame
3. JList
4. JTabbedPane
Answer:
2. JFrame
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Managing Layouts
Once you have created the UI components of an application, it is important to arrange them properly to
enhance the look and feel of the application. To arrange the components in a container, you can use the
various layout classes, such as FlowLayout and BorderLayout. These layouts use relative positioning to
place the components on the container that means the components automatically adjust their position
according to the frame size. The setLayout() method is used to set the layout of the containers. Java
provides the various layouts.
Some of the layout manager classes are:
FlowLayout
R
BorderLayout
KA
GridLayout
GridBagLayout
R
BoxLayout
SA
GroupLayout
Using FlowLayout A
R
IT
FlowLayout places components in a sequence one after the other component in a row. By default, the
R
components are aligned in the center and are placed from left to right and top to bottom. However, the
-A
ComponentOrientation.LEFT_TO_RIGHT
ComponentOrientation.RIGHT_TO_LEFT
30
The FlowLayout class provides the various constructors that can be used to create an instance.
52
FlowLayout(): Creates an instance with the centered alignment and with the default horizontal and
vertical space of 5 pixels between the components.
19
FlowLayout(int align): Creates an instance with the specified alignment, such as LEFT, RIGHT,
R
and CENTER, and the default horizontal and vertical space of 5 pixels between the components.
FlowLayout(int align, int hgap,int vgap): Creates an instance with the specified alignment
and the specified horizontal and vertical space between the components.
For example, you want to add three buttons, add, update, and delete, in a row, in a sequence of one after the
other.
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
For this, you can use the following code:
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
public FlowLayoutDemo()
{
add = new JButton("Add");
update = new JButton("Update");
R
delete = new JButton("Delete");
KA
setVisible(true);
R
setSize(300,300);
setTitle("FlowLayout Demo");
SA
setLayout(new FlowLayout());
add(add);
add(update);
A
add(delete);
R
IT
}
R
{
FlowLayoutDemo obj = new FlowLayoutDemo();
01
}
}
02
After executing the preceding code, the output is displayed, as shown in the following figure.
30
52
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Using BorderLayout
BorderLayout divides the container into five regions: NORTH, SOUTH, EAST, WEST, and CENTER. Each
region can contain only a single component. BorderLayout arranges and resizes the components to place
them in the five regions. It is the default layout of the frame container. By default, the components are added
in the CENTER region.
However, you can specify the region for the border layout using the following fields:
BorderLayout.NORTH
BorderLayout.SOUTH
BorderLayout.EAST
R
BorderLayout.WEST
KA
BorderLayout.CENTER
The BorderLayout class provides the various constructors that can be used to create an instance. Some of
R
these constructors are:
SA
BorderLayout(): Creates an instance with no space between the components.
BorderLayout(int hgap, int vgap): Creates an instance with the specified horizontal and
vertical spaces between the components.
A
R
For example, you want to add four buttons, add, update, delete, and reset, in four different regions. For this,
IT
you can use the following code:
R
-A
import java.awt.BorderLayout;
import javax.swing.JButton;
01
import javax.swing.JFrame;
02
public BorderLayoutDemo()
00
{
reset = new JButton("Reset");
19
setVisible(true);
setSize(300,300);
setTitle("BorderLayout Demo");
setLayout(new BorderLayout());
add(reset, BorderLayout.EAST);
add(add, BorderLayout.WEST);
add(update,BorderLayout.NORTH);
add(delete, BorderLayout.SOUTH);
}
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
public static void main(String[] args)
{
BorderLayoutDemo obj = new BorderLayoutDemo();
}
}
After executing the preceding code, the output is displayed, as shown in the following figure.
R
KA
R
SA
A
R
IT
R
-A
01
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Exploring Java Event Model
In a GUI application, a user interacts with User Interface (UI) in various ways, such as by clicking a button,
moving a mouse, entering text in a text field, and selecting an item from a list. Moreover, the interaction can
also be generated by the application itself, such as when a timer expires, the printing process of a document
completes, and some hardware or software failure occurs. The interaction with the application is incorporated
in Java programs by using the event model.
The event model is based on two entities, source and receiver. The source initiates the interaction and the
receiver processes the interaction generated by the source. In Java, events are handled by the classes and
interfaces defined in the java.awt.event package.
R
KA
Introducing Event Model
R
In Java programs, the event model contains the following three components that are responsible for handling
SA
the interaction between the source and the receiver:
Event source
Event listener
A
R
Event handler
IT
R
Event Source
-A
An event source is an object that generates an event. The object registers some handler, which receives
01
notifications about a specific type of event. For example, clicking of a button is an event that is fired by the
button. In this example, the button is the source of the event and the button-click-event is the notification that
02
There are various components in the Swing toolkit, such as button, frame, and combo box, which act as an
event source. These sources generate various events, such as a button generates an action event when the
52
button is clicked, a frame generates the window event when the window is opened or closed, and a combo
box generates the item event when an item is selected or deselected.
00
19
Event Listener
R
An event listener listens for a specific event and gets notified when the specific event occurs. An event
listener registers with one or more event sources to receive notifications about specific types of events and to
process the events. Once the listener is notified of a specific event, it calls the event handler and passes the
information regarding the event. The information may contain the source that generated the event and the
time when the event was generated.
Event Handler
An event handler is a method that is invoked by an event listener when the event is generated. In Java, event
listeners are the interfaces and event handlers are the methods declared in the event listener interface that is
implemented by the application.
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Introducing Event Classes
Event classes represent the characteristics of all events, such as the source, time, and ID of the event.
Whenever an event occurs, the related object of the event class is created. For example, when the mouse
button is clicked, an object of the MouseEvent class is created. Some of the event classes provided by Java
are:
ActionEvent
KeyEvent
MouseEvent
FocusEvent
R
ItemEvent
KA
WindowEvent
The EventObject class, which is in the java.util package, is the superclass for all event classes. The
R
class, EventObject, from which all event objects are derived, extends the Object class and implements the
SA
Serializable interface. The syntax of one of the constructors in the EventObject class is:
A
In the preceding syntax, source is an object that generates an event. The EventObject class contains two
R
methods, the getSource() method and the toString() method. The getSource() method returns the
IT
object on which an event has actually occurred. The toString() method returns the string representation of
R
ActionEvent
The action event is generated by components, such as a button, when an action is performed. For example,
02
clicking of a button is an action event generated by the button. The following table lists the most commonly
30
Method Description
00
19
String Returns the command string or the label of the event source.
getActionCommand() For example, clicking a button generates an action event and
R
int getModifiers() Returns an integer value that indicates the modifiers keys, such
as CTRL, ALT, and SHIFT, which are held down at the time of
the event.
The Methods of the ActionEvent Class
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Note
You need to convert the long value to the java.util.Date class object to display the
long value in the day, date, and time format.
MouseEvent
The mouse event is generated by a mouse with respect to the source component. These mouse events can
have the following two categories:
Mouse events: It contains the mouse events, such as mouse pressed, mouse clicked, and mouse entered.
R
Mouse motion events: It contains the mouse motion events, such as mouse moved and mouse dragged.
KA
The following table lists the most commonly used methods of the MouseEvent class.
R
SA
Method Description
int getClickCount()
A
Returns the total count of the mouse clicks.
R
Point getPoint() Returns the x and y coordinates of the mouse with respect to
IT
the source component.
R
-A
int getX() Returns the x coordinates of the mouse with respect to the
source component.
01
int getY() Returns the y coordinates of the mouse with respect to the
02
source component.
30
KeyEvent
00
The key event is generated by a component when a key is pressed, released, or typed within the component.
19
The following table lists the most commonly used methods of the KeyEvent class.
R
Method Description
int getKeyCode() Returns the integer key code for the key.
static String getKeyText(int Returns the name of the key, such as Home, F1, and
keyCode) Caps Lock.
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
FocusEvent
The focus event is generated by a component when it receives or loses focus. The focus events have the
following levels:
Permanent: It occurs when the focus directly moves from one component to other. For example, when
you use the TAB key or the mouse to traverse from one component to other.
Temporary: It occurs when the focus is temporarily lost for a component as an indirect result of another
operation. For example, when you open a frame by clicking a button, the focus shifts temporarily from
the button to the frame. When you close the frame, the focus shifts back from the frame to the button.
The following table lists the most commonly used methods of the FocusEvent class.
R
Method Description
KA
boolean isTemporary() Identifies whether the focus is changed
R
permanently or temporarily.
SA
component Returns the opposite component that is involved in
getOppositeComponent() focus or activation change. For example, if the
A
focus gained event occurs, the opposite
R
component, which lost focus, is returned; and if
IT
the focus lost event occurs, the opposite
R
ItemEvent
02
The item event is generated by components, such as radio button, and check box, when an item or the
30
component is selected or deselected by the user. The following table lists the most commonly used methods
of the ItemEvent class.
52
00
Method Description
19
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
WindowEvent
The window event is generated by window when it is opened, closed, activated, deactivated, or when focus is
transferred into or out of the window.
The following table lists the most commonly used methods of the WindowEvent class.
Method Description
R
KA
Window getWindow() Returns the originator of the event.
R
The Methods of the WindowEvent Class
SA
Introducing Event Listeners
A
R
An event listener provides the event handler methods that are used to handle events. For example, when a
IT
button is clicked, the actionPerformed() method of the ActionListener interface is responsible for
handling the button-click event. Some of the event listener interfaces provided by Java are:
R
-A
ActionListener
KeyListener
01
MouseListener
02
MouseMotionListener
30
FocusListener
ItemListener
52
WindowListener
00
ActionListener
19
The ActionListener interface handles the action event. It is implemented by the class that processes the
R
action events. The following table lists the method provided by the ActionListener interface to handle the
specific events.
Method Description
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
KeyListener
The KeyListener interface handles the keyboard events generated by keystrokes. The class needs to
implement the KeyListener interface that handles the keyboard events.
The following table lists the methods provided by the KeyListener interface to handle the specific events.
Method Description
void Is used to handle the event that occurs when a key is pressed.
keyPressed(KeyEvent e)
R
void Is used to handle the event that occurs when a key is released.
keyReleased(KeyEvent e)
KA
void keyTyped(KeyEvent Is used to handle the event that occurs when a key is typed.
R
e)
SA
The Methods of the KeyListener Interface
A
MouseListener R
The MouseListener interface handles the mouse events that occur when the mouse pointer is within the
IT
bounds of the component. The following table lists the methods provided by the MouseListener interface
R
Method Description
02
void mouseClicked(MouseEvent e) Is used to handle the event that occurs when the
30
void mouseEntered(MouseEvent e) Is used to handle the event that occurs when the
mouse enters a component.
00
void mouseExited(MouseEvent e)
19
void mousePressed(MouseEvent e) Is used to handle the event that occurs when the
mouse button is pressed.
void mouseReleased(MouseEvent e) Is used to handle the event that occurs when the
mouse button is released.
The Methods of the MouseListener Interface
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
MouseMotionListener
The MouseMotionListener interface handles the events that occur on the mouse movement with respect to
the component.
The following table lists the methods provided by the MouseMotionListener interface to handle the
specific events.
Method Description
R
KA
void mouseMoved(MouseEvent e) Is used to handle the event that occurs when a
mouse cursor is moved.
R
The Methods of the MouseMotionListener Interface
SA
FocusListener
A
The FocusListener interface handles the events that occur when the component gains or loses the focus.
R
The following table lists the methods provided by the FocusListener interface to handle the specific
IT
events.
R
-A
Method Description
01
ItemListener
R
The ItemListener interface handles the events generated by the selectable component, such as combo box
and radio button. The following table lists the method provided by the ItemListener interface to handle
the specific events.
Method Description
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
WindowListener
The WindowListener interface handles the events generated by the window. The following table lists the
methods provided by the WindowListener interface to handle specific events.
Method Description
R
dispose operation on the window.
KA
void windowClosing(WindowEvent e) Is used to handle the event that occurs when a
R
window is closed from the window’s system
SA
menu or by clicking the close button of the
window.
A
void windowDeactivated(WindowEvent e) Is used to handle the event that occurs when a
R
window is no longer active.
IT
void windowOpened(WindowEvent e) Is used to handle the event that occurs when a
R
Note
The window’s system menu is the menu that is accessible by clicking the upper left icon
52
on the window.
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Implementing Events
In event handling, the source generates an event and notifies one or more event listeners. It is necessary to
register the listener with a source in order to get notified about the occurrence of a particular event. Once the
event listener is notified, it processes the event. In order to achieve event handling in a Java program, you
need to implement an event handler and associate the event handler with the source.
R
action, you need to implement the event handler. For this, you need to override the methods of the listener
KA
interfaces or the methods of the adapter classes. For example, you want to display, Welcome to Java, on a
frame on the click of a button. For this, you need to override the actionPerformed() method of the
R
ActionListener interface, as shown in the following code:
SA
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
A
import javax.swing.JButton;
import javax.swing.JFrame;
R
import javax.swing.JLabel;
IT
import javax.swing.JPanel;
R
{
01
JButton click;
02
JPanel panel;
JLabel message;
30
public ActionEventDemo()
52
{
super("Action Event Demo");
00
add(panel);
panel.add(click);
panel.add(message);
setSize(300, 300);
setVisible(true);
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
public static void main(String[] args)
{
ActionEventDemo obj = new ActionEventDemo();
}
}
In the preceding code, the ActionEventDemo class implements the ActionListener interface and
overrides the actionPerformed() method to handle the event generated by the button, click.
Let’s consider another example where you want to display the current position of the mouse cursor within the
frame. For this, you can override the mouseMoved() and mouseDragged() methods of the
MouseMotionListener interface, as shown in the following code:
import java.awt.FlowLayout;
R
import java.awt.event.MouseEvent;
KA
import java.awt.event.MouseMotionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
R
SA
public class MouseMotionDemo extends JFrame implements MouseMotionListener
{
A
int x, y; R
JLabel position;
IT
public MouseMotionDemo()
R
{
-A
setLayout(new FlowLayout());
02
add(position);
30
setSize(320, 300);
52
setVisible(true);
00
{
x = me.getX();
y = me.getY();
position.setText("Mouse cursor is at " + x + " " + y);
}
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
public static void main(String[] args)
{
MouseMotionDemo obj = new MouseMotionDemo();
}
}
In the preceding code, the MouseMotionDemo class implements the MouseMotionListener interface and
overrides the mouseMoved() and mouseDragged() methods, which handle the mouse events.
Consider another example where you want to show a confirmation dialog box when a user tries to close a
frame. For this, you need to override the windowClosing() method of the WindowListener interface.
However, if we implement the listener, you need to override all the methods. Therefore, instead of using the
listener, you can use the WindowAdapter class, as shown in the following code:
R
import java.awt.event.WindowAdapter;
KA
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
R
import javax.swing.JOptionPane;
import javax.swing.WindowConstants;
SA
public class WindowDemo extends WindowAdapter
{
A
JFrame jf;
R
IT
public WindowDemo()
R
{
-A
jf.setVisible(true);
jf.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
02
}
52
JOptionPane.QUESTION_MESSAGE);
R
if (n == JOptionPane.YES_OPTION)
{
jf.dispose();
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
In the preceding code, the WindowDemo class extends the WindowAdapter class and overrides the
windowClosing() method, which handle the mouse events.
Just a minute:
Which one of the following interfaces contains the method that helps to implement the
functionality to locate the mouse cursor within the frame?
1. MouseListener
R
2. MouseMotionListener
KA
3. WindowListener
R
4. ActionListener
SA
Answer:
2. MouseMotionListener
A
R
IT
R
-A
Just a minute:
01
Which one of the following code snippets registers the ActionListener interface to
02
1. addActionPerformed(this)
52
2. addActionListener(this)
00
3. addPerformedAction(this)
19
4. addListnerAction(this)
Answer:
R
2. addActionListener(this)
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Practice Questions
1. Which one of the following methods is used to set the layout of a container?
a. setLayout()
b. startLayout()
c. initLayout()
d. layoutContainer()
2. Which one of the following components allows adding multiple lines of text?
R
a. JTextField
KA
b. JTextArea
c. JOptionPane
R
d. JDialog
SA
3. Which one of the following components is used to create a set of components that are grouped together
in which only one component can be selected?
A
a. JCheckBox
R
IT
b. JButton
R
c. JRadioButton
-A
d. JFrame
01
The JLabel class does not allow you to add an icon on the label.
30
5. Which one of the following components of the event model listens for a specific event?
52
a. Event source
b. Event handler
00
c. Event class
19
d. Event object
R
6. Which one of the following event classes contains the getX() and getY() methods?
a. MouseEvent
b. KeyEvent
c. ActionEvent
d. FocusEvent
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
7. Which one of the following event listeners contains the mouseMoved() method?
a. MouseListener
b. FocusListener
c. MouseMotionListener
d. ItemListener
8. Which one of the following event listeners handles the event generated by selecting the radio button?
a. ItemListener
b. WindowListener
c.
R
ActionListener
KA
d. MouseListener
R
SA
A
R
IT
R
-A
01
02
30
52
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Summary
In this chapter, you learned that:
In a CUI application, a user needs to remember all the commands to work with the application.
The GUI provides a graphical way of interacting with the application.
Java provides the various UI components, such as JFrame, JPanel, JButton, and JLabel, of the
javax.swing package.
The most commonly used containers and components are:
JFrame
JDialog
R
JPanel
KA
JTabbedPane
R
JMenuBar
SA
JMenu
JMenuItem
JLabel
JTextField
A
R
JTextArea
IT
JCheckBox
R
JRadioButton
-A
JList
01
JComboBox
JButton
02
JOptionPane
30
You need to import the classes and the interfaces available in the javax.swing package to create the
UI of the applications.
52
To arrange the components in a container, you can use the various layouts, such as FlowLayout and
00
BorderLayout.
The setLayout() method is used to set the layout of the containers.
19
You can use the setLayout() method of the container and pass null as an argument to create a
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
An event source is an object that generates an event.
An event listener listens for a specific event and gets notified when the specific event occurs.
An event handler is a method that is invoked by an event listener when the event is generated.
Event classes represent the characteristics of all events. Some of the event classes provided by Java are:
ActionEvent
KeyEvent
MouseEvent
FocusEvent
ItemEvent
WindowEvent
R
The EventObject class, which is in the java.util package, is the superclass for all event classes.
KA
The action event is generated by components, such as a button, when an action is performed.
The mouse event is generated by a mouse with respect to the source component.
R
The key event is generated by a component when a key is pressed, released, or typed within the
SA
component.
The focus event is generated by a component when it receives or loses focus.
A
The item event is generated by components, such as radio button, and check box, when an item or the
R
component is selected or deselected by the user.
IT
The window event is generated by window when it is opened, closed, activated, deactivated, or when
R
ActionListener
KeyListener
02
MouseListener
30
MouseMotionListener
FocusListener
52
ItemListener
00
WindowListener
The ActionListener interface handles the action event.
19
The MouseListener interface handles the mouse events that occur when the mouse pointer is within
the bounds of the component.
The MouseMotionListener interface handles the events that occur on the mouse movement with
respect to the component.
The FocusListener interface handles the events that occur when the component gains or loses the
focus.
The ItemListener interface handles the events generated by the selectable component, such as combo
box and radio button.
The WindowListener interface handles the events generated by the window.
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
R
KA
R
SA
A
R
IT
R
-A
01
02
30
52
00
19
R
Implementing Inner
Classes
CHAPTER 2
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
At times, you need to develop a helper class that should provide a very specific functionality to another class
in the program. However, at the same time, you also want to ensure that the helper class is not accessible to
other class. This can be achieved by defining the helper class inside the class that uses the functionality. A
class defined within another class is called an inner class. The inner class increases encapsulation. In
addition, it makes the code readable and maintainable.
There are times when you need to convert the data from one type into another. For this, Java supports type
casting.
This chapter focuses on creating inner classes.
Objectives
R
KA
In this chapter, you will learn to:
R
Create inner classes
SA
A
R
IT
R
-A
01
02
30
52
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Creating Inner Class
Consider a scenario where you are developing a Java application to process credit card payments for clients,
such as retail stores. In this application, you have created a CreditCard class that models the credit card
used for payment by a client. The CreditCard class defines private fields for sensitive information, such as
the credit card number, expiry date, and CVV number. You need to create a CreditCardValidator class
that contains the business logic to validate a credit card using an object of the CreditCard class. However,
you cannot create a separate CreditCardValidator class as it will not be able to access the private fields
of the CreditCard class required for performing the validation. In such a scenario, you can use an inner
class. Inner classes are the classes defined inside another class. Java provides the following four types of
inner classes:
R
Regular inner class
KA
Static inner class
R
Method-local inner class
SA
Anonymous inner class
login credentials to login. Therefore, you need to create a class named Login, which will have the username
and password fields. As these details should not be accessible to other classes, you need to declare the
-A
username and password as private fields. However, the login credentials provided by the user need to be
01
validated. Therefore, you need to define a class named ValidateCredentials to implement the validation
logic. However, if this class is declared as an outer class, you cannot access the private fields. Therefore, to
02
implement the preceding functionality, you need to create a regular inner class.
30
A regular inner class is a class whose definition appears inside the definition of another class. The regular
inner class is similar to a member of an outer class. Therefore, the regular inner class shares all the features
52
of a member of a class. The following code snippet demonstrates an example for the regular inner class:
00
{
private String username;
R
In the preceding code snippet, a class, ValidateCredential, is created inside the class, Login. The
validate() method of ValidateCredential can access all the members of the Login class. Therefore,
the private fields, username and password, are accessible to the validate() method.
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
In order to instantiate an inner class outside the outer class, you first need to get the reference of the outer
class object and create an object of the inner class, as shown in the following code snippet:
R
to instantiate the inner class. This means that for each request for a validation, two objects, one for the outer
KA
class and another for the inner class, will be created in the heap.
R
Consider an example of an enterprise application where a large number of users are making numerous
SA
validation requests. Therefore, the amount of objects that will get assigned to the heap will increase. This
will adversely affect the performance of the application.
Therefore, to address the preceding challenge, you can create a static inner class. As a result, you will be able
A
to minimize the amount of objects, which are required to access the inner class functions. This is because in
R
order to access a static inner class, you do not need its enclosing outer class object.
IT
Static inner classes are inner classes marked with the static modifier. The following code snippet
R
class PaymentDetails
{
02
{
void validate()
52
{
/* code be added */
00
}
}
19
void validate()
{
/* code be added */
}
}
static class ValidateNetBankingAccount
{
void validate()
{
/* code be added */
}
}
}
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
In the preceding code snippet, ValidateCreditCards, ValidateDebitCards and
ValidateNetBankingAccount are static inner classes defined inside the PaymentDetails class.
You need to use the following code snippet to instantiate the ValidateNetBankingAccount static inner
class outside the PaymentDetails class:
PaymentDetails.ValidateNetBankingAccount validator=new
PaymentDetails.ValidateNetBankingAccount();
Note
A static inner class cannot directly access the member variables of the outer class.
R
Therefore, to access the member variables, you need to create the instance of the outer
KA
class inside the inner class.
R
SA
Method-local Inner Class
A
A method-local inner class is defined inside the method of the enclosing class. Because the class is defined
R
inside a method, it needs to be instantiated within the same method.
IT
Consider the following code snippet of the method-local inner class:
R
-A
{
final String z = "local variable";
30
System.out.println(x);
class Inner
52
{
public void print()
00
{
System.out.println("Outer x: " + x);
19
}
}
Inner obj = new Inner();
obj.print();
}
public static void main(String args[])
{
MethodLocalInner m = new MethodLocalInners();
m.display();
}
}
In the preceding code snippet, a MethoLocalInner class with a method named display() is created. In
the display() method, a class named Inner is created with a method named print().
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Anonymous Inner Class
Consider a scenario where you need to develop a gaming application by using the Swing components. In this
application, you need to design a startup screen interface with a start button. In addition, you want to
implement the functionality wherein the game should begin when the start button is clicked. To implement
this functionality, you need to override the actionPerformed() method of the ActionListener
interface, as shown in the following code snippet:
R
/* code to be added here */
KA
}
}
R
public class StartUpScreen
{
SA
JFrame jf;
JButton start;
StartUpScreen()
{
A
jf=new JFrame("Startup Screen");
R
IT
start=new JButton("Start");
jf.setLayout(new FlowLayout());
R
jf.add(start);
-A
jf.setSize(300,300);
jf.setVisible(true);
01
start.addActionListener(new StartUpAction());
}
02
}
30
The StartUpAction class is accessible to other classes in the application. However, the functionality
defined in the StartUpAction class is not required by other classes in the application. Therefore, you need
52
not define an outer class. In addition, the instance of this class is used only once. Therefore, with the help of
an anonymous inner class, the functionality provided by the StartUpAction class can be implemented. An
00
anonymous inner class has no name, and it is either a subclass of a class or an implementer of an interface. In
19
start.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
/* code to be added here */
}
});
In the preceding code snippet, an anonymous inner class of the type, ActionListener, is created and the
actionPerformed() method is overridden.
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Just a minute:
Which one of the following inner classes can be defined without the name of the class?
R
4. Anonymous inner class
KA
Answer:
R
4. Anonymous inner class
SA
A
R
IT
Activity 2.1: Creating Inner Classes
R
-A
01
02
30
52
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Practice Questions
1. Which one of the following inner classes is defined inside the method of the enclosing class?
a. Regular inner class
b. Static inner class
c. Method-local inner class
2. Which one of the following options correctly denotes an anonymous inner class?
a. It is defined inside the method of the enclosing class.
R
KA
b. It is marked with a static modifier.
c. It is similar to the member of the outer class.
R
SA
d. It does not have a name and is either a subclass of a class or an implementer of an interface.
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Summary
In this chapter, you learned that:
A class defined within another class is called an inner class.
Java provides the following four types of inner classes:
Regular inner class
Static inner class
Method-local inner class
Anonymous inner class
A regular inner class is a class whose definition appears inside the definition of another class. The
R
regular inner class is similar to a member of an outer class.
KA
Static inner classes are inner classes marked with the static modifier.
R
A method-local inner class is defined inside the method of the enclosing class. Because the class is
SA
defined inside a method, it needs to be instantiated within the same method.
A
R
IT
R
-A
01
02
30
52
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
R
KA
R
SA
A
R
IT
R
-A
01
02
30
52
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
At times, you want to develop applications that can be used worldwide. These applications should be able to
display various pieces of information, such as text, currency, and date, according to the region where they are
deployed. To meet this requirement, Java supports localization.
In this chapter, you will learn about implementing localization.
Objectives
R
KA
R
SA
A
R
IT
R
-A
01
02
30
52
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Implementing Localization
Consider a scenario where you want to develop a hotel management application that can be used worldwide.
You want that the text in the application should be displayed according to the region. For example, if the
application is used in France, the text should be displayed in French and the currency should be displayed in
Euros. To develop such applications, you need to implement localization, which is a process of customizing
the application to a specific locale and culture. Localization can be implemented on different types of data,
such as date, currency, and text. To localize different types of data, it is necessary to determine the language
and country. To determine the language, Java provides a predefined set of language codes, such as zh for
Chinese and en for English. In addition, it provides a predefined set of country codes, such as AU for
Australia and CN for China. Further, to work with localization, the Locale class of the java.util package
R
is used. The instance of the Locale class can be created, as shown in the following code snippet:
KA
Locale l=new Locale("de","DE");
R
In the preceding code snippet, de specifies the language code and DE specifies the country code.
SA
Localizing Date
A
R
To localize the date, you need to use the various date formats. To determine the date format according to the
IT
locale, you can use the java.text.DateFormat class. To display the date in German, the following code
R
is used:
-A
import java.text.DateFormat;
01
import java.util.*;
public class DateDemo {
02
Locale("de","DE"));
String date = df.format(new Date());
52
System.out.println(date);
}
00
}
19
4. Juni 2013
Note
The preceding output may vary based on the current system’s date.
In the preceding code, DateFormat.getDateInstance is used to specify a formatting style for the
German locale. DateFormat.Long specifies the description of the date according to the locale. The String
date = df.format(new Date()); statement formats the current date into the date string.
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Similarly, to display the time in German, the following code is used:
import java.text.*;
import java.util.*;
public class TimeDemo {
public static void main(String args[]){
DateFormat df = DateFormat.getTimeInstance(DateFormat.LONG, new
Locale("de","DE"));
String time = df.format(new Date());
System.out.println(time);
}
}
The preceding code generates the following output:
R
KA
13:36:28 IST
R
Note
SA
The preceding output may vary based on the current system’s time.
A
R
In the preceding code, the getTimeInstance() method is used to specify a formatting style for the
IT
German locale. DateFormat.Long specifies the description of the date according to the locale. The String
time = df.format(new Date()); statement formats the current time into the string format.
R
-A
01
Localizing Currency
02
To localize the currency, you need to use various currency formats. To determine the currency format
30
according to the locale, you can use the java.text.NumberFormat class. To display the currency in
German, the following code is used:
52
import java.text.*;
00
import java.util.*;
public class CurrencyDemo {
19
Locale("de","DE"));
String formatted = nft.format(1000000);
System.out.println(formatted);
}
}
The preceding code generates the following output:
1.000.000,00 €
In the preceding code, NumberFormat.getCurrencyinstance returns a currency format for the locale.
The String formatted = nft.format(1000000); statement formats the currency into a string.
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Localizing Text
To localize text, you need to use the resource bundles. A resource bundle is a property file that contains the
locale specific data. To work with data stored in a resource bundle, you need to use the ResourceBundle
class. ResourceBundle is a class that encapsulates a set of resources.
To access a particular resource, you need to obtain a reference of the ResourceBundle class and call its
getObject() method.
To have a locale-specific object, a program needs to load the ResourceBundle object by using the
getBundle method, as shown in the following code snippet:
R
ResourceBundle myResourceBundle = ResourceBundle.getBundle("MessagesBundle");
KA
In the preceding code snippet, a MessagesBundle resource bundle has been loaded that contains the
localized resource. When a the getBundle() method is called, the ResourceBundle tries to load a
R
resource file with a variation of the name that was specified. It searches the resource bundle with the
SA
explicitly specified locale values appended to the name. It then searches the resource bundle with the default
Locale’s values.
A
For example, if the default Locale is Locale.US, then getBundle() will load the resource bundle file in
the US locale.
R
IT
Consider a scenario where you need to develop a Java application that displays the message, Welcome, in
R
German or Chinese. For this, you need to create the German and Chinese resource bundles.
-A
You can create the German resource bundle file, such as MessageBundle_de.properties, and add the
following code snippet inside the file to localize the message, Welcome, in German:
01
02
message=willkommen
You can create the Chinese resource bundle file, such as MessageBundle_zn.properties, and add the
30
following code snippet inside the file to localize the message, Welcome, in Chinese:
52
message=歡迎
00
19
Note
R
To create a language specific resource bundle file, you need to specify the properties
filename as <resourcebundle name>_<language code>.properties.
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
The following code demonstrates how the text is localized:
import java.util.Locale;
import java.util.ResourceBundle;
public class TestLocale {
public static void main(String args[]){
Locale l1=new Locale("de","DE");
ResourceBundle rb1 = ResourceBundle.getBundle("MessageBundle",l1);
System.out.println(rb1.getString("message"));
Locale l2=new Locale("zn","ZN");
ResourceBundle rb2 = ResourceBundle.getBundle("MessageBundle",l2);
System.out.println(rb2.getString("message"));
}
R
}
KA
In the preceding code, the getBundle() method is used to load the ResourceBundle class when the
program needs a locale-specific object. To retrieve an object from the resource bundle, the getString()
R
method is used.
SA
A
R
IT
Just a minute:
R
Which one of the following statements denotes the correct way to create an instance of
-A
Answer:
19
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Practice Questions
1. State whether the following statement is true or false.
Localization is the process of customizing the application to a specific locale and culture.
2. Identify the correct option by using which the match succeeds if the given input string starts with any
character between a and z, except b, c, and d.
a. [a-z&&[abc]]
b. [b-z&&[^bcd]]
c. [a-z&&[^n-p]]
R
d.
KA
[abc]
3. Identify the correct option that is used to match the pattern with the longest possible string.
R
a. Greedy
SA
b. Reluctant
c. Possessive
A
R
IT
R
-A
01
02
30
52
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Summary
In this chapter, you learned that:
Localization is a process of customizing the application to a specific locale and culture.
Localization can be implemented on different types of data, such as date, currency, and text.
To localize different types of data, it is necessary to determine the language and country.
To determine the language, Java provides a predefined set of language codes, such as zh for Chinese and
en for English.
To work with localization, the Locale class of the java.util package is used.
To localize the date, you need to use the various date formats. To determine the date format according to
R
the locale, you can use the java.text.DateFormat class.
KA
To localize the currency, you need to use various currency formats. To determine the currency format
R
according to the locale, you can use the java.text.NumberFormat class.
SA
To localize text, you need to use the resource bundles.
A resource bundle is a property file that contains the locale specific data. To work with data stored in a
resource bundle, you need to use the ResourceBundle class.
A
To have a locale-specific object, a program needs to load the ResourceBundle object by using the
R
getBundle() method.
IT
R
-A
01
02
30
52
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
R
KA
R
SA
A
R
IT
R
-A
01
02
30
52
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
At times, you need to create interfaces, classes, and methods that may work with different types of data. For
this, you need to write a robust and type-safe code, which is a tedious and error-prone task. To overcome the
overhead of writing the type-safe code, Java provides the generics feature. Generics allow you to create
generalized interfaces, classes, and methods.
This chapter focuses on the creation of the user-defined generic classes and methods and implementation of
type-safety.
Objectives
R
KA
Create user-defined generic classes and methods
Implement type-safety
R
SA
A
R
IT
R
-A
01
02
30
52
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Creating User-defined Generic Classes and Methods
Consider a scenario where you need to develop a class with a method, which can return various objects, such
as Integer, String, and Double. To implement the functionality, you need to create generic classes and
methods. Generics mean parameterized types that enable you to write the code that can work with many
types of object. In addition, it allows you to provide the enhanced functionality to classes and methods by
making them generalized. The generic classes and methods are created so that the references and methods
can accept any type of object.
R
KA
Generics enable you to generalize classes. This means that a reference variable, an argument of a method,
and a return type can be of any type. In the declaration of a generic class, the name of the class is followed by
R
a type parameter section. The type parameter section is represented by angular brackets, < >, that can have
SA
one or more types of parameters separated by commas. The following syntax is used to create generic
classes:
class [ClassName]<T>
A
{
R
IT
}
R
You can create a generic class by using the following code snippet:
-A
01
class GenericClassDemo<T>
{
02
}
30
Consider an example where you want to create a generic class to set and get the Integer and String
52
private T t;
R
public T getValue()
{
return t;
}
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
iobj.setValue(10);
System.out.println(iobj.getValue());
10
Ten
In the preceding code, the GenericClassDemo class is created with two methods, setValue() and
R
getValue(). T represents the type of data, which can accept any object, such as Integer and String. The
KA
T parameter in the preceding code is used as a reference type, return type, and method argument.
R
SA
Creating a Generic Method
In the generic class, a method can use the type parameter of the class, which automatically makes the method
generic. Consider the following code of the generic method inside the generic class: A
R
IT
public class GenericClassDemo<T>
R
{
-A
private T t;
01
this.t = t;
}
30
public T getValue()
52
{
return t;
00
}
}
19
In the preceding code, the setValue() and getValue() methods are using the class’s type parameter.
R
However, you can declare a generic method, which contains its own one or more type parameters. The
declaration of a generic method contains the type parameter that is represented by angular brackets, < >. The
following syntax is used to create a generic method:
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
The type parameter section can have one or more type of parameters separated by commas. Further, it is also
possible to create a generic method inside a non generic class.
Consider the following code of the generic method inside the non generic class:
R
GenericMethodDemo obj = new GenericMethodDemo();
KA
System.out.println("The generic method is called with String value: "
R
+ obj.display("Test"));
System.out.println("The generic method is called with Double value: "
SA
+ obj.display(7.5));
System.out.println("The generic method is called with Boolean value:
" + obj.display(true));
System.out.println("The
A
generic method is called with Integer value:
" + obj.display(10));
R
IT
}
R
}
-A
In the preceding code, the GenericMethodDemo class contains the display() method that is used to
display the values. In addition, inside the main() method, the display method is called four times with four
00
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Implementing Type-safety
Consider an example where you want to create an object of a generic class. To create the object, you need to
invoke the constructor of a generic class with the required type of parameters, such as Integer or String,
which increases the length of the code. However, to reduce the coding, Java provides the flexibility to leave
the type parameters empty as long as the compiler can guess or judge the type of the argument from the
context. In addition, Java provides wildcards that allow you to achieve inheritance in a type parameter.
R
You have learned how to create generic classes and methods. In order to use those classes or methods, you
KA
need to understand how Java infers the arguments that are provided as the type parameters. While using a
generic type, you must provide the type argument for every type parameter declared for the generic type. The
R
type argument list is a comma-separated list that is delimited by angular brackets and follows the type name.
SA
For example, consider the following code of a generic type with two type arguments:
A
{ R
private X first;
IT
private Y second;
R
-A
first = a1;
second = a2;
02
}
30
public X getFirst()
{
52
return first;
}
00
public Y getSecond() {
19
return second;
}
R
}
}
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Once the preceding code is executed, the following output is displayed:
String is Test
Integer is 1
Integer is 2
String is Demo
In the preceding code, the Pair class contains two methods, getFirst() and getSecond(), which return
the value of the first and second variables. In the main() method, two objects have been created that are
of the <String, Integer> and <Integer, String> types.
Java provides a new feature, type inference, which enables you to invoke the constructor of a generic class
with an empty set of type parameters, <>. The empty set of type parameters can be used as long as the
compiler can infer the type arguments from the context.
R
KA
Consider the preceding example in which you can use the empty set of type parameters while creating the
objects of the Pair class, as shown in the following code snippet:
R
SA
Pair<String, Integer> obj1 = new Pair<>("Test", 1);
A
R
IT
Note
R
The pair of angular brackets, <>, is informally called the diamond operator.
-A
01
02
Using Wildcards
30
52
Generics follow a simple rule of declaration, which says the type of reference variable declaration must
match the type passed to the actual object. This means that in generics, a subclass cannot be passed as a
00
Or
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
The following table lists the most commonly used wildcard arguments.
Wildcard Description
? extends It specifies that the type can be anything that extends from the class specified
after the extends keyword. It is a bounded wildcard.
? super It specifies that the type can be anything that is the base class of the class
specified after the super keyword. It is a bounded wildcard.
R
super type of any class. It is an unbounded wildcard.
KA
The Wildcard Arguments
R
SA
Note
A bounded wildcard is used to bound any type of object by using the keywords:
A
extends, implements, and super. An unbounded wildcard does not bind any type of
R
object and does not associate with any keyword.
IT
R
Consider an example where you want to compare the values of two objects. However, you want to compare
-A
only the numeric objects. For this, you can use the following code:
01
private T t;
30
this.t = t;
}
00
public T getValue() {
19
return t;
}
R
}
else
{
return false;
}
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
public static void main(String[] args)
{
WildCardDemo<Integer> obj1 = new WildCardDemo<Integer>();
obj1.setValue(10);
R
KA
}
}
R
In the preceding code, the WildCardDemo class is created with three methods: setValue(), getValue(),
SA
and compare(). The compare() method uses wildcards so that an object of Number or one of its subtype
can be passed to it at runtime. When the compare() method is called, a compilation error is raised because
obj2 is of type, String, and obj1 is of type, Integer.
A
R
In the preceding example, the <? extends Number> wildcard is used, which tells that the specified object
must inherit the Number class.
IT
R
-A
01
02
30
52
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Just a minute:
Which one of the following wildcards is used to specify the type that is inherited from
the specified class?
1. <?>
3. <extends ?>
R
KA
4. <? extends ?>
R
Answer:
SA
2. <? extends >
A
R
Activity 4.1: Working with Generics
IT
R
-A
01
02
30
52
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Practice Questions
1. Which one of the following symbols is used to define type parameters?
a. { }
b. [ ]
c. ( )
d. <>
R
A non generic class can contain a generic method.
KA
3. Identify the correct syntax of a generic class.
R
SA
a. public <T> class Myclass { }
5. Which one of the following wildcards specifies that the type can be anything?
00
a. ?
19
b. ? extends
R
c. ? super
d. ? implements
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Summary
In this chapter, you learned that:
Generics enable you to generalize classes, which mean that a reference variable, an argument of a
method, and a return type can be of any type.
The type parameter section is represented by angular brackets, < >, that can have one or more types of
parameters separated by commas.
In the generic class, a method can use the type parameter of the class, which automatically makes the
method generic.
You can declare a generic method, which contains its own one or more type parameters.
R
The declaration of a generic method contains the type parameter that is represented by angular brackets,
KA
< >.
Java provides wildcards that allow you to achieve inheritance in a type parameter.
R
Java provides a new feature, type inference, which enables you to invoke the constructor of a generic
SA
class with an empty set of type parameters, <>.
Java provides wildcard arguments to pass a subclass as a subtype of a superclass in generics.
Java provides the following types of wildcards:
A
R
? extends
IT
? super
R
?
-A
01
02
30
52
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
R
KA
R
SA
A
R
IT
R
-A
01
02
30
52
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
At times, you need to handle a collection of objects. This task can be performed with the help of arrays.
However, arrays work on a single type of data. Therefore, to work with the collection of different types of
object, Java provides the collection framework. This framework provides interfaces, classes, and algorithms
for implementing data structures. The collection framework is used for various purposes, such as storing,
retrieving, and manipulating objects.
This chapter explains how to use various interfaces, such as List, Set, Map, and Deque, to create a
collection of objects. In addition, it discuss about the sorting functionalities.
Objectives
R
In this chapter, you will learn to:
KA
Use the Set interface
R
Use the List interface
SA
Use the Map interface
Use the Deque interface
A
Implement sorting R
IT
R
-A
01
02
30
52
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Using the Set Interface
Consider a scenario where you need to develop a chat application. In this application, you can implement a
set of functionalities to create a chat group dynamically from the list of available contacts. Further, members
can be added and removed from the chat group as per the user preference. To implement this functionality,
you can create a collection of contacts. However, to ensure the uniqueness of the contacts in the chat group,
you need to create the collection using the Set interface.
The Set interface is used to create a collection of unique objects. The following figure shows the class
hierarchy of the java.util package, which implements the Set interface.
R
KA
R
SA
A
R
IT
R
-A
01
02
30
The preceding figure shows that the java.util package contains the AbstractCollection,
00
AbstractSet, HashSet, and TreeSet classes and the Collection and Set interfaces. The
AbstractSet class implements the Set interface and extends the AbstractCollection class, which is
19
further extended by the HashSet and TreeSet classes. In addition, the Set interface extends the
R
Collection interface.
The package, java.util, provides the Iterator interface to traverse through the set collection. The
reference of the Iterator interface can be obtained using the iterator() method of the Set interface.
The Iterator interface contains various methods, such as hasNext()and next(), which help to traverse
the set collection.
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Working with the HashSet Class
The HashSet class provides the implementation of the Set interface that enables you to create a set in which
insertion is faster because it does not sort the elements. The HashSet class provides various constructors that
can be used to create an instance.
The following table lists the commonly used constructors of the HashSet class.
Constructor Description
R
KA
HashSet(Collection<? extends E> c) Creates an instance with the specified collection.
R
HashSet(int initialCapacity) Creates an empty instance of HashSet with the
SA
specified initial capacity. The initial capacity is
the size of HashSet that grows or shrinks
automatically, whenever objects are added or
A
removed to/ from HashSet.
R
IT
The Constructors of the HashSet Class
R
The following table lists the commonly used methods of the HashSet class.
-A
01
Method Description
02
import java.util.*;
class Contacts
{
/* code to create contacts */
}
public class ChatGroup
{
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
public static void main(String args[])
{
Contacts a=new Contacts();
Contacts b=new Contacts();
Contacts c=new Contacts();
HashSet<Contacts> hs=new HashSet<Contacts>();
hs.add(a);
hs.add(b);
hs.add(c);
}
}
In the preceding code snippet, the generic type object of the HashSet class is created that contains a
collection of the Contacts objects. The add() method of the HashSet class is used to add the Contacts
R
objects to the HashSet object.
KA
You can use the following code snippet to remove the Contacts object from the HashSet object:
R
hs.remove(c);
SA
You can use the following code snippet to find the number of objects available in the HashSet object:
A
hs.size(); R
You can use the following code snippet to traverse through the HashSet object:
IT
Iterator i = hs.iterator();
R
while(i.hasNext())
-A
{
System.out.println(i.next());
01
}
02
In the preceding code snippet, the iterator()method is used to retrieve the Iterator reference. In
addition, the hasNext()method is used to check if there are more elements in HashSet, and the
30
You have learned how generics resolve type safety issues in the Java applications. In addition, you have also
used the generic HashSet collection where you need to specify the type of objects that the collection would
00
store. However, there are several existing applications that have been developed before generics were
19
introduced and such applications should continue running. To ensure interoperability of such applications,
Java also provides support for non generic collections. In the previous example, a collection of objects is
R
created by specifying the generic type, <Contact>. In this context, the collection is of the Contact objects
only. However, you can also use the non generic HashSet collection that can store any type of objects. For
this, you can use the following code snippet:
In the preceding code snippet, a non generic HashSet collection is created that contains a collection of
different objects.
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Note
Raw type is the name of the generic class or interface without any type arguments.
R
of objects. The insert or add object process is slow as it sorts the objects on every insertion. However,
KA
TreeSet automatically arranges the objects in a sorted order, which enhances the search of data from a large
amount of information. The TreeSet class provides various constructors that can be used to create an
R
instance of TreeSet. The following table lists the commonly used constructors of the TreeSet class.
SA
Constructor Description
A
TreeSet()
R
Creates an empty instance of TreeSet.
IT
TreeSet(Collection<? extends
R
Method Description
52
it is not present.
19
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Consider the following code to add and remove the objects to/ from a TreeSet collection:
import java.util.Iterator;
import java.util.TreeSet;
R
KA
System.out.println("Size of TreeSet is: " + obj.size());
R
obj.add(iobj1);
obj.add(iobj2);
SA
obj.add(iobj3);
obj.add(iobj4);
obj.add(iobj2);
A
System.out.println("\nTreeSet after adding the objects: " + obj);
R
IT
System.out.println("Size of TreeSet after adding objects: " +
obj.size());
R
obj.remove(iobj3);
-A
obj.remove(iobj1);
01
obj.size());
30
while(i.hasNext())
{
00
System.out.println(i.next());
}
19
}
R
}
Once the preceding code is executed, the following output is displayed:
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
In the preceding code, the TreeSet object contains a collection of the Integer objects. The add() method
of the TreeSet class is used to add the Integer objects to the TreeSet object. Further, two objects are
removed using the remove() method. The Iterator interface is used to iterate the objects in the set one
after the other.
R
KA
R
SA
A
R
IT
R
-A
01
02
30
52
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Using the List Interface
The List interface is used to create an ordered collection of objects, which can contain duplicate objects. In
this collection, the objects can be inserted one after the other or at the specified position in the list. Similarly,
the objects can be accessed one after the other or from the specified position in the list. The following figure
shows the class hierarchy of the java.util package that implements the List interface.
R
KA
R
SA
A
R
IT
R
-A
01
The preceding figure shows that the java.util package contains the AbstractCollection,
30
class, which is then extended by the ArrayList, AbstractSequentialList, and Vector classes. The
00
AbstractList class implements the List interface, which extends the Collection interface. The
LinkedList class extends the AbstractSequentialList class.
19
The package, java.util, provides the ListIterator interface to traverse through the list collection. The
R
reference of the ListIterator interface can be obtained using the listIterator() method of the List
interface. The ListIterator interface contains various methods, such as hasNext(), hasPrevious(),
next(), and previous(), which help to traverse the list in both directions.
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Working with the ArrayList Class
The ArrayList class provides the implementation of the List interface. The ArrayList class enables you
to create a resizable array. Its size increases dynamically when more elements are added. ArrayList proves
to be efficient in searching an object in the list and inserting the objects at the end of the list.
The ArrayList class provides various constructors that can be used to create an instance. The following
table lists the commonly used constructors of the ArrayList class.
Constructor Description
R
ArrayList() Creates an empty instance of ArrayList.
KA
ArrayList(Collection<? extends E> Creates an instance with the specified collection.
R
c)
SA
ArrayList(int initialCapacity) Creates an empty instance of ArrayList with
the specified initial capacity. The initial capacity
A
is the size of ArrayList that grows or shrinks
R
automatically, whenever an object is added or
IT
removed to/ from ArrayList.
R
The following table lists the commonly used methods of the ArrayList class.
01
02
Method Description
30
ArrayList.
00
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Consider the following code to add and remove the objects to/ from an ArrayList collection:
import java.util.ArrayList;
import java.util.ListIterator;
R
KA
System.out.println("Size of ArrayList is: " + obj.size());
R
obj.add(sobj1);
obj.add(sobj2);
SA
obj.add(sobj3);
obj.add(sobj4);
obj.add(sobj1);
A
System.out.println("\nArrayList after adding the objects: " + obj);
R
IT
System.out.println("Size of ArrayList after adding objects: " +
obj.size());
R
-A
obj.remove(2);
obj.remove(sobj4);
01
ListIterator i = obj.listIterator();
while(i.hasNext())
00
{
System.out.println(i.next());
19
}
R
}
}
In the preceding code, the ArrayList object contains a collection of the String objects. The add()
method of the ArrayList class is used to add the String objects. Further, two objects are removed using
the remove() method. The ListIterator interface is used to iterate the objects in the list one after the
other.
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Once the preceding code is executed, the following output is displayed:
R
Element 1
KA
R
Working with the LinkedList Class
SA
The LinkedList class provides the implementation of the List interface. The LinkedList class enables
you to create a doubly-linked list. The doubly-linked list is a set of sequentially linked records called nodes
A
where each node contains two links that are the references of the previous node and the next node in the
R
sequence, respectively. LinkedList can be traversed in the forward or backward direction. LinkedList
IT
proves to be efficient in insertion and deletion of objects from the list.
R
The LinkedList class provides various constructors that can be used to create an instance. The following
-A
Constructor Description
LinkedList() Creates an empty instance of LinkedList.
30
c) collection.
00
The following table lists the commonly used methods of the LinkedList class.
R
Method Description
boolean add(E e) Is used to add the specified object at the end of
LinkedList.
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Method Description
E remove(int index) Is used to remove the object at the specified
index from LinkedList.
boolean remove(Object o) Is used to remove the first occurrence of the
specified object from LinkedList.
int size() Is used to get the number of objects in
LinkedList.
R
KA
import java.util.LinkedList;
import java.util.ListIterator;
R
SA
public class LinkedListDemo
{
public static void main(String[] args)
A
{
LinkedList<Integer> obj = new LinkedList<Integer>();
R
Integer iobj1 = new Integer(101);
IT
Integer iobj2 = new Integer(102);
R
obj.add(iobj1);
obj.add(iobj2);
02
obj.add(iobj3);
obj.add(iobj4);
30
obj.add(iobj1);
52
obj.size());
19
obj.remove(iobj2);
obj.remove(iobj3);
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Once the preceding code is executed, the following output is displayed:
LinkedList after adding the objects: [101, 102, 103, 104, 101]
Size of LinkedList after adding objects: 5
R
101
KA
In the preceding code, the LinkedList object contains a collection of the Integer objects. The add()
method of the LinkedList class is used to add the Integer objects. Further, two objects are removed
R
using the remove() method. The ListIterator interface is used to iterate the objects in the list one after
SA
the other.
Vector class are synchronized, which means that only one thread at a given time can access it in a
-A
multithreaded environment. On the other hand, the methods of the ArrayList and LinkedList classes are
01
not synchronized.
The Vector class provides various constructors that can be used to create an instance. The following table
02
Constructor Description
00
collection.
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
The following table lists the commonly used methods of the Vector class.
Method Description
R
E remove(int index) Is used to remove the object at the specified
KA
index from Vector.
R
boolean remove(Object o) Is used to remove the first occurrence of the
SA
specified object from Vector.
import java.util.ListIterator;
import java.util.Vector;
01
obj.add(dobj1);
obj.add(dobj2);
obj.add(dobj3);
obj.add(dobj4);
obj.add(dobj1);
obj.remove(dobj1);
obj.remove(dobj3);
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
System.out.println("\nVector after removing the objects: " + obj);
System.out.println("Size of Vector after removing objects: " +
obj.size());
R
Size of Vector is: 0
KA
Vector after adding the objects: [77.5, 68.1, 52.8, 40.2, 77.5]
R
Size of Vector after adding objects: 5
SA
Vector after removing the objects: [68.1, 40.2, 77.5]
Size of Vector after removing objects: 3
In the preceding code, the Vector object contains a collection of the Double objects. The add() method of
-A
the Vector class is used to add the Double objects. Further, two objects are removed using the remove()
01
method. The ListIterator interface is used to iterate the objects one after the other.
02
30
52
Just a minute:
00
1. List
2. Vector
3. TreeSet
4. ArrayList
Answer:
3. TreeSet
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Using the Map Interface
The Map interface enables you to create a collection with key-value pair objects. In this collection, both key
and value are objects. You need to use the key object to access the corresponding value object. The Map
interface allows duplicate value objects but the key object must be unique. The following figure shows the
class hierarchy of the java.util package that implements the Map interface.
R
KA
R
SA
A
R
IT
The Class Hierarchy of the java.util Package
R
The preceding figure shows that the java.util package contains the AbstractMap, Dictionary,
-A
HashMap, TreeMap, and Hashtable classes and the Map interface. The HashMap and TreeMap classes
01
extend the AbstractMap class, which implements the Map interface. In addition, the Hashtable class
extends the Dictionary class that also implements the Map interface.
02
30
The HashMap class enables you to create a collection in which a value is accessible using the key. HashMap
00
stores objects in an unordered form. The HashMap class allows one null value for a key and any number of
19
The HashMap class provides various constructors that can be used to create an instance.
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
The following table lists the commonly used constructors of the HashMap class.
Constructor Description
R
HashMap(Map<? extends K, ? extends
KA
Creates an instance with the same mapping of
V> m) specified Map.
R
The Constructors of the HashMap Class
SA
The following table lists the commonly used methods of the HashMap class.
A
Method
R
Description
IT
void clear()
R
V get(Object key) Is used to get the value object of the specified key
01
V put(K key, V value) Is used to add the specified key object with the
specified value object in HashMap.
30
52
in HashMap.
R
Note
K and V represent key and value, respectively. Both, K and V, are used for the types of
classes.
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Consider the following code to add and remove the objects to/ from a HashMap collection:
import java.util.HashMap;
R
System.out.println("Size of HashMap is: " + obj.size());
KA
obj.put("L1", iobj1);
R
obj.put("L2", iobj2);
obj.put("L3", iobj3);
SA
obj.put("L4", iobj4);
obj.put("L5", iobj1);
obj.remove("L3");
-A
obj.remove("L5");
01
obj.size());
}
30
}
52
HashMap after adding the objects: {L1=11, L2=22, L3=33, L4=44, L5=11}
Size of HashMap after adding objects: 5
R
In the preceding code, the HashMap object contains a collection of key-value pair objects. The put()
method of the HashMap class is used to add the key-value pair objects. Further, the mapping of two objects
are removed using the remove() method.
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Working with the TreeMap Class
The TreeMap class enables you to create a collection of objects in the sorted order with unique keys. The
sorted collection improves the retrieval process of objects.
The TreeMap class provides various constructors that can be used to create an instance. The following table
lists commonly used constructors of the TreeMap class.
Constructor Description
R
KA
TreeMap(Map<? extends K, ? extends Creates an instance with the same mapping of
V> m) specified Map.
R
SA
The Constructors of the TreeMap Class
The following table lists the commonly used methods of the TreeMap class.
A
R
Method Description
IT
R
V get(Object key) Is used to get the value object of the specified key object from
01
TreeMap.
02
V put(K key, V value) Is used to add the specified key object with the specified value
30
object in TreeMap.
52
V remove(Object o) Is used to remove the mapping for the specified key object from
TreeMap.
00
int size()
19
import java.util.TreeMap;
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
String sobj4 = new String("Value 4");
System.out.println("Size of TreeMap is: " + obj.size());
obj.put(101, sobj1);
obj.put(102, sobj2);
obj.put(103, sobj3);
obj.put(104, sobj4);
obj.put(105, sobj1);
System.out.println("\nTreeMap after adding the objects: " + obj);
System.out.println("Size of TreeMap after adding objects: " +
obj.size());
obj.remove(103);
obj.remove(105);
System.out.println("\nTreeMap after removing the objects: " + obj);
System.out.println("Size of the TreeMap after removing objects: " +
R
obj.size());
KA
}
}
R
Once the preceding code is executed, the following output is displayed:
SA
Size of TreeMap is: 0
A
TreeMap after adding the objects: {101=Value 1, 102=Value 2, 103=Value 3,
104=Value 4, 105=Value 1}
R
Size of TreeMap after adding objects: 5
IT
R
In the preceding code, the TreeMap object contains a collection of key-value pair objects. The put()
01
method of the TreeMap class is used to add the key-value pair objects. Further, mapping of two objects are
02
The Hashtable class enables you to create an unordered collection of objects, which cannot contain the
null objects. The methods of the Hashtable class are synchronized, which means that only one thread at a
19
given time can access it in a multithreaded environment. On the other hand, the methods of the HashMap and
TreeMap classes are not synchronized.
R
The Hashtable class provides various constructors that can be used to create an instance.
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
The following table lists commonly used constructors of the Hashtable class.
Constructor Description
R
Hashtable(Map<? extends K, ?
KA
Creates an instance with the same mapping of
extends V> t) specified Map.
R
The Constructors of the Hashtable Class
SA
The following table lists the commonly used methods of the Hashtable class.
A
Method
R
Description
IT
void clear() Is used to remove all objects from Hashtable.
R
-A
V get(Object key) Is used to get the value object of the specified key
01
V put(K key, V value) Is used to add the specified key object with the
30
import java.util.Hashtable;
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Double dobj4 = new Double(12.5);
obj.put(55, dobj1);
obj.put(60, dobj2);
obj.put(65, dobj3);
obj.put(70, dobj4);
obj.put(75, dobj3);
R
obj.remove(65);
KA
obj.remove(75);
R
System.out.println("Size of Hashtable after removing objects: " +
SA
obj.size());
A
} R
Once the preceding code is executed, the following output is displayed:
IT
R
55=55.6}
Size of Hashtable after adding objects: 5
02
In the preceding code, the Hashtable object contains a collection of key-value pair objects. The put()
52
method of the Hashtable class is used to add the key-value pair objects. Further, mapping of two objects
00
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Just a minute:
Which one of the following classes contains the synchronized methods?
1. Hashtable
2. HashSet
3. TreeMap
R
4. ArrayList
KA
Answer:
R
1. Hashtable
SA
A
R
IT
R
-A
01
02
30
52
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Using the Deque Interface
The Deque interface allows you to create a collection of objects in which the objects can be inserted or
deleted from both ends. Deque is the short form for the double-ended queue. The Deque interface extends
the Queue interface that provides the collection in which objects are inserted at the end and deleted from the
beginning. The Queue interface mainly works on the First In First Out (FIFO) algorithm. The following
figure shows the class hierarchy of the java.util package that implements the Deque interface.
R
KA
R
SA
A
R
IT
R
The preceding figure shows that the java.util package contains the ArrayDeque class and the
Collection, Queue, and Deque interfaces. The ArrayDeque class implements the Deque interface that is
01
The ArrayDeque class provides an implementation of the Deque interface that enables you to create a
00
resizable array, which allows insertion and deletion from both the ends. However, the methods of the
ArrayDeque class are not synchronized, which means more than one thread at a given time can access it in a
19
multithreaded environment.
R
The ArrayDeque class provides various constructors that can be used to create an instance.
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
The following table lists the commonly used constructors of the ArrayDeque class.
Constructor Description
R
The Constructors of the ArrayDeque Class
KA
The following table lists the commonly used methods of the ArrayDeque class.
R
SA
Method Description
boolean add(E e)
A
Is used to add the specified object at the end of
R
ArrayDeque.
IT
void addFirst(E e) Is used to add the specified object as the first
R
element in ArrayDeque.
-A
element in ArrayDeque.
02
ArrayDeque.
52
ArrayDeque.
19
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Consider the following code to add and remove the objects to/ from an ArrayDeque collection:
import java.util.ArrayDeque;
R
System.out.println("Size of ArrayDeque is: " + obj.size());
KA
obj.add(dobj1);
R
obj.add(dobj2);
SA
System.out.println("\nArrayDeque after adding the objects: " + obj);
System.out.println("Size of ArrayDeque after adding objects: " +
obj.size());
A
obj.addFirst(dobj3);
R
IT
obj.addLast(dobj4);
R
obj.removeFirst();
30
}
}
19
ArrayDeque after adding the objects at first and last: [9.5, 7.5, 8.5, 10.5]
Size of ArrayDeque after adding objects at first and last: 4
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
In the preceding code, the ArrayDeque object contains a collection of the Double objects. The add()
method of the ArrayDeque class is used to add the Double objects to the Deque object. Two objects are
added, one at the beginning and the other at the end of the queue. Further, an object is removed using the
remove() method, and the removeFirst() method is used to remove the element stored at the first
position.
R
KA
R
SA
A
R
IT
R
-A
01
02
30
52
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Implementing Sorting
Consider a scenario of Address Book, which contains the contact details, such as name, contact number, and
address. Now, you need to create a list of contacts living in Asia. In addition, you need to ensure that the list
should have the flexibility to add or remove any number of contacts. For this, you have decided to create a
collection of contacts. Thereafter, you need to sort the list according to the contact name. For this, Java
provides the following interfaces to sort the objects in a collection:
The Comparable interface
The Comparator interface
The Comparable and Comparator interfaces provide their own methods to achieve the sorting on the
R
collection. However, the Comparable and Comparator interfaces are used with the sort() method of the
KA
Collections and Arrays classes to sort the collection of objects.
R
SA
Using the Comparable Interface
The Comparable interface is defined in the java.lang package and is used to sort and compare a
A
collection of objects. This interface provides the compareTo() method that compares the references of the
R
objects. The compareTo() method returns a value of the int type with the following characteristics:
IT
Negative: If the current object is less than the object being compared
R
Positive: If the current object is greater than the object being compared
01
Consider the example where you want to store the name and marks of students. Thereafter, you want to sort
02
the details of each student based on marks. For this, you have decided to create the Student class, as shown
in the following code:
30
{
private String name;
00
this.name = nm;
this.marks = mk;
}
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
public void setName(String name) {
this.name = name;
}
public int compareTo(Object obj)
{
Student s = (Student) obj;
R
}
KA
public String toString()
{
R
StringBuffer buffer = new StringBuffer();
SA
buffer.append("Name: "+ name +"\n");
buffer.append("Marks: " + marks + "\n");
return buffer.toString();
A
} R
}
IT
In the preceding code, the Student class is created, which overrides the compareTo() method of the
R
Comparable interface. The compareTo() method compares the Student object on the basis of marks. In
-A
addition, the toString() method of the Object class is overridden so that the name and marks of the
01
student are displayed when the object of the Student class is used inside the println() method.
02
Thereafter, you can use the following code to create the ComparableDemo class:
30
import java.util.ArrayList;
import java.util.Collections;
52
import java.util.ListIterator;
00
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
ListIterator li = obj.listIterator();
while(li.hasNext())
{
System.out.println(li.next());
}
Collections.sort(obj);
R
}
KA
}
}
R
Once the preceding code is executed, the following output is displayed:
SA
Student details after sorting are:
Name: Joe
A
Marks: 78 R
Name: Alex
IT
Marks: 88
R
Name: Bob
-A
Marks: 90
01
In the preceding code, the ComparableDemo class is created that creates an array list of three Student
objects by adding the objects through the add() method. In addition, the array list is sorted using the
02
You have learned that the Comparable interface is used to sort and compare a collection of objects.
19
However, by using this interface, you cannot define the logic for multiple sorting. For example, in the
previous scenario, you want to create a sorting logic based on the student marks and names. For this, you can
R
use the Comparator interface that is defined in the java.util package. This interface provides the
compare() method that is used to compare two objects in a collection. The compare() method returns the
value of int type with the following characteristics:
Negative: If the current object is less than the object being compared
Zero: If the current object is equal to the object being compared
Positive: If the current object is greater than the object being compared
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Consider the following code to define the Student class:
R
return marks;
KA
}
public String getName() {
R
return name;
}
SA
public void setName(String name) {
this.name = name;
}
A
public String toString()
R
IT
{
StringBuffer buffer = new StringBuffer();
R
}
02
}
30
In the preceding code, name and marks are the attributes of the Student class. In addition, the setter and
getter methods for the attributes are defined. Further, the toString() method of the Object class is
52
overridden.
00
Consider the following code that defines a sorting logic based on the marks of a student:
19
import java.util.Comparator;
public class MarkCompare implements Comparator{
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
In the preceding code, the compare() method of the Comparator interface is overridden and the logic to
sort the student objects based on the student marks is defined.
Consider the following code to define a sorting logic based on the names of students:
import java.util.Comparator;
public class NameCompare implements Comparator{
public int compare(Object a, Object b)
{
Student x = (Student) a;
Student y = (Student) b;
return x.getName().compareTo(y.getName());
}
}
R
In the preceding code, the compare() method of the Comparator interface is overridden and the logic to
KA
sort student objects based on the student names is defined. Because the name of the students are the String
objects, the compare() method of the String class is used to implement the sorting logic.
R
SA
Thereafter, you can use the following code to create a ComparatorDemo class:
import java.util.ArrayList;
A
import java.util.Collections; R
import java.util.ListIterator;
IT
public class ComparatorDemo
R
{
-A
obj.add(s2);
obj.add(s3);
00
ListIterator li = obj.listIterator();
R
while(li.hasNext())
{
System.out.println(li.next());
}
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Collections.sort(obj, new NameCompare());
R
Student details are:
Name: Alex
KA
Marks: 88
R
Name: Bob
SA
Marks: 90
Name: Joe
A
Marks: 78 R
Mark wise sort:
IT
Name: Joe
R
Marks: 78
-A
Name: Alex
01
Marks: 88
02
Name: Bob
Marks: 90
30
Name: Alex
Marks: 88
00
Name: Bob
19
Marks: 90
R
Name: Joe
Marks: 78
In the preceding code, the ComparatorDemo class is created that creates an array list of three Student
objects by adding the objects through the add() method. In addition, the array list is sorted using the
sort() method of the Collections class.
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Practice Questions
1. Which one of the following classes implements the List interface?
a. HashSet
b. TreeSet
c. Hashtable
d. Vector
2. Which one of the following classes is inherited from the Dictionary class?
R
a. HashSet
KA
b. TreeSet
c. Hashtable
R
d.
SA
HashMap
3. Which one of the following interfaces enables you to traverse the list of objects?
a. Iterator
A
R
b. List
IT
c. Collection
R
d. Comparable
-A
4. Which one of the following methods is used to add the objects in TreeMap?
01
a. put()
02
b. add()
30
c. addObject()
52
d. putObject()
00
5. Which one of the following interfaces is used to create a collection of unique objects?
a. Set
19
b. Map
R
c. Deque
d. List
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Summary
In this chapter, you learned that:
The Set interface is used to create a collection of unique objects.
The package, java.util, provides the Iterator interface to traverse through the set collection.
The HashSet class provides the implementation of the Set interface that enables you to create a set in
which insertion is faster because it does not sort the elements.
The TreeSet class provides the implementation of the Set interface that enables you to create a sorted
set of objects.
The List interface is used to create an ordered collection of objects, which can contain duplicate
R
objects.
KA
The package, java.util, provides the ListIterator interface to traverse through the list collection.
R
The ArrayList class provides the implementation of the List interface. The ArrayList class enables
SA
you to create a resizable array.
The LinkedList class provides the implementation of the List interface. The LinkedList class
enables you to create a doubly-linked list.
LinkedList can be traversed in the forward or backward direction.
A
R
The Vector class is similar to the ArrayList and LinkedList classes.
IT
The methods of the Vector class are synchronized, which means that only one thread at a given time
R
can access it in a multithreaded environment.
-A
The methods of the ArrayList and LinkedList classes are not synchronized.
01
The Map interface enables you to create a collection with key-value pair objects.
02
The Map interface allows duplicate value objects but the key object must be unique.
30
The HashMap class enables you to create a collection in which a value is accessible using the key.
HashMap stores objects in an unordered form.
52
The TreeMap class enables you to create a collection of objects in the sorted order with unique keys.
00
The Hashtable class enables you to create an unordered collection of objects, which cannot contain the
null objects.
19
The methods of the Hashtable class are synchronized, which means that only one thread at a given
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Java provides the following interfaces to sort the objects in a collection:
The Comparable interface
The Comparator interface
The Comparable interface is defined in the java.lang package and is used to sort and compare a
collection of objects. This interface provides the compareTo() method that compares the references of
the objects.
The Comparator interface is defined in the java.util package. This interface provides the
compare() method that is used to compare two objects in a collection.
R
KA
R
SA
A
R
IT
R
-A
01
02
30
52
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
R
KA
R
SA
A
R
IT
R
-A
01
02
30
52
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Most computer games use graphics and sounds. The graphics, score, and audio effects are presented
simultaneously. Imagine a computer game where you first see the screen changing, then you see your scores
that are being updated, and finally, you hear the sound effects. In order to appreciate and enjoy a game, all
these elements need to be processed simultaneously. In other words, the program should be able to efficiently
perform three tasks simultaneously. In Java, you can achieve the preceding functionality by making use of
threads. The game can be divided into three subunits that can be executed in parallel by using individual
threads.
This chapter discusses how to create multithreaded applications in Java. In addition, it discusses about the
thread priorities.
R
Objectives
KA
In this chapter, you will learn to:
R
Use threads in Java
SA
Create threads
A
R
IT
R
-A
01
02
30
52
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Using Threads in Java
A thread can be defined as a single sequential flow of control within a program. It is a sequence of
instructions that is executed to define a unique flow of control. For example, a Central Processing Unit
(CPU) performs various processes simultaneously, such as writing and printing a document, installing
software, and displaying the date and time. All these processes are handled by separate threads. An
application comprises one or more processes that can be performed simultaneously. Further, each process is
broken into small chunks known as tasks. Each thread is assigned a unique task to perform, independently.
For example, a text editor is an application that allows you to perform two tasks, such as write to a document
and print a document, simultaneously.
Further, you can implement multithreading in an application to achieve an efficient performance and utilize
R
the CPU processing capabilities. In order to implement multithreading, Java provides the Thread class. In
KA
order to work with threads, you need to first identify their life cycle.
R
SA
The Basic Concept of Multithreading
A single-threaded application can perform only one task at a time. The following figure shows a
single-threaded application.
A
R
IT
R
-A
01
A Single-threaded Application
A single-threaded application needs to wait for one task to complete before another can start. As a result, the
02
efficiency of the application is hampered. On the other hand, you can apply multithreading when there is a
30
the application. Every application has at least one thread and you can create more threads, if required. The
following figure shows a multi-threaded application.
00
19
R
A Multi-threaded Application
The microprocessor allocates the memory to the processes that are executed by an application and each
process occupies its own address space or memory. However, all the threads in a process occupy the same
address space.
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Advantages and Disadvantages of Multithreading
Most of the computers today utilize software and hardware, such as operating system and multiple processors
that support multithreading. Therefore, to achieve efficiency and ensure an optimized performance, most of
the applications utilize multhreading. However, there are certain advantages and disadvantages of using
multithreading that can be identified. The various advantages of multithreading are:
Improved performance: Provides improvement in the performance of the processor by the
simultaneous execution of computation and Input/Output (I/O) operations.
Minimized system resource usage: Minimizes the use of system resources by using threads, which
share the same address space and belong to the same process.
Program structure simplification: Simplifies the structure of complex applications, such as multimedia
R
applications. Subprograms can be written for each activity that makes a complex program easy to design
KA
and code.
R
The various disadvantages of multithreading are:
SA
Race condition: When two or more threads simultaneously access the same variable and at least one
thread tries to write a value to the variable, it is called the race condition. This condition is caused when
synchronization between the two threads is not implemented. For example, in a word processor program,
A
there are two threads, ThreadA and ThreadB. ThreadA wants to read a file, and at the same time,
R
ThreadB wants to write to a file. If ThreadA reads the value before ThreadB performs a write operation,
IT
ThreadA will fail to receive the updated value from the file. Such a condition is known as a race
condition.
R
Deadlock condition: The deadlock condition arises in a computer system when two threads wait for
-A
each other to complete the operations before performing the individual action. As a result, the two
01
threads are locked and the program fails. For example, consider two threads, ThreadA and ThreadB.
ThreadA is waiting for a lock to be released by ThreadB, and ThreadB is also waiting for the lock to be
02
Lock starvation: Lock starvation occurs when the execution of a thread is postponed because of its low
priority. JRE executes threads based on their priority because the CPU can execute only one thread at a
52
time. The thread with a higher priority is executed before the thread with a lower priority, and therefore,
there is a possibility that the execution of the thread that has a lower priority is always postponed.
00
19
The java.lang.Thread class is used to construct and access the individual threads in a multi-threaded
application. You can create a multi-threaded application by using the Thread class or the Runnable
interface.
The Thread class contains various methods that can be used to work with a thread, such as setting and
checking the properties of a thread, causing a thread to wait, and being interrupted or destroyed. You can
make the classes run in separate threads by extending the Thread class.
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Some of the methods defined in the Thread class are:
int getPriority(): Returns the priority of a thread.
boolean isAlive(): Determines whether a thread is running.
static void sleep(long milliseconds): Causes the thread execution to pause for a period of
time as specified by the value of milliseconds.
String getName(): Returns the name of a thread.
void start(): Starts a thread execution by calling the run() method.
static Thread currentThread(): Returns a reference to the thread object that is currently
executing.
boolean isAlive(): Is used to check the existence of a thread. This method returns true if the
R
thread is running, and returns false if the thread is new or gets terminated.
KA
public final void join(): Allows a thread to wait until the thread, on which it is called,
terminates.
R
void interrupt(): Is used to interrupt the execution of a thread.
SA
static boolean interrupted(): Is used to determine if the current thread has been interrupted by
another thread.
You can use the following code to understand the usage of the methods in the Thread class:
A
R
IT
class MainThreadDemo
{
R
{
Thread t= Thread.currentThread();
01
+ t);
System.out.println(" The current Thread is going to sleep for
52
10 seconds");
try
00
{
t.sleep(10000);
19
}
catch(InterruptedException e)
R
{
System.out.println("Main thread interrupted");
}
System.out.println(" After 10 seconds...........the current
Thread is exiting now.");
}
}
Once the preceding code is executed, the following output is displayed:
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
In the preceding code, the first thread to be executed is the main thread. It is created automatically when a
Java program is executed. In the main program, a reference to the current thread is obtained by calling the
currentThread() method and its reference is stored in the reference variable, t. The setName() method
is called to set the name of the thread, and the information about the thread is displayed. The main thread is
then made to sleep for 10 seconds by using the sleep() method, and after 10 seconds, the thread terminates.
The sleep() method throws the InterruptedException exception whenever another thread interrupts
the sleeping thread.
R
New
KA
Runnable
Not Runnable
R
SA
Terminated or Dead
The following figure shows the life cycle of a thread.
A
R
IT
R
-A
01
02
30
52
00
19
R
In the preceding code snippet, a new thread is created. This new thread is an empty object of the Thread
class, and no system resources, such as memory, are allocated to it. You have to invoke the start() method
to start the thread.
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
The following code snippet shows how to start a thread:
newThread.start();
R
KA
The Not Runnable Thread State
A thread is in the not runnable state if it is:
R
Sleeping: A thread is put into the sleeping mode by calling the sleep() method. A sleeping thread
SA
continues with its execution after the specified time of sleep has elapsed.
Waiting: A thread can be made to wait for some specified condition that needs to be satisfied by calling
A
the wait() method of the Object class. The thread can be issued a notification of the status of the
R
condition by invoking the notify() or notifyAll() method of the Object class.
IT
Being blocked by another thread: If blocked by an I/O operation, a thread enters the not runnable
R
state.
-A
A thread enters the dead state once the statements in the run() method have executed. Assigning a null
02
value to a thread object also changes the state of the thread to dead. The isAlive() method of the Thread
class is used to determine whether a thread is alive or not. You cannot restart a dead thread. In addition, a
30
thread can be killed by stopping its execution with the help of the stop() method.
52
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Creating Threads
Consider a scenario of a jumbled up word game where you need to implement a timer in the game. The timer
will be used to provide a duration of 60 seconds within which a player has to find the correct word
corresponding to a jumbled up word. Further, the timer will be displayed on the game screen when a player is
playing the game. When the timer reaches 0, the “Time Up!!!” message will be displayed to the player and
the game will stop.
In order to implement the preceding functionalities, you can create a thread. This can be done by instantiating
an object of the Thread class. You can create a thread in a Java application by using the following
approaches:
By extending the Thread class
R
KA
By implementing the Runnable interface
Further, you can also create multiple threads in an application by using the preceding approaches and set
R
their priorities to determine their execution sequence in the JRE.
SA
Creating a Thread by Extending the Thread Class
A
R
You can create threads by extending the Thread class. You need to specify the task to be performed by a
IT
thread in the overridden run() method. You can use the following code to create a thread to implement the
R
import java.awt.Color;
01
import java.awt.Font;
import javax.swing.*;
02
30
JLabel l;
JFrame fr;
00
buildGUI();
}
R
void display() {
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
}
JOptionPane.showMessageDialog(fr, "Time Up !!!!");
tf.setText("");
tf.setEnabled(false);
}
R
tf.setBackground(Color.BLACK);
KA
p.setBackground(Color.blue);
fr.add(p);
p.add(tf);
R
p.add(l);
SA
fr.setVisible(true);
fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
fr.setSize(300, 100);
A
fr.setResizable(false); R
display();
}
IT
R
}
}
02
The Output
Note
The time in the preceding figure may vary.
In the preceding code, the CountdownTimer class extends the Thread class. A new instance of the
CountdownTimer class is created in the main() method. The start() method begins the execution of a
thread by calling the run() method that provides the implementation of the timer.
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Creating a Thread by Implementing the Runnable Interface
Consider a scenario where you need to implement threads in a Java application and also extend another class
to use its functionality, such as JFrame. Because Java does not support multiple inheritance, it provides the
Runnable interface to solve this problem. The Runnable interface only consists of the run() method,
which is executed when the thread is started.
When a program needs to inherit from a class other than the Thread class, you need to implement the
Runnable interface to implement threads. The signature of the run() method is:
The run() method contains the code that the new thread will execute. When the run() method is called,
R
another thread starts executing concurrently with the main thread in the program.
KA
The class that implements the Runnable interface is used to create an instance of the Thread class. The new
R
thread object starts by calling the start() method. You can use the following code to create a thread by
SA
implementing the Runnable interface for implementing the timer functionality:
import java.awt.Color;
A
import java.awt.Font; R
import javax.swing.*;
IT
public class CountdownTimer implements Runnable {
R
JTextField tf;
-A
JLabel l;
JFrame fr;
01
buildGUI();
}
30
void display() {
52
{
try {
19
Thread.sleep(1000);
String s = Integer.toString(i);
R
}
JOptionPane.showMessageDialog(fr, "Time Up !!!!");
tf.setText("");
tf.setEnabled(false);
}
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
public void buildGUI() {
fr = new JFrame("Countown Timer");
JPanel p = new JPanel();
l = new JLabel("");
tf = new JTextField(15);
tf.setEnabled(false);
Font f = new Font("Verdana", 0, 18);
tf.setFont(f);
tf.setBackground(Color.BLACK);
p.setBackground(Color.blue);
fr.add(p);
p.add(tf);
p.add(l);
fr.setVisible(true);
R
fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
KA
fr.setSize(300, 100);
fr.setResizable(false);
display();
R
}
SA
public static void main(String args[]) {
CountdownTimer obj = new CountdownTimer();
A
Thread CountdownThread = new Thread(obj); R //Initialize thread
CountdownThread.start();
}
IT
}
R
The Output
00
19
Note
The time in the preceding figure may vary.
R
In the preceding code, the CountdownTimer class implements the Runnable interface. In the main()
method, an object of the CountdownTimer class is created and the object is passed as a parameter to the
constructor of the Thread class. The preceding object represents a runnable task. The start() method
begins the execution of a thread by calling the run() method, which provides the implementation of the
timer.
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Creating Multiple Threads
Suppose you need to develop a car racing game where multiple objects, such as obstacles, need to move
across the frame, simultaneously. For this, you need to create multiple threads where each thread represents
an obstacle. You can create multiple threads in a program either by implementing the Runnable interface or
extending the Thread class.
For the preceding scenario, you can use the following code to create multiple threads by using the Thread
class:
import java.awt.Color;
import java.util.Random;
R
import javax.swing.*;
KA
public class Race extends Thread{
String ThreadName;
R
JLabel l;
SA
JPanel l1,l2,l3;
JFrame fr;
A
public Race() R
{
buildGUI();
IT
}
R
public Race(String s)
-A
{
super(s);
01
}
02
if(Thread.currentThread().getName().equals("ObstacleA"))
52
{
runObstacleA();
00
}
if(Thread.currentThread().getName().equals("ObstacleB"))
19
{
runObstacleB();
R
}
if(Thread.currentThread().getName().equals("ObstacleC"))
{
runObstacleC();
}
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
for(int i=-10;i<400;i++)
{
}
catch(Exception e)
{
System.out.println(e);
}
}
runObstacleC();
R
}
KA
public void runObstacleB()
{
R
Random ran = new Random();
SA
int r = ran.nextInt(180);
for(int i=-10;i<400;i++)
A
{ R
l2.setBounds(i, r, 20, 20);
try {
IT
Thread.sleep(11);
R
-A
}
catch(Exception e)
01
{
System.out.println(e);
02
}
}
30
runObstacleA();
}
52
{
Random ran = new Random();
19
int m = ran.nextInt(10);
R
for(int i=-10;i<400;i++)
{
l3.setBounds(i, m, 20, 20);
try {
Thread.sleep(10);
}
catch(Exception e)
{
System.out.println(e);
}
}
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
runObstacleB();
}
public void buildGUI()
{
fr = new JFrame("Moving objects");
fr.setVisible(true);
fr.setSize(400,200);
fr.setLayout(null);
l = new JLabel("");
l.setBounds(10,10,400,20);
fr.add(l);
l1 = new JPanel();
R
l1.setSize(20, 20);
KA
l1.setBackground(Color.red);
l1.setBounds(10,40,20,20);
fr.add(l1);
R
l2 = new JPanel();
SA
l2.setSize(20, 20);
l2.setBackground(Color.blue);
l2.setBounds(10,80,20,20);
A
fr.add(l2); R
l3 = new JPanel();
IT
l3.setSize(20, 20);
R
l3.setBackground(Color.black);
-A
l3.setBounds(10,120,20,20);
fr.add(l3);
01
}
02
{
Race obj = new Race();
52
Obstacle1.setName("ObstacleA");
Obstacle2.setName("ObstacleB");
R
Obstacle3.setName("ObstacleC");
Obstacle1.start();
Obstacle2.start();
Obstacle3.start();
}
}
In the preceding code, three thread references, Obstacle1, Obstacle2, and Obstacle3 are created and the
object obj of the Race class is passed as parameter. Then, Obstacle1, Obstacle2, and Obstacle3 are
given the names, ObstacleA, ObstacleB, and ObstacleC, respectively. These obstacles will appear at
random positions.
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
You can also use the following code to create multiple threads by using the Runnable interface:
import java.awt.Color;
import java.util.Random;
import javax.swing.*;
String ThreadName;
JLabel l;
JPanel l1,l2,l3;
JFrame fr;
public Race()
R
{
KA
buildGUI();
}
R
public void run()
SA
{
if(Thread.currentThread().getName().equals("ObstacleA"))
{
runObstacleA();
A
}
R
IT
if(Thread.currentThread().getName().equals("ObstacleB"))
{
R
runObstacleB();
-A
}
if(Thread.currentThread().getName().equals("ObstacleC"))
01
{
runObstacleC();
02
}
30
}
52
for(int i=-10;i<400;i++)
R
}
catch(Exception e)
{
System.out.println(e);
}
}
runObstacleC();
}
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
public void runObstacleB()
{
Random ran = new Random();
int r = ran.nextInt(180);
for(int i=-10;i<400;i++)
{
l2.setBounds(i, r, 20, 20);
try {
Thread.sleep(11);
}
catch(Exception e)
{
R
System.out.println(e);
KA
}
}
runObstacleA();
R
}
SA
public void runObstacleC()
{
A
Random ran = new Random(); R
int m = ran.nextInt(10);
IT
for(int i=-10;i<400;i++)
R
{
-A
Thread.sleep(10);
02
}
catch(Exception e)
30
{
System.out.println(e);
52
}
}
00
runObstacleB();
}
19
{
fr = new JFrame("Moving objects");
fr.setVisible(true);
fr.setSize(400,200);
fr.setLayout(null);
l = new JLabel("");
l.setBounds(10,10,400,20);
fr.add(l);
l1 = new JPanel();
l1.setSize(20, 20);
l1.setBackground(Color.red);
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
l1.setBounds(10,40,20,20);
fr.add(l1);
l2 = new JPanel();
l2.setSize(20, 20);
l2.setBackground(Color.blue);
l2.setBounds(10,80,20,20);
fr.add(l2);
l3 = new JPanel();
l3.setSize(20, 20);
l3.setBackground(Color.black);
l3.setBounds(10,120,20,20);
fr.add(l3);
R
KA
}
R
{
SA
Race obj = new Race();
Thread Obstacle1 = new Thread(obj);
Thread Obstacle2 = new Thread(obj);
A
Thread Obstacle3 = new Thread(obj); R
Obstacle1.setName("ObstacleA");
IT
Obstacle2.setName("ObstacleB");
R
Obstacle3.setName("ObstacleC");
-A
Obstacle1.start();
Obstacle2.start();
01
Obstacle3.start();
}
02
}
30
In the preceding code, three threads, ObstacleA, ObstacleB, and ObstacleC, share the memory of the
CPU. These obstacles will appear at random positions on the frame and move across the frame. Once the
52
The Output
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Sometimes, in a multithreaded program, there may be a requirement to ensure that the execution of the main
thread finishes after all the other threads have executed. For this, they will need to know whether a thread has
finished its execution or else they can join the execution of a thread with the main() method. This can be
determined by using the isAlive() method and the join() method.
boolean isAlive()
In the preceding signature, the isAlive() method returns true if the thread is running, and returns false
R
if the thread is new or gets terminated. The thread can be in a runnable or not runnable state if the
KA
isAlive() method returns true. The following code uses the isAlive() method:
R
class NewThreadClass implements Runnable
{
SA
Thread t;
NewThreadClass()
{
t = new Thread(this,"ChildThread" );
A
System.out.println("Thread created: " + t);
R
IT
t.start();
}
R
{
try
01
{
for(int i=1;i<=5;i++)
02
{
System.out.println(t + "loop :" + i);
30
Thread.sleep(100);
}
52
}
catch( InterruptedException obj)
00
{
System.out.println("Thread :" + t + "interrupted");
19
}
R
}
}
class IsAliveDemo
{
public static void main(String args[])
{
NewThreadClass obj = new NewThreadClass();
System.out.println(obj.t + "is alive ? : " +
obj.t.isAlive());
try
{
for(int i=1;i<=5;i++)
{
System.out.println("Main Thread loop:" + i);
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Thread.sleep(200);
}
}
catch(InterruptedException e)
{
System.out.println("Main thread is interrupted");}
System.out.println(obj.t + "is alive ? : " +
obj.t.isAlive());
System.out.println("Main Thread is exiting");
}
}
Once the preceding code is executed, the following output is displayed:
R
Thread created: Thread[ChildThread,5,main]
Thread[ChildThread,5,main]is alive ? : true
KA
Main Thread loop:1
Thread[ChildThread,5,main]loop :1
R
Thread[ChildThread,5,main]loop :2
SA
Main Thread loop:2
Thread[ChildThread,5,main]loop :3
Thread[ChildThread,5,main]loop :4
A
Thread[ChildThread,5,main]loop :5
Main Thread loop:3
R
Main Thread loop:4
IT
Main Thread loop:5
R
In the preceding code, the isAlive() method is called on the thread to check whether the thread is alive or
01
dead.
02
The join() method allows a thread to wait until the thread, on which it is called, terminates. In addition, the
52
join() method enables you to specify the maximum amount of time that you need to wait for the specified
thread to terminate. The signature of the join() method is:
00
19
In the preceding signature, if another thread interrupts, the join() method throws the
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
System.out.println("Thread created: " + t);
t.start();
}
public void run()
{
try
{
for(int i=1;i<=5;i++)
{
System.out.println(t + "loop :" + i);
Thread.sleep(500);
}
}
catch( InterruptedException obj)
R
{
KA
System.out.println("Thread :" + t + "interrupted");
}
}
R
}
SA
public class JoinDemo
{
public static void main(String args[])
A
{ R
ChildThread obj = new ChildThread();
System.out.println(obj.t + "is alive ? : " +
IT
obj.t.isAlive());
R
try
-A
{
System.out.println("Main thread waiting for child thread to
01
finish");
obj.t.join();
02
}
catch(InterruptedException e)
30
{
System.out.println("Main thread is interrupted");
52
}
System.out.println(obj.t + "is alive ? : " +
00
obj.t.isAlive());
System.out.println("Main Thread is exiting");
19
}
}
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
In the preceding code, the join() method is called on the child thread and the main thread waits for the
child thread to finish its execution.
R
Defining Thread Priority
KA
Thread priorities are integers in the range of 1 to 10 that specify the priority of one thread with respect to the
priority of another thread. The execution of multiple threads on a single CPU in a specified order is called
R
scheduling.
SA
If the processor encounters another thread with a higher priority, the current thread is pushed back and the
thread with the higher priority is executed. The next thread of a lower priority starts executing if a higher
A
priority thread stops or becomes not runnable. A thread is pushed back in the queue by another thread if it is
R
waiting for an I/O operation. A thread can also be pushed back in the queue when the time for which the
IT
sleep() method was called on another higher priority thread gets over.
R
-A
In the preceding signature, the newPriority parameter specifies the new priority setting for a thread. The
52
priority levels should be within the range of two constants, MIN_PRIORITY and MAX_PRIORITY. The
MIN_PRIORITY and MAX_PRIORITY constants have the values 1 and 10, respectively. The
00
setPriority() method throws the IllegalArgumentException exception if the priority level is less
19
setPriority() method. MAX_PRIORITY is the highest priority that a thread can have. MIN_PRIORITY is
the lowest priority a thread can have, and NORM_PRIORITY is the default priority set for a thread. You can
use the following code to set the priorities of various threads:
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
public void run()
{
try
{
for(int i=1;i<=5;i++)
{
System.out.println(t + "loop :" + i);
Thread.sleep(500);
}
}
catch( InterruptedException obj)
{
System.out.println("Thread :" + t + "interrupted");}
}
R
}
KA
class PriorityDemo
{
public static void main(String args[])
R
{
SA
ChildThread obj1 = new ChildThread(Thread.NORM_PRIORITY - 2);
ChildThread obj2 = new ChildThread(Thread.NORM_PRIORITY + 2);
ChildThread obj3 = new ChildThread(Thread.NORM_PRIORITY + 3);
A
//Starting the threads with different priority
R
obj1.t.start();
IT
obj2.t.start();
R
obj3.t.start();
-A
try
{
01
obj1.t.join();
obj2.t.join();
30
obj3.t.join();
}
52
catch(InterruptedException e)
00
{
System.out.println("Main thread is interrupted");}
19
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Once the preceding code is executed, the following output is displayed:
R
Thread[ChildThread,3,main]loop :3
KA
Thread[ChildThread,7,main]loop :4
Thread[ChildThread,8,main]loop :4
R
Thread[ChildThread,3,main]loop :4
Thread[ChildThread,7,main]loop :5
SA
Thread[ChildThread,8,main]loop :5
Thread[ChildThread,3,main]loop :5
Thread[ChildThread,3,]is alive ? : false
Thread[ChildThread,7,]is alive ? : false
A
Thread[ChildThread,8,]is alive ? : false
R
IT
Main Thread is exiting
R
-A
Java
02
30
52
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Practice Questions
1. Identify the minimum value to set the thread priority.
a. 5
b. 10
c. 1
d. 15
R
KA
b. sleep()
c. syncrhonize()
R
d. alive()
SA
3. Identify the method that returns the name of a thread.
a. name()
A
b. getName()
R
IT
c. getThreadName()
R
d. currentThreadName()
-A
4. Identify the method that is used to pause the execution of a thread for a period of time.
01
a. isAlive()
02
b. sleep()
30
c. notify()
d. stop()
52
Statement B: When a thread is blocked by an I/O operation, it enters the not runnable state.
R
Which one of the following options is correct based on the preceding statements?
a. Both the statements are false.
b. Both the statements are true.
c. Statement A is true and Statement B is false.
d. Statement B is true and Statement A is false.
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Summary
In this chapter, you learned that:
A thread is defined as the path of execution of a program. It is a sequence of instructions that is executed
to define a unique flow of control.
A program that creates two or more threads is called a multi-threaded program.
The various advantages of multithreading are:
Improved performance
Minimized system resource usage
Program structure simplification
R
The various disadvantages of multithreading are:
KA
Race condition
R
Deadlock
SA
Lock starvation
The java.lang.Thread class is used to construct and access the individual threads in a multi-threaded
application.
A
The various states in the life cycle of a thread are:
R
IT
New
R
Runnable
-A
Not Runnable
01
Terminated or Dead
You can create a thread in the following ways:
02
Thread priorities are the integers in the range of 1 to 10 that specify the priority of one thread with
respect to the priority of another thread.
00
You can set the thread priority after it is created by using the setPriority() method declared in the
Thread class.
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
R
KA
R
SA
A
R
IT
R
-A
01
02
30
52
00
19
R
Implementing Thread
Synchronization and
Concurrency
CHAPTER 7
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
You have learned how to create a multi-threaded Java application. In addition, you have learned that in a
multi-threaded application, a resource can be accessed by multiple threads at a time. However, there may be
situations when you need that at a time, only one thread should access the resource. For this, Java provides
thread synchronization.
Moreover, to improve the performance of a multi-threaded application, Java supports concurrency. To
implement concurrency, a program is split into tasks, which can be executed in parallel.
This chapter focuses on implementing thread synchronization and concurrency.
Objectives
R
KA
In this chapter, you will learn to:
Implement thread synchronization
R
Implement concurrency
SA
A
R
IT
R
-A
01
02
30
52
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Implementing Thread Synchronization
In a multithreaded environment, when two threads need to share data, you must try to coordinate their
activities to ensure that one thread does not change the data used by the other thread to avoid errors. For
example, if you have two threads, one that reads a salary record from a file and another that tries to update
the salary record at the same time, there is a possibility that the thread that is reading the salary record does
not get the updated value. The following figure shows two threads accessing the data of a file at the same
time.
R
KA
R
SA
A
R
IT
R
In the preceding figure, Thread1 is updating the salary of Stella to $20,000. At the same time, another thread,
01
Thread2, is reading the salary of Stella before it is being updated. Therefore, the information read by Thread2
is faulty.
02
To avoid such situations, Java enables you to coordinate and manage the actions of multiple threads at a
30
given time by using synchronized threads and implementing communication between threads.
52
00
Synchronizing Threads
19
Consider the scenario of a banking application that allows you to access a bank account and perform
operations, such as deposit and withdraw amount. In addition, these operations can be performed by using
R
mediums, such as the Internet and Automated Teller Machine (ATM). In such a scenario, there is a
possibility that multiple operations are performed on an account simultaneously. This can lead to loss of data
or inconsistency in data. Therefore, to avoid such issues, you need to implement a mechanism using which
only a single operation can be performed on an account at a time. For this, you can apply thread
synchronization.
The synchronization of threads ensures that if two or more threads need to access a shared resource, then that
resource is used by only one thread at a time. You can implement thread synchronization by using the
following approaches:
By using the synchronized methods
By using the synchronized statement
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
The Synchronized Methods
You can synchronize a method by using the synchronized keyword. Synchronization is based on the
concept of a monitor, which is an object used as a lock. All the Java objects have a monitor and only one
thread can hold the monitor of an object at a given time. To enter an object’s monitor, you need to call a
synchronized method. The monitor controls the way in which synchronized methods access an object or
class. When a thread acquires a lock, it is said to have entered the monitor. The monitor ensures that only one
thread has access to the resources at any given time.
When a thread is within a synchronized method, all the other threads that try to call the method at the same
time have to wait. During the execution of a synchronized method, the object is locked so that no other
synchronized method can be invoked. The monitor is automatically released when the method completes its
execution. The following figure shows an example of thread synchronization.
R
KA
R
SA
A
R
IT
R
-A
01
02
In the preceding figure, Thread1 has a lock on the Salary.xls file, while updating the salary of Stella in the
file. Thread2 wants to read the salary of Stella from the Salary.xls file and is waiting for Thread1 to release
52
the lock on the file. While a thread is sleeping or waiting, it temporarily releases the lock it holds.
00
The following code snippet demonstrates how to implement synchronization for the preceding scenario by
using a synchronized method:
19
R
class EmployeeDetails
{
// Details of the employee
}
class EmployeeSalaryTransaction
{
public synchronized int processSalary()
{
// Code to process the salary
}
}
In the preceding code snippet, the processSalary() method is a synchronized method. This method
cannot be accessed by multiple threads at a time.
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
The Synchronized Statement
Synchronization among threads can also be achieved by using synchronized statements. The synchronized
statement is used where the synchronization methods are not used in a class and you do not have access to
the source code. Further, when a method contains only a small section of critical code for which
synchronization is required, then you can use the synchronized statement instead of synchronizing the entire
method. You can synchronize the access to an object of this class by placing the calls to the methods defined
by it inside a synchronized block. The following code snippet shows how to use the synchronized
block:
synchronized(obj)
{
/* statements to be synchronized*/
R
}
KA
In the preceding code snippet, obj is a reference of the object to be synchronized.
R
The following code snippet demonstrates how to implement synchronization, in case of the banking
application, by using the synchronized statement:
SA
class EmployeeDetails
{
// Details of the employee
A
R
}
IT
class EmployeeSalaryTransaction
{
R
{
synchronized(obj)
01
{
02
}
}
52
In the preceding code snippet, obj refers to an object of the EmployeeDetails class. The code to process
the salary is specified within a synchronized block to ensure that it cannot be accessed by multiple threads
00
at a time.
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
A thread may notify another thread that the task has been completed. This communication between threads is
known as inter-threaded communication. The various methods used in inter-threaded communication are:
wait(): Informs the current thread to leave its control over the monitor and wait until another thread
calls the notify() method.
notify(): Wakes up a single thread that is waiting for the monitor of the object being executed. If
multiple threads are waiting, one of them is chosen randomly.
notifyAll(): Wakes up all the threads that are waiting for the monitor of the object.
The following code shows the producer-consumer problem, but without inter-threaded communication:
class SynchronizedMethods
{
R
int d;
synchronized void getData()
KA
{
System.out.println("Got data:" + d);
R
SA
}
synchronized void putData(int d)
{
A
this.d = d;
System.out.println("Put data:" + d);
R
}
IT
}
R
SynchronizedMethods t;
01
public Producer(SynchronizedMethods t)
{
02
this.t = t;
}
30
{
System.out.println("Put Called by producer");
19
t.putData(data++);
}
R
}
}
class Consumer extends Thread
{
SynchronizedMethods t;
public Consumer(SynchronizedMethods t)
{
this.t = t;
}
public void run()
{
while(true)
{
System.out.println("Get Called by consumer");
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
t.getData();
}
}
}
public class ProducerConsumer
{
public static void main(String args[])
{
SynchronizedMethods obj1 = new SynchronizedMethods();
Producer p = new Producer(obj1);
Consumer c = new Consumer(obj1);
p.start();
c.start();
}
R
}
KA
Once executed, the preceding code runs infinitely, as shown in the following output:
R
.
SA
.
.
.
A
Put Called by producer
Put data:29670
R
Put Called by producer
IT
Put data:29671
R
Put data:29673
Put Called by producer
02
Put data:29674
Put Called by producer
30
Put data:29675
Put Called by producer
52
.
.
19
.
R
To avoid such errors, wait(), notify(), and notifyAll() methods are used. All the three methods can
be called from within the synchronized methods.
The following code shows the inter-thread communication by using the wait() and notify() methods:
class SynchronizedMethods
{
int d;
boolean flag = false;
synchronized int getData()
{
if(!flag)
{
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
try
{
wait();
}
catch(InterruptedException e)
{
System.out.println(" Exception caught");
}
}
System.out.println("Got data:" + d);
flag=false;
notify();
return d;
R
}
KA
synchronized void putData(int d)
{
R
if(flag)
SA
{
try
A
{ R
wait();
}
IT
catch(InterruptedException e)
R
{
-A
}
this.d = d;
02
flag=true;
System.out.println("Put data with value:" + d);
30
notify();
52
}
}
00
{
SynchronizedMethods t;
R
public Producer(SynchronizedMethods t)
{
this.t = t;
new Thread(this,"Producer").start();
System.out.println("Put Called by producer");
}
public void run()
{
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
t.putData(data);
}
}
}
class Consumer implements Runnable
{
SynchronizedMethods t;
public Consumer(SynchronizedMethods t)
{
this.t = t;
new Thread(this,"Consumer").start();
R
public void run()
KA
{
while(true)
R
{
SA
t.getData();
}
}
A
} R
public class InterThreadComm
{
IT
public static void main(String args[])
R
{
-A
}
}
30
Got data:1
Put data with value:2
R
Got data:2
Put data with value:3
Got data:3
Put data with value:4
Got data:4
Note
The preceding output may vary.
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Just a minute:
The ______ method is used to wake up all the threads that are waiting for the monitor
of the object.
Answer:
notifyAll()
R
KA
R
Activity 7.1: Implementing
SA
Synchronization
A
R
IT
R
-A
01
02
30
52
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Implementing Concurrency
In a multithreaded environment, it is important to implement synchronization to eliminate the interference of
threads and coordinate their activities. However, synchronization does not ensure that a multithreaded
application is utilizing the system resources efficiently. There may be a situation in an application where
multiple threads are waiting to obtain a lock on a synchronized method or code that is already locked. As a
result, the efficiency of the application is hampered. Therefore, it is important to improve the efficiency of
multithreaded applications and ensure that they are using the hardware resources of the system, such as the
processor, to their potential. For this, the Java programming language supports concurrency.
Concurrency enables Java programmers to improve the efficiency and resource utilization of their
applications by creating concurrent programs. Most computers today have more than a single processor to
R
provide a faster performance. Therefore, by applying concurrency in Java applications, the program tasks can
KA
be managed to execute simultaneously by the systems that have multiple processors. You can achieve
concurrency by dividing a program into multiple threads, where each thread has a separate task to perform.
R
This minimizes the wastage of processing time and improves the execution speed of an application.
SA
To implement concurrency, Java provides the java.util.concurrent package. This package contains the
necessary classes and interfaces that can be used to implement the different ways to achieve concurrency and
A
high performance in Java applications. R
IT
The java.util.concurrent package has the following sub packages to support concurrent programming:
01
java.util.concurrent.atomic
02
java.util.concurrent.locks
30
Consider a scenario of a multithreaded Java application that deals with updating and reading data, such as
integer values stored in variables. You want to ensure that any change made to the data is updated
00
immediately so that all the threads that access the variables get the latest value. You want to ensure that all
the updates to variables are successfully accomplished and any change made is not lost due to problems, such
19
as power outages. Moreover, you want that even in case of failures, such as starvation, the data is
R
successfully updated. For this, you can use atomic variables. Atomic variables are the single variables on
which operations, such as increment and decrement, are done in a single step. Such operations are known as
atomic operations.
An atomic operation is an operation that is performed as a single unit. In addition, an atomic operation
cannot be stopped in between by any other operations. Therefore, when multiple threads are working with an
atomic variable to perform an operation, then that operation either happens completely in a single step or
does not happen at all. The use of atomic variables improves performance as compared to synchronization
and helps in avoiding inconsistency in data. The java.util.concurrent.atomic package provides many
classes and methods that can be used to create atomic variables for performing atomic operations.
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
The following table lists the various classes of the java.util.concurrent.atomic package.
Class Description
AtomicLong
R
A long value that may be updated atomically.
KA
AtomicLongArray A long array in which elements may be updated
atomically.
R
SA
The Classes of the java.util.concurrent.atomic Package
Consider the following code that demonstrates an atomic operation of an atomic integer variable:
import java.util.concurrent.atomic.AtomicInteger;
A
R
public class AtomicVariableDemo
IT
{
R
In the preceding code, AtomicInteger named value is created with the value, 5. The get()method of the
R
AtomicInteger class is used to get the current value of the value variable. The getAndIncrement()
method is then used to atomically increment the current value of the reference variable by 1. Further, the
getAndDecrement() method is used to atomically decrement the current value by 1. The
compareAndSet() method sets the value of the value variable to 45 if its value is 39.
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
There is a possibility that the thread that has been waiting for the longest period of time never acquires the
lock. In addition, when using synchronization, if an exception is raised while a thread is executing the critical
section, then the lock may never be released. This can degrade the performance of an application. In order to
overcome the preceding drawbacks, Java provides the ReentrantLock class in the
java.util.concurrent.locks package. This class implements the Lock interface. A reentrant lock is
used for mutual locking amongst threads. A reentrant lock can be acquired by the same thread any number of
times.
In addition, this class provides useful methods that can be used to perform locking in a flexible and more
productive manner by using a lock. A lock is a tool that is used for controlling access to a shared resource.
The following table lists the constructors of the ReentrantLock class.
R
Constructor Description
KA
ReentrantLock() Is used to create an instance of the
R
ReentrantLock class.
SA
ReentrantLock(boolean fairness) Is used to create an instance of the
ReentrantLock class and set the fairness. The
A
fairness option when set to true ensures that the lock
R
is given to the longest waiting thread in the queue of
IT
waiting threads.
R
The following table lists some of the methods of the ReentrantLock class.
01
02
Method Description
30
void lock() This method is used to acquire a lock. Further, this method cannot
52
be interrupted.
00
boolean tryLock() This method is used to acquire a lock only if it is available. If the
19
boolean tryLock(long This method is used to acquire a lock only if it is available in the
time, TimeUnit unit) specified time period. If the lock is available, it returns with a
true value, else it returns with a false value.
boolean isFair() This method is used to return true if the fairness is set to true.
boolean isLocked() This method is used to query if the lock is currently held by any
thread.
The Methods of the ReentrantLock Class
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Consider the following code that shows how to implement a reentrant lock:
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ReentrantLockImplementation implements Runnable {
final Lock lock = new ReentrantLock();
String name;
Thread t;
R
t.start();
KA
}
R
public static void main(String args[]) {
ReentrantLockImplementation obj = new ReentrantLockImplementation();
SA
obj.createThreads("Thread 1");
obj.createThreads("Thread 2");
obj.createThreads("Thread 3");
}
A
R
IT
public void run() {
do {
R
try {
-A
if (lock.tryLock(400, TimeUnit.MILLISECONDS)) {
try {
01
System.out.println(Thread.currentThread().getName()+"
acquired the lock. "
02
);
Thread.sleep(1000);
30
} finally {
lock.unlock();
52
System.out.println(Thread.currentThread().getName()+"
released the lock. "
00
);
}
19
break;
R
}
else
{
System.out.println( Thread.currentThread().getName() + "
could not acquire the lock. Need to try for the lock again.");
}
}
catch (InterruptedException e)
{
System.out.println(e);
}
} while (true);
}
}
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Once the preceding code is executed, the following output is displayed:
R
Thread 2 acquired the lock.
KA
Thread 3 released the lock.
Thread 2 released the lock.
R
SA
Note
The preceding output may change as the order of thread execution cannot be predicted.
A
R
IT
In the preceding code, three threads namely Thread 1, Thread 2, and Thread 3 are created. Also, a new
R
ReentrantLock named lock is created. Then, on executing the run() method, a thread acquires a lock in
-A
the try block. Further, the lock.tryLock(400, TimeUnit.MILLISECONDS) statement is used to check
01
if a lock is available in the time period of 400 milliseconds. If it is, then it is acquired, else, the threads need
to try again for the lock. Once the task is complete, a thread releases the lock in the finally block, which
02
ensures that the lock is finally released when a thread finishes its execution.
30
In addition, to implement separate locks for the read and writes operations, respectively, Java provides the
ReentrantReadWriteLock class in the java.util.concurrent.locks package. This class allows you
52
to have separate read and write versions of the same lock in such a way that only one thread is able to write
00
and other threads are able to read at a given time. The ReentrantReadWriteLock class implements the
ReadWriteLock interface.
19
Constructor Description
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
The following table lists some of the methods of the ReentrantReadWriteLock class.
Method Description
Lock readLock() This method is used to return the lock that is used for reading.
Lock writeLock() This method is used to return the lock that is used for writing.
R
import java.util.Random;
import java.util.concurrent.locks.ReentrantReadWriteLock;
KA
class ThreadLock extends Thread {
R
SA
private static final ReentrantReadWriteLock rwlock = new
ReentrantReadWriteLock();
@Override
A
public void run()
{
R
try {
IT
readData();
R
sleep(2000);
writeData();
-A
{
System.out.println(e);
02
}
}
30
try {
rwlock.readLock().lock();
00
System.out.println(Thread.currentThread().getName() + " is
reading and the value is 5");
19
} finally {
System.out.println(Thread.currentThread().getName() + " is
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
System.out.println("The new value is: " + (5 + n));
}
finally
{
System.out.println(Thread.currentThread().getName() + " is
releasing the lock and exiting after writing.");
rwlock.writeLock().unlock();
}
}
}
R
ThreadLock obj2 = new ThreadLock();
KA
obj.start();
obj2.start();
}
R
}
SA
In the preceding code, a new ReentrantReadWriteLock lock named rwlock is created in the
ThreadLock class that extends the Thread class. A method named readData() is created in the same
A
class. When a thread begins executing this method, it obtains a read lock in the try block and releases it
R
after performing its task in the finally block. The readData() method can be accessed by multiple
IT
threads for reading. Further, when a thread enters the writeData() method, it obtains a write lock and only
the thread that has acquired the write lock can enter the critical section of the writeData() method. Finally,
R
after performing the task, the thread releases the write lock so that it can be acquired by another waiting
-A
thread.
01
Note
The preceding output may change as the order of thread execution cannot be predicted.
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Identifying Concurrency Synchronizers
Consider a scenario of a multithreaded application where you want to achieve coordination and concurrency
amongst the threads of the application to minimize data inconsistency and errors. For example, you want the
multiple threads of your application to exchange data or you want one or more threads to execute after a
specific operation has been performed by another thread in the application. In such a scenario, you can use
the synchronizer classes provided in the java.util.concurrent package. The following synchronizer
classes are available:
Semaphore
CountdownLatch
CyclicBarrier
R
Phaser
KA
Exchanger
R
SA
Semaphore
A semaphore is a lock with an internal counter. It is used to restrict access to shared resources by multiple
threads at the same time. In addition, a semaphore can also be used to restrict the number of threads that can
A
access a shared resource. Semaphores contain permits that should be acquired by a thread that wants access
R
to a shared resource. Once the thread completes its work with the shared resource, the permit must be
IT
released by the thread. The acquire() and the release() methods are used to acquire and release a lock,
R
respectively. If a permit is not available for a thread, then the requesting thread must wait until a permit is
-A
given to requesting threads. When the fairness is set to true, then the semaphore gives permits in the order
they were requested by the threads. For example, the thread that requested the permit first is given the permit.
02
When fairness is set to false, a permit can be given to any thread that is waiting to acquire the permit. The
30
use of a semaphore with fairness set to true helps in avoiding the starvation problem amongst threads in a
concurrent environment.
52
00
CountDownLatch
This synchronizer class is useful in a situation where one or more threads need to wait until a set of
19
operations or events is performed. Further, it is also useful when there is a need to synchronize multiple
R
threads with the execution of a set of events or operations. When this synchronizer class is implemented, it is
initialized with an integer number. This number is a counter value that represents the number of operations
after which the waiting threads will start executing. This counter value can be retrieved by using the
getCount() method. A thread that needs to wait for the completion of the preceding operations uses a
method named await(). This method puts that thread to sleep until the operations are completed. When an
operation completes, another method named countDown() is used to reduce the number of count by one.
Finally, when the countdown reaches zero, all the sleeping threads are released.
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
CyclicBarrier
This synchronizer class is useful in a situation where multiple threads are required to wait at a predefined
execution point that can be known as a barrier. For this, the await() method is used. This method is used by
threads to wait for each other to reach the barrier. Once all the threads reach at the same barrier, then a task is
performed. When this class is instantiated, you can specify the number of threads that will be participating to
reach an execution point. The number of threads specified cannot vary over time. Additionally, during
instantiation, the task to be performed, once the wait state is reached, can be specified. Then, the threads can
complete their part and reach the same execution wait point. When the execution wait point is reached by all
the threads, they can start working on the next part of their task.
Phaser
R
This synchronizer class is useful in a situation where independent threads need to work in phases or steps in
KA
order to complete a task. This class provides a similar functionality as provided by the CyclicBarrier
class. However, by using this class, the number of threads that require to be synchronized by using a Phaser
R
can be changed dynamically. To implement synchronization by using the Phaser class, an object of Phaser
SA
is created. A Phaser object can also be created with or without any threads. Further, the register()
method is used to register each thread and the arriveAndDeregister() method is used to deregister a
registered thread. The bulkRegister() method can also be used to register multiple threads in bulk. The
A
arriveAndAwaitAdvance() method can be used to notify each thread to wait until the other threads reach
R
the execution point. Once all the threads reach the execution point, the task to be executed can be specified
IT
by using the onAdvance() method.
R
-A
Exchanger
01
This synchronizer class is useful in a situation where there is a need to perform synchronization and
exchange of data between two concurrent running tasks. This class allows two threads to wait for a common
02
point of exchange. If a thread reaches the point of exchange early, then it waits for the other thread to reach
the common point of exchange. When both threads reach at this common point, they exchange the data
30
shared by them. The method used to exchange data between threads is named exchange(). When a thread
52
gets ready to exchange data, it invokes the exchange() method. If the other thread is not ready, the thread
that invoked the exchange method is put to sleep till the time the other thread gets ready for data exchange.
00
19
Consider a scenario where you need to create a concurrent program that implements collections to store and
manage data. Some of the classes in the collection framework, such as ArrayList, cannot be used to work
with multiple threads as the access to its data in a concurrent program cannot be controlled. For example, in a
program, concurrent tasks on an unsynchronized collection of objects, such as ArrayList, by multiple
threads can result in data inconsistency errors that can further affect the required functionality of the
application. To avoid this, Java provides the concurrency collection classes in the java.util.concurrent
package. The use of the collection classes improves the performance of a concurrent application and
improves its scalability by allowing multiple threads to share a data collection.
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Some of the concurrency collections available in the java.util.concurrent package that can be used for
concurrent programming are:
ArrayBlockingQueue: This is a blocking FIFO based queue in which the elements are maintained by
using an array. In a FIFO queue, the new elements are inserted at the end of the queue and an element is
removed from the head of the queue. You can specify the capacity of the number of elements that can be
stored in the queue, while creating an instance of this class. Moreover, there is an upper bound on the
number of elements that can be stored in the queue. This upper bound can be specified only at the time
of instantiation and cannot be changed later. If a thread attempts to add an element to this queue when it
is full, the thread will be blocked until an existing element is removed from the queue.
LinkedBlockingQueue: This is a FIFO based queue where the maximum capacity of elements to be
stored in the list can be specified. This queue is implemented by using a linked list that is a collection of
nodes. If a thread attempts to add an element to this queue when it is full, the thread will be blocked until
R
an existing element is removed from the queue. The throughput of this queue is higher than
KA
ArrayBlockingQueue.
PriorityBlockingQueue: This is a blocking queue that orders elements based on their priority. If a
R
thread attempts to add an element to this queue when it is full, the thread will be blocked until an
SA
existing element is removed from the queue. In addition, a thread is blocked when a thread attempts to
remove an element and the queue is empty.
A
SynchronousQueue: This is a blocking queue that blocks the request to add data to the queue until a
R
request to retrieve the data from the queue is received, and vice versa. This queue does not have the
capacity to store any data element.
IT
DelayQueue: This queue performs the ordering of its elements on the basis of the remaining time
R
before which they can be eliminated from the queue. In such a queue, an object can only be retrieved
-A
from the queue when its delay time is zero. Only those objects that implement the Delayed interface
01
concurrency. This class is suitable for the multithreaded environment as it segments the internal table.
30
This allows multiple threads to perform concurrent read operations. However, the lock can be applied
only on the segment that needs to be updated. As compared to a Hashtable class, this class does not
52
allow a key to have a null value. Also, the duplicate values are not allowed.
00
ConcurrentLinkedQueue: This is a FIFO based queue that is based on linked nodes. This queue can
be used for concurrent access. In this queue, the head of the queue represents the element that has been
19
in the queue for the longest period. On the other hand, the tail represents the element that has been in the
queue for the smallest time. This queue does not allow null elements to be entered in the queue.
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
ConcurrentSkipListSet: Similar to ConcurrentSkipListMap, you can use the
ConcurrentSkipListSet class to store the elements in a Set collection, where the addition insertion,
removal, update, and access operations can be safely executed concurrently by multiple threads. The
ConcurrentSkipListSet class implements the NavigableSet interface of the java.util package
to enable navigation methods reporting closest matches for given search targets. In addition, similar to
the ConcurrentSkipListMap class, the elements stored in a ConcurrentSkipListSet are sorted
according to the natural ordering or by a comparator.
CopyOnWriteArrayList: This is a thread-safe implementation of the ArrayList class. In this list, the
operations, such as add and set, are performed by making a fresh copy of the array. Such a list is
preferred as compared to a synchronized ArrayList, when the number of reads to be performed is
more than the number of updates to be performed.
CopyOnWriteArraySet: This class represents a set that uses CopyOnWriteArrayList for its
R
operations. As it uses CopyOnWriteArrayList for its operations, it is thread-safe. Further, its use is
KA
preferred when the number of reads to be performed is more than the number of updates to be
performed.
R
SA
A
R
IT
R
-A
01
02
30
52
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Practice Questions
1. Identify the keyword that is used to synchronize a method.
a. synchronize
b. synchronized
c. lock
d. monitor
R
a. wait()
KA
b. release()
c. synchronize()
R
d. notify()
SA
3. Identify the method that is used to wake up a single thread that is waiting for the monitor of the object
being executed.
A
a. wait()
R
IT
b. release()
R
c. synchronize()
-A
d. notify()
01
4. Identify the package that provides the classes and methods that can be used to create atomic variables for
02
b. java.util.atomic
52
c. java.util.concurrent.atomicInteger
00
d. java.util.concurrent.Integer
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Summary
In this chapter, you learned that:
The synchronization of threads ensures that if two or more threads need to access a shared resource, then
that resource is used by only one thread at a time.
You can implement thread synchronization by using the following approaches:
By using the synchronized methods
By using the synchronized statement
Synchronization is based on the concept of a monitor, which is an object used as a lock.
When a thread is within a synchronized method, all the other threads that try to call the method at the
R
same time have to wait.
KA
The synchronized statement is used where the synchronization methods are not used in a class and you
do not have access to the source code.
R
Multithreading eliminates the concept of polling by a mechanism known as interprocess communication.
SA
The various methods used in inter-threaded communication are:
wait()
notify()
A
R
notifyAll()
IT
Concurrency enables Java programmers to improve the efficiency and resource utilization of their
R
The java.util.concurrent package has the following sub packages to support concurrent
programming:
02
java.util.concurrent.atomic
30
java.util.concurrent.locks
Atomic variables are the single variables on which operations, such as increment and decrement, are
52
done in a single step. Such operations are known as atomic operations.
00
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
R
KA
R
SA
A
R
IT
R
-A
01
02
30
52
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
You have learned how to use traditional Input/Output (I/O) operations using the classes and interfaces in the
java.io package. However, the traditional I/O operations lack useful features, such as file locking.
Therefore, to overcome such issues and further improve the efficiency of Java applications, the New Input
Output (NIO) Application Programming Interface (API) has been introduced to provide simpler and high-
performance I/O operations.
This chapter focuses on NIO classes and interfaces. In addition, you will learn to read/write from/to a file
efficiently using the NIO classes.
Objectives
R
In this chapter, you will learn to:
KA
Get familiar with NIO
R
Perform the read and write operations on a file
SA
A
R
IT
R
-A
01
02
30
52
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Introducing NIO
In Java applications that perform I/O operations with files, you need to store data and retrieve the same from
files and work with directories to access files. I/O operations utilize system resources, and therefore, must be
performed efficiently to improve the performance of the applications and achieve the maximum processing
productivity. The functionality offered by the java.io package for I/O operations had performance related
issues, such as a thread performing a write operation was blocked until some data was transferred. Further,
there were efficiency-related issues, such as there was no method to copy a file or directory. To overcome
this and further simplify I/O operations, Java provides the java.nio package. The java.nio package
provides sub packages and classes that are useful for improving the speed and performance of I/O operations.
In order to perform I/O operations on files and directories using the NIO API, you need to make use of the
R
Path interface and the Paths class. In addition, to work with files and directories, you need to use the
KA
Files class. Further, NIO also provides support for monitoring a directory by implementing a watch service.
R
SA
Using the Path Interface and the Paths Class
The Path interface is a component of the java.nio.file package, which provides support for identifying
A
and working with files and directories. The Path interface is used to represent the path of a file or a directory
R
that is located on a file system. A path comprises the name of the file, directory/directories, and drive. For
IT
example, D:\Java\Sample\explorer.txt represents the path where explorer.txt is the name of the
R
file, Java\Sample\ are the names of directories, and D:\ is the name of the drive in the file system.
-A
In order to work with a path, you need to create a reference of the Path interface. To obtain a Path
01
reference, you need to use the get() method of the Paths helper class in the java.nio.file package. For
example, to obtain a Path reference, you can use the following code snippet:
02
30
In the preceding code snippet, a Path reference named pathobject is created. This reference represents the
52
path, D:\Java\Sample\explorer.txt.
00
Further, the Path interface provides various methods, such as getFileName() to obtain information on
19
paths of files or directories. The following table lists some of the most commonly used methods of the Path
interface.
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Method Name Description Example
R
the number of elements target=Paths.get("D:/NIODemo/Hello.java
");
KA
that constitute the
path, excluding the System.out.println(target.getNameCount(
R
root drive letter, such ));
SA
as D:/.
The output of the preceding code snippet is:
2
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Method Name Description Example
R
other) comparison of two target=Paths.get("D:/NIODemo/Hello.java
KA
paths. It returns 0 if ");
the two paths are Path
R
equal. It returns a comparePath=Paths.get("D:/NIODemo/Hello
SA
value greater than 0 if .java");
the path specified is Path
greater than the path compareNewPath=Paths.get("D:/NIODemo/NI
specified as an
A
O/Hello.java");
R
argument. It returns a System.out.println(comparePath.compareT
IT
value that is less than o(target));
R
0
6
30
Note
In order to get the same output, as shown in the preceding table, ensure that the files
R
used in the preceding code snippets are created at their respective locations.
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Some of the file operations that can be performed using the java.nio.file.Files class are:
Create a file or directory.
Copy a file or directory.
Move a file or directory.
Check the existence of a file or directory.
Delete a file or directory.
Traverse a file tree.
R
is:
KA
static Path createFile(Path path, FileAttribute<?>... attrs)
R
This method accepts a Path reference and creates a new file at the location specified by the Path reference
SA
variable. The FileAttribute reference is used to specify the attributes that define whether the file is being
created for the purpose of reading and/or writing and/or executing. These attributes are file system
dependent. Therefore, you need to utilize a file system-specific file permissions class and its helper class. For
A
example, for a POSIX compliant file system, such as Unix, you can use the PosixFilePermission enum
R
and the PosixFilePermissions class, as shown in the following code snippet:
IT
R
= PosixFilePermissions.fromString("rw-rw-rw-");
01
FileAttribute<Set<PosixFilePermission>> attr
= PosixFilePermissions.asFileAttribute(perms);
02
Files.createFile(target, attr);
In the preceding code, rw-rw-rw- specifies the permissions, which are applied on the MyStuff.txt file
30
when it is created. If the file location does not exist, the java.nio.file.NoSuchFileException
52
exception is thrown. In addition, if you try to create a file that already exists at the same location, the
java.nio.file.FileAlreadyExistsException exception is raised. However, it is not mandatory to
00
specify the file attributes. The following code snippet shows how to create a file without specifying the file
attributes:
19
R
In the preceding code snippet, pathObject is a reference variable of the Path interface. pathObject
stores the path returned by the get() method. The pathObject reference variable is passed to the
createFile() method. The createFile() method creates a file named NIODemo.java in the D:\ drive.
Similarly, to create a directory, the createDirectory() method is used. The signature of the
createDirectory() method is:
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
This method accepts a Path reference and creates a new directory at the location specified by the path
reference variable. The FileAttribute reference is used to specify the attributes that define whether the
directory is being created for the purpose of reading and/or writing and/or executing. It is not mandatory to
specify the preceding file attributes. If you try to create a directory that already exists at the same location,
then java.nio.file.FileAlreadyExistsException is raised.
The following code snippet shows how to create a directory without specifying the file attributes:
In the preceding code snippet, pathObject is a reference variable of the Path interface. pathObject
stores the path returned by the get() method. The pathObject reference variable is passed to the
createDirectory() method. The createDirectory() method creates a directory named NIO in the D:\
R
drive.
KA
If there is a requirement to create a single level or multiple levels of directories, such as
R
D:\User1\Java\Programs, you need to specify the relevant path and use the createDirectories(Path
SA
dir, FileAttribute<?>... attrs)method. This method does not throw an exception if the directories
already exist.
The following code snippet shows how to create multiple directories by using the createDirectories()
method: A
R
IT
Path newdir = Paths.get("D:/User1/Java/Programs");
R
try
-A
{
Files.createDirectories(newdir);
01
}
catch (IOException e)
02
{
System.err.println(e);
30
}
52
In the preceding code snippet, the createDirectories() method creates the directories as specified by
the path reference, newdir.
00
19
is:
This method accepts two Path references for the source file to be copied and the target file to be created as a
copy of the source file, respectively. Further, CopyOption... options is used to specify one or more
copy options that determine how the copy process should be done. It is not mandatory to specify the copy
options. These options are listed under the StandardCopyOption and LinkOption enums.
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
The following table lists the commonly used copy options that can be specified with the copy() method.
R
associated with the source file to the target file.
The file attributes define the characteristics of
KA
a file, such as its creation time and last
modification time.
R
SA
LinkOption NOFOLLOW_LINKS This option allows you to specify that the
symbolic links should not be followed to their
actual target file. A symbolic link is a file that
A
contains a reference to another target file or
R
directory.
IT
R
import java.io.IOException;
import java.nio.file.Files;
02
import java.nio.file.Path;
import java.nio.file.Paths;
30
{
public static void main(String[] args)
19
{
Path source = Paths.get("D:/Hello.java");
R
Path target=Paths.get("D:/NIODemo/Hello.java");
try
{
Files.copy(source, target, REPLACE_EXISTING, COPY_ATTRIBUTES);
}
catch(IOException e)
{
System.out.println(e);
}
}
}
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
In the preceding code snippet, the source file to be copied is specified by the source path reference and the
file to be created with the copy process is specified at the D:/NIODemo/Hello.java location. If the source
file to be copied does not exist, the java.nio.file.NoSuchFileException exception is thrown. In
addition, if a target file already exists and the REPLACE_EXISTING option is not specified, the
FileAlreadyExistsException exception is thrown.
R
This method accepts two Path references for the source file or directory to be moved and the target file or
KA
directory to which the source file or directory should be moved, respectively. However, if the specified target
file already exists, the move process fails. Further, CopyOption... options is used to specify one or
R
more copy options that determine how the copy or move process should be done. These options are listed
SA
under the StandardCopyOption enum. The following table lists the copy options that can be specified with
the move() method.
A
Option Description
R
IT
REPLACE_EXISTING
R
interrupted in between.
30
The following code shows how to move an existing file to another location:
00
import java.io.IOException;
import java.nio.file.Files;
19
import java.nio.file.Path;
import java.nio.file.Paths;
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
catch(IOException e)
{
System.out.println(e);
}
}
}
In the preceding code, the Hello.java file located in the D:/NIODemo directory is moved to the
D:\NIODemo\NIO directory. If the source file does not exist at the specified location or if an invalid target
location is specified, the NoSuchFileException exception is thrown.
The following code snippet shows how to move an existing directory to another directory:
R
Path target=Paths.get("D:/NIODemo/NIO/NewEmptyDirectory");
KA
Files.move(source, target, REPLACE_EXISTING);
When the preceding code snippet is executed, the contents specified at the D:\Pictures path will be moved to
R
the NewEmptyDirectory directory. While moving a directory, it is important to ensure that the target
SA
directory is empty. Otherwise, the DirectoryNotEmptyException exception is thrown. If the target
directory location does not exist at the specified location, the NoSuchFileException exception is thrown.
This method accepts a path reference, path, which is to be verified for its existence. Further, the link options
02
are used to specify how the symbolic links should be handled if the path represents a symbolic link. This
30
method returns true if the file or directory exists. Otherwise, it returns false. The following code snippet
shows how to use the exists() method:
52
Path target=Paths.get("D:/NIODemo/NIO/NewEmptyDirectory");
00
In the preceding code snippet, the path, D:/NIODemo/NIO/NewEmptyDirectory, is verified for its
R
existence.
Similarly, you can use the notExists() method to check if a file or directory does not exist. This method
returns true if a file or directory does not exist. Otherwise, it returns false. The following code snippet
shows how to use the notExists() method:
Path target=Paths.get("D:/NIODemo/NIO/NewEmptyDirectory");
Boolean pathExists = Files.notExists(target, LinkOption.NOFOLLOW_LINKS);
System.out.println(pathExists);
In the preceding code snippet, the path, D:/NIODemo/NIO/NewEmptyDirectory, is verified for its
non existence.
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Deleting a File or Directory
To delete a file, directory, or symbolic link, you can use either the delete(Path path) method or the
deleteIfExists(Path path) method. The signature of the delete() method is:
The preceding method accepts a Path reference that specifies the path to be deleted. The following
exceptions may be thrown by this method:
NoSuchFileException: Is thrown if the path does not exist.
DirectoryNotEmptyException: Is thrown if the path specifies a directory that is not empty.
IOException: Is thrown in case of an I/O error.
R
SecurityException: Is thrown if the permission to delete the file is denied.
KA
The following code snippet shows how to delete a file:
R
Path target=Paths.get("D:/NIODemo/NIO/Hello.java");
SA
Files.delete(target);
Once the preceding code snippet is executed, the Hello.java file that is located in the D:\NIODemo\NIO
directory is deleted.
A
R
Similarly, you can use the deleteIfExists() method for deleting a file or a directory. The signature of
IT
this method is:
R
The preceding method accepts a path reference that specifies the path to be deleted. However, this method
01
does not throw an exception in case the specified path does not exist. In such a case, it returns a boolean
value, false. The following code snippet shows how to use the deleteIfExists() method:
02
30
Path target=Paths.get("D:/NIODemo/NIO/Hello.java");
System.out.println(Files.deleteIfExists(target));
52
Once the preceding code snippet is executed, the Hello.java file located in the D:\NIODemo\NIO
directory is deleted if it exists and the appropriate boolean value is printed.
00
19
Consider a scenario where you need to create a Java application that should traverse all the folders and files
located in your directory structure to perform an operation such as, create, find, or delete a file. Further, you
may want to recursively copy the contents of a directory to another directory. To meet the preceding
requirements, you can use the FileVisitor interface provided by NIO. This interface is located in the
java.nio.file package.
The FileVisitor interface provides support to traverse a file tree recursively. It also allows you to gain
control over the traversal process and perform operations during the traversal process. In order to perform
operations during the traversal process, this interface provides some methods.
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
You need to override the following methods to perform operations during the traversal process:
FileVisitResult preVisitDirectory(): This method is used with a directory and is invoked
before visiting its contents.
FileVisitResult postVisitDirectory(): This method is used with a directory and is invoked
after all its contents are visited.
FileVisitResult visitFile(): This method is used with a file and is invoked when that file is
visited during the traversal process.
FileVisitResult visitFileFailed(): This method is used with a file and is invoked when the
file to visit cannot be accessed.
Each of the preceding methods returns a value of the type, the FileVisitResult enum. This value is used
to determine how to proceed with the traversal process. Some of the constant values in the
R
FileVisitResult enum are:
KA
CONTINUE: Is used to indicate that the traversal must continue.
R
SKIP_SUBTREE: Is used to indicate that the traversal must proceed without visiting the contents inside
SA
the directory.
TERMINATE: Is used to indicate that the traversal must terminate.
A
Further, to start the traversal process, you need to use the walkFileTree() method in the Files class. This
R
method accepts the path from where the traversal process needs to be started and the instance of the class that
implements the FileVisitor interface. The signature of this method is:
IT
R
visitor)
01
In the preceding signature, startpoint represents the path reference from which the traversal should begin.
FileVisitor<? super Path> visitor represents the instance of the class that implements the
02
FileVisitor interface.
30
The following code shows how to implement the file tree traversal process by using the FileVisitor
interface:
52
00
import java.io.IOException;
import java.nio.file.FileVisitResult;
19
import java.nio.file.FileVisitor;
import java.nio.file.Files;
R
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes
attrs) throws IOException {
R
System.out.println("Checking done..!!");
KA
return FileVisitResult.CONTINUE;
R
SA
public FileVisitResult visitFileFailed(Path file, IOException e)
throws IOException {
System.err.println(e.getMessage());
A
return FileVisitResult.CONTINUE; R
}
}
IT
public class NIODemo
R
{
-A
Files.walkFileTree(listDir, obj);
}
30
}
52
Note
The preceding output may vary based on contents of the D:/NIO directory.
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
In the preceding code, listDir represents a path reference from where the traversal should begin. Then, the
walkFileTree() method is used to start the traversal from the path specified by listDir by using the obj
instance of the MyFileVisitor class. In this class, the methods of the FileVisitor interface are
overridden. The postVisitDirectory() method prints the Just Visited message and the file or
directory name. The preVisitDirectory() method prints the About to visit message and the file or
directory name. The visitFile() method prints the name of the currently visited file and also checks if the
visited path is a directory by using the Files.isDirectory() method. Further, the visitFileFailed()
method is used to print a message if the file visit fails.
However, there can be a requirement where you do not need to provide an implementation for all the
methods of the FileVisitor interface, but only for a few methods. In such a case, you can extend the
SimpleFileVisitor class. For example, when there is a requirement to print only the names of the files in
a file tree when they are visited. The SimpleFileVisitor class implements the FileVisitor interface,
R
and therefore, its methods can be overridden depending upon the requirement of the application.
KA
Consider a scenario, where you need to perform a pattern match to obtain a list and count of filenames that
R
match a pattern, such as *.java. Therefore, to match a filename with the pattern name, you can use the
SA
PathMatcher class. The following code demonstrates how to search for all the .java files in the D:\ drive of
your computer:
A
import java.io.IOException; R
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
IT
import java.nio.file.FileVisitOption;
R
import java.nio.file.FileVisitResult;
-A
import java.nio.file.FileVisitor;
import java.nio.file.Files;
01
import java.nio.file.Path;
import java.nio.file.PathMatcher;
02
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
30
import java.util.EnumSet;
52
FileSystem fs=FileSystems.getDefault();
matcher = fs.getPathMatcher("glob:" + pattern);
}
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
public FileVisitResult postVisitDirectory(Object dir, IOException exc)
throws IOException {
return FileVisitResult.CONTINUE;
}
R
public FileVisitResult visitFile(Object file, BasicFileAttributes attrs)
KA
throws IOException {
search((Path) file);
return FileVisitResult.CONTINUE;
R
}
SA
public FileVisitResult visitFileFailed(Object file, IOException exc)
A
throws IOException { R
return FileVisitResult.CONTINUE;
}
IT
}
R
-A
class MainClass {
01
}
19
Note
The preceding output may vary.
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
In the preceding code, in the main() method, the pattern is specified as *.java. In the constructor, the
getPathMatcher() method is used. This method is used to create a PathMatcher for performing match
operations on paths. The FileSystems.getDefault() method returns an object of the FileSystem class.
The getPathMatcher()method is used to obtain the object of the PathMatcher class. This method is
accepting a glob pattern, such as glob:*.java. Further, the matches() method is used to compare the name
of the browsed files against the glob pattern. By using the counter variable, the total files that match the
pattern are displayed inside the main() method.
Note
A glob pattern is specified as a string and used to specify a pattern to be matched
R
against strings, such as file names.
KA
R
SA
Just a minute:
A
R
The_____________ constant of the FileVisitResult enum is used to indicate that
IT
the traversal must end.
R
Answer:
-A
TERMINATE
01
02
30
52
Using NIO
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Practice Questions
1. Which one of the following methods of the Paths helper class is used to obtain a file path reference?
a. get()
b. getFileName()
c. getName()
d. getRoot()
2. Identify the method of the Path interface that returns the name of the file system.
R
a. getFileName()
KA
b. getFileSystem()
c. FileSystem()
R
d.
SA
getParent()
3. Identify the method of the Path interface that is used to identify if a path represents the entire path
hierarchy.
A
a. getFileName()
R
IT
b. getFileSystem()
R
c. getRoot()
-A
d. isAbsolute()
01
4. Identify the exception that is thrown when you try to create a directory that already exists at the specified
02
FileAlreadyExistsException
b. DirectoryNotEmptyException
52
c. NoSuchFileException
00
d. IOException
19
5. Identify the interface that provides support for traversing a file structure recursively.
R
a. FileVisitor
b. FileReader
c. Watchable
d. Path
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Summary
In this chapter, you learned that:
The java.nio package provides sub packages and classes that are useful for improving the speed and
performance of I/O operations.
The Path interface is a component of the java.nio.file package, which provides support for
identifying and working with files and directories.
Some of the file operations that can be performed using the java.nio.file.Files class are:
Create a file or directory
Copy a file or directory
R
Move a file or directory
KA
Check the existence of a file or directory
R
Delete a file or directory
SA
Traverse a file tree
To create a file, you need to use the createFile() method.
A
To copy a file, you need to use the copy() method of the Files class. R
To move an existing file or directory, you can use the move() method specified in the Files class.
IT
To check whether a file or directory exists or it does not exist, you can use the exists() and
R
To delete a file, directory, or symbolic link, you can use either the delete(Path path) method or the
deleteIfExists(Path path) method.
01
A buffer is a storage area in the memory that can be used for writing or reading data.
30
52
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
R
KA
R
SA
A
R
IT
R
-A
01
02
30
52
00
19
R
Introduction to JDBC
CHAPTER 9
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Java Database Connectivity (JDBC) is an API that executes SQL statements. It consists of a set of classes
and interfaces written in the Java programming language. The interface is easy to connect to any database
using JDBC. The combination of Java and JDBC makes the process of disseminating information easy and
economical.
This chapter introduces the JDBC architecture. It gives an overview of the different types of drivers
supported by JDBC. It elaborates the methods to establish the connection with SQL Server using the Type 4
JDBC driver.
Objectives
R
In this chapter, you will learn to:
KA
Identify the layers in the JDBC architecture
R
Identify the types of JDBC drivers
SA
Use JDBC API
Access result sets
A
R
IT
R
-A
01
02
30
52
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Identifying the Layers in the JDBC Architecture
Consider a scenario where you have to develop an application for an airlines company that maintains a
record of daily transactions. You install SQL Server as an RDBMS, design the airlines database, and ask the
airlines personnel to use it. Will the database alone be of any use to the airlines personnel?
The answer will be negative. The task of updating data in the SQL Server database by using SQL statements
alone will be a tedious process. An application will need to be developed that is user friendly and provides
the options to retrieve, add, and modify data at the touch of a key to a client.
Therefore, you need to develop an application that communicates with a database to perform the following
tasks:
R
Store and update the data in the database.
KA
Retrieve the data stored in the database and present it to users in a proper format.
R
The following figure shows Airline Reservation System developed in Java that interacts with the Airlines
database using the JDBC API.
SA
A
R
IT
R
-A
01
02
30
52
JDBC Architecture
19
R
Java applications cannot communicate directly with a database to submit data and retrieve the results of
queries. This is because a database can interpret only SQL statements and not Java language statements.
Therefore, you need a mechanism to translate Java statements into SQL statements. The JDBC architecture
provides the mechanism for this kind of translation.
The JDBC architecture has the following two layers:
JDBC application layer: Signifies a Java application that uses the JDBC API to interact with the JDBC
drivers. A JDBC driver is the software that a Java application uses to access a database.
JDBC driver layer: Acts as an interface between a Java application and a database. This layer contains
a driver, such as the SQL Server driver or the Oracle driver, which enables connectivity to a database. A
driver sends the request of a Java application to the database. Once this request is processed, the
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
database sends the response back to the driver. The response is then translated and sent to the JDBC API
by the driver. The JDBC API finally forwards this response to the Java application.
The following figure shows the JDBC architecture.
R
KA
R
SA
A
R
The JDBC Architecture
IT
R
-A
01
Just a minute:
02
Answer:
52
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Identifying the Types of JDBC Drivers
While developing JDBC applications, you need to use JDBC drivers to convert queries into a form that a
particular database can interpret. The JDBC driver also retrieves the result of SQL statements and converts
the result into equivalent JDBC API class objects that the Java application uses. Because the JDBC driver
only takes care of the interactions with the database, any change made to the database does not affect the
application. JDBC supports the following types of drivers:
JDBC-ODBC Bridge driver
Native-API driver
Network Protocol driver
R
Native Protocol driver
KA
R
The JDBC-ODBC Bridge Driver
SA
The JDBC-ODBC Bridge driver is called the Type 1 driver. The JDBC-ODBC Bridge driver converts the
JDBC method calls into the Open Database Connectivity (ODBC) function calls. ODBC is an open standard
A
API to communicate with databases. The JDBC-ODBC Bridge driver enables a Java application to use any
R
database that supports the ODBC driver. A Java application cannot interact directly with the ODBC driver.
IT
Therefore, the application uses the JDBC-ODBC Bridge driver that works as an interface between the
application and the ODBC driver. To use the JDBC-ODBC Bridge driver, you need to have the ODBC driver
R
installed on the client computer. The JDBC-ODBC Bridge driver is usually used in standalone applications.
-A
01
02
30
52
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
The following figure shows how the JDBC-ODBC Bridge driver works.
R
KA
R
SA
A
R
IT
R
-A
01
02
30
The Native-API driver is called the Type 2 driver. It uses the local native libraries provided by the database
R
vendors to access databases. The JDBC driver maps the JDBC calls to the native method calls, which are
passed to the local native Call Level Interface (CLI). This interface consists of functions written in the C
language to access databases. To use the Type 2 driver, CLI needs to be loaded on the client computer.
Unlike the JDBC-ODBC Bridge driver, the Native-API driver does not have an ODBC intermediate layer.
As a result, this driver has a better performance than the JDBC-ODBC Bridge driver and is usually used for
network-based applications.
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
The following figure shows how the Native-API driver works.
R
KA
R
SA
A
R
IT
R
-A
01
02
30
The Network Protocol driver is called the Type 3 driver. The Network Protocol driver consists of client and
server portions. The client portion contains pure Java functions, and the server portion contains Java and
R
native methods. The Java application sends JDBC calls to the Network Protocol driver client portion, which
in turn, translates JDBC calls into database calls. The database calls are sent to the server portion of the
Network Protocol driver that forwards the request to the database. When you use the Network Protocol
driver, CLI native libraries are loaded on the server.
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
The following figure shows how the Network Protocol driver works.
R
KA
R
SA
A
R
IT
R
The Native Protocol driver is called the Type 4 driver. It is a Java driver that interacts with the database
30
directly using a vendor-specific network protocol. Unlike the other JDBC drivers, you do not require to
install any vendor-specific libraries to use the Type 4 driver. Each database has the specific Type 4 drivers.
52
The following figure shows how the Native Protocol driver works.
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Using JDBC API
You need to use database drivers and the JDBC API while developing a Java application to retrieve or store
data in a database. The JDBC API classes and interfaces are available in the java.sql and javax.sql
packages. The classes and interfaces perform a number of tasks, such as establish and close a connection
with a database, send a request to a database, retrieve data from a database, and update data in a database.
The classes and interfaces that are commonly used in the JDBC API are:
The DriverManager class: Loads the driver for a database.
The Driver interface: Represents a database driver. All JDBC driver classes must implement the
Driver interface.
R
The Connection interface: Enables you to establish a connection between a Java application and a
KA
database.
The Statement interface: Enables you to execute SQL statements.
R
The ResultSet interface: Represents the information retrieved from a database.
SA
The SQLException class: Provides information about exceptions that occur while interacting with
databases.
To query a database and display the result using Java applications, you need to:
A
R
Load a driver.
IT
Connect to a database.
R
Loading a Driver
30
The first step to develop a JDBC application is to load and register the required driver using the driver
52
Class.forName("package.sub-package.sub-package.DriverClassName");
You can load the JDBC-Type 4 driver for SQL Server using the following code snippet:
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Using the registerDriver() Method
You can create an instance of the JDBC driver and pass the reference to the registerDriver() method.
The following syntax is used for creating an instance of the JDBC driver:
Once you have created the Driver object, call the registerDriver() method to register the driver, as
shown in the following code snippet:
R
DriverManager.registerDriver(d);
KA
R
Connecting to a Database
SA
You need to create an object of the Connection interface to establish a connection of the Java application
with a database. You can create multiple Connection objects in a Java application to access and retrieve
A
data from multiple databases. The DriverManager class provides the getConnection() method to create
R
a Connection object. The getConnection() method is an overloaded method that has the following three
IT
forms:
R
password)
02
The getConnection (String url)method accepts the JDBC URL of the database, which you need to
access as a parameter. You can use the following code snippet to connect a database using the
30
String url =
00
"jdbc:sqlserver://localhost;user=MyUserName;password=password@123";
Connection con = DriverManager.getConnection(url);
19
The following signature is used for a JDBC Uniform Resource Location (URL) that is passed as a parameter
R
<protocol>:<subprotocol>:<subname>
A JDBC URL has the following three components:
protocol: Indicates the name of the protocol that is used to access a database. In JDBC, the name of
the access protocol is always jdbc.
subprotocol: Indicates the vendor of Relational Database Management System (RDBMS). For
example, if you use the JDBC-Type 4 driver of SQL Server to access its database, the name of
subprotocol will be sqlserver.
subname: Indicates Data Source Information that contains the database information, such as the location
of the database server, name of a database, user name, and password, to access a database server.
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Creating and Executing JDBC Statements
Once a connection is created, you need to write the JDBC statements that are to be executed. You need to
create a Statement object to send requests to a database and retrieve results from the same. The
Connection object provides the createStatement() method to create a Statement object. You can use
the following code snippet to create a Statement object:
Connection
con=DriverManager.getConnection("jdbc:sqlserver://sqlserver01;databaseName=Li
brary;user=user1;password=password#1234");
Statement stmt = con.createStatement();
You can use static SQL statements to send requests to a database. The SQL statements that do not contain
R
runtime parameters are called static SQL statements. You can send SQL statements to a database using the
KA
Statement object. The Statement interface contains the following methods to send the static SQL
statements to a database:
R
SA
ResultSet executeQuery(String str): Executes an SQL statement and returns a single object of
the type, ResultSet. This object provides you the methods to access data from a result set. The
executeQuery() method should be used when you need to retrieve data from a database table using
the SELECT statement. The syntax to use the executeQuery() method is:
A
R
IT
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(<SQL statement>);
R
In the preceding syntax, stmt is a reference to the object of the Statement interface. The
-A
executeQuery() method executes an SQL statement, and the result retrieved from a database is stored
01
are affected after processing the SQL statement. When you need to modify data in a database table using
30
the Data Manipulation Language (DML) statements, INSERT, DELETE, and UPDATE, you can use the
executeUpdate() method. The syntax to use the executeUpdate() method is:
52
In the preceding syntax, the executeUpdate() method executes an SQL statement and the number of
rows affected in a database is stored in count that is the int type variable.
R
boolean execute(String str): Executes an SQL statement and returns a boolean value. You can
use this method when you are dynamically executing an unknown SQL string. The execute() method
returns true if the result of the SQL statement is an object of ResultSet else it returns false. The
syntax to use the execute() method is:
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Querying a Table
Using the SELECT statement, you can retrieve data from a table. The SELECT statement is executed using the
executeQuery() method and returns the output in the form of a ResultSet object. You can use the
following code snippet to retrieve data from the Authors table:
In the preceding code snippet, str contains the SELECT statement that retrieves data from the Authors
table. The result is stored in the ResultSet object, rs.
When you need to retrieve selected rows from a table, the condition to retrieve the rows is specified in the
R
WHERE clause of the SELECT statement. You can use the following code snippet to retrieve selected rows
KA
from the Authors table:
R
String str = "SELECT * FROM Authors WHERE city='London'";
SA
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(str);
In the preceding code snippet, the executeQuery() method retrieves the details from the Authors table
for a particular city.
A
R
IT
Inserting Rows in a Table
R
You can add rows to an existing table using the INSERT statement. The executeUpdate() method enables
-A
you to add rows in a table. You can use the following code snippet to insert a row in the Authors table:
01
String str = " INSERT INTO Authors (au_id, au_name, phone, address, city,
02
state, zip) VALUES ('A004', 'Ringer Albert', '8018260752', ' 67 Seventh Av.
', 'Salt Lake City', 'UT', '100000078')";
30
In the preceding code snippet, str contains the INSERT statement that you need to send to a database. The
00
object of the Statement interface, stmt, executes the INSERT statement using the executeUpdate()
method and returns the number of rows inserted in the table to the count variable.
19
R
String str = "UPDATE Authors SET address='10932 Second Av.' where au_id=
'A001'";
Statement stmt = con.createStatement();
int count = stmt.executeUpdate(str);
In the preceding code snippet, str contains the UPDATE statement that you need to send to a database. The
Statement object executes this statement using the executeUpdate() method and returns the number of
rows modified in the table to the count variable.
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Deleting Rows from a Table
You can delete the existing information from a table using the DELETE statement. You can use the following
code snippet to delete a row from the Authors table:
In the preceding code snippet, str contains the DELETE statement that you need to send to a database. The
Statement object executes this statement using the executeUpdate() method and returns the number of
rows deleted from the table to the count variable.
R
Creating a Table
KA
You can use the CREATE TABLE statement to create and define the structure of a table in a database. You can
use the following code snippet in a Java application to create a table:
R
SA
String str="CREATE TABLE Publishers"
+"(pub_id VARCHAR(5),"
+"pub_name VARCHAR(50),"
A
+"phone INTEGER," R
+"address VARCHAR(50), "
+"city VARCHAR(50), "
IT
+"ZIP VARCHAR(20))";
R
Statement stmt=con.createStatement();
-A
stmt.execute(str);
In the preceding code snippet, str contains the CREATE TABLE statement to create the Publishers table.
01
You can use the ALTER statement to modify the definition of the database object. You use the ALTER TABLE
52
statement to modify the structure of a table. For example, you can use this statement to add a new column in
a table, change the data type and width of an existing column, and add a constraint to a column. You can use
00
the following code snippet to use the ALTER statement in a Java application to add a column in the Books
19
table:
R
You can use the DROP statement to drop an object from a database. You use the DROP TABLE statement to
drop a table from a database. You can use the following code snippet to drop the MyProduct table using a
Java application:
While creating JDBC applications, you need to handle exceptions. The execute() method can throw
SQLException while executing SQL statements.
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Handling SQL Exceptions
The java.sql package provides the SQLException class, which is derived from the
java.lang.Exception class. SQLException is thrown by various methods in the JDBC API and enables
you to determine the reason for the errors that occur while connecting a Java application to a database. You
can catch SQLException in a Java application using the try and catch exception handling block. The
SQLException class provides the following error information:
Error message: Is a string that describes error.
Error code: Is an integer value that is associated with an error. The error code is vendor specific and
depends upon the database in use.
SQL state: Is an XOPEN error code that identifies the error. Various vendors provide different error
R
messages to define the same error. As a result, an error may have different error messages. The XOPEN
KA
error code is a standard message associated with an error that can identify the error across multiple
databases.
R
SA
The SQLException class contains various methods that provide error information. Some of the methods in
the SQLException class are:
int getErrorCode(): Returns the error code associated with the error occurred.
String getSQLState(): Returns SQL state for the SQLException object. A
R
IT
SQLException getNextException(): Returns the next exception in the chain of exceptions.
R
try
01
{
String str = "DELETE FROM Authors WHERE au_id='A002'";
02
}
catch(SQLException sqlExceptionObject)
52
{
System.out.println("Display Error Code");
00
sqlExceptionObject.getErrorCode());
}
R
In the preceding code snippet, if the DELETE statement throws SQLException, then it is handled by the
catch block. sqlExceptionObject is an object of the SQLException class and is used to invoke the
getErrorCode() method.
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Just a minute:
Identify the interface of the java.sql package that must be implemented by all the
JDBC driver classes.
Answer:
Driver
R
KA
Activity 9.1: Creating a JDBC Application to
Query a Database
R
SA
A
R
IT
R
-A
01
02
30
52
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Accessing Result Sets
When you execute a query to retrieve data from a table using a Java application, the output of the query is
stored in a ResultSet object in a tabular format. A ResultSet object maintains a cursor that enables you
to move through the rows stored in the ResultSet object. By default, the ResultSet object maintains a
cursor that moves in the forward direction only. As a result, it moves from the first row to the last row in
ResultSet. In addition, the default ResultSet object is not updatable, which means that the rows cannot
be updated in the default object. The cursor in the ResultSet object initially points before the first row.
R
KA
You can create various types of ResultSet objects to store the output returned by a database after executing
SQL statements. The various types of ResultSet objects are:
R
Read only: Allows you to only read the rows in a ResultSet object.
SA
Forward only: Allows you to move the result set cursor from the first row to the last row in the forward
direction only.
A
Scrollable: Allows you to move the result set cursor forward or backward through the result set.
R
Updatable: Allows you to update the result set rows retrieved from a database table.
IT
You can specify the type of a ResultSet object using the createStatement() method of the
R
Connection interface. The createStatement() method accepts the ResultSet fields as parameters to
-A
create different types of the ResultSet object. The following table lists various fields of the ResultSet
01
interface.
02
other users.
19
CONCUR_READ_ONLY Specifies the concurrency mode that does not allow you
to update the ResultSet object.
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
ResultSet Field Description
R
committed.
KA
The Fields of the ResultSet Interface
R
The createStatement() method has the following overloaded forms:
SA
Statement createStatement(): Does not accept any parameter. This method creates a Statement
object for sending SQL statements to the database. It creates the default ResultSet object that only
allows forward scrolling.
A
Statement createStatement(int resultSetType, int resultSetConcurrency): Accepts
R
IT
two parameters. The first parameter indicates the ResultSet type that determines whether or not a
result set cursor is scrollable or forward only. The second parameter indicates the concurrency mode for
R
the result set that determines whether the data in result set is updateable or read only. This method
-A
concurrency mode, this method also accepts a third parameter. This parameter indicates the holdability
mode for the open result set object. This method creates a ResultSet object with the given type,
30
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Methods of the ResultSet Interface
The ResultSet interface contains various methods that enable you to move the cursor through the result set.
The following table lists some methods of the ResultSet interface that are commonly used.
Method Description
boolean first() Shifts the control of a result set cursor to the first row of the
result set.
R
boolean isFirst() Determines whether the result set cursor points to the first row
KA
of the result set.
R
void beforeFirst() Shifts the control of a result set cursor before the first row of
SA
the result set.
boolean Determines whether the result set cursor points before the first
A
isBeforeFirst() row of the result set. R
IT
boolean last() Shifts the control of a result set cursor to the last row of the
R
result set.
-A
boolean isLast() Determines whether the result set cursor points to the last row
01
void afterLast() Shifts the control of a result set cursor after the last row of the
30
result set.
52
boolean Determines whether the result set cursor points after the last
00
boolean previous() Shifts the control of a result set cursor to the previous row of
R
boolean Shifts the control of a result set cursor to the row number that
absolute(int i) you specify as a parameter.
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
You can create a scrollable result set that scrolls backward or forward through the rows in the result set. You
can use the following code snippet to create a read-only scrollable result set:
You can determine the location of the result set cursor using the methods in the ResultSet interface. You
can use the following code snippet to determine if the result set cursor is before the first row in the result set:
if(rs.isBeforeFirst()==true)
System.out.println("Result set cursor is before the first row in the result
set");
R
In the preceding code snippet, rs is the ResultSet object that calls the isBeforeFirst() method.
KA
You can move to a particular row, such as first or last, in the result set using the methods in the ResultSet
interface. You can use the following code snippet to move the result set cursor to the first row in the result
R
set:
SA
if(rs.first()==true)
System.out.println(rs.getString(1) + ", " + rs.getString(2)+ ", " +
A
rs.getString(3)); R
In the preceding code snippet, rs is the ResultSet object that calls the first() method.
IT
Similarly, you can move the result set cursor to the last row in the result set using the last() method.
R
-A
To move to any particular row of a result set, you can use the absolute() method. For example, if the
result set cursor is at the first row and you want to scroll to the fourth row, you should enter 4 as a parameter
01
when you call the absolute() method, as shown in the following code snippet:
02
rs.absolute(4);
int rowcount = rs.getRow();
52
Note
19
You can pass a negative value to the absolute() method to set the cursor to a row
R
with regard to the last row of the result set. For example, to set the cursor to the row
preceding the last row, specify rs.absolute(-2).
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
JDBC allows you to create an updateable result set that enables you to modify the rows in the result set. The
following table lists some of the methods used with the updatable result set.
Method Description
void updateRow() Updates the current row of the ResultSet object and updates
the same in the underlying database table.
void insertRow() Inserts a row in the current ResultSet object and the
underlying database table.
R
void deleteRow() Deletes the current row from the ResultSet object and the
KA
underlying database table.
R
void Updates the specified column with the given string value. It
SA
updateString(int accepts the column index whose value needs to be changed.
columnIndex, String
x)
A
void
R
Updates the specified column with the given string value. It
updateString(String
IT
accepts the column name whose value needs to be changed.
columnLabel, String
R
x)
-A
void updateInt(int Updates the specified column with the given int value. It
01
columnIndex, int x) accepts the column index whose value needs to be changed.
02
void Updates the specified column with the given int value. It
30
You can use the following code snippet to modify the information of the author using the updatable result
19
set:
R
In the preceding code snippet, the row is retrieved from the Authors table where the author id is A004. In
the retrieved row, the value in the state column is changed to NY and the value in the city column is
changed to Columbia.
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Just a minute:
Identify the field of the ResultSet interface that allows the cursor to be
scrollable and reflects the changes in the data.
1. TYPE_SCROLL_SENSITIVE
2. TYPE_SCROLL_INSENSITIVE
3. CONCUR_READ_ONLY
4. CONCUR_UPDATAB
R
KA
Answer:
1. TYPE_SCROLL_SENSITIVE
R
SA
In addition to ResultSet, Java provides RowSet. The RowSet interface provides the connected and
disconnected environments. In a connected environment the RowSet object uses a JDBC driver to make a
A
connection to the underlying database and maintains the connection throughout its life time. On the other
R
hand, in a disconnected environment, the RowSet object makes a connection to the underlying database only
IT
to read data from the ResultSet object or write back to the database. After reading or writing data, the
R
To establish the connected or disconnected environment, the JDBC API provides the following interfaces:
01
JdbcRowSet: Provides the connected environment that is most similar to the ResultSet object. It
02
It changes the data while it is disconnected.
19
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
The preceding interfaces can be used for specific need, such as connected or disconnected. However, there is
another way to provide the RowSet implementation. For this, the RowSetProvider class provides APIs to
get a RowSetFactory implementation that can be used to instantiate a proper RowSet implementation. It
provides the following two methods:
static RowSetFactory newFactory(): Is used to create an instance of the RowSetFactory
implementation.
static RowSetFactory newFactory(String factoryClassName, ClassLoader c1): Is
used to create an instance of the RowSetFactory from the specified factory class name.
The RowSetFactory interface defines the implementation of a factory that is used to obtain different types
of RowSet implementations. It provides the following five methods:
CachedRowSet createCachedRowSet(): Is used to create an instance of CachedRowSet.
R
FilteredRowSet createFilteredRowSet(): Is used to create an instance of FilteredRowSet.
KA
JdbcRowSet createJdbcRowSet(): Is used to create an instance of JdbcRowSet.
R
JoinRowSet createJoinRowSet(): Is used to create an instance of JoinRowSet.
SA
WebRowSet createWebRowSet(): Is used to create an instance of WebRowSet.
A
R
IT
R
-A
01
02
30
52
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Practice Questions
1. Which one of the following methods is used to move the cursor to a particular row in a result set?
a. absolute()
b. first()
c. isFirst()
d. relative()
2. Which one of the following components of the JDBC URL indicates the vendor of RDBMS?
R
a. Subname
KA
b. Supername
c. Subprotocol name
R
d. Superprotocol name
SA
3. Identify the field of the ResultSet interface that specifies the cursor to be scrollable and does not
reflect the changes in the data.
a. TYPE_SCROLL_INSENSITIVE A
R
IT
b. TYPE_FORWARD_ONLY
R
c. TYPE_SCROLL_SENSITIVE
-A
d. TYPE_READ_ONLY
01
4. The Connection object provides the _______________ method to create a Statement object.
02
5. Which one of the following Java drivers interacts with the database directly using a vendor-specific
30
network protocol?
a. JDBC-ODBC Bridge driver
52
b. Native-API driver
00
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Summary
In this chapter, you learned that:
The JDBC architecture has the following two layers:
JDBC application layer
JDBC driver layer
JDBC supports the following four types of drivers:
JDBC-ODBC Bridge driver
Native-API driver
Network Protocol driver
R
KA
Native Protocol driver
The classes and interfaces of the JDBC API are defined in the java.sql and javax.sql packages.
R
You can load a driver and register it with the driver manager by using the forName() method or the
SA
registerDriver() method.
A Connection object establishes a connection between a Java application and a database.
A Statement object sends a request and retrieves results to/ from a database.
A
R
You can insert, update, and delete data from a table using the DML statements in Java applications.
IT
You can create, alter, and drop tables from a database using the DDL statements in Java applications.
R
Once the SQL statements are executed, a ResultSet object stores the result retrieved from a database.
-A
You can create various types of the ResultSet objects, such as read only, updatable, and forward only.
01
02
30
52
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
R
KA
R
SA
A
R
IT
R
-A
01
02
30
52
00
19
R
Creating Applications
Using Advanced Features
of JDBC
CHAPTER 10
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
You have learned how to insert, delete, and update database tables using the java.sql.Statement object.
However, by using this object, you can use only static values for insertion, updation, or deletion. Therefore,
to work with dynamic values, Java provides the java.sql.PreparedStatement object.
At times, while executing the transactions in database, all statements within the transaction should either
execute successfully or fail. To implement this functionality, Java provides database transaction
management. In addition, to improve the efficiency of the application, Java provides batch updates. Further,
to work with SQL procedures and functions, Java provides java.sql.CallableStatement. Thereafter, to
work with metadata of database and tables, Java provides java.sql.DatabaseMetaData and
java.sql.ResultSetMetaData.
R
creating application to use the metadata of database and tables.
KA
R
Objectives
SA
In this chapter, you will learn to:
Create applications using the PreparedStatement object A
R
IT
Manage database transactions
Implement batch updates in JDBC
R
-A
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Creating Applications Using the PreparedStatement
Object
Consider a scenario where New Publishers, a publishing house, maintains details about books and authors in
a database. The management of New Publishers wants an application that can help them access the details
about authors based on different criteria. For example, the application should be able to retrieve the details of
all the authors living in a particular city specified at runtime. In this scenario, you cannot use the Statement
object to retrieve the details because the value for the city needs to be specified at runtime. You need to use
the PreparedStatement object as it can accept runtime parameters.
The PreparedStatement interface is derived from the Statement interface and is available in the
R
java.sql package. The PreparedStatement object allows you to pass runtime parameters to the SQL
KA
statements to query and modify the data in a table.
The PreparedStatement objects are compiled and prepared only once by JDBC. The further invocation of
R
the PreparedStatement object does not recompile the SQL statements. This helps in reducing the load on
SA
the database server and improves the performance of the application.
The PreparedStatement interface inherits the following methods to execute the SQL statements from the
R
Statement interface:
-A
ResultSet executeQuery(): Is used to execute the SQL statement and returns the result in a
01
ResultSet object.
int executeUpdate(): Executes an SQL statement, such as INSERT, UPDATE, or DELETE, and
02
returns the count of the rows affected.
30
boolean execute(): Executes an SQL statement and returns the boolean value.
52
Consider an example where you have to retrieve the details of an author by passing the author id at runtime.
For this, the following SQL statement with a parameterized query can be used:
00
To submit such a parameterized query to a database from an application, you need to create a
R
PreparedStatement object using the prepareStatement() method of the Connection object. You can
use the following code snippet to prepare an SQL statement that accepts values at runtime:
The prepareStatement() method of the Connection object takes an SQL statement as a parameter. The
SQL statement can contain the symbol, ?, as a placeholder that can be replaced by input parameters at
runtime.
Before the SQL statement specified in the PreparedStatement object is executed, you must set the value
of each ? parameter. The value can be set by calling an appropriate setXXX() method, where XXX is the data
type of the parameter.
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
For example, consider the following code snippet:
stat.setString(1,"A001");
ResultSet result=stat.executeQuery();
In the preceding code snippet, the first parameter of the setString()method specifies the index value of
the ? placeholder, and the second parameter is used to set the value of the ? placeholder. You can use the
following code snippet when the value for the ? placeholder is obtained from the user interface:
stat.setString(1,aid.getText());
ResultSet result=stat.executeQuery();
In the preceding code snippet, the setString() method is used to set the value of the ? placeholder with
the value retrieved at runtime from the aid textbox of the user interface.
R
The PreparedStatement interface provides various methods to set the value of placeholders for the
KA
specific data types. The following table lists some commonly used methods of the PreparedStatement
interface.
R
SA
Method Description
void setBytes(int index, Sets the Java byte type array for the parameter
-A
void setBoolean(int index, Sets the Java boolean type value for the
boolean val)
02
void setDouble(int index, Sets the Java double type value for the
double val) parameter corresponding to the specified index.
52
void setLong(int index, long Sets the Java long type value for the parameter
R
void setFloat(int index, Sets the Java float type value for the parameter
float val) corresponding to the specified index.
void setShort(int index, Sets the Java short type value for the parameter
short val) corresponding to the specified index.
void setString(int index, Sets the Java String type value for the
String val) parameter corresponding to the specified index.
The Methods of the PreparedStatement Interface
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Retrieving Rows
You can use the following code snippet to retrieve the details of the books written by an author from the
Books table by using the PreparedStatement object:
R
}
KA
In the preceding code snippet, the str variable stores the SELECT statement that contains one input
parameter. The setString() method is used to set the value for the au_id attribute of the Books table.
R
The SELECT statement is executed using the executeQuery() method, which returns a ResultSet object.
SA
Inserting Rows
A
R
You can use the following code snippet to create a PreparedStatement object that inserts a row into the
IT
Authors table by passing the author’s data at runtime:
R
-A
ps.setString(1, "1001");
ps.setString(2, "Abraham White");
02
int rt=ps.executeUpdate();
30
In the preceding code snippet, the str variable stores the INSERT statement that contains two input
parameters. The setString() method is used to set the values for the au_id and au_name columns of the
52
Authors table. The INSERT statement is executed using the executeUpdate() method, which returns an
integer value that specifies the number of rows inserted into the table.
00
19
You can use the following code snippet to modify the state to CA where city is Oakland in the Authors
table by using the PreparedStatement object:
In the preceding code snippet, two input parameters, state and city, contain the values for the state and
city attributes of the Authors table, respectively.
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
You can use the following code snippet to delete a row from the Authors table, where au_name is Abraham
White by using the PreparedStatement object:
Just a minute:
R
Identity the three methods of the PreparedStatement interface.
KA
Answer:
R
The three methods of the PreparedStatement interface are:
SA
1. ResultSet executeQuery()
A
2. int executeUpdate() R
3. boolean execute()
IT
R
-A
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Managing Database Transactions
A transaction is a set of one or more SQL statements executed as a single unit. A transaction is complete only
when all the SQL statements in a transaction execute successfully. If any one of the SQL statements in the
transaction fails, the entire transaction is rolled back, thereby, maintaining the consistency of the data in the
database.
JDBC API provides the support for transaction management. For example, a JDBC application is used to
transfer money from one bank account to another. This transaction gets completed when the money is
deducted from the first account and added to the second. If an error occurs while processing the SQL
statements, both the accounts remain unchanged. The set of the SQL statements, which transfers money from
one account to another, represents a transaction in the JDBC application.
R
KA
The database transactions can be committed in the following two ways in the JDBC applications:
Implicit: The Connection object uses the auto-commit mode to execute the SQL statements implicitly.
R
The auto-commit mode specifies that each SQL statement in a transaction is committed automatically as
SA
soon as the execution of the SQL statement completes. By default, all the transaction statements in a
JDBC application are auto-committed.
Explicit: For explicitly committing a transaction statement in a JDBC application, you need to use the
A
setAutoCommit() method. This method accepts either of the two values, true or false, to set or
R
reset the auto-commit mode for a database. The auto-commit mode is set to false to commit a
IT
transaction explicitly. You can set the auto-commit mode to false using the following code snippet:
R
-A
con.setAutoCommit(false);
Committing a Transaction
30
52
When you set the auto-commit mode to false, the operations performed by the SQL statements are not
reflected permanently in a database. You need to explicitly call the commit() method of the Connection
00
interface to reflect the changes made by the transactions in a database. All the SQL statements that appear
between the setAutoCommit(false) method and the commit() method are treated as a single transaction
19
The rollback() method is used to undo the changes made in the database after the last commit operation.
You need to explicitly invoke the rollback() method to revert a database in the last committed state.
When the rollback() method is invoked, all the pending transactions of a database are cancelled and the
database gets reverted to the state in which it was committed previously. You can call the rollback()
method using the following code snippet:
con.rollback();
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
You can use the following code to create a transaction that includes two INSERT statements and the
transaction is committed explicitly using the commit() method:
import java.sql.*;
public class CreateTrans
{
public static void main(String arg[])
{
try
{
/*Initialize and load the Type 4 JDBC driver*/
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
R
try (Connection con =
KA
DriverManager.getConnection("jdbc:sqlserver://sqlserver01;databaseName=Librar
y;user=user1;password=password#1234");)
R
{
SA
/*Set the auto commit mode to false*/
con.setAutoCommit(false);
/*Create a transaction*/
try (PreparedStatement ps = con.prepareStatement("INSERT INTO
A
R
Publishers (pub_id, pub_name) VALUES (?, ?)");)
IT
{
/*Specify the value for the placeholders in the
R
PreparedStatement object*/
-A
ps.setString(1, "P006");
ps.setString(2, "Darwin Press");
01
committed");
30
prepareStatement() method*/
try (PreparedStatement ps2 = con.prepareStatement("INSERT
00
ps2.setString(1, "P007");
ps2.setString(2, "MainStream Publishing");
R
/*Commit a transaction*/
con.commit();
System.out.println("Transaction Committed, Please
check table for data");
}
}
}
}
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
catch (Exception e)
{
System.out.println("Error : " + e);
}
}
}
In the preceding code, the auto-commit mode is set to false using the setAutoCommit() method. All the
statements that are executed after setting the auto-commit mode to false are treated as a transaction by the
database.
R
KA
Just a minute:
How can you commit a transaction explicitly?
R
SA
Answer:
You can commit a transaction explicitly by setting the auto-commit mode to false
and using the commit() method.
A
R
IT
R
-A
01
02
30
52
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Implementing Batch Updates in JDBC
A batch is a group of update statements sent to a database to be executed as a single unit. You send the batch
to a database in a single request using the same Connection object. This reduces network calls between the
application and the database. Therefore, processing multiple SQL statements in a batch is a more efficient
way as compared to processing a single SQL statement.
Note
A JDBC transaction can consist of multiple batches.
R
KA
The Statement interface provides following methods to create and execute a batch of SQL statements:
R
void addBatch(String sql): Adds an SQL statement to a batch.
SA
int[] executeBatch(): Sends a batch to a database for processing and returns the total number of
rows updated.
void clearBatch(): Removes the SQL statements from the batch.
A
R
You can create a Statement object to perform batch updates. When the Statement object is created, an
IT
empty array gets associated with the object. You can add multiple SQL statements to the empty array for
executing them as a batch. You also need to disable the auto-commit mode using the
R
setAutoCommit(false) method while working with batch updates in JDBC. This enables you to roll back
-A
the entire transaction performed using a batch of updates if any SQL statement in the batch fails. You can use
01
con.setAutoCommit(false);
Statement stmt=con.createStatement();
30
In the preceding code snippet, con is a Connection object. The setAutoCommit() method is used to set
19
the auto-commit mode to false. The batch contains two INSERT statements that are added to the batch
using the addBatch() method.
R
The SQL statements in a batch are processed in the order in which the statements appear in a batch. You can
use the following code snippet to execute a batch of SQL statements:
int[] updcount=stmt.executeBatch();
In the preceding code snippet, updcount is an integer array that stores the values of the update count
returned by the executeBatch() method. The update count is the total number of rows affected when an
SQL statement is processed. The executeBatch() method returns the updated count for each SQL
statement in a batch, if it is successfully processed.
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Exception Handling in Batch Updates
The batch update operations can throw two types of exceptions, SQLException and
BatchUpdateException. The JDBC API methods, addBatch() and executeBatch(), throw
SQLException when any problem occurs while accessing a database. The SQLException exception is
thrown when you try to execute a SELECT statement using the executeBatch() method. The
BatchUpdateException class is derived from the SQLException class. The BatchUpdateException
exception is thrown when the SQL statements in the batch cannot be executed due to:
Presence of illegal arguments in the SQL statement.
Absence of the database table.
R
BatchUpdateException uses an array of the update count to identify the SQL statement that throws the
KA
exception. The update count for all the SQL statements that are executed successfully is stored in the array in
the same order in which the SQL statements appear in the batch. You can traverse the array of the update
R
count to determine the SQL statement that is not executed successfully in a batch. The null value in an
SA
array of the update count indicates that the SQL statement in the batch failed to execute. You can use the
following code to use the methods of the SQLException class that can be used to print the update counts for
the SQL statements in a batch by using the BatchUpdateException object:
A
import java.sql.*;
R
IT
public class BatchUpdate
R
{
-A
try
{
02
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Creating an Application to Insert Rows in a Table Using Batch Updates
You can execute multiple objects of the Statement and PreparedStatement interfaces together as
batches in a JDBC application using batch updates. You can use the following code to insert data in a table
using batch updates:
import java.sql.*;
R
/*Initialize and load Type 4 JDBC driver*/
KA
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
R
/*Connect to a data source using Library DSN*/
SA
try (Connection con =
DriverManager.getConnection("jdbc:sqlserver://sqlserver01;databaseName=Librar
y;user=user1;password=password#1234");
/*Create a Statement object*/
Statement stmt = con.createStatement();)
A
R
{
IT
con.setAutoCommit(false);
R
System.out.println("");
System.out.println("Using Statement object");
19
System.out.println("--------------------------");
for (int i = 0; i < results.length; i++)
R
{
System.out.println("Rows affected by " + (i + 1) + "
INSERT statement: " + results[i]);
}
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
/*Specify the value for the placeholders*/
ps.setString(1, "B007");
ps.setInt(2, 575);
ps.addBatch();
ps.setString(1, "B008");
ps.setInt(2, 350);
R
System.err.println("Rows affected by " + (i + 1) + "
KA
INSERT statement: " + numUpdates[i]);
}
R
/*Commit the INSERT statements in the batch*/
SA
con.commit();
A
} R
}
}
IT
catch (BatchUpdateException bue)
R
{
-A
catch (Exception e) {
System.out.println("Error : " + e);
52
}
}
00
}
19
In the preceding code, two batches are created using the Statement and PreparedStatement objects. The
INSERT statements are added to the batch using the addBatch() method and are executed using the
R
executeBatch() method. The executeBatch() method returns an array, which stores the update count
for all the SQL statements in the batch. You can display the number of rows affected by each SQL statement
in the batch using the for loop.
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Creating and Calling Stored Procedures in JDBC
The java.sql package provides the CallableStatement interface that contains various methods to
enable you to call database stored procedures. The CallableStatement interface is derived from the
PreparedStatement interface.
R
non parameterized.
KA
You can use the following code snippet to create a non parameterized stored procedure in a JDBC
application:
R
SA
String str = "CREATE PROCEDURE Authors_info "
+"AS "
+ "SELECT au_id,au_name "
+ "FROM Authors "
A
R
+ "WHERE city = 'Oakland' "
IT
+ "ORDER BY au_name";
Statement stmt=con.createStatement();
R
int rt=stmt.executeUpdate(str);
-A
In the preceding code snippet, the SELECT statement specifies that the data is retrieved from the Authors
01
table in the order of the au_name column. The Connection object con is used to send the CREATE
PROCEDURE SQL statement to a database. When you execute the code, the Authors_info stored procedure
02
You can use the following code snippet to create a parameterized stored procedure:
52
+ " AS "
+ " SELECT @auth_name=au_name, @auth_city=city, @auth_state=state "
R
In the preceding code snippet, the Authors_info_prmtz stored procedure is created that accepts the author
id as a parameter and retrieves the corresponding author information from the database. The retrieved
information is stored in the OUT parameters. The output keyword is used to represent OUT parameters.
A stored procedure can accept one or multiple parameters. A parameter of a stored procedure can take any of
the following forms:
IN: Refers to the argument that you pass to a stored procedure.
OUT: Refers to the return value of a stored procedure.
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
INOUT: Combines the functionality of the IN and OUT parameters. The INOUT parameter enables you to
pass an argument to a stored procedure. The same parameter can also be used to store a return value of a
stored procedure.
Note
When you use the stored procedures to perform database operations, it reduces
network traffic because instead of sending multiple SQL statements to a database, a
single stored procedure is executed.
R
Calling a Stored Procedure Without Parameters
KA
The Connection interface provides the prepareCall() method that is used to create the
R
CallableStatement object. This object is used to call a stored procedure of a database. The
SA
prepareCall() method is an overloaded method that has various forms. Some of the commonly used
forms are:
CallableStatement prepareCall(String str): Creates a CallableStatement object to call a
A
stored procedure. The prepareCall() method accepts a string as a parameter that contains an SQL
R
statement to call a stored procedure. You can also specify the placeholders to accept parameters in the
IT
SQL statement.
R
parameters:
02
String object: Contains an SQL statement to call a stored procedure. The SQL statement can
contain one or more parameters.
30
TYPE_SCROLL_INSENSITIVE, or TYPE_SCROLL_SENSITIVE.
00
returns a ResultSet object that has the specified result type, concurrency mode, and constant to set the
result set state.
The following signature is used to call a stored procedure without parameters:
exec <procedure_name>
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
You can use the following code snippet to call a stored procedure that does not accept parameters:
In the preceding code snippet, con is the Connection object that invokes the prepareCall() method. The
str variable contains the call to the Authors_info stored procedure, and this call is passed as a parameter
to the prepareCall() method.
R
KA
Calling a Stored Procedure with Parameters
R
SA
The SQL escape syntax is used to call a stored procedure with parameters. The SQL escape syntax is a
standard way to call a stored procedure from RDBMS and is independent of RDBMS. The driver searches
the SQL escape syntax in the code and converts the SQL escape syntax into the database compatible form.
A
There are two forms of the SQL escape syntax, one that contains result parameter and the other that does not
R
contain result parameters. Both the forms can take multiple parameters. If the SQL escape syntax contains a
IT
result parameter, the result parameter is used to return a value from a stored procedure. The result parameter
R
is an OUT parameter. Other parameters of the SQL escape syntax can contain the IN, OUT, or INOUT
-A
The placeholders are used to represent the IN, OUT, and INOUT parameters of a stored procedure in the
procedure call. The signature to call a stored procedure with parameters is:
30
{ call <procedure_name>(?) };
52
You need to set the value of the IN parameters before the CallableStatement object is executed.
00
Otherwise, SQLException is thrown while processing the stored procedure. The set methods are used to
specify the values for the IN parameters. The CallableStatement interface inherits the set methods from
19
the PreparedStatement interface. The signature to set the value of the IN parameter is:
R
<CallableStatement_object>.setInt(<value>);
In the preceding signature, the setInt() method is used to set the value for an integer type, IN parameter.
If the stored procedure contains the OUT and INOUT parameters, these parameters should be registered with
the corresponding JDBC types before a call to a stored procedure is processed. The JDBC types determine
the Java data types that are used in the get methods while retrieving the values of the OUT and INOUT
parameters. The registerOut() method is used to register the parameters. SQLException is thrown if the
placeholders, representing the OUT and INOUT parameters, are not registered.
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
The prototypes of the registerOut() method are:
registerOut(int index, int stype): Accepts the position of the placeholder and a constant in
the java.sql.Types class as parameters. The java.sql.Types class contains constants for various
JDBC types. For example, if you want to register the VARCHAR SQL data type, you should use the
STRING constant of the java.sql.Types class. You can use the following method call to the
registerOut() method to register a parameter:
cstmt.registerOutParameter(1, java.sql.Types.STRING);
registerOut(int index, int stype, int scale): Accepts the position of a placeholder, a
constant in the java.sql.Types class, and a scale of the value that is returned as parameters. You need
to define the scale of a parameter while registering numeric data types, such as NUMBER, DOUBLE, and
R
DECIMAL. For example, if you want to register the DECIMAL SQL data type that has three digits after
KA
decimal, the value for the scale parameter should be three. You can use the following code snippet to
specify the scale parameter while invoking the registerOut() method:
R
SA
cstmt.registerOutParameter(1, java.sql.Types.DECIMAL, 3);
You can use the prepareCall() method to call a stored procedure that accepts parameters. The
prepareCall() method returns a result after processing the SQL and control statements defined in the
procedure body. You can use the following code to call a stored procedure with parameters:
A
R
IT
import java.sql.*;
R
{
01
{
String id, name, address, city;
30
try
{
52
DriverManager.getConnection("jdbc:sqlserver://sqlserver01;databaseName=Librar
y;user=user1;password=password#1234");
/*Call a stored procedure*/
CallableStatement cstmt = con.prepareCall(str);)
{
/*Pass IN parameter*/
cstmt.setString(1, "A001");
/*Register OUT parameters*/
cstmt.registerOutParameter(2, Types.VARCHAR);
cstmt.registerOutParameter(3, Types.VARCHAR);
cstmt.registerOutParameter(4, Types.VARCHAR);
/*Process the stored procedure*/
cstmt.execute();
/*Retrieve Authors information*/
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
name = cstmt.getString(2);
address = cstmt.getString(3);
city = cstmt.getString(4);
/*Display author information*/
System.out.println("");
System.out.println("Displaying Author Information");
System.out.println("------------------------------");
System.out.println("First name: " + name);
System.out.println("Address: " + address);
System.out.println("City: " + city);
}
}
catch (Exception e)
R
{
KA
System.out.println("Error " + e);
}
}
R
}
SA
In the preceding code, the Authors_info_prmtz stored procedure is invoked. This stored procedure
accepts one IN type parameter and four OUT type parameters. The IN parameter is used to specify the id of an
A
author whose information you want to retrieve. The OUT parameters are used to retrieve the first name, last
R
name, address, and city of the authors. The setString() method is used to specify the author id, and the
IT
registerOut() method is used to register the OUT parameters.
R
-A
01
02
30
52
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Using Metadata in JDBC
Metadata is the information about data, such as structure and properties of table. For example, a database
contains the employee table that has the name, address, salary, designation, and department
columns. The metadata of the employee table includes certain information, such as names of the columns,
data type of each column, and constraints to enter data values in the columns. JDBC API provides the
following two metadata interfaces to retrieve the information about the database and the result set:
DatabaseMetaData
ResultSetMetaData
R
Using the DatabaseMetaData Interface
KA
The DatabaseMetaData interface provides the methods that enable you to determine the properties of a
R
database. These properties include names of database tables, database version, SQL keywords, and isolation
SA
levels of the data stored in the database.
You can create an object of DatabaseMetaData using the getMetaData() method of the Connection
A
interface. You can use the following code snippet to create an object of the DatabaseMetaData interface:
R
IT
DatabaseMetaData dm=con.getMetaData();
R
In the preceding code snippet, con refers to an object of the Connection interface.
-A
The methods declared in the DatabaseMetaData interface retrieve the database-specific information. The
01
following table lists some commonly used methods of the DatabaseMetaData interface.
02
Method Description
30
52
String column_name)
R
String getDriverName() Retrieves the name of the JDBC driver for the
DatabaseMetaData object.
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Method Description
R
boolean Returns a boolean value that indicates whether the
KA
supportsSavepoints() database supports savepoints.
R
The Methods of the DatabaseMetaData Interface
SA
The methods in the DatabaseMetaData interface retrieve information about the database to which a Java
application is connected. You can use the following code to retrieve and display the names of various
database tables by using the methods of the DatabaseMetaData interface:
A
R
IT
import java.sql.*;
R
{
public static void main(String args[])
01
{
try {
02
DriverManager.getConnection("jdbc:sqlserver://sqlserver01;databaseName=Librar
y;user=user1;password=password#1234");)
00
{
/*Create a DatabaseMetaData object*/
19
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
catch (Exception e)
{
System.out.println("Error : " + e);
}
}
}
In the preceding code, a connection is established with the Library data source. The object of the
DatabaseMetaData interface is declared using the getMetaData() method. The DatabaseMetaData
object is used to retrieve the names of database tables using the getTables() method.
R
KA
The ResultSetMetaData interface contains various methods that enable you to retrieve information about
the data in a result set, such as numbers, names, and data types of the columns. The ResultSet interface
R
provides the getMetaData() method to create an object of the ResultSetMetaData interface. You can
use the following code snippet to create an object of the ResultSetMetaData interface:
SA
ResultSetMetaData rm=rs.getMetaData();
A
In the preceding code snippet, rs refers to an object of the ResultSet interface. rs calls the
R
getMetaData() method to create an object of the ResultSetMetaData interface.
IT
The following table lists some commonly used methods of the ResultSetMetaData interface.
R
-A
01
Method Description
02
String getColumnName(int
19
int getColumnType(int Retrieves the SQL data type of the table column
column_index) corresponding to the specified index.
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Method Description
R
column_index) the ResultSet column corresponding to the
KA
specified index is writeable.
R
The Methods of the ResultSetMetaData Interface
SA
A
R
Just a minute:
IT
What are the metadata interfaces used to retrieve information about the database and
R
Answer:
01
02
The metadata interfaces used to retrieve information about the database and the result
set are:
30
1. DatabaseMetaData
52
2. ResultSetMetaData
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Practice Questions
1. The ________ interface provides the methods that enable you to determine the properties of a database
or RDBMS.
2. Identify the method of the PreparedStatement interface that sets the Java byte type value for the
parameter corresponding to the specified index.
a. setByte(int index, byte val)
b. setBytes(int index, byte[] val)
c. setString(int index, String val)
R
d. setShort(int index, short val)
KA
3. Why do you need to disable the auto-commit mode while working with batch updates?
R
SA
4. Which is a standard way to call a stored procedure from RDBMS?
5. Which method of the Connection interface is used to create the callableStatement object?
a. A
prepareCall()
R
IT
b. getMetaData()
c.
R
prepareStatement()
-A
d. createStatement()
01
02
30
52
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Summary
In this chapter, you learned that:
The PreparedStatement object allows you to pass runtime parameters to the SQL statements using
the placeholders.
There can be multiple placeholders in a single SQL statement. An index value is associated with each
placeholder depending upon the position of the placeholder in the SQL statement.
The placeholder stores the value assigned to it until the value is explicitly changed.
A transaction is a set of one or more SQL statements executed as a single unit. A transaction is complete
only when all the SQL statements in a transaction are successfully executed.
R
If the setAutoCommit() method is set to true, the database operations performed by the SQL
KA
statements are automatically committed in the database.
The commit() method reflects the changes made by the SQL statements permanently in the database.
R
The rollback() method is used to undo the effect of all the SQL operations performed after the last
SA
commit operation.
A batch is a group of update statements sent to a database to be executed as a single unit. You send the
batch to a database as a single request using the same Connection object.
A
R
The executeBatch() method returns an integer array that stores the update count for all the SQL
IT
statements that are executed successfully in a batch. The update count is the number of database rows
R
Batch update operations can throw two types of exceptions, SQLException and
BatchUpdateException.
01
SQLException is thrown when the database access problem occurs. SQLException is also thrown
02
BatchUpdateException is thrown when the SQL statement in the batch cannot be executed due to the
problem in accessing the specified table or presence of illegal arguments in the SQL statement.
52
The CallableStatement interface contains various methods that enable you to call the stored
procedures from a database.
00
The parameters of a stored procedure can take any of the following three forms:
19
IN
R
OUT
INOUT
Metadata is the information about data, such as the structure and properties of table.
JDBC API provides two metadata interfaces to retrieve the information about the database and result set,
DatabaseMetaData and ResultSetMetaData.
The DatabaseMetaData interface declares the methods that enable you to determine the properties of a
database.
The ResultSetMetaData interface declares the methods that enable you to determine the information
of a result set.
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
The getMetaData() method of the Connection interface enables you to obtain the objects of the
DatabaseMetaData interface. The methods in the DatabaseMetaData interface retrieve the
information only about the database to which a Java application is connected.
The getMetaData() method of the ResultSet interface enables you to create the instance of the
ResultSetMetaData interface.
R
KA
R
SA
A
R
IT
R
-A
01
02
30
52
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Glossary
BufferedOutputStream Class
A
The BufferedOutputStream class writes bytes
Anonymous Inner Class to an output stream using a buffer for increased
An anonymous inner class has no name, and it is efficiency.
either a subclass of a class or an implementer of BufferedReader Class
an interface.
The BufferedReader class is used to read the
text from a character-input stream, such as a file,
R
Atomic Operation
console, and array, while buffering characters.
KA
An atomic operation is an operation that is
performed as a single unit. In addition, an atomic BufferedWriter Class
R
operation cannot be stopped in between by any
The BufferedWriter class can be used to write
SA
other operations.
text to an output stream.
Atomic Variables
Atomic variables are the single variables on
A
which operations, such as increment and
R
C
IT
decrement, are done in a single step.
R
The auto-commit mode specifies that each SQL CLI is an interface consists of functions written in
the C language to access databases.
01
statement completes.
Concurrency enables Java programmers to
30
B programs.
00
Batch Cursor
19
A batch is a group of update statements sent to a Cursor enables you to move through the rows
database to be executed as a single unit. stored in the ResultSet object.
R
Buffer
A buffer is a storage area in the memory that can
be used for writing or reading data. As compared D
to streams, buffers can be used to provide faster Data Source Information
I/O operations.
Data Source Information contains the database
BufferedInputStream Class information, such as the location of the database
The BufferedInputStream class is used to server, name of a database, user name, and
perform the read operations by using a temporary password, to access a database server.
storage, buffer, in the memory.
NIIT G.1
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Deadlock
G
The deadlock condition arises in a computer
Generics
system when two threads wait for each other to
complete the operations before performing the Generics mean parameterized types that enable
individual action. you to write the code that can work with many
types of object.
Doubly-linked List
The doubly-linked list is a set of sequentially
linked records called nodes where each node
contains two links that are the references of the I
previous node and the next node in the sequence, Implicit Casting
respectively.
R
Implicit casting refers to an automatic conversion
Downcasting of one data type into another.
KA
Downcasting is usually done along the class Inner Classes
R
hierarchy in a direction from the base class
towards the derived classes. Inner classes are the classes defined inside
SA
another class.
E A
R
L
IT
Explicit Casting
R
Lock Starvation
Explicit casting occurs when one data type cannot
-A
be implicitly converted into another data type. Lock starvation occurs when the execution of a
thread is postponed because of its low priority.
01
02
F
30
M
FileInputStream Class
52
Metadata
The FileInputStream class is used to read data
and the steams of bytes from the file. Metadata is the information about data, such as
00
FileOutputStream Class
Method-local Inner
The FileOutputStream class is used for
R
writing data, byte by byte, to a file. A method-local inner is a class defined inside the
method of the enclosing class.
FileReader Class
The FileReader class is used for reading
characters from a file, but it does not define any
method of its own.
O
FileWriter Class Open Database Connectivity (ODBC)
The FileWriter class writes character data to a ODBC is an open standard API to communicate
file. with databases.
G.2 NIIT
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Type Parameter
R
The type parameter section is represented by
Regular Expressions
angular brackets, < >, that can have one or more
Regular expressions allow you to match a types of parameters separated by commas.
character sequence with another string.
Regular Inner Class
A regular inner class is a class whose definition U
appears inside the definition of another class. Upcasting
Upcasting is usually done along the class
hierarchy in a direction from the derived class to
R
S the base class.
KA
Semaphore
A semaphore is a lock with an internal counter. It
R
is used to restrict access to shared resources by X
SA
multiple threads at the same time. XOPEN
Static Inner Classes The XOPEN error code is a standard message
Static inner classes are inner classes marked with A
associated with an error that can identify the error
R
the static modifier. across multiple databases.
IT
R
Symbolic Link
-A
T
52
Task
A task is an object that implements the Runnable
00
or Callable interface.
19
Thread
R
NIIT G.3
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Objectives Attainment Feedback
Programming in Java
The objectives of this course are listed below. Please tick whether the objectives were achieved by you or
not. Calculate the percentage at the end, fill in your name and batch details, and return the form to your
R
coordinator.
KA
R
S. No. Objectives Yes No
SA
1. Explore UI components
A
R
2. Manage layouts
IT
R
4. Implement events
02
6. Implement localization
00
8. Implement type-safety
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
S. No. Objectives Yes No
R
17. Implement concurrency
KA
R
18. Get familiar with NIO
SA
19. Perform the read and write operations on a file
A
R
20. Identify the layers in the JDBC architecture
IT
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
R
KA
R
SA
A
R
IT
R
-A
01
02
30
52
00
19
R
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.