Sunteți pe pagina 1din 117

Java and Web Technologies Lab

DCET

INTRODUCTION TO JAVA
Java is a new object oriented language receiving a worldwide attention from both industry and academia. Java was developed by James Gosling and his team at Sun Micro systems in California. The language is based on C and C++ and was originally intended for writing programs that control consumer appliances such as toaster, microwave ovens and others. The language was first named as Oak, but since the name has already been taken, the team renamed it as Java. Java programs can be of two types: 1) Applications 2) Applets 1. Java applications is a complete stand alone program that does not require a web browser. It is analogous to programs written in other programming languages. 2. Java is often described as a web programming language because of its use in writing programs called applets. Applets run in a web browser, i.e. a web browser is needed to execute Java applets. Applets allow more dynamic and flexible dissemination of information on the internet, and this feature alone makes Java an attractive language to learn.

JAVA PROGRAM STRUCTURE:


Documentation Section <--Suggested Package Statements <--Optional Import Statements <--Optional Interface Statements <--Optional Class Definition <--Optional Main Method Class { Main Method Definition <--Essential } 1. DOCUMENTATION SECTION: This section comprises a set of comment lines giving the name of the program, the author and other details, which the programmer would like to refer at later stages. E.g. /**.*/ - > Documentation comment. //.. - > Single or Multiline comment 2. PACKAGE STATEMENT: This statement declares a package name and informs the compiler that the classes define here belongs to this package. E.g.: package student; Default package is lang 3. IMPORT STATEMENTS: This statement instructs the interpreter to load a class contained in some other package. Mohammad Sufiyan [1] 160310737027

Java and Web Technologies Lab E.g.: import student.test; test is a class and student is a package. 4. INTERFACE STATEMENTS: An interface is like a class but includes a group of method declarations. This implements a multiple inheritance feature in Java.

DCET

5. CLASS DEFINITIONS: Classes are the primary and essential elements of a Java Program. A Java program may contain a multiple class definition. 6. MAIN METHOD CLASS: Every stand-alone program in Java requires a main method as its starting point. This is essential part in Java. The main method creates objects of various classes and established communications between them. On reaching the end of the main, the program terminates and control passes back to the operating system.

7. MAIN METHOD DEFINITION: public static void main (String args[]) : This statement defines a method main( ). This is the starting point for the interpreter to begin the execution of the program. public:This is the access specifier, which declares the main method as unprotected and therefore making it accessible to all other classes. static: This keyword declares the main method as one that belongs to the entire class and not a part of any objects of the class. The main () method must always be declared as static, since the interpreter uses this method before any objects are created. void: The type modifier void states that the main method does not return any value. String args[]: String is a class which declares a parameter named as args, which is an array of instances of the class String. args receives any command line arguments present when the program is created. out: out is an output stream connected to the console. System is a predefined class that provides access to the system

Mohammad Sufiyan

[2]

160310737027

Java and Web Technologies Lab

DCET

Typical Java development environment:


Phases Using Storage Description

Phase I : Edit

Editor

Disk

Program is created in an editor and stored on disc in a file ending with .java as an extension. The editor here is a notepad.

Phase II : Compile

Compiler

Disk

Compiler creates bytecodes and stores them on disc in a file ending with .class as an extension.

Class loader reads .class files containing bytecodes Phase III : Load Loader Primary Memory from disc and put those byte codes in memory.

Phase IV : Verify

Byte code Primary Verifier Memory

Bytecode verifier confirms that all bytecodes are valid & do not violate Javas security restrictions.

Phase V : Execute

Java Virtual Machine (JVM)

Primary Memory

To execute the program, the Java Virtual Memory (JVM) reads bytecodes and translates them into a computer language understandable by the computer. As the program execute, it may store data values in primary memory.

Mohammad Sufiyan

[3]

160310737027

Java and Web Technologies Lab

DCET

Steps in writing, compiling & running Java Application Programs:


1. Write Java programs in a note pad. 2. Create a folder in D drive by your roll number i.e. 03095001. 3. After writing save all the programs in the folder created, with .java as an extension. 4. Open the command prompt by typing cmd in Run window. 5. Change the directory to the directory in which the program is stored. C:\>D: D:\>cd ITJAVA 4. Start compiling D:\ITJAVA> javac <filemanme>.java 5. Always remember to save the program with same name as that of class name. For Example: class Example { // } Should be saved with Example.java in the folder. 6. While using multiple classes, class name which include the main method should be the name of the file for saving the program.

For Example: class Sample { Public static void main (String args[]) } class Example { // } Should be saved with Sample.java 7. Always remember to write the class name with its first alphabet in capital letters and stored the file with the same name.

Mohammad Sufiyan

[4]

160310737027

Java and Web Technologies Lab

DCET

1.A SIMPLE JAVA PROGRAM


Program:
/**Program demonstrating simple java program*/ /**Welcome.java*/ class Welcome { public static void main(String args[]) { System.out.print("Hello"); System.out.println("welcome to the world of"); System.out.print("JAVA"); } }

OUTPUT

Description of the program:


This program displays a simple message upon execution. The class name is Welcome and consists of the main( ) method, which in turn consists of the print ln( ) method used for displaying the output. The println( ) method is preceded with System.out which indicates that the println( ) method is present inside the System class and used with the out object.

Mohammad Sufiyan

[5]

160310737027

Java and Web Technologies Lab

DCET

2. DEMONSTRATION OF TYPE PROMOTION & TYPE CASTING

(a) Automatic conversion of data types. (b) Demonstrating type casting.


It is fairly common to assign a value of one type to a variable of another type. If the two types are compatible, then java will perform the conversion automatically, but if the conversion is between two different types of compatibility, that is the two variables are not compatible then explicit conversion is perform between incompatible types. This explicit conversion is called cast. Other name of automatic conversion is widening conversion and of casting is narrowing conversion.

(a) Javas automatic conversion: Two conditions are met while performing automatic conversion: 1) The two types must be compatible. 2) The destination is larger than the source type.

Type promotion rules:


1. 2. 3. 4. All byte, short, and char values are promoted to int. If one operand is long, the entire expression is promoted to long: If one operand is float, the entire expression is promoted to float. If any of the operand is double , the result is double.

Mohammad Sufiyan

[6]

160310737027

Java and Web Technologies Lab

DCET

(A).TYPE PROMOTION
Program: /**Demostration of type promotion*/ /**Promote.java*/ class Promote { public static void main(String args[]) { byte b=42; char c='a'; short s=1024; int i=500000; float f=5.67f; double d=0.1234,result; result=(f*b)+(i/c)-(d*s); System.out.println("result is="+result); } }

OUTPUT:-

Mohammad Sufiyan

[7]

160310737027

Java and Web Technologies Lab

DCET

Description of the program:


This program is used for demonstrating automatic conversion. Take a closer look at the expression: Result = (f *b) + i/c d * s; Here: in (f*b), b is promoted to float and the result of the sub expression is float. In (i/c), c is promoted to int and the result of the sub expression is of type int In (d*c), c is promoted to double, and the result of the sub expression is of type double. Finally these three intermediate values float, int, double are considered. The output of float plus int is a float. Then the resultant float minus the last double is promoted to double which is the type for the final result.

Mohammad Sufiyan

[8]

160310737027

Java and Web Technologies Lab

DCET

(B).TYPE CASTING
Program: /**Demonstration of type casting*/ /**Casting.java*/ class Casting { public static void main(String args[]) { System.out.println("variable created"); byte b=60; short s=1991; int i=123456789; long l=1234567654321l; float f1=3.14f,n1; System.out.println("s="+s); System.out.println("i="+i); System.out.println("f1="+f1); System.out.println("l="+l); System.out.println(" "); System.out.println("type connected"); short s1=(short)b; short s2=(short)i; n1=(float)l; int n2=(int)f1; System.out.println("byte connected to short is:"+s1); System.out.println("int connected to short is:"+s2); System.out.println("long connected to float is:"+n1); System.out.println("float connected to int is:"+n2); i=(byte)b; System.out.println("double connected to byte is:"+i); } }

Mohammad Sufiyan

[9]

160310737027

Java and Web Technologies Lab

DCET

OUTPUT

Description of the program:


This program demonstrates type casting of variables that are declared in the main method, i.e., b, s, I & f1. All the values assigned to the above variables are printed in the output first. The next step is converting byte and int values to short and long value to float and also converting float value to int. The resultant output is displayed by using the last four statement of println ( ) method.

Mohammad Sufiyan

[10]

160310737027

Java and Web Technologies Lab

DCET

3.DEMONSTRATION OF CLASSES AND METHODS


A class usually consists of two things: instance variables and methods. Methods are powerful and flexible in JAVA. Methods can be used in two ways: (a)Methods that return values and (b)Methods that take parameters.

(a) Methods that return values:


Methods that have return type other than 'void' , return a value to the calling routine using the following general form: type name () { return value; } Here, 'value', is the value to be returned.

(b) Methods that take parameters: General form of a method:


