Embed
Email

JAVA

Document Sample
JAVA
Categories
Stats
views:
14
posted:
8/17/2009
language:
English
pages:
20
Java Advanced Java Programming

Lab Guide









© Infosys Technologies Ltd

No. 350, Hebbal Electronics City, Hootagalli

Mysore – 571186









Author(s) Manasi Kundu



Authorized by Dr. M. P. Ravindra

Creation Date 18-Jul-2005

Version 1.00

Java Advanced Java Programming Lab Guide Version 1.0









Document Revision Summary



Version Date Author Reviewed by Comments

0.0 18-Jul-05 Manasi Kundu Rajagoplan P Initial Draft

1.0 28-Jul-05 Manasi Kundu Rajagopalan P Incorporated the

review comments









Education & Research Department 2

© Infosys Technologies Limited

Java Advanced Java Programming Lab Guide Version 1.0









TABLE OF CONTENTS

1 BACKGROUND .............................................................................................4



2 ASSIGNMENTS FOR JAVA ADVANCED JAVA PROGRAMMING - MULTITHREADING ...........4

2.1 ASSIGNMENT 1: HOW TO CREATE A THREAD BY EXTENDING THE THREAD CLASS......................... 4

2.2 ASSIGNMENT 2: HOW TO CREATE A THREAD BY IMPLEMENTING THE RUNNABLE INTERFACE.............. 6

2.3 ASSIGNMENT 3: HOW SLEEP () METHOD AND PRIORITY OF THREADS WORK .............................. 8

2.4 ASSIGNMENT 4: HOW EXECUTION HAPPENS WITH SYNCHRONIZED METHODS ........................... 10

2.5 ASSIGNMENT 5: TO WORK WITH THE DIFFERENT METHODS OF THE THREAD CLASS .................... 12



3 ASSIGNMENTS FOR JAVA ADVANCED JAVA PROGRAMMING - JDBC .......................... 15

3.1 ASSIGNMENT 1: JAVA PROGRAM TO INSERT DATA INTO A TABLE USING STATEMENT ................... 15

3.2 ASSIGNMENT 2: JAVA PROGRAM TO INSERT DATA INTO A TABLE USING PREPAREDSTATEMENT ......... 15

3.3 ASSIGNMENT 3: TO READ RESULTSETMETADATA AND TO LOOP THROUGH THE RESULTSET ............ 16

3.4 ASSIGNMENT 4: JAVA PROGRAM TO WORK WITH CALLABLESTATEMENT ............................... 16



4 ASSIGNMENTS FOR JAVA ADVANCED JAVA PROGRAMMING – JAVA BEAN .................. 17



4.1 ASSIGNMENT 7: WRITING A SIMPLE EMPLOYEEBEAN .................................................. 17









Education & Research Department 3

© Infosys Technologies Limited

Java Advanced Java Programming Lab Guide Version 1.0









1 Background

This document contains the assignments to be completed as part of the hands on for

the subject Java Advanced Java Programming



Note: All assignments in this document must be completed in the sequence in this

document in order to complete the course.









2 Assignments for Java Advanced Java Programming -

Multithreading





2.1 Assignment 1: How to create a Thread by extending the

Thread class



Objective: To create and run a Thread by extending the Thread class.



Step 1: Create a folder Assignment1 under your work directory (ie.C:\work\AdvJava)



Step 2: Set the basic environment variables required for working with Java by running

the script created in Java LabGuide



Step 3: Open a text editor (In Windows, notepad.exe and in case of UNIX, vi) and type

the following:



/*

* Date: 30-Jan-2005

* @author E&R Dept, Infosys Technologies Limited

* @version 1.0

* Description: This file is a demo Java program depicting

* the use of threads by extending the Thread class

*/



/**

* class ExtThread

* Description: class extends Thread class

* overrides run() method

*/









Education & Research Department 4

© Infosys Technologies Limited

Java Advanced Java Programming Lab Guide Version 1.0





/*how to create a thread extending from Thread class, here

start is being called from main method where the thread is

getting created*/





class ExtThread extends Thread

{

ExtThread()

{

System.out.println("Child Thread created");

}

public void run()

{

System.out.println("Child Thread running");

}

}



/**

* class ExtThreadMain

* Description: class contains main method

*/



class ExtThreadMain

{

/**

* Method main, starting point of the application

* @param String args[] to take in command line

arguments

* creates object of the ExtThread class and calls its

start method

*/



public static void main(String a[])

{

System.out.println("Hi I'm main thread");

ExtThread obj=new ExtThread ();

obj.start(); //Line1

}

}



Save the file as ‘ExtThreadMain.java’





