la g la10_javaprogramming

100
Java Programming Lab Guide © Infosys Technologies Ltd No. 350, Hebbal Electronics City, Hootagalli Mysore – 571186 Author(s) Manasi Kundu , Raghavendran N, Rejaneesh Authorized by Dr. M. P. Ravindra Creation Date 15-Jan-2004 Version 1.00

Upload: divyainfy123

Post on 15-Aug-2015

44 views

Category:

Documents


5 download

TRANSCRIPT

Page 1: La g la10_javaprogramming

Java Programming Lab Guide

© Infosys Technologies Ltd No. 350, Hebbal Electronics City, Hootagalli

Mysore – 571186

Author(s) Manasi Kundu , Raghavendran N, Rejaneesh

Authorized by Dr. M. P. Ravindra

Creation Date 15-Jan-2004

Version 1.00

Page 2: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department ii

© Infosys Technologies Limited

Document Revision Summary Version Date Author Reviewed by Comments 1.00b 25-Jan-05 Manasi Kundu

Raghavendran N Rejaneesh

Nagendra R Setty Rajagopalan P

Added Java doc comments

1.00 22-Feb-05 Manasi Kundu Raghavendran N Rejaneesh

Nagendra R Setty Rajagopalan P

Review comments incorporated

Page 3: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 1

© Infosys Technologies Limited

TABLE OF CONTENTS

1 BACKGROUND .............................................................................................3

2 ASSIGNMENTS FOR DAY 1 OF JAVA PROGRAMMING ..............................................3

ASSIGNMENT 1: UNDERSTANDING JAVA CLASSPATH ............................................................ 3

ASSIGNMENT 2: WRITING AND COMPILING THE FIRST JAVA PROGRAM ............................................ 5

ASSIGNMENT 3: WRITING A SCRIPT TO SET ENVIRONMENT VARIABLES ............................................. 8

ASSIGNMENT 4: JAVA PROGRAM WITH A CLASS AND METHOD ..................................................... 9

ASSIGNMENT 5: A CLASS WITH GETTER AND SETTER METHODS .................................................. 11

ASSIGNMENT 6: DECLARING AND USING ARRAYS................................................................. 12

ASSIGNMENT 7: ARRAY OF OBJECTS ............................................................................ 15

ASSIGNMENT 8: USING MATH CLASS ............................................................................ 19

ASSIGNMENT 9: USING STATIC DATA MEMBERS AND METHODS ................................................... 19

3 ASSIGNMENTS FOR DAY 2 OF JAVA PROGRAMMING ............................................ 23

ASSIGNMENT 10: COMMAND LINE ARGUMENTS .................................................................. 23

ASSIGNMENT 11: SORTING A GIVEN SET OF NUMBERS ........................................................... 24

ASSIGNMENT 12: LEARNING JAVA.LANG PACKAGE .............................................................. 25

ASSIGNMENT 13: METHOD OVERLOADING....................................................................... 25

ASSIGNMENT 14: OVERLOADING CONSTRUCTORS ............................................................... 26

ASSIGNMENT 15: CONSTRUCTOR CHAINING AND DYNAMIC POLYMORPHISM....................................... 29

ASSIGNMENT 16: MULTILEVEL INHERITANCE .................................................................... 34

ASSIGNMENT 17: ABSTRACT CLASSES AND FINAL MODIFIER ...................................................... 34

ASSIGNMENT 18: PACKAGES.................................................................................... 35

ASSIGNMENT 19: ACCESS SPECIFIERS ........................................................................... 38

ASSIGNMENT 20: TYPECASTING OF OBJECTS.................................................................... 42

ASSIGNMENT 21: INTERFACES AND REFERENCE OBJECTS ........................................................ 43

ASSIGNMENT 22: CREATING JAR FILES ......................................................................... 45

4 ASSIGNMENTS FOR DAY 3 OF JAVA PROGRAMMING ............................................ 48

ASSIGNMENT 23: MANIPULATION OF STRINGS................................................................... 48

ASSIGNMENT 24: WORKING WITH DATES........................................................................ 48

ASSIGNMENT 25: HASH TABLE.................................................................................. 48

ASSIGNMENT 26: WORKING WITH COLLECTION CLASSES......................................................... 48

ASSIGNMENT 27: EXCEPTION HANDLING ........................................................................ 49

ASSIGNMENT 28: FLOW OF EXCEPTIONS ........................................................................ 51

ASSIGNMENT 29: USER DEFINED EXCEPTION .................................................................... 53

ASSIGNMENT 30: DEBUGGING RUN-TIME ERRORS ............................................................... 56

ASSIGNMENT 31: DEBUGGING RUN-TIME ERRORS ............................................................... 57

ASSIGNMENT 32: READING A .PROPERTIES FILE ................................................................. 57

5 ASSIGNMENTS FOR DAY 4 OF JAVA PROGRAMMING ............................................ 61

Page 4: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 2

© Infosys Technologies Limited

ASSIGNMENT 33: FILE INPUT AND OUTPUT ..................................................................... 61

ASSIGNMENT 34: HANDLING PRIMITIVE DATA TYPES ............................................................ 63

ASSIGNMENT 35: INPUT AND OUTPUT BUFFERING .............................................................. 67

ASSIGNMENT 36: DEVICE INDEPENDENT INPUT AND OUTPUT.................................................... 67

ASSIGNMENT 37: FILE COPY ................................................................................... 70

ASSIGNMENT 38: LINENUMBERREADER ......................................................................... 73

ASSIGNMENT 39: BUFFERED READER ........................................................................... 77

ASSIGNMENT 40: PUSHBACK INPUTSTREAM..................................................................... 79

ASSIGNMENT 41: OBJECT SERIALIZATION AND DESERIALIZATION ................................................ 80

6 ASSIGNMENTS FOR DAY 5 OF JAVA PROGRAMMING ............................................ 85

ASSIGNMENT 42: CREATING A GUI ............................................................................. 85

ASSIGNMENT 43: EVENT HANDLING ............................................................................ 90

ASSIGNMENT 44: LOGIN VALIDATION ........................................................................... 94

ASSIGNMENT 45: APPLET CREATION............................................................................ 95

Page 5: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 3

© Infosys Technologies Limited

1 Background This document contains the assignments to be completed as part of the hands on for the subject Java Programming.

Note: All assignments in this document must be completed in the sequence in order to complete the course.

2 Assignments for Day 1 of Java Programming All the assignments in this section must be completed on Day 1 of your Java

Programming course.

Assignment 1: Understanding Java CLASSPATH

Objective: To learn about setting up the barebones environment variables that are required to work with the Java compiler and the JVM. Background: The Java SDK (software development kit) directory structure has been explained to you in the classroom. The Java SDK installation directory will contain a bin folder which has all the executables and a lib folder which contains the tools.jar file. The file tools.jar has all the Core Java SDK classes. Step 1: Locate the installation directory of the latest JDK in your machine. (Hint: Typically, it will be installed under C:\ on Windows and under /usr/java or /usr/java<version> on a UNIX machine). In this case, say for example the Java SDK installation directory is C:\j2sdk1.4.2_03) Step 2: Inspect the contents of the JDK installation directory and ascertain that it is indeed the Java SDK installation directory Step 3: Open a Command shell to begin the assignment. In Windows, Select the Start Menu->Run… Type in cmd In UNIX, use the telnet to connect to the server and open a shell. Step 4: Setting the JAVA_HOME. Set an environment variable called JAVA_HOME to point to the Java SDK installation directory. For Example, In Windows, set JAVA_HOME=C:\j2sdk1.4.2_03 In UNIX, JAVA_HOME=/usr/java export JAVA_HOME

Page 6: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 4

© Infosys Technologies Limited

Step 5: Setting the CLASSPATH. Set the CLASSPATH environment variable to contain tools.jar. tools.jar contains all the Core Java SDK classes.

Note: It is a good practice to utilize the environment variable JAVA_HOME to derive all other paths related to Java.

In Windows, set CLASSPATH=%JAVA_HOME%\lib\tools.jar In UNIX, CLASSPATH=$JAVA_HOME/lib/tools.jar export CLASSPATH Step 6: Setting the PATH Variable. Most operating systems (Windows, UNIX) pick up executable files for command line from the directories in the environment variable PATH. We should add the directory <JAVA_HOME>\bin to the PATH variable. This will allow us to execute the Java compiler, other Java utilities and the Java runtime (JVM) by simply typing the names. In Windows, set PATH=%JAVA_HOME%\bin;%PATH% In UNIX, PATH=$JAVA_HOME/bin:$PATH Step 7: Make sure that the directory <JAVA_HOME>\bin has been added to the PATH variable. In Windows, echo %PATH% In UNIX, echo $PATH You should see the directory <JAVA_HOME>\bin in the PATH variable. Step 8: Test similarly to make sure the other environment variables are also set by using the echo command (JAVA_HOME, CLASSPATH). Step 9: Run the Java compiler by typing

javac If everything is set correctly, you should be able to see the compiler display its usage and command line arguments!

Page 7: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 5

© Infosys Technologies Limited

Step 10: Similarly, run the Java runtime by typing

java

If everything is set correctly, you should be able to see the java runtime display its usage and command line arguments! Summary of this exercise: You have just learnt

• How to set up the necessary environment variables to get the Java compiler and JVM working

• In the next assignment, we shall create our first java program, compile it and run it.

Assignment 2: Writing and Compiling the first Java Program

Objective: To write, compile and run the first java Program and in the process, learn more about Java CLASSPATH. Step 1: Create a folder Assignment2 under your work directory (ie.C:\work\Java) Step 2: Check the basic environment variables required for working with Java. (Refer to Assignment 1: Understanding Java CLASSPATH) Step 3: Open a text editor (In Windows, notepad.exe and in case of UNIX, vi) and type the following: Filename DisplayDemo.java

/*

* This java file is a demo Java program which depicts a class

* with a main method inside and it displays a string

*/

/**

* This class displays a string “My First Java Program”.

* Date: 12-Jan-2005

* @author E&R Dept, Infosys Technologies Limited

* @version 1.0

*/

public class DisplayDemo {

/**

* Displays a string by invoking println() method.

Page 8: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 6

© Infosys Technologies Limited

* @param args The command line arguments

*/

public static void main (String args[]) {

System.out.println ("My First Java Program");

}

}

Save the file as ‘DisplayDemo.java’ Step 4: Compiling the program: Close the editor. Now compile your program using the command line:

javac DisplayDemo.java If there are no syntax errors in your program, the compilation will succeed. Resolve the syntax errors if any, and get the program to compile. Step 5: Running the program: Run your program using the command line:

java DisplayDemo However, the Java runtime will display an error message. Step 6: Why are we getting the error message? (Hint: Read the error message and try to find out before going to Step 7.) Step 7: Reason for error: The Java Runtime is not able to load the class file you have just created by compiling your source code. Inspect the CLASSPATH environment variable. It contains only <JAVA_HOME>\lib\tools.jar This means, the Java runtime can read all the Core Java classes, but cannot read the class file you have just created. Step 8: Set the CLASSPATH so that the Java Runtime picks up the class file you just compiled. In most operating systems, “.” refers to the current working directory. So, you should add “.” to the CLASSPATH along with Core Java classes in tools.jar In Windows, set CLASSPATH=%JAVA_HOME%\lib\tools.jar;. In UNIX, CLASSPATH=$JAVA_HOME/lib/tools.jar:. export CLASSPATH

Page 9: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 7

© Infosys Technologies Limited

Note: In the CLASSPATH and PATH variables, multiple paths are separated by ‘;’ in case of Windows and by ‘:’ in case of UNIX

Step 9: Now try and run your code again. java DisplayDemo If everything is fine, you should be able to see the output, because the Java Runtime can now pick up the classes that you have created. Step 10: Instead of using ‘.’, you can also put the fully qualified path of your working folder as well. For example: In Windows, set CLASSPATH=%JAVA_HOME%\lib\tools.jar;C:\work\java\Assignment2 In UNIX, CLASSPATH=$JAVA_HOME/lib/tools.jar:$HOME/work/java/Assignment2 Try with this CLASSPATH. You should still be able to get your program to work! Summary of this exercise: You have just learnt

• Writing, compiling and executing your first Java Program

• More about CLASSPATH and how the Java Runtime picks up classes from the directories and Jar files specified in the CLASSPATH environment variable

Page 10: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 8

© Infosys Technologies Limited

Assignment 3: Writing a script to set environment variables

Objective: To create a generic command/batch script (shell script in case of UNIX) which will help set the environment required to work with Java. Background: Instead of typing a set of commands to set environment, it is a good practice to create a script which does the same. This will help in reducing manual and repetitive work. Step 1: Open a text editor. Type in all the commands you used in Assignment 1: Understanding Java CLASSPATH. In Windows, set JAVA_HOME= C:\j2sdk1.4.2_03 set CLASSPATH=%JAVA_HOME%\lib\tools.jar;. set PATH=%JAVA_HOME%\bin;%PATH% In UNIX, JAVA_HOME=/usr/java CLASSPATH=$JAVA_HOME/lib/tools.jar:. PATH=$JAVA_HOME/bin:$PATH export JAVA_HOME export CLASSPATH export PATH Step 2: Save the file. In Windows, you can save the file as setjavaenv.cmd or setjavaenv.bat (Both extensions bat and cmd represent command scripts). Save the file In UNIX, you can save the file as setjavaenv.sh Step 3: Setting the environment using the script: To set the environment required for java, open a command prompt/shell and execute the script In Windows, type the following at the command prompt setjavaenv In UNIX, ../setjavaenv.sh

Page 11: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 9

© Infosys Technologies Limited

