Download as pdf or txt
Download as pdf or txt
You are on page 1of 60

1151CS302-JAVA PROGRAMMING LAB LAB MANUAL

SCHOOL OF COMPUTING

DEPARTMENT OF COMPUTER SCIENCE


ENGINEERING

LAB MANUAL

LAB CODE : 1151CS302

LAB NAME : JAVA PROGRAMMING LAB.

ACADEMIC YEAR : 2018-2019(ODD SEM)

YEAR/SEM : II / IV

Prepared By,

Dr.N.PARTHEEBAN/Associate Professor
Dr.R.KAVITHA/Associate Professor
Mrs.VIJAYALAKSHMI.K/Assistant Professor
Mrs.S.UMA/Assistant Professor

1
1151CS302-JAVA PROGRAMMING LAB LAB MANUAL

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VISION AND MISSION OF THE DEPARTMENT

VISION

 To attain global recognition in the field of computer science and engineering,


research and training to meet the growing needs of the industry and society by
producing globally competitive and self-disciplined Computer Engineers.
MISSION

 To offer high quality education in the field of computer science and engineering by
imparting quality training, hands on experience and value education.
 To create an environment encourages for research and to innovate new
technologies in the field of Computer Science and Engineering and across
disciplines in order to serve the needs of industry, government and society.
 Encourage students to become self-motivated, ethically strong, problem solving
individuals who can find and understand the knowledge needed to be successful in
the profession

PROGRAMME EDUCATIONAL OBJECTIVES (PEOs):

After 3-5 years from the year of graduation, our graduates will,

1. Have strong foundations in mathematical, scientific and engineering fundamentals


necessary to formulate, solve and analyze computer science and engineering
problems.
2. Have an exposure to a variety of high level programming languages, systems to
analyze, design and implement hardware and software systems in advanced
computing environment.

2
1151CS302-JAVA PROGRAMMING LAB LAB MANUAL

3. Demonstrate the impact of computing on the society, ethical, social and


professional responsibilities/implications of their work.
4. Have strong communication inter-personal skills, multicultural adoptability and to
work effectively in multidisciplinary teams.
5. Engage life-long learning to become successful in their professional work.

PROGRAMME OUTCOMES (PO’s)

Engineering Graduates will be able to:

1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering


fundamentals, and an engineering specialization to the solution of complex engineering
problems.

2. Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of
mathematics, natural sciences, and engineering sciences.

3. Design/development of solutions: Design solutions for complex engineering


problems and design system components or processes that meet the specified needs with
appropriate consideration for the public health and safety, and the cultural, societal, and
environmental considerations.

4. Conduct investigations of complex problems: Use research-based knowledge and


research methods including design of experiments, analysis and interpretation of data,
and synthesis of the information to provide valid conclusions.

5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and
modern engineering and IT tools including prediction and modeling to complex
engineering activities with an understanding of the limitations.

3
1151CS302-JAVA PROGRAMMING LAB LAB MANUAL

6. The engineer and society: Apply reasoning informed by the contextual knowledge to
assess societal, health, safety, legal and cultural issues and the consequent responsibilities
relevant to the professional engineering practice.

7. Environment and sustainability: Understand the impact of the professional


engineering solutions in societal and environmental contexts, and demonstrate the
knowledge of, and need for sustainable development.

8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities
and norms of the engineering practice.

9. Individual and team work: Function effectively as an individual, and as a member or


leader in diverse teams, and in multidisciplinary settings.

10. Communication: Communicate effectively on complex engineering activities with


the engineering community and with society at large, such as, being able to comprehend
and write effective reports and design documentation, make effective presentations, and
give and receive clear instructions.

11. Project management and finance: Demonstrate knowledge and understanding of


the engineering and management principles and apply these to one’s own work, as a
member and leader in a team, to manage projects and in multidisciplinary environments.

12. Life-long learning: Recognize the need for, and have the preparation and ability to
engage in independent and life-long learning in the broadest context of technological
change.

4
1151CS302-JAVA PROGRAMMING LAB LAB MANUAL

SYLLABUS
COURSE CODE COURSE TITLE L T P C
1151CS302 JAVA PROGRAMMING LAB 0 0 2 1
Course Category: Program Core

A. Preamble :
Most of the software need to develop runs in cross platform. Java is the one of the pioneer
software development tool developed used for cross platform development software. From the system
towards the handheld devices all place Java become one of the most dominant software. This course
provides a basic concept about Object Oriented Programming, Database connectivity, Networking
and finally provides programming skills in java. After successful completion of this course learners
can able to develop software modules for real world problem.

B. Pre-requisites:
Sl. No Course Code Course Name
1 1150CS201 Problem Solving using C

C. Related Courses:
Sl. No Course Code Course Name
1 1156CS601 Minor Project
2 1156CS701 Major Project

D. Course Outcomes:
Students undergoing this course are able to
Knowledge Level
CO
Course Outcomes (Based on revised
Nos.
Bloom’s Taxonomy)
Write a java program using classes, methods, Objects and
1 control structures.
S3
Implement inheritance, interfaces and packages in various S3
2 applications.
Develop simple applications for handling pre-defined and user S3
3 defined exceptions.
Develop simple applications using GUIs and event driven S3
4 programming.
5 Construct an application using JDBC. S3

E. Correlation with Programme Outcomes :


COs PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12
CO1 H M H
CO2 H M H
CO3 H H M H
CO4 H M H
CO5 H M H
5
1151CS302-JAVA PROGRAMMING LAB LAB MANUAL

F. Course Content
-LIST OF EXPERIMENTS:
1. Simple Java applications
- for understanding reference to an instance of a class (object), methods
- Handling Strings in Java
2. Constructors
-Implement constructor overloading.
3. Inheritance
- To Implement Method Overloading and Method Overriding.
4. Package creation.
- Developing user defined packages in Java
5. Interfaces
- Developing user-defined interfaces and implementation
- Use of predefined interfaces
6. Threading
- Creation of thread in Java applications
- Multithreading
7. Exception Handling Mechanism in Java
- Handling pre-defined exceptions
- Handling user-defined exceptions
8. AWT-To Create Different Layout Managers.
9. JDBC-To connect Oracle/MS Access for Table creation and Data Manipulation.

LIST OF EQUIPMENT FOR A BATCH OF 30 STUDENTS:


Stand alone desktops with JDK 30 Nos.

G. Learning Resources
i. Text Books
1.E. Balaguruswamy,Programming in java , Fourth Edition,TMH,2010.
2. PatricNaughton , Herbert Schildt, The Complete Reference “Java 2 “, Ninth edition
Tata McGraw Hills ,2014.
ii. Reference Books
1. H.M.Deitel and P.J.Deitel –“Java How to Program” Pearson Prentice Hall 6th Edition,
2011.
2. Sachinmalhotra, ”Programming in JAVA”, Oxford University Press, 2011.
3. Maydene Fisher, Jonathan Ellis, Jonathan Bruce,”JDBC Database access with java”
Addison-Wesley, Third Edition 2003
4. Bruce Eckel – “Thinking in Java” Pearson Prentice Hall Third Edition-2006
iii. Online Resources
1. docs.oracle.com/javaee/6/tutorial/doc/girgm.html
2. www.webreference.com/programming/java.html
3. www.apl.jhu.edu/~hall/java/Documentation.html

6
1151CS302-JAVA PROGRAMMING LAB LAB MANUAL

LIST OF EXPERIMENTS
1.Given the following table containing information about employees of an organization,
develop a small java application which accepts employee id from the command prompt and
displays the following details as output:

EmpNoEmpNameDepartment Designation Salary


Emp No Emp Join Date Designation Department Basic HRA IT
Name Code
1001 Ashish 01/04/200 e R&D 20000 8000 3000
9
1002 Sushma 23/08/201 c PM 30000 12000 9000
2
1003 Rahul 12/11/201 k Acct 10000 8000 1000
3
1004 Chahat 29/01/201 r Front Desk 12000 6000 2000
3
1005 Ranjan 16/07/200 m Engg 50000 20000 20000
5
1006 Suman 1/1/2000 e Manufacturin 23000 9000 4400
g
1007 Tanmay 12/06/200 C PM 29000 12000 10000
6

DA(Dearness Allowance) details are given in the below “Designation Table”


Designation Code Department DA
e Engineer 20000
c Consultant 32000
k Clerk 12000
r Receptionist 15000
m Manager 40000

Note 1: Salary should be calculated as (Basic +HRA+DA-IT)


Note 2: Use Switch case to print Designation and to find the value of DA for a particular
employee.
Expected Output Format (assuming that your class name is Project 1)
 If you execute the command java Project 1003, the output should be –
EmpNoEmpNameDepartment Designation Salary
1003 Rahul Acct Clerk 29000
 If you execute the command java project 123, the output should be
There is no employee with empid :123

1(a). Write a Java application program to handle String functions.

7
1151CS302-JAVA PROGRAMMING LAB LAB MANUAL

You are expected to write a program to perform the basic components like insert, delete, display,
search etc. on a list. The list should contain string object items. The operations should be
available to the user through a console-based menu as shown below:

Sample Input and Output:

MAINMENU

1.Insert
2.Search
3.Delete
4.Display
5.Replace
6.Sort
7.Shuffle
8.Reverse
9.Exit
Enter your choice (1…9):1
Enter the item to be inserted :Bottle
Inserted Successfully.

MAINMENU

1.Insert
2.Search
3.Delete
4.Display
5.Replace
6.Sort
7.Shuffle
8.Reverse
9.Exit
Enter your choice (1…9):1
Enter the item to be inserted :Water
Inserted Successfully.

MAINMENU

1.Insert
2.Search
3.Delete
4.Display
5.Replace
6.Sort
7.Shuffle
8.Reverse

8
1151CS302-JAVA PROGRAMMING LAB LAB MANUAL

9.Exit
Enter your choice (1…9):1
Enter the item to be inserted :Cap
Inserted Successfully.

2. Write a Java program to build the following number series.

Pattern 1 : Pattern 2: Pattern 3: Pattern 4: Pattern 5:


1 1111111 1 (i) 0000000
12 1111122 26 a 0100000
123 1111333 3 7 10 aba 0020000
1234 1114444 4 8 11 13 abcba 0003000
12345 1155555 5 9 12 14 15 abcdcba 0000400
123456 1666666 abcba 0000050
1234567 7777777 aba 0000006
123456 a
12345 (ii)
1234 j
123 ja
12 jav
1 java

2 (a) To write simple java application program to implement control statement for
generating the followings:

a) Generate Prime Numbers


b) Generate Fibonacci series
c) Decimal To Binary Conversion

3. The goal of this project is to design and implement a simple inventory control system for
a small video rental store. Note: This program based on OOPS and Inheritance.

The following are the various classes that are implemented,


1. video
Member variables
• String videoName
• Boolean checkout
• int rating

Member functions
• String getName();
• void doCheckout();
• void doReturn();
• void receiveRating(int rating);
• intgetRating();

9
1151CS302-JAVA PROGRAMMING LAB LAB MANUAL

• booleangetCheckout();

Constructor
• Video(String name);

2.Videostore

Member variables

Video[] store

Member Functions
• void addVideo(String name);
• void doCheckout(String name);
• void doReturn(String name);
• void receiveRating(String name, int rating);
• void listinventory();

3. VideoLaucher
Contains the main method to test the program.

4. To write a simple java application program for Multilevel inheritance.

5. Write a Java Program to implement Interest Calculator based on the following scenario.

Calculate interest based on the type of account and the status of the account holder.
The rate of interest changes according to the amount (greater than or less than 1 crore) age
of the account holder (General or Senior citizen) and the number of days if the type of
account is FD or RD.

Applicable rates are as given in the below table

Rate of FD interest for amounts below 1 Crore


Currents rates of Interest (in %)
Maturity period General Senior Citizen
7 days to 14 days 4.50 5
15 days to 29 days 4.75 5.25
30 days to 45 days 5.50 60
45 days to 60 days 7 750
61 days to 184 days 7.50 8
185 days to 1 year 8.00 8.5

Rate of FD interest for amounts above 1 Crore


Maturity Period Interest Rate
7 days to 14 days 6.50
15 days to 29 days 6.75

10
1151CS302-JAVA PROGRAMMING LAB LAB MANUAL

30 days to 45 days 6.75


45 days to 60 days 8
61 days to 184 days 8.50
185 days to 1 year 10

Rate of RD Interest:
Current Rate of Interest
Maturity period General Senior Citizen
6 months 7.50 8.00
9 months 7.75 8.25
12 months 8.00 8.50
15 months 8.25 8.75
18 months 8.50 9.00
21months 8.75 9.25

SB Account interest rate:

Type of Account Interest Rate


Normal 4%
NRI 6%

Requirements:
1.Seprate classes should be created for the different types of accounts.
2.All class should be derived form an abstract class named ‘Account’ which should contain a
method called ’calculate interest’
3.Implement the ‘calculate Interest’ method according to the type of the account, interest rates,
amount and age of the account holder.
4.if the user enters an Invalid value(e.g negative)if any field, raise a user defined exception.

Sample class structure are given bellow:

Account(Abstract)
double interestRate
Double amount
Abstract double calculateInterest()

FDAccount
double interestRate
double amount
int noOfDays
int ageOfACHolder
abstract double calculateInterest()

11
1151CS302-JAVA PROGRAMMING LAB LAB MANUAL

SBAccount
double interestRate
Double amount
abstract double calculateInterest()

RDAccount
double interestRate
double amount
int noOfmonths
double monthlyAmount;
abstract double calculateInterest()

Hint:Use method overloading

Sample Output

MAIN MENU
____________

1.Interest Calculator-SB
2. Interest Calculator-FD
3. Interest Calculator-RD
4.Exit
Enter your option (1…4 ):1
Enter the Average amount in your account:10000
Interest gained:Rs.400

MAIN MENU

1.Interest Calculator-SB
2. Interest Calculator-FD
3. Interest Calculator-RD
4.Exit

Enter your option (1…4 ):2


Enter FD mount:10000
Enter the Number of days:91
Enter your age:65
Interest gained:Rs.800

MAIN MENU

1.Interest Calculator-SB
2. Interest Calculator-FD

12
1151CS302-JAVA PROGRAMMING LAB LAB MANUAL

3. Interest Calculator-RD
4.Exit

Enter your option (1…4 ):2


Enter FD mount:10000
Enter the Number of days:91
Enter your age:34
Interest gained:Rs750

MAIN MENU

1.Interest Calculator-SB
2. Interest Calculator-FD
3. Interest Calculator-RD
4.Exit

Enter your option (1…4 ):2


Enter FD mount:10000
Enter the Number of days:-7
Enter your age:78
Invalid Number of days. please enter non-negative values.

6. To write java program for developing user-defined interfaces and implementation.

7. To write a java program for developing a chatting application(Client and Server) using
Thread.

8. Write a Java Program to implement Multithreading concept for the following


application:

Rabbit and Tortoise Race


This is a simple project which involves creation of multiple threads and explores some
thread control mechanisms and thread priorities.

1. Create two threads named ‘Rabbit’ and ‘Tortoise’ . The threads created should run
100 meters and the thread which finishes first ‘ wins the race’. When one of the threads wins the
race, stop the second thread.
Start both the threads and observe which thread finishes first.

2. Since the rabbit is faster than Tortoise, set a high priority to Rabbit and observe the
results.
3. Now modify the program so that the ‘Rabbit’ thread ‘ sleeps ‘ or 1000 milliseconds after
running 60 meters. Observe which thread wins the race.

How the thread is created:

13
1151CS302-JAVA PROGRAMMING LAB LAB MANUAL

We can create threads in two ways: either by extending thread class or by implementing
Runnable interface.

How the thread runs 100 meters:

We can use for loop or iterating rom 0 to 100. A print statement can be included so that we can
see how far each thread has run.

9. Write a Java Program to implement Student Grade Calculation System. Apply


appropriate Exception handling mechanisms.

Here, test data is available in array of Student objects. The functions accept either a
student object or an array of students as arguments.
If the given object has any data errors, then, the program is expected to return appropriate
error messages by throwing the exceptions. Or, if given object has no data errors, then, we need
to find the grade and print the same.
Also, need to implement counter functions to count the number of null entries in the
given array of objects.
Package 1: com.mile1.bean
Class Student
Variables Description
String name; Instance variables
int marks[];
String grade;
Constructors Auto generated
public Student() {

}
public Student(String grade, int[] marks,
String name)
{
// do the initialization
}
Methods Auto generated
Provide public Getters And public Setters for all instance
variables

Package 2: com.mile1.exception
All the classes in this package should extend the Exception class.
Class Method Description
NullMarksArrayException Override toString() method Return "mark array is null"
NullNameException Override toString() method Return "name is null"
NullStudentObjectException Override toString() method Return "object is null"

14
1151CS302-JAVA PROGRAMMING LAB LAB MANUAL

Package 3: com.mile1.service
Class StudentReport
Method Description
Assumption:
public StringfindGrades Only valid objects are passed to this function. So, just
(Student studentObject) concentrate on the logic part.

{ Get the marks from the given object studentObject.


// write code here
if (any one of the marks is less than 35 )
then grade= "F";
else
{
Find the Sum of all the marks.

} if (sum <150) grade= "C";


else if (sum <200) grade= "B";
else if (sum <250) grade= "A";
else grade="A+";
return the grade;
}

public String validate Check whether there is any null data in the given object.
(Student studentObject) If given Object itself is null, then, throw the
throws NullNameException, NullStudentObjectException.
NullMarksArrayException, Else
we need to look for null inside the object.
NullStudentObjectException 1) Check whether name is null. If so, throw the
NullNameException
{
2) Check whether marks array is null. If so, throw the
// write code here NullMarksException

If all data is valid, call the findGrades function which is


defined in the same class.
}
Return the string returned by this function.

Package3 com.mile1.service
ClassStudentService
Note: If you are not careful, you will get NullPointerException in these function.

Method Description