Step 4: Compiling the program. Close the editor. Now compile your program using the

command line:



javac ExtThreadMain.java



Education & Research Department 5

© Infosys Technologies Limited

Java Advanced Java Programming Lab Guide Version 1.0







Step 5: Run your program using the command line:



java ExtThreadMain



The output of the program should come up.



NOTE: Check the sequence of execution of steps. Also note that the run() method has

been overridden in class ExtThread which is a sub class of Thread class



Step 6: Now comment out the line marked Line1, recompile the code and run it.



Step 7: You find that the thread got created but the method run() never got executed

as start didn’t get called.



Summary of this exercise:

You have just learnt

• How to create your own Thread by extending the Thread class

• How to override the run() method

• If start() is not called the run() method does not get executed





2.2 Assignment 2: How to create a Thread by implementing the

Runnable interface



Objective: To create and run a Thread by extending the Thread class.



Step 1: Create a folder Assignment1 under your work directory (ie.C:\work\AdvJava)



Step 2: Set the basic environment variables required for working with Java by running

the script created in Java LabGuide



Step 3: Open a text editor (In Windows, notepad.exe and in case of UNIX, vi) and type

the following:



/**

* Date: 30-Jan-2005

* @author E&R Dept, Infosys Technologies Limited

* @version 1.0

* Description: This file is a demo Java program depicting

* the use of threads by implemeting the Runnable interface

*/



/**

* class ExtThread

* Description: class implements Runnable interface

* implements run() method

*/

Education & Research Department 6

© Infosys Technologies Limited

Java Advanced Java Programming Lab Guide Version 1.0









/*how to create a thread implementing Runnable interface,

here

an instance of Thread is getting created in the main

method*/





class RunnableThread implements Runnable

{

RunnableThread()

{

System.out.println("Child Thread: ");

}

public void run()

{

System.out.println("Hi I'm a new thread");

}

}



/**

* class RunnableThreadMain

* Description: class contains main method

*/



class RunnableThreadMain

{

/**

* Method main, starting point of the application

* @param String args[] to take in command line

arguments

* creates object of the RunnableThreadMain class

* and passes this object as a job for the Thread

class object

*/

public static void main(String a[])

{

System.out.println("Hi I'm main thread");

RunnableThread rt=new RunnableThread();

Thread t=new Thread(rt);

t.start();

}

}



Save the file as ‘RunnableThreadMain.java’



Step 4: Compiling the program. Close the editor. Now compile your program using the

command line:



Education & Research Department 7

© Infosys Technologies Limited

Java Advanced Java Programming Lab Guide Version 1.0







javac RunnableThreadMain.java



Step 5: Run your program using the command line:



java RunnableThreadMain



The output of the program should come up.



NOTE: 1) Check the sequence of execution of steps.

2) If the Thread class is being implementing Runnable interface, the run()

methos has to be implemented else there will be compilation error.

3) Note when the Thread is getting created, an object of Runnable type is

being passed to the constructor of the Thread class.

4) This process of Thread creation is followed when the class has already

extended some class



Summary of this exercise:

You have just learnt

• How to create a Thread by implementing Runnable interface

• The run() method needs to be implemented for the code to compile





2.3 Assignment 3: How sleep () method and priority of threads

work



Objective: To study a multithreaded program and see the effect on the output by

making a thread sleep and then by changing the priority of a thread.



Step 1: Create a folder Assignment3 under your work directory (ie.C:\work\AdvJava)



Step 2: Set the basic environment variables required for working with Java by running

the script created in Java LabGuide



Step 3: Open a text editor (In Windows, notepad.exe and in case of UNIX, vi) and type

the following:





class SimpleThread extends Thread

{

public SimpleThread(String st)

{

super(st);

System.out.println(st + " started");



}



public void run()

Education & Research Department 8

© Infosys Technologies Limited

Java Advanced Java Programming Lab Guide Version 1.0





{

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

{

System.out.println(i + " " + getName());

//Block 1

/*try{

sleep(1000);

}

catch(InterruptedException e)

{}*/

}

System.out.println("Done " + getName());

}

}





class MultiThreadDemo

{

public static void main(String a[])

{



SimpleThread st1=new SimpleThread("Hello");

//st1.setPriority(8); //Line1

st1.start();

SimpleThread st2=new SimpleThread("Hi");

st2.start();

}

}



Save the file as ‘MultiThreadDemo.java’



Step 4: Compiling the program. Close the editor. Now compile your program using the

command line:



javac MultiThreadDemo.java



Step 5: Run your program using the command line:



java MultiThreadDemo



The output of the program should come up.



