Documente Academic
Documente Profesional
Documente Cultură
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 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
DCET
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
Bytecode verifier confirms that all bytecodes are valid & do not violate Javas security restrictions.
Phase V : Execute
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
DCET
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
DCET
OUTPUT
Mohammad Sufiyan
[5]
160310737027
DCET
(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.
Mohammad Sufiyan
[6]
160310737027
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
DCET
Mohammad Sufiyan
[8]
160310737027
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
DCET
OUTPUT
Mohammad Sufiyan
[10]
160310737027
DCET
Mohammad Sufiyan
[11]
160310737027
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
DCET
OUTPUT
Mohammad Sufiyan
[13]
160310737027
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.
Mohammad Sufiyan
[14]
160310737027
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
DCET
OUTPUT
Mohammad Sufiyan
[16]
160310737027
DCET
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.
Mohammad Sufiyan
[17]
160310737027
DCET
Mohammad Sufiyan
[18]
160310737027
DCET
OUTPUT
Mohammad Sufiyan
[19]
160310737027
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
DCET
OUTPUT
Mohammad Sufiyan
[21]
160310737027
DCET
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
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
DCET
Mohammad Sufiyan
[24]
160310737027
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
DCET
OUTPUT
Mohammad Sufiyan
[26]
160310737027
DCET
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
DCET
OUTPUT
Mohammad Sufiyan
[28]
160310737027
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.
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.
Mohammad Sufiyan
[30]
160310737027
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
DCET
OUTPUT
Mohammad Sufiyan
[32]
160310737027
DCET
Mohammad Sufiyan
[33]
160310737027
DCET
OUTPUT
Mohammad Sufiyan
[34]
160310737027
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
DCET
OUTPUT
Mohammad Sufiyan
[36]
160310737027
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
DCET
OUTPUT
Mohammad Sufiyan
[38]
160310737027
DCET
Mohammad Sufiyan
[39]
160310737027
DCET
OUTPUT
Mohammad Sufiyan
[40]
160310737027
DCET
Mohammad Sufiyan
[41]
160310737027
DCET
OUTPUT
Mohammad Sufiyan
[42]
160310737027
DCET
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
DCET
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
DCET
OUTPUT
Mohammad Sufiyan
[46]
160310737027
DCET
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
DCET
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
DCET
Mohammad Sufiyan
[51]
160310737027
DCET
Java and Web Technologies Lab } catch(InterruptedException e) { System.out.println("main thread interrupted"); } System.out.println("exit from main thread"); } }
DCET
OUTPUT
Mohammad Sufiyan
[53]
160310737027
DCET
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
Mohammad Sufiyan
[55]
160310737027
DCET
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.
Mohammad Sufiyan
[56]
160310737027
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
DCET
OUTPUT
Mohammad Sufiyan
[58]
160310737027
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
DCET
Mohammad Sufiyan
[61]
160310737027
DCET
OUTPUT
Mohammad Sufiyan
[62]
160310737027
DCET
DCET
OUTPUT
Mohammad Sufiyan
[64]
160310737027
DCET
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.
Mohammad Sufiyan
Java and Web Technologies Lab Interface set <E>. here E specifies the type of objects that set will hold.
DCET
interface Queue<E> E specifies the type of objects that the set will hold.
General declaration:
interface Dequeue<E> E specifies the type of objects that the set will hold. Mohammad Sufiyan [67] 160310737027
DCET
Mohammad Sufiyan
[68]
160310737027
DCET
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
DCET
OUTPUT
Mohammad Sufiyan
[70]
160310737027
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
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
DCET
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.
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
DCET
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
DCET
OUTPUT
Mohammad Sufiyan
[76]
160310737027
DCET
Mohammad Sufiyan
[77]
160310737027
DCET
OUTPUT
Mohammad Sufiyan
[78]
160310737027
DCET
OUTPUT:-
Mohammad Sufiyan
[79]
160310737027
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.
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
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.
Mohammad Sufiyan
[81]
160310737027
DCET
OUTPUT
Mohammad Sufiyan
[82]
160310737027
DCET
Mohammad Sufiyan
[83]
160310737027
DCET
OUTPUT
Mohammad Sufiyan
[84]
160310737027
DCET
Mohammad Sufiyan
[85]
160310737027
DCET
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
DCET
Mohammad Sufiyan
[88]
160310737027
DCET
Mohammad Sufiyan
[89]
160310737027
DCET
OUTPUT
Mohammad Sufiyan
[90]
160310737027
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
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
DCET
OUTPUT
Mohammad Sufiyan
[93]
160310737027
DCET
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
DCET
OUTPUT
Mohammad Sufiyan
[96]
160310737027
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
DCET
OUTPUT
Mohammad Sufiyan
[98]
160310737027
DCET
Mohammad Sufiyan
[99]
160310737027
DCET
Mohammad Sufiyan
[100]
160310737027
DCET
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
DCET
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
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
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
DCET
OUTPUT
Mohammad Sufiyan
[109]
160310737027
DCET
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
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
DCET
OUTPUT
Mohammad Sufiyan
[115]
160310737027
DCET
Mohammad Sufiyan
[116]
160310737027
DCET
OUTPUT
Mohammad Sufiyan
[117]
160310737027