75
Lab Manual-Software Development Tools Laboratory [Third year IT] +Assignment No: 1 Aim: Introduce Java as strong object oriented language and explain its features. Problem Statement: Write a simple program in java, compile & execute it. Pre Lab: Knowledge of programming in C . Knowledge of object oriented concepts of C++. Theory: 1.1 Introduction to Java: Java was developed by five inventors from Sun Microsystems of USA in 1991.These inventors are James Gosling, Patrick Naughton, Chris Warth, Ed Frank & Mike Sheridan. This language was initially called “OAK” (name of tree) but was renamed “Java” in 1995.Java is simple & powerful language. It is an object oriented language. Also it is platform independent language, because it can run under any O.S. Such as Linux, win98, win 2000, win XP etc. 1.2 Features of Java 1) Simple: In java no need of header files, pointer arithmetic, operator overloading, virtual base class. 2) Object Oriented: Java is object oriented language, but dose not support multiple inheritance. 3) Distributed & Dynamic: Java allows to create application on n/w hence it is distributed, also capacity to dynamically linking in new class libraries, methods & object. Department of Information technology, BSIOTR PUNE. 1

Lab Mannual of SDTL

Embed Size (px)

Citation preview

Page 1: Lab Mannual of SDTL

Lab Manual-Software Development Tools Laboratory [Third year IT]

+Assignment No: 1

Aim: Introduce Java as strong object oriented language and explain its features.

Problem Statement: Write a simple program in java, compile & execute it.

Pre Lab: Knowledge of programming in C . Knowledge of object oriented concepts of C++.

Theory:

1.1 Introduction to Java:

Java was developed by five inventors from Sun Microsystems of USA in 1991.These inventors are James Gosling, Patrick Naughton, Chris Warth, Ed Frank & Mike Sheridan.

This language was initially called “OAK” (name of tree) but was renamed “Java” in 1995.Java is simple & powerful language. It is an object oriented language. Also it is platform independent language, because it can run under any O.S. Such as Linux, win98, win 2000, win XP etc.

1.2 Features of Java

1) Simple: In java no need of header files, pointer arithmetic, operator overloading, virtual base class.

2) Object Oriented: Java is object oriented language, but dose not support multiple inheritance. 3) Distributed & Dynamic: Java allows to create application on n/w hence it is distributed, also capacity to dynamically linking in new class libraries, methods & object. 4) Robust: Java dose not allow pointer & concept of reference variable. 5) Secure: Java security has 3 primary components 1 class loader

2 byte code verifier 3 security manager 6) Portable: Platform independent 7) Architectural natural: Java generate byte code which can be executed by any processor. 8) Interpreted: Java interpreter can execute java byte code directly on any m/c. Interpreter use byte code hence interpreter is faster 9) Multithreading: Java handles multiple tasks simultaneously. 10) High performance: Java gives high performance due to use of intermediate Byte Code.

Department of Information technology, BSIOTR PUNE.1

Page 2: Lab Mannual of SDTL

Lab Manual-Software Development Tools Laboratory [Third year IT]

1.3 Compile Time & Runtime Environment of Java : Compile Time Env. Runtime Env. (java platform)

Fig1.a : source code is compiled to get byte codes which are executed at runtime.

1.4 A first simple program:Let’s start by compiling & running the short simple program shown here/* This is a simple java program.Call this file “Example.java ”.*/class Example { //your program begins with a call to main(). public static void main(String args[ ]) {

Department of Information technology, BSIOTR PUNE.2

Java source file(.java file)

Java “c” compiler

java byte codes(.class file)

Java byte codes move locally or through n/w

Class loader byte code verifier

Java class libraries

(JVM)

Java interpreter

Just in time compiler

Run time system

Operating system

Hardware

Page 3: Lab Mannual of SDTL

Lab Manual-Software Development Tools Laboratory [Third year IT]

System.out.println(“This is a simple java program.”); } }

Compiling the java program:To compile the program use following command.C:>javac Example.java where javac is a compiler

To run the program, you must use the java interpreter, called java.C:>java Example

When the program is run, the following o/p is displayed:This is a simple java program.

1.5 Data types in JAVA

Java Basics:   Data Types

Java is what is known as a strongly typed language. That means that Java is a language that will only accept specific values within specific variables or parameters. Some languages, such as JavaScript, are weakly typed languages. This means that you can readily store whatever you want into a variable. Here is an example of the difference between strongly typed and weakly typed languages:

JavaScript (weakly typed) 1: var x; // Declare a variable 2: x = 1; // Legal 3: x = "Test"; // Legal 4: x = true; // LegalJava (strongly typed) 1: int x; // Declare a variable of type int 2: x = 1; // Legal 3: x = "Test"; // Compiler Error 4: x = true; // Compiler Error

In a weakly typed language, such as JavaScript, you simply declare a variable without assigning it a type. In a strongly typed language, such as Java, you must give a variable a type when you declare it. Once you've declared a variable to be that type, it will remain of that type indefinitely and will only accept values that are within that types range. You should note that this is one of the many differences between Java and JavaScript. Despite their names, they have very little to do with one another.

Department of Information technology, BSIOTR PUNE.3

Page 4: Lab Mannual of SDTL

Lab Manual-Software Development Tools Laboratory [Third year IT]

Now that we know that Java is a strongly typed language, you can probably see how important it is to know what data types there are in Java. There are 9 data types in Java, 8 primitive types and a reference type. First, let's look at primitive types and then we'll move along to reference types.

Primitive Types

Type Name

Description Size RangeSample

Declaration & Initialization

Boolean true or false 1 bit {true, false}boolean myBool = true;

CharUnicode Character

2 bytes

\u0000 to \uFFFF char myChar = 'a';

Byte Signed Integer 1 byte -128 to 127 int myInt = 100;

Short Signed Integer2 bytes

-32768 to 32767short myShort = 1000;

Int Signed Integer4 bytes

-2147483648 to 2147483647 int myInt = 100000;

Long Signed Integer8 bytes

-9223372036854775808 to 9223372036854775807

long myLong = 0;

FloatIEEE 754 floating point

4 bytes

±1.4E-45 to ±3.4028235E+38float myFloat = 10.0f;

DoubleIEEE 754 floating point

8 bytes

±4.9E-324 to ±1.7976931348623157E+308

double myDouble = 20.0;

1.6 Variables:

Variable declaration:

Now, where do these variables come from? Actually, you create them by declaring them in you code. Variable declarations can be at the beginning of a class (before the methods) or inside of a method. This will make more sense later when you learn about scope (mouthwash?). Declaring a variable is very simple, here is a variable declaration.

int MyVariable;

Variables can also be set to a value in the same statement as the declaration.

int MyVariable=5

You can even declare multiple variables in the same statement.

Department of Information technology, BSIOTR PUNE.4

Page 5: Lab Mannual of SDTL

Lab Manual-Software Development Tools Laboratory [Third year IT]

int MyVariable, MySecondVariable, MyThirdVariable;

1.7 Array data types:

Array declarations:

Arrays are Java objects All Java arrays are technically one-dimensional. Two-dimensional arrays are

arrays of arrays. Declaring an array does not create an array object or allocate space in memory;

it creates a variable with a reference to an array Array variable declarations must indicate a dimension by using []

Examples of valid array declarations:

String[]s; String []s;

String [] s; String [ ] s; // extra white space ignored

String[] s; String[ ] s; // extra white space ignored

String s[]; String s []; String s [ ]; // extra white space ignored

String[] s[]; String[][]s; String s [] [ ]; // extra white space ignored declaring the size of the array with the following notation is illegal

String[5] s; // illegal declaration the standard convention for declaring arrays is:

String[] s; // one-dimensional array String[][] s; // two-dimensional array

Initializing arrays

All arrays are zero-based Arrays must be indexed by int values or byte, short or char values (as these can

be promoted to int) Using a long index value to access an array causes a compile error

Department of Information technology, BSIOTR PUNE.5

Page 6: Lab Mannual of SDTL

Lab Manual-Software Development Tools Laboratory [Third year IT]

Attempting to access an array with an index less than 0 or greater than the length of the array causes an ArrayIndexOutOfBoundsException to be thrown at runtime

Since arrays are objects they can be initialized using the new operator . When created, arrays are automatically initialized with the default value of their

type.

String[] s = new String[100]; // default values: null boolean[] b = new boolean[4]; // default values: false int[][] i = new int[10][10]; // default values: 0

Array references declared as members are initialized to null BUT array references declared in methods are not initialized