NOTE: 1) Switching between threads happens but the developer has no control over it

and it is a feature of the OS



Step 6: Now remove the comment from line marked Line1, save and recompile the

program and run it again





Education & Research Department 9

© Infosys Technologies Limited

Java Advanced Java Programming Lab Guide Version 1.0





Step 7: Analyze the output, you find that the Thread named Hello behaves like a

selfish thread as it has been set a higher priority. So Hello thread finishes execution

after which Hi thread gets a chance to run.



Step 8: Now remove the block comment from the code marked Block1. Save,

recompile and run the code.



Step 9: Analyze the output, you find that due to the call to sleep() method, the thread

with the lower priority gets a chance to run in parallel with the thread of higher

priority



Note: The call to sleep() has been placed in a try-block method as the method throws

InterruptedException which is a checked exception





Summary of this exercise:

You have just learnt

• How to set the priority of a thread

• How a higher priority thread behaves like a selfish thread

• How a higher priority thread can be made to sleep so that a thread of lower

priority can get a chance to execute









2.4 Assignment 4: How execution happens with synchronized

methods



Objective: To learn the concept of synchronized methods



Step 1: Create a folder Assignment4 under your work directory (ie.C:\work\AdvJava)



Step 2: Set the basic environment variables required for working with Java by running

the script created in Java LabGuide



Step 3: Open a text editor (In Windows, notepad.exe and in case of UNIX, vi) and type

the following:





/*try this example first without the synchronized keyword for the method

printMessage() and then try it as synchronized*/



class SameResource

{

public void printMessage(String msg)

{

try

{

Education & Research Department 10

© Infosys Technologies Limited

Java Advanced Java Programming Lab Guide Version 1.0





System.out.print("***");

Thread.sleep(1000);

System.out.println(msg + "***");

}

catch(InterruptedException e)

{

System.out.println(e);

}

}

}



class AThread extends Thread

{

SameResource r;

String message;

AThread(String name, SameResource r,String message)

{

super(name);

this.r = r;

this.message = message;

start();

}

public void run()

{

r.printMessage(message);



}

}



class SynchronizationDemo

{

public static void main(String args[])

{

SameResource s = new SameResource();

AThread t1 = new AThread("one",s,"Hello");

AThread t2 = new AThread("two",s,"From");

AThread t3 = new AThread("three",s,"Java");

try

{

t1.join();

t2.join();

t3.join();

}

catch(InterruptedException e)

{

System.out.println(e);

}

Education & Research Department 11

© Infosys Technologies Limited

Java Advanced Java Programming Lab Guide Version 1.0









}

}

Save the file as ‘SynchronizationDemo.java’



Step 4: Compiling the program. Close the editor. Now compile your program using the

command line:



javac SynchronizationDemo.java



Step 5: Run your program using the command line:



java SynchronizationDemo



The output of the program should come up.



Step 6: Analyse the results. We find that the output is like:



*********Hello***

From***

Java***



ie. In between the method call printMessage() when every thread goes to sleep, the

other thread executes the method and hence a disordered output happens



Step 7: Our objective is to get the output as :



***Hello***

***From***

***Java***





Step 8: Add the keyword synchronized to the method signature of printMessage(). Now

save, recompile and run the code again.



Step 9: We get the desired output as no other thread is allowed to run the method

printMessage() as long as one thread has the monitor for it





Summary of this exercise:

You have just learnt

• How to work with synchronized methods









2.5 Assignment 5: To work with the different methods of the

Thread class



Objective: To work with various functions of the Thread class

Education & Research Department 12

© Infosys Technologies Limited

Java Advanced Java Programming Lab Guide Version 1.0







Step 1: Create a folder Assignment4 under your work directory (ie.C:\work\AdvJava)



Step 2: Set the basic environment variables required for working with Java by running

the script created in Java LabGuide



Step 3: Open a text editor (In Windows, notepad.exe and in case of UNIX, vi) and type

the following:





/*

* Date: 30-Jan-2005

* @author E&R Dept, Infosys Technologies Limited

* @version 1.0

* Description: This file is a demo Java program depicting

* the various methods of threads

*/



/**

* class ThreadMethods demo

* Description: class contains main method

*/



/*demo for depicting various methods of threads*/



class ThreadMethodsDemo

