Core Java Lab Book (Patni Computer Systems, 2005 ) (Patni)

background image


Patni Computer Systems Ltd.

Core Java

Lab Guide






Version 3.0

3rd June 2005













Copyright © 2005 Patni Computer Systems., Akruti, MIDC Cross Road No. 21,
Andheri (E), Mumbai 400 093. All rights reserved. No part of this publication
reproduced in any way, including but not limited to photocopy, photographic,
magnetic, or other record, without the prior agreement and written permission
of Patni Computer Systems.
Patni Computer Systems, considers information included in this document to be
Confidential and Proprietary.

background image


Core Java




Core

Java

Lab Guide

Version 3.0

3rd June 2005


















Copyright

© 2005 by Patni

Page 2 of 53

background image


Core Java

Index

1 Introduction......................................................................4

2 Lab Exercise 1: Language Fundamentals ....................................7

3 Lab Exercise 2: OOPS in JAVA .................................................9

4 Lab Exercise 3: Inheritance in Java ........................................ 19

5 Lab Exercise 4: Working with Eclipse ...................................... 22

6 Lab Exercise 5: Packages and Interfaces .................................. 27

7 Lab Exercise 6: Exceptions .................................................. 30

8 Lab Exercise 7: Collection Classes.......................................... 32

9 Lab Exercise 8: Property Files............................................... 36

10 Lab Exercise 9: File Input / Output ........................................ 37

11 Lab Exercise 10: Multithreading in Java ................................... 40

12 Lab Exercise 11: AWT and Events........................................... 43

13 Lab Exercise 12: Java Swing................................................. 46

14 Lab Exercise 13: JDBC ........................................................ 49


Copyright

© 2005 by Patni

Page 3 of 53

background image


Core Java

Introduction

These hands-on labs will expose you to working with Java applications. Creating
Classes, Interfaces, GUI-based applications and applets, Database application,

networking and mailing concepts.

Setup Checklist for Java

Setup
Here is what is expected on your machine in order for the lab to work.
Minimum System Requirements


Intel Pentium 90 or higher (P166 recommended)
Any operating system having JVM implementation for it, like Microsoft Windows 95,
98, or NT 4.0,XP, 2000.
Memory: 64MB of RAM (higher recommended)
1GB hard disk space

VGA or higher resolution monitor
JDK version 1.4 with help, Netscape or IE
MS-Access


Please ensure that the following is done:

JDK 1.4 is installed. (This path is henceforth referred as <JAVA_HOME>)
Classpath environment variable is set. (Described below)

Path environment variable is set. (Described below)
A text editor like Notepad or WordPad is installed.
Eclipse as an IDE is installed.

Installing Eclipse:
Download eclipse-SDK-3.0-win32.zip.
Unzip the Eclipse SDK to a folder or directory of your choice, for example

d:\eclipse3.0

.

To start Eclipse, go to the

eclipse

subdirectory of the folder in which you extracted the

zip file (e.g.,

d:\eclipse3.0\eclipse

) and run

eclipse.exe

.

You will save all the examples given in this lab book in a directory, which is referred
as <USER_DIR>.


Note: Please replace the actual values of <JAVA_HOME> and <USER_DIR> wherever it
is referred.

Setting Classpath Environment variable:

Copyright

© 2005 by Patni

Page 4 of 53

background image


Core Java


Open the Control Panel and double click on System icon which opens System
Properties dialog box.
Select Environment tab page.

Select Classpath from the System Variables list as shown in the figure below.





















Append the string as given below to the Classpath value, if it does not already exists.
.;<JAVA_HOME>\lib\tools.jar;<JAVA_HOME>\lib\classes12.zip;

here (dot) specifies the current directory which is very much required.

Click on Set button to set this value.
Click on Apply and OK buttons to apply the value and dismiss the dialog box.

For accessing Oracle database through Java Program we need to include API support
from classes12.zip file. This file should be available in ORACLE-HOME\lib.

For jdbc assignments for working with DataSource and Rowsets tools.jar from
jdk1.5 is needed for API classes in javax.sql.rowset and orcs12.zip should be in the
classpath for Oracle Implementation of the RowSets.

Copyright

© 2005 by Patni

Page 5 of 53

background image


Core Java


Setting Path Environment variable:

Open the System dialog box as specified in “Setting Classpath Environment

variable”.

Select the Path variable from the Environment tab page and append the value as
given below, if does not exists.
<JAVA_HOME>\bin;
Set and apply the changes and click on OK to dismiss the dialog box.



Copyright

© 2005 by Patni

Page 6 of 53

background image


Core Java

Lab Exercise 1: Language Fundamentals

Estimated time to complete this exercise: 40 minutes
Objectives:
Create simple programs in Java language.

Problem 1:


Write a simple Java program that displays a message “Hello World”.

Solution:

Step 1: Type the following code in a text editor and save the file with the name
“Welcome.java”

class Welcome {

/*This is a block comment */

public static void main(String args[]) {


System.out.println(“Hello

World“);


} //main ends.


} //class ends


Step 2: Open the command prompt and change the directory to <USER_DIR>

Step 3: Compile the program by typing the following command

javac

Welcome.java


Step 4: After successful compilation let us now execute the program using the
command

java Welcome




Step 5: You should get the output as

Copyright

© 2005 by Patni

Page 7 of 53

background image


Core Java

Hello World



Problem 2: Using loops


Print the following output on screen

* * * *
* * *
* *
*
and

* * * *

* * *
* *

*

Problem 3:

Modify the Welcome program. Accept an integer value at command line and print the
message that many number of times. E.g. c:\>Welcome 2 should print message 2
times.

(Hint : use the args[] parameter of main(). This holds an array of strings, each
parameter represented by one string.)