Class TestArray{ int[] arr; // member declaration, initialized to 'null' public static void main(String[] args) { int[] arr1; // reference variable 'arr1' not initialized // compiles ok System.out.println("arr:" + new TestArray().arr); System.out.println("arr1: " + arr1); // compile error }}

As arrays are allocated at runtime, you can use a variable to set their dimension.

int arrSize = 100; String[] myArray = new String[arrSize];

You can use curly braces {} as part of an array declaration to initialize the array

String[] oneDimArray = { "abc","def","xyz" };Note Curly braces {} can only be used in array declaration statements.

String[] s; s = { "abc", "def", "hij"}; // illegal initialization int[] arr = new int[] {1,2,3}; // legal

You can assign an array a null value but you can't create an empty array by using a blank index

int[] array = null; // legal

int[] array = new int[]; // illegal initialization

Department of Information technology, BSIOTR PUNE.6

Page 7: Lab Mannual of SDTL

Lab Manual-Software Development Tools Laboratory [Third year IT]

Initializing two-dimensional arrays

The first dimension represents the rows, the second dimension, the columns . Curly braces {} may also be used to initialize two dimensional arrays. Again

they are only valid in array declaration statements.

int[][] twoDimArray = { {1,2,3}, {4,5,6}, {7,8,9} }; You can initialize the row dimension without initializing the columns but not

vice versa.

int[][] myArray = new int[5][]; int[][] myArray = new int[][5]; // illegal

The length of the columns can vary

Post-Lab: Hence from this assignment you can learn how to compile & execute simple java program from command prompt & using IDE.

References: The Complete reference JAVA2 by Herbert Schildt.

Viva Questions:

1) Who was developed “JAVA” Language?2) What is mean by platform neutral (or platform Independent) language?3) Why we would use JAVA Language?4) What are the Features of JAVA?5) Why java is secure language? 6) Why interpreter is faster in Java?7) What is the use of “static” k/w in public static void main (String args[]) function?8) Why we use String args[] as parameter of main method?9) How to declare array & allocate memory for array elements in Java? Give with

example?10) What is the difference between Java & C++?

Assignment No:2

Aim: Design and develop classes and create its objects in java.

Problem Statement: Write a program to construct a class Circle and creates its objects using overloaded constructors.

Pre Lab:

Department of Information technology, BSIOTR PUNE.7

Page 8: Lab Mannual of SDTL

Lab Manual-Software Development Tools Laboratory [Third year IT]

Knowledge of programming in C . Knowledge of object oriented concepts of C++.Theory:

2.1 Introducing Classes & Objects:

A Brief Introduction to Classes

Following is the code for a class called SimplePoint that represents a point in 2D space:

public class SimplePoint { public int x = 0; public int y = 0;} This segment of code declares a class-- a new data type really-- called SimplePoint. The SimplePoint class contains two integer member variables, x and y. The public keyword preceding the declaration for x and y means that any other class can freely access these two members.

You create an object from a class such as SimplePoint by instantiating the class. When you create a new SimplePoint object (we show you how shortly), space is allocated for the object and its members x and y. In addition, the x and y members inside the object are initialized to 0 because of the assignment statements in the declarations of these two

members. Fig2.1

Now, here's a class, SimpleRectangle ,That represents a rectangle in 2D space: public class SimpleRectangle { public int width = 0; public int height = 0; public SimplePoint origin = new SimplePoint();}

This segment of code declares a class (another data type)--SimpleRectangle-- that contains two integer members, width and height. SimpleRectangle also contains a third member, origin, whose data type is SimplePoint. Notice that the class name SimplePoint is used in a variable declaration as the variable's type. You can use the name of a class anywhere you can use the name of a primitive type.

As with SimplePoint, when you create a new SimpleRectangle object, space is allocated for the object and its members, and the members are initialized according to their

Department of Information technology, BSIOTR PUNE.8

Page 9: Lab Mannual of SDTL

Lab Manual-Software Development Tools Laboratory [Third year IT]

declarations. Interestingly, the initialization for the origin member creates a SimplePoint object with this code: new SimplePoint() as illustrated here:

Fig 2.2 This diagram shows the difference between primitive types and reference types. Both width and height are integers and are fully contained within SimpleRectangle. On the other hand, origin simply references a SimplePoint object somewhere else.

The SimplePoint and SimpleRectangle classes as shown are simplistic implementations for these classes. Both should provide a mechanism for initializing their members to values other than 0. Additionally, SimpleRectangle could provide a method for computing its area, and because SimpleRectangle creates a SimplePoint when it's created, the class should provide for the clean up of the SimplePoint when SimpleRectangle gets cleaned up. So, here's a new version of SimplePoint, called Point, that contains a constructor which you can use to initialize a new Point to a value other than (0,0):

public class Point { public int x = 0; public int y = 0;

// a constructor! public Point(int x, int y) {

this.x = x;this.y = y;

}}

Now, when you create a Point, you can provide initial values for it like this: new Point(44, 78) The values 44 and 78 are passed into the constructor and subsequently assigned to the x and y members of the new Point object as shown here:

Department of Information technology, BSIOTR PUNE.9

Page 10: Lab Mannual of SDTL

Lab Manual-Software Development Tools Laboratory [Third year IT]

Fig 2.3

2.2 Overloading Methods

In Java it is possible to define two or more methods within the same class that share the same name, as long as their parameter declarations are different. When this is the case, the methods are said to be overloaded, and the process is referred to as method overloading. Method overloading is one of the ways that Java implements polymorphism. If you have never used a language that allows the overloading of methods, then the concept may seem strange at first. But as you will see, method overloading is one of Java’s most exciting and useful features.

When an overloaded method is invoked, Java uses the type and/or number of arguments as its guide to determine which version of the overloaded method to actually call. Thus, overloaded methods must differ in the type and/or number of their parameters. While overloaded methods may have different return types, the return type alone is insufficient to distinguish two versions of a method. When Java encounters a call to an overloaded method, it simply executes the version of the method whose parameters match the arguments used in the call.

Here is a simple example that illustrates method overloading:

// Demonstrate method overloading.class OverloadDemo

{  void test() {    System.out.println("No parameters");  }  // Overload test for one integer parameter.  void test(int a) {    System.out.println("a: " + a);  }  // Overload test for two integer parameters.  void test(int a, int b) {    System.out.println("a and b: " + a + " " + b);  }

Department of Information technology, BSIOTR PUNE.10

Page 11: Lab Mannual of SDTL

Lab Manual-Software Development Tools Laboratory [Third year IT]

  // overload test for a double parameter  double test(double a) {    System.out.println("double a: " + a);    return a*a;  }}class Overload {  public static void main(String args[]) {    OverloadDemo ob = new OverloadDemo();    double result;    // call all versions of test()    ob.test();    ob.test(10);    ob.test(10, 20);    result = ob.test(123.25);    System.out.println("Result of ob.test(123.25): " + result);  }}

This program generates the following output:

No parametersa: 10a and b: 10 20double a: 123.25Result of ob.test(123.25): 15190.5625

As you can see, test( ) is overloaded four times. The first version takes no parameters, the second takes one integer parameter, the third takes two integer parameters, and the fourth takes one double parameter. The fact that the fourth version of test( ) also returns a value is of no consequence relative to overloading, since return types do not play a role in overload resolution. When an overloaded method is called, Java looks for a match between the arguments used to call the method and the method’s parameters.

2.3 Constructor:

Methods declared having the same name as that of class name, This type of declaration are called as constructor.

Once defined, the constructor is automatically called immediately after the object is created, before the new operator completes.

Constructors look a little strange because they have no return type, not even void.

2.4 “this” Keyword:

Department of Information technology, BSIOTR PUNE.11

Page 12: Lab Mannual of SDTL

Lab Manual-Software Development Tools Laboratory [Third year IT]

Sometimes a “method” will need to refer to the “object” that invoked it or call it. To allow this, java defines the “this” keyword.

“this” is always a reference to the object on which the method was invoked or called.

You can use “this” anywhere a reference to an object of the current class type is permitted.

2.5 Overloading Constructor:

In addition to overloading normal methods, you can also overload constructor methods. In overloading constructor, class name & method name both are same, only parameter passes are different. That type of overloading is called as overloading constructor.

Post-Lab: Hence from this assignment you can learn how to create class, define methods, object creation & constructor overloading.

References: The Complete reference JAVA2 by Herbert Schildt.

Viva Questions:11) What is mean by constructor? & How this constructor get call?12) What is the use of “this” keyword?13) In java how dynamically allocated memory for object is released or how such

objects are destroyed for later reallocation?14) What is the use of Garbage Collector in java?15) What is mean by Method Overloading?16) What is mean by Constructor Overloading?17) What is the default Data Type of all members of a class in Java?

Assignment No: 3

Department of Information technology, BSIOTR PUNE.12

Page 13: Lab Mannual of SDTL

Lab Manual-Software Development Tools Laboratory [Third year IT]

Aim: Inherit classes and its properties/behavior in derived one.

Problem Statement: Write a program to inherit a class “MangotTree” from “Tree” class its members using extends keyword.

Pre Lab: Knowledge of programming in C . Knowledge of object oriented concepts of C++.

Theory:

3.1 Inheritance: One of the strengths of object-oriented programming is inheritance. This feature allows you to create a new class that is based on an old class.

Def: super class having all methods & variables is accessed by its subclass are called “Inheritance”.

3.2 Types of Inheritance: There are five types of inheritance:

a) Single b)multilevel c)hierarchical d) hybrid e) Multiple inheritance.Note: Multiple inheritance is not possible in java

Keyword “extends” used to create a subclass of superclass.Syntax:class Math1 //superclass{}class math2 extends math1 //child class{}

3.3 Access specifiers in Inheritance: a) public: ‘public’ members of superclass is accessible to subclass. b) private: ‘private’ members of superclass is not accessible to subclass. c) protected: ‘protected’ members of superclass is accessible to subclass.

