46
Directions for Lab Exercises o Student should not solve an exercise without accomplished the exercises given before that o Time given to solve each lab exercise is 1 hour o Each student will solve atleast two exercises in each lab

Core Java Lab Guide

Embed Size (px)

Citation preview

Directions for Lab Exercises

o Student should not solve an exercise without accomplished the exercises given before that o Time given to solve each lab exercise is 1 hour o Each student will solve atleast two exercises in each lab

Core Java

Core JavaLab Guide

Page 2 of 53

Core Java

Index1 Introduction.....................................................................4

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

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

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

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

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

7 Lab Exercise 13: Exceptions.................................................. 30

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

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

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

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

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

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

14 Lab Exercise 20: JDBC ....................................................... 49

Page 3 of 53

Core Java

IntroductionThese hands- on labs will expose you to working with Java applications. CreatingClasses, Interfaces, GUI- based applications and applets, Database application,networking and mailing concepts.

Setup Checklist for JavaSetupHere 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 spaceVGA or higher resolution monitorJDK version 1.4 with help, Netscape or IEMS-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 subdirectory of the folder in which you extracted theeclipsezip file (e.g., ) and run .d: \eclipse3.0\eclipse eclipse.exeYou 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:

Page 4 of 53

Core Java

Open the Control Panel and double click on System icon which opens SystemProperties 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.

Page 5 of 53

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.

Page 6 of 53

Core Java

Lab Exercise 1: Language Fundamentals

Estimated time to complete this exercise: 40 minutesObjectives: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 thecommand

java Welcome

Step 5: You should get the output as

Page 7 of 53

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 2times.

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

Page 8 of 53

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 Javaand 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 theobject.

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;

Page 9 of 53

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 thecommand

java UseDate

Step 5: You should get the output as

Date is 09/07/2002

Page 10 of 53

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 settermethods and not the constructor.( For this you will need to create a defaultconstructor too.)

Page 11 of 53

Core Java

Problem 2:

Create a class Employee that has members as specified below. Implement the setterand 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 Codeprivate String eName; // Nameprivate String desig; // Designation private int age; // Ageprivate 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 methodsvoid 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)

Page 12 of 53

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 screenpublic 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.

Page 13 of 53

Core Java

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

Page 14 of 53

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 toStr ing() method of Object class to replace thefunctionality 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?

Page 15 of 53

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 shownbelow wherein value of chartoprint is ‘*’ and the value of number3.** ** * ** **

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 3args

void displayDetails(){// display product details}

Page 16 of 53

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 callsthe 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{

Page 17 of 53

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 andcalls 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 resultsHint: make use of Math.random() functions, Arrays, Collections classes.

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

Page 18 of 53

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 – HRAand 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 asgiven 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 }

Page 19 of 53

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 … { class Service ……{height Date startDate

width Date endDatelength int startHour, startMin, endHour,

warranty (in months) endMincost of shipping (in rupees) }manufacturer public displayDetails(){

// code to display itempublic displayDetails(){ }// code to display item }}}

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

Page 20 of 53

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( );}}

Page 21 of 53

Core Java

Lab Exercise 4: Working with Eclipse

Following are the guidelines to create a simple java project and a simple javaprogram with Eclipse3.0:Open eclips e3.0 .Select File->new->project ->java project.

Click next and provide name for the project.

Page 22 of 53

Core Java

Click next and select build options for the project.

Page 23 of 53

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 javaclass.

Page 24 of 53

Core Java

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

Page 25 of 53

Core Java

This will open MyClass.java in the editor, with ready skeleton for the class, withdefault 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.

Page 26 of 53

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 respectiv e 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.jiet.payroll package. Create an interface Computation with two methods – computeSalary and showPayslip in the package com.jiet.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 hastwo methods as given below.

Package com.jiet.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

Page 27 of 53

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\jiet\payroll\ subdirectory.

Step 4: Modify Employee.java file and make it a part of com.jiet.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.jiet.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 theUseSalaried.java file which we will use to test the package, is in the same folder asthat of Employee and Salaried source/class files then the compiler will pick the classfile from the current directory rather than taking it from the package. This happensbecause 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\jiet\payroll\ folder.

Step 8: Set the classpath variable to the current directory so that it can refer to theclass 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 (Us eSalaried.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();}}