type name(parameter_list) { //body of method } Here , 'type' specifies the type of data returned by the method. This can be any valid type, including the classes that are created. If the method does not return any value its return type is 'void'. 'name' specifies the name of the method which is a legal identifier. 'parameter_list' is a sequence of type & identifier pairs separated by commas. A parameter is a variable defined by a method that receives a value when the method is called. An argument is a value that is passed to a method when it is invoked.

Mohammad Sufiyan

[11]

160310737027

Java and Web Technologies Lab

DCET

Program: /**Demonstration of classes and method*/ /**ClassMeth.java*/ class Box { double width; double height; double depth; double volume() { return width*height*depth; } void setDim(double w,double h,double d) { width=w; height=h; depth=d; } } class ClassMeth { public static void main(String args[]) { double vol1,vol2; Box obj1=new Box(); Box obj2=new Box(); obj1.setDim(10,20,30); obj2.setDim(3,6,9); System.out.print("volume of 1st box"); vol1=obj1.volume(); System.out.println(vol1); vol2=obj2.volume(); System.out.println("volume of 2nd Box"+vol2); } }

Mohammad Sufiyan

[12]

160310737027

Java and Web Technologies Lab

DCET

OUTPUT

Description of the program:


This program consists of the Box class and ParamMeth class. The Box class consists of the instance variables width, height & depth, a method volume(), to compute the volume of the box & return the values to the calling routine and another method SetDim() with parameters w, h & d of type double. These parameters are assigned to width, height & depth respectively, when the SetDim() method is called from the "ParamMeth" class with arguments in it.

Mohammad Sufiyan

[13]

160310737027

Java and Web Technologies Lab

DCET

4. DEMONSTRATION OF CONSTRUCTORS
JAVA allows objects to initialize themselves when they are created. This automatic initialization is performed through the use of a constructor. A constructor initializes an object immediately upon creation. It has the same name as that of the class in which it resides & is syntactically similar to a method, with a difference that constructors do not have return type not even void because its implicit return type is its class type itself. Once defined, the constructor is automatically called immediately, after the object is created, before the "new" operator completes. If a constructor is not defined explicitly for a class, then JAVA creates a default constructor for the class. The default constructor automatically initializes all instance variables to zero. General form of constructor: class <classname> { <classname>() { //body of the constructor } } Constructors can take two forms: 1. Normal Constructors 2. Parameterized Constructors Normal Constructors are the constructors that do no have parameters in it.

Parameterized Constructors are used in situations where default constructors


not required, instead values are passed as arguments upon calling a constructor during the creation of an object with the help of "new" operator.

Mohammad Sufiyan

[14]

160310737027

Java and Web Technologies Lab

DCET

Program:
/**Demonstration of constructors*/ /**ConstDemo.java*/ class Box { double width,height,depth; Box() { System.out.println("constructing 1st Box"); width=height=depth=20; } Box(double w,double h,double d) { width=w; height=h; depth=d; } double volume() { return width*height*depth; } } class ConstDemo { public static void main(String args[]) { double vol1,vol2; Box obj1=new Box(); vol1=obj1.volume(); System.out.println("volume of box1 is"+vol1); Box obj2=new Box(3,6,9); System.out.println("Constructing 2nd Box"); vol2=obj2.volume(); System.out.println("volume of Box2 is "+vol2); } }

Mohammad Sufiyan

[15]

160310737027

Java and Web Technologies Lab

DCET

OUTPUT

Description of the program:


This program demonstrates the use of normal constructors, i.e., constructors with no parameters and constructors with parameters. In class "Box", a constructor "Box()" is defined which assigns values to width, height & depth inside its block. This class also consists of the method volume() to compute the volume of the boxes & return the value. Most constructors will not display anything, the println() statement inside Box() constructor is for illustration sake only. Once the object or objects of the Box class is created, the respective constructor is called, here the Box() constructor assigns '10' to all the variables. The volume() method is invoked by the object of Box class to compute the volume & the value is displayed at the output.

Mohammad Sufiyan

[16]

160310737027

Java and Web Technologies Lab

DCET

5. DEMONSTRATION OF OVERLOADING CONCEPT


Method Overloading. Constructor Overloading.

METHOD OVERLOADING:
Two or more methods with same name , within the same class but with different parameter declarations are said to be overloaded and the process is known as Method Overloading. Method Overloading is one of the ways that java supports Polymorphism. When an overloaded method is invoked , java uses the type and/or no. of arguments as its guide to determine which overloaded method to actually call . Thus overloaded methods should differ in Type , No. of parameters , Return types. Method overloading supports polymorphism because it is the only way java implements one interface , multiple methods paradigm . There is no rule that overloaded methods must relate to one another , but in practice methods should be overloaded in closely related operations.

ADVANTAGES OF METHOD OVERLOADING:


1) Makes the program more readable and understandable. 2) Eliminates the use of different methods for same operation. That is, several names are reduced to one. 3) Achieve greater flexibility in program. 4) Manage greater complexity.

Mohammad Sufiyan

[17]

160310737027

Java and Web Technologies Lab

DCET

(A).METHOD OVERLOADING Program:


/**Program to demonstrate method overloading*/ /**OverloadMeth.java*/ class Overload { void test() { System.out.println("there are no parameters"); } void test(int a) { System.out.println("value of a is"+a); } void test(int a,int b) { System.out.println("a&b are:"+a+"&"+b); } double test(double a) { System.out.println("value of a for double is:"+a); return a*a; } } class OverloadMeth { public static void main(String args[]) { Overload obj=new Overload(); double result; obj.test(); obj.test(20); obj.test(10,20); result=obj.test(123.25); System.out.println("result is:"+result); } }

Mohammad Sufiyan

[18]

160310737027

Java and Web Technologies Lab

DCET

OUTPUT

Description of the program:


In the above program test( ) is overloaded 4 times , 1- for no parameters , 2- 2 for one integer parameter , 3- 3 for 2 integer parameters and 4- 4 for double type of one parameter

Mohammad Sufiyan

[19]

160310737027

Java and Web Technologies Lab

DCET

(B).CONSTRUCTOR OVERLOADING
Program: /**Program demonstrating constructors overloading*/ /**OverloadConst.java*/ class Box { double width,height,depth; Box(double w,double h,double d) { width=w; height=h; depth=d; } Box() { width=height=depth=2; } Box(double len) { width=height=depth=len; } double volume() { return width*height*depth; } } class OverloadConst { public static void main(String args[]) { Box objc1=new Box(); Box objc2=new Box(3,9,81); Box objc3=new Box(12); System.out.println("volume of 1st box is"+objc1.volume()); System.out.println("volume of 2nd box is"+objc2.volume()); System.out.println("volume of 3rd box is"+objc3.volume()); } }

Mohammad Sufiyan

[20]

160310737027

Java and Web Technologies Lab

DCET

OUTPUT

Description of the program:


From the above program , the proper overloaded constructor is called based upon the parameters when new is executed .

Mohammad Sufiyan

[21]

160310737027

Java and Web Technologies Lab

DCET

6. DEMONSTRATION OF ARGUMENT PASSING


There are two ways a computer language can pass arguments to a subroutine: 1) Call by value. 2) Call by reference.

1) Call by value : This approach copies the value of an argument into the formal
parameter of subroutine. Therefore changes made to the parameter of the subroutine have no effect on the argument. When a primitive type is passed to a method it is done by call by value.

2) Call by reference :
In this approach, reference to an argument (not the value of the argument) is passed to the parameter. Inside the subroutine, this reference is used to access the actual argument specified in the call. This means that changes made to the parameter will affect the argument used to call the subroutine. When an object is passed to a method , the situation changes dramatically , because objects are passed by call by reference . When a variable of a class type is created , you are creating a reference to an object . Thus when a reference to a method is called , the parameter that receives it will refer to the same object as that referred to by the argument .This effectively means that objects are passed to methods by use of call by reference . Changes to the object inside the method affect the object used as an argument .

Mohammad Sufiyan

[22]

160310737027

Java and Web Technologies Lab

DCET

(A).CALL BY VALUE
Program: //**program demonstrating call by value*/ //**CallByValue.java*/ class Test { void meth(int i,int j) { i*=2; j/=2; } } class CallByValue { public static void main(String args[]) { int a=45,b=90; Test obj=new Test(); System.out.println("value of a and b before call is:"+a+"and"+b+"respectively"); obj.meth(a,b); System.out.println("value of a and b after call is "+a+"and"+b+"respectively"); } }

OUTPUT

Mohammad Sufiyan

[23]

160310737027

Java and Web Technologies Lab

DCET

Description of the program:


From the program operation that occurs inside meth( ) have no effect on the values of a and b used in the call , if there was any effect then their values would have changed to 30 and 10 respectively , but this did not happen .

Mohammad Sufiyan

[24]

160310737027

Java and Web Technologies Lab

DCET

(B).CALL BY REFERENCE
Program: /**Program to demonstrate call by reference*/ /**CallByReference.java*/ class Test { int a,b; Test(int i,int j) { a=i; b=j; } void meth(Test t) { t.a*=2; t.b/=2; } } class CallByReference { public static void main(String args[]) { Test obj=new Test(25,50); System.out.println("value of a&b before call"+obj.a+"&"+obj.b); obj.meth(obj); System.out.println("value of a&b after call"+obj.a+"&"+obj.b); } }

Mohammad Sufiyan

[25]

160310737027

Java and Web Technologies Lab

DCET

OUTPUT

Description of the program:


From the above program actions performed in meth( ) have affected the object used as an argument .

Mohammad Sufiyan

[26]

160310737027

Java and Web Technologies Lab

DCET

7. DEMONSTRATION OF COMMAND LINE ARGUMENTS:


Sometimes there will be needs to pass information into a program while it is run. This is accomplished by passing command line arguments to main ( ). A command line argument is the information that directly follows the programs name on the command line when it is executed. Command line arguments are stored (and passed) as strings in a String array passed to the args parameter of main( ). The first command line argument is stored at args [0], and so on .

PROGRAM:/**Program to demonstrate command line arguments*/ /**CmdlineTest.java*/ class CmdlineTest { public static void main(String args[]) { int count,i=0; String xyz; count=args.length; System.out.println("no. of arguments="+count); while(i<count) { xyz=args[i]; i=i+1; System.out.println(i+":"+"java is "+xyz+"!"); } } }

Mohammad Sufiyan

[27]

160310737027

Java and Web Technologies Lab

DCET

OUTPUT

Mohammad Sufiyan

[28]

160310737027

Java and Web Technologies Lab

DCET

8. DEMONSTRATION OF INHERITANCE
INHERITANCE: This is one of the aspects of OOP paradigm. Def: Mechanism of deriving a new class from an old class is called Inheritance.
The old class is known as base class (or) super class (or) parent class. The new class is called derived class (or) sub class (or) child class.

Inheritance allows subclasses to inherit all the variables and methods of their of
their parent classes.

Different forms of inheritance:


1) Single Inheritance (only one super class & one sub class) A

2) Multilevel Inheritance (derived from a derived class) A

3) Hierarchical Inheritance (one super class many sub classes)

Mohammad Sufiyan

[29]

160310737027

Java and Web Technologies Lab 4) Multiple Inheritance (Several super classes) ( not supported by Java directly)

DCET

Class A

Interface B

derived class C Java does not directly implements multiple inheritance. This concept is implemented using the concept of interfaces. To inherit a class , extends keyword is used.

Syntax for defining a subclass:


class subclassname extends superclassname { Variable declaration; Methods declaration; } The keyword extends specifies that the properties of superclass are extended (inherited) by the subclass.

ADVANTAGE OF INHERITANCE : Once if a superclass is created that defines the


attributes common to a set of objects, it can be used to create any number of more specific subclasses. Each subclass can precisely tailor its own classification.

Mohammad Sufiyan

[30]

160310737027

Java and Web Technologies Lab

DCET

(A).SINGLE INHERITANCE
Program: //**program to demonstrate single inheritance*/ class A { int i,j; void showij() { System.out.println("i & j are "+i+" & "+j); } } class B extends A { int k; void showk() { System.out.println("k is "+k); } void sum() { System.out.println("i+j+k is "+(i+j+k)); } } class SimpleInherit { public static void main(String args[]) { A superobj=new A(); B subobj=new B(); superobj.i=18; superobj.j=54; System.out.println("contents of super class"); superobj.showij(); System.out.println(); subobj.i=43; subobj.j=44; subobj.k=45; System.out.println("contents of subclass:"); subobj.showij(); subobj.showk(); System.out.println("addition is:"); subobj.sum(); } }

Mohammad Sufiyan

[31]

160310737027

Java and Web Technologies Lab

DCET

OUTPUT

Description of the program:


From the program , it is seen that , inside sum() method , I & j can be referred to directly , as if they are part of B, because B inherits all the properties of A.

Mohammad Sufiyan

[32]

160310737027

Java and Web Technologies Lab

DCET

(B).USE OF SUPER KEYWORD


Program: //**UseSuper.java*/ class A { int i; A() { System.out.println("this is A's constructor"); } } class B extends A { int i; B() { super(); System.out.println("this is B's constructor"); } B(int a,int b) { super.i=a; i=b; } void show() { System.out.println("value of i in superclass"+super.i); System.out.println("valueo f i in subclass"+i); } } class UseSuper { public static void main(String args[]) { B subobj1=new B(); B subobj2=new B(45,55); subobj2.show(); } }

Mohammad Sufiyan

[33]

160310737027

Java and Web Technologies Lab

DCET

OUTPUT

Description of the program:


Although the instance variable i in B hides the i in A, super allows access to the i defined in the superclass. super can also be used to call methods that are hidden by a subclass.

Mohammad Sufiyan

[34]

160310737027

Java and Web Technologies Lab

DCET

(C).MULTILEVEL INHERITANCE
Consider three classes A, B & C , for multilevel inheritance A is a suoerclass for B and B is again a superclass for C. Therefore C inherits all the aspects of B & A. Program: //**program to demonstrate multilevel inheritance*/ class A { A() { System.out.println("this is A's constructor"); } } class B extends A { B() { System.out.println("this is B's constructor"); } } class C extends B { C() { System.out.println("this is C's constructor"); } } class MultiInherit { public static void main(String args[]) { C obj=new C(); } }

Mohammad Sufiyan

[35]

160310737027

Java and Web Technologies Lab

DCET

OUTPUT

Mohammad Sufiyan

[36]

160310737027

Java and Web Technologies Lab

DCET

(D).HIERARCHICAL INHERITANCE
Hierarchical inheritance is one superclass and multiple subclasses. Program: /**Program to demonstrate hierarchical inheritance*/ class A { void callme() { System.out.println("this is A's call method"); } } class B extends A { void callme() { System.out.println("this is B's call method"); } } class C extends A { void callme() { System.out.println("this is C's call method"); } } class HierarcInherit { public static void main(String args[]) { A obja=new A(); B objb=new B(); C objc=new C(); A objr; objr=obja; objr.callme(); objr=objb; objr.callme(); objr=objc; objr.callme(); } }

Mohammad Sufiyan

[37]

160310737027

Java and Web Technologies Lab

DCET

OUTPUT

Mohammad Sufiyan

[38]

160310737027

Java and Web Technologies Lab

DCET

(E).MULTIPLE INHERITANCE VIA INTERFACE


Program: /**Program to demonstrate multiple inheritance via interface*/ interface i1 { public void i(); } class A { public void a() { System.out.println("i m in a"); } } class B extends A implements i1 { public void i() { System.out.println("i m in b and came from interface i1"); } } class MultipleInherit { public static void main(String args[]) { A x=new A(); B y=new B(); y.a(); y.i(); } }

Mohammad Sufiyan

[39]

160310737027

Java and Web Technologies Lab

DCET

OUTPUT

Mohammad Sufiyan

[40]

160310737027

Java and Web Technologies Lab

DCET

9. DEMONSTRATION OF METHOD OVERRIDING


In a class hierarchy, when a method in a subclass has the same name and type signature as method in the superclass, then the method in the subclass is said to override the method in the superclass. When an overridden method is called from a subclass, it will always refer to the version of that method defined by the subclass .The version of the method defined by the superclass will be hidden. Program: /**Demonstration of method overriding*/ class A { int i,j; A(int a,int b) { i=a; j=b; } void show() { System.out.println("i & j are "+i+"& "+j); } } class B extends A { int k; B(int a,int b,int c) { super(a,b); k=c; } void show() { super.show(); System.out.println("k is "+k); } } class MethOveride { public static void main(String args[]) { B subobj=new B(1,2,3); subobj.show(); } }

Mohammad Sufiyan

[41]

160310737027

Java and Web Technologies Lab

DCET

OUTPUT

Description of the program:


Here super.show( ) calls the superclass version of show( ) .And when show ( ) is invoked on object of type B , the version of show ( ) defined within B is called . That is , the version of show( ) inside B overrides the version of show( ) inside A. Method overriding can be prevented using super keyboard.

Mohammad Sufiyan

[42]

160310737027

Java and Web Technologies Lab

DCET

10. DEMONSTRATION OF DYNAMIC POLYMORPHISM:

DYNAMIC POLYMORPHISM
It is a mechanism by which a call to an overrided method is resolved at run time , rather than compile time . Its the type of object being referred to and not the type of reference variable , that determines which version of an overridden method will be executed. Advantages of dynamic polymorphism is that it implements concept of reusability and robustness of the code . Program: /**demonstration of dynamic polymorphism*/ class Figure { double dim1,dim2; Figure(double a,double b) { dim1=a; dim2=b; } double area() { System.out.println("area for figure is not defined"); return 0; } } class Rectangle extends Figure { Rectangle(double a,double b) { super(a,b); } double area() { System.out.println("this is rectangle"); return dim1*dim2; } } class Triangle extends Figure { Triangle(double a,double b) { super(a,b); } double area() { System.out.println("this if for triangle"); Mohammad Sufiyan [43] 160310737027

Java and Web Technologies Lab return dim1*dim2/2; } } class DynPoly { public static void main(String args[]) { Figure f=new Figure(10,10); Rectangle r=new Rectangle(9,5); Triangle t=new Triangle(10,8); Figure figref; figref=r; System.out.println("area is "+figref.area()); figref=t; System.out.println("area is "+figref.area()); figref=f; System.out.println("area is "+figref.area()); } }

DCET

OUTPUT

Mohammad Sufiyan

[44]

160310737027

Java and Web Technologies Lab

DCET

11. DEMONSTRATION OF ABSTRACT CLASSES