3.4 Inheritance using “super”: Private data members basically not accessible to subclass due to

encapsulation. Whenever a subclass needs to refer to its nearer superclass, it can do so by

use of the k/w “super” to access private data also. “super” has two general forms:

A) Using “super” to calls the “superclass constructor”.

Department of Information technology, BSIOTR PUNE.13

Page 14: Lab Mannual of SDTL

Lab Manual-Software Development Tools Laboratory [Third year IT]

A subclass can call a constructor method defined by its superclass by use of the following form of super.Syntax: Super(parameter-list);

B) The 2nd is used to access members of the superclass that has been hidden by a members of a subclass.

The 2nd form of super acts somewhat like this, except that it always refers to the superclass of the subclass in which it is used.

Syntax: Super.member Here, member can be either a method or an instance variable. This 2nd form of super is most applicable to situations in which ‘member names’ of a subclass hide members by the same name in the superclass.

3.5 Method overriding: If a method in subclass having same name & type as that method of superclass then it is called as ‘overridden’ of method of subclass, And that superclass method makes hidden by the subclass.

If you wish to access the superclass version of an overridden function. You can do so by using super.class Parent{ Void show() { }}class Child1 extends Parent {int k=6;void display(){ } void show() //overridden method { Super.show(); Syste.out.println(“k:”+k); }}

class overridesdemo{Public static void main(string args[]) { child1 obj=new child(); obj.show();

Department of Information technology, BSIOTR PUNE.14

Page 15: Lab Mannual of SDTL

Lab Manual-Software Development Tools Laboratory [Third year IT]

}}

3.6 Using final with inheritance:There are three uses of final keyword:

1) 1st it can be used to create the equivalent of a ‘named constant’ this use was described in previously

2) The other two uses of final apply to inheritance is as follows:A) Using final to prevent overriding: To disallow a method from being overridden, specify final as a modifier at the

start of its declaration. Methods declared as “final” cannot be overridden

Syntax:class Test{Final void show() { System.out.println(“this is the final method”); }}

Because of method declared as final in superclass Test, it cannot override in its child class. When you trying to do this then compile time error is occurred.

B) Using final prevent inheritance: Sometimes you will want to prevent a class from being inherited. To do this,

precede the class declaration with final. Declaring class as final implicitly declares all of its method as final.

Syntax:final class test{Int x;Void display(){ }}Class child extends test //this class is illegal.{}

Post lab: hence from this assignment you learn creation of Inheritance in java. Also use of super, final & abstract classes.

Department of Information technology, BSIOTR PUNE.15

Page 16: Lab Mannual of SDTL

Lab Manual-Software Development Tools Laboratory [Third year IT]

References: The Complete reference JAVA2 by Herbert Schildt.

Viva Questions:18) What is the use of “static” k/w in java?19) What are the restrictions when methods declared as static?20) At Which time static block get executed?21) How you call static methods from outside its class?22) How to declare constant in java?23) What is mean by nested classes?24) What is the scope of Nested(inner) class in their outer class ?25) Which k/w is used to create Inheritance in java?26) Which are the access specifiers in inheritance?27) Which are the two uses of “super” in Inheritance?28) What is the syntax of “super” to call superclass constructor?29) What is the basic difference of “this” & “super” keyword? 30) What is mean by method overriding?31) How to access overridden function in child class?32) Which keyword is used in Inheritance to refer nearer class member?33) Which keyword is used to prevent method overriding in Inheritance?34) How to prevent Inheritance?35) What is mean by abstract class?36) Which keyword is used to declare abstract class & method?37) What are the restrictions of abstract class?38) Why abstract class contain no any private method?39) Why abstract class contain no any abstract constructor?40) Why method overriding is prevented in abstract class?

41) How you create multiple inheritance in java?42) What are the members of interface class?43) The constants in interface as always by default ……… , ………… & ……….. .44) The methods in an interface class are always by default …………& …………but

these can never be ………….45) Can we create object of interface class?46) How we can declare interface class?

Assignment no: 4

Department of Information technology, BSIOTR PUNE.16

Page 17: Lab Mannual of SDTL

Lab Manual-Software Development Tools Laboratory [Third year IT]

Aim: Construct packages and interface.

Problem Statement:a) Write a program to create nested packages “Company and

Department” using package keyword those can be used in “Employee” class.

b) Write a program to create interface “Conversions” that can be implemented by “Convert” class.

Pre Lab: Knowledge of programming in C . Knowledge of object oriented concepts of C++.

Theory: 4.1 Abstract classes:

An abstract class is a class in which one or more methods declared but not defined, that means the bodies of the method are neglected. Such methods are called as “abstract methods”.

To declare class abstract simply use the “abstract” k/w in front of the class k/w in class declaration.

A abstract class is superclass that only defines a generalize form which will be shared by all of its subclass.

Restrictions: Abstract methods cannot be private because private methods cannot be inherited. An object of abstract class cannot be instantiated using new k/w, whereas you can

declare variable of a type abstract class. There is no need to define all methods of abstract class within its subclass. Also you cannot declare abstract constructor or abstract Static methods. Method overriding is not possible or prevented. Any subclass must implement all “abstract class methods” declared in superclass.

4.2 (A) Interface:

We already know that multiple inheritances are not permitted in java. But in real life application we need to inherit methods and properties from

several distinct classes. To support the concept of multiple inheritances java provide the alternative

approach known as interface. An interface is a collection of constant or abstract methods or both Interface does not define what method dose ( i.e no method body) The constant in interface as always by default public static & final. The methods in an interface are always by default public & abstract, these

can never be static. We cannot create object of interface.

Syntax:Interface name{

Department of Information technology, BSIOTR PUNE.17

Page 18: Lab Mannual of SDTL

Lab Manual-Software Development Tools Laboratory [Third year IT]

datatype final_vari1=value;Returntype method_name<parameters>;}

In implement inherited class contain abstract method body is defined, that method always defined as public.

interface conversions{double gmtokg=1000;double gmtokg(double gm); double kgtogm(double kg);}

class Convert implements conversions {public double gmtokg(double gm) { return gm/gmtokg; }public double kgtogm(double kg) { Return kg*gmtokg; }}

class Interfacetest{public static void main(String args[]) { Convert obj =new convert(); Conversions ref; Ref=obj; System.out.println(ref.gmtokg(2000)); System.out.println(ref.kgtogm(4)); }}

Output: 2.04000.0

4.3 (B) Packages: Packages are container for classes.

Department of Information technology, BSIOTR PUNE.18

Page 19: Lab Mannual of SDTL

Lab Manual-Software Development Tools Laboratory [Third year IT]

You can define classes inside a package that are not accessible by code outside that package.

Defining a package:General form of package statement:

Syntax:

package pkg;

Here, pkg is the name of packageFor e.g. the following statement creates a package called MyPackage.

e.g. package MyPackage;

Multileveled package statements: You can create a hierarchy of packages. To do so, simply separate each package name from the one above it by use of a period. The general form of multileveled package statement is shown as follows.

package pkg1[.pkg2[.pkg3]];

You cannot rename a package without renaming the directory in which the classes are stored.

e.g mypack :is directory(package name) pack1.java :is the class file inside the mypack package

package mypack; //package nameclass one{String name=”keshav”;Public one() {System.out.println(“Name of stud:”+name); }}

public class pack1 //class always public inside the package{public void add(int x,int y) { Syste.out.println(x+y); }One obj=new one();}

Department of Information technology, BSIOTR PUNE.19

Page 20: Lab Mannual of SDTL

Lab Manual-Software Development Tools Laboratory [Third year IT]

Now importing that package in other class

import mypack.pack1;class impl{public static void main(Strig args[]) {System.out.println(“I am in package importation class”);pack1 ob1=new pack1();ob1.add(4,10); }}

Compiling & executing impl.java program:Output:D:\keshav\cd mypackD:\keshav\mypack>javac pack1.javaD:\keshav\mypack>cd..D:\keshav>javac impl.javaD:\keshav>java impl

I am in package importation class Name of student: keshav 14

Note: main function i.e. public static void main(String args[]) is not present into the package classes files. In above first e.g class pack1 is one of the class in package(i.e. mypack). In this class pack1 contain no any main function is present.

Post lab: Hence from this assignment you learn creation of packages and How to create multiple inheritance by using interface.References: The Complete reference JAVA2 by Herbert Schildt.Viva Questions:

47) What is mean by packages?48) How we define package?49) How we can create multileveled (or Nested) packages?50) What is the use of interface?51) What type of methods are present in interface class?52) What is the access specifiers of methods that when we implement in

implementation class & that are abstract in interface class?Assignment No: 5

Department of Information technology, BSIOTR PUNE.20

Page 21: Lab Mannual of SDTL

Lab Manual-Software Development Tools Laboratory [Third year IT]

Aim: Use of try–catch block to handle exceptions at run time.

Problem Statement: Write a program to handle exception (e. g. Arithmetic Exception, Array Index out of bound) in java using try-catch block.

Pre Lab: Knowledge of programming in C. Knowledge of object oriented concepts of C++.Theory:

5.1Exception Handling: An Exception is an “abnormal condition” that arises( or occurred) in a code