15
1151CS302-JAVA PROGRAMMING LAB LAB MANUAL

public
intfindNumberOfNullMarksArray This function is used to count the number of objects in
(Student studentObjects[]) studentObjectswhere the marks array in that objects is
{ null.
// write code here
Declare Counter=0;
Check (studentObjects is not null)
If so{
for ( each student in studentObjects array {
} if (student !=null and student.getMarks() is null)
Counter++;
}
return the Counter value;
}

public intfindNumberOfNullName
(Student studentObjects[]) This function is used to count the number of objects in
{ studentObjectswhere the name in that object is null.

// similar to findNumberOfNullMarksArrayfunction

// write code here


}

public intfindNumberOfNullObjects This function is used to count the number of null objects
(Student studentObjects[]) in studentObjects[] array.
{
Declare Counter=0;
Check (studentObjects!= null)
If so
{
for (each student in studentObjectsarray ){
// write code here if (student is null) Counter++;
} }

return the Counter value;


}

Package 4 com.mile1.main
Class StudentMain – Test Code Given
This is used to test your project locally
Variables
static Student data[] = new Student[4];

Methods

16
1151CS302-JAVA PROGRAMMING LAB LAB MANUAL

StudentMain() // Constructor
{
// Code Given
}

public static void main(String[] args) {


// Code Given

TestCases:-
TC1 -- Calculate the grades for valid objects – Check for A+ grade computation.
TC8 -- Calculate the grades for valid objects – Check for F grade computation.
Test the validate function Implementation in service package
Check whether the validate function handles the following situations.
TC2 -- If the Object is null, throw NullStudentObjectException().
TC3-- If the Name is null, throw NullNameException().
TC4 -- If the Marks array is null, throw NullMarksArrayException().
Test the counting functions Implementation in service package
TC5 –Test findNumberOfNullNamefunction.
TC6–Test findNumberOfNullObjects function.
TC7 -- Test findNumberOfNullName

SAMPLE DATA SET1: Note that your program will be tested with another set of data. Not this
set of data. This is given to understand the testing process used in the background.

Sample Data M1+M2+ Expected Grade


M3
s[0]= new Student("A1",new int[] 219 A
{72,73,74});
s[1]= new Student("B1",new int[] 228 A
{75,76,77});
s[2]= new Student("C1",new int[] 297 A+
{99,99,99});
s[3]= new Student("D1",new int[] 299 A+
{100,100,99});
s[4]= new Student("E1",new int[] 114 F
{13,88,13});
s[5]= new Student("F1",new int[] 127 F
{14,14,99});
s[6]= new Student("G1",new int[] 144 F

17
1151CS302-JAVA PROGRAMMING LAB LAB MANUAL

{77,55,12});
s[7]= new Student(null,newint[]{13,88,13}); 114 // this is invalid object
Validate function will
throw new
NullNameException()
s[8]= new Student("J1",null); -- // this is invalid object
Validate function will
throw new
NullMarksArrayException
()
s[9]= null; -- // this is invalid object
Validate function will
throw new
NullStudentObjectExcepti
on()

10. To write a java program to simulate the traffic light using AWT component.

11. To write a calculator program codes using Java Swing component.

12. Develop a mini project on Inventory and Sales System application based on java with
Data base Connectivity.(Oracle SQL PLUS).

Project Objective:
As per the requirement from the client you are required to create a console based application
using java as frontend and oracle as backend for their inventory and sales maintenance. Already
the design team have completed the requirement design and you are expected the complete the
assigned module.
Project Design:
Database Design: you are required to get the Database ready using Oracle SQL Plus.
Task1:
Create a table called TBL_STOCK with the given specification:

Column name Type Description


Product_ID Varchar length6 Primary Key
Product_Name Varchar length 20 Unique
Quantity_On_Hand Number Should not be <0
Quantity-Unit-Price Number Should not be <0

Product_Unit_Price Number Should not be <0

Reorder-Level Number Should not be <0


Create a table Called TBL_SALES with the given Specification:
Column Name Type Description

Sales-ID Varchar Length 6 Primary Key


18
Sales _Date Date
Product_ID Varchar Length 20 Foreign key from TRL_STOCK table
Quantity_Sold Number Should not be <0
Sales_Price_Per_unit Number Should not be <0
1151CS302-JAVA PROGRAMMING LAB LAB MANUAL

Task2:
Enter sample record into TBL_STOCK table:
Product_I Product_Name Quantity_On_Hand Product_unit_price Reorder_Leve
D l
RE1001 REDME Note 3 20 12000 5
ip1002 Iphone 5s 10 21000 2
PA1003 Panasonic p55 50 5500 5

Task 3:
Create the following sequence:
Sequence _Name Start value Incremental Value
SEQ_SALES_ID 1000 1
SEQ_PRODUCT_ID 1004 1

Task 4:
Create a view named V_SALES_REPORT usingTBL_SALES table based joined with
TBL_STOK table based on ProductID order the result based on Profit_ Amount in descending
and Sales_ID in Ascending.
Column Name Description
Sales_ID
Sales _Date
Product-+_ID
Product_Name
Quantity_Sold
Sales_Price_per_unit
Profit_Amount Return the difference between Sales_Price_Per_Unit And
Product_Unit_Price.

APPLICATION DESIGN: Create java application to manage the sales:


Create a Java Applicationto manage the sales and control inventory. Create new Java
project under eclipse.
Create the following Package and the specified Classes below.
Name of the Package Usage
Com.wipro.sales.util Contains the class that establishes
The database connection.
Com.Wipro.sales.bean Contain all the bean classes.
Com.wipro.sales.dao Contain the DAO Classes that performs the real JDBC Operation.
Com.wipro.sales.servic Contain the administrator class that receive input from servlets and that
e involves the respective DAO class Methods.
Com.wipro.sales.main Contain executable class with the main Method.

Under the package com.wipro.sales.util create the following classes.


Class Method and variable Description
DBUtil DB connection class

19
1151CS302-JAVA PROGRAMMING LAB LAB MANUAL

Public static Connction getDBConnection() Establish a connection to the


database and return the
java.sql.connection reference.

Under the package com.wipro.sales.bean create the following classes:


Class Method and variable Description
Product Bean class
String productID
String productName
Int quantityOnHand
Double productUnitPrice
Int ReorderLevel
Setter and Getter for all Using Eclipse create getters setters
properties. for all properties.

SalesReport Bean class


String salesID
Java.util.Date salesDate
String productID
String productName
int Quantityonhand
Double productUnitPrice
Double salesPriceperUnit
int ReOrderLevel
Double Profit Amount
Setter and getter for all Using Eclipse create getter
properties. setter for all properties.
Under the package com.wipro.sales.bean create the following classes.

Class Method and Variable Description


Sales Beans class
String salesID
Java.util.Date salesDate
String productID
int quantitySold
Double salesPricePerUnit
Setter and Getter for all Using Eclipse create getter setter
properties. for all properties.

Under the package com.wipro.sales.dao create the following classes.


Class Method and variable Description
SalesDao Int InsertSales(Sales sales) This method is used to insert thegiven sales obj
into TBL_SALES table
String This method used to generate SalesID using the

20
1151CS302-JAVA PROGRAMMING LAB LAB MANUAL

genrateSalesID(java.util.Date last 2digit of the year part of the given date


salesDate) concatenated with the SEQ_SALES _ID sequence
generated number
ArrayList<SalesReport>getS This method runs theV_SALES_REPORT view
alesReport() and store every record sales Report adding them
to arraylist which is return back to user

Class Method and variable Description


StockDao Dao class
insertStock(Stock Sales) This method is used to insert the given Stock obj
into TBL_STOCK table
generateProductID(String This method is used to generate stock ID Using the
productName) First 2 letters of the given product name
concatenated with the
updateStock(String This method is used to update the Stock table by
productID,int soldQty) Subtracting the current Quanty-On_Hand by the
given soldQty of the given productID
Stock getStock(String This method is used to fetch a specific record detail
productID) from the Stock table for the given productID store
the information to a store the information to stock
bean object the return the same
deleteStock(String This method is used to delete thestock record of the
productID) given ProductID

Class Method and variable Description


Administrato Service Classes
r
String This method is used to insert the given stockobj int the
insertStock(Stock TBL_STOCK table using StockDao class insertStock
stockobj) method if the below conditions are successful.
1.stockobj should not be null
2.ProductName should be of minimum 2 letters in
length
3.if above 2 are valid generate Product Id using
stockDao
Class generateProductId method and store the same in
the given stock Object
If any of the above condition fail return “data not valid
for insertion”
Else
Return the generated ProductId
String Delete the record of the given product id using
deleteStock(String stockDao class deleteStock method,if delete is
ProductID) successful return”delete” else return “record can not be
delete”
String This method is used to insert the given salesobj into the
21
1151CS302-JAVA PROGRAMMING LAB LAB MANUAL

insertSales(Stock TBL_SALES table using SalesDao class


salesobj) insertSalesmethod if the below condition are successful.
1.Salesobj should not be null
Else return “Object can not valid for insertion”
2. productID should be present in the TBL_Stock table
else return p“Unknown product for sales”
3.Product current QuantityOnHand value else return
“Not enough Stock on hand for Sale”,
4.Sale Date should be currentdate or earlier date and
future date,else return “Invalid date “,
5 If above 4 are valid generate Sale id using SalesId
using SalesDao class generateSalesId method and store
the same in the SalesId member of the given Sales
Object
Call the insertSale method of SalesDao and insert the
record. If insertion is successful call the updatedStock
method of the stockDao and update the sold quantity to
the stock.
On the successful completion of both the transaction
return “sales Completed” else “ Error”,
ArrayList<SalesRepo This method calls the getsalesReport of the SalesDao
rt> and return the ArrayList.
getSalesReport()
Under the package com.wipro.sales.main create the following classes.
Class Method And Description
Variables
SalesApplication Executable Class

This method has to display a main menu with following


option:
public static void 1.Insert stock.
main(String 2.Delete stock.
arg[]) 3.Insert sales.
4.View Sales Report.
Enter your choice:
On selecting the choice it should accept the required
date from the user create appropriate object and call the
valid method from the administrator class.
Eg.if the selected option is 1.then create Stock bean
object and get all Stock bean data from user and set it to
the object and call insertStock method from the
Administrator class.

CONTENT BEYOND SYLLABUS

22
1151CS302-JAVA PROGRAMMING LAB LAB MANUAL

The objective of this following assessment is to check your ability to complete a project as per
the provided “Project Design”.
14. House Management System
15. Weather Forecast System
16. University Management System
17. Bus Schedule Management System
18. Library Management system

14. HOUSE MANAGEMENT SYSTEM

Project Assessment

GENERAL INSTRUCTIONS: Please carefully read the below instructions


The objective of this assessment is to check your ability to complete a project as per the provided
“Project Design”.
You are expected to –
1. Write the source code for the classes, methods and packages EXACTLY as mentioned in
the “Project Design” section.
2. Ensure that the names of the packages, classes, methods and variables EXACTLY
MATCH with the names specified in the “Project Design” section.
3. Understand the project requirements and ACCORDINGLY WRITE the code and logic in
the classes and methods so as to meet all given requirements.
Creating the project and testing it –
1. You are expected to create your project locally using eclipse (or any other IDE) on your
desktop.
Project Objective:
Create a console based Java application that would allow a user of a House Management System
to perform the following operations
 Create a new Rental Property into the system [Posting availability of a new property that
is available for rent]
 The user will receive the following details from the customer
 The rental amount
 The number of bedrooms
 City name
 Location name
 The property id needs to be computed

Project Design:
A. Database Design:
1. Create a new user in database [ To be done in the backend by using sql commands ]
a) Note: Do NOT use the default scott/tiger account of oracle for this project. You will have
to create a new user in the below mentioned format.
b) Username/password : B<batchnumber><employeeid>