Copyright

© 2005 by Patni

Page 8 of 53

background image


Core Java

Lab Exercise 2: OOPS in JAVA

Estimated time to complete this exercise: 120 minutes

Objectives:

Understand and Appreciate the Object Oriented Programming concepts used in Java
and concept of containment hierarchy.

Problem 1:

Create a Date class, which represents the Date with its attributes. Write a UseDate
class, which makes use of the Date class to instantiate, and call methods on the
object.

Solution:

Step 1: Type the following code in a text editor and save the file with the name
“UseDate.java”

class Date
{

int intDay, intMonth, intYear;

Date(int intDay, int intMonth, int intYear) // Constructor

{

this.intDay

=

intDay;

this.intMonth = intMonth;
this.intYear = intYear;
}

void setDay(int intDay)

// setter method for day

{

this.intDay

=

intDay;

}

int getDay( )

// getter method for month

{

return this.intDay;

}

void setMonth(int intMonth)

{

this.intMonth = intMonth;

Copyright

© 2005 by Patni

Page 9 of 53

background image


Core Java

}

int getMonth( )

{

return this.intMonth;

}

void setYear(int intYear)

{

this.intYear=intYear;

}

int getYear( )

{

return this.intYear;

}

public String toString() //converts date obj to string.

{

return “Date is “+intDay+”/”+intMonth+”/”+intYear;

}

} // Date class

class UseDate
{

public static void main(String[] args)

{

Date d = new Date(09,07,2002);

System.out.println(d); //invokes toString() method

}
}


Step 2: Open the command prompt and change the directory to <USER_DIR>


Step 3: Compile the program by typing the following command

javac

UseDate.java

Step 4: After successful compilation let us now execute the program using the
command

java

UseDate


Step 5: You should get the output as

Date is 09/07/2002

Copyright

© 2005 by Patni

Page 10 of 53

background image


Core Java

Step 6 : Redo the setter methods to incorporate validation checks. (Eg day should be
between 1 & 31, Year must be less than 1984 etc). Now accept a date using setter
methods and not the constructor.( For this you will need to create a default
constructor too.)




Copyright

© 2005 by Patni

Page 11 of 53

background image


Core Java

Problem 2:

Create a class Employee that has members as specified below. Implement the setter
and getter methods for the data members.

Step 1: Make the changes as required and save the file as Employee.java.

public class Employee

{

private int eCode;

// Employee Code

private String eName;

// Name

private String desig; // Designation

private int age;

// Age

private Date DOB;

// Date of Birth

public Employee()

// Constructor

{

// To Do: Initialize data members

}

public Employee(int eCode, String eName)

{

// To Do: Initialize data members based on the paramters

}

public Employee(int eCode, String eName,

String designation, int age)
{

// To Do: Initialize data members based on the parameters

}

// setter methods

void setEcode(int eCode)

{

// To Do: Setter method for eCode

}

public void setEname(String eName)

{

// To Do: Setter method for eName

}

void setDesig(String desig)

{

// To Do: Setter method for desig

}

void setAge(int age)

Copyright

© 2005 by Patni

Page 12 of 53

background image


Core Java

{

// To Do: Setter method for age

}

void setDOB(Date birthdate)

{

// To Do: Setter method for date of birth

}


// getter methods

int

getEcode()

{

// To Do: getter method for eCode

}

String

getEname()

{

// To Do: getter method for Ename

}


String

getDesig()

{

// To Do: getter method for desig

}

int

getAge()

{

// To Do: getter method for Age

}

Date getDOB()

{

// To Do: getter method for Salary

}

// prints the Employee details on the screen

public

void

displayDetails()

{

System.out.println("The Ecode is "+ eCode);

// To Do: Print the other members in the same format

}

} // end of class Employee


Step 3: Compile the program, which will create Employee.class file.

Copyright

© 2005 by Patni

Page 13 of 53

background image


Core Java

Step 4: Write the program given below, which creates an object of Employee and
calls the member to display the details, and save the file as “UseEmployee.java”

Copyright

© 2005 by Patni

Page 14 of 53

background image


Core Java

Class UseEmployee
{

public static void main(String[] args)

{

Employee e = new Employee( );

e.displayDetails(

);

}
}


Step 4: Compile and execute the program

Step 5: Write the results below









Step 6 : Now, override the toString() method of Object class to replace the
functionality of displayDetails() method.

public String toString(){
// code to return a string equivalent of Employee object
}


Step 7 : Change UseEmployee class as:

class UseEmployee

{

public static void main(String[] args)

{

Employee e = new Employee( );

System.out.println(“Employee details: “ + e);

}
}


Step 8 : What are the results?


Copyright

© 2005 by Patni

Page 15 of 53

background image


Core Java

Problem 3:

Write a class Dimond having following specifications :