sequence at run time. In other words, an exception is a run time error. In computer language like “c” that do not support exception handing. Java exception handling is managed via 5 keywords: try, catch, throw, throws,

& finally. Briefly, here is how they work:

a) try : program statements that you want to monitor for exception are contained within try block.

b) catch: if an exceptions occurs within the try block, it is thrown. Your code can catch this exception (using catch) & handle it in some rational manner.

c) throw: system generated exceptions are automatically thrown by the java un time system. To manually throw an exception, use the keyword throw.

d) throws: any exception that is thrown out of a method must be specified as such by a throws clause.

e) finally: any code that absolutely must be executed before a method returns is put in a finally block.

5.2 General form of an exception handling block: Try{//block of code to monitor for errors.}catch(Exceptiontype1 exobject){//exception handler for exception type1.}

catch(Exceptiontype2 exobject){//exception handler for exception type2.}

Department of Information technology, BSIOTR PUNE.21

Page 22: Lab Mannual of SDTL

Lab Manual-Software Development Tools Laboratory [Third year IT]

//……..finally{//block of code to be executed before try block ends.}

Here, “Exception Type” is the type of exception that has occurred. Each try block must have at least one catch block present. Multiple catch blocks with one try are possible.

5.3 multiple catch clauses: In some cases, more than one exception could be occurred by a single piece

of code. To handle this type of situation, you can use two or more “catch” clauses,

each catching a different type of exception. When an exception is thrown, each catch statement is inspected in order, &

the 1st one whose type matches that of the exception is executed. After one catch statement executes, the other are bypassed, & execution

continues after the try/catch block.

5.4 Nested try statements: The try statement can be nested. i.e., a try statement can be inside the block of another try. If an inner try statement does not have a catch handler for a particular

exception, the next try statements catch handlers are inspected for a match. This continuous until one of the catch statement succeeds, or until the entire

nested try statements are exhausted. If o catch statement matches, then the java run time system will handle the

exception.

5.5 throw k/w: So far you have only been catching exceptions that are thrown by the java run

time system. However, it is possible for your program to throw an exception explicitly, using

the throw statement. General syntax of throw is as follows:

throw Exceptionobject;

The flow of execution stops immediately after the “throw” statement; any subsequent statements are not executed.

The nearest enclosing try block is inspected to see if it has a catch statement that matches the type of the exception. If it does find a match, control is transferred to that statement. if not then the next enclosing try statement is inspected, & so on. If

Department of Information technology, BSIOTR PUNE.22

Page 23: Lab Mannual of SDTL

Lab Manual-Software Development Tools Laboratory [Third year IT]

no matching catch is found, then the default exception handler halts the program & print the stack trace.

5.6 throws k/w: If a method is capable of causing an exception that it does not handle, it must

specify this behavior so that callers of the method can guard themselves against that exception.

You do this by including a “throws” clause in the methods declaration. A throws clause list the types of exceptions that a method might throw. This is necessary for all exceptions except those of type Error or

RuntimeException.

Syntax:General syntax of a method declaration that includes a “throws” clause:

Type method_name(parameterlist) throws exceptionlist{//Body of method}

Here, ‘Exception list’ is a comma separated list of the exceptions that a method can throw.

5.7 finally clause: Finally creates block of code that will be executed after a try catch block has

completed & before the code following the try/catch block. The finally block will execute, whether or not an exception is thrown. If an exception is thrown, the finally block will execute even if no “catch”

statement matches the exception.

Uses of finally: This can be useful for closing file handles & freeing up any other

resources that might have been allocated at beginning of method. “finally” clause optional. However each try statement requires at least

one catch or a finally clause.

Post –Lab: Hence from this assignment you learn exception handling by using try, catch, throw, throws, finally keywords.

Department of Information technology, BSIOTR PUNE.23

Page 24: Lab Mannual of SDTL

Lab Manual-Software Development Tools Laboratory [Third year IT]

References: The Complete reference JAVA2 by Herbert Schildt.

Viva Questions:53) What is mean by Exception?54) In java how Exception handling is managed?55) What is the use of try & catch block?56) What is the use of “throw” clause in Exception handling?57) What is the use of “throws” clause in Exception handling?58) What are the uses of finally block?59) At which time finally block get executed?

Assignment No: 6

Department of Information technology, BSIOTR PUNE.24

Page 25: Lab Mannual of SDTL

Lab Manual-Software Development Tools Laboratory [Third year IT]

Aim: Application of Multithreading in java.

Problem Statement: Write a program to create a Bouncing Ball as example of use of Multithreading.

Pre Lab: Knowledge of programming in C . Knowledge of object oriented concepts of C++. Knowledge of Multithreaded programming Knowledge of Thread class, Runnable interface & its different methods. Theory:

6.1 Multithreaded Programming: Definition: “multithreaded program” contain two or more parts (i.e threads) that can run concurrently (or same time) are called as multithreaded programming.

6.2 The “Thread” class & “Runnable” interface: Thread class defines several methods that help to manage threads.“Thread” class methods Meaning

1) getName Obtain a threads name.2) getPriority Obtain a threads priority.3) isAlive Determine if a thread is still running.4) Join Wait for a thread to terminate.5) Run Entry point for the thread.(thread start running)6) Sleep Suspend a thread for a period of time.7) Start Start a thread by calling its run() method.

Thus all examples, which we have seen in previously, that all are a “single thread” of execution.

The reminder of this assignment explains how to use “Thread class “ and “Runnable interface” to create and manage threads.

6.3 Main Thread: If any java program starts up, one thread running immediately called it as main

thread. It is important for two reasons:

i) Main thread is a thread on which child threads are created.ii) Often it must be the last thread to finish execution because it performs

various shutdown actions. Although the main thread is created automatically when your program is started, It can be controlled through a “Thread class” object. To do so, you must obtain a

reference to it by calling the method “currentThread()”. Which is the public static member of Thread.

Its general Syntax is shown here:

Department of Information technology, BSIOTR PUNE.25

Page 26: Lab Mannual of SDTL

Lab Manual-Software Development Tools Laboratory [Third year IT]

Static Thread.currentThread()

This method (i.e currentThread()) returns a “reference” to the thread in which it is called. Once you have a reference to the “main thread” you can control it just like any other thread.

6.4 Creating a thread:

In the most common method you create a ‘thread’ by instantiating an object of type “Thread” class.

In java there are defines two ways to create the Threads: I) You can implement the “Runnable interface”. II) You can extend the “Thread” class, itself.

I) Implementing Runnable: The easiest way to create a ‘thread’ is to create a class that implements Runnable

interface. Runnable abstracts the unit of executable code. You can construct a thread on any object that implements Runnable To ‘implement Runnable’, a class need only implement a single method called

“run”. which is declared like this.

Syntax: public void run() Inside run(), you will define the code that constitutes the new thread. It is important to understand that ‘run()’ can call other methods, use other classes,

& declare variables, just like the main thread can. The only difference is that “run()” establishes the entry point for another,

concurrent thread of execution within your program. This ‘thread’ will end when ‘run()’ returns. After you create a class that implements ‘Runnable’ interface, you will

instantiate an object of type “Thread” from within that class. “Thread” defines several constructors. The one that we will use is shown here:

Thread (Runnable threadob, String threadName) // constructor

In this constructor, ‘threadob’ is an instance of a class that implements the Runnable interface. This defines where execution of the thread will start. The name of the new thread is specified by ‘threadName’.

After the new thread is created, it will not start running until you call its ‘start()’ method, which is declared within Thread class.

In essence, “start()” executes call to ‘run()’. The start method syntax is as follows:

void start() //run() calls the start() method.

6.5 Extending “Thread”:

Department of Information technology, BSIOTR PUNE.26

Page 27: Lab Mannual of SDTL

Lab Manual-Software Development Tools Laboratory [Third year IT]

First create a new class that extends “Thread” class, and then to create an instance of that class.

The extending class must override the “run()” method, which is the entry point of the new thread.

Run() method must also call by using “start()” method to start execution of the new thread.

6.6 Creating multiple threads:- So far, we have been seen only two threads: the main thread & child thread. However, your program can create many threads as it needs. For example following programs creates three(3) child threads.

Class NewThread implements Runnable{String Name;Thread t;

NewThread(String threadname) //constructor {Nmae=threadname;T=new Thread(this, Name);System.out.println(“New thread:”+t);t.start(); }

Public void run(){try {For (int i=5;i>0;i--) {System.out.println(Name+”:”+i);Thread.sleep(1000); } }catch(InterruptedException e) {System.out.println(Name+”interrupted”); }System.out.println(Name+”exiting”); }}

Class MultiThreadDemo //Main thread.{Public static void main(String args[])

Department of Information technology, BSIOTR PUNE.27

Page 28: Lab Mannual of SDTL

Lab Manual-Software Development Tools Laboratory [Third year IT]