Java allows us to do something that is exactly opposite to final , i.e., methods declared as abstract should compulsorily overridden. Abstract methods are declared usinga type modifier abstract Abstract methods are sometime referred as a subclasses responsibility

General form :
abstract type name( parameter list ); There can be no objects for an abstract class, i.e., an abstract class cannot be instantiated directly with new operator. Such objects would be useless because an abstract class is not fully defined . Abstract constructor or abstract static methods cannot be declared . Any subclass of an abstract class must either implement all of the abstract methods in the superclass , or be itself declared abstract . Program /**program to demonstrate abstract classes*/ abstract class A { abstract void callme(); void callmetoo() { System.out.println("this is a concrete method"); } } class B extends A { void callme() { System.out.println("B's implementation of call me"); } } class AbstractDemo { public static void main(String args[]) { B bobj=new B(); bobj.callme(); bobj.callmetoo(); } }

Mohammad Sufiyan

[45]

160310737027

Java and Web Technologies Lab

DCET

OUTPUT

Description of the program:


No objects of class A are declared in the program. Class A implements a concrete method called callmetoo ( ).This is pearfectly acceptable. Although abstract classes cannot be used to instantiate objects, they can be used to create object references, because Javas approach to run time polymorphism is implemented through the use of superclass reference. Thus, it must be possible to create a reference to an abstract class so that it can be used to point to a subclass object.

Mohammad Sufiyan

[46]

160310737027

Java and Web Technologies Lab

DCET

12. DEMONSTRATION OF PACKAGES:


Packages are containers for classes that are used to keep the class name space compartmentalized. Packages are stored in a hierarchical manner and are explicitly imported in to new class definitions. For example : A package allows creation of a class named List, which can be stored in a particular package without concern that it will collide with some other class named with the same name List stored elsewhere .

Defining A Package :
To create a package include a package command as the first statement in a Java source file . Any classes declared within that file will belong to the specified package . If the package statement is omitted, then the class names are put into default package which has no name. The default package is fine for short programs but it is inadequate for real applications. The general form of package statement : Package <pkg_name>; for example :package MyPackage; Creates a package with the name MyPackage. Java uses file system directories to store packages. The directory name must match the package name exactly. More than one file can include the same package statement. The package statement simply specifies to which package the classes defined in a file belong. A hierarchy of packages can also be created. General form of a multilevel package statement is: package pkg1[.pkg2[.pkg3]];

Mohammad Sufiyan

[47]

160310737027

Java and Web Technologies Lab Program: package MyPack; class Balance { String name; double bal; Balance(String n,double b) { name=n; bal=b; } void show() { if(bal<0) System.out.println("---->"); System.out.println(name+"$ " +bal); } } class AccountBal { public static void main(String args[]) { Balance current[]=new Balance[3]; current[0]=new Balance("XYZ",123.23); current[1]=new Balance("ABC",157.02); current[2]=new Balance("HIJ",-12.33); for(int i=0;i<3;i++) current[i].show(); } }

DCET

OUTPUT

Mohammad Sufiyan

[48]

160310737027

Java and Web Technologies Lab

DCET

13. DEMONSTRATION OF CREATING A THREAD


A thread can be created by instantiating and object of type Thread. Java defines two ways of creating a thread: a) Creating a thread by implementing Runnable interface. b) Creating a thread by extending a Thread class.

(A).BY IMPLEMENTING RUNNABLE INTERFACE


Program: /**Creating thread by implementing Runnable INTERFACE*/ class NewThread implements Runnable { Thread t; NewThread() { t=new Thread(this,"demothread"); System.out.println("child thread"+t); t.start(); } public void run() { try { for(int i=5;i>0;i--) { System.out.println("child thread"+i); Thread.sleep(500); } } catch(InterruptedException e) { System.out.println("child interrupted"); } System.out.println("exit from child threads"); } } class ThreadDemoRunnable { public static void main(String args[]) { new NewThread(); try { for(int i=5;i>0;i--) { Mohammad Sufiyan [49] 160310737027

Java and Web Technologies Lab System.out.println("main thread"+i); } Thread.sleep(1000); } catch(InterruptedException e) { System.out.println("main thread interrupted"); } System.out.println("exit from main thread"); } }

DCET

OUTPUT

Mohammad Sufiyan

[50]

160310737027

Java and Web Technologies Lab

DCET

Descrption of the program:


There are two classes define in this program : NewThread class which consist of the code for starting the new thread , and ThreadDemoRunnable class which is the main class that spawned the new child thread by following statement : new NewThread( ) ; With this above statement the constructor for NewThread is invoked ,which creates a new Thread object by the following statement : t = new Thread (this , DemoThread ); Passing this as the first argument specifies that the user wants the new Thread to call run( ) method on this object. Next ,start( ) method is called , which starts the thread of execution beginning at the run( ) method. After calling the start( ) method , the control comes out of the NewThreads constructor and returns to the main( ) methods next line i.e ., the try block which consist of the for loop . Main thread is then resumed and start displaying the output. When this main thread invokes sleep( ) method ; it leaves the CPU for 1 second and the CPU time is utilized by the child thread . Both the threads continue running , sharing the CPU , until their loop gets terminated. The output may vary based on processor speed and task

Mohammad Sufiyan

[51]

160310737027

Java and Web Technologies Lab

DCET

(b). CREATING THREAD BY EXTENDING Thread CLASS


The second way to create a thread is to 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 enrty point for the new thread. It must also call start ( ) method to begin executing of the new thread. Program: /**Creating thread by extending thread class*/ class NewThread extends Thread { Thread t; NewThread() { super("demo thread"); System.out.println("child thread"+this); start(); } public void run() { try { for(int i=5;i>0;i--) { System.out.println("child thread"+i); Thread.sleep(500); } } catch(InterruptedException e) { System.out.println("child thread interrupted"); } System.out.println("exit from child thread"); } } class ThreadDemoThread { public static void main(String args[]) { new NewThread(); try { for(int i=5;i>0;i--) { System.out.println("mainthread"+i); } Thread.sleep(10000); Mohammad Sufiyan [52] 160310737027

Java and Web Technologies Lab } catch(InterruptedException e) { System.out.println("main thread interrupted"); } System.out.println("exit from main thread"); } }

DCET

OUTPUT

Description of the program:


In this program, the class New Thread extends th Thread class so as to create a new thread. The child thread is created in the main() method by instantiating an object of NewThread class which is derived from Threadclass,because of this ,any reference to thread is not created ,instead a method of Thread class can be directly accessed from its derived class . The super( ) constructor inside the NewThread class invokes the following form of Thread constructor: public Thread(String thrd Name) Here ,thrd Name specifies the name of the thread .The control of this program runs in the same way as that of the preceding program which implements Runnable interface for creation of thread.

Mohammad Sufiyan

[53]

160310737027

Java and Web Technologies Lab

DCET

14. DEMONSTRATION OF CREATING MULTIPLE THREADS


Java program can spawn as many threads as needed by the java programmers. This concept ensures the multithreading criteris in java. The program below demonstrates the concept of multiple threads.This program creates three different threads:

Program: //**demonstration of creating multiple Threads*/ class NewThread implements Runnable { String name; Thread t; NewThread(String threadname) { name=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 MultipleThreadDemo { public static void main(String args[]) { new NewThread("one"); new NewThread("two"); new NewThread("three"); try { Mohammad Sufiyan [54] 160310737027

Java and Web Technologies Lab Thread.sleep(10000); } catch(InterruptedException e) { System.out.println("main thread interrupted"); } System.out.println("main thread exiting"); } }

DCET

OUTPUT

Description of the program:


This program generates three threads T-One,T-Two,T-Three from the main thread .And till the main thread is sleeping for 10 seconds ,all these three child threads share the CPU among themselves. The call to sleep() method in main ensures that the main() method will finish or terminate last.

Mohammad Sufiyan

[55]

160310737027

Java and Web Technologies Lab

DCET

15. DEMONSTRATION OF THREAD SYNCHRONIZATION:


When two or more threads need access to a shared resource, they need some way to ensure that a resource will be used only by one thread at a time . The process by which this is achieved is called Synchronization. Key to synchronization is the concept of the monitor or Semaphore.

Definition: A monitor is an object that is used as a mutually exclusive lock (or mutex).
Only one thread can own a monitor at a given time. When a thread acquires a lock, it is said to have entered the monitor. All other threads attempting to enter the locked monitor will be suspended until the first thread exits the monitor. These other threads are said to be waiting for the monitor. A thread that owns a monitor can re-enter the same monitor if it so desires. Since Java implements synchronization through language elements, most of the complexity associated synchronization has been eliminated.

(a) Using Synchronisation With Methods :


Synchronisation is easy in Java , because all objects have their own implicit monitor associated with them . To enter an objects monitor , just call a method that has been modified with the synchronized keyword . While the thread is inside a synchronized method , all other threads that try to call it (or any other synchronized method) an the same instance have to wait .To exit the monitor or relinquish control of the object to the next waiting thread , the owner of the monitor simply return from the synchronized method .

(b) Using Synchronisation With block of codes or statements:


This is used when there are situations where user need to synchronize the call to predefined methods present in some other package that cannot be modified. For this the statement that calls the method will be preceeded by the synchronized keyword.