Class Diamond{

char chartoprint;
int number;

Diamond(char a, int b){…}

Void PrintDiamond(……) : will print the diamond shape as shown
below wherein value of chartoprint is ‘*’ and the value of number
3.

*
* *
* * *
* *
*












Write the following main function in the same class to test the functionality.

Public static void main( String args[]) {

Diamond d = new Diamond(‘#’, 7)

d.printDiamond();
}

Problem 4:

Step 1: Create a class Product that contains detail of a product.

class Product{
int productId;
String description;
double price;
int unit;


Product (){…} //default constructor

Product (int ProdID, String Descr, double Price, int Unit) //constructor with 3
args


void displayDetails(){
//

display

product

details

}

Copyright

© 2005 by Patni

Page 16 of 53

background image


Core Java

public int getId(){
// return the product id
}

public String getDescription(){

// returns the description of product
}

public double getPrice(){
// returns the price
}


public int getUnit(){
// returns the unit

}
}

Step 2: Compile the program, which will create Product.class file.

Step 3: Write the program given below, which creates an object of Product and calls
the member to display the details, and save the file as “UseProduct.java”

Class UseProduct
{

public static void main(String[] args)

{

Product p = new Product( );

p.displayDetails(

);

}
}


Step 4: Compile and execute the program

Step 5: What is the result?


Problem 5 :

Step 1 : Create a class ArrayHelp, that behaves like a wrapper around an array. The
class should have methods to create array, add elements into it, shuffle contents of
array, search for an element in the array etc.


class ArrayHelp{

Copyright

© 2005 by Patni

Page 17 of 53

background image


Core Java

int contents [] // declare array.
ArrayHelp (int){

// Create array of size <int>

}

void populateContents(){

// Populate the array

}

void showContents(){

// Display contents of array.

}

Vector/void shuffleContents(){

// Algorithm to shuffle the contents

}

int searchElement(int Element-to-be-searched){

// search for element; if found, return its index location, else return –1.

}
}


Step 2: Compile the program, which will create ArrayHelp.class file.

Step 3: Write the program given below, which creates an object of ArrayHelp and
calls the various methods, and save the file as “UseArray.java”

Class UseArray
{

public static void main(String[] args)

{

ArrayHelp ah1 = new ArrayHelp( );

// call to the methods in the class.

}
}


Step 4: Compile and execute the program

Step 5: Observe the results
Hint: make use of Math.random() functions, Arrays, Collections classes.

(Note: Follow the setter and getter design pattern rd for all further assignments.)

Copyright

© 2005 by Patni

Page 18 of 53

background image


Core Java

Lab Exercise 3: Inheritance in Java

Estimated time to complete this exercise: 60 minutes

Objectives:

To study the use of Abstract classes, Inheritance, method overloading and overriding.

Problem 1:

Modify the Employee class to make it an abstract base class. Create a class Salaried

derived from Employee, which has, along with other members, two properties – HRA
and DA, a constructor, which takes two parameters to set the value for hra and da.
Override the displayDetails method to display HRA and DA.

Solution:

Step 1: Modify Employee.java file. Make Employee class as an abstract class and save
the file.

Step 2: Compile Employee.java file

Step 3: Create a class Salaried, which extends Employee class, in Salaried.java as
given below.

// To Do: Add the Salaried class signature here

{

private double da, hra;

// members of Salaried class


public

Salaried()

{

// To Do: implement the default constructor

}

public Salaried(int eCode, String eName, String desig,

int age, double da, int hra)
{

// To Do: implement the constructor

}

public Salaried(double da, double hra)

{

// To Do: implement the constructor

}

Copyright

© 2005 by Patni

Page 19 of 53

background image


Core Java

// write the setter and getter methods



// override the displayDetails method

// to display the new member details.

} // end of class Salaried;

Step 4: Compile the Salaried.java file, which creates Salaried.class file.

Step 5: Write the following code in UseSalaried.java file to check the Salaried class.

Class UseSalaried
{

public static void main(String[] args)

{

Salaried s1 = new Salaried(102,"BB","Accountant",53,10,50);

s1.displayDetails(

);

}
}


Step 6: Compile and run the program and write the output below






Problem 2:

Step 1 :Create two classes that derive from the Product class.

class Item …… {
height

width
length

warranty (in months)
cost of shipping (in rupees)
manufacturer

public displayDetails(){

// code to display item

}
}

class Service …………{
Date startDate

Date endDate

int startHour, startMin, endHour,
endMin
}

public displayDetails(){

// code to display item

}
}










Both the classes should override displayDetails() method from Product class.

Copyright

© 2005 by Patni

Page 20 of 53

background image


Core Java

Step 2 : Create two classes UseItem and UseService that allow objects of class Item
and class Service to be created.

class UseItem
{

public static void main(String[] args)

{

Item i1 = new Item(<appropriate parameters>);

i1.displayDetails();
}
}


class UseService
{

public static void main(String[] args)

{

Service s1 = new Service(<appropriate parameters>);

s1.displayDetails(

);

}
}

Copyright

© 2005 by Patni

Page 21 of 53

background image


Core Java

Lab Exercise 4: Working with Eclipse


Following are the guidelines to create a simple java project and a simple java

program with Eclipse3.0:
Open eclipse3.0 .

Select File->new->project->java project.

Click next and provide name for the project.

Copyright

© 2005 by Patni

Page 22 of 53

background image


Core Java

Click next and select build options for the project.

Copyright

© 2005 by Patni

Page 23 of 53

background image


Core Java

Click finish to complete the project creation.
Right-click on myproject, and select resource type to create, e.g. class if it is a java

class.

Copyright

© 2005 by Patni

Page 24 of 53

background image


Core Java

Provide name and other details for the class and click finish.

Copyright

© 2005 by Patni

Page 25 of 53

background image


Core Java


This will open MyClass.java in the editor, with ready skeleton for the class, with

default constructor and main() method , necessary javadoc comments.
Modify MyClass.java as per the requirement. Save the changes .
To run this class select Run from toolbar or select run as ->java application.Or select
run.. and will be guided through a wizard, for the selection of class containing main()
method.
Console window shows the output.








Copyright

© 2005 by Patni

Page 26 of 53

background image


Core Java

Lab Exercise 5: Packages and Interfaces


Estimated time to complete this exercise: 60 minutes


Instructions:

Compilation steps include –d switch for command line compilation of java programs to
the respective packages.

Objectives:
To study the concepts of Interfaces and Packages.



Problem 1:

Create an Interface Computation and modify Employee and Salaried classes so that
now they are part of com.patni.payroll package. Create an interface Computation
with two methods – computeSalary and showPayslip in the package com.patni.payroll.
Also modify Salaried class so that it implements Computation and defines its methods.


Solution:

Step 1: Create an interface Computation in Computation.java file. This interface has
two methods as given below.

Package com.patni.payroll;

public interface Computation
{
double

computeSalary(

);

void showPaySlip( );


} // end of interface Computation


Step 2: Compile the code with the –d switch on the command line. The dot specifies
that the directories of the package must be created under current directory.

javac

–d

.

Computation.java


Copyright

© 2005 by Patni

Page 27 of 53

background image


Core Java

Step 3: Observe the path in which the Computation.class file is created. If you are
working in <USER_DIR>, then Computation.class file will be created under
<USER_DIR>\com\patni\payroll\ subdirectory.

Step 4: Modify Employee.java file and make it a part of com.patni.payroll package.


Step 5: Compile and create Employee.class file, which must be created in the same
directory as Computation.class file.

Step 6: Modify Salaried.java file and make it a part of com.patni.payroll package.
Also make the change as specified in problem statement, and save the file.


Step 7: Compile and create Salaried.class file, which must be created in the same
directory as Computation.class file.


Note:
Copy the files Employee.java and Salaried.java from the current directory into some
other directory before you test the package. This step is required here because if the
UseSalaried.java file which we will use to test the package, is in the same folder as
that of Employee and Salaried source/class files then the compiler will pick the class
file from the current directory rather than taking it from the package. This happens

because the classpath variable contains the local directory (dot) value set.

Check:
All of the above mentioned class files must have been created under
<USER_DIR>\com\patni\payroll\ folder.

Step 8: Set the classpath variable to the current directory so that it can refer to the
class files created in the package. To do this follow the steps mentioned in “Setting
Classpath Environment Variable” section and append the path given below.

<USER_DIR>;

Step 9: Test the Interface and Package: Test the Salaried class by creating the
following (UseSalaried.java) java file. This class belongs to the default package.

// To Do: Import the required files

class UseSalaried
{

public static void main(String[] args)

{

Salaried

s1=new

Salaried(102,"BB","Accountant",53,10,50);

s1.showPaySlip();
}
}

Copyright

© 2005 by Patni

Page 28 of 53

background image


Core Java



Step 10: Compile and execute the file and write the results here.



Problem 2 :

Continuing with the Product class, write an interface Description having a

package com.patni.payroll;

public interface Description
{

public String getLongDescription(){

// method that has to be implemented by the subclasses.
// Returns a description of the product as an HTML table.

}

} // end of interface Descrition


Product class implements the interface Description but getLongDescription is abstract
in Product class. Override this method in the sub classes i.e. Good and Service.

Problem 3 :

Make Product, Good, Service classes and Description interface as a part of
com.patni.catalogue package. To test these classes, create a class Impl in the
default package.

<appropriate import statements>
class Impl{
public static void main(String args[]){
// create a Product array that holds 2 products, one instance
// each of class Item and Service.
// Display details of both products using the displayDetails() methods,

// while looping thru the array.
}
}// End of class Impl.

Copyright

© 2005 by Patni

Page 29 of 53

background image


Core Java

Lab Exercise 6: Exceptions


Estimated time to complete this exercise: 120 minutes


Objectives:

To understand how the exceptions are handled in a Java program.

Problem:
Create application specific exception class NullNameException to validate the name
of an employee. The validation rule is that the Name should always be entered and

cannot be blank.

Solution:

Step 1: Create a new class NullNameException in NullNameException.java file.

Package com.patni.payroll;

public class NullNameException extends Exception

{
NullNameException(String

message)

{
super(message);
}
}//class NullNameException;


Step 2: Compile and check whether the NullNameException.class file is created in the

directory as specified by the package.

Step 3: Modify the Employee.java file. Modify the setName( ) method as given below,
save and compile.

public void setEname(String eName) throws NullNameException
{
if

(eName.equals(""))

{

throw new NullNameException("Name must be entered");

}
else
{
this.eName=eName;
}
}

Copyright

© 2005 by Patni

Page 30 of 53

background image


Core Java


Step 4: Write ExceptCheck.java to test the thrown exception. Type as given below
and save the file.

import com.patni.payroll.*;

class ExceptCheck
{

public static void main(String[] args)
{
try
{
Salaried s = new Salaried(123, "a", "DS", 13, 324.0, 454);

s.setEname("");
}

catch (NullNameException e)

{
System.out.println(e);
}
}
}


Step 5: Compile the file and run. Analyze the results.


Step 6: Similarly add AgeException to the Employee class. Validation for age: it
should be between 22 and 55.

Step 7: Modify ExceptCheck.java to handle both the exceptions.


Problem 2 :

Write a class MathOperation which accepts integers from command line. Create an
array using these parameters. Loop thru the array and obtain the sum and average of
all the elements. Display the result. Check for various exceptions that may arise like
ArrayIndexOutOfBoundsException, ArithmaticException, NumberFormatException etc.

Eg :The class would be invoked as :

C:>java MathOperation 1900, 4560, 0, 32500

Problem 3.
Design an user defined class DivisionByZeroException to represent
ArithmaticException Divide by zero. Create a class DivionByZero to implement the
above class raising proper exception.

Copyright

© 2005 by Patni

Page 31 of 53

background image


Core Java

Lab Exercise 7: Collection Classes


Estimated time to complete this exercise: 120 minutes


Objectives:

To study the use of Collection classes

Problem 1:
Write a class EmployeeDB in com.patni.payroll package. The class holds a list of
objects of Employee hierarchy. This class must be useful for holding the

heterogeneous objects (Employee subclasses). Implement the methods defined below
as specified.

Solution:

Step 1: Write the class mentioned below in “EmployeeDB.java” file. Implement the
methods specified.

import java.util.*;
class EmployeeDB // holds a list of Employee objects
{

// use ArrayList and Enumeration classes

// to hold and process the list of Employee objects


boolean addEmployee(Employee e)

{

// Add the object to the list

}

boolean deleteEmployee(int eCode)

{

// Enumerate and delete the Employee if eCode found

// return true if deleted, otherwise false

return

ans;

} // deleteEmployee


String

showPaySlip(int

eCode)

{

// return the paySlip in the String format for the eCode

return

strPaySlip;

} // showPaySlip


Employee[]

listAll()

{

Copyright

© 2005 by Patni

Page 32 of 53

background image


Core Java

// return the list of employees, existing in Vector,

//

as

an

Employee

array

} // end of listAll

void sort () {

//sorts the collection based on Employee code
//Make use of Comparable interface and Arrays.sort method to sort the vector
where Employee implements Comparable.)

}

} // end of class EmployeeDB


