Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

ProgramminginJava-ActivityBook

The document is a personal copy of an activity book titled 'Programming in Java' issued to ARITRA SARKAR from NIIT Kolkata Jadavpur Centre on 07/02/2019. It contains various chapters and exercises focusing on Java programming concepts such as user interface design, inner classes, localization, generics, collections, threads, JDBC, and more. The book emphasizes that no part of it may be reproduced or distributed without permission.

Uploaded by

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

ProgramminginJava-ActivityBook

The document is a personal copy of an activity book titled 'Programming in Java' issued to ARITRA SARKAR from NIIT Kolkata Jadavpur Centre on 07/02/2019. It contains various chapters and exercises focusing on Java programming concepts such as user interface design, inner classes, localization, generics, collections, threads, JDBC, and more. The book emphasizes that no part of it may be reproduced or distributed without permission.

Uploaded by

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

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

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

All software is used for educational purposes only.


-A
01
02
30
52
00
19
R

Programming in Java/AB/18-M08-V1.0
Copyright ©NIIT. All rights reserved.

No part of this publication may be reproduced, stored in retrieval


system or transmitted in any form, or by any means, electronic,
mechanical, photocopying, recording or otherwise, without the
prior written permission of the publisher.

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur 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

Chapter 1 – Designing a User Interface and Handling Events

Exercises ---------------------------------------------------------------------------------- 1.2


Exercise 1 ---------------------------------------------------------------------------- 1.2
Exercise 2 ---------------------------------------------------------------------------- 1.3

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

Chapter 3 – Working with Localization


R
-A
01

Activity 3.1: Implementing Localization ------------------------------------------- 3.2


Problem Statement ------------------------------------------------------------------ 3.2
02

Solution ------------------------------------------------------------------------------ 3.2


30

Exercises ---------------------------------------------------------------------------------- 3.4


52

Exercise 1 ---------------------------------------------------------------------------- 3.4


Exercise 2 ---------------------------------------------------------------------------- 3.4
00
19

Chapter 4 – Working with Generics


R

Activity 4.1: Working with Generics ------------------------------------------------ 4.2


Problem Statement ------------------------------------------------------------------ 4.2
Solution ------------------------------------------------------------------------------ 4.2
Exercises ---------------------------------------------------------------------------------- 4.6
Exercise 1 ---------------------------------------------------------------------------- 4.6

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur 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

Activity 5.1: Working with Collections --------------------------------------------- 5.2


Problem Statement ------------------------------------------------------------------ 5.2
Solution ------------------------------------------------------------------------------ 5.2
Exercises ---------------------------------------------------------------------------------- 5.9
Exercise 1 ---------------------------------------------------------------------------- 5.9

Chapter 6 – Working with Threads

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

Chapter 7 – Implementing Thread Synchronization and


R
-A

Concurrency
01
02

Activity 7.1: Implementing Synchronization -------------------------------------- 7.2


Problem Statement ------------------------------------------------------------------ 7.2
30

Solution ------------------------------------------------------------------------------ 7.2


52

Exercises ---------------------------------------------------------------------------------- 7.6


00

Exercise 1 ---------------------------------------------------------------------------- 7.6


Exercise 2 ---------------------------------------------------------------------------- 7.6
19
R

Chapter 8 – Working with NIO Classes and Interfaces

Activity 8.1: Performing File Operations Using NIO ---------------------------- 8.2


Problem Statement ------------------------------------------------------------------ 8.2
Solution ------------------------------------------------------------------------------ 8.2
Exercises ---------------------------------------------------------------------------------- 8.7
Exercise 1 ---------------------------------------------------------------------------- 8.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.
Chapter 9 – Introduction to JDBC

Activity 9.1: Creating a JDBC Application to Query a Database ------------- 9.2


Problem Statement ------------------------------------------------------------------ 9.2
Solution ------------------------------------------------------------------------------ 9.2
Exercises ---------------------------------------------------------------------------------- 9.5
Exercise 1 ---------------------------------------------------------------------------- 9.5

Chapter 10 – Creating Applications Using Advanced Features of

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

Problem Statement ----------------------------------------------------------------- 10.9


-A

Solution ----------------------------------------------------------------------------- 10.9


Exercises -------------------------------------------------------------------------------- 10.12
01

Exercise 1 -------------------------------------------------------------------------- 10.12


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

Designing a User Interface


and Handling Events
CHAPTER 1

NIIT Introduction to Object-Oriented Programming 1.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.
Exercises
Exercise 1
Mark has been assigned a task to design the complaint form, as shown in the following figure.

Employee Name: ____________ Employee ID: __________________

Sex: _____ Male ______ Female


Email: _______________________ Contact No.:______________________

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

Please list the settlement you are requesting:


01