{

/**

* Method main, starting point of the application

* @param String args[] to take in command line

arguments

* queries the main thread using various methods of

the Thread class

*/

public static void main(String args[]) throws

InterruptedException

{

Thread t = Thread.currentThread();

// threadname,priority,threadgroup

System.out.println("Current Thread : " + t);

System.out.println("Name of thread : " +

t.getName());

System.out.println("Priority : " +

t.getPriority());

System.out.println("Active count : " +

Thread.activeCount());

System.out.println("Thread Group : " +

t.getThreadGroup());

Education & Research Department 13

© Infosys Technologies Limited

Java Advanced Java Programming Lab Guide Version 1.0





System.out.println("Is Daemon ? " +

t.isDaemon());

System.out.println("Is Alive ? " + t.isAlive());

//IllegalArgumentException is thrown here as the

value of priority is not in range 1 to 10

//t.setPriority(11);

}

}



Save the file as ‘ThreadMethodsDemo.java’



Step 4: Compiling the program. Close the editor. Now compile your program using the

command line:



javac ThreadMethodsDemo.java



Step 5: Run your program using the command line:



java ThreadMethodsDemo



The output of the program should come up.



Step 6: Analyse the results.



Step 7: Remove the comment entry from the line marked Line1. Now save, recompile

and run the code again.



Step 8: You get runtime error at Line1 as the priority is being set to 11 whereas the

valid values for Thread priority is in the range of 1 to 10.



Summary of this exercise:

You have just learnt

• How to work with the different methods of the Thread class









Education & Research Department 14

© Infosys Technologies Limited

Java Advanced Java Programming Lab Guide Version 1.0









3 Assignments for Java Advanced Java Programming -

JDBC



Database: For assignment no. 1 to 4, create a table Employee having the following

fields EmpI, EmpName and Age. Make the EmpId field as a sequence. Insert valid

data into the table like



EmpID EmpName Age

101 Tom 30

102 Harry 25

103 Jim 22





3.1 Assignment 1: Java program to insert data into a table using

Statement



Objective: To write and compile a java Program using Statement in JDBC.



Problem Description:

• Write down a JDBC program to insert a new row into the table where the

EmpName is ‘Jill’ and age is 28. If the insertion into the table is successful then

it should print out for me “Insertion successful” else display “Insertion failed”



Hint:

executeUpdate() method returns an int as to how many rows got affected. So if the

return value is 0 it indicates that insertion failed





3.2 Assignment 2: Java program to insert data into a table using

PreparedStatement



Objective: To relate AWT with JDBC.



Problem Description:



The problem has 2 parts to it:



• Create a small form titled ‘Employee Details Entry’ using AWT which has 2

labels ‘Name’ and ‘Age and 2 text fields to take these data. There is a Submit

button which on clicked validates that data has been filled in both the fields.

• If the validation is ok, it should call a function that will insert the details of

this employee into the Employee table. Use PreparedStatement to insert this

data



Education & Research Department 15

© Infosys Technologies Limited

Java Advanced Java Programming Lab Guide Version 1.0







3.3 Assignment 3: To read ResultSetMetadata and to loop

through the ResultSet



Objective: To learn the usage of ResultSetMetaData and ResultSet



Problem Description:

Write down a JDBC program to query the Employee table. There will be 2 displays

from the program:

• First set of display will display the no. of columns in the table, the datatypes of

each column and the column name

• Next it should display all the rows of the table Employee as:



The Employee Details are:

EmpID: 101 EmpName: Tom Age: 30

………………………………………….



3.4 Assignment 4: Java program to work with CallableStatement



Objective: To learn the usage of CallableStatement and passing and retrieving

parameters to/from a stored procedure.



Problem Description:



The problem has 2 parts to it:



• Create a stored procedure in your Oracle database named GetEmpDetails which

has 1 input parameter and 2 output parameters. The input parameter takes in

the EmpID and the output parameters brings back the Name and Age of the

employee whose EmpId is given as the input parameter, Test that the stored

procedure is working without errors.

• Write a Java program to give a call to ‘GetEmpDetails’ using CallableSatement.

The program should finally display the name and age of the Employee whose

EmpId is being passed



Hint: Remember to register the output parameters of the stored procedure using

registerOutParameter() method. The SQL datatypes are declared in the class

Types present in java.sql package. Refer to Javadoc for help.









Education & Research Department 16

© Infosys Technologies Limited

Java Advanced Java Programming Lab Guide Version 1.0









4 Assignments for Java Advanced Java Programming –

Java Bean





4.1 Assignment 7: Writing a simple EmployeeBean



Objective: To demonstrate how to write a simple EmployeeBean.



Step 1: Write an Employee class implemented as a java bean with a few properties



Filename Employee.java



/** This class contains few variables and methods. The properties

of

* this class represents a simple Employee bean. Set methods here

* simply assigns a value to the variables and get methods

returns the

* value to the calling method

* Date : 4th Aug 2005

* Author : E&R Dept, Infosys Technologies Limited

* Version: 1.0

*/