Note: In UNIX, you should run environment scripts using the syntax . <script> so that it gets executed in the current shell only and will not spawn a new shell.

Step 4: Inspect whether the environment variables JAVA_HOME, CLASSPATH and PATH have been set. (Hint: Use echo command).

Note: The script written in this assignment can be used for setting environment for all the assignments you do from now onwards.

Summary of this exercise: You have just learnt

• Writing a simple script (command/shell) to set the environment required to work with Java

• Scripts like these can be used to reduce manual and repetitive work

Assignment 4: Java program with a class and method

Objective: To write and compile a java Program having a class with a method. To create an object of the class from some other class and invoke the method. Step 1: Create a folder Assignment4 under your work directory (ie.C:\work\Java) Step 2: Check the basic environment variables required for working with Java by running the script created in Assignment3. Step 3: Open a text editor (In Windows, notepad.exe and in case of UNIX, vi) and type the following: Filename DisplaySum.java

/* This java file contains a class with a method to compute the

* Sum of two numbers. This method is invoked from another class

* by passing the necessary values as parameters

*/

/**

* This class contains a method to print sum of two numbers.

Page 12: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 10

© Infosys Technologies Limited

* Date: 12-Jan-2005

* @author E&R Dept, Infosys Technologies Limited

* @version 1.0

*/

class DisplaySum{

/**

* Displays the sum of the two integer variables passed

* as parameters

* @param number1 The First number

* @param number2 The Second number

*/

void display(int number1, int number2){

System.out.println("The output is " +

(number1 + number2));

}

}

Open a text editor (In Windows, notepad.exe and in case of UNIX, vi) and type the following: Filename SumOfNumbers.java

/* This java file contains a class with the method that invokes

* the display() method of DisplaySum class with two parameters

*/

/**

* Starter class. Creates an instance of DisplaySum class and

* invokes the display method to print sum of two numbers.

* Date: 12-Jan-2005

* @author E&R Dept, Infosys Technologies Limited

* @version 1.0

*/

public class SumOfNumbers{

/**

* Creates an object of the displayDemo class and

* invokes the method display using the object

* @param args Command line arguments

*/

Page 13: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 11

© Infosys Technologies Limited

public static void main (String args[]) {

DisplaySum object = new DisplaySum();

object.display(10,5);

}

}

Save the file as ‘NumberSum.java’ Step 4: Compiling the program. Close the editor. Now compile your program using the command line:

javac NumberSum.java There is compilation error generated in the program. Step 5: Why are we getting the error message? (Hint: Read the error message and try to find out before going to Step 6.) Step 6: Reason for error: If there is a public class defined in the program and it contains main( ) method ,the file needs to be saved as per that class name which was not done. Resave the file as SumOfNumbers.java and repeat Step4. If there are no syntax errors the program should compile now.

Note: Check the folder, for every class that is present in the program there is a separate .class file that gets created after compilation. It is a good practice to keep a separate .java file for each class defined.

Step 7: Run your program using the command line:

java SumOfNumbers The output of the program should come up. Summary of this exercise: You have just learnt

• If a program has a public class defined the program should be named as per that class

• How to write a class with a method defined in it

• How to create an object of the class and invoke its method by passing parameters from some other class

Assignment 5: A class with getter and setter methods

Page 14: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 12

© Infosys Technologies Limited

Objective: To write a program with getter and setter methods. Problem Description: Write a class in Java that stores the marks of 3 subjects of a student. Provide methods to set the marks and get the values of the marks. Also, provide a method called getResults(), which prints the grade of the students. Write another class that contains the main() method which creates the instance of the above created class and invokes the respective methods. The computation of grades are as follows:

Average marks Grade

80 to 100 A

73 to 79 B+

65 to 72 B

55 to 64 C

0 to 54 D

Note: It is a good practice in Java to prefix names of methods with ‘get’ for methods that read a member variable and ‘set’ for methods that modify the member variables. It is also a good practice to have a get/set pair of methods for member variables which just store data.

Assignment 6: Declaring and using arrays

Objective: To write and compile a java program to deal with arrays for storing primitive data types. Depicts how to store values into the array and then retrieve the values. Step 1: Create a folder Assignment6 under your work directory (ie.C:\work\Java) Step 2: Check the basic environment variables required for working with Java by running the script created in Assignment3. Step 3: Open a text editor (In Windows, notepad.exe and in case of UNIX, vi) and type the following: Filename ArrayCreation.java

/*

* This java file contains a class that creates an array and uses

* methods to set and display the values of the array

*/

Page 15: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 13

© Infosys Technologies Limited

/**

* This class creates an integer array using a constructor and

* uses setValues method to store integers into the array and

* showValues method to display the values of the array.

* Date 12-Jan-2005

* @author E&R Dept, Infosys Technologies Limited

* @version 1.0

*/

public class ArrayCreation {

int array[];

/**

* Constructor creates an integer array that can hold

* maximum of five elements

*/

public ArrayCreation() {

array = new int[5];

}

/**

* This method Stores the integers into the array using a

* loop

*/

public void setValues() {

// Fill the array with five integers

for(int count = 0;count < 5;count++) {

array[count] = count+1;

}

}

/**

* This method displays the values in the array using a

* loop

*/

public void showValues() {

Page 16: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 14

© Infosys Technologies Limited

// Display the values in the array

for(int count = 0;count < 5;count++) {

System.out.println("array[ "+count+" ] = "+

array[count] );

}

}

}

Save the file as ‘ArrayCreation.java’ Filename ArrayDemo.java

/*

* This java file contains a class that creates an object of

* ArrayCreation class and calls the method to store and display

* the values of the array

*/

/**

* This class creates an instance of ArrayCreation class

* and invokes the setValues to store integers into the array and

* showValues method to display the values in the array.

* Date 12-Jan-2005

* @author E&R Dept, Infosys Technologies Limited

* @version 1.0

*/

public class ArrayDemo

{

/**

* Starting point of the application.

* creates an object of the ArrayCreation class and

* invokes the methods setValues and showValues using the

* object.

* @param args Command line arguments

*/

public static void main(String args[]){

/* Create an object of ArrayCreation class and call

the methods */

ArrayCreation object = new ArrayCreation();

object.setValues();

object.showValues();

Page 17: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 15

© Infosys Technologies Limited

}

}

Save the file as ‘ArrayDemo.java’ Step 4: Compiling the program. Close the editor. Now compile your program using the command line:

javac ArrayDemo.java Step 5: Run your program using the command line:

java ArrayDemo The output of the program should come up. Summary of this exercise: You have just learnt

• How to declare an array

• How to assign values to an array

• How to retrieve values from an array

Assignment 7: Array of objects

Objective: To write and compile a java program to deal with arrays for storing objects. Depicts how to store objects into the array and then retrieve the objects. Step 1: Create a folder Assignment7 under your work directory (ie.C:\work\Java) Step 2: Check the basic environment variables required for working with Java by running the script created in Assignment3 is set. Step 3: Open a text editor (In Windows, notepad.exe and in case of UNIX, vi) and type the following: Filename Book.java

/*

* This java file contains a class having the attributes of a

* book and also contains methods to set and get the properties

* of the book

*/

/**

* This class has two attributes name and price and uses set and

* get methods to set and get the properties of the book.

* Date: 12-Jan-2005

* @author E&R Dept, Infosys Technologies Limited

Page 18: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 16

© Infosys Technologies Limited

* @version 1.0

*/

public class Book{

String bookTitle;

float price;

/**

* Method setName

* @param bookName String parameter to set the title of the

* book

*/

public void setName(String bookName) {

bookTitle = bookName;

}

/**

* This method sets the price of the book

* @param cost Price of the book

*/

public void setPrice(float cost){

price = cost;

}

/**

* This method returns the title of the book

* @return Title of the book

*/

public String getName(){

return bookTitle;

}

/**

* This method returns the price of the book

* @return The price of the book

*/

public float getPrice(){

return price;

}

Page 19: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 17

© Infosys Technologies Limited

}

Save the file as ‘Book.java’ Filename BookDemo.java

/*

* This java file contains a class that creates array of book

* object and invokes the methods to set and get the properties

* of the book

*/

/**

* This class has two methods: createBooks to create an array of

* books and showBooks to display the details of the books. It

* also contains the main method that creates an object of

* BookDemo class and invokes createBooks and showBooks methods.

* Date: 12-Jan-2005

* @author E&R Dept, Infosys Technologies Limited

* @version 1.0

*/

class BookDemo{

Book books[] ;

/**

* Constructor. creates an array of objects of Book class

* that can hold the properties of two books

*/

BookDemo() {

books = new Book[2];

}

/**

* This method creates two objects of Book class and sets

* the title and price of the books using setName and

* setPrice methods

*/

void createBooks(){

// Create the first book object and set its attributes

books[0] = new Book();

books[0].setName("Gone with the wind");

books[0].setPrice(500);

/* Create the second book object and set its

Page 20: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 18

© Infosys Technologies Limited

Attributes */

books[1] = new Book();

books[1].setName("Java Programming");

books[1].setPrice(300);

}

/**

* This method displays the contents of book object by

* calling getName and getPrice methods

*/

void showBooks(){

/* Display the array of book objects. The variable

length stores the number of items in an array */

System.out.println("Book Title \t\t\t Price");

System.out.println("=========== \t\t\t =====");

for(int count=0;count < books.length;count++) {

System.out.println(books[count].getName() +

" \t\t " + books[count].getPrice());

}

}

/**

* Starting point of the application.

* Creates an object of BookDemo class and calls

* createBooks and showBooks methods to create and display

* an array of Book objects

* @param args Command line arguments

*/

public static void main(String a[]){

/* Create an object of BookDemo class and invoke

createBooks and showBooks methods using the

object */

BookDemo object = new BookDemo();

object.createBooks();

object.showBooks();

}

}

Save the file as ‘BookDemo.java’

Page 21: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 19

© Infosys Technologies Limited

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

javac BookDemo.java Step 5: Run your program using the command line:

java BookDemo The output of the program should come up. Summary of this exercise: You have just learnt

• How to declare an array variable of user defined data type

• How to populate an array with objects

• How to retrieve objects from an array

Assignment 8: Using Math class

Problem Description: Write a program in Java which generates a random number between 0 and 1. If the number generated is less than 0.5 then the program must print “The Value is less than 0.5” and if the number generated is greater than or equal to 0.5, then the program must print “The value is greater than 0.5”. Write the program using a) If – else b) using the Ternary operator Hint: Search the java doc and look for the Math class.

Assignment 9: Using static data members and methods

Objective: To write and compile a java program to learn the concept of ‘static’ Step 1: Create a folder Assignment9 under your work directory (ie.C:\work\Java) Step 2: Check the basic environment variables required for working with Java by running the script created in Assignment3 is set. Step 3: Look through the code below. Open a text editor (In Windows, notepad.exe and in case of UNIX, vi) and type the following: Filename StaticAndNonStaic.java

/* This java file has a class that contains static and non static

* instance variables and static and static and non static

* methods to access these variables

*/

Page 22: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 20

© Infosys Technologies Limited

/**

* This class contains a static variable and a non static

* instance variable. The static variable is accessed through a

* static method and the non static instance variable is accessed

* through a non static method.

* Date: 12-Jan-2005

* @author E&R Dept, Infosys Technologies Limited

* @version 1.0

*/