_____________________________________________________________________
_____________________________________________________________________
02
30

The Complaint Form


52

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.

1.2 Designing a User Interface and Handling Events 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.
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

NIIT Designing a User Interface and Handling Events 1.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.
R
KA
R
SA
A
R
IT
R
-A
01
02
30
52
00
19
R

Implementing Inner
Classes
CHAPTER 2

NIIT Introduction to Object-Oriented Programming 1.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.
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 Candidates.java file with the following code:
R

package details;
import java.util.*;
-A

public class Candidates {


01

private String name, qualification, status;


private int age;
02

public void getCandiatesDetails(){


30

Scanner sc=new Scanner(System.in);


System.out.println("Enter your name:");
52

name=sc.next();
System.out.println("Enter your qualification:");
00

qualification=sc.next();
System.out.println("Enter your age:");
19

age=sc.nextInt();
AgeValidation obj=new AgeValidation();
R

obj.validateAge();
}
private class AgeValidation{
public void validateAge(){
if(age>=21 && age<=25){
status="selected";
}
else{
status="rejected";
}

}
}

2.2 Implementing Inner Classes 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.
public void printCandiatesDetails(){
System.out.println("Name: "+name);
System.out.println("Qualification: "+qualification);
System.out.println("Age: "+age);
System.out.println("Selection Status: "+status);
}
public static void main(String args[]){
Candidates candidate=new Candidates();
candidate.getCandiatesDetails();
candidate.printCandiatesDetails();

}
}

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

Enter your age:


-A

Once you provide the age as 23, the following output is displayed:
01

Name: Andrew
Qualification: MBA
02

Age: 23
30

Selection Status: selected


52
00
19
R

NIIT Implementing Inner Classes 2.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.
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

2.4 Implementing Inner Classes 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.
R
KA
R
SA
A
R
IT
R
-A
01
02
30
52
00
19
R

Working with Localization


CHAPTER 3

NIIT Introduction to Object-Oriented Programming 1.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.
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 Puzzle.txt and GameWindow.txt 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 Puzzle.txt file.
R

5. Replace the code in the Puzzle.java file with the code in the Puzzle.txt file.
-A

6. Create a class, GameWindow, inside the package, localize.


01

7. Open the GameWindow.txt file.


8. Replace the code in the GameWindow.java file with the code in the GameWindow.txt file.
02

9. Add the following code after the //English Language comment:


30

currentLocale= new Locale("en", "US");


52

messages = ResourceBundle.getBundle("MessagesBundle", currentLocale);


00

10. Add the following code after the //French Language comment:
19

currentLocale= new Locale("fr", "FR");


R

messages = ResourceBundle.getBundle("MessagesBundle", currentLocale);

11. Add the following code after the //Language Conversion comment:

b1 = new JButton(messages.getString("PlayGame"));
b2 = new JButton(messages.getString("ViewInstructions"));
b3 = new JButton(messages.getString("Exit"));
f.setTitle(messages.getString("Puzzle"));
JLabel l = new JLabel(messages.getString("Puzzle"));

3.2 Working with Localization 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.
12. Create a MessagesBundle_en.properties resource bundle outside the package but within the application
and type the following data:

PlayGame Play Game


ViewInstructions View Instructions
Exit Exit
Puzzle Puzzle

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

The Output of the LocalizationApp Application


52

Once you select the langauge as French, the following output is displayed:
00
19
R

The Output of the LocalizationApp Application

NIIT Working with Localization 3.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.
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

chapter03, inside the application, Exercises.


-A
01
02
30
52
00
19
R

3.4 Working with Localization 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.
R
KA
R
SA
A
R
IT
R
-A
01
02
30
52
00
19
R

Working with Generics


CHAPTER 4

NIIT Introduction to Object-Oriented Programming 1.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.
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 MessageProcessor.txt and MainClass.txt files.
02

Solution
30

To achieve the preceding requirements, Sam needs to perform the following steps:
52

1. Create a Java application, MessagingApplication.


00

2. Create a package, messenger, in the Java application, MessagingApplication.


19

3. Create a class, EmailMessage, in the package, messenger.


4. Replace the code in the EmailMessage.java file with the following code:
R

package messenger;

public class EmailMessage


{
public String receiver, message;

public EmailMessage(String receiver, String message)


{
this.receiver = receiver;
this.message = message;
}
}

4.2 Working with Generics 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.
5. Create a class, SMSMessage, in the package, messenger.
6. Replace the code in the SMSMessage.java file with the following code:

package messenger;

public class SMSMessage


{
public String receiver, message;

public SMSMessage(String receiver, String message)


{
this.receiver = receiver;
this.message = message;

R
}
}

KA
7. Create a class, MessageProcessor, in the package, messenger.