Mohammad Sufiyan

[56]

160310737027

Java and Web Technologies Lab

DCET

(A).SYNCHRONIZING METHODS
Program: class CallMe { synchronized void callmeth(String msg) { System.out.print("["+msg); try { Thread.sleep(1000); } catch(InterruptedException e) { System.out.println("Thread interrupted"); } System.out.println("]"); } } class Caller implements Runnable { String msg; CallMe target; Thread t; public Caller(CallMe targ,String s) { this.target=targ; msg=s; t=new Thread(this); t.start(); } public void run() { target.callmeth(msg); } } class SynchMeth { public static void main(String args[]) { CallMe target=new CallMe(); Caller obj1=new Caller(target,"hello"); Caller obj2=new Caller(target,"synchronized"); Caller obj3=new Caller(target,"world"); try { obj1.t.join(); obj2.t.join(); Mohammad Sufiyan [57] 160310737027

Java and Web Technologies Lab obj3.t.join(); } catch(InterruptedException e) { System.out.println("interrupted"); } } }

DCET

OUTPUT

Descrition of the program:


This program consist of three classes Callme, SynchMeth and Caller class . The caller class creates a thread and inside the run ( ) method calls the method callmeth( ) by invoking it with the parameter msg, which inturn is provided by the main class SynchMeth. By calling the callmeth( ) method and sleep( ) methods , execution switches from one thread to another thread , resulting in the mixed-up output of the three message strings . When synchronization is not used , there exists no way for stopping all the threads from calling the same method on the same object ,at the same time . This condition is known as Race Condition, because the three threads are racing eachother to complete the method. This program uses sleep ( ) method to make the effects repeatable and abvious. In most situations, a race condition is more subtle and less predictable, because context switch may occur at any time. This causes the program to run right one time and wrong the next time. To fix this problem synchronization is provided. Using synchronized keyword near callmeth () method prevents other threads from entering this method, while another thread is using it.

Mohammad Sufiyan

[58]

160310737027

Java and Web Technologies Lab

DCET

(B)SYNCHRONIZING OBJECTS
Program: /**Using Synchronisation with block of code or statements*/ class CallMe { void callmeth(String msg) { System.out.print("["+msg); try { Thread.sleep(1000); } catch(InterruptedException e) { System.out.println("thread interrupted"); } System.out.println("]"); } } class Caller implements Runnable { String msg; CallMe target; Thread t; public Caller(CallMe targ,String s) { this.target=targ; msg=s; t=new Thread(this); t.start(); } public void run() { synchronized(target) { target.callmeth(msg); } } } class SynchBlock { public static void main(String args[]) { CallMe target=new CallMe(); Caller obj1=new Caller(target,"hello"); Caller obj2=new Caller(target,"synchronized"); Caller obj3=new Caller(target,"world"); Mohammad Sufiyan [59] 160310737027

Java and Web Technologies Lab try { obj1.t.join(); obj2.t.join(); obj3.t.join(); } catch(InterruptedException e) { System.out.println("interrupted"); } } }

DCET

OUTPUT

Mohammad Sufiyan

[60]

160310737027

Java and Web Technologies Lab

DCET

16.DEMONSTRATION OF DIRECTORIES USING FILENAMEFILTER INTERFACE


Program: import java.io.*; class OnlyExt implements FilenameFilter { String ext; public OnlyExt(String ext) { this.ext="."+ext; } public boolean accept(File dir,String name) { return name.endsWith(ext); } } class DirListOnly { public static void main(String args[]) { String dirname="/ITJAVA"; File f1=new File(dirname); FilenameFilter only=new OnlyExt("java"); String s[]=f1.list(only); for(int i=0;i<s.length;i++) { System.out.println(s[i]); } } }

Mohammad Sufiyan

[61]

160310737027

Java and Web Technologies Lab

DCET

OUTPUT

Mohammad Sufiyan

[62]

160310737027

Java and Web Technologies Lab

DCET

17.DEMONSTRATION OF BUFFEREDINPUTSTREAM CLASS


Program: import java.io.*; class BISDemo { public static void main(String args[])throws IOException { String s="This is a &copy; copyright symbol"+" but this is &copy not.\n"; byte buf[]=s.getBytes(); ByteArrayInputStream in=new ByteArrayInputStream(buf); BufferedInputStream f=new BufferedInputStream(in); int c; boolean marked=false; while((c=f.read())!=-1) { switch(c) { case '&':if(!marked) { f.mark(32); marked=true; } else { marked=false; } break; case ';':if(marked) { marked=false; System.out.print("(c)"); } else System.out.print((char)c); break; case ' ':if(marked) { marked=false; f.reset(); System.out.print("&"); } else System.out.print((char)c); break; default:if(!marked) System.out.print((char)c); Mohammad Sufiyan [63] 160310737027

Java and Web Technologies Lab break; } } } }

DCET

OUTPUT

Mohammad Sufiyan

[64]

160310737027

Java and Web Technologies Lab

DCET

EXPLORING java.util PACKAGE


THE COLLECTION INTERFACES
The collections frame work defines several interfaces which are summarized below:-

Interface hierarchy of Collections


Iterable

Collection

List

Set

Queue

Sorted set

Dequeue

Navigable Set

In addition to the above interfaces, there are some more interfaces that do not belong to the above hierarchy. They are listed below; Comparator defines how two objects are compared. Iterator List Iterator Random access - A list which implements this interface indicates that it support efficient, random access to its elements. Collection can be categorized as; [65] 160310737027 Enumerates the objects within a collection

1. 2. 3. 4.

Mohammad Sufiyan

Java and Web Technologies Lab Modifiable: Collections that support method used to modify their contents.

DCET

Unmodifiable: Collection that does not allow their contents to be changed is called unmodifiable collection. If an attempt is made to modify the contents of an unmodifiable collection an unsupported Operation Exception is thrown.

The Collection Interface:


This is the foundation upon which collections frame work is built. This is a generic interface and has the declaration; interface collection <E> E specifies the type of objects that the collection will hold. Collection extends the iterable interface. All collections implements Collection interface and its core methods.

The List interface:


The List interface extends the Collection interface and declares the behavior of a collection that stores a sequence of elements. Elements can be inserted are accessed by the position in the list, using the zero base index. A list may contain duplicate elements. This is a generic interface that has the declaration as; Interface List <E> Here E specifies the type of objects that the list will hold.

The Set interface;


This interface defines a set. It extends collection and declares the behavior a collection that does not allow duplicate elements. The add ( ) method returns false if an attempt is made to add duplicate elements to a set. It does not define any additional methods of its own. Set a generic interface which has the declaration as shown below: [66] 160310737027

Mohammad Sufiyan

Java and Web Technologies Lab Interface set <E>. here E specifies the type of objects that set will hold.

DCET

The SortedSet interface;


This interface extends set and declares the behavior of a set sorted in ascending order. This is a general interface and has the declaration as shown below: interface Sorted Set <E> here E specifies the type of objects that the set will hold.

The Navigable Set Interface;


This interface was added by jawa SE6. It extends Sorted Set and declares the behavior of a collection that support retrieval of elements based on the closest match to a given value or values. This is a generic interface and has the declaration as Interface Navigable Set <E>

The Queue Interface:


This interface extends collectionand declares the behavior of a queue which is often a first -in -first -out list. This is a generic interface that has this declaration

interface Queue<E> E specifies the type of objects that the set will hold.

The Dequeue Interface:


This interface was added by Java SE6. It extends Queue and declares the behavior of a double-ended Queue.

General declaration:
interface Dequeue<E> E specifies the type of objects that the set will hold. Mohammad Sufiyan [67] 160310737027

Java and Web Technologies Lab

DCET

The Array List Class:


This class extends the Abstract List class and implements the list interface. This class is a generic class and has a declaration as shown below: Class Array List <E> E specifies the type of objects the list will hold. Array List Class support dynamic arrays, i.e., after specifying a value during initialization of an array, it can be grown are shrink during the run time as required by the user. Array List is a variable length array of object references, it can be dynamically increased or decreased in size. Array lists are created with an initial size, when this size is exccded, the collection is automatically enlarged and when objects are removed, the array can be shrunk.

Mohammad Sufiyan

[68]

160310737027

Java and Web Technologies Lab

DCET

18.DEMONSTRATION OF COLLECTION CLASSES (A).LINKEDLIST CLASS


The Linked List Class:This class extends Abstract Sequential List class and implements the List, Deque and Queue interfaces. It provides a linked list data structure. Linked List is a generic class and has this declaration: class Linked List <E> E specifies the type of objects that the set will hold.

Program: /**Demonstrating th use of linked list class*/ import java.util.*; class LinkedlistDemo { public static void main(String args[]) { LinkedList<String> llist=new LinkedList<String>(); llist.add("A"); llist.add("B"); llist.add("C"); llist.addFirst("D"); llist.addLast("E"); System.out.println("original contents of linked list are:"+llist); llist.remove("B"); llist.remove("W"); System.out.println("linked list after removal is:"+llist); String val=llist.get(1); llist.set(1,val+"this is changed"); System.out.println("linked list after change is"+llist); } }

Mohammad Sufiyan

[69]

160310737027

Java and Web Technologies Lab

DCET

OUTPUT