public class StaticAndNonStatic {

static int objectCount;

char userChoice;

/**

* Constructor. increments objectCount when an

* object is created and sets the instance

* variable userChoice with the parameter passed.

* @param choice User's choice

*/

StaticAndNonStatic(char choice) {

// Increment the count of objects

objectCount++;

userChoice =choice;

}

/**

* The static variable objectCount is

* displayed using this method

*/

static void displayObjectCount() {

System.out.println("Number of Objects :

"+objectCount);

}

/**

* The non static instance variable userChoice is

* displayed using this method

*/

Page 23: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 21

© Infosys Technologies Limited

void displayUserChoice()

{

System.out.println("The user choice is

"+userChoice);

}

}

Save the file as ‘StaticAndNonStatic.java’ Filename StaticAndNonStaicDemo.java

/* This java file has a class that creates the object of

* StaticAndNonStatic class and invokes the static and

* non static methods

*/

/**

* This class contains the main method which creates the object

* of StaticAndNonStatic class and calls the static and

* non static methods to refer to static and non static instance

* variables.

* Date: 12-Jan-2005

* @author E&R Dept, Infosys Technologies Limited

* @version 1.0

*/

class StaticAndNonStaticDemo {

/**

* Starting point of the application.

* Creates an object of StaticAndNonStatic class and calls

* the displayObjectCount and displayUserChoice methods

* @param args Command line arguments

*/

public static void main(String args[]) {

/* Call the static method to display

the number of objects created */

System.out.println("Before creating

objects");

StaticAndNonStatic.displayObjectCount();

/* Create an object and call the methods

Page 24: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 22

© Infosys Technologies Limited

using the object */

System.out.println();

System.out.println("After creating

objects");

StaticAndNonStatic object = new

StaticAndNonStatic('N');

StaticAndNonStatic.displayObjectCount();

StaticAndNonStatic.displayUserChoice();

}

}

Save the file as ‘StaticAndNonStaticDemo.java’ Compile the program and analyze the mistake in the code and rectify it. Summary of this exercise: You have just learnt

• The difference between static and instance variables

• How static variables can be accessed via object or class name

• A non-static method or variable cannot be accessed from a static context

Page 25: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 23

© Infosys Technologies Limited

3 Assignments for Day 2 of Java Programming All the assignments in this section must be completed on Day 2 of your Java

Programming course.

Assignment 10: Command line arguments

Objective: To write and compile a java program to deal with arrays for storing primitive data types. Depicts how to store values into the array and then retrieve the values. Step 1: Create a folder Assignment10 under your work directory (ie.C:\work\Java) Step 2: Set the basic environment variables required for working with Java by running the script created in Assignment3 Step 3: Open a text editor (In Windows, notepad.exe and in case of UNIX, vi) and type the following:

/* This file is a demo Java program which depicts the concept of

* command line arguments

*/

/**

* This class contains the main method which accepts the

* command line arguments and displays the concatenates strings.

* Date: 15-Jan-2005

* @author E&R Dept, Infosys Technologies Limited

* @version 1.0

*/

public class CommandLineArgs {

/**

* Starting point of the application.

* Expects exactly two command line arguments else

* prints an error message and terminates the program

* @param args Command line arguments

*/

public static void main(String args[]) {

if (args.length < 2 || args.length > 2) {

System.out.println("Invalid no of arguments –

Supply exactly two arguments");

Page 26: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 24

© Infosys Technologies Limited

System.exit(0);

}

System.out.println(args[0]+" "+args[1]);

}

}

Save the file as ‘CommandLineArgs.java’ Step 4: Compiling the program. Close the editor. Now compile your program using the command line:

javac CommandLineArgs.java Step 5: Run your program using the command line:

java CommandLineArgs Check the output of the program. Now run the program using the command line:

java CommandLineArgs Mother Teresa Check the output of the program. Now run the program using the command line:

java CommandLineArgs 5 6.8 Now the output will be 5 6.8 Step 6: Make changes to the code so that the two numbers instead of being concatenated get added. Hint: Refer to Javadoc for the wrapper classes Summary of this exercise: You have just learnt

• How to pass command line arguments into a java program

• The arguments are passed as a String

• How to convert the String value to its respective integer value in order to perform numerical operation on it

Assignment 11: Sorting a given set of numbers

Objective: To sort a given set of numbers

Page 27: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 25

© Infosys Technologies Limited

Problem Description:

• Accept five numbers from the user as command line arguments

• Sort the numbers and display the result Programming Guidelines:

• The numbers entered could be negative or even decimal.

• The command line arguments are String, need to be converted to their numeric values

• Use any sorting technique to sort the numbers

• Display the sorted array

Assignment 12: Learning java.lang package

Objective: To learn to refer to Java documentation and use the system defined classes Problem Description:

• Accept a number from the user as command line arguments.

• The number could be an integer or decimal value

• Display the absolute value of the input number

• Display the rounded off value of the input number

• Display the square root of the input value

Hint: There are in-built functions to achieve the above mentioned objectives. Refer to Javadoc for classes in the java.lang package

Assignment 13: Method overloading

Objective: To learn method overloading by extending a given piece of code Problem Description:

• Compile and run the given piece of code below

• Add an overloaded method to the code that takes a double as a parameter and returns the square of it

• Write another class with the main method

• Create an object of MethodOverLoadingDemo and call the methods

/**

* This class contains a method that finds the square of the

* given number.

* Date: 15-Jan-2005

* @author E&R Dept, Infosys Technologies Limited

* @version 1.0

*/

public class MethodOverLoadingDemo{

/**

* This method finds the square of the given integer

* and returns the same

Page 28: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 26

© Infosys Technologies Limited

* @param number1 The number for which the square to be

* found

* @returns The square of the number

*/

public int findSquare( int number1){

return ( number1* number1);

}

//Add an overloaded method that takes a double value

//and returns the square of it

Assignment 14: Overloading constructors

Objective: To write and compile a java program to learn the concept of constructors. Step 1: Create a folder Assignment14 under your work directory (ie.C:\work\Java) Step 2: Check the basic environment variables required for working with Java by running the script created in Assignment3. Step 3: Open a text editor (In Windows, notepad.exe and in case of UNIX, vi) and type the following: Filename ConstructorOverload.java

/* This java file has a class that contains multiple constructors

* and these constructors are invoked from another class

*/

/**

* This class contains three overloaded constructors

* Date: 12-Jan-2005

* @author E&R Dept, Infosys Technologies Limited

* @version 1.0

*/

public class ConstructorOverload {

int value1;

int value2;

/**

* Constructor. Creates the ConstructorOverload object and

* initializes value1 with the parameter supplied and also

* displays the values of value1 and value2

Page 29: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 27

© Infosys Technologies Limited

* @param number The instance variable value1 is set with

* this value

*/

public ConstructorOverload(int number) {

/* Initialize the instance variable with the supplied

parameter and display */

value1 = number;

System.out.print("Constructor with one argument :- ");

System.out.println("value1: " + value1 + " " +

"value2: " + value2);

}

/**

* Constructor. Creates the ConstructorOverload object and

* initializes value1 and value2 with the parameters

* supplied and also displays the values of value1 and

* value2

* @param number1 The variable value1 is set with this value

* @param number2 The instance variable value2 is set with

* this value

*/

public ConstructorOverload(int number1, int number2) {

// Initialize the instance variables with the supplied

parameters and display

value1 = number1;

value2 = number2;

System.out.print("Constructor with two

arguments :- ");

System.out.println("value1: " + value1 + " " +

"value2: " + value2);

}

/**

* Constructor. Default constructor, does not take any

* arguments and displays the values of value1 and value2

*/

public ConstructorOverload() {

/* Display the instance variable values without

initializing it. The instance variables by default

Page 30: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 28

© Infosys Technologies Limited

are initialized to zero */

System.out.print("Constructor with no arguments

(default constructor) :- ");

System.out.println("value1: " + value1 + " " +

"value2: " + value2);

}

}

Save the file as ‘ConstructorOverload.java’ Filename ConstructorDemo.java

/* This java file has a class that creates three objects of

* ConstructorOverlad class and invokes the constructors

*/

/**

* This class creates three instances of ConstructorOverload

* class and invokes the constructor with one and two parameters

* and the default constructor.

* Date: 12-Jan-2005

* @author E&R Dept, Infosys Technologies Limited

* @version 1.0

*/

public class ConstructorDemo {

/**

* creates three objects of the ConstructorOverload class

* and invokes the three overloaded constructors

* @param args Command line arguments

*/

public static void main(String args[]){

/* Create an object of ConstructorOverload class and

invokes the default (with no arguments) constructor */

ConstructorOverload obj1 = new ConstructorOverload();

/* Create an object ConstructorOverload class and

invokes the constructor with one argument */

ConstructorOverload obj2 = new ConstructorOverload(10);

/* Create an object of ConstructorOverload class and

invokes the constructor with two arguments */

ConstructorOverload obj3 = new ConstructorOverload(20,30);

Page 31: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 29

© Infosys Technologies Limited

}

}

Save the file as ‘ConstructorDemo.java’ Step 4: Compiling the program. Close the editor. Now compile your program using the command line:

javac ConstructorDemo.java Step 5: Run your program using the command line:

java ConstructorDemo The output of the program should come up.

Note: If the member variables of a class are not initialized they get initialized to their default values.

Now try out the code by removing the default constructor and recompiling the code. It gives compilation error. Try to analyze the reason. Summary of this exercise: You have just learnt

• How to write the constructor for a class

• How to overload the constructors for a class

• If user defined constructors are given for a class, then the default constructor will not be provided

Assignment 15: Constructor chaining and dynamic polymorphism

Objective: Whenever a child class object gets created, the base class constructor gets invoked (known as constructor chaining). If the base class has a parameterized constructor then an explicit call to the base class constructor is to be made using the keyword ‘super’. Step 1: Create a folder Assignment15 under your work directory (C:\work\Java) Step 2: Set the basic environment variables required for working with Java by running the script created in Assignment3 Step 3: Open a text editor (In Windows, notepad.exe and in case of UNIX, vi) and type the following.

Page 32: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 30

© Infosys Technologies Limited

Filename Person.java

/* This Java file contains a Person class that depicts the

* concept of constructor chaining

*/

/**

* This class contains the attributes of a person such as name

* and date of birth and a method to display the details.

* Date: 15-Jan-2005

* @author E&R Dept, Infosys Technologies Limited

* @version 1.0

*/

public class Person{

String personName;

int day

int month;

int year;

/**

* Constructor. Initializes name and date of birth of a

* person

* @param name The name of the person

* @param dd The day of the month

* @param mm The month of the year

* @param yyyy The year

*/

public Person(String name, int dd, int mm, int yyyy) {

personName = name;

day = dd;

month = mm;

year = yyyy;

}

/**

* This method displays the details of a person

*/

public void displayDetails(){

System.out.println("Name : " + personName);

Page 33: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 31

© Infosys Technologies Limited

System.out.println("Date of

birth:"+day+"/"+month+"/"+year);

}

}

Filename Employee.java

/* This Java file contains an Employee class which is a sub class

* of Person class and depicts the concept of overriding and

* creating objects of the classes Person and Employee

*/

/**

* This class contains the attributes of an employee such as

* employeId and salary and a method to display the details of an

* employee and also contains a main method that creates the

* objects and invokes the methods.

* Date: 15-Jan-2005

* @author E&R Dept, Infosys Technologies Limited

* @version 1.0

*/

public class Employee extends Person {

int employeeId;

double salary;

/**

* Constructor. Initializes employeeId and salary of an

* employee and also calls the super class constructor to

* initialize name and date of birth

* @param empId The employeeId of an employee

* @param ename The name of the employee

* @param eday The day of month

* @param emonth The month of the year

* @param eyear The year

* @param sal The salary of the employee

*/

public Employee(int empId, String ename, int eday,

int emonth, int eyear, double sal) {

// Call the super class constructor

// super(ename, eday, emonth, eyear);

employeeId = empId;

salary = sal;

Page 34: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 32

© Infosys Technologies Limited

}

/**

* This method displays the details of an employee

*/

public void displayDetails() {

super.displayDetails();

System.out.println("Employee Id : "+employeeId);

System.out.println("Salary : "+salary);

}

/**

* Starting point of the application.

* creates the objects of Person and Employee classes

* invokes the displayDetails method

* @param args Command line arguments

*/

public static void main(String args[]) {

/* Create the object of Person class by passing

name and date of birth and call the

displayDetails method */

Person objectPerson =

new Person("James Gosling", 10,11,1967);

objectPerson.displayDetails();

/* Create an object of Employee class and call

the method */

Employee objectEmployee =

new Employee(1101,"Dennis Ritchie",

25,05,1955,50000);

objectEmployee.displayDetails();

/* The object objectPerson is made as a

reference to objectEmployee */

objectPerson = objectEmployee;

objectPerson.displayDetails();

}

}

Save the file as ‘Employee.java’

Page 35: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 33

© Infosys Technologies Limited

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

javac Employee.java There is are compilation errors. Step 5: Why is the error? Read the error and try to debug before going to Step6. Step 6: Reason for error: When an object of the child class Employee is being created, the constructor of the Employee class is getting invoked. The sequence of action is, the base class constructor will get executed followed by child class constructor. In this case, the base class ie. Person has a parameterized constructor and hence default constructor will not be provided to the Person class (we learnt this in Assignment5). Hence to execute the Person class’ constructor, an explicit call using super() is to be made and the parameters to be passed. There is a commented line // super(ename, eday, emonth, eyear); Remove the comment (double slash) and the line should be super(ename,day,emont,eyear); Now recompile the code. There are still errors. Step 7: Why is the error? Read the error and try to debug. A weaker access privilege is being provided to the overriding function displayDetails(). Rectify the code above by making the function displayDetails() public and recompile. Now it should compile without error. Run your program using the command line:

java Employee The output of the program should come up.

Note 1: A base class reference can point to an object of the child class (objectPerson = objectEmployee) Note 2: When objectEmployee points to an Employee object then the Employee version of the displayDetails() function is getting called. When it is pointing to a Person object, the Person version of the displayDetails() function is getting called. So, it is being decided at run-time. Note 3: If the base class constructor is to be invoked using the keyword super(), the call should be the first line in the child class constructor Note 4: Note the displayDetails() method in the Employee class. A call to the displayDetails() of the Person class is being made using super.displayDetails(). When a child class needs to access the base class

Page 36: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 34

© Infosys Technologies Limited

version this is how it is done.

Summary of this exercise: You have just learnt

• How constructor chaining works

• When there is no default constructor of the base class, the child class constructor needs to invoke the base class constructor using super () and passing the required parameters.

• If a method has been overridden in the child class, the base class version can be accessed from the child class using super.methodname ().

• How to override a function of the base class in the child class

• While overriding, a greater access may be provided but narrowing of access is not allowed

• The method called during run-time is dependant on the object being pointed to and not on the type of the reference

Assignment 16: Multilevel inheritance

Objective: To learn multilevel inheritance and dynamic polymorphism Problem Description:

• Write a class called as Trainee to store GradePointAverage

• The Trainee class is a subclass of Employee

• Add a constructor to construct the Trainee class

• Add displayDetails method to display the GradePointAverage

• Write another class called as MutlilevelDemo to hold the main() method

• Create a reference to Person in main() method

• Create an object of Employee class

• Make the Person reference to point to the employee object and call the displayDetails method

• Create an object of Trainee class

• Make the Person reference to point to Trainee class and call the displayDetails method

Hint: A reference to Person class is created by including the statement Person personReference;

Assignment 17: Abstract classes and final modifier

Objective: To understand the various modifiers used in the Java language Problem Description: Given the following source code, which of the commented lines amongst (1), (2), (3) or (4) could be uncommented without changing anything else in the code and without introducing errors?

Page 37: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 35

© Infosys Technologies Limited

abstract class Demo {

protected static int count;

private int number;

abstract void getValues();

final void displayValues(){

}

//final void compute(){ } // (1)

}

final class MyDemo extends Demo{

int value;

//MyDemo(int temp){ value = temp; } // (2)

public static void main(String args[]) {

Demo object = new MyDemo();

}

void getValues(){ }

void compute() { }

//void incrementCount() { count++; } // (3)

//void incrementNumber() { number++; } // (4)

}

Analyze the results.

Assignment 18: Packages

Objective: To place a class inside a package. Compile the code and save the .class file in a different location using the –d option. See how packages affect the classpath. Step 1: Create the directory structure \MyProject\source\com\enr\Package1 under your work directory (ie.C:\work\Java) and also create a folder classes under C:\work\Java\MyProject Step 2: Set the basic environment variables required for working with Java by running the script created in Assignment3

Page 38: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 36

© Infosys Technologies Limited

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

/* This java files contains a class that depicts the concept of

* packages

*/

/**

* This class which is part of package com.enr.MyPackage contains

* the main method that prints a string.

* Date: 15-Jan-2005

* @author E&R Dept, Infosys Technologies Limited

* @version 1.0

*/

/* Include the package statement because the class should be

part of com.enr.MyPackage */

package com.enr.MyPackage;

public class PackageDemo {

/**

* Starting point of the application.

* Displays a string

* @param args Command line arguments

*/

public static void main(String args[]){

System.out.println("I am part of a package now");

}

}

Save the file as ‘PackageDemo.java’

Note: The first line of the above code. The class PackageDemo is a part of com.enr. MyPackage now.

Step 4: Compiling the program. Close the editor. Till now, after compilation, the .class file got saved in the same location as the .java file. Now our objective is to save the .class file in a different location so that the class files are separated from the

Page 39: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 37

© Infosys Technologies Limited

source code. Go to the location C:\work\Java\MyProject\source\com\enr\MyPackage and compile your program using the command line:

javac –d \work\Java\MyProject\classes PackageDemo.java

Note: The option –d will create the directory structure if it does not exist and the .class file will automatically get created in the right path.

Step 5: Go to the location C:\work\Java\MyProject\classes\com\enr\MyPackage and run your program using the command line:

java PackageDemo There is a runtime error stating that the class cannot be found. Step 6: Why is the error? Note that once a class is placed inside the package, it has to be accessed using its fully qualified name. So, how to rectify the error? Step 7: Go to the location C:\work\Java\MyProject\classes and run your program using the command line: java com.enr.MyPackage.PackageDemo Check the output of the program. It works!!!!! So, whenever you are working with packages you have to be in the location one level up from where the package directory structure begins and run the code using the fully qualified name of the class. Step 8: What if I want to run the code from any location let’s say from C:\ For this, where the package directory structure is, that information has to be added to the classpath. In Windows, set CLASSPATH=%CLASSPATH%\work\Java\MyProject\classes; In UNIX, CLASSPATH=$CLASSPATH\work\Java\MyProject\classes; export CLASSPATH Now go to C:\ and use the command line: java com.enr.MyPackage.PackageDemo It works!!!!

Page 40: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 38

© Infosys Technologies Limited

Summary of this exercise: You have just learnt

• How to make a class a part of a package

• How to use –d option and place the class file in a different location

• How package affects the classpath and in order that the package can be located from anywhere what changes in classpath setting needs to be done

Assignment 19: Access Specifiers

Objective: To place the base class in one package and the child class in some other package. How the child class needs to import the base class. It also explains how access specifiers determine what all will be available to the child class in a different package. Step 1: Work with the same directory structure \MyProject\source\com\enr\Package1 under your work directory (ie.C:\work\Java) that was created in Assignment 18. Step 2: Set the basic environment variables required for working with Java by running the script created in Assignment3 Step 3: Open a text editor (In Windows, notepad.exe and in case of UNIX, vi) and type the following:

/* This Java file contains a class the depicts different access

* specifiers with the class declared as part of a package

*/

/**

* This class contains default, protected and private data

* members and the method is declared with public access

* specifier which displays the values of instance variables.

* Date: 15-Jan-2005

* @author E&R Dept, Infosys Technologies Limited

* @version 1.0

*/

package com.enr.MyPackage;

public class AccessSpecifiers{

int number1;

protected int number2;

private int number3;

Page 41: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 39

© Infosys Technologies Limited

/**

* Constructor. Initializes the instance

* variables

*/

public AccessSpecifiers() {

number1 = 10;

number2 = 20;

number3 = 50;

}

/**

* This method displays the values of instance variables

*/

public void display(){

System.out.println("From the public function");

System.out.println("number1 = "+number1);

System.out.println("number2 = "+number2);

System.out.println("number3 = "+number3);

}

}

Save the file as ‘AccessSpecifiers.java’. This is the base class that we have created.

Note: The AccessSpecifiers class has been given public access as it will be accessed from a different package.

Step 4: Compiling the program. Close the editor. As in Assignment13 go to the location \work\Java\MyProject\source\com\enr\Package1 and compile your program using the command line: javac –d \work\Java\MyProject\classes AccessSpecifiers.java So, now the .class file of AccessSpecifiers is available in \work\Java\MyProject\classes\com\enr\MyPackage Step 5: Now it is time to write the code for the child class. Create a folder Package2 in the location \work\Java\MyProject\classes\com\enr. Open a text editor (In Windows, notepad.exe and in case of UNIX, vi) and type the following:

Page 42: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 40

© Infosys Technologies Limited

/* This Java file contains a class which is a sub class of

* AccsessSpecifiers class and is part of different package and

* it also depicts the access specifiers across packages

*/

/**

* This class which is a sub class of AccessSpecifiers and is

* part of DemoPackage. It creates an object of the class

* AccessSpecifiersDemo and it accesses the method. It also

* accesses the members of the super class.

* Date: 15-Jan-2005

* @author E&R Dept, Infosys Technologies Limited

* @version 1.0

*/

package com.enr.DemoPackage;

import com.enr.MyPackage.*;

class AccessSpecifiersDemo extends AccessSpecifiers

{

/**

* This method accesses the instance variables of the super

* class that are declared using different access specifiers

*/

void view()

{

/* Instance variable number1 has default(package)

access in super class and accessible only within

the package, but not accessible outside the package

*/

System.out.println(number1);

/* Instance variable number2 has protected access in

super class and accessible either within the

package or within the sub class outside the

package, but not accessible in a non sub class

outside the package */

System.out.println(number2);

/* Instance variable number has private access in

super class and not accessible outside the class */

Page 43: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 41

© Infosys Technologies Limited

System.out.println(number3);

/* Method with public access specifier can be accessed

in all the classes with in the package and outside

the package */

display();

}

/**

* Starting point of the application. This method creates

* an object of AccessSpecifiersDemo and call the view

* method

* @param args Command line arguments

*/

public static void main(String a[])

{

// Create an object and invoke the method

AccessSpecifiersDemo object = new

AccessSpecifiersDemo();

object.view();

}

}

Note 1: There is an import statement in the 2nd line which makes the classes available in Package1 to this class which is in a different package Package2. Note 2: If there is a package statement and an import statement, the order has to be maintained. The package statement has to be the first line in the code.

Step 6: Compiling the program. Close the editor. As in Assignment13 go to the location \work\Java\MyProject\source\com\enr\DemoPackage and compile your program using the command line: javac –d \work\Java\MyProject\classes AccessSpecifiers.java You get many compilation errors one which states that the reference of AccessSpecifiers is not available.

Page 44: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 42

© Infosys Technologies Limited

Step 7: Why is the error? Please remember that the code has reference to AccessSpecifiers so the classpath needs the information where the package com.enr.Package1 is. So as you did in assignment13 before, set the classpath as: In Windows, set CLASSPATH=%CLASSPATH%\work\Java\MyProject\classes; In UNIX, CLASSPATH=$CLASSPATH\work\Java\MyProject\classes; export CLASSPATH Now try to compile the code again as before. The compilation errors are less and the errors are that number1 and number3 are not accessible Step 8: Why is the error? Remember ‘number1’ has package access hence it is not accessible to Package2Child which is in a different package Package2. ‘number3’ has private access and hence not accessible outside the Package1Base class. Remove these lines of code and compile. It works!!! Step 9: Running the code. The main method is in AccessSpecifiersDemo. So to run the code from anywhere (remember the classpath is already set), type in the command line: java com.enr.DemoPackage.AccessSpecifiersDemo It should work if you have followed the steps correctly Summary of this exercise: You have just learnt

• How to use import statement

• How the child class in one package can refer to a base class located in a different package

• How the child class in a different package can only access the public and protected members of the base class of a different package

Assignment 20: Typecasting of objects

Objective: To understand the how type casting works in the Java language Problem Description:

Page 45: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 43

© Infosys Technologies Limited

Given the following source code, which of the lines (1), (2), (3) will throw compilation or run-time error? Or will the code compile and run successfully. Try to analyze before actually compiling and running the code

class Parent{

}

class Child extends Parent{

}

public class TypecastDemo{

public static void main(String args[]){

Parent[] arrParent;

Child[] arrChild;

arrParent = new Parent[10];

arrChild = new Child[20];

arrParent = arrChild; //1

arrChild = (Child[])arrParent; //2

arrParent = new Parent[10];

arrChild = (Child[])arrParent; //3

}

}

Now, compile and run the code and try to analyze the results.

Assignment 21: Interfaces and reference objects

Objective: To understand which are the valid reference types to point to an object Problem Description: Given the following class definitions and declaration statements, which one of these assignment statements is legal at compile time? Try to analyze before actually compiling the code

//Class and Interface Definitions

Page 46: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 44

© Infosys Technologies Limited

interface MyInterface{}

class MyClass1 {

}

class MyClass2 extends MyClass1 implements MyInterface {

}

class MyClass3 implements MyInterface {

}

class ReferenceDemo{

public static void main(String args[]){

//Declaration statements

MyClass1 class1Object = new MyClass1 ();

MyClass2 class2Object = new MyClass2 ();

MyClass3 class3Object = new MyClass3();

}

}

From the following options, Identify the valid option.

a) class2Object = class3Object; b) class3Object = class2Object; c) MyInterface InterfaceRef = class3Object; d) class3Object = (MyClass3) class2Object; e) class2Object = class1Object;

Hint: A base class reference can point to an object of the child class. An interface reference can also point to an object of its implementing class Now, compile the code and try to analyze the results.

Page 47: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 45

© Infosys Technologies Limited

Assignment 22: Creating jar files

Objective: To place a class (which is part of a package) inside a .jar file and run the program from within the jar. Step 1: Open a text editor (In Windows, notepad.exe and in case of UNIX, vi) and type the following:

/* This Java file contains a class which is part of

* package and will be placed in a jar file

*/

/**

* This class has the starter method

* to display a message

* Date: 25-Jan-2005

* @author E&R Dept, Infosys Technologies Limited

* @version 1.0

*/

package com.enr.package1;

class Sample{

/**

* Starting point of the application.

* Displays a message on the console

* @param args Command line arguments

*/

public static void main(String args[]){

System.out.println("I am running from inside a jar");

}

}

Step 2: Save this file as Sample.java in the path C:\work\Java\MyProject\source\com\enr\package1 Step 3: Using javac –d option (as learnt in Assignment 18) compile Sample.java and save the .class file under C:\work\Java\MyProject\classes. So, Sample.class is now a part of package com.enr.package1. Step 4: Making an executable jar. The first step to create a .jar file is to create the manifest file that states which class has the main () method. The fully-qualified class name must be mentioned. Make a text file named manifest.txt that has a single line:

Page 48: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 46

© Infosys Technologies Limited

Main-Class: com.enr.package1.Sample

Note 1: Give a space after the colon. Note 2: Press return key after typing the first line

Save this manifest.txt file in the path C:\work\Java\MyProject\classes Step 5: Go to the location C:\work\Java\MyProject\classes and run the jar command from the command line as: jar –cvmf manifest.txt packEx.jar com

Note 1: c, stands for create, -v, verbose -m, include information of the manifest file

-f, specify archive file name Note 2: packEx.jar is the name of the jar file to be created. Note 3: Only the com directory needs to be specified and the entire package will go into the JAR

Step 6: Run the code stored in the jar file Go to the location C:\work\Java\MyProject\classes (path where the jar file has got saved) and type from the command line: java –jar packEx.jar Check the output of the program. It works!!!!! Step 8: Let us list out the contents of packEx.jar that we just now created. Type from the command line: jar -tf packEx.jar

Page 49: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 47

© Infosys Technologies Limited

Note: -tf stands for table of files.

Note: The jar utility created the directory META-INF (‘meta information’) and a file MANIFEST.MF got created inside it. The contents from manifest.txt file were written into MANIFEST.MF file.

Summary of this exercise: You have just learnt

• How to run the jar utility and create a jar file

• How to run the code kept inside a jar file

• The importance of a manifest file

• How to list the contents of a jar file

Page 50: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 48

© Infosys Technologies Limited

4 Assignments for Day 3 of Java Programming All the assignments in this section must be completed on Day 3 of your Java Programming course.

Assignment 23: Manipulation of strings

Problem Description: Write a program in Java which accepts 2 strings as command line arguments. The program should do the following:

i) print and display the total number of occurrences of the character ‘a’ or ‘A’ present in both the strings

ii) replace every occurrence of ‘a’ or ‘A’ by @ iii) convert both the strings to upper case iv) concatenate the two strings and finally display the result