{new NewThread(“One”);new NewThread(“Two”);new NewThread(“Three”);try {Thread.sleep(10000); //suspend thread some period }catch(InterruptedException e) {System.out.println(“Main thread Interrupted”); }System.out.printl(“main thread exiting”); }}

Output:New thread: Thread[One,5,main]New thread: Thread[Two,5,main]New thread: Thread[Three,5,main]One:5Two:5Three:5One:4Two:4Three:4 One:3Two:3Three:3One:2Two:2Three:2One:1Two:1Three:1One exitingTwo exitingThree exitingMain Thread exiting

6.7 Using isAlive() & join(): There are, 2 ways exist to determine whether a thread has finished. (I) you can call “isAlive()” on the “Thread”. This method is defined by

‘Thread’, & its general syntax is as follows:

final Boolean isAlive()

Department of Information technology, BSIOTR PUNE.28

Page 29: Lab Mannual of SDTL

Lab Manual-Software Development Tools Laboratory [Third year IT]

True: the isAlive method returns ‘true’ if the thread upon which it is called is still running.

False: otherwise it returns ‘false’ (II)while isAlive() is occasionally useful the method that you will more

commonly use to wait for a thread to finish is called “join()”Syntax:final void join() throws InterruptedException

Advancements: Create child window in applet by extending Frame class. Then use Graphics class

that present in AWT to fill Oval in frame & then animate them by changing coordinates.

Post-Lab: Hence from this assignment you learn how to create multiple child threads in Main thread by extending Thread class & implementing Runnable interface.

References: 1) The Complete Reference JAVA2 by Herbert Schildt.

Viva Questions:60) What is mean by Multithreaded Programming?61) Which are the methods defined by “Thread” class to manage thread?62) What is the use of isAlive() & join() method of Thread class in multithreading?63) Why main thread is important?64) How we can get reference of main thread so that we can control it?65) Which are the two methods for creation of child threads?66) What is the use of run() method & who is calling this run() method?

Assignment No: 7

Aim: Use of I/O classes in java.

Problem Statement: Write a java program to read from txt file and write to console using I/O classes in java.

Department of Information technology, BSIOTR PUNE.29

Page 30: Lab Mannual of SDTL

Lab Manual-Software Development Tools Laboratory [Third year IT]

Pre Lab: Knowledge of programming in C . Knowledge of object oriented concepts of C++. Knowledge of I/O classes in JAVA.Theory:

7.1 Writing console output:

Console output is most easily accomplished with print() & println(), described earlier, which are used in most of the examples in this book.

These ‘methods’ are defined by the class ‘PrintStream’ (which is the type of the object referenced by System.out).

PrintStream class also implements the low level method “write()”.Thus, ‘write()’ can be used to write to the console.

e.g// Demonstrate System.out.write()

class WriteDemo{public static void main(String args[]) { int b; b=’A’;System.out.write(b);System.out.write(‘\n’); }}

You will not often use write() to perform console output, because “print()” & “println()” are substantially easier to use.

7.2 The PrintWriter class:-

Although using ‘System.out’ to write to the console is still permissible under java. For real world programs, the recommended method of writing to the console

when using java is through a PrintWriter stream. ‘PrintWriter’ is one of the character based classes. PrintWriter defines several constructors. The one we will use is shown here:

PrintWriter(OutputStream outputstream, Boolean flushonnewline)

Department of Information technology, BSIOTR PUNE.30

Page 31: Lab Mannual of SDTL

Lab Manual-Software Development Tools Laboratory [Third year IT]

Here , flushonnewline controls whether java flushes the output stream every time a println() method is called. If flushonnewline is true, flushing automatically takes place. If false, flushing is not automatic.

‘PrintWriter’ supports the print() & println() methods for all types including object. Thus you can use these methods in the same way as they have been used with System.out.

To write to the console by using a “printWriter’, specify ‘System.out’ for the o/p stream & flush the stream after each newline.For e.g, this line of code creates a “PrintWriter” that is connected to console output.

PrintWriter pw=new PrintWriter(System.out,true);

The following application illustrates using a ‘PrintWriter’ to handle console output.

//demonstrate PrintWriter

Import java.io.*;public class PrintWriterDemo{public static void main(String args[]) {PrintWriter pw=new PrintWriter(System.out,true);pw.println(“This is a string”);Int i=-7;pw.println(i);double d=4.5e-7;pw.println(d); }}

Output: This is a string-74.5e-7

7.3 Reading & Writing Files: Java provides a number of classes & methods that allows you to read & write

files. In java, all files are ‘byte oriented’, & java provides methods to read & write

bytes from & to a file. In java there are two stream classes are used.

1) FileInputStream2) FileOutputStream

Both these classes create byte streams linked to files.

Department of Information technology, BSIOTR PUNE.31

Page 32: Lab Mannual of SDTL

Lab Manual-Software Development Tools Laboratory [Third year IT]

To open a file, you simply create an object of one of these classes, passing the name of the file as an argument to the constructor.

While both classes support additional, overridden constructors, the following are the forms that we will be using.

FileInputStream(String fileName)throws FileNotFoundExceptionFileOutputStream(String fileName)throws FileNotFoundException

Here ,filename- indicates the name of file that you want to open. When you create an input stream, if the file does not exist, then

FileNotFoundException is thrown. For OutputStreams, if the file can not be created, then FileNotFoundException is

thrown. Note: in earlier versions of java, FileOutputStream() throw an IOException when

an output file could not be created. This was changed by Java2. When you are done with a file , you should close it by calling ‘close()’. It is

defined by both classes(i.e FileInputStream & FileOutputStream), as shown here

void close() throws IOException //syntax of closing file.

To read from a file , you can use a method read() that is defined within FileInputStream.

Syntax: Int read() throws IOException

Each time that it is called , it reads a single(1) byte from the file & returns the byte as an integer value.

read() returns -1 when the end of file is occurred. It can throw an IOException. The following program uses read() to i/p & display the content of the text file, the

name of which is specified as a command line argument. you can use this same approach whenever you use command line arguments.

Reading File:import java.io.*;class ShowFile{public static void main(String args[])throws IOExceptio {int i;FileInputStream fin;try { fin=new FileInputStream(args[0]); }catch(FileNotFoundException e) { System.out.println(“File not found:”+e);

Department of Information technology, BSIOTR PUNE.32

Page 33: Lab Mannual of SDTL

Lab Manual-Software Development Tools Laboratory [Third year IT]

return; }catch(ArrayIndexOutOfBoundsException e) {System.out.println(“Usage:showFile file”); Return; }//read charcter until EOF is encountered do { i=fin.read(); //read file by one byte stream each time. if(i!=-1) { System.out.print((char)i); } }while(i!=-1) fin.close(); } }

Run the above program using following command:

\>java ShowFile TEST.TXT

Writing File: To write to a file, you will use the ‘write() method defined by FileOutputStream

class. Its simplest syntax is shown here:

void write(int byteval)throws IOException This method writes the byte specified by byteval to the file. Although byteval is

declared as an integer. Only the low order eight bits are written to the file. If an error occurs during writing, an IOException is thrown. The next e.g uses ‘write()’ to copy a text file.

/* Copy a text fileTo use this program, specify the name of the source file & the destination file. For e.g, to copy a file called FIRST.TXT to a file called ‘SECOND.TXT, use the following cmd line.\>java CopyFile FIRST.TXT SECOND.TXT*/import java.io.*;class CopyFile{public static void main(String args[])throws IOException

Department of Information technology, BSIOTR PUNE.33

Page 34: Lab Mannual of SDTL

Lab Manual-Software Development Tools Laboratory [Third year IT]

{ int i; FileInputStream fin; FileOutputStream fout;try{ //open i/p file try { fin=new FileInputStream(args[0]); }catch(FileNotFoundException e) {System.out.println(“input file not found”+e); return; }//open o/p filetry{fout=new FileOutputStream(args[1]);}catch(FileNotFoundException e) {System.out.println(“error in opening o/p file ”);return; }}catch(ArrayIndesOutOfBoundsException e){System.out.println(“Usage:copyFile from to”);return;}//read source file & copy data in destination filetry{do { i=fin.read(); if(i!=-1) { fout.write(i); }while(i!=-1)}catch(IOException e){System.out.println(“File error”+e);}

Department of Information technology, BSIOTR PUNE.34

Page 35: Lab Mannual of SDTL

Lab Manual-Software Development Tools Laboratory [Third year IT]

fin.close();fout.close();}}

Run this program using following command:\>java CopyFile FIRST.TXT SECOND.TXT

Post-Lab: Hence from this assignment you learn use of JAVA I/O classes to create new file & Read data from that file.

References: 1) The Complete Reference JAVA2 by Herbert Schildt.

Viva Questions:1. What is the use of BufferedReader & DataInputStream class in java?2. What is the use of FileInputStream class?3. What is the use of FileOutputStream class?4. How you open a file that you want to read or write?

Assignment No: 8

Aim: Design and develop Applet in java.

Department of Information technology, BSIOTR PUNE.35

Page 36: Lab Mannual of SDTL

Lab Manual-Software Development Tools Laboratory [Third year IT]

Problem Statement: Write a program to construct Applet in java.

Pre Lab: Knowledge of programming in C, C++. Knowledge of object oriented concepts of C++.

Theory:

8.1 Applet: Applets are small application that are accessed on an internet server, transported

over the internet, automatically installed, & run as part of a web document. Applets are differ from applications in several key areas Let’s start with the simple applet shown here:

import java.awt.*;import java.applet.*;/*<applet code=”SimpleApplet” width=200 height=60></applet>*/public class SimpleApplet extends Applet{public void paint(Graphics g) {g.drawString(“a simple applet”,20,20); }}

In above program first statement imports the ‘awt’ (Abstract Window Toolkit) package containing all classes.

Applets interact with the user through the AWT, not through the console based I/O classes.

The AWT contains support for a “windows-Based”, graphical interface. The second statement imports the “applet” package, which contains the class

Applet. Every ‘applet’ that you create must be a childclass of “Applet”. After that we create ‘SimpleApplet’ class, and that class is subclass of ‘Applet’

class. This class must be declared as ‘public’, because it will be accessed by code that is outside the program.

Inside ‘SimpleApplet’, ‘paint()’ is declared. This method is defined by the AWT & must be overridden by the applet.

‘paint()’ is called each time that the ‘applet’ must ‘redisplay’ its output. “paint()” is also called when the applet begins execution.

The ‘paint()’ method has one parameter of type ‘Graphics’. This parameter contains the graphics context, which describes the graphics environment in which the applet is running. This context is used whenever o/p to the applet is required.

Department of Information technology, BSIOTR PUNE.36

Page 37: Lab Mannual of SDTL

Lab Manual-Software Development Tools Laboratory [Third year IT]

Inside the ‘paint()’, ’drawString()’ method is called, which is a member of the ‘Graphics’ class.

This method outputs a string beginning at the specified x, y location. It has following general syntax:

void drawString(String msg, int x, int y)

In a java window, the upper left corner is location 0,0. The call to drawString() in the applet causes the msg “A simple applet” to be displayed beginning at location 20,20.

NOTE: Applet does not have a main() method. Unlike java programs, applets do not start execution at main(). Instead, an applet start execution when the name of its class is passed to an ‘applet viewer’ or to a network browser.

There are 2 ways in which you can run an applet :1) Executing the applet within a java-compatible web browser(e).2) Using an “applet viewer”, such as the standard SDK tool, ‘appletviewer’. An

