Java Programming Activity Book
Java Programming Activity Book
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
Activity Book
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur 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/AB/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 – ACTIVITY BOOK
Table of Contents
Chapter
Activity
Problem Statement
R
KA
Prerequisite
R
Solution
SA
Exercises
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.
Table of Contents
R
Chapter 2 – Implementing Inner Classes
KA
R
Activity 2.1: Creating Inner Classes ------------------------------------------------ 2.2
SA
Problem Statement ------------------------------------------------------------------ 2.2
Solution ------------------------------------------------------------------------------ 2.2
Exercises ---------------------------------------------------------------------------------- 2.4
A
Exercise 1 ---------------------------------------------------------------------------- 2.4
R
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 5 – Working with Collections
R
KA
Activity 6.1: Implementing Threads in Java -------------------------------------- 6.2
R
Problem Statement ------------------------------------------------------------------ 6.2
SA
Solution ------------------------------------------------------------------------------ 6.2
Exercises ---------------------------------------------------------------------------------- 6.5
Exercise 1 ---------------------------------------------------------------------------- 6.5
A
Exercise 2 ---------------------------------------------------------------------------- 6.5
R
IT
Concurrency
01
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.
Chapter 9 – Introduction to JDBC
R
JDBC
KA
R
Activity 10.1: Creating an Application that Uses the
SA
PreparedStatement Object----------------------------------------------------------- 10.2
Problem Statement ----------------------------------------------------------------- 10.2
A
Solution ----------------------------------------------------------------------------- 10.3
R
Activity 10.2: Creating an Application to Determine the Structure
IT
of a Table -------------------------------------------------------------------------------- 10.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.
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.
Exercises
Exercise 1
Mark has been assigned a task to design the complaint form, as shown in the following figure.
R
KA
Department: ________________________________
R
Name of Immediate Supervisor: __________________________
SA
Problem Category: _____ Infrastructure ______ Food ______ Cab ______ Work Environment
A
Please describe the details of your grievances:
R
IT
____________________________________________________________________
____________________________________________________________________
R
-A
_____________________________________________________________________
_____________________________________________________________________
02
30
For this, he needs to identify the best suitable components and write a program for the same. Help Mark to
achieve the preceding requirement.
00
19
Note
R
You need to create the class of exercise 1 inside the package, chapter01, in the
application, Exercises.
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
Exercise 2
Create a GUI application that implements a simple arithmetic calculator. The application must have two
input text boxes and an additional text box that will be read-only. In addition, the application must have
command buttons for arithmetic functions, such as addition, subtraction, multiplication, and division.
The user will enter two numbers in the input text boxes and will click any arithmetic function command
button. Once the button is clicked, the result should be displayed in the third text box.
Note
You need to create the classes of exercise inside the package, chapter01, in the
application Exercises.
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
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.
Activity 2.1: Creating Inner Classes
Problem Statement
Mellos Inc. is a software development company. The company has received an assignment to develop an
aptitude assessment application. The management of the company has assigned this task to Mike, the Senior
Developer of the company. In the initial phase, Mike needs to create a class that accepts the candidate details,
such as name, qualification, and age. In addition, he needs to validate the age of the candidate who can
appear for the test. The age of the candidate must range between 21 and 25. Further, Mike needs to logically
R
group the class, so that each class provides its own functionality. Help Mike in achieving the preceding tasks.
KA
Solution
R
SA
To achieve the preceding requirements, Mike needs to perform the following steps:
1. Create a Java application, InnerClassDemo.
2. Create a package, details, in the Java application, InnerClassDemo.
A
3. Create a class, Candidates, inside the package, details.
R
IT
4. Replace the code in the [Link] file with the following code:
R
package details;
import [Link].*;
-A
name=[Link]();
[Link]("Enter your qualification:");
00
qualification=[Link]();
[Link]("Enter your age:");
19
age=[Link]();
AgeValidation obj=new AgeValidation();
R
[Link]();
}
private class AgeValidation{
public void validateAge(){
if(age>=21 && age<=25){
status="selected";
}
else{
status="rejected";
}
}
}
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur 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 printCandiatesDetails(){
[Link]("Name: "+name);
[Link]("Qualification: "+qualification);
[Link]("Age: "+age);
[Link]("Selection Status: "+status);
}
public static void main(String args[]){
Candidates candidate=new Candidates();
[Link]();
[Link]();
}
}
R
5. Compile and execute the InnerClassDemo Java application.
KA
After executing the application, the following output is displayed:
R
Enter your name:
SA
Once you provide the name as Andrew, the following output is displayed:
A
Enter your qualification: R
Once you provide the qualification as MBA, the following output is displayed:
IT
R
Once you provide the age as 23, the following output is displayed:
01
Name: Andrew
Qualification: MBA
02
Age: 23
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.
Exercises
Exercise 1
Write a program to display a frame. In addition, you need to handle the movement of the mouse by using an
anonymous inner class, so that the position of the mouse pointer is displayed by a label inside the frame.
Note
You need to create the classes of the exercise 1 inside the package, chapter02, inside
R
the application, Exercises.
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.
Activity 3.1: Implementing Localization
Problem Statement
You need to develop a puzzle game application that supports various languages, such as French and English,
so that it can be used in different countries, such as France and US. In the initial phase, you only need to
design a localized menu for the game application.
Prerequisite
R
KA
To perform the activity, you need to use the [Link] and [Link] files.
R
Solution
SA
To achieve the preceding requirements, you need to perform the following steps:
1. Create a Java application, LocalizationApp.
A
2. Create a package, localize, in the application, LocalizationApp. R
3. Create a class, Puzzle, inside the package, localize.
IT
4. Open the [Link] file.
R
5. Replace the code in the [Link] file with the code in the [Link] file.
-A
10. Add the following code after the //French Language comment:
19
11. Add the following code after the //Language Conversion comment:
b1 = new JButton([Link]("PlayGame"));
b2 = new JButton([Link]("ViewInstructions"));
b3 = new JButton([Link]("Exit"));
[Link]([Link]("Puzzle"));
JLabel l = new JLabel([Link]("Puzzle"));
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
12. Create a MessagesBundle_en.properties resource bundle outside the package but within the application
and type the following data:
13. Create a MessagesBundle_fr.properties resource bundle outside the package but within the application
and type the following data:
Puzzle Réflexion
PlayGame jouer le jeu
R
ViewInstructions voir directives
KA
Exit quitter
Puzzle Réflexion
R
SA
14. Compile and execute the LocalizationApp application.
After executing the application, the following output is displayed:
A
R
IT
R
-A
01
02
30
Once you select the langauge as French, the following output is displayed:
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.
Exercises
Exercise 1
Write a program that accepts a Web portal name from the user. In addition, the program should validate the
format of the Web portal name. The Web portal name should have the following fields:
Protocol, such as https or http.
Domain, such as xyz.
The top level domain should be more than one character, such as .co.
R
Exercise 2
KA
Sam needs to write a program to localize the date according to the locale, such as France and US. This
program should provide the following functionalities:
R
A menu should be displayed to the user that allows the selection of the locale.
SA
On the basis of the locale selected by the user, the date should be localized and displayed to the user.
A
R
IT
Note
You need to create the classes of the exercises, 1 and 2, inside the package,
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.
Activity 4.1: Working with Generics
Problem Statement
Futuristic Inc. is a leading software development organization based in the US. After analysing the
communication system of the organization, the management has decided to develop a messaging application
for the internal communication. For this, the management has asked Sam, the Senior Software Developer, to
develop the application. The management wants the application code to be simple. Sam decides to implement
R
the following functionalities to develop the application:
KA
The application should display a menu. Using the menu, the user should be able to select either of the
two options, SMS or email.
R
On the selection of the SMS option, the user should be asked to enter the cell phone number and
SA
message.
On the selection of the email option, the user should be asked to enter the email id and message.
A
After entering the required details, the sent message should be processed. R
In the initial phase, Sam needs to design the application to implement a handling mechanism that provides
IT
the SMS and email services. In addition, to initially test this functionality, he needs to process the sent
R
message by appending the date and displaying the same. Help Sam to achieve the preceding requirements.
-A
Prerequisite
01
To perform the activity, you need to use the [Link] and [Link] files.
02
Solution
30
To achieve the preceding requirements, Sam needs to perform the following steps:
52
package messenger;
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
5. Create a class, SMSMessage, in the package, messenger.
6. Replace the code in the [Link] file with the following code:
package messenger;
R
}
}
KA
7. Create a class, MessageProcessor, in the package, messenger.
R
SA
8. Open the [Link] file.
9. Replace the code in the [Link] file with the code in the [Link] file.
10. Add the following code snippet after the comment, //Import Package, in the
[Link] file:
A
R
IT
import [Link];
R
-A
11. Replace the comment, //Type Parameter, in the [Link] with the following code
snippet:
01
<X>
02
30
12. Add the following code snippet after the comment, //Generic Variable, in the
[Link] file:
52
private X message;
00
19
13. Add the following code snippet after the comment, //Generic Constructor, in the
[Link] file:
R
public MessageProcessor(X a1 )
{
message = a1;
}
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
14. Add the following code snippet after the comment, //Processing Logic, in the
[Link] file:
R
Object messageValue = [Link](message);
KA
[Link]("=======================================");
R
[Link]("Message: " + messageValue + " sent to " +
SA
receiverValue + " was submitted for processing at " + new
[Link]().toString());
}
A
catch (Exception ex)
{
R
[Link]();
IT
}
R
}
-A
01
Note
The Field class and the getDeclaredField() method of the Class class are the
02
part of Reflection API that are used to get the information of a field of a class. The
30
17. Replace the code in the [Link] file with the code in the [Link] file.
18. Add the following code snippet after the comment, //SMS Method, in the [Link] file:
R
[Link]("=======================================");
[Link]("Enter the contact no: ");
contact = [Link]();
[Link]("\nEnter the message: ");
message = [Link]();
SMSMessage sObj = new SMSMessage(contact, message);
MessageProcessor<SMSMessage> message1 = new MessageProcessor<>(sObj);
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
[Link]();
19. Add the following code snippet after the comment, //Email Method, in the [Link] file:
[Link]("=======================================");
[Link]("Enter the email id: ");
email = [Link]();
R
[Link]("\nEnter the message: ");
KA
message = [Link]();
EmailMessage eObj = new EmailMessage(email, message);
R
MessageProcessor<EmailMessage> message2 = new MessageProcessor<>(eObj);
SA
[Link]();
}
A
20. Compile and execute the MessagingApplication Java application. After executing the application, the
R
following output is displayed:
IT
---------Menu---------
R
1. SMS
-A
2. Email
3. Exit
01
Once you provide the option as, 1, the following output is displayed:
30
=======================================
52
Once you provide the contact no, such as 8767875698, the following output is displayed:
19
Once you provide the message, such as Hello, the following output is displayed:
=======================================
Message: Hello sent to 8767875698 was submitted for processing at Sat Jun 15
07:11:46 IST 2013
Note
Date and time may vary according to the execution date and 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.
Exercises
Exercise 1
Mark needs to create the ToDoList application. In the initial phase, he has decided to design the application
to maintain a track of the list of daily tasks to be completed. For this, Mark has decided to create the
following Java classes in the application:
Task: Will store and display the basic details for both the types of tasks, event and meeting.
Event: Will inherit the Task class and contain the information of an event.
Meeting: Will inherit the Task class and contain the information of a meeting.
R
TaskProcessor: Will be a generic class that will accept an object of the class that is inherited from the
KA
Task class. In addition, it will process the tasks, event or meeting.
ToDoList: Will provide a user interface that will allow a user to create an event or meeting by providing
R
the name and time, which is greater than the current time. In addition, it will allow a user to view the
SA
created To Do list.
Help Mark to achieve the preceding requirements.
A
R
Note
IT
You need to create the class of the exercise, 1, inside the package, chapter04, in the
R
application, Exercises.
-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.
Activity 5.1: Working with Collections
Problem Statement
Turbin Inc. is a leading software development organization based in the US. The organization has got a new
client deal to develop the Phone Book application. The management has asked Bob, the Senior Software
Developer, to develop the application. The management wants the application code to be simple. In addition,
the Phone Book application should be a standalone application. Bob decides to implement the following
functionalities in the application:
R
The application should display a menu. Using the menu, the user will be able to select either of the two
KA
options, add contact or view contact.
R
On the selection of the add contact option, the user will be presented with the interface to enter the name
SA
and contact number of a person.
On selecting the Add button, the details must be added to the database. However, Bob has decided to
store the contact details in the collections before storing them in the database.
A
On the selection of the view contact option, the user will be presented with the list of contacts. The list
R
of contact will be displayed in the form of a list box.
IT
The user will be able to view the contact details by double-clicking the contact name.
R
-A
In the initial phase, Bob needs to design the user interface and store the contact details in the collections.
Help Bob to achieve the preceding functionalities.
01
Prerequisite
02
To perform the activity, you need to use the [Link], [Link], and [Link] files.
30
52
Solution
To achieve the preceding functionalities, Bob needs to perform the following steps:
00
import [Link];
import [Link];
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
10. Add the following code snippet after the comment, //Collection Variable in the
[Link] file:
TreeSet<Contact> contactList;
11. Add the following code snippet after the comment, //Sorting Classes in the [Link]
file:
R
}
KA
}
class NameSort implements Comparator<Contact>
R
{
SA
public int compare(Contact c1, Contact c2)
{
return [Link]().compareTo([Link]());
A
} R
}
IT
12. Add the following code snippet after the comment, //Collection Initialization in the
R
[Link] file:
-A
01
13. Add the following code snippet after the comment, //Action Performed Event in the
[Link] file:
30
if ([Link]("") || ([Link]("")))
19
{
[Link](jf_AddContact, "Please fill the details
R
[Link](obj);
dlm_contact.removeAllElements();
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur 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 (Contact c : tempList)
{
dlm_contact.addElement(c);
}
txt_name.setText("");
txt_cno.setText("");
R
if (status == 0)
KA
{
jf_AddContact.setVisible(true);
}
R
else
SA
{
jf_AddContact.dispose();
}
A
} R
IT
14. Add the following code snippet after the comment, //Mouse Clicked Event in the [Link]
R
file:
-A
if ([Link]() == jl_contact)
01
{
JList l = (JList) [Link]();
02
if ([Link]() == 2)
{
30
{
String name = [Link]();
00
String no = [Link]();
String info = "Name is: " + name + "\nContact No is: " + no;
19
}
}
}
AddContact addContObj;
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
19. Add the following code snippet after the comment, //Action Performed Event in the [Link]
file:
if([Link]() == btn_add)
{
[Link]();
}
else if([Link]() == btn_view)
{
[Link]();
}
20. Compile and execute the PhoneBookApplication Java application. After executing the application, the
R
following output is displayed:
KA
R
SA
A
R
IT
R
-A
01
02
30
Once you click the Add Contact button, the following output is displayed:
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.
Once you enter the name, Peter Parker, in the Enter Name text box and number, 87483747, in the Enter
Contact No text box, and then click the Add button, the following output is displayed:
R
KA
R
SA
The Output of the PhoneBookApplication Application
A
Once you click the OK button, the following output is displayed: 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.
Once you click the No button, the following output is displayed:
R
KA
R
SA
The Output of the PhoneBookApplication Application
Once you click the View Contact button, the following output is displayed:
A
R
IT
R
-A
01
02
30
52
00
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 you double-click Peter Parker, the following output is displayed:
R
KA
R
SA
The Output of the PhoneBookApplication Application
Click the OK button and close the application.
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.
Exercises
Exercise 1
James works as the Software Developer at AxisPro Technologies. He has been assigned the task to create the
Fill in the Blanks game for kids. The menu of the game should provide the following options:
1. Play
2. View Instructions
3. Quit
Thereafter, James wants to implement the following functionalities:
R
On selecting the Play option:
KA
The game should provide a list of categories, such as countries, fruits, and animals.
R
The player will have to create his/her own customized list of one or more categories.
SA
The game should randomly select a category from the customized list, and then a word should be
chosen randomly from that category and displayed in the form of blanks.
The player will have to correctly guess an alphabet for each of the blanks.
A
R
The game should display an appropriate message when the player correctly guesses all the blanks
and wins the game.
IT
On selecting the View Instructions option, the instructions of the game should be displayed.
R
In the initial phase, James needs to create a game with a list of three categories only. Help James to achieve
the preceding functionalities.
02
30
Note
52
You need to create the classes of the exercise, 1, inside the package, chapter05, in the
application, Exercises.
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.
Activity 6.1: Implementing Threads in Java
Problem Statement
Create a GUI-based Java application that simulates the working of the traffic lights by using threads. The
GUI should be similar to the interface, as shown in the following figure.
R
KA
R
SA
A
R
IT
R
-A
01
1. Initially, when the application is executed, only the RED light must be ON.
30
2. After 3 seconds, the RED light should turn OFF and only the GREEN light should turn ON for 5
seconds.
52
3. Then, the GREEN light should turn OFF and only the YELLOW light should turn ON for 2 seconds.
00
Prerequisite
To perform the activity, you need to use the [Link] file.
Solution
To achieve the preceding requirements, you need to perform the following steps:
1. Create a Java application, ImplementingThreads.
2. Create a package, signal, in the application, ImplementingThreads.
3. Create a class, SignalDemo, inside the package, signal.
4. Open the [Link] file.
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
5. Replace the code in the [Link] file with the code in the [Link] file.
6. Replace the //implements runnable comment with implements Runnable in the
[Link] file.
7. Add the following code after the //Add run() method comment:
R
[Link]([Link]);
KA
for( int i=3;i>0;i--)
{
R
String s = [Link](i);
[Link](s+" - Stop - ");
SA
[Link](1000);
A
[Link]([Link]);
R
IT
[Link]([Link]);
[Link]([Link]);
R
{
String s = [Link](i);
01
[Link](s+" - Go - ");
[Link](1000);
02
}
30
[Link]([Link]);
[Link]([Link]);
52
[Link]([Link]);
for( int i=2;i>0;i--)
00
{
19
String s = [Link](i);
[Link](s+" - Get Slow - ");
R
[Link](1000);
}
}
}
catch(InterruptedException e)
{
[Link](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.
8. Add the following code after the //create task comment:
R
KA
R
SA
A
R
IT
The Output
R
-A
01
02
Note
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.
Exercises
Exercise 1
Create a Java program that creates two threads namely ThreadA and ThreadB. Moreover, you need to ensure
that the execution of the threads occurs in such a way that the main method is exited only after both the
threads have executed. Furthermore, both the threads should be assigned a sleep time of 5 seconds. The
output should be displayed in the following format:
Thread A starts
Thread A in for loop, i = 1
Thread A in for loop, i = 2
R
Thread A in for loop, i = 3
KA
Thread A in for loop, i = 4
Thread A in for loop, i = 5
Thread A in for loop, i = 6
R
Thread A in for loop, i = 7
SA
Thread A in for loop, i = 8
Thread A in for loop, i = 9
Thread A in for loop, i = 10
A
Thread A exits R
Thread A sleeping for 5 seconds
Thread B starts
IT
Thread B in for loop, i = 1
R
Thread B exits
Thread B sleeping for 5 seconds
00
Exercise 2
R
Write a GUI-based application and implement threads to create a notification ticker that will display the
message, !!..Congratulations..!!, on the frame. The message should scroll from left to right on the frame.
Then, the message should also scroll backwards from right to left. The message scroll must continue
infinitely.
Note
You need to create the classes of the exercises, 1 and 2, inside the package, chapter06,
in the application, Exercises.
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur 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.
Activity 7.1: Implementing Synchronization
Problem Statement
Write an application to simulate the vehicles crossing a toll bridge on a motorway. You need to simulate the
environment for five vehicles that are approaching the bridge and tollbooth. The vehicles are numbered from
one to five.
The vehicles have to go through the following five stages:
R
Start the journey
KA
Arrive at the toll
Enter the tollbooth
R
SA
Exit the tollbooth
Cross the bridge
A
The vehicles can be in any of the stages in parallel, except the third stage, as only one vehicle can enter the
R
tollbooth at a time. The simulation should be performed by creating one thread for each vehicle.
IT
Solution
R
To achieve the preceding requirements, you need to perform the following steps:
-A
package simulation;
import [Link];
00
{
private int id; // id identifies each vehicle
R
private static TollBooth toll = new TollBooth(); // only one toll booth
public Vehicle(int id)
{
// each vehicle has a different identifying number
[Link] = id;
}
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
[Link](this); // current vehicle uses toll booth
travel(Rnd); // time taken to cross bridge
[Link]("Vehicle "+(id+1)+" has crossed the bridge");
}
R
{
KA
for (int k=0; k < limit; k++)
{// do nothing
};
R
}
SA
}
}
A
class TollBooth R
{
boolean inUse;
IT
R
public TollBooth()
-A
{
inUse = false;
01
}
02
while (true)
{
52
if (inUse == false)
{
00
synchronized (this)
{ inUse=true;
19
[Link]("Vehicle
"+([Link]()+1)+" enters toolbooth");
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.
public class Simulate
{
private static int noOfVehicles = 5;
private static Vehicle[] vehicles;
public static void main(String[] args)
{
try
{
Simulate sm=new Simulate();
vehicles=new Vehicle[5];
for(int i=0;i<noOfVehicles;i++)
{
vehicles[i]=new Vehicle(i);
Thread t = new Thread(vehicles[i]);
R
[Link]();
KA
[Link](10);
}
}
R
catch (Exception ex)
SA
{
[Link](ex);
A
} R
}
}
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.
Note
The preceding output can vary as the order of thread execution cannot be determined.
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.
Exercises
Exercise 1
Create a Java program that creates two threads namely Thread1 and Thread2. You need to create a method
that prints a table for a specified integer up to 10 numbers. Thread1 should print the table of 2 and Thread2
should print the table of 4. The table values must be printed with a delay of 1 second. You need to ensure that
only one thread at a time can print the table. Further, the name of the thread that is printing the table should
be displayed.
Exercise 2
R
Create a Java program that creates two runnable tasks, Display 1 to 10 and Display 11 to 20. The Display 1
KA
to 10 task should print the numbers in the range of 1 to 10 inside a loop. The task, Display 11 to 20, should
print the numbers in the range of 11 to 20 inside a loop. Implement the preceding tasks by using an executor
R
service. Ensure that the executor service is shutdown.
SA
Note
A
You need to create the classes of the exercises, 1 and 2, inside the package, chapter07,
R
in the application, Exercises.
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.
,
Problem Statement
Steve is a programmer in Global Systems Inc. He has been assigned a task to create a Java application that
stores the following details about the computer products in a text file:
Product ID
Product name
R
Product price
KA
In the preceding list, Product ID and Product name should accept a string value. Product price should accept
R
an integer value.
SA
In addition, the application should store the following details about the shops that sell a product:
Shop ID
A
Shop name R
Address
IT
In the preceding list, Shop ID should accept an integer value. Shop name and Address should accept a string
R
value.
-A
As the details are added, they must be appended in the [Link] file located in the D:\Details
01
directory. Further, you need to maintain the most recent copy of the preceding file in the D:\Backup directory
to ensure a backup.
02
Prerequisite
30
You need to create the Details and Backup folders in the D:\ drive of your computer.
52
Solution
00
To achieve the preceding requirements, Steve needs to perform the following steps:
19
package details;
import [Link];
import [Link];
import [Link];
import [Link].*;
import [Link];
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur 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 class ComputerProducts {
R
}
KA
public void enterProductDetails() throws IOException {
Scanner input = new Scanner([Link]);
R
[Link]("Enter the product ID: ");
SA
prid = [Link]();
[Link]("Enter the product name: ");
pname = [Link]();
A
[Link]("Enter the product price: "); R
price = [Link]();
sprid = prid;
IT
iprice = price;
R
sprice = [Link]();
-A
printprodDetails();
enterShopDetails();
01
}
02
int id = [Link]();
[Link]("Enter the shop name: ");
00
name = [Link]();
[Link]("Enter the address: ");
19
address = [Link]();
iid = id;
R
sid = [Link]();
[Link]("Do you want to add more shop details: (Y/N) ");
Scanner shopchoice = new Scanner([Link]);
String sch;
sch = [Link]();
switch ([Link]()) {
case "Y":
printshopDetails();
enterShopDetails();
break;
case "N":
printshopDetails();
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
//printDetails();
[Link]("Do you want to continue to add product
details: (Y/N) ");
Scanner choice = new Scanner([Link]);
String ch;
ch = [Link]();
switch ([Link]()) {
case "Y":
enterProductDetails();
break;
case "N":
[Link](0);
R
break;
KA
default:
[Link]("Invalid entry!");
break;
R
}
SA
break;
default:
[Link]("Invalid entry!");
A
break; R
}
}
IT
R
[Link], [Link])) {
[Link]("==========");
02
[Link]();
[Link]("Product ID: " + sprid + "\n");
30
[Link]();
[Link]("Product Name: " + pname + "\n");
52
[Link]();
[Link]("Product price: " + sprice + "\n");
00
[Link]();
[Link]();
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
ComputerProducts obj = new ComputerProducts();
KA
[Link]();
}
}
R
SA
5. Compile and execute the GlobalSystems Java application.
After executing the application, the following output is displayed:
A
Enter the product ID:
R
IT
Once you enter the product id as M1, the following output is displayed:
R
-A
Once you enter the product name as Mouse, the following output is displayed:
02
Once you enter the shop id as 131, the following output is displayed:
00
Once you enter the name as Technosolutions, the following output is displayed:
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
Further, you can enter Y or N to enter more shop and product details.
Note
After executing the preceding application, if the application skips any of the inputs, you
need to recompile and execute the application.
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.
Exercises
Exercise 1
You need to create a GUI-based file searching application. The application should enable the user to input
the name of the file to be searched. Then, on clicking the search button, the file should be searched in the D:\
drive of the computer. Further, the appropriate search results must be displayed to the user.
Note
R
You need to create the class of the exercise, 1, inside the package, chapter08, in the
KA
application, Exercises.
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
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.
Activity 9.1: Creating a JDBC Application to
Query a Database
Problem Statement
Create an application to retrieve information (author ID, name, and city) about the authors who are living in
the city where the city name begins with the letter, S.
Prerequisite
R
You need to ensure that the Library database exists and comprises the Authors table. In addition, the
KA
structure of the Authors table should be similar to the structure, as shown in the following figure.
R
SA
A
R
IT
R
-A
01
Solution
30
To achieve the preceding requirements, you need to perform the following steps:
1. Create a Java application, Library.
52
package book;
import [Link].*;
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur 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 (Connection con =
[Link]("jdbc:sqlserver://localhost;
databaseName=Library;user=sa;password=password@123");
Statement stmt = [Link]();)
{
ResultSet rs = [Link](str);
while ([Link]())
{
String id = [Link]("au_id");
String name = [Link]("au_name");
R
String city = [Link]("city");
KA
[Link](id + "\t");
if ([Link]() <= 7)
R
{
SA
[Link](name + "\t\t");
}
else
A
{ R
[Link]("\t" + name + "\t");
}
IT
[Link](city);
R
}
-A
}
}
01
[Link]("Error occurred");
[Link]("Error:" + ex);
30
}
}
52
}
00
19
Note
R
You need to specify the credentials in the preceding code, as per the configuration of
SQL Server on your computer.
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
6. Compile and execute the Library Java application. After executing the application, the following output
is displayed:
Note
The preceding output may vary according to the existing values in the Authors table of
the Library database.
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.
Exercises
Exercise 1
The City library maintenance officer wants to view the names of the books along with their respective author
names. Write a program to show the preceding details.
Note
You need to create the classes of the exercise, 1, inside the package, chapter09, in the
application, Exercises.
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
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.
Activity 10.1: Creating an Application that
Uses the PreparedStatement Object
Problem Statement
The management of City library has decided to computerize the book inventory. The library management has
assigned the preceding task to a leading software development company of the US. The Lead Analyst has
assigned the development of the Book Inventory application to Mark, the Senior Software Developer.
However, in the initial phase, Mark has decided to create an interface that will allow a user to add the details
of a new publisher to the publishers table, as shown in the following figure.
R
KA
R
SA
A
R
IT
R
-A
01
02
30
52
00
19
Prerequisite
You need to ensure that the Library database exists and comprises the Publishers table.
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur 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 structure of the Publishers table should be similar to the structure, as shown in the following figure.
R
The Structure of the Publishers Table
KA
Solution
R
SA
To achieve the preceding requirements, Mark needs to perform the following steps:
1. Create a Java application, BookInventory.
2. Add the jar file, [Link], in the BookInventory Java application.
3. Create a package, inventory, in the Java application, BookInventory.
A
R
IT
4. Create a class, PublisherInfo, in the package, inventory.
5. Replace the code in the [Link] file with the following code:
R
-A
package inventory;
01
import [Link];
import [Link];
02
import [Link].*;
import [Link].*;
30
52
Connection con;
Statement stmt;
PreparedStatement stat;
ResultSet rs;
JPanel p1;
JFrame f1;
public PublisherInfo()
{
try
{
[Link]("[Link]");
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
con =
[Link]("jdbc:sqlserver://localhost;databaseName=Library;
user=sa;password=password@123");
stmt = [Link]();
}
catch (Exception e)
{
[Link]("Error : " + e);
}
}
R
f1 = new JFrame("PUBLISHERS");
KA
p1 = new JPanel();
heading = new JLabel("PUBLISHERS INFORMATION");
lpubid = new JLabel("Publishers ID:");
R
lpub_name = new JLabel("Publishers Name:");
SA
lphone = new JLabel("Phone Number:");
laddress = new JLabel("Address:");
lcity = new JLabel("City:");
A
lstate = new JLabel("State:"); R
lzip = new JLabel("Zip:");
IT
pub_idField = new JTextField(6);
R
[Link](null);
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.
[Link](75, 180, 200, 30);
[Link](400, 180, 250, 25);
[Link](laddress);
[Link](addressField);
R
KA
[Link](75, 270, 200, 30);
[Link](400, 270, 200, 25);
[Link](lzip);
R
[Link](zipField);
SA
[Link](175, 350, 100, 30);
[Link](325, 350, 100, 30);
A
[Link](insert); R
[Link](exit);
IT
[Link](p1);
R
[Link](680, 500);
-A
[Link](true);
[Link](JFrame.EXIT_ON_CLOSE);
01
[Link](this);
02
[Link](this);
}
30
{
if ([Link]() == "Exit")
00
{
[Link](0);
19
}
R
if ([Link]() == "Insert")
{
if(!pub_idField.getText().equals(""))
{
try
{
stat = [Link]("INSERT INTO Publishers VALUES(?,
?, ?, ?, ?,?, ?)");
String pid = pub_idField.getText();
String pname = pub_nameField.getText();
String pphone = [Link]();
String padd = [Link]();
String pcity = [Link]();
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur 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 pstate = [Link]();
String pzip = [Link]();
[Link](1, pid);
[Link](2, pname);
[Link](3, pphone);
[Link](4, padd);
[Link](5, pcity);
[Link](6, pstate);
[Link](7, pzip);
[Link]();
pub_idField.setText("");
R
pub_nameField.setText("");
KA
[Link]("");
[Link]("");
[Link]("");
R
[Link]("");
SA
[Link]("");
[Link](f1, "Information has been
inserted.", "Information", JOptionPane.INFORMATION_MESSAGE);
A
} R
catch (Exception e)
{
IT
R
if([Link]().equals(msg))
01
{
[Link](f1, "Record already
02
pub_nameField.setText("");
[Link]("");
52
[Link]("");
[Link]("");
00
[Link]("");
[Link]("");
19
}
R
}
}
else
{
[Link](f1, "Please fill the details
properly.", "Error Message", JOptionPane.ERROR_MESSAGE);
}
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur 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[])
{
PublisherInfo p = new PublisherInfo();
[Link]();
}
}
Note
You need to specify the credentials in the preceding code, as per the configuration of
SQL Server on your computer.
R
KA
6. Compile and execute the BookInventory Java application. After executing the application, the output is
R
displayed, as shown in the following figure.
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.
8. Click the Insert button. The output is displayed, as shown in the following figure.
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.
Activity 10.2: Creating an Application to
Determine the Structure of a Table
Problem Statement
The Manager of the New Publishers publishing company often requires the information regarding the tables
of the company’s database. However, he is not familiar with the SQL statements. Therefore, he has asked
Jane, the Software Developer, to create an application that will help him to determine the total number of
columns and the data types of the columns of a given table. In addition, Jane needs to ensure that the table
name should be specified at runtime.
R
KA
Prerequisite
R
You need to ensure that the Library database exits and comprises tables, such as Authors, Books, and
SA
Publishers.
Solution
To achieve the preceding requirements, Jane needs to perform the following steps:
A
R
1. Create a Java application, NewPublishers.
IT
2. Add the jar file, [Link], in the NewPublishers Java application.
R
5. Replace the code in the [Link] file with the following code:
02
package metadata;
30
import [Link].*;
52
import [Link];
00
String tablename;
try
{
[Link]("[Link]");
This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur Centre , issued on 07/02/2019.
No Part of this book may be distributed or transferred to anyone in any form by any means.
tablename = [Link]();
String str = "SELECT * FROM " + tablename + " ";
try (Statement stmt = [Link]();)
{
ResultSet rs = [Link](str);
ResultSetMetaData rsmd = [Link]();
[Link]();
[Link]("==================================");
[Link]("Number of Attributes in the " +
tablename + " table: " + [Link]());
[Link]("");
[Link]("----------------------------------");
[Link]("Attributes of the " + tablename + "
R
Table");
KA
[Link]("----------------------------------");
R
{
SA
[Link]([Link](i) + " : " +
[Link](i));
}
A
}
R
}
IT
}
R
catch (Exception e)
-A
{
[Link]("Error : " + e);
01
}
}
02
}
30
52
Note
00
You need to specify the credentials in the preceding code, as per the configuration of
SQL Server on your computer.
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.
6. Compile and execute the NewPublishers Java application. After executing the application, the following
output is displayed:
Once you provide the table name as, Publishers, the following output is displayed:
==================================================================
Number of Attributes in the Publishers table: 7
-------------------------------------
Attributes of the Publishers Table
-------------------------------------
pub_id : varchar
R
pub_name : varchar
KA
phone : varchar
address : varchar
R
city : varchar
state : varchar
SA
zip : varchar
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.
Exercises
Exercise 1
The management of Park Library has decided to automate the task of managing the author’s details in a
database. For this, the library management has assigned the task to a leading software development company
of the US. The Senior Software Developer has assigned the development of the Author Management
application to Jessica, the Junior Software Developer. For this application, Jessica needs to implement the
functionality to view, insert, update, and delete an author’s information. Help Jessica to achieve the
preceding requirement.
R
KA
Note
You need to create the classes of the exercise, 1, inside the package, chapter10, in the
R
application, Exercises..
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.
In the `Library` and `BookInventory` applications, JDBC connectivity is established by loading the JDBC driver class using `Class.forName` and creating a connection to the database using `DriverManager.getConnection`. The database URL, user credentials, and driver details are specified to connect and execute SQL queries. The jar file `sqljdbc4-2.0.jar` is added to the applications to enable SQL Server connectivity . These steps ensure that the applications can interact with the database to perform operations like querying and updating records .
Storing contact details in collections before a database, as in Bob's Phone Book application, allows for efficient in-memory operations, such as sorting and searching, without the overhead of database operations . Collections like `TreeSet<Contact>` allow sorting with a comparator, enabling efficient retrieval and ordering of contacts. However, direct database storage facilitates persistent data storage and concurrent access, which is absent in volatile collections. Both methods, however, can maintain a list of contacts and ensure data integrity with proper management .
In the Phone Book application, mouse events are used to display contact details by detecting double clicks on a contact name in a `JList`. The `MouseListener` checks if the `clickCount` equals two, which signifies a double-click. Upon detecting the event, it retrieves the selected contact's details and displays them in a message dialog . This approach leverages event listening to enhance user interaction, allowing users to easily access detailed information on demand .
The user interface of the `BookInventory` application includes design elements like text fields for user input (e.g., Publisher ID, Name) and JButton for actions (e.g., insert data). These elements interact with backend database operations via the `PreparedStatement` object, offering real-time data entry and manipulation . The design ensures that entries can be verified before submission, reducing data entry errors and supporting structured data management with back-end validation .
In the `AuthorsInfo` class, SQL exception handling is implemented using a `try-catch` block. The code includes database connection and query execution within a try block, catching any `SQLExceptions` and printing error messages if an exception occurs . This ensures that the application can handle database connectivity issues or query failures gracefully, preventing the application from crashing and providing informative diagnostic output .
Using generics in the `MessageProcessor` class, as indicated by type parameter `<X>`, allows for type safety and flexibility by enabling the class to process various types of messages without explicit type casting . Generics enable compile-time type checking, preventing runtime errors due to incompatible types, and promote code reuse across different message types. This abstraction reduces redundancy and potential bugs associated with casting and allows a single `MessageProcessor` class to handle different message types uniformly .
The Reflection API in Java can be used to access private fields by obtaining the field object using `Class.getDeclaredField(String name)` method. Once the field object is obtained, you can make it accessible using `Field.setAccessible(true)`. In the `MessageProcessor.java` example, the `Field` class and `getDeclaredField()` method are used to retrieve the private fields 'receiver' and 'message' of a class, enabling their values to be accessed and printed .
The `Phone Book` application utilizes `TreeSet<Contact>` to manage contacts by automatically sorting them based on a comparator (e.g., `ContactSort` or `NameSort`). `TreeSet` is appropriate because it maintains a naturally ordered contact set, enabling efficient retrieval and display operations due to its self-balancing tree structure . This ensures that the insertion and lookup operations are performed in `O(log n)` time complexity, making it ideal for applications demanding sorted data .
Using a `TreeSet` with custom comparators in the Phone Book application allows for efficient, sorted contact management, impacting performance favorably by leveraging the `TreeSet`'s inherent characteristics. Custom comparators like `ContactSort` and `NameSort` dictate sorting logic, allowing for different orderings based on contact number or name . This feature aids rapid access and reliability in presenting ordered data, achieving `O(log n)` operation time, which is crucial for maintaining responsive performance in applications that handle frequent insertion and retrieval of elements .
The use of `PreparedStatement` in the `BookInventory` application enhances database operations by allowing precompilation of SQL queries, reducing parsing time, and offering protection against SQL injection attacks . Unlike a simple `Statement`, `PreparedStatement` supports parameterized queries, improving efficiency by reusing the same query structure with different input parameters. This also results in better performance and security when interacting with the database, particularly for repeated insertions or updates .