Hint: Refer to Java documentation for String and StringBuffer classes.

Assignment 24: Working with dates

Problem Description: Write a program in Java which initializes the starting date as your birthday and displays the date 90 days later in the format day name, month name, day, year (eg. Monday, April 20, 1998) Hint: Refer to java documentation for GregorianCalendar and DateFormatter classes.

Assignment 25: Hash Table

Problem Description: Store the names of 10 major cities and the names of corresponding countries in a hash table. Accept the name of a city as a command-line argument and display the country in which it is situated. Make provision to display a message if the user either forgets to provide command-line argument or specifies a city that is not in the hash table.

Assignment 26: Working with collection classes

Problem Description: Take in 10 numbers as command line arguments and store it in a collection. The numbers are to be displayed in the reverse order in which they were entered. Proper error messages should be displayed if:

i) command line arguments have not been entered ii) less than 10 numbers have been fed in iii) If one of the arguments is not a valid number

Page 51: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 49

© Infosys Technologies Limited

Assignment 27: Exception handling

Objective: We will learn the usage of try-catch-finally blocks as a part of exception handling in Java. This assignment shows the flow of a program when an exception occurs. Step 1: Create a folder Assignment27 under your work directory (C:\work\Java) Step 2: Set the basic environment variables required for working with Java by running the script created in Assignment3 Step 3: Open a text editor (In Windows, notepad.exe and in case of UNIX, vi) and type the following. Filename: DivisionByZero.java