“applet viewer” executes your applet in window. Each of these method described below:

- To execute an applet in a ‘web browser’, you need to write a short HTML text file that contains the appropriate applet tag. here is the HTML file that executes SimpleApplet.<applet code=”SimpleApplet” width=200 height=60></applet>

After you create this file, you can execute your browser & then load this file, which causes simple applet to be executed.To execute “SimpleApplet”, with an “appletviewer “ you may also execute the HTML file shown earlier. For e.g, if the preceding HTML file is called “RunApp.html”, then the following command line will run ‘SimpleApplet’:

C:\>appletviewer RunApp.html

or use following command:

C:\>javac SimpleApplet.javaC:\>appletviewer SimpleApplet.java

After execution of above cmd. The window produced by ‘SimpleApplet’, as displayed by the “appletviewer” is shown in the following illustration.

8.2 An Applet Skeleton:- All but the most trivial applets override a set of methods that provides the

basic mechanism by which the ‘browser’ or ‘applet viewer’ interfaces to the applet & controls its execution. 4 of these methods i)ini() ii)start() iii) stop(), ?& iv)display() are defined by the applet. Another, paint(), is defined by the AWT component class.

Department of Information technology, BSIOTR PUNE.37

Page 38: Lab Mannual of SDTL

Lab Manual-Software Development Tools Laboratory [Third year IT]

Default implementations for all of these methods are provided. Applets do not need to override those methods they do not use.

8.3 Applet Initialization & Termination: When an applet started, the AWT calls the following methods, in this sequence:

1) init() 2) start 3) paint() When an applet is terminated, the following sequence of methods calls takes

place:1) stop() 2) destroy()All should execute each time as applet program is loaded hence called as life cycle of applet.

8.4 Lets see more closely at these methods: 1)init(): the init() method is the 1st method to be called. This is where you should “initialize variables”.Syntax: public void init() //called 1st { //initialization of variables. }

2)start(): this method called 2nd time, after init().it is also called to “restart an applet” after it has been stopped.Syntax: //called 2nd after init() public void start() { //start or resume execution } 3)paint(): paint() method called when an applets window must be restored. Also paint() method redisplay contents of window. paint() is also called when the applet begins execution. The paint() method has one parameter of type Graphics. Parameter will contain the graphics context, which describes the graphics environment in which the applet running.Syntax: public void paint(Graphics g) { //redisplay contents of window } 4)stop(): method is called when the applet is stopped. or it suspends execution of applet.Syntax: public void stop() { //suspend execution

Department of Information technology, BSIOTR PUNE.38

Page 39: Lab Mannual of SDTL

Lab Manual-Software Development Tools Laboratory [Third year IT]

}

5) destroy(): this method is called when the environment determines that your applet needs to be removed completely from memory. Syntax:/* called when applet is terminated. This is the last method executed */ Public void destroy() { //perform shutdown activities. }

8.5 Simple Applet Display Method: As we have mentioned, applets are displayed in a window & they use the AWT to

perform i/p & o/p. Although we will examine the methods, procedures & techniques necessary to

fully handle the ‘AWT’ window environment in subsequent chapters. A few are described here, because we will use them to write ‘sample applet’.

In previous program, to output a string to an applet , use drawstring() method, which is a member(method) of the Graphics class. Typically, it is called from within either paint().

void drawString(String msg, int x, int y)

Here, msg is the string to be o/p beginning at x,y. In a java window, the upper-left corner is location 0,0.

The drawstring() method will not recognize newline characters. If you want to start line of text on another line, you must do so manually, specifying the precise x,y location where you want the line to start.

Methods:1) setBackground(): to set the background color of an applet’s window, use

setBackground() method.2) setForeground(): to set the foreground color of an applets window, use

setForeground() method.

These methods are defined by Component,Syntax: void setBackground(Color.newColor) void setForground(Color.newColor)

Wher, newColor->specifies the new color. class Color->defines the constants shown here that can be used to specify the color:

Department of Information technology, BSIOTR PUNE.39

Page 40: Lab Mannual of SDTL

Lab Manual-Software Development Tools Laboratory [Third year IT]

Color.black Color.cyanColor.pink Color.redColor.yellowColor.magnetaColor.lightGrayColor.greenColor.darkGray

Color.gray Color.blue Color.orange

For e.g this sets the background color to green & text color to red. setBackground(Color.green); setForeground(Color.red);

A good place to set the foreground & background colors is in the ‘init()’ method. Of course, you can change these colors as often as necessary during the execution of your applet.The default Foreground color is “Black”The default Background color is “light gray”.

You can obtain the current settings for the B.G & F.G. colors by calling getBackground() & getForeground(), respectively.

They are also defined by Component & are shown here: Color getBackground() Color getForeground()

8.6 Requesting Repainting: As a general rule, an applet writes to its window only when its update() or

paint() method is called by the AWT. This raises an interesting question:

How can the applet itself cause its window to be changed when its information changes ?

For e.g. If an applet is displaying a moving banner, what mechanism dose the applet use to update the window each time this banner scrolls ?

The applet is that it must quickly return control to the “AWT run time system”. It cannot create a loop inside paint() that repeatedly scrolls the banner, for e.g. this

would prevent control from passing back to the AWT. Whenever your applet needs to update the information displayed in its window, it

simply calls “repaint()” The repaint() method is defined by the AWT. It causes the AWT run-time system

to execute a call to your applets update() method, which in its default implementation, calls paint().

Department of Information technology, BSIOTR PUNE.40

Page 41: Lab Mannual of SDTL

Lab Manual-Software Development Tools Laboratory [Third year IT]

Thus, for another part of your applet to o/p to its window, simply store the o/p &? Then call “repaint()”. The AWT will then execute a call to paint(), which can display the stored information.

For e.g. if part of your applet needs to o/p a string, it can store this string in a String variable & then call repaint().

Inside ‘paint()’ you will output the string using drawString(). The repaint() method has 4 forms:

1)The simplest version of repaint() is shown here: void repaint() //entire window to be repainted

2)The following version shows a “region” that will be repainted: void repaint(int left, int top, int width, int height)

void repaint(long maxDelay) void repaint(long maxDelay, int x, int y, int width, int height)

Advancements: Creation & Execution applet by using IDE. for example use of NetBeans

Post-Lab: Hence from this assignment you learn how to execute Applet application in Browser as well as how to execute by using appletviewer.

References:1) The Complete Reference JAVA2 by Herbert Schildt.

Viva Questions: 1) Where is applet executed?

2) What is the life cycle of Applet?3) Which methods get executed sequentially when applet application is loaded?4) What is the use of init() method in Applet?5) What is the use of paint() method in Applet?6) What is the use of repaint() method?7) What is the use of appletviewer in applet?

Assignment No: 9

Department of Information technology, BSIOTR PUNE.41

Page 42: Lab Mannual of SDTL

Lab Manual-Software Development Tools Laboratory [Third year IT]

Aim: Design and develop Abstract Window Toolkit and layout in java.

Problem Statement: Write a program to construct GUI of notepad or calculator using an Abstract Window Toolkit.