import java.lang.*;



public class Employee {



private int employeeNumber;

private String employeeName;

private double employeeSalary;



public void setEmployeeNumber (int employeeNumber) {

this.employeeNumber = employeeNumber;

}



public void setEmployeeName (String employeeName) {

this.employeeName = employeeName;

}



public void setEmployeeSalary (double employeeSalary) {

this.employeeSalary = employeeSalary;

}



Education & Research Department 17

© Infosys Technologies Limited

Java Advanced Java Programming Lab Guide Version 1.0









public int getEmployeeNumber () {

return this.employeeNumber;

}



public String getEmployeeName () {

return this.employeeName;

}



public double getEmployeeSalary () {

return this.employeeSalary;

}

}



Step 2: Create a simple class called PropertyManager which contains Static methods to

set/get a property by name.



Filename PropertyManager.java



/** This class is used to get or set properties by string based

name

* Date : 4th Aug 2005

* Author : E&R Dept, Infosys Technologies Limited

* Version: 1.0

*/



import java.lang.*;

import java.lang.reflect.*;

import java.beans.*;



class PropertyManager {

public static Object getProperty (Object bean, String

propertyName) {

try {

Class employeeClass =

Class.forName("Employee");

String methodName = "get" + propertyName;

Method method = employeeClass.getMethod

(methodName, null);

return method.invoke (bean, null);

}catch (Exception e) {

System.out.println (e);

e.printStackTrace();

return null;

}



Education & Research Department 18

© Infosys Technologies Limited

Java Advanced Java Programming Lab Guide Version 1.0





}

/* You can also use setProperty method to set the properties for

a bean. The syntax is as follows */



public static void setProperty (Object bean, String propertyName,

Object value) {

}

}



Step 3: Write a class called Test with main method to instantiate the Employee Bean



File name Test.java



/* This file contains main method. We are going to instantiate

the

* Employee bean and print the result in this class

*/



/**

* Date : 4th Aug 2005

* Author : E&R Dept, Infosys Technologies Limited

* Version: 1.0

*/



import java.lang.*;

import java.lang.reflect.*;

import java.beans.*;



public class Test {

public static void main (String[] args) {

try {

// Get Employee class by name

Class employeeClass = Class.forName("Employee");



// Create an instance of Employee class

Employee obj = (Employee)

employeeClass.newInstance();

obj.setEmployeeNumber (15090);

obj.setEmployeeName ("Infosys");

obj.setEmployeeSalary(100045);

Method[] methods = employeeClass.getMethods ();

for(int iIndex = 0; iIndex <

methods.length;iIndex++){

Method method = methods [iIndex];

System.out.println ("Method " + iIndex +

": " + method.getName());

Education & Research Department 19

© Infosys Technologies Limited

Java Advanced Java Programming Lab Guide Version 1.0





}

Object propertyVal =

PropertyManager.getProperty(obj,

"EmployeeNumber");

Object propertyVal1 =

PropertyManager.getProperty(obj,

"EmployeeName");

Object propertyVal2 =

PropertyManager.getProperty(obj,

"EmployeeSalary");

System.out.println ("PROPERTY EmployeeNumber

value: " + propertyVal);

System.out.println ("PROPERTY EmployeeName

value: " + propertyVal1);

System.out.println ("PROPERTY EmployeeSalary

value: " + propertyVal2);

}

catch (Exception e) {

System.out.println (e);

e.printStackTrace();

}

}

}



Step 4. Make sure the CLASSPATH environment variable is set



Step 5: Compile all the three files



Test.java

Employee.java

ProprtyManager.java





Step 6: Run the program as java Test



Summary of this exercise:



You have just learnt



• How to create a simple bean

• Instantiating the bean

• Setting the properties of a bean

• Running a bean









Education & Research Department 20

© Infosys Technologies Limited


Related docs
Other docs by aswath ramacha...
JAVA
Views: 200  |  Downloads: 13
c,c++
Views: 457  |  Downloads: 48
C LANGUAGE
Views: 57  |  Downloads: 7
Interview questions
Views: 84  |  Downloads: 34
Computer Notes
Views: 5  |  Downloads: 0
Wireless Networking
Views: 8  |  Downloads: 0
Computer Notes
Views: 3  |  Downloads: 0
Computer Notes
Views: 25  |  Downloads: 0
C-papers
Views: 18  |  Downloads: 0
Computer Notes
Views: 5392  |  Downloads: 7
By registering with docstoc.com you agree to our
privacy policy

You are almost ready to download!

You are almost ready to download!