Page 28 of 53

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.jiet.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 abstractin 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.jiet.catalogue package. To test these classes, create a class Impl in thedefault 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.

Page 29 of 53

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.jiet.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 thedirectory 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; }}

Page 30 of 53

Core Java

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

import com.jiet.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 anarray using these parameters. Loop thru the array and obtain the sum and average ofall 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 theabove class raising proper exception.

Page 31 of 53

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.jiet.payroll package. The class holds a list ofobjects of Employee hierarchy. This class must be useful for holding theheterogeneous objects (Employee subclasses). Implement the methods defined belowas 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 falsereturn ans;} // deleteEmployee

String showPaySlip(int eCode){// return the paySlip in the String format for the eCode return strPaySlip; } // showPaySlip

Employee[] listAll(){

Page 32 of 53

Core Java

// return the list of employees, existing in Vector,// as an Employee array} // end of listAll

void sort () {//sorts the co llection 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 addProdu ct(Product e){ //Adds product to product vector.}

Product searchProduct(int id){// searches for product with prod-id =<id>, returns Product if found, else errormessage}Product[] listAll(){ // Return all products in Product Array}

Page 33 of 53

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.

Page 34 of 53

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 alsohere.(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 timeconsuming, the method should cache the results so that when the method is given astring previously encountered, it will simply retrieve the stored result. Use collectionswherever appropriate.

Page 35 of 53

Core Java

Lab Exercise 8: Property FilesEstimated 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 theemployee, 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.

Page 36 of 53

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

Page 37 of 53

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 adatabase 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:

Page 38 of 53

Core Java

One line contains one productAll values in the line are comma separatedThe 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 adescription of the service If the product is a Good the remaining line will contain the following information:description: a string with a short descriptionprice (in rupees): a decimal numberunit: 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 integercost of shipping (in rupees): a decimal numbermanufacturer: string with the name of the manufacturerif the product is a service the remaining line will contain the following information: description: a string with a short descriptionprice (in rupees): a decimal numberunit: a string that describes the unit(s) the customer get for this price start time: a string containing the hour and minuteend time: a string containing the hour and minuteContents 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 thecommand line.

Hint: use File class.

Page 39 of 53

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() methodtry{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");}}

Page 40 of 53

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 therequired 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 differentbaseNumber, stepValue and priority.

Step 3 : Compile and execute the program.

Problem 3:

Consider an airline reservation system in which many clients are attempting to bookseats 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 ofmany entries each representing a seat on particular flight for a particular day between particular cit ies. In a typical airline reservation scenario, the client will probe around in the database looking for the "optimal" flight to meet that client'sneeds.So a client may probe the database many times before deciding to try and book aparticular 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.

Page 41 of 53

Core Java

The client probing around the database is called a reader . The client attempting tobook the flight is called a writer . Clearly, any number of readers can be probingshared 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 andcancelReservation . A reader has one possible transaction queryReservation.

Note: Your program should allow multiple readers to access the shared datasimultaneously 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 byany reader that wants to begin accessing a reservation, stopReading to be called byany reader that has finished reading a reservation. StartWriting to be called by anywriter that wants to make a reservation and stopWriting to be called by any writerthat has finished making reservation.

Hint: Use wait & notify

Page 42 of 53

Core Java

Lab Exercise 11: AWT and Events

The objective of this exercise is to learn how to develop efficient GUI based Javaapplications.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 settim e buttonprivate IntTextField hourField; // represents hour input field private IntTextField minuteField;// represents minute input fieldprivate ClockCanvas clock; // represents clock display canvas

public ClockTest() {/* layout is set in the constructor. All relevant objects instantiated along with registeringactionListeners. An windowListener object is registered to support windowClosing.*/

Page 43 of 53

Core Java

}public void actionPerformed(ActionEvent evt){/* find the source of action. If it is tick then call ClockCanvas objects tick method else callClockCanvas 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 totrue.*/}

}

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();}

}

Page 44 of 53

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 whichcontains color menu items in the form of radio menu items or enable-disable menuitems. The application has a font menu on selection of which a font dialog boxappears. 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 tocontrol the behaviour of the running thread.

Page 45 of 53

Core Java

Lab Exercise 12: Java SwingObjectives: 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 thediagr am 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 rightframe

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

Page 46 of 53