/*

* This file is a demo Java program which

* depicts exception handling

*/

/**

* This class has risky code which might throw

* run-time exceptions and hence exception handlers have

* been placed

* Date: 31-Jan-2005

* @author E&R Dept, Infosys Technologies Limited

* @version 1.0

*/

public class DivisionByZero {

/**

* computes division of two numbers

*/

public void division(){

int num1 = 10;

int num2 = 0;

try {

System.out.println(num1 + "/" + num2 + "=" +

(num1/num2));

System.out.println("This line will not get

executed");

}

catch(NullPointerException e){

Page 52: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 50

© Infosys Technologies Limited

System.out.println("In the first catch

block");

}

catch(ArithmeticException e){

System.out.println("In the second catch

block");

}

finally {

System.out.println("Finally done.");

}

System.out.println("Returning from division");

}

/**

* Creates an object of the DivisionByZero class and

* invokes the method division using the object

* @param args Command line arguments

*/

public static void main(String args[]){

new DivisionByZero().division();

System.out.println("Returning from main");

}

}

Save the file as ‘DivisionByZero.java’ Step 4: Compiling the program. Close the editor. Now compile your program using the command line: javac DivisionByZero.java Step 5: Try to predict the output of the code during run-time before moving to Step 6: Now run the code by typing in the command line: java DivisionByZero The output of the program should come up.

Note: 1) As Arithmetic exception got raised, the catch block to handle that exception only got executed 2) The second line in the try block never got executed as the exception got raised in the first line. If the control moves out of a block due to an exception, it never re-enters the same block again.

Page 53: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 51

© Infosys Technologies Limited

3) Finally block gets executed always 4) Once the exception has been caught, the flow of the program continues normally. Hence we got the outputs “Returning from division” and “Returning from main”

Step 7: Make slight modification to the given code by adding a new catch block (given below) before the catch block for ArithmeticException

catch(Exception e){

System.out.println("In the exception catch block");

}

Step 8: Try to recompile this modified code. You will get compilation error. Why is the error? Step 9: The sequence of catch blocks added to the code does matter. Since Exception class is a base class for ArithmeticException, any exception that can be caught by ArithmeticException class can be handled by Exception class as well. So, the catch block of ArithmeticException will never get a chance to be executed and hence the compilation error. Summary of this exercise: You have just learnt

• How to write code for exception handling using try-catch-finally blocks.

• Which catch block gets executed depends on the type of exception that is raised.

• If an exception has been handled by any of the catch blocks, the program flow can continue as usual.

• The sequence of adding the catch blocks in the code matters.

Assignment 28: Flow of exceptions

Objective: We will see how the program flow occurs if a particular exception has not been caught. Step 1: Create a folder Assignment28 under your work directory (C:\work\Java) Step 2: Set the basic environment variables required for working with Java by running the script created in Assignment3 Step 3: Open a text editor (In Windows, notepad.exe and in case of UNIX, vi) and type the following. The code is a slight modification of the code used in Assignement25.

Page 54: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 52

© Infosys Technologies Limited

Filename: DivisionByZero1.java

/*

* This file is a demo Java program which

* depicts exception handling

*/

/**

* This class has risky code which might throw

* run-time exceptions and hence exception handlers have

* been placed.

* Date: 31-Jan-2005

* @author E&R Dept, Infosys Technologies Limited

* @version 1.0

*/

public class DivisionByZero1 {

/**

* Computes division of two numbers

*/

public void division(){

int num1 = 10;

int num2 = 0;

try{

System.out.println(num1 + "/" + num2 + "=" +

(num1/num2));

}

catch (NullPointerException e){

System.out.println("In the first catch block");

}

finally {

System.out.println("Finally done.");

}

System.out.println("Returning from division");

}

/**

Page 55: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 53

© Infosys Technologies Limited

* Creates an object of the DivisionByZero class and

* invokes the method division using the object.

* @param args Command line arguments

*/

public static void main(String args[]){

new DivisionByZero1().division();

System.out.println("Returning from main");

}

}

Save the file as ‘DivisionByZero1.java’ Step 4: Compiling the program. Close the editor. Now compile your program using the command line:

javac DivisionByZero1.java

Step 5: Try to predict the output of the code during run-time before moving to The next step. Step 6: Now run the code by typing in the command line:

java DivisionByZero

The output of the program should come up.

Note1: In the changed code, the exception could not be handled by a suitable catch block. Note2: However, finally block even then got executed. Note3:The exception got percolated up and was finally handled by the default handler.

Make necessary changes to the code of DivisionByZero1.java so that “Returning from division” should not get printed but “Returning from main” should get printed. Summary of this exercise: You have just learnt

• How the program flow occurs if the exception has not been caught in any of the catch blocks

Assignment 29: User defined exception

Page 56: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 54

© Infosys Technologies Limited

Objective: Now we will see how to code for a user defined exception class and how to throw and catch a user defined exception. Step 1: Create a folder Assignment29 under your work directory (C:\work\Java) Step 2: Set the basic environment variables required for working with Java by running the script created in Assignment3 Step 3: Open a text editor (In Windows, notepad.exe and in case of UNIX, vi) and type the following. The code is a modification of the code used in Assignement23 to incorporate a user defined exception class.

/*

* This file is a demo Java program which

* depicts how to user defined exception classes

*/

/**

* This class is a user defined exception class

* sub classing from Exception class.

* Date: 31-Jan-2005

* @author E&R Dept, Infosys Technologies Limited

* @version 1.0

*/

class DivisionByZeroException extends Exception{ // (1)

/**

* Constructor. Calls the base class constructor by

* passing a String parameter.

* @param message This string value is passed to the

* base class constructor

*/

public DivisionByZeroException(String message){

super(msg);

}

}

/**

* This class has a method division which can throw an exception.

* Date: 31-Jan-2005

* @author E&R Dept, Infosys Technologies Limited

* @version 1.0

*/

Page 57: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 55

© Infosys Technologies Limited

public class DivisionByZero2{

/**

* Computes the division of two numbers.

* @exception DivisionByZeroException

*/

public void division() throws DivisionByZeroException { //(2)

int num1 = 10;

int num2 = 0;

if (num2 == 0)

throw new DivisionByZeroException("/ by 0");

//(3)

System.out.println(num1 + "/" + num2 + "=" +

(num1/num2));

System.out.println("Returning from division");

}

/**

* Starting point of the application.

* creates references of class DivisionByZero2

* and calls the method division.

* @param args command line arguments

*/

public static void main(String args[]){

try{

new DivisionByZero2().division();

}

catch(DivisionByZeroException e){ //(4)

System.out.println("In main, dealt with "+ e);

//(5)

}

finally {

System.out.println("Finally done in main.");

}

System.out.println("Returning from main.");

}

}

Save the file as ‘DivisionByZero2.java’ Step 4: Note the steps involved when coding for a user defined exception class:

1) class DivisionByZeroException is the user defined exception class which must extend from the exception class (Step marked (1))

Page 58: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 56

© Infosys Technologies Limited

2) The method division() declares that it throws exception of type DivisionByZeroException (Step marked (2))

3) The user defined exception is explicitly thrown using the throw clause (Step marked (3))

4) In the catch block in the main() method, the DivisionByZeroException is caught (Step marked (4))

Step 5: Compiling the program. Close the editor. Now compile your program using the command line:

javac DivisionByZero2.java Step 6: Now run the code by typing the command line:

java DivisionByZero2 The output of the program should come up.

Note: Look at output coming from the Step marked (5). Effectively .toString() method is getting invoked here. Go to javadoc and check the Exception class. See how toString() method of Object class is overridden by the Throwable class and which is used in Exception class as well (Exception class is a child class of Throwable).

Summary of this exercise: You have just learnt

• How to write a user defined exception class

• How to use the ‘throw’ and ‘throws’ clause in Exception handling

Assignment 30: Debugging run-time errors

Problem Description: The code below has a Student class defined and we are trying to work with an array of Student objects, trying to set rollNo and names to the students. The code is compiling fine but throwing exception during run-time. Read the error message and rectify the code.

class Student{

private int rollNo;

private String name;

public void setrollNo(int rollNo){

this.rollNo = rollNo;

}

Page 59: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 57

© Infosys Technologies Limited

public void setName(String name){

this.name = name;

}

public int getrollNo(){

return rollNo;

}

public String getName(){

return name;

}

public static void main(String args[]){

Student arrStudent[]=new Student[2];

arrStudent[0].setrollNo(1001);

System.out.println(arrStudent[0].getrollNo());

}

}

Assignment 31: Debugging run-time errors

Problem Description: The code below compiles fine but throws run-time exception. Debug the code and rectify it. Analyze the error.

class TypeCast{

public static void main(String args[]){

String aString= "abcde";

Object anObject = aString;

String testString = (String)anObject;

Integer anInteger = new Integer(10);

anObject = anInteger;

Integer testInteger = (Integer)anObject;

testString = (String)anObject;

}

}

Assignment 32: Reading a .properties file

Page 60: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 58

© Infosys Technologies Limited

Objective: To read values present in the .properties file from the java program using

ResourceBundle class.

Step 1: Create a .properties file by name productlist.properties and the contents as shown below Filename: productlist.properties

# Properties file for storing the information about products

name = powder,soap,lipstick,toothpaste

price = 100,150,25,250

company = Johnson,Lever,Lakme,Colgate

Step 2: Open your favorite editor and type the code below and save the file with the name ReadProperties.java. Filename: ReadProperties.java

/*

* This file is a demo Java program which

* depicts how to read from a .properties file

*/

import java.util.ResourceBundle;

/**

* This class reads the data present in the

* productlist.properties file and displays on

* to the console screen

* Date: 16-Jul-2005

* @author E&R Dept, Infosys Technologies Limited

* @version 1.0

*/