Mohammad Sufiyan

[70]

160310737027

Java and Web Technologies Lab

DCET

(B).HASHSET CLASS
This class extends Abstractset class & implements the interface set. It creates a collection that used a hash table for storage. This is a generic class & has the declaration as shown below: class Hash Set <E> E-objects that list will hold. A hash table stores the information by using a mechanism call hashing. In hashing informational content of a key is used to determine a unique value, called its hash code. This hash code is used to as index at which the data associated with the key is stored. The transformation of the key into its hash code is performed automatically & implicitly. Program: /**demonstrating the use of Hashset class*/ import java.util.*; class HashSetDemo { public static void main(String args[]) { HashSet<String> hs=new HashSet<String>(); hs.add("B"); hs.add("A"); hs.add("D"); hs.add("E"); hs.add("C"); hs.add("F"); System.out.println(hs); } }

OUTPUT

Mohammad Sufiyan

[71]

160310737027

Java and Web Technologies Lab

DCET

(C).TREESET CLASS
This class extends the Abstract Set & implements the Navigable Set interface. It created a collection that uses a tree for storage. Objects are sorted in sorted, ascending order. Access & retrieval times are fast which makes this class an excellent choice when storing large amounts of sorted information that must be found quickly. This is a generic class that has the general declaration as follows: class TreeSet <E> E specifies the type of objects that the set will hold. Program: /**Demonstrating th use of Tree set class*/ import java.util.*; class TreeSetDemo { public static void main(String args[]) { TreeSet<String> ts=new TreeSet<String>(); ts.add("C"); ts.add("A"); ts.add("B"); ts.add("E"); ts.add("F"); ts.add("D"); System.out.println(ts); } }

OUTPUT

Mohammad Sufiyan

[72]

160310737027

Java and Web Technologies Lab

DCET

19. DEMONSTRATION OF ITERATORS:


ACCESSING A COLLECTION VIA AN ITERATOR: There are situation, where user want to cycle through the elements in a collection, for example: displaying each element. One way to fulfill this situation is to employ an iterator. iterator is an object that implements wither Iterator or ListIterator interface.

Iterator Interface:
This interface enables the user to cycle through the collection, obtain or remove elements. General declaration: interface Iterator <E> E specifies the type of objects that the set will hold. Using An Iterator By calling the method iterator ( ) which is present in all of the collection classes.

Iterator ( ) method returns an iterator to the start of the collection.

By using this iterator object, the element in the collection can be accessed one at a time.

1. 2. 3.

There are three important steps in obtaining the iterator & cycling through the elements of a collection. Obtain an iterator to the start of the collection by calling the collections integrator ( ) method. Setup a loop that makes a call to has Next ( ). Have the loop iterate as long as hasNext ( ) returns true. Within the loop, obtain each element by calling next ( ).

Mohammad Sufiyan

[73]

160310737027

Java and Web Technologies Lab

DCET

List Iterator Interface :


This interface extends Iterator interface. It allows bidirectional traversal of a list, & the modification of elements. List Iterator is a generic interface & has the general declaration as shown below: interface List Iterator <E>

Using an iterator can be obtained by calling a list iterator ( ) method. List Iterator is used just like Iterator, but only to those collections that implement List interface Program: /**Demonstration of iterators*/ import java.util.*; class IteratorDemo { public static void main(String args[]) { ArrayList<String> al=new ArrayList<String>(); al.add("C"); al.add("A"); al.add("E"); al.add("B"); al.add("D"); al.add("F"); System.out.println("original contents of array list;"+al); Iterator<String> itr=al.iterator(); while(itr.hasNext()) { String element=itr.next(); System.out.print(element+" "); } System.out.println(); ListIterator<String> litr=al.listIterator(); while(litr.hasNext()) { String element=litr.next(); litr.set(element+"+"); } System.out.print("modified contents of al:"); itr=al.iterator(); while(itr.hasNext()) { String element=itr.next(); System.out.print(element+" "); Mohammad Sufiyan [74] 160310737027

Java and Web Technologies Lab } System.out.println(); System.out.print("modified list backwards"); while(litr.hasPrevious()) { String element=litr.previous(); System.out.print(element+" "); } System.out.println(); } }

DCET

OUTPUT

Mohammad Sufiyan

[75]

160310737027

Java and Web Technologies Lab

DCET

20. DEMONSTRATION OF COMPARATORS


Program: //**demonstration of use of comparators*/ import java.util.*; class MyComp implements Comparator<String> { public int compare(String a,String b) { String aStr,bStr; aStr=a; bStr=b; return bStr.compareTo(aStr); } } class CompDemo { public static void main(String args[]) { TreeSet<String> ts=new TreeSet<String>(new MyComp()); ts.add("C"); ts.add("A"); ts.add("B"); ts.add("E"); ts.add("F"); ts.add("D"); for(String element:ts) System.out.print(element+" "); System.out.println(); } }

OUTPUT

Mohammad Sufiyan

[76]

160310737027

Java and Web Technologies Lab

DCET

21.DEMONSTRATION OF ENUMERATION INTERFACE


Program: //**demonstration of use of enumeration interface via vector class*/ import java.util.*; class EnumVectorDemo { public static void main(String args[]) { Vector<Integer> v=new Vector<Integer>(3,2); System.out.println("initial size:"+v.size()); System.out.println("initial capacity:"+v.capacity()); v.addElement(1); v.addElement(2); v.addElement(3); v.addElement(4); System.out.println("capacity after four additions:"+v.capacity()); v.addElement(5); System.out.println("current capacity:"+v.capacity()); v.addElement(6); v.addElement(7); System.out.println("current capacity:"+v.capacity()); v.addElement(9); v.addElement(10); System.out.println("current capacity:"+v.capacity()); v.addElement(11); v.addElement(12); System.out.println("first element:"+v.firstElement()); System.out.println("last element:"+v.lastElement()); if(v.contains(3)) System.out.println("vector contains 3."); Enumeration vEnum=v.elements(); System.out.println("\n elements in vector:"); while(vEnum.hasMoreElements()) System.out.print(vEnum.nextElement()+" "); System.out.println(); } }

Mohammad Sufiyan

[77]

160310737027

Java and Web Technologies Lab

DCET

OUTPUT

Mohammad Sufiyan

[78]

160310737027

Java and Web Technologies Lab

DCET

22.DEMONSTRATING THE USE OF STRING TOKENIZER


Program: //**demonstration of use of string tokenizers*/ import java.util.StringTokenizer; class STDemo { static String in="title=java:THE COMPLETE REFERENCE; " +"author=Schildt;"+"publisher=Osborne/McGrawHill;"+"copy right=2007"; public static void main(String args[]) { StringTokenizer st=new StringTokenizer(in,"=;"); while(st.hasMoreTokens()) { String key=st.nextToken(); String val=st.nextToken(); System.out.println(key+"\t"+val); } } }

OUTPUT:-

Mohammad Sufiyan

[79]

160310737027

Java and Web Technologies Lab

DCET

APPLETS
There are two varieties of applets. 1. Applets based on 'Applet' class which use the AWT(Abstract Window Toolkit) to provide the graphical user interface. This style of applet is available since Java is first created. 2. Applets based on the Swing class 'JApplet', that uses the Swing classes to provide the GUI(Graphical User Interface).

Applet Basics:
All applets are subclasses of Applet class either directly or indirectly. Applets are not stand-alone programs. They run either within a web browser or an 'appletviewer' which is provided by the JDK(Java Development tool-Kit). All the programs in this record are run through 'appletviewer' itself. Applets do not have main() method their execution begins at init() method.

Steps for Compiling & Running an Applet through 'appletviewer':


Write the applet program in a notepad & store it with .java as an extension. Create another file with .html as an extension which includes the following html tags: <HTML> <BODY> <APPLET CODE=javafilename WIDTH=400 HEIGHT=400> </APPLET> </BODY> </HTML> Compile it in the same format as done for normal applications as shown below: javac <filename>.java Run the applet through the appletviewer by the following step:

appletviewer <filename>.html Once the above step is executed in the command prompt an appletviewer window will be opened displaying the required output.

IMPORTANT METHODS USED FOR APPLETS: 1. METHODS USED FOR APPLET INITIALIZATION & TERMINATION: (a) init() method: This is the first method to be called when an applet begins
its execution. This method initializes the variables & is called only once during the runtime of the applet. Mohammad Sufiyan [80] 160310737027

Java and Web Technologies Lab

DCET

(b) start() method: This method is called after init() method to restart an applet
after it has been stopped. This method is called each time an applet's HTML document is displayed onscreen. So, if a user leaves a web page & comes back, the applet resumes the execution at start() method instead of init() method. (c) paint() method: This method is called each time an applet's output is redrawn. This method has one parameter of type Graphics, which contains the graphics context, that describes the graphics environment in which the applet is running. This context is used whenever output to the applet is required. (d) stop() method: This method is called when a web browser leaves the HTML document containing the applet- For example when it goes to another page. This method is used when the applet is not visible. If the user returns o the page the start( ) method is called for restatrting the applet. (e) destroy( ) method: This method is called when the environment determines that the applet needs to be removed completely from memory. At this point any resources that are held by the applet should be freed.

2. SIMPLE APPLET DISPLAY METHODS:


(a) void drawstring(String message, int x, int y): This method is used to output
a string specified by message to the applet beginning at x co-ordinate & y coordinate. This method recognizes new line characters. (b) void setBackground(Color newColour): This method is used for stting the background colour of an applet by specifying it in the newColour. This method is defined by Component class. (c) void setForeground(Color newColour): This method is used for setting the fore ground colour or the colour in which the text is shown.

3. USING THE STATUS WINDOW:


In addition to displaying information in the applet window, an applet can also output a message in appletviewers status window by using the following method: showStatus( Any message );

Mohammad Sufiyan

[81]

160310737027

Java and Web Technologies Lab

DCET

1. DEMONSTRATION OF A SIMPLE APPLET


Program: //**demonstration of use of simple applet*/ import java.awt.*; import java.applet.*; public class SimpleApplet extends Applet { String msg; public void init() { setBackground(Color.pink); setForeground(Color.red); msg="Inside init()---"; } public void start() { msg+="Inside start()---"; } public void paint(Graphics g) { msg+="Inside paint()---"; g.drawString(msg,10,30); } }

OUTPUT

Mohammad Sufiyan

[82]

160310737027

Java and Web Technologies Lab

DCET

2.DEMONSTRATION OF EVENT HANDLING (A).KEY EVENT HANDLING


Program: //**demonstrating a program for key event*/ import java.awt.*; import java.applet.*; import java.awt.event.*; public class KeyDemo extends Applet implements KeyListener { String str="Welcome"; public void init() { setBackground(Color.pink); addKeyListener(this); } public void keyPressed(KeyEvent ke) { //repaint(); showStatus("now key is pressed"); } public void keyReleased(KeyEvent ke) { //repaint(); showStatus("now key is Released"); } public void keyTyped(KeyEvent ke) { showStatus("now key is Typed"); str+=ke.getKeyChar(); repaint(); } public void paint(Graphics g) { g.drawString(str,20,20); } }

Mohammad Sufiyan

[83]

160310737027

Java and Web Technologies Lab

DCET

OUTPUT

Mohammad Sufiyan

[84]

160310737027

Java and Web Technologies Lab

DCET

Mohammad Sufiyan

[85]

160310737027

Java and Web Technologies Lab

DCET

(B).MOUSE EVENT HANDLING


Program: /**demonstrating of use of event handling*/ /**demonstrating a program of mouse event*/ import java.awt.*; import java.awt.event.*; import java.applet.*; public class Me2 extends Applet implements MouseListener,MouseMotionListener { String msg=" "; int mousex=10; int mousey=10; public void init() { setBackground(Color.green); addMouseListener(this); addMouseMotionListener(this); } public void mouseClicked(MouseEvent me) { msg="Mouse Clicked"; repaint(); } public void mouseEntered(MouseEvent me) { mousex=0; mousey=10; msg="Mouse Entered"; repaint(); } public void mouseExited(MouseEvent me) { msg="Mouse Exited"; repaint(); } public void mousePressed(MouseEvent me) { msg="Mouse Pressed"; repaint(); } public void mouseReleased(MouseEvent me) { msg="Mouse Released"; repaint(); } public void mouseDragged(MouseEvent me) { Mohammad Sufiyan [86] 160310737027

Java and Web Technologies Lab mousex=me.getX(); mousey=me.getY(); msg="Mouse Dragged"; showStatus("Dragging mouse at"+mousex+","+mousey); repaint(); } public void mouseMoved(MouseEvent me) { showStatus("moving mouse at"+me.getX() + "," +me.getY()); repaint(); } public void paint(Graphics g) { g.drawString(msg,10,20); } }

DCET

OUTPUT

Mohammad Sufiyan

[87]

160310737027

Java and Web Technologies Lab

DCET

Mohammad Sufiyan

[88]

160310737027

Java and Web Technologies Lab

DCET

3. DEMONSTRATION OF GUI WITH DIFFERENT CONTROLS


(A) CHOICE CLASS
Program: /**demonstration of use of choice*/ import java.awt.*; import java.applet.*; public class ChoiceDemo extends Applet { public void init() { setBackground(Color.red); int width=Integer.parseInt(getParameter("width")); int height=Integer.parseInt(getParameter("height")); Choice os=new Choice(); Choice browser=new Choice(); os.addItem("windows 95"); os.addItem("windows 98"); os.addItem("windows 2000"); os.addItem("windows Vista"); os.addItem("windows 7"); add(os); browser.addItem("google chrome"); browser.addItem("Mozilla Firefox"); browser.addItem("Netscape"); browser.addItem("Internet Explorer"); browser.addItem("Hot Java"); add(browser); os.reshape(0,0,width/2,height/2); browser.reshape(0,height/2,width,height); } }

Mohammad Sufiyan

[89]

160310737027

Java and Web Technologies Lab

DCET

OUTPUT

Mohammad Sufiyan

[90]

160310737027

Java and Web Technologies Lab

DCET

(B).CHECKBOX CLASS
Program: /**demonstration of use of check boxes*/ import java.awt.*; import java.applet.*; public class Chkboxtxt extends Applet { public void init() { setBackground(Color.red); Checkbox c1=new Checkbox(); Checkbox c2=new Checkbox("Solaris"); Checkbox c3=new Checkbox("Windows 95"); Checkbox c4=new Checkbox("Windows 98",true); Checkbox c5=new Checkbox("Windows 2000",null,true); Checkbox c6=new Checkbox("Windows XP",null,true); Checkbox c7=new Checkbox("Windows 7"); Checkbox c8=new Checkbox("Unix"); add(c1); add(c2); add(c3); add(c4); add(c5); add(c6); add(c7); add(c8); } }

OUTPUT

Mohammad Sufiyan

[91]

160310737027

Java and Web Technologies Lab

DCET

4. DEMONSTRATION OF MENUS
Program: import java.awt.*; import java.applet.*; public class MenuDemo extends Applet { public void init() { int width=Integer.parseInt(getParameter("width")); int height=Integer.parseInt(getParameter("height")); Frame f=new Frame("demo frame"); f.resize(width,height); MenuBar mbar=new MenuBar(); f.setMenuBar(mbar); Menu file=new Menu("File"); file.add(new MenuItem("New...")); file.add(new MenuItem("Open...")); file.add(new MenuItem("Close...")); file.add(new MenuItem("...")); file.add(new MenuItem("Quit...")); mbar.add(file); Menu edit=new Menu("Edit"); edit.add(new MenuItem("cut")); edit.add(new MenuItem("copy")); edit.add(new MenuItem("paste")); edit.add(new MenuItem("...")); Menu sub=new Menu("Special"); sub.add(new MenuItem("first")); sub.add(new MenuItem("second")); sub.add(new MenuItem("third")); edit.add(sub); edit.add(new CheckboxMenuItem("Debug")); edit.add(new CheckboxMenuItem("Testing")); mbar.add(edit); f.show(); } }

Mohammad Sufiyan

[92]

160310737027

Java and Web Technologies Lab

DCET

OUTPUT

Mohammad Sufiyan

[93]

160310737027

Java and Web Technologies Lab

DCET

5.AN APPLICATION OF APPLET


Program: /**demonstration of an application on AWT control*/ import java.awt.*; import java.awt.event.*; import java.applet.*; public class AWTdemo extends Applet implements ActionListener { String str; Font f; Button b1,b2; TextArea ad,cv; TextField name,fname; public void init() { CheckboxGroup cbg=new CheckboxGroup(); Checkbox m,fe; Label title=new Label(" ...................APPLICATION........... ",Label.CENTER); Label namep=new Label(" Name:",Label.LEFT); Label fnamep=new Label(" Fathers Name:",Label.LEFT); Label adp=new Label(" Address:",Label.LEFT); Label hobp=new Label(" Hobbies: ",Label.LEFT); Label cp=new Label(" Branch:",Label.RIGHT); Label g=new Label(" Gender:",Label.LEFT); f=new Font("Monotype Corsiva",Font.BOLD|Font.ITALIC,16); setFont(f); Checkbox c1,c2,c3,c4; c1=new Checkbox("Indoor Games ",null,true); c2=new Checkbox("Outdoor Games "); c3=new Checkbox("Board Games "); c4=new Checkbox("Others "); m=new Checkbox("Male ",cbg,true); fe=new Checkbox("Female ",cbg,false); ad=new TextArea("",5,20); cv=new TextArea("",13,100); name=new TextField(30); fname=new TextField(30); Choice c=new Choice(); c.add("IT"); c.add("ECE"); c.add("EEE"); Mohammad Sufiyan [94] 160310737027

Java and Web Technologies Lab c.add("IT"); Button b1=new Button(" Submit "); Button b2=new Button(" Cancel "); setBackground(Color.cyan); setForeground(Color.red); add(title); add(namep); add(name); add(fnamep); add(fname); add(g); add(m); add(fe); add(adp); add(ad); add(cp); add(c); add(hobp); add(c1); add(c2); add(c3); add(c4); add(cv); add(b1); add(b2); } public void actionPerformed(ActionEvent ae) { String str,s1; s1=ae.getActionCommand(); if(s1.equals(" Submit ")) { str="Name:"+name.getText(); } } public void paint(Graphics g) { g.drawString(str,10,500); } }