R
SA
8. Open the MessageProcessor.txt file.
9. Replace the code in the MessageProcessor.java file with the code in the MessageProcessor.txt file.
10. Add the following code snippet after the comment, //Import Package, in the
MessageProcessor.java file:
A
R
IT
import java.lang.reflect.Field;
R
-A

11. Replace the comment, //Type Parameter, in the MessageProcessor.java with the following code
snippet:
01

<X>
02
30

12. Add the following code snippet after the comment, //Generic Variable, in the
MessageProcessor.java file:
52

private X message;
00
19

13. Add the following code snippet after the comment, //Generic Constructor, in the
MessageProcessor.java file:
R

public MessageProcessor(X a1 )
{
message = a1;
}

NIIT Working with Generics 4.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.
14. Add the following code snippet after the comment, //Processing Logic, in the
MessageProcessor.java file:

public void printResult()


{
try
{
Field receiverField =
message.getClass().getDeclaredField("receiver");

Object receiverValue = receiverField.get(message);

Field messagefield = message.getClass().getDeclaredField("message");

R
Object messageValue = messagefield.get(message);

KA
System.out.println("=======================================");

R
System.out.println("Message: " + messageValue + " sent to " +

SA
receiverValue + " was submitted for processing at " + new
java.util.Date().toString());
}

A
catch (Exception ex)
{
R
ex.printStackTrace();
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

reflected field may be a class (static) field or an instance field.


52

15. Create a class, MainClass, in the package, messenger.


00

16. Open the MainClass.txt file.


19

17. Replace the code in the MainClass.java file with the code in the MainClass.txt file.
18. Add the following code snippet after the comment, //SMS Method, in the MainClass.java file:
R

public void getSMSDetails()


{
Scanner sc = new Scanner(System.in);
String contact, message;

System.out.println("=======================================");
System.out.print("Enter the contact no: ");
contact = sc.nextLine();
System.out.print("\nEnter the message: ");
message = sc.nextLine();
SMSMessage sObj = new SMSMessage(contact, message);
MessageProcessor<SMSMessage> message1 = new MessageProcessor<>(sObj);

4.4 Working with Generics 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.
message1.printResult();

19. Add the following code snippet after the comment, //Email Method, in the MainClass.java file:

public void getEmailDetails()


{
Scanner sc = new Scanner(System.in);
String email, message;

System.out.println("=======================================");
System.out.print("Enter the email id: ");
email = sc.nextLine();

R
System.out.print("\nEnter the message: ");

KA
message = sc.nextLine();
EmailMessage eObj = new EmailMessage(email, message);

R
MessageProcessor<EmailMessage> message2 = new MessageProcessor<>(eObj);

SA
message2.printResult();
}

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

Choose the option (1/2/3):


02

Once you provide the option as, 1, the following output is displayed:
30

=======================================
52

Enter the contact no:


00

Once you provide the contact no, such as 8767875698, the following output is displayed:
19

Enter the message:


R

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.

NIIT Working with Generics 4.5

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur 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

4.6 Working with Generics 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.
R
KA
R
SA
A
R
IT
R
-A
01
02
30
52
00
19
R

Working with Collections


CHAPTER 5

NIIT Introduction to Object-Oriented Programming 1.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.
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 Contact.txt, AddContact.txt, and Menu.txt files.
30
52

Solution
To achieve the preceding functionalities, Bob needs to perform the following steps:
00

1. Create a Java application, PhoneBookApplication.


19

2. Create a package, phonebook, in the Java application, PhoneBookApplication.


R

3. Create a class, Contact, in the package, phonebook.


4. Open the Contact.txt file.
5. Replace the code in the Contact.java file with the code in the Contact.txt file.
6. Create a class, AddContact, in the package, phonebook.
7. Open the AddContact.txt file.
8. Replace the code in the AddContact.java file with the code in the AddContact.txt file.
9. Add the following code snippet after the comment, //Import Packages in the AddContact.java
file:

import java.util.Comparator;
import java.util.TreeSet;

5.2 Working with Collections 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.
10. Add the following code snippet after the comment, //Collection Variable in the
AddContact.java file:

TreeSet<Contact> contactList;

11. Add the following code snippet after the comment, //Sorting Classes in the AddContact.java
file:

class ContactSort implements Comparator<Contact>


{
public int compare(Contact c1, Contact c2)
{
return c1.getNo().compareTo(c2.getNo());

R
}

KA
}
class NameSort implements Comparator<Contact>

R
{

SA
public int compare(Contact c1, Contact c2)
{
return c1.getName().compareTo(c2.getName());

A
} R
}
IT

12. Add the following code snippet after the comment, //Collection Initialization in the
R

AddContact.java file:
-A
01

contactList = new TreeSet<Contact>(new ContactSort());


02

13. Add the following code snippet after the comment, //Action Performed Event in the
AddContact.java file:
30

String name = txt_name.getText();


52

String cno = txt_cno.getText();


00

if (name.equals("") || (cno.equals("")))
19

{
JOptionPane.showMessageDialog(jf_AddContact, "Please fill the details
R

properly", "Warning Message", JOptionPane.WARNING_MESSAGE);


}
else
{
Contact obj = new Contact();
obj.setName(name);
obj.setNo(cno);

contactList.add(obj);

ArrayList<Contact> tempList = new ArrayList<Contact>(contactList);


Collections.sort(tempList, new NameSort());

dlm_contact.removeAllElements();

NIIT Working with Collections 5.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.
for (Contact c : tempList)
{
dlm_contact.addElement(c);
}

txt_name.setText("");
txt_cno.setText("");

JOptionPane.showMessageDialog(jf_AddContact, "Contact has been added",


"Success Message", JOptionPane.INFORMATION_MESSAGE);
int status = JOptionPane.showConfirmDialog(jf_AddContact, "Do you want to add
more contacts?", "Confirmation", JOptionPane.YES_NO_OPTION,
JOptionPane.WARNING_MESSAGE);

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 AddContact.java
R

file:
-A

if (e.getSource() == jl_contact)
01

{
JList l = (JList) e.getSource();
02

if (e.getClickCount() == 2)
{
30

Contact o = (Contact) l.getSelectedValue();


if (o != null)
52

{
String name = o.getName();
00

String no = o.getNo();
String info = "Name is: " + name + "\nContact No is: " + no;
19

JOptionPane.showMessageDialog(jf_AddContact, info, "Contact


Details", JOptionPane.INFORMATION_MESSAGE);
R

}
}
}

15. Create a class, Menu, in the package, phonebook.


16. Open the Menu.txt file.
17. Replace the code in the Menu.java file with the code in the Menu.txt file.
18. Add the following code snippet after the comment, //AddContact Object in the Menu.java file:

AddContact addContObj;

5.4 Working with Collections 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.
19. Add the following code snippet after the comment, //Action Performed Event in the Menu.java
file:

if(e.getSource() == btn_add)
{
addContObj.addComponentToAdd();
}
else if(e.getSource() == btn_view)
{
addContObj.addComponentToView();
}

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

The Output of the PhoneBookApplication Application


52

Once you click the Add Contact button, the following output is displayed:
00
19
R

The Output of the PhoneBookApplication Application

NIIT Working with Collections 5.5

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur 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

The Output of the PhoneBookApplication Application

5.6 Working with Collections 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.
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

The Output of the PhoneBookApplication Application


R

NIIT Working with Collections 5.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.
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

5.8 Working with Collections 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.
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

 On selecting the Quit option, the game must be terminated.


-A
01

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

NIIT Working with Collections 5.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.
R
KA
R
SA
A
R
IT
R
-A
01
02
30
52
00
19
R

Working with Threads


CHAPTER 6

NIIT Introduction to Object-Oriented Programming 1.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.
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

The Traffic Lights GUI


The application must fulfill the following requirements:
02

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

4. Then, the YELLOW light should turn RED.


19

5. The preceding process should continue, infinitely.


6. You also need to display the remaining time for each light.
R

Prerequisite
To perform the activity, you need to use the SignalDemo.txt 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 SignalDemo.txt file.

6.2 Working with Threads 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.
5. Replace the code in the SignalDemo.java file with the code in the SignalDemo.txt file.
6. Replace the //implements runnable comment with implements Runnable in the
SignalDemo.java file.
7. Add the following code after the //Add run() method comment:

public void run()


{
try
{
while(true)
{
red.setBackground(Color.red);
yellow.setBackground(Color.GRAY);

R
green.setBackground(Color.GRAY);

KA
for( int i=3;i>0;i--)
{

R
String s = Integer.toString(i);
show.setText(s+" - Stop - ");

SA
Thread.sleep(1000);

A
yellow.setBackground(Color.GRAY);
R
IT
green.setBackground(Color.GREEN);
red.setBackground(Color.GRAY);
R

for( int i=5;i>0;i--)


-A

{
String s = Integer.toString(i);
01

show.setText(s+" - Go - ");
Thread.sleep(1000);
02

}
30

yellow.setBackground(Color.YELLOW);
green.setBackground(Color.GRAY);
52

red.setBackground(Color.GRAY);
for( int i=2;i>0;i--)
00

{
19

String s = Integer.toString(i);
show.setText(s+" - Get Slow - ");
R

Thread.sleep(1000);
}
}
}
catch(InterruptedException e)
{
System.out.println(e);

}
}

NIIT Working with Threads 6.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.
8. Add the following code after the //create task comment:

Thread task = new Thread(signal);


task.start();

9. Compile and execute the ImplementingThreads application.


After executing the application, the following output is displayed:

R
KA
R
SA
A
R
IT
The Output
R
-A
01
02

Note
30

The preceding output sequence will continue indefinitely.


52
00
19
R

6.4 Working with Threads 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.
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 in for loop, i = 2


-A

Thread B in for loop, i = 3


Thread B in for loop, i = 4
01

Thread B in for loop, i = 5


Thread B in for loop, i = 6
02

Thread B in for loop, i = 7


Thread B in for loop, i = 8
30

Thread B in for loop, i = 9


Thread B in for loop, i = 10
52

Thread B exits
Thread B sleeping for 5 seconds
00

Exit from the main thread


19

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.

NIIT Working with Threads 6.5

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur 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

NIIT Introduction to Object-Oriented Programming 1.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.
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

1. Create a Java application, MotorwaySimulation.


01

2. Create a package, simulation, in the application, MotorwaySimulation.


02

3. Create a class, Simulate, inside the package, simulation.


30

4. Replace the code in Simulate.java with the following code:


52

package simulation;
import java.util.Random;
00

class Vehicle implements Runnable


19

{
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
this.id = id;
}

public void run()


{
System.out.println("Vehicle "+(id+1)+" starts journey");
Random RandGen = new Random();
int Rnd = RandGen.nextInt(100);
travel(Rnd); // time taken from starting point to toll booth
System.out.println("Vehicle "+(id+1)+" arrives at the toll");

7.2 Implementing Thread Synchronization and Concurrency 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.
toll.useToll(this); // current vehicle uses toll booth
travel(Rnd); // time taken to cross bridge
System.out.println("Vehicle "+(id+1)+" has crossed the bridge");
}

public int getVehicleId ()


{
return this.id;
}

public void travel(int time)


{
int limit = 500000;
for (int j=0; j < time; j++)

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

public void useToll(Vehicle vehicle)


{
30

while (true)
{
52

if (inUse == false)
{
00

synchronized (this)
{ inUse=true;
19

System.out.println("Vehicle
"+(vehicle.getVehicleId()+1)+" enters toolbooth");
R

vehicle.travel(50); // vehicle spends 50 time units in


the toll booth
System.out.println("Vehicle
"+(vehicle.getVehicleId()+1)+" exits toolbooth");
inUse = false;
break;
}

}
}
}

NIIT Implementing Thread Synchronization and Concurrency 7.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.
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
t.start();

KA
Thread.sleep(10);
}
}

R
catch (Exception ex)

SA
{
System.out.println(ex);

A
} R
}
}
IT
R

5. Compile and execute the MotorwaySimulation Java application.


-A

After executing the application, the following output is displayed:


01

Vehicle 1 starts journey


02

Vehicle 1 arrives at the toll


Vehicle 1 enters toolbooth
30

Vehicle 1 exits toolbooth


Vehicle 1 has crossed the bridge
52

Vehicle 2 starts journey


Vehicle 2 arrives at the toll
00

Vehicle 2 enters toolbooth


Vehicle 2 exits toolbooth
19

Vehicle 2 has crossed the bridge


Vehicle 3 starts journey
R

Vehicle 3 arrives at the toll


Vehicle 3 enters toolbooth
Vehicle 3 exits toolbooth
Vehicle 3 has crossed the bridge
Vehicle 4 starts journey
Vehicle 4 arrives at the toll
Vehicle 4 enters toolbooth
Vehicle 4 exits toolbooth
Vehicle 4 has crossed the bridge
Vehicle 5 starts journey
Vehicle 5 arrives at the toll
Vehicle 5 enters toolbooth
Vehicle 5 exits toolbooth
Vehicle 5 has crossed the bridge

7.4 Implementing Thread Synchronization and Concurrency 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.
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

NIIT Implementing Thread Synchronization and Concurrency 7.5

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur 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

7.6 Implementing Thread Synchronization and Concurrency 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.
R
KA
R
SA
A
R
IT
R
-A
01
02
30
52
00
19
R

Working with NIO Classes


and Interfaces
CHAPTER 8

NIIT Introduction to Object-Oriented Programming 1.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.
,

Activity 8.1: Performing File Operations


Using NIO

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 ProductDetails.txt 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

1. Create a Java application, GlobalSystems.


R

2. Create a package, details, in the application, GlobalSystems.


3. Create a class, ComputerProducts, inside the package, details.
4. Replace the code in ComputerProducts.java with the following code:

package details;

import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.*;
import java.util.Scanner;

8.2 Working with NIO Classes and Interfaces 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.
public class ComputerProducts {

String pname, prid, name, address, sid;


int price;
String sprid;
Integer iprice, iid;
String sprice;
Path file = Paths.get("D:/Details/ProductDetails.txt");
Path target = Paths.get("D:/Backup/BackupProductDetails.txt");

public void createDirectory() throws IOException {


Path dir = Paths.get("D:/Details");
Path copydir = Paths.get("D:/Backup");
enterProductDetails();

R
}

KA
public void enterProductDetails() throws IOException {
Scanner input = new Scanner(System.in);

R
System.out.println("Enter the product ID: ");

SA
prid = input.nextLine();
System.out.println("Enter the product name: ");
pname = input.nextLine();

A
System.out.println("Enter the product price: "); R
price = input.nextInt();
sprid = prid;
IT
iprice = price;
R

sprice = iprice.toString();
-A

printprodDetails();
enterShopDetails();
01

}
02

public void enterShopDetails() throws IOException {


30

Scanner inputs = new Scanner(System.in);


System.out.println("Enter the shop ID: ");
52

int id = inputs.nextInt();
System.out.println("Enter the shop name: ");
00

name = inputs.next();
System.out.println("Enter the address: ");
19

address = inputs.next();
iid = id;
R

sid = iid.toString();
System.out.println("Do you want to add more shop details: (Y/N) ");
Scanner shopchoice = new Scanner(System.in);
String sch;
sch = shopchoice.next();

switch (sch.toUpperCase()) {
case "Y":
printshopDetails();
enterShopDetails();
break;
case "N":
printshopDetails();

NIIT Working with NIO Classes and Interfaces 8.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.
//printDetails();
System.out.println("Do you want to continue to add product
details: (Y/N) ");
Scanner choice = new Scanner(System.in);
String ch;
ch = choice.next();
switch (ch.toUpperCase()) {
case "Y":
enterProductDetails();

break;
case "N":

System.exit(0);

R
break;

KA
default:
System.out.println("Invalid entry!");
break;

R
}

SA
break;
default:
System.out.println("Invalid entry!");

A
break; R
}
}
IT
R

public void printprodDetails() throws IOException {


-A

Charset charset = Charset.forName("US-ASCII");


try (BufferedWriter writer = Files.newBufferedWriter(file, charset,
01

StandardOpenOption.CREATE, StandardOpenOption.APPEND)) {
writer.write("==========");
02

writer.newLine();
writer.append("Product ID: " + sprid + "\n");
30

writer.newLine();
writer.append("Product Name: " + pname + "\n");
52

writer.newLine();
writer.append("Product price: " + sprice + "\n");
00

writer.newLine();
writer.newLine();
19

}
}
R

public void printshopDetails() throws IOException {


Charset charset = Charset.forName("US-ASCII");
try (BufferedWriter swriter = Files.newBufferedWriter(file, charset,
StandardOpenOption.CREATE, StandardOpenOption.APPEND)) {
swriter.newLine();
swriter.append("Shop ID: " + sid + "\n");
swriter.newLine();
swriter.append("Shop name: " + name + "\n");
swriter.newLine();
swriter.append("Address: " + address + "\n");
swriter.newLine();
swriter.close();

8.4 Working with NIO Classes and Interfaces 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.
}

Path copyfile = Paths.get("D:/Backup/BackupProductDetails.txt");


if (Files.exists(copyfile)) {
Files.delete(copyfile);
Files.copy(file, target);
} else {
Files.copy(file, target);
//enterProductDetails();
}
}

//// Enter shop details


public static void main(String[] args) throws IOException {

R
ComputerProducts obj = new ComputerProducts();

KA
obj.createDirectory();
}
}

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

Enter the product name:


01

Once you enter the product name as Mouse, the following output is displayed:
02

Enter the product price:


Once you enter the product price as 15, the following output is displayed:
30

Enter the shop ID:


52

Once you enter the shop id as 131, the following output is displayed:
00

Enter the shop name:


19

Once you enter the name as Technosolutions, the following output is displayed:
R

Enter the address:


Once you enter the address as XYZ street, the following output is displayed:

Do you want to add more shop details: (Y/N)

NIIT Working with NIO Classes and Interfaces 8.5

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur 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

8.6 Working with NIO Classes and Interfaces 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.
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

NIIT Working with NIO Classes and Interfaces 8.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.
R
KA
R
SA
A
R
IT
R
-A
01
02
30
52
00
19
R

Introduction to JDBC
CHAPTER 9

NIIT Introduction to Object-Oriented Programming 1.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.
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

The Structure of the Authors Table


02

Solution
30

To achieve the preceding requirements, you need to perform the following steps:
1. Create a Java application, Library.
52

2. Add the jar file, sqljdbc4-2.0.jar, in the Library Java application.


00

3. Create a package, book, in the Java application, Library.


19

4. Create a class, AuthorsInfo, in the package, book.


5. Replace the code in the AuthorsInfo.java file with the following code:
R

package book;

import java.sql.*;

public class AuthorsInfo


{
public static void main(String args[])
{
try
{
String str = "SELECT * FROM Authors WHERE city LIKE 'S%'";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

9.2 Introduction to JDBC 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.
try (Connection con =
DriverManager.getConnection("jdbc:sqlserver://localhost;
databaseName=Library;user=sa;password=password@123");
Statement stmt = con.createStatement();)
{
ResultSet rs = stmt.executeQuery(str);

System.out.println("Author ID\tAuthor Name\tCity");


System.out.println("--------------------------------------");

while (rs.next())
{
String id = rs.getString("au_id");
String name = rs.getString("au_name");

R
String city = rs.getString("city");

KA
System.out.print(id + "\t");

if (name.length() <= 7)

R
{

SA
System.out.print(name + "\t\t");
}
else

A
{ R
System.out.print("\t" + name + "\t");
}
IT
System.out.println(city);
R

}
-A

}
}
01

catch (Exception ex)


{
02

System.out.println("Error occurred");
System.out.println("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.

NIIT Introduction to JDBC 9.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.
6. Compile and execute the Library Java application. After executing the application, the following output
is displayed:

Author ID Author Name City


----------------------------------------------
A007 Ringer Albert Salt Lake City

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

9.4 Introduction to JDBC 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.
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

NIIT Introduction to JDBC 9.5

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur 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

NIIT Introduction to Object-Oriented Programming 1.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.
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

The User Interface of the Application


R

Help Mark to achieve the preceding requirement.

Prerequisite
You need to ensure that the Library database exists and comprises the Publishers table.

10.2 Creating Applications Using Advanced Features of JDBC 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.
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, sqljdbc4-2.0.jar, 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 PublisherInfo.java file with the following code:
R
-A

package inventory;
01

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
02

import javax.swing.*;
import java.sql.*;
30
52

public class PublisherInfo implements ActionListener


{
00

JLabel heading, lpubid, lpub_name, lphone, laddress, lcity, lstate, lzip;


JTextField pub_idField, pub_nameField, phoneField, addressField,
19

cityField, stateField, zipField;


JButton insert, exit;
R

Connection con;
Statement stmt;
PreparedStatement stat;
ResultSet rs;
JPanel p1;
JFrame f1;

public PublisherInfo()
{
try
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

NIIT Creating Applications Using Advanced Features of JDBC 10.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.
con =
DriverManager.getConnection("jdbc:sqlserver://localhost;databaseName=Library;
user=sa;password=password@123");
stmt = con.createStatement();

}
catch (Exception e)
{
System.out.println("Error : " + e);
}
}

public void compshow()


{

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

pub_nameField = new JTextField(50);


-A

phoneField = new JTextField(15);


addressField = new JTextField(50);
01

cityField = new JTextField(50);


stateField = new JTextField(50);
02

zipField = new JTextField(20);


30

insert = new JButton("Insert");


exit = new JButton("Exit");
52

p1.setLayout(null);
00

heading.setBounds(250, 35, 200, 40);


p1.add(heading);
19

lpubid.setBounds(75, 90, 200, 30);


R

pub_idField.setBounds(400, 90, 100, 25);


p1.add(lpubid);
p1.add(pub_idField);

lpub_name.setBounds(75, 120, 200, 30);


pub_nameField.setBounds(400, 120, 200, 25);
p1.add(lpub_name);
p1.add(pub_nameField);

lphone.setBounds(75, 150, 200, 30);


phoneField.setBounds(400, 150, 150, 25);
p1.add(lphone);
p1.add(phoneField);

10.4 Creating Applications Using Advanced Features of JDBC 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.
laddress.setBounds(75, 180, 200, 30);
addressField.setBounds(400, 180, 250, 25);
p1.add(laddress);
p1.add(addressField);

lcity.setBounds(75, 210, 200, 30);


cityField.setBounds(400, 210, 200, 25);
p1.add(lcity);
p1.add(cityField);

lstate.setBounds(75, 240, 200, 30);


stateField.setBounds(400, 240, 200, 25);
p1.add(lstate);
p1.add(stateField);

R
KA
lzip.setBounds(75, 270, 200, 30);
zipField.setBounds(400, 270, 200, 25);
p1.add(lzip);

R
p1.add(zipField);

SA
insert.setBounds(175, 350, 100, 30);
exit.setBounds(325, 350, 100, 30);

A
p1.add(insert); R
p1.add(exit);
IT
f1.add(p1);
R

f1.setSize(680, 500);
-A

f1.setVisible(true);
f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
01

insert.addActionListener(this);
02

exit.addActionListener(this);
}
30

public void actionPerformed(ActionEvent ae)


52

{
if (ae.getActionCommand() == "Exit")
00

{
System.exit(0);
19

}
R

if (ae.getActionCommand() == "Insert")
{
if(!pub_idField.getText().equals(""))
{
try
{
stat = con.prepareStatement("INSERT INTO Publishers VALUES(?,
?, ?, ?, ?,?, ?)");
String pid = pub_idField.getText();
String pname = pub_nameField.getText();
String pphone = phoneField.getText();
String padd = addressField.getText();
String pcity = cityField.getText();

NIIT Creating Applications Using Advanced Features of JDBC 10.5

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur 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 = stateField.getText();
String pzip = zipField.getText();

stat.setString(1, pid);
stat.setString(2, pname);
stat.setString(3, pphone);
stat.setString(4, padd);
stat.setString(5, pcity);
stat.setString(6, pstate);
stat.setString(7, pzip);

stat.executeUpdate();

pub_idField.setText("");

R
pub_nameField.setText("");

KA
phoneField.setText("");
addressField.setText("");
cityField.setText("");

R
stateField.setText("");

SA
zipField.setText("");
JOptionPane.showMessageDialog(f1, "Information has been
inserted.", "Information", JOptionPane.INFORMATION_MESSAGE);

A
} R
catch (Exception e)
{
IT
R

String msg = e.getMessage();


-A

if(e.getMessage().equals(msg))
01

{
JOptionPane.showMessageDialog(f1, "Record already
02

exists.", "Warning Message", JOptionPane.WARNING_MESSAGE);


pub_idField.setText("");
30

pub_nameField.setText("");
phoneField.setText("");
52

addressField.setText("");
cityField.setText("");
00

stateField.setText("");
zipField.setText("");
19

}
R

}
}
else
{
JOptionPane.showMessageDialog(f1, "Please fill the details
properly.", "Error Message", JOptionPane.ERROR_MESSAGE);
}

10.6 Creating Applications Using Advanced Features of JDBC 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.
public static void main(String args[])
{
PublisherInfo p = new PublisherInfo();
p.compshow();
}
}

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

The Output of the BookInventory Application


7. Type P006, Park Publishing House, 0089282389, 7 Park Street, Riverbank, California, and
3338733 in the Publishers ID, Publishers Name, Phone Number, Address, City, State, and Zip text
boxes, respectively.

NIIT Creating Applications Using Advanced Features of JDBC 10.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.
8. Click the Insert button. The output is displayed, as shown in the following figure.

The Output of the BookInventory Application


9. Click the OK button and close the PUBLISHERS window.

R
KA
R
SA
A
R
IT
R
-A
01
02
30
52
00
19
R

10.8 Creating Applications Using Advanced Features of JDBC 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.
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, sqljdbc4-2.0.jar, in the NewPublishers Java application.
R

3. Create a package, metadata, in the Java application, NewPublishers.


-A

4. Create a class, ColumnInfo, in the package, metadata.


01

5. Replace the code in the ColumnInfo.java file with the following code:
02

package metadata;
30

import java.sql.*;
52

import java.util.Scanner;
00

public class ColumnInfo


{
19

public static void main(String args[])


{
R

Scanner sc = new Scanner(System.in);

String tablename;

try
{

Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

try (Connection con =


DriverManager.getConnection("jdbc:sqlserver://localhost;databaseName=Library;
user=sa;password=password@123");)
{
System.out.println("Enter the table name: ");

NIIT Creating Applications Using Advanced Features of JDBC 10.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.
tablename = sc.nextLine();
String str = "SELECT * FROM " + tablename + " ";
try (Statement stmt = con.createStatement();)
{
ResultSet rs = stmt.executeQuery(str);
ResultSetMetaData rsmd = rs.getMetaData();
rs.next();

System.out.println("==================================");
System.out.println("Number of Attributes in the " +
tablename + " table: " + rsmd.getColumnCount());
System.out.println("");
System.out.println("----------------------------------");
System.out.println("Attributes of the " + tablename + "

R
Table");

KA
System.out.println("----------------------------------");

for (int i = 1; i <= rsmd.getColumnCount(); i++)

R
{

SA
System.out.println(rsmd.getColumnName(i) + " : " +
rsmd.getColumnTypeName(i));
}

A
}
R
}
IT
}
R

catch (Exception e)
-A

{
System.out.println("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

10.10 Creating Applications Using Advanced Features of JDBC 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.
6. Compile and execute the NewPublishers Java application. After executing the application, the following
output is displayed:

Enter the table name:

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

NIIT Creating Applications Using Advanced Features of JDBC 10.11

This book is a personal copy of ARITRA SARKAR of NIIT Kolkata Jadavpur 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

10.12 Creating Applications Using Advanced Features of JDBC 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.
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 might also like