public class ReadProperties{

/* Resourcebundle class object */

ResourceBundle resourcebundle;

/**

* Constructor. It reads the properties file and keys

* present in the properties file and display

* on to the console.

*/

public ReadProperties(){

Page 61: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 59

© Infosys Technologies Limited

/* getting the resource bundle from the properties

file */

resourcebundle=ResourceBundle.getBundle

("productlist");

/* getting the key names present in the properties

file and split w r t ',' given in the properties

in order to get each value which is separated by

','*/

StringnameOfProduct[]=resourcebundle.

getString("name").split(",");

String priceOfProduct[]=resourcebundle.

getString("price").split(",");

String companyOfProduct[]=resourcebundle.

getString("company").split(",");

/* Loop for getting each of the values present

in the string array */

for (int loopIndex=0;

loopIndex<nameOfProduct.length;

loopIndex++){

/* Printing in a required format */

System.out.println("Product No :"+(loopIndex+1));

System.out.println("----------------

-------------------------");

System.out.println("Name of the Product :"+

nameOfProduct[loopIndex]);

System.out.println("Price of the Product Rs: "+

priceOfProduct[loopIndex]+"/-");

System.out.println("Manufacturer of the Product

:"+companyOfProduct[loopIndex]);

System.out.println("------------------------

-----------------");

}

}

/**

* Starting point of the application.

* @param args Command line arguments

Page 62: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 60

© Infosys Technologies Limited

*/

public static void main(String[] args) {

ReadProperties readproperties=new ReadProperties();

}

}

Step 3: Compile and run the program. Step 4: The Output of the above program is as show below:

Page 63: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 61

© Infosys Technologies Limited

5 Assignments for Day 4 of Java Programming All the assignments in this section must be completed on Day 4 of your Java Programming course.

Assignment 33: File Input and Output

Objective: To write a program that creates a FileOutputStream object, fileOutputStream, and stores bytes into the file “Data”. Each byte of input is written, one at a time, to fileOutputStream. A FileInputStream object, fileInputStream, is created to read the available bytes from the file “Data” that is used as an argument

to the FileInputStream constructor.

Step 1: Create a folder Assignment33 under your work directory (C:\work\Java) Step 2: Set the basic environment variables required for working with Java Step 3: Open a text editor (In Windows, notepad.exe and in case of UNIX, vi) and type the following. Filename FileIOTest.java

/* This Java file contains a class which write bytes

* to a file and read bytes from the same

* file.

*/

/**

* This class uses FileOutputStream to write bytes to a file

* and FileInputStream to read bytes from the same file.

* Date: 12-Jan-2005

* @author E & R Dept, Infosys Technologies Limited

* @version 1.0

*/

import java.io.*;

public class FileIOTest {

/**

* Starting point of the application. Creates

* objects of FileOutputStream and FileInputStream and

* invokes methods of these objects

Page 64: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 62

© Infosys Technologies Limited

* @param args Command line arguments

*/

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

/* Creates a FileOutputStream to write bytes to the

file "Data". It creates a file before opening it

for output when an object is created */

FileOutputStream fileOutputStream = new

FileOutputStream("Data");

byte b1 = 65, b2 = 66, b3 = 67;

//Write these bytes to the file

fileOutputStream.write(b1);

fileOutputStream.write(b2);

fileOutputStream.write(b3);

//Close the stream

fileOutputStream.close();

//Create a stream to read bytes from the file

FileInputStream fileInputStream = new

FileInputStream("Data");

int value = fileInputStream.read();

//Loop till the end of the stream is reached

while(value != -1) {

System.out.println((byte)value);

value = fileInputStream.read();

}

//close the input stream

fileInputStream.close();

}

}

Save the file as ‘FileIOTest.java’

Page 65: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 63

© Infosys Technologies Limited

Note 1: After creating a FileOutputStream, each byte is written to file “Data” using FileOutputStream, one at a time. Note 2 : The stream is closed after the write operation

Note 3 : A FileInputStream object, fileInputStream, is created. The read() method is invoked for fileInputStream to read available bytes of data.

Step 4: Compile and run the program The contents of the file are printed as follows: 65 66 67 Summary of this exercise: You have just learnt

• The steps required to define streams for File input and output with which it is possible to write to a file and read file

Assignment 34: Handling Primitive data types

Objective: We will see the following program which uses DataInputStream and DataOutputStream to read and write tabular data. The tabular data is formatted in columns, where each column is separated from the next by tabs. The columns contain the Employee age,name and employee number Step 1: Create a folder Assignment34 under your work directory (C:\work\Java) Step 2: Set the basic environment variables required for working with Java Step 3: Open a text editor (In Windows, notepad.exe and in case of UNIX, vi) and type the following. Filename DataIOApp.java

/* This Java file contains a class which writes primitive types

* to a file and read these types from the same file

* to a file and read bytes from the same

* file.

*/

Page 66: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 64

© Infosys Technologies Limited

/**

* This class DataIOApp has the starter method main. This

* class shows you how to use the java.io DataInputStream and

* DataOutputStream classes. It reads and writes tabular data.

* The tabular data is formatted in columns, where each column is

* separated from the next by tabs. The columns contain the

* Employee age, name and employee number.

* Date: 12-Jan-2005

* @author E&R Dept, Infosys Technologies Limited

* @version 1.0

*/

import java.io.*;

class DataIOApp

{

/**

* Starting point of the application. Creates

* objects of DataInputStream, DataOutputStream,FileInputStream

* and FileOutputStream invokes methods of these objects

* @param args Command line arguments

*/

public static void main(String[] args) {

//Create the file

try {

//Creates filter sream that wraps around file stream

DataOutputStream dataOutputStream = new

DataOutputStream(new FileOutputStream

("Trainee.txt")); //(1)

//Formatted data to be stored in to the file

double[] dAge = {29.53, 39.74,35.35, 28.99, 34.99};

int[] iEmpno = { 12, 8, 13, 29, 50 };

String[] sName = { "Narendran", "Sanjay",

"Susan", "Ram Gopal","Sukesh" };

//Writing to the file using filter stream

for(int Count=0;Count<dAge.length;Count ++){ //(2)

Page 67: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 65

© Infosys Technologies Limited

dataOutputStream.writeDouble(dAge[Count]);

dataOutputStream.writeChar('\t');

dataOutputStream.writeInt(iEmpno[Count]);

dataOutputStream.writeChar('\t');

dataOutputStream.writeChars(sName[Count]);

dataOutputStream.writeChar('\n');

}

dataOutputStream.close();

}

catch (IOException ioException) {

System.out.println("DataIOApp: " + ioException);

}

//Read the file

try {

//Creates filter stream to read from file

DataInputStream dataInputStream = new

DataInputStream(new

FileInputStream("Trainee.txt")); //(3)

double dAge;

int iEmpno;

String sName;

double total = 0.0;

try {

while (true) {

//Reading from the file

dAge=dataInputStream.readDouble(); //(4)

dataInputStream.readChar();//throws out tab

iEmpno = dataInputStream.readInt();

dataInputStream.readChar();// throws out tab

sName = dataInputStream.readLine();

System.out.println("You've Retrieved Name :

" + sName + " Age : " +

dAge + " Empno : " + iEmpno);

}

}

catch (EOFException eofException) {

Page 68: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 66

© Infosys Technologies Limited

}

dataInputStream.close();

}

catch (FileNotFoundException fileNotFoundException) {

System.out.println("DataIOApp: "+

fileNotFoundException);

}

catch (IOException ioException) {

System.out.println("DataIOApp: " + ioException);

}

}

}

Save the file as ‘DataIOApp.java’

Note 1: A DataOutputStream, like other filtered output streams, must be attached to some other OutputStream. In this case, it's attached to a

FileOutputStream that's set up to write to a file named Trainee.txt.(marked as steps (1)

Note 2: Next, DataIOApp uses DataOutputStream's specialized writeXXX() methods to write the invoice data (contained within arrays in the program) according to the type of data being written. (marked as step (2)) Note 3: Next, DataIOApp opens a DataInputStream on the file just written DataInputStream, also must be attached to some other InputStream. In this case, it's attached to a FileInputStream set up to read the file just written--

Trainee.txt. (marked as step(3)) Note 4: DataIOTest then just reads the data back in using DataInputStream's

specialized readXXX() methods. (marked as step(4))

Step 4: Compile and run the program. The output of the program will give the primitive data values read form the file. Summary of this exercise: You have just learnt

• The steps required to define streams for reading and writing primitive data types

• How to read and write formatted data from/to a file using filtered streams.

Page 69: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 67

© Infosys Technologies Limited

Assignment 35: Input and Output Buffering

Objective: Modify Assignment 33 such that input and output operations are performed with buffering using BufferedInputStream and BufferedOutputStream.

Assignment 36: Device Independent Input and Output

Objective: To write a program that uses similar type of interfaces to write data to a file, bytearray, standard output making use of Java’s device independent IO system. It creates a FileOutputStream object, BytearrayOutputStream object and uses System.out to write data to a file “Data”, bytearray and standard output.

Step 1: Create a folder Assignment36 under your work directory (C:\work\Java) Step 2: Set the basic environment variables required for working with Java Step 3: Open a text editor (In Windows, notepad.exe and in case of UNIX, vi) and type the following. Filename ByteWriter.java

/* This Java file contains a class which uses * * *

* FileOutputStream,BytearrayOutputStream,System.in streams to

* write to different type of destinations using the device

* independent form

*/

/**

* This class contains FileOutputStream, BytearrayOutputStream,

* System.in streams to write bytes to a file, byteArray and

* standard input respectively.

* Date: 12-Jan-2005

* @author E&R Dept, Infosys Technologies Limited

* @version 1.0

*/

import java.io.OutputStream;

import java.io.IOException;

import java.io.ByteArrayOutputStream;

Page 70: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 68

© Infosys Technologies Limited

import java.io.FileOutputStream;

import java.io.FileInputStream;

public class ByteWriter{

/**

* This method writes bytes to the specified destination

*/

public void writeBytes(OutputStream outputStream){

try {

outputStream.write(65);

outputStream.write(66);

outputStream.write(67);

}

catch(IOException exception){

System.out.println(exception);

}

}

/**

* Starting point of the application. Creates objects of

* DataInputStream, DataOutputStream, FileInputStream and

* FileOutputStream invokes methods of these objects

* @param args Command line arguments

*/

public static void main(String [] args){

try{

ByteArrayOutputStream byteArrayOutputStream = new

ByteArrayOutputStream();

FileOutputStream fileOutputStream = new

FileOutputStream("Data");

ByteWriter byteWriter = new ByteWriter();

//Write to the console

byteWriter.writeBytes(System.out);

System.out.println(“\n”);

//Write to a byte array

byteWriter.writeBytes(byteArrayOutputStream);

//Write to a file

byteWriter.writeBytes(fileOutputStream);

Page 71: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 69

© Infosys Technologies Limited

//Printing all elements of the byte array

byte data[] =

byteArrayOutputStream.toByteArray();

for(int i = 0; i < data.length; ++i){

System.out.println(data[i]);

}

//Printing all elements from the file

FileInputStream fileInputStream = new

FileInputStream("Data");

int value = fileInputStream.read();

while(value != -1){

System.out.println((byte)value);

value = fileInputStream.read();

}

fileInputStream.close();

}

catch(IOException exception){

System.out.println(exception);

}

}

}

Save the file as ‘ByteWriter.java’

Note : Each time the writeBytes method is called, a stream object of type FileOutputStream, BytearrayOutputStream and System.in are passed as arguments. Since the Formal argument of type OutputStream used in the writeBytes method is the super class of all these stream objects, similar interfaces could be used to call the method.

Step 4: Compile and run the program. The output of the program is as follows: ABC 65 66

Page 72: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 70

© Infosys Technologies Limited

67 65 66 67 Summary of this exercise: You have just learnt

• The steps required to create device independent form of input/output operations using Java’s stream classes.

Assignment 37: File Copy

Objective: Java can read several types of information from files: binary, Java objects, text, zipped files, etc. Here we will see how to read text files using the classes FileReader, BufferedReader, FileWriter, and BufferedWriter. It's a main program without a graphical user interface, taking parameters from the command line. Step 1: Create a folder Assignment37 under your work directory (C:\work\Java) Step 2: Set the basic environment variables required for working with Java Step 3: Open a text editor (In Windows, notepad.exe and in case of UNIX, vi) and type the following. Filename FileCopyDemo.java

/* This Java file contains a class which uses FileReader,

* BufferedReader, FileWriter, and BufferedWriter to copy the

* contents of a file to another.

*/

/**

* This class copies the content of first file

* mentioned in the command line to the second file.

* Date: 12-Jan-2005

* @author E&R Dept, Infosys Technologies Limited

* @version 1.0

*/

import java.io.*;

public class FileCopyDemo{

Page 73: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 71

© Infosys Technologies Limited

/**

* Starting point of the application. Creates

* objects of File, BufferedReader and BufferedWriter and

* also invokes methods of these objects

* @param args Command line arguments

*/

public static void main(String args[]){ //(1)

/* Get the source and target file names as command

line arguments */

if (args.length != 2){

System.err.println("Usage: java FileCopyDemo

sourcefile targetfile");

System.exit(1);

}

//Create File objects

File inFile = new File(args[0]); //(2)

File outFile = new File(args[1]); //(3)

/* Enclose in try..catch because of possible io

Exceptions */

try {

//Create reader and writer for text files

BufferedReader reader = new BufferedReader(new

FileReader(inFile)); //(4)

BufferedWriter writer = new BufferedWriter(new

FileWriter(outFile)); //(5)

//Loop as long as there are input lines

String line = null;

while ((line=reader.readLine()) != null) //(6)

{

writer.write(line); //(7)

// Write system dependent end of line

writer.newLine();

}

//Close reader and writer

reader.close();

writer.close();

Page 74: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 72

© Infosys Technologies Limited

}

catch (IOException exception){

System.err.println(exception);

System.exit(1);

}

}

}

Save the file as ‘FileCopyDemo.java’

Note 1: This program takes two files as commandline arguments and copy the content of the first file to the second file. (marked as steps (1),(2)and (3)) Note 2 Reader is a bufferded reader for input text file and writer is a buffered writer for output text file. They allow buffering of characters while reading and writing to enhance performance. (marked as step (4) and (5)) Note 3 : readLine() will read lines of text form the first file and writeLine() writes those lines to the second file. A loop is set up for copying all the lines form first file to second file. (marked as step(6) and (7))

Step 4: Compile the program. Step 5: Create a text file “input.dat” with some lines of text. Step 6: Run your program using the command line: java FileCopyDemo input.dat output.dat

The execution of this program copy all the text lines from input.dat to output.dat Step 7 : Open the file output.dat. You can see the contents of input.dat copied to output.dat Summary of this exercise: You have just learnt

• The steps required to define streams for character IO and buffering with files.

• How to read a line of text from one text file with buffering.

• How to write a line of text to one text file with buffering.

Page 75: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 73

© Infosys Technologies Limited

Assignment 38: LineNumberReader

Objective: To write a program that demonstrates the use of LineNumberReader and to print out all the lines of a file, with each line prefixed by its number. Step 1: Create a folder Assignment38 under your work directory (C:\work\Java) Step 2: Set the basic environment variables required for working with Java Step 3: Open a text editor (In Windows, notepad.exe and in case of UNIX, vi) and type the following. Filename LineNumberDemo

/* This Java file contains a class which uses LineNumberReader

* and displays the line numbers along with lines read from a

* file

*/

import java.io.*;

/**

* This class uses LineNumberReader stream. It prints out all

* lines of a file, with each line prefixed by its number. It

* has the starter method main.

* Date: 12-Jan-2005

* @author E&R Dept, Infosys Technologies Limited

* @version 1.0

*/

public class LineNumberDemo{

/**

* Starting point of the application. Creates

* objects of FileReader and LineNumberReader and also

* invokes methods of these objects.

* @param args Command line arguments

*/

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

try {

/* Creates a filereader class to connect to file

DataIOApp.java */

FileReader fileIn = new

Page 76: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 74

© Infosys Technologies Limited

FileReader("DataIOApp.java"); //(1)

/* Create a LineNumberReader object to get line

number of read lines from file */

LineNumberReader lineNumberReader = new

LineNumberReader(fileIn); //(2)

String line;

while ((line= lineNumberReader.readLine()) != null)

{

System.out.println

(lineNumberReader.getLineNumber() +

". " + line); //(3)

}

} catch (IOException ioException) {

ioException.printStackTrace();

}

}

}

Save the file as ‘LineNumberDemo.java’

Note 1: A file reader is used to read lines from a java source file.(marked as step (1) Note 2 A filter class LineNumberReader is used to wrap the FileReader object, which helps to read the lines as well as line numbers form the connected file. (marked as step(2) Note 3 : The getLineNumber() method is used which returns the current line number. (marked as steps (3))

Step 4: Compile the program. Step 5: Run your program using the command line: java LineNumberDemo

Page 77: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 75

© Infosys Technologies Limited

The lines of the java source file DataIOApp.java are printed prefixedby the numbers as follows: 1. /* This Java file contains a class which writes primitive types 2. * to a file and read these types from the same file 3. * to a file and read bytes from the same 4. * file. 5. */ 6. 7. 8. /** 9. * Created on Mar 29, 2005 10. * @author: E & R Dept., Infosys Technologies Ltd. 11. * @version 1.0 12. * class DataIOApp 13. * Description : class DataIOApp has the starter method main 14. * This class shows you how to use the java.io DataInputStream 15. * and DataOutputStream classes.It reads and writes tabular data. 16. * The tabular data is formatted in columns, where each column is 17. * separated from the next by tabs. 18. * The columns contain the Employee age,name and employee number. 19. */ 20. 21. import java.io.*; 22. 23. class DataIOApp 24. { 25. 26. 27. /** 28. * Method main, starting point of the application 29. * @param String args[] to take in command line arguments 30. * creates objects of DataInputStream, DataOutputStream 31. * FileInputStream and FileOutputStream 32. * invokes methods of these objects 33. */ 34. public static void main(String[] args) 35. { 36. 37. // writing part 38. try 39. { 40. 41. // creates filter sream that wraps around file stream 42. DataOutputStream dataOutputStream = new 43. DataOutputStream(new FileOutputStream 44. ("Trainee.txt")); //(1) 45. 46. // formatted data to be stored in the file

Page 78: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 76

© Infosys Technologies Limited

47. double[] dAge = {29.53, 39.74,35.35, 28.99, 34.99}; 48. int[] iEmpno = { 12, 8, 13, 29, 50 }; 49. String[] sName = { "Narendran", "Sanjay", 50. "Maheendranath", "Ram Gopal","Sukesh" }; 51. 52. // writing to the file using filter stream 53. for(int Count=0;Count<dAge.length;Count ++) //(2) 54. { 55. dataOutputStream.writeDouble(dAge[iCount]); 56. dataOutputStream.writeChar('\t'); 57. dataOutputStream.writeInt(iEmpno[iCount]); 58. dataOutputStream.writeChar('\t'); 59. dataOutputStream.writeChars(sName[iCount]); 60. dataOutputStream.writeChar('\n'); 61. } 62. dataOutputStream.close(); 63. } 64. catch (IOException e) 65. { 66. System.out.println("DataIOApp: " + e); 67. } 68. 69. // reading part 70. try 71. { 72. 73. // creates filter stream to read from file 74. DataInputStream dataInputStream = new 75. DataInputStream(new 76. FileInputStream("Trainee.txt")); //(3) 77. 78. double dAge; 79. int iEmpno; 80. String sName; 81. double total = 0.0; 82. 83. try 84. { 85. while (true) 86. { 87. 88. // reading from the file 89. dAge=dataInputStream.readDouble(); //(4) 90. dataInputStream.readChar();//throws out tab 91. iEmpno = dataInputStream.readInt(); 92. dataInputStream.readChar();// throws out tab 93. sName = dataInputStream.readLine(); 94. System.out.println("You've Retrieved Name :

Page 79: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 77

© Infosys Technologies Limited

95. " + sName + " Age : " + 96. dAge + " Empno : " + iEmpno); 97. 98. } 99. } 100. catch (EOFException e) 101. { 102. } 103. 104. dataInputStream.close(); 105. } 106. catch (FileNotFoundException e) 107. { 108. System.out.println("DataIOApp: " + e); 109. } 110. catch (IOException e) 111. { 112. System.out.println("DataIOApp: " + e); 113. } 114. } 115. } Summary of this exercise: You have just learnt

• The steps required to define a reader for reading lines and line numbers from a file

• How to get the line number of current line from the file

Assignment 39: Buffered Reader

Objective: We will see the following program which uses BufferedReaderStream and its readLine() method to count the number of white space characters in the input. Step 1: Create a folder Assignment39 under your work directory (C:\work\Java) Step 2: Set the basic environment variables required for working with Java Step 3: Open a text editor (In Windows, notepad.exe and in case of UNIX, vi) and type the following. Filename DemoForBufferedReader

/* This Java file contains a class which uses BufferedReader and

* System.in to count the number of white space characters in the

* input.

Page 80: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 78

© Infosys Technologies Limited

*/

/**

* This class uses BufferedReaderStream and its readLine()method

* to count the number of white space haracters in the input.

* Date: 12-Jan-2005

* @author E&R Dept, Infosys Technologies Limited

* @version 1.0

*/

import java.io.*;

class DemoForBufferedReader

{

/**

* Starting point of the application.

* creates object of filter BufferedReader and also invokes

* methods of this object.

* @param args Command line arguments

*/

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

System.out.println("Enter the String to check");

/* Creates a filter for buffered reading from standard

input device */

BufferedReader bufferedReader = new BufferedReader(new

InputStreamReader(System.in)); //(1)

//Reads from the standard input using the filter

String str= bufferedReader.readLine(); //(2)

System.out.println(str);

int Count=0,Temploc;

//Counts the number of white spaces using a loop

for(int loopCount=1;

loopCount<str.length();loopCount++){

Temploc=str.charAt(loopCount); //(3)

If (Temploc == 32){

Count++;

}

}

Page 81: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 79

© Infosys Technologies Limited

System.out.println("No. of white space charachters

="+Count);

}

}

Save the file as ‘DemoForBufferedReader.java’

Note 1: A BuffredReader is created that wraps around an InputStreamReader with a default buffer size. It reads text from a character –input stream, buffering characters so as to provide for efficient reading of characters and lines.(marked as steps (1) Note 2 The readLine() reads a line of text and returns the contents of the line without including any line-termination characters, or null if the end of the stream has been reached. (marked as step (2)) Note 3 : The number of white space characters are counted using a loop form the text returned by readLine() method. (marked as step(3))

Step 4: Compile and run the program. The output of the program will give the number of white space characters in the input text form the keyboard. Summary of this exercise: You have just learnt

• The steps required to define streams for character IO and buffering

• How to read a line of text from keyboard

Assignment 40: PushBack InputStream

Objective : To change the first character of the input stream from one case to another using pushback filter. Problem Description : Store the text “This is Java Input/Output” into a bytearray using ByteArrayOutputStream. Using PushbackInputStream change the first character of the input stream from an uppercase ‘T’ to a lowercase ‘t’. PushbackInputStream should read the first character of the input stream and display it. It should then push back a ‘t’ onto the stream.

Page 82: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 80

© Infosys Technologies Limited

Assignment 41: Object Serialization and Deserialization

Objective: We will see how to store the state of objects to a persistent storage area(file) and restore these objects using deserialization. Step 1: Create a folder Assignment41 under your work directory (C:\work\Java) Step 2: Set the basic environment variables required for working with Java Step 3: Open a text editor (In Windows, notepad.exe and in case of UNIX, vi) and type the following files. Filename Employee.java

/* This Java file contains a class Employee and

* implements serializable interface

* for storing and retrieving Employee type objects.

*/

/**

* This class creates employee object and returns the members

* using toString() method.

* Date: 12-Jan-2005

* @author E&R Dept, Infosys Technologies Limited

* @version 1.0

*/

class Employee implements Serializable //(5)

{

String Name;

int empNo;

double Salary;

/**

* Constructor. Sets he employee object members with the

* parameters passed

*/

public Employee(String Name,int empNo, double Salary)

{

this.Name = Name;

this.empNo = empNo;

this.Salary = Salary;

}

/**

Page 83: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 81

© Infosys Technologies Limited

* Returns the members of Employee class

*/

public String toString()

{

return "Name= " + Name + ";Empno= "+ empNo + ";

Salary= "+Salary;

}

}

Save the file as ‘Employee.java’ Filename SerializationDemo.java

/* This Java file contains uses serialization and deserialization

* techniques for storing and retrieving Employee type objects.

*/

/**

* This class stores the state of objects to a persistent

* storage area(file) and restore these objects using

* deserialization.

* Date: 12-Jan-2005

* @author E&R Dept, Infosys Technologies Limited

* @version 1.0

*/

import java.io.*;

public class SerializationDemo{

/**

* Starting point of the application.

* creates objects of FileOutputStream, FileOutputStream,

* ObjectOutputStream and ObjectInputStream and also

* invokes methods of these objects

* @param args Command line arguments

*/

public static void main(String args[]) {

try {

//create an instance of Employee class

Employee emp1 = new Employee("gopal",1000,8888);

//Stream for writing to the file

FileOutputStream fileOutputStream = new

Page 84: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 82

© Infosys Technologies Limited

FileOutputStream("Employee.dat"); //(1)

/* Create filter object for saving the state of

the object */

ObjectOutputStream objectOutputStream = new

ObjectOutputStream(fileOutputStream); //(2)

/* Serialization: Saving the current state of the

object to the file */

objectOutputStream.writeObject(emp1); //(3)

System.out.print("The employee details are

successfully");

System.out.println("written to file Employee.dat");

objectOutputStream.flush();

objectOutputStream.close();

}

catch(Exception exception){

System.out.println("Exception occured during

serialization : " + exception);

System.exit(0);

}

try {

Employee emp2;

//Create file stream for reading from the file

FileInputStream fileInputStream = new

FileInputStream("Employee.dat"); //(4)

//Filter Stream for object deserialization

ObjectInputStream objectInputStream = new

ObjectInputStream(fileInputStream); //(5)

//Deserializing the object

emp2 =(Employee)objectInputStream.readObject(); //(6)

System.out.println("Details : " + emp2);

objectInputStream.close();

}

catch(Exception exception){

System.out.println("Exception occured during reading

: " + exception);

System.exit(0);

Page 85: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 83

© Infosys Technologies Limited

}

}

}

Save the file as ‘DemoForSerialization.java’

Note 1: A FileOutputStream is created that refers to a file named “Employee.dat” and an ObjectOutputStream is created for that file stream. (marked as steps (1) and (2)) Note 2 The writeObject() method of ObjectOutputStream is used to serialize the Employee object. This will write the object state to the file. (marked as step (3)) Note 3 : A FileInputstream is created that refers to the file named “Employee.dat” and an ObjectInputStream is created for that file stream. (marked as step(4) and (5)) Note 4 : The readObject method of ObjectInputStream is used to deserialize the object form the file. (marked as step(6))

Step 4: Compile and run the program. The output of the program will be as follows : The employee details are successfully written to file Employee.dat Name= gopal ; Empno= 1000 ; Salary= 8888 Step 5: Open the Employee.dat file form prompt and try to read the contents. You cannot !!! Because serialization stores the state of the objects in the binary format. By deserialization it is possible to restore the human readable format of the object states, this is done with the help of ObjectInputStream in the program. Step 6: Modify Employee class without implementing serialization. Compile the program again. There is a compilation error !! Step 7: What is the reason ?

Page 86: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 84

© Infosys Technologies Limited

Only an object that implements the Serialization interface can be saved and restored by the serialization facilities. Step 8: Modify the iEmpNo instance variable of employee class to be transient. Compile and run the program. Step 9: What is the difference ? The data is not saved during serialization. Why ? Variables that are declared as transient and static are not saved during serialization. Summary of this exercise: You have just learnt

• The steps required to define streams for serialization and deserialization.

• How to serialize an object to a file.

• How to deserialize an object form a file.

• Transient and static variables are not saved during serialization.

Page 87: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 85

© Infosys Technologies Limited

6 Assignments for Day 5 of Java Programming All the assignments in this section must be completed on Day 5 of your Java Programming course.

Assignment 42: Creating a GUI

Objective: We will see how to work with the java.awt package and build up a GUI step by step. Problem Description: Create a billing application where the GUI is as follows:

Step 1: Create a folder Assignment42 under your work directory (C:\work\Java) Step 2: Check the basic environment variables required for working with Java by running the script created in Assignment3 is set. Step 3: Open a text editor (In Windows, notepad.exe and in case of UNIX, vi) and type the following. Filename GUIDemo.java

/* This file depicts the building of GUI using

* the java.awt package

*/

/**

* This class helps to build a frame with labels, text

* components and buttons

* Date: 02-Feb-2005

* @author E&R Dept, Infosys Technologies Limited

* @version 1.0

*/

Page 88: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 86

© Infosys Technologies Limited

import java.awt.*; //(1)

class GUIDemo extends Frame { //(2)

Label label1;

Label label2;

Label label3;

Label label4;

TextField textBillAmount;

TextField textDiscountedAmount;

/**

* Constructor.Invokes base class constructor and creates

* labels and textfields and adds them to the frame

*/

GUIDemo(){

super("Bill Application");

setSize(300,100); //(3)

//Code to be added here

label1 = new Label("Bill Amount"); //(4)

textBillAmount = new TextField(50);

label2 = new Label("Discount");

label3 = new Label("10%");

label4 = new Label("Discounted Price");

textDiscountedAmount = new TextField(10);

add(label1); //(5)

add(textBillAmount);

add(label2);

add(label3);

add(label4);

add(textDiscountedAmount);

setVisible(true); //(6)

}

Page 89: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 87

© Infosys Technologies Limited

/**

* Creates an object of the class GUIDemo

* @param args Command line arguments

*/

public static void main(String args[])

{

new GUIDemo();

}

}

Save the file as ‘GUIDemo.java’

Note: The important steps in building a frame and adding controls to it:

1. import the java.awt package (marked Step (1)) 2. If you want to build a frame your class needs to extend the

in-built class Frame (marked Step (2)). Look into Java documentation for the Frame class. It acts like a container on which other controls could be added.

3. Set a size for the frame. This needs some amount of trial error, you need to see the output and then modify the size if required (marked Step (3))

4. Create objects of the controls that are to be placed on the screen (marked Step (4))

5. Add the controls onto the frame which is the container in this case (marked Step (5))

6. Use the setVisible(true) to make the frame visible. Remember nothing comes up on the screen when you run the program if you have missed this step (marked Step (6))

Step 4: Compile and run the program. The output is not how you wanted it to be. You had added a total of 4 controls onto the frame (3 labels and 1 text field) but you only find the last added control being displayed. Why is it so? Try to analyze the result before going to the next step. Step 5: The output you got is because you did not set a layout for your frame. Remember by default a frame has border layout and by default it chooses the center. So the controls got added one after another in center alignment and only the last control could be visible. So, now you need to add a layout to the frame. Seeing the desired output try to predict the layout we should choose. Step 6: The GUI can be split into 2 rows and 2 colums, so we can choose a Grid layout for the frame. Also, note if a background is to be given for the frame how to do it. Modify the code above by adding the lines given below:

Page 90: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 88

© Infosys Technologies Limited

setBackground(Color.cyan); setLayout(new GridLayout(2,2)); The lines are to be added where it is marked //code to be added here. Step8: Now recompile the code and run the code again and see the output. It should match the desired GUI. Step 9: Now the GUI is to be extended further by adding 3 buttons. The required design is as shown below:

Note: The frame has the top and bottom portions having a different layout of arranging components and also the background color is different. So, the code above has to be modified to incorporate these changes.

Step 10: The source code has to be modified as follows:

import java.awt.*;

class GUIDemo extends Frame implements ActionListener {

Panel panel1;

Panel panel2;

Label label1;

Label label2;

Label label3;

Label label4;

TextField textBillAmount;

TextField textDiscountedAmount;

Button buttonCalculate;

Button buttonReset;

Button buttonExit;

Page 91: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 89

© Infosys Technologies Limited

GUIDemo(){

super("Bill Application");

setSize(300,200); //(1)

panel1=new Panel(); //(2)

panel1.setLayout(new GridLayout(2,2));

panel1.setBackground(Color.cyan);

label1 = new Label("Bill Amount");

textBillAmount = new TextField("Manasi");

label2 = new Label("Discount");

label3 = new Label("10%");

label4 = new Label("Discounted Price");

textDiscountedAmount = new TextField(10);

panel1.add(label1);

panel1.add(textBillAmount);

panel1.add(label2);

panel1.add(label3);

panel2=new Panel(); //(3)

panel2.setBackground(Color.pink);

buttonCalculate = new Button("Calculate");

buttonReset = new Button("Reset");

buttonExit = new Button("Exit");

panel2.add(buttonCalculate);

panel2.add(buttonReset);

panel2.add(buttonExit);

add(panel1); //(4)

add(panel2,BorderLayout.SOUTH);

setVisible(true);

}

public static void main(String args[]){

new GUIDemo();

}

}

Page 92: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 90

© Infosys Technologies Limited

Note: The important steps are: 1. The controls cannot be added directly to the frame as the

layout is different on the top and bottom portions of it. So, a combination of frame and panel has to be chosen.

2. So, a frame is created, its size specified (marked as step(1)) 3. panel1 follows the grid layout as designed before (marked as

step(2)) 4. Similarly panel2 is built as a container for the buttons having

its own background color. No specific layout has been chosen as the buttons could be arranged as per flow layout which is the default for a panel (marked as step(3))

5. Once the panels are ready, they are finally added to the frame. Remember a frame has border layout by default, so the panel1 is added to the center of the frame. Panel2 is added to the south of the frame using BorderLayout.SOUTH (marked as step(4))

Step 11: Recompile the code and run it. See the GUI output. Summary of this exercise: You have just learnt

• How to work with the java.awt package

• How to choose the containers (frame/panel), choose the components and then place the components on the container following a layout

• How to determine the size of the container and make things visible

Assignment 43: Event Handling

Objective: We will see how to work with the java.awt.event package and provide functionality to the GUI that was built in Assignment42. Problem Description: The buttons shown in the GUI built in Assignment42 should be provided with the following functionality:

1) The textbox beside Discounted price is non-editable ie. The user cannot enter data into it. On clicking on the ‘Calculate’ button, 10% discount will be calculated on the bill amount entered by the user in the text-box and the discounted price will be displayed in the second text-box.

2) On clicking the ‘Reset’ button, the text in the text-box should be cleared. 3) On clicking on the ‘Exit’ button, the application should close.

Step 1: Create a folder Assignment43 under your work directory (C:\work\Java)

Page 93: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 91

© Infosys Technologies Limited

Step 2: Check the basic environment variables required for working with Java by running the script created in Assignment3 is set. Step 3: Open a text editor (In Windows, notepad.exe and in case of UNIX, vi) and type the following.

/* This java file demonstrates event handling

*/

import java.awt.*;

import java.awt.event.*; //(1)

/**

* This class creates GUI components and adds to the frame. This

* class also handles Action event.

* Date: 02-Feb-2005

* @author E&R Dept, Infosys Technologies Limited

* @version 1.0

*/

class GUIDemo extends Frame implements ActionListener { //(2)

Panel panel1;

Panel panel2;

Label label1;

Label label2;

Label label3;

Label label4;

TextField textBillAmount;

TextField textDiscountedAmount;

Button buttonCalculate;

Button buttonReset;

Button buttonExit;

/**

* Constructor. Creates GUI components and adds it to the

* frame

*/

GUIDemo(){

//Create a frame and set the size of the frame

Page 94: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 92

© Infosys Technologies Limited

super("Bill Application");

setSize(300,200);

//Create a panel

panel1=new Panel();

//Specify no of rows and columns

panel1.setLayout(new GridLayout(3,2));

panel1.setBackground(Color.cyan);

//Create labels for displaying the message

label1 = new Label("Bill Amount");

label2 = new Label("Discount");

label3 = new Label("10%");

label4 = new Label("Discounted Price");

//Create the ext fields

textBillAmount = new TextField(10);

textDiscountedAmount = new TextField(10);

textDiscountedAmount.setEditable(false); //(3)

//Add the labels and textfileds to the panel

panel1.add(label1);

panel1.add(textBillAmount);

panel1.add(label2);

panel1.add(label3);

panel1.add(label4);

panel1.add(textDiscountedAmount);

//Create another panel and set its background color

panel2=new Panel();

panel2.setBackground(Color.pink);

//Create buttons and the listener to handle events

buttonCalculate = new Button("Calculate");

buttonReset = new Button("Reset");

buttonExit = new Button("Exit");

buttonCalculate.addActionListener(this); //(4)

buttonReset.addActionListener(this);

buttonExit.addActionListener(this);

//Add the buttons to the panel

panel2.add(buttonCalculate);

Page 95: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 93

© Infosys Technologies Limited

panel2.add(buttonReset);

panel2.add(buttonExit);

//Add the panel to the frame

add(panel1);

add(panel2,BorderLayout.SOUTH);

setVisible(true);

}

/**

* This method handles the events that could be generated

* by the buttons. It uses getSource() method to know which

* button had generated the event.

*/

public void actionPerformed(ActionEvent actionevent){

//(5)

if (actionevent.getSource() == buttonCalculate){

//(6)

float var1 = Float.parseFloat

(textBillAmount.getText())*(0.90F);

textDiscountedAmount.setText

(String.valueOf(var1));

}

else if (actionevent.getSource() == buttonReset){

textBillAmount.setText("");

textDiscountedAmount.setText("");

}

else if (actionevent.getSource() == buttonExit){

System.exit(0); //(7)

}

}

/**

* Starting point of the application. Creates an object of

* GUIDemo class

*/

Page 96: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 94

© Infosys Technologies Limited

public static void main(String args[])

{

new GUIDemo();

}

}

Note: The important steps in implementing event handling are: 1. java.awt.event package is to be imported (marked in step (1)) 2. The class which will handle the event needs to implement the

required Listener interface. The Listener interface to be implemented depends on which type of event to be handled. Since we are dealing with buttons that give rise to Action Event, we are implementing ActionListener interface (marked in step (2))

3. The Listener has to ba attached with the component for which it will listen by the method addXXXListener()(marked in step (4))

4. Since the class is implementing ActionListener interface it needs to provide functionality to actionPerformed() method declared in the interface. The code written in this method decides how the event will be handled (marked in step (5))

5. There are 3 buttons on the GUI and click on each button is to be handled in a separate manner. So we need to know from which button the event was generated. The getSource() method helps in this (marked in step (5))

Step 4: Compile and run the program. Enter data in the textbox and test the output by clicking on the various buttons. Summary of this exercise: You have just learnt

• How to work with the java.awt.event package

• How to implement the right Listener interface and provide functionality to the required method

Assignment 44: Login Validation

Problem Description: Create a login screen which has the GUI as follows:

Page 97: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 95

© Infosys Technologies Limited

The password field should display the entry as “*******” as shown. The screen should be getting closed using the ‘X’ symbol on the window. On clicking the Login button, the following validations should be made:

1) No field can be left empty 2) The Email ID field must contain a @ symbol 3) The Email ID field cannot be starting or ending with an @

If any of the validations fails, an error message should be displayed to the user in the form of a dialog-box clearly stating which of the following condition(s) has been violated. Hint: Refer to the String class in Javadoc for Email validation

Assignment 45: Applet Creation

Objective: We will see how to code for an applet and the process to pass parameters to an applet. Step 1: Create a folder Assignment45 under your work directory (C:\work\Java) Step 2: Check the basic environment variables required for working with Java by running the script created in Assignment3 is set. Step 3: Open a text editor (In Windows, notepad.exe and in case of UNIX, vi) and type the following. Filename ParameterApplet.java

/* This file is a demo Java applet

* which depicts how to pass parameters into an applet and

Page 98: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 96

© Infosys Technologies Limited

* how an applet is run

*/

import java.awt.*; //(1)

import java.applet.*; //(2)

/**

* This class is an applet which takes in two

* parameters namely font name and font size and displays a

* message accordingly

* Date: 02-Feb-2005

* @author E&R Dept, Infosys Technologies Limited

* @version 1.0

*/

public class ParameterApplet extends Applet{

String fontName ;

int fontSize;

/**

* This is first method that gets invoked when an applet

* starts its execution

*/

public void init(){

if (getParameter("fontName") == null) { //(3)

showStatus("Font not specified");

fontName = "Ariel";

}

else {

fontName = getParameter("fontName");

}

if (getParameter("fontSize") == null){

showStatus("size not specified");

fontSize = 20;

}

else {

Page 99: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 97

© Infosys Technologies Limited

fontSize =

Integer.parseInt

(getParameter("fontSize")); //(4)

}

setFont(new Font(fontName,Font.PLAIN,fontSize));

}

/**

* This is the method used to display a message or draw a

* GUI component on the applet

*/

public void paint(Graphics g){

g.drawString("This is the font",20,20);

}

}

Save the file as ‘ParameterApplet.java’

Note: The important steps in building an applet: 1) Classes from java.awt and java.applet package to be imported

(marked as steps (1) and (2)) 2) When a parameter is being passed to an applet, to retrieve the

parameter use the method getParameter(“name of the param”) (marked as step(3))

3) Also, note that parameters passed into the applet come as String values, they need to be converted into their respective numeric values wherever required (marked as step(4))

Step 4: Compile the program. Step 5: From here things change. Running an applet code is different from how an application is run. An applet is embedded inside a html document. So, now we will create a html file in which we will use the .class file generated in Step4. Open a text editor (In Windows, notepad.exe and in case of UNIX, vi) and type the following. <html> <applet code="ParameterApplet" width=500 height=500> <param name=fontName value="Comic Sans MS"> <param name=fontsize value=26> </applet> </html> Save the file as ‘ParameterApplet.html’.

Page 100: La g la10_javaprogramming

Java Programming Lab Guide Version 1.0

Education & Research Department Page 98

© Infosys Technologies Limited

Note 1: Name of the .html file could be anything, not necessarily matching with the .class file Note 2: code, width and height are the minimum parameters required for the applet tag. The code value contains the name of the .class file of the java applet. Note 3: param tag contains the parameters to be passed into the applet in the form as name value pair.

Now open the ParameterApplet.html file in your browser and see the output. You will find that the writing comes in the font specified as parameters. Step6: To build a html file that uses the .class file is how an applet is used for all practical purposes. However there is a tool called appletviewer which can be used to test the applet code without building the .html file. Remember, this is only for the purpose for testing your applet. To use the appletviewer tool add the following code to the beginning of the ParameterApplet.java file:

/*

<applet code="ParameterApplet" width=200 height=200>

<param name=fontName value="Comic Sans MS">

<param name=fontsize value=26>

</applet>

*/

Note: The code is commented, that’s how it should be. It is not for the java compiler to read but for the appletviewer tool which works like a minimal browser to parse this code. Recompile the code and test the applet using the command line:

Run the program by giving: appletviewer ParameterApplet.java

The output should come up. Step 7: In the previous step, the .html file and the .class file were saved in the same location. Now save the .class file in some other path (not in the same directory as the .class file) and add the attribute codebase to the applet tag and see how it works. Summary of this exercise: You have just learnt

• The steps required to write an applet code

• How to pass parameters to an applet

• How to build a .html file and use the .class file of the applet in it