Step 2:
Compile and generate the class file.

Step 3: Write the helper class to test the EmployeeDB in the

file UseEmployeeDB.java.

class UseEmployeeDB
{

public static void main(String[] args)

{

// Create the objects of Salaried and

// add them into EmployeeDB object

// use members of EmployeeDB


} // end of main

} // end of class UseEmployeeDB


Step 4: Compile and execute to see the results.

Problem 2:

Step 1 : Write a class Catalogue in above created package with following structure.

class Catalogue{
Vector products; // data member

boolean addProduct(Product e){

//Adds product to product vector.

}

Product searchProduct(int id){

// searches for product with prod-id =<id>, returns Product if found, else error

message
}
Product[] listAll(){

// Return all products in Product Array

}

Copyright

© 2005 by Patni

Page 33 of 53

background image


Core Java

void sort (){
// sorts the collection based on product code

}

boolean deleteProduct(int productId){

//deletes product from collection and returns true if successful delete, false

otherwise.
}


Step 2 : Create a class UseCatalogue to test this class.

class UseCatalogue
{

public static void main(String[] args)

{

// Create Product objects and add to vector

// use methods of Catalogue class


} // end of main

} // end of class UseCatalogue


Problem 3 :
Step 1 :
Create a wrapper class ProductStack that uses the Stack class to implement
various methods like push, pop etc.


class ProductStack{

Methods:
void pushProduct(Product object){

// Push product object onto the stack

}

Product popProduct(){

// Pop product object from the stack

}


Product takeAPeek(){

//returns the topmost product withour removing it from stack

}

int searchStack(Product pObj){

//Searches product on stack and returns 1 if found, -1 if not.

}

Step 2 : Test this class, by creating a UsePrStack class. Incorporate stack

functionalities in the main method.

Copyright

© 2005 by Patni

Page 34 of 53

background image


Core Java

Problem 4 :

Write a program, which will count the occurrence of words in a line.
For example, Search for word here in the following sentence, I am here, you are also

here.

(Hint: Use StringTokenizer class )
Output should be :

Number of words found : 2

Problem 5: (Extra Assigment)

Create a class with a method that takes a string and returns the number of characters
that only occur once in the string. It is expected that the method will be called
repeatedly with the same strings. Since the counting operation can be time
consuming, the method should cache the results so that when the method is given a
string previously encountered, it will simply retrieve the stored result. Use collections
wherever appropriate.

Copyright

© 2005 by Patni

Page 35 of 53

background image


Core Java

Lab Exercise 8: Property Files

Estimated time to complete this exercise: 30 minutes

Objectives:
To understand how property files can be used.


Problem 1:
Create a Property file as EmpProperties.properties that stores details of the
employee, for the Employee class, as created by you in Lab excercise 5.
Write TestProperties.java for reading, loading and displaying the Employee details
captured from the propertyfile EmpProperties.properties.

Problem 2:
Create a property file as testvalues.properties, which stores test values for an array
sorting program.

Write a program which sorts the array contents as are available from the
testvalues.properties file.

Copyright

© 2005 by Patni

Page 36 of 53

background image


Core Java

Lab Exercise 9: File Input / Output


Estimated time to complete this exercise: 120 minutes


Objectives:

To understand how Java implements File Input/Output operations.

Problem 1:
Write a program to read the employees information, from the console, and save into
“EmpRec.dat” file. It must accept multiple records till user wants to exit. Maintain a

Vector to hold all the records.

Solution:

Step 1: Modify Salaried.java file. Salaried class must be serialized.

Step 2: Save and compile Salaried.java file.

Step 3: Write a file “EmployeeFile.java” which contains the methods as given below.

import java.io.*;

class EmployeeFile
{

// To Do: add the members required for reading/writing into file

// To Do: add the members to work with Employee object


void addToVector() throws Exception

{
// To Do: read one Salaried employee information from console

// To Do: create and add the object to the vector


} // end of addToVector

void writeData() throws Exception

{

// To Do: write the objects from vector

// to EmpRec.dat file one by one

} // end of writeData


void readData() throws Exception

{

// To Do: read the records from the file

Copyright

© 2005 by Patni

Page 37 of 53

background image


Core Java

// To Do: add them into vector

// To Do: display Employee details for every record

} // end of readData


public static void main(String[] args) throws Exception

{
String

option="y";


while(!option.equals("y"))

{

//

To

Do:

addToVector


} // end of while


// To Do: write data


// To Do: read data


} // end of main

} // end of EmployeeFile


Step 4: Compile and execute the program.

Problem 2 :

Step 1 : Add the following static methods to the previously created Catalogue class.

class Catalogue {

………………
public static Catalogue readFile(String fname)
// See below for a description of what this method should do.
}

public static Product createProduct(String line){

// this function is used by readFile method which reads

// one line of the file and creates a respective Product.

}

}

The readFile() is a static method that takes a filename as an argument. It should read
the file and create an array of Products. That means an element of the array can

either be an instance of the Good class or the Service class. The input file serves as a
database that contains a list of all available goods and services. The format of the file
is described below.

The format of the input file is as follows:

Copyright

© 2005 by Patni

Page 38 of 53

background image


Core Java

One line contains one product
All values in the line are comma separated
The first value is the product id (integer)
If the second value in the line is a "G" then the remaining part of the line contains a

description of a good (see format below)

If the second value of the line is a "S" then the remaining part of the line contains a
description of the service
If the product is a Good the remaining line will contain the following information:
description: a string with a short description
price (in rupees): a decimal number
unit: a string that describes the unit(s) the customer get for this price

height: a decimal number (inches)
width: a decimal number (inches)
length: a decimal number (inches)

warranty (in months): an integer
cost of shipping (in rupees): a decimal number
manufacturer: string with the name of the manufacturer
if the product is a service the remaining line will contain the following information:
description: a string with a short description
price (in rupees): a decimal number
unit: a string that describes the unit(s) the customer get for this price

start time: a string containing the hour and minute
end time: a string containing the hour and minute
Contents of the text file are shown in following figure :

Step 2 :

Write a java appliction that uses the class described above. Implement the main
method that support reading and writing product data from the corresponding data
file.


Problem 3(Extra Assignment)
Write a console based java application to list all entries in a directory specified in the
command line.

Hint: use File class.

Copyright

© 2005 by Patni

Page 39 of 53

background image


Core Java

Lab Exercise 10: Multithreading in Java


Estimated time to complete this exercise: 120 minutes


Objectives:

The objective of this exercise is to understand the concept of Multithreading in Java.

Problem 1:

Write a PingPong class using threads to display ping and pong on a console window.

One-thread prints pong and other thread prints ping.

Solution:

Step 1: Create the class PingPong in PingPong.java file. Type the code as given
below.

class PingPong implements Runnable{
String

word;


public PingPong(String pp){

word=pp;

Thread t1 = new Thread(this);

t1.start();
}

public void run(){ //overriding the run() method

try{

for (int i = 1; i < 10; i++)

{

System.out.println(word);

}

Thread.sleep(50);

//

50

millisecond

sleep

}

catch(InterruptedException

e){

System.out.println("sleep

interrupted");

}

}


public static void main(String args[]){

PingPong p1 = new PingPong("ping");

PingPong p2 = new PingPong("pong");

}
}

Copyright

© 2005 by Patni

Page 40 of 53

background image


Core Java


Step 2: Compile and run the program. See the results.

Problem 2:

Create a program, which will execute 4 threads simultaneously, printing the numbers
in the sequence. Each thread starts from its baseNumber and is incremented by the

stepValue. Accept baseNumber, stepValue and the priority of the thread in the class
constructor.

Solution:

Step 1: Create a class SeqNumber derived from Thread, which takes an integer as the
parameter in the constructor. and as given below. Write the code to implement the
required functionality.

class SeqNumber extends Thread
{

int baseNumber, stepValue, priority;


SeqNumber(int base, int step, int priority)

{

// To Do: Construct the class

}


// implement the thread features

}


Step 2: Write UseThread class, which creates 4 objects of SeqNumber with different

baseNumber, stepValue and priority.

Step 3
: Compile and execute the program.

Problem 3:

Consider an airline reservation system in which many clients are attempting to book
seats on particular flights between particular cities. All the information about the
flights and seats is stored in a common database in memory. The database consists of
many entries each representing a seat on particular flight for a particular day
between particular cities. In a typical airline reservation scenario, the client will
probe around in the database looking for the "optimal" flight to meet that client's
needs.
So a client may probe the database many times before deciding to try and book a
particular flight. A seat that was available during this probing phase could easily be
booked by someone else before the client has a chance to book it after deciding on it.
In that case, when the client attempts to make the reservation, the client will

discover that the data has changed and the flight is no longer available.

Copyright

© 2005 by Patni

Page 41 of 53

background image


Core Java


The client probing around the database is called a reader. The client attempting to
book the flight is called a writer. Clearly, any number of readers can be probing
shared data at once, but each writer needs exclusive access to the shared data to

prevent the data being corrupted.


Write a multithreaded Java program that launches multiple reader threads and
multiple writer threads, each attempting to access a single reservation record. A
writer thread has two possible transactions, makeReservation and
cancelReservation. A reader has one possible transaction queryReservation.

Note: Your program should allow multiple readers to access the shared data
simultaneously when no writer is active. But if a writer is active, then no readers
should be allowed to access the shared data.


Implement your monitor with the folowing methods: startReading which is called by
any reader that wants to begin accessing a reservation, stopReading to be called by
any reader that has finished reading a reservation. StartWriting to be called by any
writer that wants to make a reservation and stopWriting to be called by any writer
that has finished making reservation.

Hint: Use wait & notify

Copyright

© 2005 by Patni

Page 42 of 53

background image


Core Java

Lab Exercise 11: AWT and Events

T

he objective of this exercise is to learn how to develop efficient GUI based Java

applications.
Estimated time to complete this exercise: 2.5 hrs

Problem 1:


Objectives: Develop a java application that supports the following functions:
On clicking tick button the minute line moves ahead by one minute and

correspondingly the hour line. We can set a particular time by putting values in the
text fields.

Solution:
Create ClockTest.java file to represent the application. The code is as follows:

Step 1: Design the ClockTest class as follows :

import java.awt.*;
import java.awt.event.*;
import java.text.*;

class ClockTest extends Frame implements ActionListener{

private Button ticktime; // represents tick button

private Button settime; // represents settime button

private IntTextField hourField; // represents hour input field

private IntTextField minuteField;// represents minute input field

private ClockCanvas clock; // represents clock display canvas


public ClockTest() {

/* layout is set in the constructor. All relevant objects instantiated along with registering
actionListeners. An windowListener object is registered to support windowClosing.*/

Copyright

© 2005 by Patni

Page 43 of 53

background image


Core Java


}
public void actionPerformed(ActionEvent evt){
/* find the source of action. If it is tick then call ClockCanvas objects tick method else call

ClockCanvas objects setTime method after validating values in hourField and minutefield. */
}
public static void main(String args[]) {
/* Instantiate an object of the class ClockTest and set the visible property of the object to
true.*/
}

}


Step 2:
Design the ClockCanvas class to represent the display canvas as follows:

class ClockCanvas extends Canvas{
private

int

minutes=0;

public void paint(Graphics g){

g.drawOval(0,0,100,100);
double

hourAngle=2*Math.PI*(minutes-3*60)/(12*60);

double

minuteAngle=2*Math.PI*(minutes-15)/60;


g.drawLine(50,50,50+(int)(30*Math.cos(hourAngle)),50+(int)(30*Math.sin(hourA
ngle)));


g.drawLine(50,50,50+(int)(45*Math.cos(minuteAngle)),50+(int)(45*Math.sin(min

uteAngle)));

}

public void setTime( int h, int m){

minutes=h*60+m;
repaint();
}

public void tick(){

minutes++;
repaint();
}

}

Copyright

© 2005 by Patni

Page 44 of 53

background image


Core Java


Step 3:
Design the IntTextField class to represent numeric text fields as follows:
class IntTextField extends TextField{

public IntTextField(int def, int min, int max,int size){

super(""+def,size);

low=min;

high=max;

}
public

boolean

inValid(){

int value;

try{

value=(Integer.valueOf((String)getText().trim())).intValue();

if( value< low || value > high)

throw new NumberFormatException();

}

catch(NumberFormatException

e){

requestFocus();
return

false;

}

return

true;

}
public

int

getValue(){

return

(Integer.valueOf((String)getText().trim())).intValue();

}
private

int

low;

private

int

high;

}

Step 4:
Put all the classes in one application file (ClockTest.java) and execute. The main
method in the class ClockTest creates an object of the same class to represent the
application.

Problem 2:
Write a java application to design a Text Editor. All editing tasks (Like in Notepad) are
performed through menu options. Also incorporate short cut keys.
Problem 3( extra assignment)
Write a java application to display the name of the user scrolling in the center of the
frame. The color of the text should be selected from an user defined menu which
contains color menu items in the form of radio menu items or enable-disable menu

items. The application has a font menu on selection of which a font dialog box

appears. The size and style of the font can be selected through this dialog box.

Problem 4:(Extra assignment)

Write a java applicaton to display a running counter. Provide Start and Stop button to

control the behaviour of the running thread.

Copyright

© 2005 by Patni

Page 45 of 53

background image


Core Java

Lab Exercise 12: Java Swing

Objectives: This exercise describes the fundamental aspects of how to write an
Applet and design a swing application. It also covers the concepts of making an applet

a part of an html page and executing the same in a browser.

Estimated time to complete this exercise: 4 hrs.

Problem 1:


Write a java applet, which will be incorporated in an html page for display. The
applet has list box with site names as entries. On selecting a particular site from the
list box corresponding page should be displayed on the right frame as displayed in the
diagram below:



Part 1:
Step 1:
Create the SiteApplet.java file to represent the applet loaded through an html page.
The applet is loaded in the left frame and the selected page gets open in the right

frame


import java.applet.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

Copyright

© 2005 by Patni

Page 46 of 53

background image


Core Java

import java.net.*;


public class SiteApplet extends Applet

{

List sites=new List(10);

public void init()

{
/* add the necessory site names in the list box. Set a mouselistener on list object

through MouseAdapter class and implement mouseClicked method using inner class

syntax. In the mouseClicked method check for mouse double click and get the
selected entry from the list box. Show the selected page using AppletContext
showDocument method using the site url and target parameters.*/
}
}
Step 2:
Compile and make the SiteApplet.class file.

Part 2:
Create left.html file to load SiteApplet.class using Applet tag.

Part 3:
Step 1:
Create SiteApplet.html file to incorporate left.html file in the left frame using
frameset tag.
Step 2:
Load the SiteApplet.html file on the browser. Select an entry in the list box and
double click to see the output on the right frame.


Problem 2: (Extra assignment)
Write a Java Swing Applet that implements inter applet communication machanism.
Design an html page to load two applets and show how applets can interact with each
other using some sample code. The applets should call each other methods and

update corresponding GUI components.


Problem 3:
Create a swing applet which displays two buttons, as Save, Show and a textarea.
This applet creates a file as savedata.txt.Save button saves the contents entered in
the textarea in the file. Show button displays contents of the file in the textarea.
Buttons should have proper imageicons on them

.


Problem 4:

Copyright

© 2005 by Patni

Page 47 of 53

background image


Core Java


Create a Swing application which has text entry areas for employee details such as
employee-name, employee-code, employee-address,employee-phone. Check for the
entry of all the details and store them in a employee.dat file. Dialog boxes showing

errors, warnings about the data entered in the textfields should be appropriate to
indicate kind of error that has occurred

.

Problem 5:
Create a hierarchical view of the lab exercise folders.


Problem 6:
Create a Swing application, which displays the contents of the employee. At created
in Problem 4 in a tabular format. Provide means to change the look and feel of the
output window in two different ways.




















Copyright

© 2005 by Patni

Page 48 of 53

background image


Core Java

Lab Exercise 13: JDBC

Prerequisite:
For DataSource implementation and RowSets tools.jar from jdk1.5 is required.

For Oracle Implementation of the RowSets and DataSource orcs12.zip must be in the
classpath.

Objectives:

To demonstrate the use of JDBC for executing SQL statements.


Problem 1:
Estimated time to complete this exercise: 2.5 hrs.

Part 1: Inserting a record to the existing table.

Problem:
Write InsertRecord class to insert the employee details in the employee database

table

Solution:

Step 1: Create the file insertRecord.java and write the code as specified.

Import java.sql.*;

Class insertRecord {

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


// To Do: Create the URL string depending on the oracle server


Connection conn;
Statement

stmt;


// To Do: Register the driver

// To Do: Get the connection


// To Do: Accept the details of Employee
// (empno, ename, job, sal, deptno)

// To Do: Create and execute statement,

// which inserts a record into
// Emp (default) table in Oracle.
}

Copyright

© 2005 by Patni

Page 49 of 53

background image


Core Java


}


Step 2: Compile and run to see the results.

Part 2: Updating the records.

Problem:
Write UpdateRecord class to update the employee details in the emp database table


Solution:

Step 1: Create the updateRecord.java file. Write the code as specified.

class updateRecord {

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

// To Do: Register the driver


// To Do: Get the connection


// To Do: Create the statement

// To Do: Accept the Employee number from the user

// To Do: Execute the update command which will update

// To Do: Employee table with the new values
// based on employee code
}
}