Pre Lab: Knowledge of programming in C . Knowledge of object oriented concepts of C++. Knowledge of Core JAVA. Knowledge about GUI of editor. Knowledge of AWT programming. Theory:9.1 Working with Frame Windows:

After the applet, the type of window you will most often create is derived from Frame. You will use it to create child windows within applets, and top-level or child windows for applications. As mentioned, it creates a standard-style window. Frame supports these two constructors:Frame( )Frame(String title)

The first form creates a standard window that does not contain a title. The second form creates a window with the title specified by title. Notice that you cannot specify the dimensions of the window. Instead, you must set the size of the window after it has been created. There are several methods you will use when working with Frame windows. They are examined here.Setting the Window's DimensionsThe setSize( ) method is used to set the dimensions of the window. Its signature is shown here:

void setSize(int newWidth, int newHeight)void setSize(Dimension newSize)

The new size of the window is specified by newWidth and newHeight, or by the width and height fields of the Dimension object passed in newSize. The dimensions are specified in terms of pixels. The getSize( ) method is used to obtain the current size of a window. Its signature is shown here:

Dimension getSize( )

This method returns the current size of the window contained within the width and height fields of a Dimension object.

Hiding and Showing a Window:

Department of Information technology, BSIOTR PUNE.42

Page 43: Lab Mannual of SDTL

Lab Manual-Software Development Tools Laboratory [Third year IT]

After a frame window has been created, it will not be visible until you call setVisible( ). Itssignature is shown here:

void setVisible(boolean visibleFlag)

The component is visible if the argument to this method is true. Otherwise, it is hidden.

Setting a Window's Title:

You can change the title in a frame window using setTitle( ), which has this general form:

void setTitle(String newTitle)

Here, newTitle is the new title for the window.

Closing a Frame Window:

When using a frame window, your program must remove that window from the screen when it is closed, by calling setVisible(false). To intercept a window-close event, you must implement the windowClosing( ) method of the indowListener interface. Inside windowClosing( ), you must remove the window from the screen. The example in the next section illustrates this technique.

9.2 Menu Bars and Menus: A top-level window can have a menu bar associated with it. A menu bar displays a list oftop-level menu choices. Each choice is associated with a drop-down menu. This concept is implemented in Java by the following classes: MenuBar, Menu, and MenuItem. In general, a menu bar contains one or more Menu objects. Each Menu object contains a list of MenuItem objects. Each MenuItem object represents something that can be selected by the user. Since Menu is a subclass of MenuItem, a hierarchy of nested submenus can be created. It is also possible to include checkable menu items. These are menu options of type CheckboxMenuItem and will have a check mark next to them when they are selected. To create a menu bar, first create an instance of MenuBar. This class only defines the default constructor. Next, create instances of Menu that will define the selections displayed on the bar. Following are the constructors for

Menu:

Menu( ) Menu(String optionName)

Menu(String optionName, boolean removable)

Here, optionName specifies the name of the menu selection. If removable is true, the pop-up menu can be removed and allowed to float free. Otherwise, it will remain attached

Department of Information technology, BSIOTR PUNE.43

Page 44: Lab Mannual of SDTL

Lab Manual-Software Development Tools Laboratory [Third year IT]

to the menu bar. (Removable menus are implementation-dependent.) The first form creates an empty menu. Individual menu items are of type MenuItem. It defines these constructors:

MenuItem( )MenuItem(String itemName)MenuItem(String itemName, MenuShortcut keyAccel)

Here, itemName is the name shown in the menu, and keyAccel is the menu shortcut for this item. You can disable or enable a menu item by using the setEnabled( ) method. Its form is shown here:

void setEnabled(boolean enabledFlag)

If the argument enabledFlag is true, the menu item is enabled. If false, the menu item is disabled. You can determine an item's status by calling isEnabled( ). This method is shown here:

boolean isEnabled( )

isEnabled( ) returns true if the menu item on which it is called is enabled. Otherwise, it returns false.You can change the name of a menu item by calling setLabel( ). You can retrieve the current name by using getLabel( ). These methods are as follows:

void setLabel(String newName)String getLabel( )

Here, newName becomes the new name of the invoking menu item. getLabel( ) returns the current name.You can create a checkable menu item by using a subclass of MenuItem called CheckboxMenuItem. It has these constructors:

CheckboxMenuItem( )CheckboxMenuItem(String itemName)CheckboxMenuItem(String itemName, boolean on)

Here, itemName is the name shown in the menu. Checkable items operate as toggles. Each time one is selected, its state changes. In the first two forms, the checkable entry is unchecked. In the third form, if on is true, the checkable entry is initially checked. Otherwise, it is cleared. You can obtain the status of a checkable item by calling getState( ). You can set it to a known state by using setState( ). These methods are shown here:

boolean getState( )void setState(boolean checked) If the item is checked, getState( ) returns true. Otherwise, it returns false. To check an item, pass true to setState( ). To clear an item, pass false.

Department of Information technology, BSIOTR PUNE.44

Page 45: Lab Mannual of SDTL

Lab Manual-Software Development Tools Laboratory [Third year IT]

Once you have created a menu item, you must add the item to a Menu object by using add( ), which has the following general form:

MenuItem add(MenuItem item)

Here, item is the item being added. Items are added to a menu in the order in which the calls to add( ) take place. The item is returned.Once you have added all items to a Menu object, you can add that object to the menubar by using this version of add( ) defined by MenuBar:

Menu add(Menu menu)

Here, menu is the menu being added. The menu is returned.Menus only generate events when an item of type MenuItem or CheckboxMenuItem is selected. They do not generate events when a menu bar is accessed to display a dropdown menu, for example. Each time a menu item is selected, an ActionEvent object is generated. Each time a check box menu item is checked or unchecked, an ItemEvent object is generated. Thus, you must implement the ActionListener and ItemListener interfaces in order to handle these menu events. The getItem( ) method of ItemEvent returns a reference to the item that generated this event. The general form of this method is shown here:

Object getItem( )

Advancements: Building GUI of Notepad such that it contain Menu Bar, Menu, Menu Items,

Check Box Menu Items, Sub Menus are present. Use of event handling to perform different operations

Post-Lab: Hence from this assignment you learn how to create editor by using AWT classes.

References: 1) The Complete Reference JAVA2 by Herbert Schildt.

Viva Questions:

1. Which class is present at the top of the AWT hierarchy?2. What is the use of Frame class?

3. When we select Menu Item from the Menu then which type of event is occurred?

4. When we select CheckoxMenuItem from Menu then which type of event is occurred?

Department of Information technology, BSIOTR PUNE.45

Page 46: Lab Mannual of SDTL

Lab Manual-Software Development Tools Laboratory [Third year IT]

Assignment No: 10

Aim: Event Handling in java.

Problem Statement: Write a program to extend notepad or calculator application to demonstrate event handling in java.

Pre Lab: Knowledge of programming in C . Knowledge of object oriented concepts of C++. Knowledge of Event classes . Knowledge of interface classes & its abstract methods.

Theory:

10.1 Event Handling: As we have seen that applets are event driven programs. Thus, event handling is

at the core of successful applet programming. Most events to which your applet will respond are generated by the user. These

events are passed to your applet in a verity of ways, with the specific methods depending upon the actual event.

There are several type of events: 1)The most commonly ‘handled events’ are those generated by the mouse, the keyboard, & various controls, such as push button.

Events are supported by the java.awt.event package

The theory starts with an overview of java’s event handling mechanisms. It then examines the main event classes & interfaces, & develops several examples that illustrate the fundamentals of event processing.

10.2 Definition of ‘Event’ & description of the roles of ‘Sources’ & ‘listeners’: A) Events: In the delegation model, an event is an object that describes a

state change in a source. It can be generated as a consequence of a person interacting with the elements in a

graphical user interface GUI. E.g. some of the activities that cause events to be generated are pressing a button, entering a character via the keyboard, selecting an item in a list, & clicking the mouse. Many other user operations could also be cited as examples.

Events may also occur that are not directly caused by interactions with a user interface for e.g. an event may be generated when a timer expires, a counter exceeds a value, a s/w or h/w failure occurs, or an operation is completed.

You are free to define events that are appropriate for your application. B) Event Sources: a source is an object that generates an event. This occurs

when the internal state of that object changes in some way. sources may generate more than one type of event.

Department of Information technology, BSIOTR PUNE.46

Page 47: Lab Mannual of SDTL

Lab Manual-Software Development Tools Laboratory [Third year IT]

A sources must register listener in order for the listeners to receive notification about a specific type of event.

Each type of event has its own registration methodSyntax:public void addTypeListener(TypeListener el) //add listener method is provided by “source”.

Here, Type is the name of the event & el is a object(reference) to the event listener.

For e.g. the method that registers a ‘keyboard event’ listener is called “addKeyListener()”. llly

The method that registers a mouse motion listener is called “addMouseMotionListener()”.

When an event occurs, all registered listeners are notified and receive a copy of the event object. This is known as multicasting the event.

Some sources may allow only one listener to registerSyntax:public void addTypeListener(TypeListener el)throws java.util.TooManyListenersException

A source must also provide a method that allows a listener to unregister an interest in a specific type of event.Syntax:

Public void removeTypeListener(TypeListener el) Here, Type->is the name of event El->is a reference to the event listener.For e.g: To remove a ‘keyboard listener ‘, you would call “rmoveKeyListener()”

The methods that add or remove listeners are provided by the “source” that generates events.

For e.g: the component class provides methods to add & remove keyboard & mouse event listener.

C) EventListeners: A listener is an object that is notified when an event occurs. It has two major requirements.1)It must have been registered with one or more sources to receive notifications about specific types of events.2)It must implement methods to receive & process these notification

The methods that receive & process events are defined in a set of interfaces found in java.awt.event

For e.g. the ‘MouseMotionListener” interface defines two methods to receive notifications when the mouse is dragged or moved.

Any object may receive & process one or both of these events if it provides an implementation of this interfaces.

10.3 Event Classes: In java’s event handling mechanism uses the classes that represent events.

Department of Information technology, BSIOTR PUNE.47

Page 48: Lab Mannual of SDTL

Lab Manual-Software Development Tools Laboratory [Third year IT]

At the root of the java event class hierarchy is ‘EventObject’, which is in java.util.EventObject.

It is the superclass of all events. Its one constructor is shown here:

EventObject(Object src)

Here, src is the object that generates this event. EventObject contains two methods:

1) getSource() //returns the source of event2) toString() //returns the string equivalent of the event.

General syntax of getSource() the class “AWTEvent”, defined within the ‘java.awt’ package

EventObject -superclass of all AWT based events AWTEvent -subclass

all the classes that we are going to study, these all are subclasses of “AWTEvent”.To summarize:EventObject: is a superclass of all events.

AWTEvent: is a superclass of all AWT events. The package “java.awt.event” defines several type of events that are generated by

various user interface elements. Following table list out the most important of these event classes & provides a

brief description of when they are generated. The most commonly used constructors & methods in each class are described in

the following section.

10.4 Event Classes: Main Event classes in java.awt.event1) ActionEvent:2) AdjustmentEvent3) ComponentEvent4) ContainerEvent5) FocusEvent6) InputEvent7) ItemEvent8) KeyEvent9) MouseEvent10) MouseWheelEvent11) TextEvent12) WindowEvent

The ActionEvent class : The ActionEvent class defines 4 integer constants that can be used to identify

any modifiers associated with an action event: ALT_MASK, CTRL_MASK, META_MASK, SHIFT_MASK.in addition, there is an integer, there is an integer constant, ACTION_PERFORMED, which can be used to identify action events.

Department of Information technology, BSIOTR PUNE.48

Page 49: Lab Mannual of SDTL

Lab Manual-Software Development Tools Laboratory [Third year IT]

ActionEvent has 3 Constructors: ActionEvent(Object src, int type, String cmd) ActionEvent(Object src, int type, String cmd, int modifiers) ActionEvent(Object src, int type, String cmd, long when, int modifiers)

String getActionCommand() //by using this method we can obtain the cmd name for the calling ActionEvent.

int getModifiers() //this method returns a value that indicates which modifier keys were pressed when the event was generated.

long getWhen() //this method returns the time at which the event tookplace.

The ‘KeyEvent’ class: A ‘KeyEvent’ is generated when k/b input is occurs, There are 3 types of key events, which are identified by these integer constants:

KEY_PRESSED, KEY_RELEASED, & KEY_TYPED Here are two of constructors:

KeyEvent(Component src, int type, long when, int modifiers, int code) KeyEvent(Component src, int type, long when, int modifiers, int code, char ch)

KeyEvent class defines several methods: Char getKeyChar() //which returns the character that was entered. getKeyCode() //which returns the key code.

10.5 Sources of events: Following are some of the user interface components that can generate the events

described in the previous section. In addition to these GUI elements, other components such as an applet, can

generate events. For e.g. you receive “Key” &”Mouse” events from an applet. Event Source

1) Button2) Checkbox3) Choice4) List5) MenuItem6) Scrollbar7) TextComponents8) Window

10.6 Event Listener Interfaces: The event model has two parts:

A) Sources B) Listeners

Listeners: are created by implementing one or more of the interfaces defined by the “java.awt.event” package.

Source: when an event occurs, the event source call the appropriate method defined by the listener & provides an “event object” as its argument.

Department of Information technology, BSIOTR PUNE.49

Page 50: Lab Mannual of SDTL

Lab Manual-Software Development Tools Laboratory [Third year IT]

Following are commonly used ‘Listener Interfaces’: 1) KeyListener interface

Methods: void keyPressed(KeyEvent ke) void keyReleased(KeyEvent ke) void keyTyped(KeyEvent ke)

2) MouseListener interface Method: void mouseClicked(MouseEvent me) void mouseEntered(MouseEvent me) void mouseExited(MouseEvent me) void mousePresseed(MouseEvent me) void mouseReleased(MouseEvent me)

3) MouseMotionListener4) MouseWheelListener.

Advancements:Building GUI of Calculator such that this calculator performing scientific mathematical operations. Also handling the Action Event.

Post-Lab: Hence from this assignment you learn how to handle the different type of events by using Event Handling concept of JAVA.

References: 1) The Complete Reference JAVA2 by Herbert Schildt.

Viva Questions:

1. Which are the abstract methods present in KeyListener interface class to handle the keyboard events?2. Which are the abstract methods present in MouseListener interface class to handle the mouse events?3. Which are the abstract methods present in ActionListener interface class to handle the events?4. Which are the abstract methods present in ItemListener interface class to handle the events?5. What is mean by Event?6. How events are generated?7. Which package we import for handling the various type of events?8. Which are the Event Source classes present in java.awt.event.* package?

Department of Information technology, BSIOTR PUNE.50

Page 51: Lab Mannual of SDTL

Lab Manual-Software Development Tools Laboratory [Third year IT]

Assignment No: 11

Aim: Creating java DB connectivity using JDBC & ODBC driver.

Problem Statement: Write a program to access Student database using JDBC connectivity with Access or Oracle.

Pre Lab: Knowledge of programming in C . Knowledge of object oriented concepts of C++. Knowledge of SQL. Knowledge of Oracle, SQL server, MS Access Databases.

Theory:

JDBC

11.1 What is JDBC?

Working with leaders in the database field, Sun developed a single API for database access—JDBC.

As part of this process, they kept three main goals in mind: I) JDBC should be a SQL-level API. II) JDBC should capitalize on the experience of existing database APIs. III)JDBC should be simple.

A SQL-level API means that JDBC allows you to construct SQL statements and embed them inside Java API calls.

In short, you are basically using SQL. But JDBC lets you smoothly translate between the world of the database and the world of the Java application. Your results from the database, for instance, are returned as Java objects, and access problems get thrown as exceptions.

Sun drew upon the successful aspects of one such API, Open DataBase Connectivity (ODBC). ODBC was developed to create a single standard for database access in the Windows environment.

11.2 JDBC has four driver of connection:1) JavaPure Driver2) Java net API Driver3) JDBC ODBC driver.4) Third party driver

11.3 The Structure of JDBC: JDBC accomplishes its goals through a set of Java interfaces, each implemented

differently by individual vendors. The set of classes that implement the JDBC

Department of Information technology, BSIOTR PUNE.51

Page 52: Lab Mannual of SDTL

Lab Manual-Software Development Tools Laboratory [Third year IT]

interfaces for a particular database engine is called a JDBC driver. In building a database application, you do not have to think about the implementation of these underlying classes at all; the whole point of JDBC is to hide the specifics of each database and let you worry about just your application. Figure 11.1 illustrates the JDBC architecture.

If you think about a database query for any database engine, it requires you to connect to the database, issue your SELECT statement, and process the result set.

Figure 3.1. The JDBC architecture In Example, you have the full code listing for a simple SELECT application from

the Imaginary JDBC Driver for. This application is a single class that gets all of the rows from a table in an MS Access database located on my drive.

First, it connects to the database by getting a database connection under my user id, from the JDBC DriverManager class. It uses that database connection to create a Statement object that performs the SELECT query.

A ResultSet object then provides the application with the key and val fields from the test table.Source code:Import java.io.*;import java.sql.*;

public class JDBCcon{public static void main(String args[]) {try {Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);

Department of Information technology, BSIOTR PUNE.52

Page 53: Lab Mannual of SDTL

Lab Manual-Software Development Tools Laboratory [Third year IT]

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

try {Connection con=DriverManager.getConnection(“jdbc:odbc:DataBase1”);Statement stmt=con.createStatement();ResultSet rs=stmt.executeQuery(“select * from student”); while(rs.next()) { Syste.out.println(“ “+rs.getString(1)+” “+ rs.getString(2)); } }catch(Exception e) {System.out.println(e); }}}

Advancements: Building GUI of window & take i/p from keyboard by interacting user

with this GUI & performing different operations on table.For e.g Delete, Insert, Update, Display.

Post-Lab: Hence from this assignment you learn JDBC concept of JAVA to create connectivity to any Database by using specific Driver. Also performing different operations on that.

References:1) SQL & PL/SQL programming by Evan Bayross.

2) Viva Questions:

1) What is mean by JDBC driver?2) Which are the drivers in JDBC for Connection?3) What is the use of following method of Class in JDBC?

Class.forName();

Department of Information technology, BSIOTR PUNE.53