23
1151CS302-JAVA PROGRAMMING LAB LAB MANUAL

For example, if your batch number is 39806 and Employee number is 12345, then the oracle user
should be B3980612345 and the password should be B3980612345
c) For JDBC connection, only use orcl as service name and 1521 as port number

2. Steps for creating a new user


a) Open command prompt
b) Sqlplus / as sysdba
c) Create user <username> identified by <password>; [ For example to create a user named
“test” with password “test” : create user test identified by test; ]
d) Grant connect,resource to <username>; [ E.g: grant connect,resource to test;]
e) Commit;
f) Exit;

3. Create Table [ To be done using sql commands, after logging-in as the new user that
has been created in above step ]

Table Name: RENTAL_TBL


Column Datatype Description
PROPERTYID VARCHAR2(20) PRIMARY KEY (auto
generated)
RENTALAMOUNT NUMBER(10, 2) NOT NULL
NOOFBEDROOMS NUMBER(2) NOT NULL
LOCATION VARCHAR2(20) NOT NULL
CITY VARCHAR2(20) NOT NULL

Sequence Name: RENTAL_SEQ


Sequence Minimum Max Incremental Start
Name Value Values value Value
Rental_se 1000 9999 1 1000
q

B. System Design:
Name of the package Usage
com.wipro.hms.service This package will contain the class that displays the console
menu and takes the user input.
com.wipro.hms.bean This package will contain the bean class
com.wipro.hms.dao This package will contain the class that will do the database
related operations
com.wipro.hms.util This package will contain a class to establish database
connection and also another class that handles the user defined
exception.

Package: com.wipro.hms.util
Class Method and Variables Description
DBUtil DB connection class

24
1151CS302-JAVA PROGRAMMING LAB LAB MANUAL

public static Establish a connection to the


Connection getDBConnection() database and return the
java.sql.Connection
reference
InvalidCityException User defined Exception class
public String toString() Returns “INVALID CITY”

Package: com.wipro.hms.bean
Class Method and Variables Description
RentalPropertyBean Class
private float rentalAmount;
private int noOfBedRooms;
private String location;
private String city;
private String propertyId;

Package: com.wipro.hms.dao
Class Method and Variables Description
RentalProp DAO class
ertyDAO
public String This method should return the propertyId
generatePropertyID(String city) which is auto generated using sequence.
Format: First 3 letters of the city in uppercase
followed by the 4 digit auto generated
number.
E.g. CHE1000 – if the city name is Chennai
public int  This method should invoke
createRentalProperty(RentalProp the generatePropertyIDmethod of this class,
ertyBean bean) receive the id and initialize the bean with the
id value.
 It should then insert the bean’s
properties into the rental_tbl and should return
the count of the records inserted
 If there is some Exception(could be
SQLException or any other Exception), the
function should return -1.

Package: com.wipro.hms.service
Class Method and Variables Description
Rental Main class
Property
Service
public static void main(String[] The code that is needed to test your program
args) goes here. A sample code is shown at the end
of the document.

25
1151CS302-JAVA PROGRAMMING LAB LAB MANUAL

public String  It returns “NULL VALUES IN


addRentalProperty(RentalProper INPUT” if city or location is null
tyBean bean)  It returns “INVALID INPUT” under
the following conditions
 Length of city or location is 0
 No of bedrooms/Rental amount is 0
 This method will call validateCity
method for validating city. If city is not either
Chennai or Bengaluru (not case sensitive) the
method should return “INVALID CITY”
In all other conditions this method should call
createRentalProperty method of DAO and
returns “SUCCESS” if record is inserted else
returns “FAILURE” if the record cannot be
inserted
public void validateCity(String  This method will throw
city) throws InvalidCityException if the provided city
InvalidCityException name is not either chennai or bengaluru (case
insensitive)

Main Method:
You can write code in the main method and test all the above test cases. A sample code of
the main method to test a test case is shown below for your reference.
public static void main(String[] args) {
RentalPropertyBean bean=new RentalPropertyBean();
bean.setCity("Chennai");
bean.setLocation("Velachery");
bean.setNoOfBedRooms(2);
bean.setRentalAmount(15000);
RentalPropertyService service=new RentalPropertyService();
System.out.println(service.addRentalProperty(bean));
}

15.WEATHER FORECAST SYSTEM

Project Assessment

GENERAL INSTRUCTIONS: Please carefully read the below instructions


The objective of this assessment is to check your ability to complete a project as per the provided
“Project Design”.
You are expected to –
1. Write the source code for the classes, methods and packages EXACTLY as mentioned in
the “Project Design” section.
2. Ensure that the names of the packages, classes, methods and variables EXACTLY
MATCH with the names specified in the “Project Design” section.

26
1151CS302-JAVA PROGRAMMING LAB LAB MANUAL

3. Understand the project requirements and ACCORDINGLY WRITE the code and logic in
the classes and methods so as to meet all given requirements.
Creating the project
1. You are expected to create your project locally using eclipse (or any other IDE) on your
desktop.

Project Objective:
An online application needs to be created for entering weather reports for various locations and
later for viewing the reports.
Note: This application will cover only limited functionalities for the assessment.
Sample Output:
menu.html

1. If “Add Forecast” link is clicked, the following screen is shown


addForecast.jsp

On Successful Insert, the user should be directed to the success.html page.


success.html

27
1151CS302-JAVA PROGRAMMING LAB LAB MANUAL

If there is any error while adding the record, the following page should be displayed.
error.html

2. If “View Forecast” link is Clicked on menu.html, the below given page should be displayed
viewForecast.jsp

If matching records exists in the database, display the schedule details in the below given page.
displayForecast.jsp

28
1151CS302-JAVA PROGRAMMING LAB LAB MANUAL

If no matching records exists in the database, display the following message in


displayForecast.jsp

Project Design:
A. Database Design:
1. Create a new user in database [ To be done in the backend by using sql commands ]
a) Note: Use the default scott/tiger account of oracle for this project. You will have to create
a new user in the below mentioned format.
c) For JDBC connection, only use orcl as service name and 1521 as port number

2. Steps for creating a new user


a) Open command prompt
b) Type Sqlplus / as sysdba
c) Create user <username> identified by <password>; [ For example to create a user
named “test” with password “test” : create user test identified by test; ]
d) Grant connect, resource to <username>; [E.g: grant connect, resource to test;]
e) Commit;
f) Exit;