Step 2: Compile and run the program and verify the results.


Problem 2:


The XYZ LTD Company hires employees and want to computerize employee/salary

record maintenance. The company maintains a database of employees in Oracle. The
employee table contains information related to employee and is shown in the

following employee table structure.

The structure of the employee table is-

Column Name

Type

Constraint

Remark

Ecode

Number

(4) Primary

Key

Employee ID

Copyright

© 2005 by Patni

Page 50 of 53

background image


Core Java

Ename

Varchar (20)

Not Null

Employee Name

Designation

Varchar (4)

Not Null

Employee’s Designation

Age

Number

(2)

Not Null

Age in Years

Basic_Pay

Decimal (8,2)

Not Null

Basic pay of the

employee


When new employee joins the company, the employee record is created in the
employee table. The valid employee details are-

Ecode: Valid value is a 4-digit number.
Ename: Valid value can contain maximum 20 letters in uppercase.

Designation: Valid value is one of these - SS, SE, SSE, SSS, and CS.
Age: Must be in the range >=18 and <=80.
Basic_Pay: Must be greater than or equal to 6000.

When an employee leaves the company, the record related to that employee is to be
deleted from the employee table.

When a change in the designation or basic pay of an employee occurs, a respective
change in the employee record is to be updated.

At the end of each month, the salary calculation is done for the employee. The rule
for calculating the salary is

