Java and Web Record
-
Upload
sufiyan-mohammad -
Category
Documents
-
view
231 -
download
0
Transcript of Java and Web Record
-
7/31/2019 Java and Web Record
1/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [1] 160310737027
INTRODUCTION TO JAVA
Java is a new object oriented language receiving a worldwide attention from both industryand 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, theteam renamed it as Java.
Java programs can be of two types:1) Applications2) Applets
1. Java applications is a complete stand alone program that does not require a webbrowser. 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 writingprograms called applets. Applets run in a web browser, i.e. a web browser is
needed to execute Java applets. Applets allow more dynamic and flexibledissemination of information on the internet, and this feature alone makes Java anattractive language to learn.
JAVA PROGRAM STRUCTURE:Documentation Section
-
7/31/2019 Java and Web Record
2/117
-
7/31/2019 Java and Web Record
3/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [3] 160310737027
Typical Java development environment:
Phases Using Storage Description
Phase I :Edit
Editor Disk
Program is created in an editor and stored on disc in afile ending with .java as an extension. The editor hereis a notepad.
Phase II :Compile
Compiler DiskCompiler creates bytecodes and stores them ondisc in a file ending with .class as an extension.
Phase III:Load
LoaderPrimaryMemory
Class loader reads .class files containing bytecodes
from disc and put those byte codes in memory.
Phase IV: Verify
Byte codeVerifier
PrimaryMemory
Bytecode verifier confirms that all bytecodes are valid& do not violate Javas security restrictions.
Phase V :
Execute
Java VirtualMachine
(JVM)
Primary
Memory
To execute the program, the Java Virtual Memory(JVM) reads bytecodes and translates them into acomputer language understandable by the computer.
As the program execute, it may store data values inprimary memory.
-
7/31/2019 Java and Web Record
4/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [4] 160310737027
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 compilingD:\ITJAVA> javac .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 thename of the file for saving the program.
For Example:
class Sample{Public static void main (String args[])
}class Example{
//}
Should be saved with Sample.java7. Always remember to write the class name with its first alphabet in capital letters and storedthe file with the same name.
-
7/31/2019 Java and Web Record
5/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [5] 160310737027
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.
-
7/31/2019 Java and Web Record
6/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [6] 160310737027
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 variablesare 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. All byte, short, and char values are promoted to int.2. If one operand is long, the entire expression is promoted to long:3. If one operand is float, the entire expression is promoted to float.4. If any of the operand is double , the result is double.
-
7/31/2019 Java and Web Record
7/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [7] 160310737027
(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:-
-
7/31/2019 Java and Web Record
8/117
-
7/31/2019 Java and Web Record
9/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [9] 160310737027
(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);
}}
-
7/31/2019 Java and Web Record
10/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [10] 160310737027
OUTPUT
Description of the program:
This program demonstrates type casting of variables that are declared in the mainmethod, 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 andalso converting float value to int.
The resultant output is displayed by using the last four statement of println ( ) method.
-
7/31/2019 Java and Web Record
11/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [11] 160310737027
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 thefollowing 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 iscalled.
An argument is a value that is passed to a method when it is invoked.
-
7/31/2019 Java and Web Record
12/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [12] 160310737027
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);
}
}
-
7/31/2019 Java and Web Record
13/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [13] 160310737027
OUTPUT
Description of the program:
This program consists of the Box class and ParamMeth class. The Box class consists of theinstance variables width, height & depth, a method volume(), to compute the volume of thebox & return the values to the calling routine and another method SetDim() with parametersw, 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.
-
7/31/2019 Java and Web Record
14/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [14] 160310737027
4. DEMONSTRATION OF CONSTRUCTORS
JAVA allows objects to initialize themselves when they are created. This automaticinitialization is performed through the use of a constructor. A constructor initializes an objectimmediately upon creation. It has the same name as that of the class in which it resides & issyntactically similar to a method, with a difference that constructors do not have return typenot even void because its implicit return type is its class type itself. Once defined, theconstructor 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 constructorfor the class. The default constructor automatically initializes all instance variables to zero.
General form of constructor:
class
{ (){
//body of the constructor}
}
Constructors can take two forms:1. Normal Constructors2. 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 constructorduring the creation of an object with the help of "new" operator.
-
7/31/2019 Java and Web Record
15/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [15] 160310737027
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);
}
}
-
7/31/2019 Java and Web Record
16/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [16] 160310737027
OUTPUT
Description of the program:
This program demonstrates the use of normal constructors, i.e., constructors with noparameters and constructors with parameters. In class "Box", a constructor "Box()" is definedwhich assigns values to width, height & depth inside its block. This class also consists of themethod volume() to compute the volume of the boxes & return the value.
Most constructors will not display anything, the println() statement inside Box() constructoris 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 invokedby the object of Box class to compute the volume & the value is displayed at the output.
-
7/31/2019 Java and Web Record
17/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [17] 160310737027
5. DEMONSTRATION OF OVERLOADING CONCEPT
Method Overloading. Constructor Overloading.
METHOD OVERLOADING:
Two or more methods with same name , within the same class but with differentparameter declarations are said to be overloaded and the process is known as MethodOverloading.
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 javaimplements one interface , multiple methods paradigm .
There is no rule that overloaded methods must relate to one another , but in practicemethods 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.
-
7/31/2019 Java and Web Record
18/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [18] 160310737027
(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);}
}
-
7/31/2019 Java and Web Record
19/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [19] 160310737027
OUTPUT
Description of the program:
In the above program test( ) is overloaded 4 times ,1- for no parameters ,2- 2for one integer parameter ,3- 3for 2 integer parameters and4- 4for double type of one parameter
-
7/31/2019 Java and Web Record
20/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [20] 160310737027
(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());
}}
-
7/31/2019 Java and Web Record
21/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [21] 160310737027
OUTPUT
Description of the program:
From the above program , the proper overloaded constructor is called based upon theparameters when new is executed .
-
7/31/2019 Java and Web Record
22/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [22] 160310737027
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 formalparameter of subroutine. Therefore changes made to the parameter of the subroutine have noeffect on the argument. When a primitive type is passed to a method it is done by call byvalue.
2) Call by reference :In this approach, reference to an argument (not the value of the argument) is passed to theparameter. Inside the subroutine, this reference is used to access the actual argumentspecified in the call. This means that changes made to the parameter will affect the argumentused to call the subroutine.
When an object is passed to a method , the situation changes dramatically , becauseobjects are passed by callbyreference .
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 referto the same object as that referred to by the argument .This effectively means thatobjects are passed to methods by use of callbyreference .
Changes to the object inside the method affect the object used as an argument .
-
7/31/2019 Java and Web Record
23/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [23] 160310737027
(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
-
7/31/2019 Java and Web Record
24/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [24] 160310737027
Description of the program:
From the program operation that occurs inside meth( ) have no effect on the values of a and bused in the call , if there was any effect then their values would have changed to 30 and 10respectively , but this did not happen .
-
7/31/2019 Java and Web Record
25/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [25] 160310737027
(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);}
}
-
7/31/2019 Java and Web Record
26/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [26] 160310737027
OUTPUT
Description of the program:From the above program actions performed in meth( ) have affected the objectused as an argument .
-
7/31/2019 Java and Web Record
27/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [27] 160310737027
7. DEMONSTRATION OF COMMAND LINE ARGUMENTS:
Sometimes there will be needs to pass information into a program while it is run. This isaccomplished by passing command line arguments to main ( ).
A commandline argument is the information that directly follows the programsname on the command line when it is executed.
Command line arguments are stored (and passed) as strings in a String array passedto 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
-
7/31/2019 Java and Web Record
28/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [28] 160310737027
OUTPUT
-
7/31/2019 Java and Web Record
29/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [29] 160310737027
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
B
2) Multilevel Inheritance (derived from a derived class)A
B
C
3) Hierarchical Inheritance (one super class many sub classes)
A
B C D
-
7/31/2019 Java and Web Record
30/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [30] 160310737027
4) Multiple Inheritance (Several super classes)( not supported by Java directly)
Java does not directly implements multiple inheritance. This concept is implementedusing 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 theattributes common to a set of objects, it can be used to create any number of more specificsubclasses. Each subclass can precisely tailor its own classification.
Interface
B
Class
A
derivedclass
C
-
7/31/2019 Java and Web Record
31/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [31] 160310737027
(A).SINGLE INHERITANCEProgram:
//**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();
}}
-
7/31/2019 Java and Web Record
32/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [32] 160310737027
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.
-
7/31/2019 Java and Web Record
33/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [33] 160310737027
(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();
}}
-
7/31/2019 Java and Web Record
34/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [34] 160310737027
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.
-
7/31/2019 Java and Web Record
35/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [35] 160310737027
(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();}
}
-
7/31/2019 Java and Web Record
36/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [36] 160310737027
OUTPUT
-
7/31/2019 Java and Web Record
37/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [37] 160310737027
(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();
}}
-
7/31/2019 Java and Web Record
38/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [38] 160310737027
OUTPUT
-
7/31/2019 Java and Web Record
39/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [39] 160310737027
(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 interfacei1");
}}
class MultipleInherit{public static void main(String args[]){
A x=new A();B y=new B();y.a();y.i();
}}
-
7/31/2019 Java and Web Record
40/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [40] 160310737027
OUTPUT
-
7/31/2019 Java and Web Record
41/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [41] 160310737027
9. DEMONSTRATION OF METHOD OVERRIDING
In a class hierarchy, when a method in a subclass has the same name and type signature asmethod in the superclass, then the method in the subclass is said to override the method in thesuperclass.
When an overridden method is called from a subclass, it will always refer to the version ofthat method defined by the subclass .The version of the method defined by the superclass willbe 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();
}}
-
7/31/2019 Java and Web Record
42/117
-
7/31/2019 Java and Web Record
43/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [43] 160310737027
10. DEMONSTRATION OF DYNAMIC POLYMORPHISM:
DYNAMIC POLYMORPHISMIt is a mechanism by which a call to an overrided method is resolved at run time , ratherthan 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 androbustness 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");
-
7/31/2019 Java and Web Record
44/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [44] 160310737027
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());}
}
OUTPUT
-
7/31/2019 Java and Web Record
45/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [45] 160310737027
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 modifierabstract Abstract methods are sometime referred as a subclasses responsibility
General form :
abstract type name( parameterlist );
There can be no objects for an abstract class, i.e., an abstract class cannot be instantiateddirectly 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();
}}
-
7/31/2019 Java and Web Record
46/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [46] 160310737027
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 runtime polymorphism isimplemented through the use of superclass reference.
Thus, it must be possible to create a reference to an abstract class so that it can beused to point to a subclass object.
-
7/31/2019 Java and Web Record
47/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [47] 160310737027
12. DEMONSTRATION OF PACKAGES:
Packages are containers for classes that are used to keep the class name spacecompartmentalized.
Packages are stored in a hierarchical manner and are explicitly imported in to newclass definitions.For example : A package allows creation of a class named List, which can be stored in aparticular package without concern that it will collide with some other class named withthe same name List stored elsewhere .
Defining A Package :
To create a package include a package command as the fi rst statement in a Java sourcefile . 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 realapplications.
The general form of package statement :Package ;
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]];
-
7/31/2019 Java and Web Record
48/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [48] 160310737027
Program:
package MyPack;class Balance{
String name;double bal;Balance(String n,double b){
name=n;bal=b;
}void show(){
if(bal
-
7/31/2019 Java and Web Record
49/117
-
7/31/2019 Java and Web Record
50/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [50] 160310737027
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");
}}
OUTPUT
-
7/31/2019 Java and Web Record
51/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [51] 160310737027
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 themain 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 invokessleep( ) method ; it leaves the CPU for 1 second and the CPU time is utilized by the childthread .Both the threads continue running , sharing the CPU , until their loop gets terminated.
The output may vary based on processor speed and task
-
7/31/2019 Java and Web Record
52/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [52] 160310737027
(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);
-
7/31/2019 Java and Web Record
53/117
-
7/31/2019 Java and Web Record
54/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [54] 160310737027
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 threedifferent 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{
-
7/31/2019 Java and Web Record
55/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [55] 160310737027
Thread.sleep(10000);}catch(InterruptedException e){
System.out.println("main thread interrupted");
}System.out.println("main thread exiting");
}}
OUTPUT
Description of the program:
This program generates three threads T-One,T-Two,T-Three from the main thread .And tillthe main thread is sleeping for 10 seconds ,all these three child threads share the CPU amongthemselves.The call to sleep() method in main ensures that the main() method will finish or terminatelast.
-
7/31/2019 Java and Web Record
56/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [56] 160310737027
15. DEMONSTRATION OF THREAD SYNCHRONIZATION:
When two or more threads need access to a shared resource, they need some way toensure that a resource will be used only by one thread at a time . The process bywhich this is achieved is called Synchronization.
Key to synchronization is the concept of the monitor orSemaphore.
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 thefirst thread exits the monitor. These other threads are said to be waiting for themonitor.
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 thecomplexity associated synchronization has been eliminated.
(a) Using Synchronisation With Methods :
Synchronisation is easy in Java , because all objects have their own implicit monitorassociated with them .
To enter an objects monitor , just call a method that has been modified with thesynchronized 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 themonitor or relinquish control of the object to the next waiting thread , the owner of themonitor 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 thatcalls the method will be preceeded by the synchronized keyword.
-
7/31/2019 Java and Web Record
57/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [57] 160310737027
(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();
-
7/31/2019 Java and Web Record
58/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [58] 160310737027
obj3.t.join();}catch(InterruptedException e){
System.out.println("interrupted");
}}
}
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 onethread 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 fromcalling 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.
-
7/31/2019 Java and Web Record
59/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [59] 160310737027
(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");
-
7/31/2019 Java and Web Record
60/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [60] 160310737027
try{
obj1.t.join();obj2.t.join();obj3.t.join();
}catch(InterruptedException e){
System.out.println("interrupted");}}
}
OUTPUT
-
7/31/2019 Java and Web Record
61/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [61] 160310737027
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
-
7/31/2019 Java and Web Record
62/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [62] 160310737027
OUTPUT
-
7/31/2019 Java and Web Record
63/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [63] 160310737027
17.DEMONSTRATION OF BUFFEREDINPUTSTREAM
CLASSProgram:
import java.io.*;class BISDemo{
public static void main(String args[])throws IOException{
String s="This is a copyright symbol"+" but this is © 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);
-
7/31/2019 Java and Web Record
64/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [64] 160310737027
break;}
}}
}
OUTPUT
-
7/31/2019 Java and Web Record
65/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [65] 160310737027
EXPLORING java.util PACKAGE
THE COLLECTION INTERFACES
The collections frame work defines several interfaces which are summarized below:-Interface hierarchy of Collections
In addition to the above interfaces, there are some more interfaces that do not belongto the above hierarchy. They are listed below;1. Comparatordefines how two objects are compared.2. Iterator - Enumerates the objects within a collection3. List Iterator4. Random access - A list which implements this interface indicates that it support
efficient, random access to its elements.
Collection can be categorized as;
Iterable
Collection
SetList Queue
Sorted set
Navigable Set
Dequeue
-
7/31/2019 Java and Web Record
66/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [66] 160310737027
Modifiable: Collections that support method used to modify their contents. 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 anunsupported Operation Exception is thrown.The Collection Interface:
This is the foundation upon which collections frame work is built. This is a genericinterface and has the declaration;
interface collection E specifies the type of objects that the collection will hold.
Collection extends the iterable interface. All collections implements Collectioninterface and its core methods.
The List interface:
The List interface extends the Collection interface and declares the behavior of acollection that stores a sequence of elements.
Elements can be inserted are accessed by the position in the list, using the zero baseindex. A list may contain duplicate elements. This is a generic interface that has the declaration as; Interface List 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 acollection that does not allow duplicate elements.
The add ( ) method returns false if an attempt is made to add duplicate elements to aset.
It does not define any additional methods of its own. Set a generic interface which has the declaration as shown below:
-
7/31/2019 Java and Web Record
67/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [67] 160310737027
Interface set .
here E specifies the type of objects that set will hold.
The SortedSet interface;
This interface extends set and declares the behavior of a set sorted in ascendingorder.
This is a general interface and has the declaration as shown below:interface Sorted Set
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 retrievalof elements based on the closest match to a given value or values.
This is a generic interface and has the declaration asInterface Navigable Set
The Queue Interface:
This interface extends collectionand declares the behavior of a queue which is oftena first -in -first -out list.
This is a generic interface that has this declarationinterface Queue
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 specifies the type of objects that the set will hold.
-
7/31/2019 Java and Web Record
68/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [68] 160310737027
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 specifies the type of objects the list will hold.
Array List Class support dynamic arrays, i.e., after specifying a value duringinitialization of an array, it can be grown are shrink during the run time as required bythe user.
Array List is a variable length array of object references, it can be dynamicallyincreased or decreased in size.
Array lists are created with an initial size, when this size is exccded, the collection isautomatically enlarged and when objects are removed, the array can be shrunk.
-
7/31/2019 Java and Web Record
69/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [69] 160310737027
18.DEMONSTRATION OF COLLECTION CLASSES
(A).LINKEDLIST CLASS
The Linked List Class:This class extends Abstract Sequential List class and implements theList, Deque and Queue interfaces.
It provides a linked list data structure. Linked List is a generic class and has thisdeclaration:
class Linked List
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 llist=new LinkedList();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);}}
-
7/31/2019 Java and Web Record
70/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [70] 160310737027
OUTPUT
-
7/31/2019 Java and Web Record
71/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [71] 160310737027
(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-objects that list will hold.
A hash table stores the information by using a mechanism call hashing. In hashinginformational 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 hs=new HashSet();hs.add("B");hs.add("A");hs.add("D");hs.add("E");hs.add("C");
hs.add("F");System.out.println(hs);
}}
OUTPUT
-
7/31/2019 Java and Web Record
72/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [72] 160310737027
(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 storinglarge amounts of sorted information that must be found quickly.This is a generic class that has the general declaration as follows:
class TreeSet 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 ts=new TreeSet();ts.add("C");ts.add("A");ts.add("B");ts.add("E");ts.add("F");ts.add("D");System.out.println(ts);
}}
OUTPUT
-
7/31/2019 Java and Web Record
73/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [73] 160310737027
19. DEMONSTRATION OF ITERATORS:
ACCESSING A COLLECTION VIA AN ITERATOR:
There are situation, where user want to cycle through the elements in a collection, forexample: displaying each element. One way to fulfill this situation is to employ aniterator.
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 removeelements.
General declaration:interface Iterator
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 atime.
There are three important steps in obtaining the iterator & cycling through theelements of a collection.1. Obtain an iterator to the start of the collection by calling the collections integrator
( ) method.
2. Setup a loop that makes a call to has Next ( ). Have the loop iterate as long ashasNext ( ) returns true.
3. Within the loop, obtain each element by calling next ( ).
-
7/31/2019 Java and Web Record
74/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [74] 160310737027
List Iterator Interface :
This interface extends Iterator interface. It allows bidirectional traversal of a list, & themodification of elements. List Iterator is a generic interface & has the general declaration asshown below:
interface List Iterator
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 Listinterface
Program:
/**Demonstration of iterators*/
import java.util.*;class IteratorDemo{
public static void main(String args[]){
ArrayList al=new ArrayList();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 itr=al.iterator();while(itr.hasNext()){
String element=itr.next();System.out.print(element+" ");
}
System.out.println();ListIterator 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+" ");
-
7/31/2019 Java and Web Record
75/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [75] 160310737027
}System.out.println();System.out.print("modified list backwards");while(litr.hasPrevious()){
String element=litr.previous();System.out.print(element+" ");
}System.out.println();
}}
OUTPUT
-
7/31/2019 Java and Web Record
76/117
-
7/31/2019 Java and Web Record
77/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [77] 160310737027
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 v=new Vector(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();
}}
-
7/31/2019 Java and Web Record
78/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [78] 160310737027
OUTPUT
-
7/31/2019 Java and Web Record
79/117
-
7/31/2019 Java and Web Record
80/117
-
7/31/2019 Java and Web Record
81/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [81] 160310737027
(b) start() method:This method is called after init() method to restart an appletafter it has been stopped. This method is called each time an applet's HTMLdocument is displayed onscreen. So, if a user leaves a web page & comes back, theapplet resumes the execution at start() method instead of init() method.
(c) paint() method:This method is called each time an applet's output isredrawn. This method has one parameter of type Graphics, which contains thegraphics context, that describes the graphics environment in which the applet isrunning. This context is used whenever output to the applet is required.
(d) stop() method:This method is called when a web browser leaves the HTMLdocument containing the applet- For example when it goes to another page. Thismethod 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 determinesthat the applet needs to be removed completely from memory. At this point anyresources 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 co-ordinate. This method recognizes new line characters.
(b)void setBackground(Color newColour): This method is used for stting thebackground 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 );
-
7/31/2019 Java and Web Record
82/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [82] 160310737027
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
-
7/31/2019 Java and Web Record
83/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [83] 160310737027
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);}}
-
7/31/2019 Java and Web Record
84/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [84] 160310737027
OUTPUT
-
7/31/2019 Java and Web Record
85/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [85] 160310737027
-
7/31/2019 Java and Web Record
86/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [86] 160310737027
(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){
-
7/31/2019 Java and Web Record
87/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [87] 160310737027
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);}
}
OUTPUT
-
7/31/2019 Java and Web Record
88/117
-
7/31/2019 Java and Web Record
89/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [89] 160310737027
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);}}
-
7/31/2019 Java and Web Record
90/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [90] 160310737027
OUTPUT
-
7/31/2019 Java and Web Record
91/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [91] 160310737027
(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
-
7/31/2019 Java and Web Record
92/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [92] 160310737027
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();}
}
-
7/31/2019 Java and Web Record
93/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [93] 160310737027
OUTPUT
-
7/31/2019 Java and Web Record
94/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [94] 160310737027
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(" FathersName:",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");
-
7/31/2019 Java and Web Record
95/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [95] 160310737027
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);}}
-
7/31/2019 Java and Web Record
96/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [96] 160310737027
OUTPUT
-
7/31/2019 Java and Web Record
97/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [97] 160310737027
WEB APPLICATIONS
1. DEVELOPING AN HTML FORM WITH CLIENT
VALIDATION USING JAVA SCRIPT
login page
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();}}LOGIN ID:PASSWORD:
-
7/31/2019 Java and Web Record
98/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [98] 160310737027
OUTPUT
-
7/31/2019 Java and Web Record
99/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [99] 160310737027
-
7/31/2019 Java and Web Record
100/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [100] 160310737027
-
7/31/2019 Java and Web Record
101/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [101] 160310737027
2. DEVELOPING AN XML DOCUMENT USING XSLT
XML PROGRAM:
16037001 John Thomas 75 IT
16037002 Jennie Watson 73 IT
16037003 James Joseph
63 IT
STYLESHEET DOCUMENT: (xslt)
STUDENTS DESCRIPTION
Roll No.:
Name:
Father Name:
-
7/31/2019 Java and Web Record
102/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [102] 160310737027
Percentage:
Branch:
--------------------------------OUTPUT
-
7/31/2019 Java and Web Record
103/117
-
7/31/2019 Java and Web Record
104/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [104] 160310737027
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.
-
7/31/2019 Java and Web Record
105/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [105] 160310737027
Step 4: In Framework, there is no need to do select anything just click finish.
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:
-
7/31/2019 Java and Web Record
106/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [106] 160310737027
Step 6: Give the Name and Location to the Servlet i.e., Session.
Step 7: Now configure the Servlet Deployment which registers the Servlet with theDeployment descriptor (web.xml).
-
7/31/2019 Java and Web Record
107/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [107] 160310737027
Step 8: By this a Servlet will be created with the name (Session.java).Now by doubleclicking on the file name you will get a window to write the code on the right side. Insert theServlet 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";
-
7/31/2019 Java and Web Record
108/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [108] 160310737027
}else{
heading="Welcome once again";cnt=new Integer(cnt.intValue()+1);
}session.setAttribute("cnt",cnt);PrintWriter out = res.getWriter();out.println("");
out.println("");out.println("Servlet Session");
out.println("");out.println("");
out.println("");out.println(""+heading+"");out.println("The number of previous access="+cnt);
out.println("");out.println("");out.println("");
}}
-
7/31/2019 Java and Web Record
109/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [109] 160310737027
OUTPUT
-
7/31/2019 Java and Web Record
110/117
-
7/31/2019 Java and Web Record
111/117
-
7/31/2019 Java and Web Record
112/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [112] 160310737027
Step 4: In Framework, there is no need to do select anything just click finish.
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:
-
7/31/2019 Java and Web Record
113/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [113] 160310737027
Step 6: Give the Name and Location to the JSP i.e., Inputform.
Step 7: By this a JSP will be created with the name (Inputform.jsp).Now by double clickingon the file name you will get a window to write the code on the right side. Insert the JSP codein it.
-
7/31/2019 Java and Web Record
114/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [114] 160310737027
CODE:
Data passsing demo between JSP pagesEnter User Name:
welcome.jsp
WELCOME ${param.username}!!!
-
7/31/2019 Java and Web Record
115/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [115] 160310737027
OUTPUT
-
7/31/2019 Java and Web Record
116/117
Java and Web Technologies Lab DCET
Mohammad Sufiyan [116] 160310737027
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: exam15Password: dcetit
Step 3: After getting connected create a perl file by typing the following command:vi .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 buttonType :wq
Step 6: Now run the program by typing following command:
perl .pl
-
7/31/2019 Java and Web Record
117/117
Java and Web Technologies Lab DCET
OUTPUT