3. Create Table [ To be done using sql commands, after logging-in as the new user that
has been created in above step ]

Table Name: WEATHER_TB

29
1151CS302-JAVA PROGRAMMING LAB LAB MANUAL

Column Datatype Description


REPORTID VARCHAR2(12 BYTE) Primary Key
LOCATION VARCHAR2(30 BYTE) Not null
R_DATE DATE Not null
TEMPERATURE NUMBER
HUMIDITY NUMBER
WIND VARCHAR2(10)
FORECAST VARCHAR2(50 BYTE)

Sequence Name: WEATHER_SEQ


Sequence Name Start Value Max Value Increment By
WEATHER_SEQ 10 99 1

B. System Design: Server Side


Name of the package Usage
com.wipro.weather.util Contains the class that establishes the database connection
com.wipro.weather.bean Contains all the bean classes
com.wipro.weather.dao Contains the DAO classes that performs the real JDBC
operations
com.wipro.weather.service Contains the administrator class that receives input from Servlets
and then invokes the respective DAO class methods
com.wipro.weather.servlets Contains the MainServlet that performs the role of a Controller

Package: com.wipro.weather.util

Class Method and Variables Description


DBUtil DB connection class
static Establish a connection to
Connection getDBConnection() the database and return the
java.sql.Connection
reference

Class Method and Variables Description


InvalidInputException Exception Class
String toString() Return the error message:
“Invalid Input”

Package: com.wipro.weather.bean
Class Method and Variable Names Description
WeatherBean Bean Class
String reportId ID number of the weather report
String location Location
Date date java.util.Date
int humidity Humidity

30
1151CS302-JAVA PROGRAMMING LAB LAB MANUAL

int temperature Temperature


String wind Wind in Kilometer/Hour
String forecast Forecast of the specific location
Setters and Getters for all properties Using Eclipse, create getters and
setters for all the properties

Package: com.wipro.weather.dao
Class Method and Description
Variables
WeatherDAO DAO class
public String  This method is used to insert the weatherBean
createForecast(Weat attributes into the WEATHER_TB table
herBeanweatherBea  If the insertion is successful, this method should
n) return the reportId of the weatherBean
 It returns “FAIL” if the value is not inserted
public  This method is used to fetch the weather report of
WeatherBeanfetchFo a specific location on a specific date from the
recast(String WEATHER_TB table.
location, Date date)  If no records are found, this method will return
null.
public String  This method is used to generate the reportId of
generateReportID(St the Weather forecast before the report is stored in the
ring location,Date WEATHER_TB table.
date)  The reportId should be a combination of the
date in YYYYMMDD format followed by first two
letters of location in uppercase followed by a two
digit random number generated by the sequence
WEATHER_SEQ
 ie. If the date entered is 14 Dec 2015 and the
location is Bengaluru then the reportId should be
20151214BE11 where 11 is the number generated from
sequence.

To convert the date into required format, the


following code can be used:
DateFormat
format=newSimpleDateFormat("yyyyMMdd");
String temp=format.format(date);

If date variable value is 14 Dec 2015(12/14/2015) then


the tempvariable will contain “20151214”

public  This method is used to check whether for the


booleanreportExists( given date and location, the weather report exists or not.
String location,Date  It will return true if the data already exists for the
date) given location and date

31
1151CS302-JAVA PROGRAMMING LAB LAB MANUAL

 Otherwise it will return false


[ Hint : Use fetchForecast method if required]

Package: com.wipro.weather.service
Class Method and Description
Variables
Administrator
public String  This method receives a WeatherBean object
addForecast(Weath  The following checks need to be made before
erBeanweatherBean proceeding further
) 1. If the weatherBean object is null or location is null
or date is null, then this should throw an
InvalidInputException and return the exception
message “INVALID INPUT”
2. If the length of location name is less than 2
characters then it should return “INVALID
LOCATION”
3. The date should be a future date. If the date is in
the past or current date, then it should return “INVALID
DATE”
4. Calls the reportExists(String location,Date
date) method of WeatherDAO to check whether the
report already exists for the given location and date. If
exists, then it should return “ALREADY EXISTS”
 Otherwise calls generateReportID(String
location,Date date)ofWeatherDAO which will return a
reportId
 If the reportId is successfully generated, initialize
the weather bean id and
call createForecast(WeatherBeanweatherBean) of
WeatherDAO and return a string indicating the status of
the operation
public  This method receives a location and date
WeatherBeanviewF  It should call fetchForecast(String location, Date
orecast(String date) of WeatherDAO and will return the matching bean
location,Date date) object

Package: com.wipro.weather.servlets
Class Method and Description
Variables
MainServlet Servlet Class
public String  This method is invoked by the
addForecast(HttpSer doPost(HttpServletRequest request, HttpServletResponse
vletRequest request) response) method of the Servlet Class if the Client has
clicked on ‘Add Forecast’ link in the menu page

32
1151CS302-JAVA PROGRAMMING LAB LAB MANUAL

 This method will create a WeatherBean Object and


will initialize all its properties with the values that are
available in the request object
 It will invoke the Administrator
class’s addForecast(WeatherBeanweatherBean)and will
return the String value received from it
public  This method is invoked by the
WeatherBeanviewFo doPost(HttpServletRequest request, HttpServletResponse
recast(HttpServletRe response) method of the Servlet Class if the Client has
quest request) clicked on ‘View Forecast’ link in the menu page
 This method will invoke the
WeatherBeanviewForecast(String location,Date date)method
of the Administrator Class and it should return the
WeatherBean object received from it

protected void  This method processes the Client’s request


doPost(HttpServletR  It accesses a request parameter called ‘operation’ and
equest request, based on the value of that parameter, it’ll decide whether to
HttpServletResponse access the addForecast(HttpServletRequest
response) throws request) or viewForecast(HttpServletRequest
ServletException, request) method
IOException  If the operation parameter value is ‘newForecast’ then
the following things needs to be done
1. the addForecast(HttpServletRequest
request) method should be called
2. If return value equals “FAIL” or exception message
then the servlet should redirect to "error.html"
3. Otherwise it should redirect to“success.html”
 If the operation parameter value is ‘viewForecast’ then
the following things needs to be done
1. viewForecast(HttpServletRequest request) method
will be invoked
2. If the return value is null the servlet should redirect
to “displayForecast.jsp” displaying a message- ‘No
matching records exists! Please try again!’
3. Else the WeatherBean object should be set as an
attribute to the request object and should forward the control
to “displayForecast.jsp”

B. System Design: UI Pages

33
1151CS302-JAVA PROGRAMMING LAB LAB MANUAL

1. menu.html  Contains two links Add


Forecast and View Forecast
 Add Forecast link will take
you to addForecast.jsp
 View Forecast will take you to
viewForecast.jsp

2. addForecast.jsp  In the HTML form include


this tag
<input type="hidden"
name="operation"
value="newForecast">. This will
help the MainServlet to understand
that the add operation need to be
done
 When the submit button is
clicked it invokes the post method
of the MainServlet
3.error.html  If there is any error during
record insertion, should display the
Following message

“Error! Please try again!”

4.success.html  If the record is inserted then


display the message- ‘Added
successfully’

5.  When the Search button is


viewForecast.jsp clicked it invokes the post method
of the MainServlet
 In the HTML form include
this tag
<input type="hidden"
name="operation"
value="viewForecast">. This will
help the MainServlet to understand
that the view operation need to be
done.

34
1151CS302-JAVA PROGRAMMING LAB LAB MANUAL

6.  If the combination of location


displayForecast.js and date exists, display the
p matching reports.
 Otherwise display- ‘No
matching records exists! Please
try again!’

Sample Test Cases:


1. Test add forecast functionality with valid values
2. Test add forecast with all invalid conditions
3. Test add forecast with null values
4. Test add forecast where report already exists
5. Test view forecast with valid values
6. Test view forecast with invalid values
7. Test for add Forecast method of Servlet
8. Test for view Forecast method of Servlet

16. UNIVERSITY MANAGEMENT SYSTEM

Project Assessment

GENERAL INSTRUCTIONS: Please carefully read the below instructions


The objective of this assessment is to check your ability to complete a project as per the provided
“Project Design”.
You are expected to –
1. Write the source code for the classes, methods and packages EXACTLY as mentioned in
the “Project Design” section.
2. Ensure that the names of the packages, classes, methods and variables EXACTLY
MATCH with the names specified in the “Project Design” section.
3. Understand the project requirements and ACCORDINGLY WRITE the code and logic in
the classes and methods so as to meet all given requirements.
Creating the project and testing it –
1. You are expected to create your project locally using eclipse (or any other IDE) on your
desktop.
Project Objective:
35
1151CS302-JAVA PROGRAMMING LAB LAB MANUAL