DA = 20% of Basic_Pay
HRA = 10% of Basic_Pay

Salary = Basic_Pay + DA + HRA

The salary slip is provided to the employee by generating the salary slip file.
The Salary slip format is – (e.g. For Employee with Ecode 5085)

XYZ Limited


Date:

30-Jan-2002


Employee Code: 5085

Employee Name: Anil

Employee Designation: SS

BASIC: 6000

HRA:

600

DA:

1200

Salary = 7800

The company wants to write a java application for computerizing employee/salary
management system to perform-

Copyright

© 2005 by Patni

Page 51 of 53

background image


Core Java

1) Addition of new employee record in the employee database.
2) Deletion of the employee record from the employee database.
3) Modification of employee record.

4) Display employee details.

5) Create a salary slip for the employee.
6) Find the total salary of all the employees.


Write a GUI based java application program to computerise the above.
Hints:

The application should be completely modularized performing each activity in
separate user defined methods.


e.g
Loading the database driver, creation of connection object and creation of statement
object etc. can be done in a connectToDatabase method.
Addition of records is performed through addEmployee method. The method gets the
employee details from corresponding field components and an insert statement is
generated based on the content entered in those components. The insert statement is
then executed through the statement object.
Deletion of records are performed through delEmployee method. The user enters the
specific employee number for whom the corresponding record to be deleted from the
table. Based on the entered employee number delete statement is generated and it is
executed through the statement object.
Modification of employee records are performed through the ModEmployee method.