DCET

Mohammad Sufiyan

[95]

160310737027

Java and Web Technologies Lab

DCET

OUTPUT

Mohammad Sufiyan

[96]

160310737027

Java and Web Technologies Lab

DCET

WEB APPLICATIONS
1. DEVELOPING AN HTML FORM WITH CLIENT VALIDATION USING JAVA SCRIPT
<html> <head><title>login page</title> </head> <body bgcolor="pink"><br /><br /> <script language="javascript"> function validate() { var flag=0; if((document.myform.id.value=="beit")&&(document.myform.pwd.value=="webtech")) { flag=1; } if(flag==1) { window.open("main.html"); } else { alert("INVALID INPUT"); document.myform.focus(); } } </script> <form name="myform"> <div align="center"><pre> LOGIN ID:<input type="text" name="id"> PASSWORD:<input type="password" name="pwd"> <br /><br /></div> <div align="center"> <input type="submit" value="ok" onclick="validate()"> <input type="reset" value="clear"> </form> </body> </html>

Mohammad Sufiyan

[97]

160310737027

Java and Web Technologies Lab

DCET

OUTPUT

Mohammad Sufiyan

[98]

160310737027

Java and Web Technologies Lab

DCET

Mohammad Sufiyan

[99]

160310737027

Java and Web Technologies Lab

DCET

Mohammad Sufiyan

[100]

160310737027

Java and Web Technologies Lab

DCET

2. DEVELOPING AN XML DOCUMENT USING XSLT


XML PROGRAM: <?xml version="1.0" encoding="utf-8"?> <!--student.xml--> <?xml-stylesheet type="text/xsl" href="stylestudent.xsl" ?> <students> <student> <rollno> 16037001 </rollno> <name> John </name> <fname> Thomas </fname> <percentage> 75 </percentage> <branch> IT </branch> </student><br /> <student> <rollno> 16037002 </rollno> <name> Jennie </name> <fname> Watson </fname> <percentage> 73 </percentage> <branch> IT </branch> </student><br /> <student> <rollno> 16037003 </rollno> <name> James </name> <fname> Joseph </fname> <percentage> 63 </percentage> <branch> IT </branch> </student><br /> </students>

STYLESHEET DOCUMENT: (xslt) <?xml version="1.0" encoding="utf-8"?> <!-- stylestudent.xsl --> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns="http://www.w3.org/1999/xhtml" > <xsl:template match="students"> <h2> STUDENTS DESCRIPTION </h2> <xsl:for-each select="student"> <span style="font-style: italic; color:blue; bgcolor:pink;"> Roll No.: </span> <xsl:value-of select="rollno" /><br /> <span style="font-style: italic; color:pink;"> Name: </span> <xsl:value-of select="name" /><br /> <span style="font-style: italic; color:cyan;"> Father Name: </span> <xsl:value-of select="fname" /><br /> Mohammad Sufiyan [101] 160310737027

Java and Web Technologies Lab <span style="font-style: italic; color:red;"> Percentage: </span> <xsl:value-of select="percentage" /><br /> <span style="font-style: italic; color:green;"> Branch: </span> <xsl:value-of select="branch" /><br /><br /> <h2> --------------------------------</h2> </xsl:for-each> </xsl:template> </xsl:stylesheet>

DCET

OUTPUT

Mohammad Sufiyan

[102]

160310737027

Java and Web Technologies Lab

DCET

3.DEVELOPING A JAVA SERVLET APPLICATION USING SESSION TRACKING


SERVLET A Servlet is a Java programming language class used to extend the capabilities of servers that host applications access via a request-response programming model. Although Servlets can respond to any type of request, they are commonly used to extend the applications hosted by Web servers. Thus, it can be thought of as a Java Applet that runs on a server instead of a browser.

STEPS FOR DEVELOPING A SERVLET

Step 1: Open the NetBeans ide6.5.1, create a new project in it and perform the following as shown below:

Mohammad Sufiyan

[103]

160310737027

Java and Web Technologies Lab

DCET

Step 2: Write the name of the project and location i.e., Webapplication1 and press next.

Step3: Select the Glassfish v2 server and the also select some javaEE version and click next.

Mohammad Sufiyan

[104]

160310737027

Java and Web Technologies Lab Step 4: In Framework, there is no need to do select anything just click finish.

DCET

Step 5: Create a Servlet file from the default package by expanding the source package. By right clicking on the default package as shown below:

Mohammad Sufiyan

[105]

160310737027

Java and Web Technologies Lab Step 6: Give the Name and Location to the Servlet i.e., Session.

DCET

Step 7: Now configure the Servlet Deployment which registers the Servlet with the Deployment descriptor (web.xml).

Mohammad Sufiyan

[106]

160310737027

Java and Web Technologies Lab

DCET

Step 8: By this a Servlet will be created with the name (Session.java).Now by double clicking on the file name you will get a window to write the code on the right side. Insert the Servlet code in it.

CODE: import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class Session extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html;charset=UTF-8"); HttpSession session=req.getSession(); String heading; Integer cnt=(Integer)session.getAttribute("cnt"); if(cnt==null) { cnt=new Integer(0); heading="Welcome you are accessing the page for the first time"; Mohammad Sufiyan [107] 160310737027

Java and Web Technologies Lab } else { heading="Welcome once again"; cnt=new Integer(cnt.intValue()+1); } session.setAttribute("cnt",cnt); PrintWriter out = res.getWriter(); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet Session</title>"); out.println("</head>"); out.println("<body>"); out.println("<center>"); out.println("<h1>"+heading+"</h1>"); out.println("The number of previous access="+cnt); out.println("</center>"); out.println("</body>"); out.println("</html>"); } }

DCET

Mohammad Sufiyan

[108]

160310737027

Java and Web Technologies Lab

DCET

OUTPUT

Mohammad Sufiyan

[109]

160310737027

Java and Web Technologies Lab

DCET

DEVELOPING A SIMPLE JSP APPLICATION


JAVA SERVER PAGES (JSP) JavaServer Pages (JSP) is a technology that helps software developers create dynamically generated web pages based on HTML, XML, or other document types. Released in 1999 by Sun Microsystems, JSP is similar to PHP, but it uses the Java programming language. STEPS FOR DEVELOPING A JAVA SERVER PAGE

Step 1: Open the NetBeans IDE 6.5.1, create a new project in it and perform the following as shown below:

Mohammad Sufiyan

[110]

160310737027

Java and Web Technologies Lab

DCET

Step 2: Write the name of the project and location i.e., Webapplication1 and press next.

Step3: Select the Glassfish v2 server and the also select some javaEE version and click next.

Mohammad Sufiyan

[111]

160310737027

Java and Web Technologies Lab Step 4: In Framework, there is no need to do select anything just click finish.

DCET

Step 5: Create a JSP file from the default package by expanding the source package. By right clicking on the default package as shown below:

Mohammad Sufiyan

[112]

160310737027

Java and Web Technologies Lab Step 6: Give the Name and Location to the JSP i.e., Inputform.

DCET

Step 7: By this a JSP will be created with the name (Inputform.jsp).Now by double clicking on the file name you will get a window to write the code on the right side. Insert the JSP code in it.

Mohammad Sufiyan

[113]

160310737027

Java and Web Technologies Lab CODE: <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Data passsing demo between JSP pages</title> </head> <body> <% if(request.getParameter("username")!=null) { %> <jsp:forward page="welcome.jsp"/> <% } else { %> <form method="get" action="Inputform.jsp"> <strong>Enter User Name:</strong> <input type="text" name="Username"> </br> <input type="Submit" value="Enter"> </form> <% } %> </body> </html> welcome.jsp <html> <head> </head> <body> <b> WELCOME ${param.username}</b>!!! </body> </html>

DCET

Mohammad Sufiyan

[114]

160310737027

Java and Web Technologies Lab

DCET

OUTPUT

Mohammad Sufiyan

[115]

160310737027

Java and Web Technologies Lab

DCET

DEVELOPING AN APPLICATION FOR PATTERN MATCHING USING PERL (LINUX OS)


while(<>) { @line_words=split/[\.,;!\?]*/; foreach $word (@line_words) { if (exists $freq{$word}) { $freq{$word}++; } else { $freq{$word}=1; } } } print "\n word \t\t Frequency \n\n"; foreach $word (sort keys %freq) { print "$word \t\t $freq{$word} \n"; }

Steps for execution of Perl Program:


Perl programs can be executed on Windows or UNIX or LINUIX Operating system. The program in this record is executed by working on LINUX operating system. The Implementation and execution of Perl program is as shown below: Step 1: Connect to Linux Server by typing the ip address of the linux server i.e., 192.168.0.5 Step 2: Provide the login id and password which is: Loginid: exam15 Password: dcetit Step 3: After getting connected create a perl file by typing the following command: vi <filename>.pl Step 4: Type the program by first pressing ito enter into the insert mode Step 5: Save and quit the program by following: Press Escape button Type :wq Step 6: Now run the program by typing following command: perl <filename>.pl

Mohammad Sufiyan

[116]

160310737027

Java and Web Technologies Lab

DCET

OUTPUT

Mohammad Sufiyan

[117]

160310737027

S-ar putea să vă placă și