Create a console based Java application that allows the university admin to validate and add
school or college students, calculate grade points and display the final grade on the basis of
marks obtained.
Project Design:
Create a sequence STUD_SEQ starting with 1000 and incrementing by 5.
Create the STUD_DETAILS table with the following columns :
Note: only these fields need to be added in database.
Column Name Data_Type
studentId Varchar(7)
studentName Varchar(25)
studentAge Integer
studentType Varchar(1)
StudentAdmNo Integer
studentGP Integer

A. System Design:
Name of the package Usage
com.wipro.ums.bean This package will contain the bean classes
com.wipro.ums.util This package will contain the user defined exception class
com.wipro.ums.main This package will contain the main class that is used to test the
application
com.wipro.ums.service This package will contain the class that is used to validate the
data and calculate the result
com.wipro.ums.dao This package will contain the class that is used to add students
details to the database.

Package: com.wipro.ums.util
Class Method and Variables Description
StudentValidationException An Exception Class
public String toString() Returns the message
“Invalid Student Details”

Package: com.wipro.ums.bean
Class Method and Variables Description
StudentBean Abstract Class
public StudentBean() Zero argument constructor
String studentId Unique five digit Student ID
String studentName Student name
intstudentAge Student age
char studentType Student type
intStudentAdmNo Five digit admission number of the
student
intstudentMarks[] Array of marks in six subjects
intstudentGP Grade point obtained by student

36
1151CS302-JAVA PROGRAMMING LAB LAB MANUAL

public abstract Abstract method


intcalcGradePoint(int[] marks)
public abstract String Abstract method
calcGrade(intsGradePoint)
setters & getters Should create the getter and setter
methods for all the attributes
mentioned in the class

Package: com.wipro.ums.bean
Class Method and Variables Description
SchoolStudentBean Class
public SchoolStudentBean() Zero argument constructor
public intcalcGradePoints(int[] This method accepts the marks
marks) array, calculates average marks by
diving sum of all marks[i] by
length of the array.
Then it computes and returns the
grade points (as given in the “Table
for School Student”) on the basis
of average marks calculated.
It should return -1 for any case not
specified in table.
public String It calculates and returns the student
calcGrade(intsGradePoint) grade on the basis of sGradePoint.
Refer the grading given in the
“Table for School Student”.
It should return null for any case
not specified in table.

Package: com.wipro.ums.bean
Class Method and Variables Description
College Class
Student
Bean
public Zero argument constructor
CollegeStudentBean()
public This method accepts the marks array, calculates
intcalcGradePoints(int[] average marks by diving sum of all marks[i] by
marks) length of the array.
Then it computes and returns the grade points (as
given in the “Table for College Student”) on the
basis of average marks calculated.
It should return -1 for any case not specified in
table.
public String It calculates and returns the student grade on the
calcGrade(intsGradePoint) basis of sGradePoint.

37
1151CS302-JAVA PROGRAMMING LAB LAB MANUAL

Refer the grading given in the “Table for College


Student”.
It should return null for any case not specified in
table.
Table for School Student
Average Marks Range Grade Point Grade
91-100 10 A1
81-90 9 A2
71-80 8 B1
61-70 7 B2
51-60 6 C1
41-50 5 C2
33-40 4 D
21-32 3 E1
00-20 0 E2
Table for College Student
Average Marks Range Grade Point Grade
90-100 10 A+
80-89 9 A
70-79 8 B+
60-69 7 B
55-59 6 C+
45-54 5 C
40-44 4 D
39 or less 0 F

Package: com.wipro.ums.dao
Class Method and Variables Description
StudentDA Class
O
public String This method adds the studBean to the
addStudent(StudentBeanstudBean) STUD_TABLE.
It should return “SUCCESS” in case
student data has been added successfully.
It should return “FAILURE” in any other
case.

Package: com.wipro.ums.service
Class Method and Variables Description
Student Class
Service
public String generateID(String This method accepts studentName and
studentName, StudentAdmNo and generates studentId as
intStudentAdmNo) follows:
First two letters of studentName converted

38
1151CS302-JAVA PROGRAMMING LAB LAB MANUAL

to uppercase and concatenated with the


STUD_SEQ.
For ex: if studentName is “Robin”
STUD_SEQ value is 12345, then studentId
becomes “RO12345”.
public String This method validates the input values and
validateStudent(String sName, throws StudentValidationException if:
char sType, intsAge, • sNameor sMarks is null
intsAdmNo ,int[] sMarks) • sAge or sAdmNo is zero,
• sType is anything other than ‘S’ or
‘C’.
The exception should be caught in the
same method and the method should return
“Invalid Student Details”.

It should return “Invalid Marks” if


SMarks[i] is less than 0 or greater than
100.
It should return “Incorrect Admission
No” length of sAdmNo is not five.
It should return “Invalid Age” ifsAge is
less than 0 or greater than 26.
If all the values are valid, the method
should return “SUCCESS”.
public String addStudent(String This method will invoke the
sName, char sType, intsAge, validateStudent method to check whether
intsStudentAdmNo ,int[] all the inputs received are valid.
sMarks) • If validateStudent() returns
“SUCCESS”:
• Create appropriate StudentBean
object [SchoolStudentBean
object if sType is ‘S’ or
CollegeStudentBean is sType is
‘C’] and assign the input
parameters to the newly created
object.
• Assign the studentID by calling the
generateID() method.
• Invoke the calcGradePoints()
method and assign the returned
value to the studentGP of the
created object.
• Invoke the calcGrade() method
with the studentGP obtained.
Invoke addStudent() of StudentDAO and
add the student details to the database.

39
1151CS302-JAVA PROGRAMMING LAB LAB MANUAL

Return “SUCCESS” if addStudent returns


“SUCCESS” message, else return
“FAILURE”.
If validateStudent() returns any message
other than “SUCCESS” then this method
should return “Invalid Input”.
Package: com.wipro.ums.main
Class Method and Variables Description
StudentMai Class
n
public static void main(String Get the following input from the user
args[]) • Get student name
• Get the student type
• Get the student age
• Get the student admission number
• Get the student marks
After receiving all this data, invoke the
addStudent() method of StudentService
class present in com.wipro.ums.service
package and test your program
The main method of the StudentMain Class may look like this:
public static void main(String args[])
{
System.out.println(new StudentService().addStudent (“Robin”, ’S’, 17, 12548, new int[]
{44,88,67,90,78,65}));
}
Test your program with different inputs.

17. BUS SCHEDULE MANAGEMENT SYSTEM

Project Assessment

GENERAL INSTRUCTIONS: Please carefully read the below instructions


The objective of this assessment is to check your ability to complete a project as per the provided
“Project Design”.
You are expected to –
1. Write the source code for the classes, methods and packages EXACTLY as mentioned in
the “Project Design” section.
2. Ensure that the names of the packages, classes, methods and variables EXACTLY
MATCH with the names specified in the “Project Design” section.
3. Understand the project requirements and ACCORDINGLY WRITE the code and logic in
the classes and methods so as to meet all given requirements.
Creating the project and testing it –
1. You are expected to create your project locally using eclipse (or any other IDE) on your
desktop.

40
1151CS302-JAVA PROGRAMMING LAB LAB MANUAL

Bus Schedule Management System


Project Objective:
BlueBus.com is an online bus ticket booking system. They wanted to develop an administrator
module to add schedules of different buses. This is only a part of their application.
Sample Output:
menu.html

1. If “Add Schedule” link is clicked, the following screen is shown


addSchedule.jsp

On Successful Insert, the user should be directed to the success.jsp page.


success.jsp

If there is any error while adding the record, the following page should be displayed.

41
1151CS302-JAVA PROGRAMMING LAB LAB MANUAL

errorInserting.html

2. If “View Schedule” link is Clicked on menu.html, the below given page should be
displayed
viewSchedule.jsp

If matching records exists in the database, display the schedule details in the below given page.
displaySchedule.jsp

If no matching records exists in the database, display the following message in


displaySchedule.jsp

42
1151CS302-JAVA PROGRAMMING LAB LAB MANUAL

Project Design:
A. Database Design:
1. Create a new user in database [ To be done in the backend by using sql commands ]
a) Note: Do NOT use the default scott/tiger account of oracle for this project. You will have
to create a new user in the below mentioned format.
b) Username/password : B<batchnumber><employeeid>
For example, if your batch number is 39806 and Employee number is 12345, then the oracle user
should be B3980612345 and the password should be B3980612345
c) For JDBC connection, only use orcl as service name and 1521 as port number

2. Steps for creating a new user


a) Open command prompt
b) Type Sqlplus / as sysdba
c) Create user <username> identified by <password>; [ For example to create a user
named “test” with password “test” : create user test identified by test; ]
d) Grant connect, resource to <username>; [ E.g: grant connect, resource to test;]
e) Commit;
f) Exit;

3. Create Table [ To be done using sql commands, after logging-in as the new user that
has been created in above step ]

Table Name: SCHEDULE_TBL


Column Datatype Description
SCHEDULEID VARCHAR2(8 BYTE) Primary Key
SOURCE VARCHAR2(30 BYTE) Not null
DESTINATION VARCHAR2(30 BYTE) Not null
STARTTIME VARCHAR2(5 BYTE)
ARRIVALTIME VARCHAR2(5 BYTE)