The new values are obtained from corresponding components entered by the user and
the update statement if generated. The statement is then executed with the
statement object.
Displaying of records is done through displayRecords method. A proper select query to
retrieve employee details is formed and the output can be shown in a textarea.
Salary details of a particular employee can be displayed using a proper GUI through
the user defined method salarySlip.

Total salary for all the employees can be calculated using a method totalSal and the
detail can be shown in a textfield or label with proper heading.

Problem 3:
Create a GUI based application displaying the contents of employee table in
columnar format. Application should facilitate the user to add, delete,update the
details.(Use CachedRowSet as a ResultSet )

Problem 4:
Write a java program that uses DataSource and ConnectionPoolDataSource for
establishing connection to the database server. Create a table called TestTable
having two columns col1 as number and col2 as text. Open 5 connections and perform

Copyright

© 2005 by Patni

Page 52 of 53

background image


Core Java

simultaneous actions on the specified table. Compare performance with the Driver-
managed connection.

Problem 5:(extra assignment)

Write a JDBC based application to perform the following:

Supports selection of a particular table from the database. Use DatabaseMetadata
interface getMetaData method of Connection interface and getTables method of
DatabaseMetadata interface.
For the selected table, browse through the records with first, previous, next and last
options. Use scrollable resultset. (Also implement using CachedRowSet)
Provide option for moving to a particular record.

Copyright

© 2005 by Patni

Page 53 of 53


Wyszukiwarka

Podobne podstrony:

więcej podobnych podstron