Sequence Name: SCHEDULE_SEQ


Sequence Name Minimum Max Incremental Start

43
1151CS302-JAVA PROGRAMMING LAB LAB MANUAL

Value Values value Value


SCHEDULE_SEQ 1000 9999 1 1000

B. System Design: Server Side


Name of the package Usage
com.wipro.bus.util Contains the class that establishes the database connection
com.wipro.bus.bean Contains all the bean classes
com.wipro.bus.dao Contains the DAO classes that performs the real JDBC
operations
com.wipro.bus.service Contains the administrator class that receives input from Servlets
and then invokes the respective DAO class methods
com.wipro.bus.servlets Contains the MainServlet that performs the role of a Controller

Package: com.wipro.bus.util
Class Method and Variables Description
DBUtil DB connection class
static Establish a connection to
Connection getDBConnection() the database and return the
java.sql.Connection
reference

Class Method and Variables Description


InvalidInputException Exception Class
String toString() Return the error message:
“Invalid Input”

Package: com.wipro.bus.bean
Class Method and Variable Description
Names
ScheduleBea Bean Class
n
String scheduleId ID number of the schedule
String source Source of bus schedule
String destination Destination of bus schedule
String startTime Start time of bus
String arrivalTime Arrival time of the bus
Setters and Getters for Using Eclipse, create getters and setters for all the
all properties properties

Package: com.wipro.bus.dao
Class Method and Variables Description
ScheduleDA DAO class
O
public String  This method receives a ScheduleBean object

44
1151CS302-JAVA PROGRAMMING LAB LAB MANUAL

createSchedule(Schedul and inserts the values in the database


eBean scheduleBean) . If inserted the method should return
"SUCCESS"
public String  This method receives two strings- source
generateID(String name and destination name and creates a scheduleId
source, String from it.
destination)  The Schedule ID is a combination of first two
letters of source in uppercase, first two letters of
destination in uppercase followed by 4 digit number
generated from a sequence in database.
 Eg: If source is Chennai and destination is
Bengaluru then the scheduleId will be CHBE1234
where 1234 is the number generated by the
sequence.
public ArrayList<Sched  Should fetch the records matching criteria and
uleBean> return the collection.
viewSchedule(String
source,String
destination)

Package: com.wipro.bus.service
Class Method and Variables Description
Administrato
r
public String  This method receives a ScheduleBean object
addSchedule(Schedule  Refer testcases given at the end of the
Bean scheduleBean) document and perform the necessary validations.
 If same source and destination is provided
should give back a message “Source and
Destination Same”
 If validation is successful, then
Call generateID(String source, String
destination) from dao which will return a schedule
ID and store the same in the bean.
 Invoke createSchedule(ScheduleBean
scheduleBean) from dao and return the string value
For other user defined error messages, please look at
the test cases given at the end of the document.
publicArrayList<Sched  This method receives the names of source and
uleBean> destination and returns an ArrayList of
viewSchedule(String ScheduleBean with matching records.
source,String
destination)

Package: com.wipro.bus.servlets
Class Method and Variables Description

45
1151CS302-JAVA PROGRAMMING LAB LAB MANUAL

MainServl Servlet Class


et
public String  This method is invoked by the
addSchedule(HttpServletR doPost(HttpServletRequest request,
equest request) HttpServletResponse response) method of the
Servlet Class if the Client has clicked on ‘Add
Schedule’ link in the menu page
 This method will create a ScheduleBean
Object and will initialize all its properties with the
values that are available in the request object
 It will invoke the Administrator
class’s addSchedule(ScheduleBean
scheduleBean) and will return the String value
received from String addSchedule(ScheduleBean
scheduleBean) method
public ArrayList<Schedul  This method is invoked by the
eBean> doPost(HttpServletRequest request,
viewSchedule(HttpServlet HttpServletResponse response) method of the
Request request) Servlet Class if the Client has clicked on ‘View
Schedule’ link in the menu page
 This method will invoke the
viewSchedule(String source,String
destination) method of the Administrator Class and it
should return the ArrayList of ScheduleBean object
received
protected voiddoPost(Http  This method processes the Client’s request
ServletRequest request,  It accesses a request parameter called
HttpServletResponse ‘operation’ and based on the value of that parameter,
response) throwsServletEx it’ll decide whether to access
ception, IOException the addSchedule(HttpServletRequest
request) or viewSchedule(HttpServletRequest
request) method
 If the operation parameter value is
‘newSchedule’ then the following things needs to be
done
1. the addSchedule(HttpServletRequest
request) method should be called
2. If return value equals “SUCCESS” the servlet
should redirect to “success.jsp”
3. If return value equals “FAIL” or exception
message then the servlet should redirect
to "errorInserting.html"
 If the operation parameter value is
‘viewSchedule’ then the following things needs to be
done
1. viewSchedule(HttpServletRequest

46
1151CS302-JAVA PROGRAMMING LAB LAB MANUAL

request) method will be invoked


2. If the return value is null the servlet should
redirect to “displaySchedule.jsp” displaying a
message- ‘No matching schedules exists!
Please try again!’
3. Else the ArrayList of beans should be set as an
attribute to the request object and should forward the
control to “displaySchedule.jsp”

B. System Design: UI Pages


1.  Contains two links Add
menu.html Schedule and View Schedule
 Add Schedule link will take
you to addSchedule.jsp
 View Claim link will take you
to viewSchedule.jsp

2.  In the HTML form include this


addSchedule tag
.jsp <input type="hidden"
name="operation"
value="newSchedule">.This will
help the MainServlet to understand
that the add operation need to be
done
 When the submit button is
clicked it invokes the post method of
the MainServlet

3.errorInsert  If there is any error during


ing.html record insertion, should display the
Following message

“Error in adding the record! Please


try again!”

47
1151CS302-JAVA PROGRAMMING LAB LAB MANUAL

4.success.jsp  If the record is inserted then


display the message- ‘Added
successfully’

5.  When the Search button is


viewSchedul clicked it invokes the post method of
e.jsp the MainServlet
 In the HTML form include this
tag
<input type="hidden"
name="operation"
value="viewSchedule">.This will
help the MainServlet to understand
that the view operation need to be
done.

6.  If the combination of source


displaySche and destination exists, display the
dule.jsp matching schedules.
 Otherwise display- ‘No
matching schedules exists! Please
try again!’

48
1151CS302-JAVA PROGRAMMING LAB LAB MANUAL

Example Test Cases:


Testcase No Testcase Expected Result
1 Passing bean object with valid values SUCCESS
to addSchedule(ScheduleBean
scheduleBean) method of
Administrator class
2 Passing null bean object The user define exception
to addSchedule(ScheduleBean InvalidInputException is
scheduleBean) method of thrown and ‘INVALID
Administrator class INPUT’ is returned
3 Passing bean object with empty The user define exception
source or destination InvalidInputException is
to addSchedule(ScheduleBean thrown and ‘INVALID
scheduleBean) method of INPUT’ is returned
Administrator class
4 Passing bean object with source or The user define exception
destination which has less than 2 InvalidInputException is
letters to addSchedule(ScheduleBean thrown and ‘INVALID
scheduleBean) method of INPUT’ is returned
Administrator class
5 Passing valid source and destination ArrayList of ScheduleBean
to viewSchedule(String source,String objects which is not null
destination)method of Administrator
class
6 Passing invalid source and Null
destination to viewSchedule(String
source,String destination)method of
Administrator class
7 Checking whether the servlet IMPLEMENTED
methods are implemented

18. LIBRARY MANAGEMENT SYSTEM

Project Assessment

GENERAL INSTRUCTIONS: Please carefully read the below instructions


The objective of this assessment is to check your ability to complete a project as per the provided
“Project Design”.
You are expected to –
1. Write the source code for the classes, methods and packages EXACTLY as mentioned in
the “Project Design” section.
2. Ensure that the names of the packages, classes, methods and variables EXACTLY
MATCH with the names specified in the “Project Design” section.

49
1151CS302-JAVA PROGRAMMING LAB LAB MANUAL

3. Understand the project requirements and ACCORDINGLY WRITE the code and logic in
the classes and methods so as to meet all given requirements.
Creating the project and testing it –
1. You are expected to create your project locally using eclipse (or any other IDE) on your
desktop.

Project Objective:
Azim Premji University maintains a library of Books written by their faculty members which are
published by different Publishers. Develop a web based application that helps the librarian to
perform some basic operations like
a) Adding a book to the database
b) Fetching the details of the book including the Author information
Menu.html

1. If “Add Book” link is clicked, the following screen is shown


AddBook.html

50
1151CS302-JAVA PROGRAMMING LAB LAB MANUAL

On Successful Insert, the user should be directed to the menu.html page again.

2. If “View Book” link is Clicked, there are two Scenarios


Scenario 1: Book with the given isbn exists
Scenario 2: Book with the given isbn does not exist

Scenario 1: Book with the given isbn exists


ViewBook.html

51
1151CS302-JAVA PROGRAMMING LAB LAB MANUAL

View.jsp

Scenario 2: Book with the given isbn does not exist


ViewBook.html

Invalid.html

52
1151CS302-JAVA PROGRAMMING LAB LAB MANUAL

Project Design:
A. Database Design:
1. Create a new user in database [ To be done in the backend by using sql commands ]
a) Note: Do NOT use the default scott/tiger account of oracle for this project. You will have
to create a new user in the below mentioned format.
b) Username/password : B<batchnumber><employeeid>
For example, if your batch number is 39806 and Employee number is 12345, then the oracle user
should be B3980612345 and the password should be B3980612345
c) For JDBC connection, only use orcl as service name and 1521 as port number

2. Steps for creating a new user


a) Open command prompt
b) Type Sqlplus / as sysdba
c) Create user <username> identified by <password>; [ For example to create a user
named “test” with password “test” : create user test identified by test; ]
d) Grant connect,resource to <username>; [ E.g: grant connect,resource to test;]
e) Commit;
f) Exit;

3. Create Table [ To be done using sql commands, after logging-in as the new user that
has been created in above step ]

Table Name: Author_Tbl [ Master Table ]


Column Datatype Description
Author_code Number(5) Primary Key
Author_name Varchar2(20) Not null
Contact_no Number(10)

[Note: Insert 3 valid Author Details and commit]

Sample Input:
AUTHOR_CODE AUTHOR_NAME CONTACT_NO
----------- -------------------- ---------------------------------------
1 RobinSharma 8800799224
2 R.K.Narayan 9971935000
3 Paulo Coelho 1234567890

Table Name: Book_Tbl [Transaction Table]


Column Datatype Description
ISBN Varchar2(10) Primary Key
Book_title Varchar2(20) Not null
Book_type Char(1) Should accept only ‘G’ or ‘T’
(G- General, T-Technical)
Author_code Number(5) Not Null and the values used
here should be present in the
Author_Tbl

53
1151CS302-JAVA PROGRAMMING LAB LAB MANUAL

Book_cost Number(8,2) Not Null

B. System Design: Server Side


Name of the package Usage
com.wipro.book.util Contains the class that establishes the database connection
com.wipro.book.bean Contains all the bean classes
com.wipro.book.dao Contains the DAO classes that performs the real JDBC
operations
com.wipro.book.service Contains the administrator class that receives input from Servlets
and that invokes the respective DAO class methods
com.wipro.book.servlets Contains the MainServlet that performs the role of a Controller

Package: com.wipro.book.util
Class Method and Variables Description
DBUtil DB connection class
public static Establish a connection to the
Connection getDBConnection() database and return the
java.sql.Connection reference

Package: com.wipro.book.bean

Class Method and Variables Description


AuthorBean Bean Class
int authorCode Numeric code of the Author
String authorName Name of the Author
long contactNo Contact Number of the Author
Setters and Getters for all properties Using Eclipse, create getters and
setters for all the properties

Class Method and Variables Description


BookBean Bean Class
String isbn ISBN of the book. This can
include characters and digits.
String bookName Name of the book
AuthorBean author Author of book
char bookType; Category of Book( Can have ‘G’
or ‘T’
float cost Cost of Book.
Getters and Setters Using Eclipse, create getters and
setters for all the properties

Package: com.wipro.book.dao

54
1151CS302-JAVA PROGRAMMING LAB LAB MANUAL

Class Method and Variables Description


AuthorDAO DAO class
AuthorBean  This method receives the authorCode and fetches
getAuthor(int the corresponding author details from the Author_tbl
authorCode) and the function should return that AuthorBean object
 If there is no such author with the given
authorCode the function should return null

AuthorBean  This method receives the authorName and


getAuthor(String fetches the corresponding author details from the
authorName) Author_tbl and the function should return
that AuthorBean object
 If there is no such author with the given
authorName the function should return null
 [Note : Assumption is Author names are
unique]

Class Method and Variables Description


BookDAO DAO class
BookBean  This method receives an isbn and it should fetch
fetchBook(String isbn) the corresponding book details from book_tbl,
author_tbl and should return the corresponding
BookBean object
 Note: For the given isbn number, it should
fetch the corresponding author details from the
Author_tbl
 The function may use the getXXX() methods
present in the AuthorDAO class to fetch those details
 The BookBean object should be initialized
with the respective author details and return that
object
 If there is no such book with the given isbn

55
1151CS302-JAVA PROGRAMMING LAB LAB MANUAL

number, then the function should return null


int  This method should take the values from the
createBook(BookBean bookBean object and insert it into the Book_Tbl.
bookBean)  The function should return a value 1 on
successful insertion
 In case of any JDBC exception such as
SQLException occur, this function should return 0

Package: com.wipro.book.service

Class Method and Description


Variables
Administrator Main class
String  This method should add a BookBean Object to
addBook(BookBean the database.
bookBean)  This method returns a String “INVALID” under
the following conditions
 bookBean is null
 bookName of bookBean is empty String
 isbn of bookBean is empty String
 bookType of bookBean
is empty space
 bookType of bookBean is neither ‘G’ nor ‘T’
 cost of bookBean is 0
 authorName of Author is empty
 It invokes the createBook(BookBean bookBean)
of the BookDAO class to add the bean object
 If the insertion was successful this method
returns “SUCCESS”
 Else it returns “FAILURE”

56
1151CS302-JAVA PROGRAMMING LAB LAB MANUAL

BookBean  This method should return the BookBean Object


viewBook(String for the corresponding isbn String passed.
isbn)  It invokes the fetchBook(String isbn) method of
the BookDAO class
 If there was a book with the given isbn, then the
corresponding BookBean object will be returned
 If the isbn is empty then the function returns null

Package: com.wipro.book.servlets
Class Method and Variables Description
MainServle Servlet Class
t
public String  This method is invoked by the
addBook(HttpServletReques doPost(HttpServletRequest request,
t request) HttpServletResponse response) method of the
Servlet Class if the Client has clicked on ‘Add
Book’ link in the menu page
 This method will create a BookBean Object
and will initialize all its properties with the values
that are available in the request object
 It will invoke the Administrator class’s
addBook(BookBean bookBean) by passing the
BookBean object that was initialized
 The method will return the String value
received from addBook(BookBean bookBean)
method
public BookBean  This method will invoke the
viewBook(String isbn) viewBook(String isbn) method of the
Administrator Class and it should return the
BookBean object received
void  This method processes the Client’s request
doPost(HttpServletRequest  It accesses a request parameter called
request, ‘operation’ and based on the value of that
HttpServletResponse parameter, it’ll decide whether to access the
response) throws addBook(HttpServletRequest request) or

57
1151CS302-JAVA PROGRAMMING LAB LAB MANUAL

ServletException, viewBook(String isbn) method


IOException  [Note: The name of the submit
button in ‘AddBook.html’ and ‘ViewBook.html
’ is ‘operation’ and the Servlet uses this to
determine what operation needs to be done]
 If the operation parameter value is
‘AddBooks’ then the following things needs to be
done
1. addBook(request) method is called
2. If return value equals “SUCCESS” the
servlet should redirect to “Menu.html”
3. If return value equals “FAILURE” the
servlet should redirect to “Failure.html”
4. If return value equals “INVALID” the
servlet should redirect to “Invalid.html”
 If the operation parameter value is ‘Search’
then the following things needs to be done
1. viewBook(String isbn) method will be
invoked
2. If the return value is null the servlet should
redirect to “Invalid.html”
3. Else the bean should be set as an attribute to
the request object and should forward the control
to “View.jsp”

B. System Design: UI Pages


1. Menu.html  Contains two links Add Book and
View Book.
 Add Book link will take you to
AddBook.html
 View Book link will take you to
ViewBook.html
2. AddBook.html  For Book Type hard code the values
with ‘G’ for General and ‘T’ for Technical
 For Author Name hard code the
values from the Author_Tbl as it is
 The name of the submit button
is‘operation’and its value is ‘AddBooks’.
 When the submit button is clicked it
invokes the post method of ‘MainServlet’

58
1151CS302-JAVA PROGRAMMING LAB LAB MANUAL

3.  When the Search button is clicked it


ViewBook.html invokes the post method of the
MainServlet
 The name of the submit button
is‘operation’and its value is ‘Search’.
 When the submit button is clicked it
invokes the post method of ‘MainServlet’

4.Invalid.html  Will be called by the MainServlet


whenever Invalid
Input is given
 The details on when it has to be
called is specified earlier

5. Failure.html  Should display the


Following message

59
1151CS302-JAVA PROGRAMMING LAB LAB MANUAL

6. View.jsp  Used to display the Book Details

Example Test Cases:


Test Case 1: Test Null value for BookBean and invoke addBook method
Test Case 2: Test Empty BookBean attributes and invoke addBook method
Test Case 3: Test addBook method with empty author values
Test Case 4: Test addBook method with wrong category of Book
Test Case 5: Test addBook method with valid BookBean data
Test Case 6: Test addBook method with invalid author data
Test Case 7: Test the View Book functionality with correct ISBN
Test Case 8: Test the View Book functionality with incorrect ISBN
Test Case 9: Test viewBook method and addBook method from Servlet

60

You might also like