0% found this document useful (0 votes)
12 views190 pages

Java Programming Basics and Concepts

The document provides an overview of various programming languages, focusing on Java and its features, including the differences between procedural and object-oriented programming. It discusses the characteristics of object-oriented programming, the need for Java, and the installation and configuration of the EditPlus IDE. Additionally, it covers Java data types, variable types, constructors, operators, and provides code examples to illustrate these concepts.

Uploaded by

Laxmi Pandey
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views190 pages

Java Programming Basics and Concepts

The document provides an overview of various programming languages, focusing on Java and its features, including the differences between procedural and object-oriented programming. It discusses the characteristics of object-oriented programming, the need for Java, and the installation and configuration of the EditPlus IDE. Additionally, it covers Java data types, variable types, constructors, operators, and provides code examples to illustrate these concepts.

Uploaded by

Laxmi Pandey
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd

Java

BASIC (Beginners All Purpose Symbolic Instruction Code)


COBOL (Common Business Oriented Language) Non - structured
FORTRON (Formula Translation) Procedural
ADA

C First Programmer’s Language by Dennis Richie

C++ Object Oriented Programming Skills by Bjarne Stroucstrup

Difference Between :
Procedural Programming Language Object Oriented Programming
Emphasis on :
Object
Attributes - Data
Behavior - Methods
Functions
Procedure

Characteristics of OOPS : Object A Object B


1) Polymorphism
2) Inheritance
3) Abstraction DATA Communication DATA
4) Encapsulation
METHODS METHODS

Encapsulation

Difference between JAVA and C++ :

JAVA C++

Java Source Code C++ Source Code


.java .cpp

1 Compiler converts 3 Compilers convert

.class Bytecode .exe Intermediate File


3 Interpreters 3 Interpreters

Window Unix Mac Window Unix Mac

Installing EDITPLUS :
Run  [Link]

To install cracker :
UNZIP  [Link]

Extract all files to  c:\Program Files\ EditPlus2\editpluscrack

Run  c:\Program Files\ EditPlus2\editpluscrack\[Link]

This will create three files. 1) dni 2) tCA) tCAedit201acrk

Copy them  c:\Program Files\ EditPlus2

Run  tCA_edit201acrk

Configure EDITPLUS2 :
Click - Tools  Configure User Tools
Select - Tools  User Tools  Group 1
Click - Add Tools  Program

Menu text : javac


Command : c:\jdk1.3\bin\[Link]
Argument : $(FileName)
Initial Directory : $(FileDir)

Menu text : java


Command : c:\jdk1.3\bin\[Link]
Argument : $(FileNameNoExt)
Initial Directory : $(FileDir)

Menu text : appletviewer


Command : c:\jdk1.3\bin\[Link]
Argument : $(FileName)
Initial Directory : $(FileDir)

Menu text : Javac1.4


Command : c:\j2sdk1.4.0_01\bin\[Link]
Argument : $(FileName)
Initial Directory : $(FileDir)

Menu text : Java1.4


Command : c:\j2sdk1.4.0_01\bin\[Link]
Argument : $(FileNameNoExt)
Initial Directory : $(FileDir)
The need for Java :
Java is developed in 1991. It is Architecture Independent. It is a language basically designed to
work in consumer electronics.
Earlier languages like BASIC, COBOL, FORTRON, ADA etc. were not suitable for system
programming because it was more structured and procedural in nature.
The first programmer’s language called ‘C’ was developed by Dennis Richie and ended up being
too complex.
C++ was developed by Bjarne Stroucstrup and was called as “C with classes” initially.
The four pillars of OOPS(Object Oriented Programming Skills) are :
1. Polymorphism
2. Inheritance
3. Data Abstraction(Hiding the implementation)
4. Encapsulation
In procedural programming focus is on procedures where as in object oriented programming
emphasis is given to data.
What we need to create and execute JAVA files :
1) JDK - lib (Libraries)
bin (All EXE Files)
JRE (Java Runtime Environment)
2) Note Pad Plus
3) Integrated Development Environment – Edit Plus

Run – Command – For Windows 95, Windows 98


cmd Windows 2000 and above

Set path at DOS prompt before you compile a file. - set path=c:\jdk1.4\bin
To compile a java file - javac <name of file with extension>
To execute / interpret a java file - java <name of file without extension>

class Hello
public static void main(String [] args)
{
[Link](“Hello”);
}

javac [Link]
java Hello

[Link](“Hello”);
In System class, we have 3 members (also known as Fields)
1) In - InputStream
2) Out - PrintStream
3) Err - PrintStream Err
println is in System class in Out field which is pointing to PrintStream.
Variables : A variable is a named part of memory giving 3 information –
int a = 10;
1) A data type it can hold
2) The name of the variable
3) The value of the variable

The three types of variables are :


1] Class Variables : A variable defined outside all methods and whose scope is throughout
the class is called Class Variable.
Class Variable takes a default value depending on its data type.
For calling methods of a class we should create an instance of that class.
In this example ‘x’ is a class variable. Name the file as [Link]
since it contains main().
class a Output :
{ 0
int x; 0
void met1()
{ [Link](x);
}
}
class ClassVariable
{
public static void main(String args[])
{
a m=new a();
m.met1();
[Link](m.x);
}
}

2] Method Variable : A variable defined inside a method and whose scope is only within
that method is called Method Variable.
Method Variable needs to be mandetarilly initialized.
class MethodVariable Output :
{ 10
void met1()
{
int x=10;
[Link](x);
}
public static void main(String args[])
{
MethodVariable p = new MethodVariable();
p.met1();
}
}
3] Instance Variable : Static Variables have only one memory location and all instances
share the same where as non-static variables can take separate values for
different instances.
All non-static Class Variables are called Instance Variables.
class InstanceVariable Output :
{ 60
static int x = 10; 20
int y = 20;
public static void main(String args[])
{
InstanceVariable i = new InstanceVariable();
i.x = 40;
i.y = 100;
InstanceVariable j = new InstanceVariable();
j.x = 60;
j.y = 200;
InstanceVariable k = new InstanceVariable();
[Link](k.x);
[Link](k.y);
}
}

Static / Non-static Methods :


Non-static methods requires an instance of a class where as static methods can be directly called
with class name.
Limitation of static methods is that it can access only static class variables.
The source code file name should be the name of the class in which public static void
main(String [] args) is there, so that the JVM can directly call it with the <filename>.main().
Method Variable can not be static because the scope is within the method.
Every object is not a instance but every instance is an object. Object has no memory location but
instance has. Instance has copy of that class. In Java every class has instance other than String.

class a Output :
{ 10
int x=10; 20
void met1()
{
[Link](x);
}
}
class b
{
//int y = 20;
//this will give compile error non-static variable cannot be referenced from static context

static int y=20;


static void met2()
{
[Link](y);
}
}
class StaticMethodTest
{
public static void main(String args[])
{
a m=new a();
m.met1();
b.met2();
}
}

Constructor : The Constructor is like a method having the same name as the class name,
without a return type and it is automatically called when an instance is created
with appropriate arguments.
The main purpose of a Constructor is to initialize the class variables.
The JVM will give a default Constructor only if there is no parameterized
constructor in the class.

Without Constructor With Constructor


class Student1 class Student2
{ {
String name; String name;
int id; int id;
void show() void show()
{ {
[Link]("Your Name = "+name); [Link]("Your Name = "+name);
[Link]("Your ID = "+id); [Link]("Your ID = "+id);
} }
} }
class Constructor1 Student2(String a, int b)
{ {
public static void main(String args[]) name = a;
{ id = b;
Student1 n=new Student1(); }
[Link]="Maya"; }
[Link]=100; class Constructor2
[Link](); {
} public static void main(String args[])
{
Student2 n2 = new Student2(“Maya”,100)
[Link]();
Student2 y = new Student2();
}
` }

Student2 y gives an error couse there is no


constructor without parameter

Data Types in Java :


Data Types

Predefined Primitive User Defined


class
structure
enum

1] Integral - byte - 8 bit - 28 = 256 -128 to 127


- short - 16 bit
- int - 32 bit
- long - 64 bit
2] Floating - float - 32 bit
- double 64 bit
3] Textual - char - 16 bit Unicode
4] Logical - boolean 1 bit

You can find more about Unicode on [Link] .org.


In ASCII storage system the last 7 bits are used to store data and the first bit is reserved for
storing sign. Hence it is difficult to store foreign language symbol, that’s where Unicode comes
handy.

1) There are two categories of data types in Java :


a) Primitive Data Type
b) User Defined Data Types (class, structure, enum)

2) All data type in Java are is strictly typed (range is fixed) and pre-defined.
3) Integral and Floating point data types are signed. The default of Integral category is int
and byte and short automatically get promoted to int when any calculation is done on
them.
4) Type casting means forcibly putting a large size data type into a smaller size which might
result in loss of precession.

class ByteText
{
public static void main(String args[])
{
byte a = 10;
byte b = 13;
//byte c = (a+b); // possible loss of precision
//[Link](c);
int c1 = (a+b);
[Link](c1); // output : 23
byte c2 = (byte) (a+b);
[Link](c2); // output : 23
byte c3 = (byte)(a*b);
[Link](c3); // output : -126
}
}
byte range is -128 to 127. When there is overflow it starts from beginning
-128 -127 -126
128 129 130

Auto conversion – smaller to bigger

byte short int double

Type casting – bigger to smaller

Long Type : Since the default of Integral category is int while initializing long if the value
goes beyond 32 bits we should have a ‘l’ or ‘L’ suffixed to the value.
class LongText
{
public static void main(String args[])
{
long a = 10;
long b = 12345678910;
[Link](a);
[Link](b);
}
}
Output : Compile Error - Integer number too large Solution : suffix ‘L’ or ‘l’
long b = 12345678910L;

Floating Type : The default of the floating type category is double and hence while
initializing float we should have a ‘f’ or ‘F’ suffixed to the value. Double gives
more precision.
class FloatText
{
public static void main(String args[])
{
float a = 10;
float b = 10.00;
[Link](a);
[Link](b);
}
}
Default of float is double that’s why in float b = 10.0 , 10.0 is treated as double. In this case you
are trying to store 64 bit value in 32 bit value. Solution for this is : float b = 10.0F;
OUTPUT : 10.0
10.0

char Type :
class CharText
{
public static void main(String args[])
{
char c = 'a';
int i = c;
[Link]("The ASCI Value of " +c + " is " + i);
}
}
OUTPUT : The ASCII value of a is 97.

boolean Type :
class BooleanText
{
static boolean a;
public static void main(String args[])
{
[Link](a);
}
}
OUTPUT : false
If static method calls non-static variable, the compile error is :
Non static variable ‘b’ cannot be referenced from a static context

Use of toString() :
class PlusText
{
public static void main(String args[])
{
int a = 10;
int b = 10;
String s = "Hello";
Integer i = new Integer(a);
String s1 = [Link]();
Integer j = new Integer(b);
String s2 = [Link]();
[Link](a+s+b);
[Link](s+s1+s2);
}
}
OUTPUT : 1010Hello
If we do not use toString() then it will be 20Hello.
[Link] - top most class. All classes inherit it. It is a Super class.

toString() - converts object into a string

Data Variables Wrapper Classes (convert each data variable into object)
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean

Operators :
1) Unary :
a) ‘+’ : All primitive data types are corresponding classes, the category of which is called
wrapper classes. The main purpose of a wrapper class is to convert the primitive data
types into an object.
The topmost class (super class) of all classes in Java is [Link] class which has
a method called toString() which converts the object into string.

b) “++” / “—“ : Incase of pre-increment the RHS is first incremented and then assigned to LHS
where as in post increment it is first assigned then incremented.
int a = 10;
[Link](a++); OUTPUT : 10
[Link](++a); OUTPUT : 11

int a =100; int a = 10; a b


a = a++; int b = 20 10 20
a = a++; a = ++b; 21 21
a = a++; b = a--; 20 21
OUTPUT : 100 b=++a;21 21 21

a = a++; In this case since it is same variable the memory location is same. Therefore a = 100
It wont check what is on the right side of the variable, hence ++ is ignored. But b = a++; there
are two variables, therefore different memory location. Therefore b = 100 and a = 101

c) ‘~’ Bitwise Inversion Operation : When used ~ all zeroes are changed to ones
advice versa
int a = 10; 00000000000000000000000000001010
int b = ~a; 11111111111111111111111111110101
[Link](b);
OUTPUT : -11

d) ! Boolean compliment operation :


e) cast ( ) :

2) Aritmetic Operator :
BODMAS - / * + - and %

3) Comparison Operators : All comparative operators return boolean type value.


a) Object Type
b) Memory Type
a) Object Type : The instance of keyword is used to check whether a instance on LHS
belongs to the class on the RHS or not.
This returns a value only when there is a relationship between the instance and a
class check.
class A
{
}
class B extends A
{
}
class C extends A
{
}
class InstanceText
{
public static void main(String[] args)
{
A x = new A();
B y = new B();
C z = new C();
[Link](x instanceof B);
[Link](y instanceof A);
[Link](z instanceof B);
}
}
Subclass knows everything about super class. In java multiple inheritance is not allowed.
OUTPUT : compiler error – inconvertible type - [Link](z instanceof B);

b) Memory Type : String is the only class in Java that can be created without the new
keyword. The two types of memory comparison operators are :
a) Based on location
b) Based on contents
The two types of memory locations are Stack and Heap.
Primitive data types are stored in Stack where as Objects are stored in Heap.
The “= =” operator checks for the memory location of its operand.
The equals() method in the Object class also acts like the “= =” operator but it
is overridden in String and Wrapper classes to check for the contents.

class MemoryText
{
public static void main(String args[])
{
String s = "Hello";
String s1 = "Hello";
String s2 = new String("Hello");
String s3 = new String("Hello");
MemoryText x = new MemoryText();
MemoryText y = new MemoryText();
int i = 10;
int j = 10;
Integer a = new Integer(i); //True
Integer b = new Integer(j); //False
[Link](s == s1 ); //False
[Link](s2 == s3); //True
[Link](x == y); //False
[Link]([Link](s3)); //True
[Link]([Link](y)); //False
[Link](i == j); //True
[Link]([Link](b)); //True
[Link](a == b); //False
}
}

STACK HEAP MEMORY


Primitive Data Objects Location Contents
s Hello – s2 equals – Object - = =
Hello Hello – s3 Overridden
s1 String & Wrapper
(check for contents)

4) Bitwise : & | ^
1 0 0 1
1 0 1 0
- - - -
1 0 1 1
Others 0 1 0 0

class BitwiseOperator
{
public static void main(String args[])
{
int a = 10;
int b = 20;
int c = a & b;
int d = a | b;
int e = a ^ b;
[Link](c); // 0
[Link](d); // 30
[Link](e); // 30
}
}

5) Short Circuit Operator : && / || If the LHS of “&&” is false the whole answer is
false without checking the RHS and if true will act like a normal ‘&’
operator.
class ShortCircuit
{
public static void main(String args[])
{
String s = null;
if ((s != null) & ([Link]() > 5))
{
[Link]("Inside");
}
[Link]("Finished");
}
}
OUTPUT : Runtime Error – [Link]() > 5 – NullPointerException

class ShortCircuit1
{
public static void main(String args[])
{
String s = null;
if ((s != null) && ([Link]() > 5))
{
[Link]("Inside");
}
[Link]("Finished");
}
}
OUTPUT : Finished

The two ways to convert a String into a primitive int is :


A) use the static method of Integer class called parseInt()
B) use the non static method of the Integer class called intValue()
class TernaryText
{
int max(int i, int j)
{
int c = (i > j)? i: j;
return c;
}
public static void main(String args[])
{
String s = args[0];
String s1 = args[1];
int p1 = [Link](s);
Integer i = new Integer(s1);
int p2 = [Link]();
TernaryText E = new TernaryText();
int r = [Link](p1, p2);
[Link](r );
}
}
Execute File – java TernaryText 10 20
In EditPlus software – click on Tools – Configure User Tools – select java -[x] prompt parameter

Flow Controls

loops selection jump


for if – else break
do – while if continue
while switch

switch : switch is used when


a) Branching is to balance based on a non boolean value
b) Multiple conditions have same output

class SwitchTest
{
public static void main(String args[])
{
for(int i=0;i<3;i++)
{
switch(i)
{
case 2:
{
[Link]("Two");
}
default:
{
[Link]("Default");
}
case 1:
{
[Link]("One");
}
}
}
}
}
In a switch case if break is not there between cases it will go in all the cases below a case which
is matched. Hence OUTPUT is :
One
One
Two
Default
One
Break : break should always be in a conditional black. You can use break in following :
Break
loops
switch
labeled breaks

Label Break : In case of a labeled break the break should be followed by the labeled name.
class LabelBreak
{
public static void main(String args[])
{
One:
{
Two:
{
Three:
{
[Link]("Before");
if(true)
{
break Two;
}
[Link]("After");
}
[Link]("After3");
}
[Link]("After2");
}
[Link]("After1");
}
}
OUTPUT : Before
After2
After1

Loop Break : To throw the control out of loop.


class BreakFor
{
public static void main(String[] args)
{
for (int i = 1; i < 10 ; i++ )
{
[Link](i);
if(i = = 4)
{
break;
}
}

}
}
OUTPUT : 1 2 3

Continue : Continue is used to manually go down to next alteration without reaching the end
of the current black.
class ContinueBreak
{
public static void main(String args[])
{
for(int i=0; i <10 ; i++)
{
if(i % 2 == 0)
{
continue;
}
[Link](i);
}
}
}
OUTPUT : 1 3 5 7 9

this : 1) The first use of this is it refer to the class variable when the parameter variable or
method variable hides the class variable.
class This1
{
int a;
This1(int a)
{
this.a = a;
}
public static void main(String args[])
{
This1 m = new This1(10);
[Link](m.a);
}
}
OUTPUT : 10

class This2
{
int x=10;
void met()
{
int x = 40;
[Link](x);
[Link](this.x);
}
public static void main(String args[])
{
This2 m = new This2();
[Link]();
[Link](m.x);
}
}
OUTPUT : 40
10
10

this : 2) The second use of this is to call another constructor of the same class from within a
constructor by passing appropriate arguments.
Web Site Form Database
Name : Name Salary
Salary : Yes Yes
OK No (Unknown) Yes
Yes No (0)
No (Unknown) No (0)

class This3
{
String name;
int sal;
This3(String s, int i)
{
name=s;
sal=i;
[Link]("Name : "+name);
[Link]("Salary : " + sal);
}
This3(String s)
{
this(s,0);
}
This3(int i)
{
this("Unknown",i);
}
This3()
{
this(0);
}
public static void main(String args[])
{
This3 w = new This3("Maya", 1000);
This3 x = new This3("Sangeeta");
This3 y = new This3(5000);
This3 z = new This3();
}
}
OUTPUT : Name : Maya
Salary : 1000
Name : Sangeeta
Salary :0
Name : Unknown
Salary : 5000
Name : Unknown
Salary :0

Super Keyword : 1) The first use of super is to refer to a super class variable or method
which is hidden (variable) or overridden (method) in the super class.
Super can be written only in now static.
class A
{
int x = 10;
void met1()
{
[Link](x);
}
}

class Super1 extends A


{
int x=100;
void met1()
{
[Link]("Super1");
[Link](super.x);
super.met1();
}
public static void main(String args[])
{
Super1 p = new Super1();
p.met1();
[Link](p.x);
}
}
OUTPUT : Super1
10
10
100

Super : 2) The second use of super is to call a specific super class constructor from the
subclass’s constructor by passing appropriate arguments.
The call to super should be in the first line of the sub class’s constructor.

Form 1 Form 2 Form 3

Length : Length :
Calculate Area Breadth : Breadth :
Height :
Calculate Volume
Area Area Volume

class Area
{
int l, b;
Area(int a, int b)
{
l=a;
this.b = b;
}
void calArea()
{
int c = l * b;
[Link]("Area : "+c);
}
}
class Volume extends Area
{
int h;
Volume(int a, int b, int c)
{
super(a,b);
h=c;
}
void calVolume()
{
int v = l * b * h;
[Link]("Volume : " + v);
}
public static void main(String args[])
{
Volume x = new Volume(10,20,30);
[Link]();
[Link]();
}
}
OUTPUT : Area : 200
Volume : 6000

Order of Constructor calling :


All subclasses constructor have a implicit super in its first line which calls the default constructor
of super class. This is necessary because the super class methods and variables should be loaded
in memory before the subclass is created.
class A
{
A() { [Link]("One"); }
}
class B extends A
{
B() { [Link]("Two"); }
}
class C extends B
{
C() { [Link]("Three"); }
}
class ConstuctorOrder1
{
public static void main(String args[])
{ C x = new C(); }
}

OUTPUT : One
Two
Three

class A
{
A()
{ [Link]("One"); }
void met1() { [Link]("Met1"); }
}
class B extends A
{
B()
{ [Link]("Two"); }
}
class C extends B
{
C()
{ [Link]("Three"); }
}
class ConstuctorOrder2
{
public static void main(String args[])
{
C x = new C();
x.met1();
}
}
OUTPUT : One
Two
Three
Met1

class A
{
A()
{ [Link]("One"); }
}
class B extends A
{
B(int i)
{ [Link]("Four"); }
}
class C extends B
{
C()
{
[Link]("Three");
}
}
class ConstuctorOrder3
{
public static void main(String args[])
{
C x = new C();
}
}
OUTPUT : Compile Error – can not resolve symbol – Symbol : constructor B

class A
{
A()
{
[Link]("One");
}
}
class B extends A
{
B(int i)
{
[Link]("Four");
}
}
class C extends B
{
C()
{
super(10);
[Link]("Three");
}
}
class ConstuctorOrder4
{
public static void main(String args[])
{
C x = new C();
x.met1();
}
}
OUTPUT : One
Four
Three
Call by reference / Call by value :
Primitive data types in Java is passed by value where as objects are always passed by reference.

class CallByReference
{
int a, b;
CallByReference(int x, int y)
{
a = x;
b = y;
}
void met1(CallByReference m)
{
m.a =m.a * 2;
m.b =m.b / 2;
}
public static void main(String[] args)
{
CallByReference p1 = new CallByReference(10, 20);
[Link](p1.a+" "+p1.b);
p1.met1(p1);
[Link](p1.a+" "+p1.b);
p1.met1(p1);
[Link](p1.a+" "+p1.b);
}
}
OUTPUT : 10 20
20 10
40 5

Call by value :
class CallByValue
{
int met1(int a)
{
return ++a;
}
public static void main(String[] args)
{
int i = 10;
CallByValue p = new CallByValue();
int j = p.met1(i);
[Link](i);
[Link](j);
}
}
INNER CLASS
1) Normal Inner Class : For a normal inner class a instance of the outer class is
mandatory and through that instance a inner class instance class
instance can be created.
The inner class can access even the private variable of the outer class
but not vise versa.
Two class files created would be [Link] and A$[Link] after you
compile.
class A
{
private int x = 10;
class B
{
int y=20;
void met1()
{
[Link](x+" "+y);
}
}
}
class Inner1
{
public static void main(String args[])
{
A m = new A();
A.B n = [Link] B();
n.met1();
}
}
OUTPUT : 10 20

2) Static Inner Class : Inner classes can not have static keywords but in case it has one
the whole class should be declared as static inner class.
class A
{
static int x = 10;
class B
{
static int y=20;
static void met1()
{
[Link](x+" "+y);
}
}
}

class Inner2
{
public static void main(String args[])
{
A.B.met1();
[Link](A.x);
[Link](A.B.y);
}
}
OUTPUT : Compile Error – inner classes can not have static declaration

class A
{
static int x = 10;
static class B
{
static int y=20;
static void met1()
{
[Link](x+" "+y);
}
}
}
class Inner2
{
public static void main(String args[])
{
A.B.met1();
[Link](A.x);
[Link](A.B.y);
}
}
OUTPUT : 10 20
10
20

3) Inner class inside a method : Any outer class method variable which will be
accessed in the inner class should be declared as final.
The inner class instance should be created and the inner class
methods should be called before exiting the outer class method.
class M
{
int x = 10;
void met1()
{
final int y=20;
class N
{ int z = 30;
void met2()
{
[Link](x+" "+y+" "+z);
}
}
N p = new N();
p.met2();
[Link]("Back");
}
}
class Inner3
{
public static void main(String args[])
{
M a = new M();
a.met1();
}
}
OUTPUT : 10 20 30
Back

Over Loading :
Over loading means having the same method name but different type and order of parameters.
Overloading can not be done based only on return types.
class OverLoad1
{
void met1()
{
[Link]("A");
}
int met1()
{
[Link]("B");
return 10;
}
public static void main(String args[])
{
OverLoad1 o = new OverLoad1();
o.met1();
}
}
OUTPUT : Compile Error – met1() is already defined in OverLoad1

class OverLoad2
{
void met1(int a)
{
[Link]("A");
}
int met1(String s)
{
[Link]("B");
return 0;
}
public static void main(String args[])
{
OverLoad2 o = new OverLoad2();
o.met1(10);
}
}
OUTPUT : A

PACKAGES :

The scope of a private variable in only in the class in which it is declared.


The scope of default or friendly is in all classes in the same package either by
a) Inheritance OR b) by creating an instance
The visibility of the protected is like default as well as in another class in another package only if
there is an inheritance and a instance of sub class is mandatory for non static variables (static
variables can be called without creating an instance)
The visibility of public is in all classes in any Package.

package One;
public class Pack1
{
private int x1 = 10;
static int x2 = 20;
protected int x3 = 30;
protected static int x4 = 40;
public int x5 = 50;
}

Save this file as [Link] under the same folder : c:\students\Maya>


Set the path : c:\students\Maya>set path=c:\jdk1.3\lib
Compile the file : c:\students\Maya>javac –d . [Link]
The above command creates One folder under Maya and saves compiled file [Link] in One.
package One;
class Pack2 extends Pack1
{
public static void main(String [] args)
{
//[Link](x1);
[Link](x2);
//[Link](x3);
[Link](x4);
//[Link](x5);
}
}

Save this file as [Link] under the same folder : c:\students\Maya>


Compile the file : c:\students\Maya>javac –d . [Link]
Run the file : c:\students\Maya>java One.Pack2

OUTPUT : Compile Error – x1 private access in One.Pack1


x3 non static variable can not be referenced from a static
x5 non static variable can not be referenced from a static
Hence comment these 3 lines using “//” and save and compile [Link] file.
OUTPUT : 20
40

package One;
class Pack3
{
public static void main(String [] args)
{
Pack1 m = new Pack1();
//[Link](m.x1);
[Link](m.x2);
[Link](m.x3);
[Link](m.x4);
[Link](m.x5);
}
}

OUTPUT : Compile Error - x1 private access in One.Pack1


Non static variables x3 and x5 are getting printed because instance of Pack1 class is created to
refer to them. Non static variables can be called in static methods by referring them by the
instance. Comment x1 and then save the file.
Save this file as [Link] under the same folder : c:\students\Maya>
Compile the file : c:\students\Maya>javac –d . [Link]
Run the file : c:\students\Maya>java One.Pack3
OUTPUT : 20 30 40 50
package Two;
import One.*;
class Pack4
{
public static void main(String [] args)
{
Pack1 n = new Pack1();
//[Link](n.x1);
//[Link](n.x2);
//[Link](n.x3);
//[Link](n.x4);
[Link](n.x5);
}
}
Save this file as [Link] under the same folder : c:\students\Maya>
Compile the file : c:\students\Maya>javac –d . [Link]
Run the file : c:\students\Maya>java Two.Pack4
The above command creates Two folder under Maya and saves compiled file [Link] in
Two.

OUTPUT : Compile Error – n.x1 private access in One.Pack1


n.x2 not public in Pack1. default has a scope within same package
n.x3 has a protected access in Pack1. Protected has a scope within the
same package & in another package only inherited class
n.x4 on has a protected access in Pack1. Protected has a scope within
the same package & in another package only inherited class
package Two;
import One.*;
class Pack5 extends Pack1
{
public static void main(String [] args)
{
Pack1 p = new Pack1();
//[Link](p.x1);
//[Link](p.x2);
//[Link](p.x3);
[Link](p.x4);
[Link](p.x5);

Pack5 p1 = new Pack5();


//[Link](p1.x1);
//[Link](p1.x2);
[Link](p1.x3);
[Link](p1.x4);
[Link](p1.x5);
}
}

Save this file as [Link] under the same folder : c:\students\Maya>


Compile the file : c:\students\Maya>javac –d . [Link]
Run the file : c:\students\Maya>java Two.Pack5

OUTPUT : Compile Error – p.x1 private access in One.Pack1


p.x2 not public in Pack1. default has a scope within same package
p.x3 has a protected access in Pack1. Protected has a scope within the
same package & in another package only inherited class. But the
non static variables can be referenced only by the instance of
subclass
p1.x1 private access in One.Pack1
p1.x2 not public in Pack1. default has a scope within same package
OUTPUT : After commenting the above lines : 40 50 30 40 50

Save all java files under same folder c:\students\Maya. Compile files [Link], [Link]
and [Link] get created in folder One whereas [Link] and [Link] get created in
folder Two.

Over Riding : When in a method in the sub class has the same signature as that of the super
class, the sub class method is set to over ride the super class method.
The six parts in the signature of a method are :
1) Visibility Modifier
2) Keyword
3) Return Type
4) Name
5) Parameters
6) Throws Conditions

The main rule of over riding that the signature of the method should be the same.
The two exceptions to this rule are :
1) the overriding method can not be less accessible than the overridden
method
2) the over riding method can not throw super classes of the exception that is
thrown by the overridden method.

class A
{
public void met1()
{
[Link]("A");
}
}
class OverRidden extends A
{
void met1()
{
[Link]("OVERRIDDEN");
}
public static void main(String args[])
{
OverRidden o = new OverRidden();
o.met1();
}
}
OUTPUT : Attempting to assign weaker access privilege.
Because overriding method OverRidden.met1(), has less accessibility (default) than
the overridden method A.met1() (public).

class A
{
public void met1()
{
[Link]("A");
}
}
class OverRidden extends A
{
void met1()
{
[Link]("OVERRIDDEN");
}
public static void main(String args[])
{
OverRidden o = new OverRidden();
o.met1();
}
}
OUTPUT : OVERRIDDEN

The hierarchy of Throwable Exception


Throwable

Error Exception

RuntimeException

class A
{
void met1() throws Exception
{
[Link]("A");
}
}
class Throw1 extends A
{
void met1() throws Exception
{
[Link]("OVERRIDDEN");
}
public static void main(String args[])throws Exception
{
Throw1 o = new Throw1();
o.met1();
}
}

OUTPUT : OVERRIDDEN
If we don’t write throws Exception with main(), there will be a compile error – Unprotected
Exception
Same level throws Exception creates no error.

class A
{
void met1() throws Exception
{
[Link]("A");
}
}
class Throw2 extends A
{
void met1()
{
[Link]("OVERRIDDEN");
}
public static void main(String args[])
{
Throw2 o = new Throw2();
o.met1();
}
}

OUTPUT : OVERRIDDEN
No error since over ridden method throwing higher level Exception than the over riding method.
class A
{
void met1() throws Exception
{
[Link]("A");
}
}
class Throw3 extends A
{
void met1() throws RuntimeException
{
[Link]("OVERRIDDEN");
}
public static void main(String args[])
{
Throw3 o = new Throw3();
o.met1();
}
}

OUTPUT : OVERRIDDEN
No error since the method in super class is throwing Exception of the higher level than the over
riding method in the sub class from the Throwable hierarchy.

class A
{
void met1() throws Exception
{
[Link]("A");
}
}
class Throw4 extends A
{
void met1() throws Throwable
{
[Link]("OVERRIDDEN");
}
public static void main(String args[])
{
Throw4 o = new Throw4();
o.met1();
}
}

OUTPUT : Compile Error – met1() in Throw4 does not throw Throwable.


Because overriding method is throwing higher level Exception than over method.
Late Binding / Virtual Method Invocation / Runtime Polymorphism / Dynamic Binding
In late binding we create the instance of the super class but call the constructor of the sub class,
only to check if a upper class method is overridden in the in the sub class or not.
class A
{
int x = 10;
A()
{
[Link]("Constructor in A");
}
void met1()
{
[Link]("met1 in A");
}
void met2()
{
[Link]("met2 in A");
}
}
class B extends A
{
int x = 20;
B()
{
[Link]("Constructor in B");
}
void met1()
{
[Link]("met1 in B");
}
void met3()
{
[Link]("met3 in B");
}
}
class LateBinding
{
public static void main(String args[])
{
A m = new B();
[Link](m.x);
m.met1();
m.met2();
//m.met3();
}
}

OUTPUT : Compile Error – can not resolve symbol met3(). Comment it.
OUTPUT : Constructor in A
Constructor in B
10
met1 in B
met2 in A

A m = new B(); is same as A m = new A();


B n = new B();
m = n;
Creating an object of class A and invoking the constructor of B which invokes constructor of A
(super class).

Abstract Classes :
1. A method without a body is called abstract method.
2. If a class has an abstract method the whole class should be declared as abstract class.
3. Any sub class extending the abstract class should override all the abstract methods of the
super class.
4. Abstract classes can have non abstract methods.
5. Abstract classes can not be instantiated.
6. Abstract classes need not have an abstract method.

In order to prevent Instance creation


 Declare class as Abstract.
 Declare constructor of the class private.

abstract class Shape1


{
abstract void area();
void met1()
{
[Link]("met1 in shape1");
}
}
class Square extends Shape1
{
void area()
{
[Link]("area in Square");
}
}
class Rectangle extends Shape1
{
void area()
{
[Link]("area in Rectangle");
}
}
class Abstract1
{
public static void main(String args[])
{
//Shape1 x = new Shape1();
Square a = new Square();
[Link]();
a.met1();
Rectangle b = new Rectangle();
[Link]();
b.met1();

}
}

OUTPUT : Compile Error – Shape1() is abstract; can not be instantiated. Comment it.
OUTPUT : met1 in Shape1
area in Square
area in Rectangle
met1 in Shape1

Interface :
To over ride met1() and met2() methods from different classes in one class, you need to inherit
class A and class B. But multiple inheritance is not allowed in Java. That’s where you need to
use interface.
An interface is like a class but having all methods as public and abstract and all variables as
static, public and final.
A class can extend only one class but can implement multiple interfaces.
Any class implementing an interface should override all the methods of that interface.
interface A
{
public void met1();
}
interface B
{
final int x = 10;
public void met2();
}
class Interface1 implements A, B
{
public void met1()
{
[Link]("met1 in Interface1");
}
public void met2()
{
[Link]("met2 in Interface1");
}
public static void main(String args[])
{ [Link](B.x); }
}

OUTPUT : 10
Applets :
Application Applet
1) console Browser
2) main() init() once in life cycle
start maximize multiple time
stop minimize multiple time
destroy once in life cycle
3) [Link]() paint()

1) An applet in a Java class file embedded in a htm; page which is loaded and
executed by the browser
2) Applets require browser where as Applications are console (DOS prompt) based.
3) The entry point in an Application in the main() method where as the life cycle
methods of an Applet are init(), start(), stop() and destroy().
4) init() and destroy() are called only once in the life cycle where as start() and stop()
is called whenever the Applet is maximized and minimized respectively.
5) In an Application for printing we use [Link]() method where as in
Applet we use the paint() method.

import [Link].*;
import [Link].*;
public class MyApplet extends Applet
{
public void paint(Graphics g)
{
[Link]("Hello",100,100);
}
}
Save this file as [Link] and compile. Don’t execute the file.
In NotePlus  Tools  Configure User Tools  java  [ ] Capture Output (Remove)

Click new  File  html and save this file as [Link]


<BODY>
<APPLET code=[Link] width=400 height=400 >
</APPLET>
</BODY>
Save this file [Link] and press CTRL+3 to see appletview. When you click CTRL+3,
[Link] file get executed which run Applet [Link] which prints “Hello” at 100 th
row and 100th column.
Next Applet takes values (parameters) from HTML page and print it on the screen.

import [Link].*;
import [Link].*;
public class ParamApplet extends Applet
{
String s;
int x,y;
public void init()
{
s = getParameter("N");
String s1 = getParameter("X");
String s2 = getParameter("Y");
x = [Link](s1);
Integer j = new Integer(s2);
y=[Link]();
}
public void paint(Graphics g)
{
[Link](s,x,y);
}
}

Click new  File  html and save this file as [Link]


<BODY BGCOLOR="#FFFFFF">
<Applet code=[Link] width=400 height=400>
<Param name="N" value="ABC">
<Param name="X" value="100">
<Param name="Y" value="200">
</Applet>
</BODY>

OUTPUT : ABC get printed at 100th row and 100th column


Life Cycle of an Applet : String is an immutable class whereas StringBuffer is a mutable object
which means any changes.
We use the toString() method to convert an Object to a string.

import [Link].*;
import [Link].*;
public class LifeCycleApplet extends Applet
{
StringBuffer sb;
public void init()
{
sb = new StringBuffer();
[Link]("init ");
}
public void start()
{
[Link]("start ");
}
public void stop()
{
[Link]("stop ");
}
public void paint(Graphics g)
{
[Link]([Link](),100,100);
}
}

Click new  File  html and save this file as [Link]


<BODY BGCOLOR="#FFFFFF">
<APPLET code=[Link] height=400 width=400>
</APPLET>
</BODY>

cannot change String Immutable


same memory StringBuffer Mutable

append
insert

Method In Applet :
getCodeBase() getDocumentBase()
returns URL returns URL
in java net
Directory .class Directory + Html File
File:/c:/students/Maya File:/c:/students/Maya/[Link]
Four parts of URL : 1) Protocol, 2) DNS, 3) Port, 4) File
The getCodeBase( ) method returns the directory of .class file whereas
getDocumentBase( ) method returns the directory of the HTML file with
HTML file name.

import [Link].*;
import [Link].*;
import [Link].*;
public class CodeDocTextApplet extends Applet
{
URL u1, u2;
public void init()
{
u1 = getCodeBase();
u2 = getDocumentBase();
}
public void paint(Graphics g)
{
[Link]([Link](),50,50);
[Link]([Link](),50,100);
}
}

Click new  File  html and save this file as [Link]


<BODY>
<APPLET code=[Link] HEIGHT=200 WIDTH=400 >
</APPLET>
</BODY>

AWT-(Abstract Window Toolkit) :


Three categories of AWT controls are :
1. Non-Menu Components
2. Container Components
3. Menu Components
Two categories of Container Components are :
1. Panel and Applet
2. Window and Frame
Two reasons for the bifurcation :
1. Based on the type of Application
2. Based on the type of Layout Manager

Panel and Applet has Flow Layout as its default Layout Manager and Frame and Window has
Border as its Layout Manager

AWT(GUI)

Component Container Menu


(Non-menu Component)
Panel Window

Label Applet Frame Only one control


Text Field 1) Type of Application N
Text Area Browser Console
Button 2) Layout Manager (DOS Base)
List Flow Border W C E
Choice
Scrollbar S
Canvas

In a Border Layout one control in one position in a frame at a time.


Login _[ ]X
1) Application and Applet

Login : Password :

1) Application
import [Link].*;
class Login
{
Frame f;
Label l1, l2;
TextField tf1, tf2;
Button b1;
Login()
{
f=new Frame("Login");
l1=new Label("Login");
l2=new Label("Password");
tf1=new TextField(10);
tf2=new TextField(10);
b1=new Button("OK");

//Change in Layout Manager if necessary


[Link](new FlowLayout());

[Link](l1);
[Link](tf1);
[Link](l2);
[Link](tf2);
[Link](b1);

[Link](100,400);
[Link](true);
}
public static void main(String args[])
{
Login x = new Login();
}
}

1) Applet
import [Link].*;
import [Link].*;
public class LoginApplet extends Applet
{
Frame f;
Label l1, l2;
TextField tf1, tf2;
Button b1;

public void init()


{
f=new Frame("Login");
l1=new Label("Login");
l2=new Label("Password");
tf1=new TextField(10);
tf2=new TextField(10);
b1=new Button("OK");

add(l1);
add(tf1);
add(l2);
add(tf2);
add(b1);

}
}

Click new  File  html and save this file as [Link]


<BODY>
<APPLET code= [Link] HEIGHT=200 WIDTH=400 >
</APPLET>
</BODY>

Listener :

1. An Event is an object generated by the component on user inter action


2. An Event Source is a component which generated the Event.
3. An Event Listener is an object to which the component has delegated the task of handling
the Event.
4. The Event Handlers are the methods inside the Event Listener which actually handle the
Event.
5. The Event Listener should be registered with the Event Source to receive Events.

Application 1 : Take a Login and Password from the user and display it on the screen on
clicking OK button and clear both the TextFields on clicking RESET button.
Login _[ ]X
Login : Password : OK RESET

import [Link].*;
import [Link].*;
import [Link].*;
class Login1 implements ActionListener
{
Frame f;
Label l1, l2;
TextField tf1, tf2,tf3;
Button b1, b2;

Login1()
{
f=new Frame("Login");
l1=new Label("Login");
l2=new Label("Password");
tf1=new TextField(10);
tf2=new TextField(10);
tf3 =new TextField(35);
b1=new Button("OK");
b2=new Button("RESET");

//Change in Layout Manager if necessary


[Link](new FlowLayout());

[Link](l1);
[Link](tf1);
[Link](l2);
[Link](tf2);
[Link](b1);
[Link](b2);
[Link](this);
[Link](this);
[Link]('*');

[Link](100,400);
[Link](true);
}
public void actionPerformed(ActionEvent e)
{
if ([Link]() == b1)
{
String s = [Link]();
String s1 = [Link]();
[Link]("Login = "+s+" "+"Password = "+s1);
}
else
{
[Link](" ");
[Link]("");
}
}
public static void main(String [] args)
{
Login1 x = new Login1();
}
}

Applet 1 : Take a Login and Password from the user and display it on the third TextField which
appears only on clicking OK button and clear both the TextFields on clicking RESET
button.
Login _[ ]X

Login : Password : OK RESET

import [Link].*;
import [Link].*;
import [Link].*;
public class LoginApplet1 extends Applet implements ActionListener
{
Frame f;
Label l1, l2;
TextField tf1, tf2, tf3;
Button b1,b2;

public void init()


{
f=new Frame("Login");
l1=new Label("Login");
l2=new Label("Password");
tf1=new TextField(10);
tf2=new TextField(10);
tf3=new TextField(35);
b1=new Button("OK");
b2=new Button("RESET");
[Link](false);

add(l1);
add(tf1);
add(l2);
add(tf2);
add(b1);
add(b2);
add(tf3);

[Link](this);
[Link](this);
[Link]('*');

public void actionPerformed(ActionEvent e)


{
if([Link]() == b1)
{
String s = [Link]();
String s1 = [Link]();
[Link]("Login : "+s+" "+"Password : "+s1);
[Link](true);
}
else
{
[Link](false);
[Link](" ");
[Link]("");
}
validate(); // to rearrange controls
repaint(); // to get back to original screen
}
}

Click new  File  html and save this file as [Link]


<BODY>
<Applet code=[Link] height=100 width=400 >
</Applet>
</BODY>

Application 2 : Display 4 Buttons (“NORTH”, “SOUTH”, “EAST”,”WEST”) in four parts of


Frame and TextArea in the center. On clicking any button, display the button
name in the TextArea.
NORTH

W NORTH E
E EAST A
S CENTRE S
T T

SOUTH
import [Link].*;
import [Link].*;
import [Link].*;
class Frame1 implements ActionListener
{
Frame f;
TextArea ta;
Button b1, b2, b3, b4;

Frame1()
{
f = new Frame("Border Frame");
ta = new TextArea(20,20);
b1 = new Button("NORTH");
b2 = new Button("SOUTH");
b3 = new Button("EAST");
b4 = new Button("WEST");

[Link](b1,[Link]);
[Link](b2,[Link]);
[Link](b3,[Link]);
[Link](b4,[Link]);
[Link](ta,[Link]);

[Link](this);
[Link](this);
[Link](this);
[Link](this);

[Link](400,400);
[Link](true);
}
public void actionPerformed(ActionEvent e)
{
if([Link]() == b1)
[Link]("NORTH\n");
else
if([Link]() == b2)
[Link]("SOUTH\n");
else
if([Link]() == b3)
[Link]("EAST\n");
else
[Link]("NORTH\n");
}
public static void main(String [] args)
{
Frame1 f = new Frame1();
}
}

Applet 2 : Same as above


import [Link].*;
import [Link].*;
import [Link].*;
public class FrameApplet1 extends Applet implements ActionListener
{
Frame f;
TextArea ta;
Button b1, b2, b3, b4;

public void init()


{
f = new Frame("Border Frame");
ta = new TextArea(20,20);
b1 = new Button("NORTH");
b2 = new Button("SOUTH");
b3 = new Button("EAST");
b4 = new Button("WEST");

add(b1,[Link]);
add(b2,[Link]);
add(b3,[Link]);
add(b4,[Link]);
add(ta,[Link]);

[Link](this);
[Link](this);
[Link](this);
[Link](this);
}
public void actionPerformed(ActionEvent e)
{
if([Link]() == b1)
[Link]("NORTH\n");
else
if([Link]() == b2)
[Link]("SOUTH\n");
else
if([Link]() == b3)
[Link]("EAST\n");
else
[Link]("NORTH\n");
validate();
repaint();
}
}

Click new  File  html and save this file as [Link]


<BODY>
<Applet code=[Link] height=100 width=400 >
</Applet>
</BODY>

Rules of AWT : 1) Declare the Controls.


2) Initialize the Controls in Constructor or init() method.
3) Change Layout Manager.
4) Add Controls to Container.
5) Register the Listener.
6) Set Size and Visibility of the Frame.

Frame is for grouping Controls.


Panel is for grouping Components.

Applet

Hi

Hi OK

import [Link].*;
import [Link].*;
import [Link].*;
public class FramePanel extends Applet implements ActionListener
{
Frame f;
TextField tf1;
Button b1;
Panel p;
TextArea ta1;

public void init()


{
f = new Frame("Frame With Panel");
tf1 = new TextField(20);
b1 = new Button("OK");
p = new Panel();
ta1 = new TextArea(10,20);
add(ta1);
add(p);
[Link](tf1);
[Link](b1);
add(p,[Link]);
[Link]();
[Link](this);
[Link](this);
}
public void actionPerformed(ActionEvent e)
{
String s = [Link]();
[Link](" ");
[Link]();
[Link](s+"\n");
}
}

Click new  File  html and save this file as [Link]


<BODY>
<Applet code=[Link] height=100 width=400 >
</Applet>
</BODY>

Applet : Whatever is typed inside TextField is added to dropdown Choice Popup when ADD
Button is selected and is deleted from dropdown Choice Popup when DELETE Button
is clicked.

ADD DELETE

import [Link].*;
import [Link].*;
import [Link].*;
public class FramePopup extends Applet implements ActionListener
{
Frame f;
TextField tf1;
Button b1,b2;
Choice c;
public void init()
{
f = new Frame("Frame With Popup");
tf1 = new TextField(20);
b1 = new Button("ADD");
b2 = new Button("DELETE");
c = new Choice();
add(tf1);
add(b1);
add(b2);
add(c);
[Link](this);
[Link](this);
}
public void actionPerformed(ActionEvent e)
{
if([Link]() == b1)
{
String s = [Link]();
[Link](s);
[Link](" ");
}
else if([Link]() == b2)
{
String s1 = [Link]();
[Link](s1);
[Link](" ");
}
[Link]();
[Link]();
}
}

Click new  File  html and save this file as [Link]


<BODY>
<Applet code=[Link] height=100 width=400 ></Applet>
</BODY>

Application : There are two Panels with different background. In one panel, there are two
Buttons. On clicking ADD Button, a TextField appears. Whatever user type in
this TextField is added as a Button in second Panel and at the same time the
TextField disappears. On clicking DELETE Button, again a TextField appears.
After user type in this TextField, the same name Button gets deleted from second
Panel.
ADD DELETE ADD DELETE

import [Link].*;
import [Link].*;
import [Link].*;
class FramePanel2 implements ActionListener
{
Frame f;
Panel p1, p2;
TextField tf1, tf2;
Button b1,b2;

FramePanel2()
{
f=new Frame("Frame with Panels");
p1 = new Panel();
[Link]([Link]);
p2 = new Panel();
[Link]([Link]);
b1 = new Button("ADD");
b2 = new Button("DELETE");

//Change in Layout Manager if necessary


[Link](new FlowLayout());

[Link](p1);
[Link](b1);
[Link](b2);
[Link](p2);

[Link](this);
[Link](this);

[Link](400,400);
[Link](true);
}
public void actionPerformed(ActionEvent e)
{
if ([Link]() == b1)
{
tf1 = new TextField(20);
[Link](this);
[Link](tf1);
[Link]();
[Link](false);
[Link](false);
}
else
if([Link]() == tf1)
{
String s1 = [Link]();
[Link](" ");
[Link](tf1);
Button b3 = new Button(s1);
[Link](b3);
[Link](true);
[Link](true);
}
else
if([Link]() == b2)
{
tf2 = new TextField(20);
[Link](this);
[Link](tf2);
[Link]();
[Link](false);
[Link](false);
}
else
if([Link]() == tf2)
{
String s2 = [Link]();
Component c[] = [Link]();
for(int i = 0; i < [Link]; i++)
{
if(c[i] instanceof [Link])
{
Button b4 = (Button) c[i];
if([Link]([Link]()))
{
[Link](b4);
}
}
}
[Link](tf2);
[Link](true);
[Link](true);

Component c1[] = [Link]();


if([Link] == 0)
{
[Link](false);
}
}
[Link]();
[Link]();
}
public static void main(String [] args)
{
FramePanel2 x = new FramePanel2();
}
}

Application : Menu “File” is displayed on the Frame. On clicking File the Popup containing
“Open”, “Save” and “Exit”; options are displayed. On clicking “Open” option
FileDialog appears which let user to open file from hard disk. On clicking “Save”
option FileDialog appears which let user to save file to hard disk. On clicking
“Exit” option Panel containing “YES” and “NO” Buttons appear. On clicking
“YES” Button application is closed whereas on clicking “NO” Button, Panel
disappear.
File Menu m;
Open MenuBar mb;
Save MenuItem m1, m2, m3;
Exit

import [Link].*;
import [Link].*;
class FrameMenu implements ActionListener
{
Frame f;
Menu m;
MenuBar mb;
MenuItem m1, m2, m3;
Panel p;
Button b1, b2;
Dialog d;
FileDialog fd1, fd2;

FrameMenu()
{
f=new Frame("Frame with Menu");
m = new Menu("File");
mb = new MenuBar();
m1 = new MenuItem("Open");
m2 = new MenuItem("Save");
m3 = new MenuItem("Exit");
fd1 = new FileDialog(f, "Open File",[Link]);
fd2= new FileDialog(f, "Save File",[Link]);
d = new Dialog(f, "Are You Sure");
p = new Panel();
b1 = new Button("YES");
b2 = new Button("NO");

//Change in Layout Manager if necessary


//[Link](new FlowLayout());

[Link](m1);
[Link](m2);
[Link](m3);
[Link](m);
[Link](mb);

[Link](this);
[Link](this);
[Link](this);

[Link](200,200);
[Link](true);
}
public void actionPerformed(ActionEvent e)
{
if ([Link]() == m1)
{
[Link]();
}
else
if([Link]() == m2)
{
[Link]();
}
else
if([Link]() == m3)
{
[Link](100,100);
[Link](true);
[Link](p);
[Link](b1);
[Link](b2);
[Link](this);
[Link](this);
}
else
if([Link]() == b1)
{
[Link](0);
}
else
if([Link]() == b2)
{
[Link](false);
}
[Link]();
[Link]();
}
public static void main(String [] args)
{
FrameMenu x = new FrameMenu();
}
}

Adjustment Listener :
ScrollBar
Public void adjustmentValueChanged(ActionEvent e)
{
----
----
}

Applet : Three ScrollBars each displaying colour value for r, g, and b respectively. On changing
these three values, the TextField as well as the Background color is changed to that
color and at the same time color code is displayed in TextField.
ScrollBar sb1, sb2, sb3;
Sb1 = new ScrollBar([Link],
0, starting point
1, increment
0, minimum value
255,) maximum value

import [Link].*;
import [Link].*;
import [Link].*;
public class FrameScroll extends Applet implements AdjustmentListener
{
Frame f;
TextField tf1;
Scrollbar sb1, sb2, sb3;

public void init()


{
f = new Frame("Frame With Scroll");
tf1 = new TextField(20);
sb1 = new Scrollbar([Link],0,1,0,255);
sb2 = new Scrollbar([Link],0,1,0,255);
sb3 = new Scrollbar([Link],0,1,0,255);

add(sb1);
add(sb2);
add(sb3);
add(tf1);

// [Link](new FlowLayout());
[Link](this);
[Link](this);
[Link](this);
}
public void adjustmentValueChanged(AdjustmentEvent e)
{
repaint();
}
public void paint(Graphics g)
{
int a = [Link]();
int b = [Link]();
int c = [Link]();
Color d = new Color(a,b,c);
setBackground(d);
[Link](a+" "+b+" "+c);
[Link](d);
}
}

Click new  File  html and save this file as [Link]


<BODY>
<Applet code=[Link] height=100 width=400 >
</Applet>
</BODY>

Applet : Take color value in three TextField for r, g, and b respectively. On clicking “SHOW
COLOR” Button, change the Background color to that color.
SHOW COLOR

import [Link].*;
import [Link].*;
import [Link].*;
public class FrameColors extends Applet implements ActionListener
{
Frame f;
TextField tf1, tf2, tf3;
Button b1;

public void init()


{
f = new Frame("Frame With Scroll");
tf1 = new TextField(5);
tf2 = new TextField(5);
tf3 = new TextField(5);
b1 = new Button("Show Color");

add(tf1);
add(tf2);
add(tf3);
add(b1);

// [Link](new FlowLayout());
[Link](this);
[Link](this);
[Link](this);
[Link](this);
}
public void actionPerformed(ActionEvent e)
{
repaint();
}
public void paint(Graphics g)
{
String x = [Link]();
String y = [Link]();
String z = [Link]();

int a = [Link](x);
int b = [Link](y);
int c = [Link](z);

Color d = new Color(a,b,c);


setBackground(d);
}
}

Click new  File  html and save this file as [Link]


<BODY>
<Applet code=[Link] height=100 width=400 >
</Applet>
</BODY>

Component Listeners : Component Shown


Component Hidden
Component Moved
Component Resized

Applet : On clicking “SHOW” Button, a Component Frame appears on the screen and
simultaneously word “Shown” is displayed in the TextArea. On moving or resizing
Frame Component, the word “Moved” or “Resized” appear in the TextArea. On
clicking “HIDDEN” Button, Frame Component disappear and word “Hidden” is
displayed in TextArea.

Shown Hidden Shown Hidden Shown

import [Link].*;
import [Link].*;
import [Link].*;
public class FrameComponent extends Applet implements ActionListener,ComponentListener
{
Frame f1;
TextArea ta1;
Button b1, b2;
public void init()
{
f1 = new Frame("Frame With Component");
ta1 = new TextArea(20,20);
b1 = new Button("Show");
b2 = new Button("Hide");

add(b1);
add(b2);
add(ta1);

[Link](this);
[Link](this);
[Link](this);
}
public void actionPerformed(ActionEvent e)
{
if([Link]() == b1)
{
[Link](true);
}
else
if([Link]() == b2)
{
[Link](false);
}
}
public void componentShown(ComponentEvent e1)
{
[Link]("Shown\n");
}
public void componentHidden(ComponentEvent e1)
{
[Link]("Hidden\n");
}
public void componentMoved(ComponentEvent e1)
{
[Link]("Moved\n");
}
public void componentResized(ComponentEvent e1)
{
[Link]("Resized\n");
}
}

Click new  File  html and save this file as [Link]


<BODY>
<Applet code=[Link] height=100 width=400 >
</Applet>
</BODY>

Item Listener : List


Checkbox
Choice
CheckboxGroup (Radio Buttons)

Public void itemStateChanged(ItemEvent)


{
------
------
}

Java VB C++
Books Selected :
Java
VB
C++

import [Link].*;
import [Link].*;
import [Link].*;
public class FrameCheckbox extends Applet implements ItemListener
{
Checkbox cb1, cb2, cb3;

public void init()


{
cb1 = new Checkbox("Java");
cb2 = new Checkbox("VB");
cb3 = new Checkbox("C++");

add(cb1);
add(cb2);
add(cb3);

[Link](this);
[Link](this);
[Link](this);
}
public void itemStateChanged(ItemEvent e)
{
repaint();
}
public void paint(Graphics g)
{
[Link]("Books Selected",100,100);
if([Link]())
{
[Link]("Java",100,120);
}
if([Link]())
{
[Link]("VB",100,130);
}
if([Link]())
{
[Link]("C++",100,140);
}
}
}

Click new  File  html and save this file as [Link]


<BODY>
<Applet code=[Link] height=200 width=400 >
</Applet>
</BODY>

Applet : This is to display Radio Buttons.

Male Female CheckboxGroup


Sex is : Checkbox

import [Link].*;
import [Link].*;
import [Link].*;
public class FrameCheckboxGroup extends Applet implements ItemListener
{
Checkbox cb1, cb2;
CheckboxGroup cbg1;

public void init()


{
cbg1 = new CheckboxGroup();
cb1 = new Checkbox("Male",cbg1,false);
cb2 = new Checkbox("Female",cbg1,false);

add(cb1);
add(cb2);

[Link](this);
[Link](this);
}
public void itemStateChanged(ItemEvent e)
{
repaint();
}
public void paint(Graphics g)
{
[Link]("Sex is : ",100,100);
if([Link]())
{
[Link]("Male",150,100);
}
if([Link]())
{
[Link]("Female",150,100);
}
}
}

Click new  File  html and save this file as [Link]


<BODY>
<Applet code=[Link] height=200 width=400 >
</Applet>
</BODY>

Applet : Choice (Dropdown List)

Qualification : Select Option

Qualification :

import [Link].*;
import [Link].*;
import [Link].*;
public class FrameChoice extends Applet implements ItemListener
{
Choice c;

public void init()


{
c = new Choice();
[Link]("Select Option");
[Link]("Under Graduate");
[Link]("Graduate");
[Link]("Post Graduate");
add(c);
[Link](this);
}
public void itemStateChanged(ItemEvent e)
{
repaint();
}
public void paint(Graphics g)
{
[Link]("Qualification : ",100,100);
String s1 = [Link]();
if(s1 == "Under Graduate")
{
[Link]("Under Graduate",200,100);
}
if(s1 == "Graduate")
{
[Link]("Graduate",200,100);
}
if(s1 == "Post Graduate")
{
[Link]("Post Graduate",200,100);
}
}
}

Click new  File  html and save this file as [Link]


<BODY>
<Applet code=[Link] height=200 width=400 >
</Applet>
</BODY>

Applet : List – List allow user to select all the options listed in it.

Hobbies : Music
Reading
Shopping
Hobbies : Music
Reading
Shopping

import [Link].*;
import [Link].*;
import [Link].*;
public class FrameList extends Applet implements ItemListener
{
List l;
Label l1;

public void init()


{
l1 = new Label("Hobbies are : ",[Link]);
l = new List(4);

[Link]("Music");
[Link]("Sports");
[Link]("Reading");
[Link]("Treking");

add(l1);
add(l);

[Link](this);
[Link](true);
}
public void itemStateChanged(ItemEvent e)
{
repaint();
}
public void paint(Graphics g)
{
[Link]("Hobbies : ",100,100);
int i[] = [Link]();
for (int j=0;j<[Link];j++)
{
switch(i[j])
{
case 0 : { [Link]("Music",150,100); }
break;
case 1 : { [Link]("Sports",150,120); }
break;
case 2 : { [Link]("Reading",150,140); }
break;
case 3 : { [Link]("Treking",150,160); }
break;
}
}
}
}

Click new  File  html and save this file as [Link]


<BODY>
<Applet code=[Link] height=200 width=400 >
</Applet>
</BODY>

Mouse Listener : mouseEntered


mouseExited
mousePressed
mouseReleased
mouseClicked
Applet : Application displays three canvas with Red, Green and Cyan color. On selecting
particular canvas the background color is changed to that canvas color.

import [Link].*;
import [Link].*;
public class FrameMouseCanvas extends Applet implements MouseListener
{
Canvas c1,c2,c3;
public void init()
{
c1=new Canvas();
c2=new Canvas();
c3=new Canvas();

add(c1);
add(c2);
add(c3);

[Link](100,100);
[Link](100,100);
[Link](100,100);

[Link]([Link]);
[Link]([Link]);
[Link]([Link]);

[Link](this);
[Link](this);
[Link](this);
}
public void mouseEntered(MouseEvent e)
{
if([Link]()==c1)
{
setBackground([Link]);
}
else if([Link]()==c2)
{
setBackground([Link]);
}
else if([Link]()==c3)
{
setBackground([Link]);
}
}
public void mouseExited(MouseEvent e)
{
if([Link]()==c1||[Link]()==c2||[Link]()==c3)
{
setBackground([Link]);
}
}
public void mousePressed(MouseEvent e)
{
}
public void mouseClicked(MouseEvent e)
{
}
public void mouseReleased(MouseEvent e)
{
}
}

Click new  File  html and save this file as [Link]


<BODY>
<Applet code=[Link] height=200 width=400 >
</Applet>
</BODY>

Application : In first TextArea user perform any MouseAction, simultaneously the action name
should appear in the second TextArea along with the location(row and column
number).

Entered at _,_
Exited at _,_
Pressed at _,_
Released at _,_
Clicked at _,_

import [Link].*;
import [Link].*;
class FrameMouseAction implements MouseListener
{
Frame f;
TextArea ta1, ta2;
FrameMouseAction()
{
f = new Frame();
ta1=new TextArea(20,20);
ta2=new TextArea(20,20);

[Link](ta1);
[Link](ta2);

[Link](new FlowLayout());
[Link](this);

[Link](400,400);
[Link](true);
}
public void mouseEntered(MouseEvent e)
{
int x = [Link]();
int y = [Link]();
[Link]("Entered"+" at "+x+","+y+"\n");
}
public void mouseExited(MouseEvent e)
{
int x = [Link]();
int y = [Link]();
[Link]("Exited"+" at "+x+","+y+"\n");
}
public void mousePressed(MouseEvent e)
{
int x = [Link]();
int y = [Link]();
[Link]("Pressed"+" at "+x+","+y+"\n");
}
public void mouseClicked(MouseEvent e)
{
int x = [Link]();
int y = [Link]();
[Link]("Clicked"+" at "+x+","+y+"\n");
}
public void mouseReleased(MouseEvent e)
{
int x = [Link]();
int y = [Link]();
[Link]("Released"+" at "+x+","+y+"\n");
}
public static void main(String [] args)
{
FrameMouseAction x = new FrameMouseAction();
}
}

Mouse Motion Listener : mouseDragged


mouseMoved

Application : In first TextArea user perform any MouseMotionAction (Dragged or Moved),


simultaneously the action name should appear in the second TextArea along with
the location(row and column number).

Dragged at _,_
Moved at _,_

import [Link].*;
import [Link].*;
class FrameMouseMotion implements MouseMotionListener
{
Frame f;
TextArea ta1, ta2;

FrameMouseMotion()
{
f = new Frame();
ta1=new TextArea(20,20);
ta2=new TextArea(20,20);

[Link](ta1);
[Link](ta2);

[Link](new FlowLayout());
[Link](this);

[Link](400,400);
[Link](true);
}
public void mouseDragged(MouseEvent e)
{
int x = [Link]();
int y = [Link]();
[Link]("Dragged"+" at "+x+","+y+"\n");
}
public void mouseMoved(MouseEvent e)
{
int x = [Link]();
int y = [Link]();
[Link]("Moved"+" at "+x+","+y+"\n");
}
public static void main(String [] args)
{
FrameMouseMotion x = new FrameMouseMotion();
}
}

Focus Listener : focusGained


focusLost

Applet : When user enter Password in TextField, if it is less that 8 characters long, display a
Dialog “Invalid Password” otherwise display the password in TextArea.

Enter Password : Invalid Password


OK

import [Link].*;
import [Link].*;
import [Link].*;
public class FrameMouseFocus extends Applet implements FocusListener,ActionListener
{
Frame f;
TextArea ta1;
TextField tf1;
Dialog d1;
Button b1;
Label l1;

public void init()


{
f = new Frame();
ta1=new TextArea(10,15);
tf1=new TextField(10);
l1 = new Label("Enter Password : ");

add(l1);
add(tf1);
add(ta1);
[Link]();
[Link]('*');
[Link](this);
}
public void focusLost(FocusEvent f1)
{
if([Link]().length() < 8)
{
d1 = new Dialog(f,"Invalid Password");
b1 = new Button("OK");
[Link](150,100);
[Link](true);
[Link](b1);
[Link](this);
[Link]("");
}
else
{
[Link]([Link]()+"\n");
[Link]("");
[Link]();
}
}
public void actionPerformed(ActionEvent a)
{
if([Link]() == b1)
{
[Link](false);
[Link]();
}
}
public void focusGained(FocusEvent f)
{

}
}

Click new  File  html and save this file as [Link]


<BODY>
<Applet code=[Link] height=200 width=400 >
</Applet>
</BODY>

Key Listener : keyPressed


keyReleased
keyTyped
Application : Whatever typed in first TextField should appear simultaneously in second
TextField. Also on clicking ALT+’x’ , application should get closed.

import [Link].*;
import [Link].*;
class FrameKey implements KeyListener
{
Frame f;
TextField tf1, tf2;
boolean b1;

FrameKey()
{
f=new Frame("Frame with Key");
tf1 = new TextField(20);
tf2 = new TextField(20);

//Change in Layout Manager if necessary


[Link](new FlowLayout());

[Link](tf1);
[Link](tf2);

[Link](this);

[Link](400,100);
[Link](true);
}
public void keyTyped(KeyEvent e)
{
String s = [Link]();
char c = [Link]();
[Link](s+c);
if(b1 && ([Link]() == 'x'))
{
[Link](0);
}
}
public void keyPressed(KeyEvent e)
{
if ([Link]() == e.VK_ALT)
{
b1=true;
}
}
public void keyReleased(KeyEvent e)
{
b1=false;
}
public static void main(String [] args)
{
FrameKey x = new FrameKey();
}
}

Window Listener : windowOpened


windowClosed
windowClosing
windowIconified
windowDeiconified
windowActivated
windowDeactivated

Application : Application display another Frame and TextArea. When Frame is minimized,
windowIconified( ) and windowDeactivated( ) method get invoked and
simultaneously messages are displayed in TextArea. On maximizing Frame,
windowActivated( ), windowDeactivated( ) and windowActivated( ) method are
called and simultaneously messages are displayed in TextArea. On Closing the
Frame, either you can call [Link](0) which kill the entire application or call
[Link]( ) method which can display windowclosing( ) and windowclosed( )
method.

import [Link].*;
import [Link].*;
class FrameWindow implements WindowListener
{
Frame f1,f2;
TextArea ta1;

FrameWindow()
{
f1=new Frame("Frame 1");
f2=new Frame("Frame 2");
ta1 = new TextArea(20,20);

//Change in Layout Manager if necessary


[Link](new FlowLayout());
[Link](new FlowLayout());
[Link](ta1);

[Link](this);

[Link](200,200);
[Link](100,100);
[Link](true);
[Link](true);
}
public void windowOpened(WindowEvent e)
{
[Link]("Opened\n");
}
public void windowClosed(WindowEvent e)
{
[Link]("Closed\n");
}
public void windowClosing(WindowEvent e)
{
[Link]("Closing\n");
[Link]();
}
public void windowIconified(WindowEvent e)
{
[Link]("Minimised\n");
}
public void windowDeiconified(WindowEvent e)
{
[Link]("Maximised\n");
}
public void windowActivated(WindowEvent e)
{
[Link]("Activated\n");
}
public void windowDeactivated(WindowEvent e)
{
[Link]("Deactivated\n");
}
public static void main(String [] args)
{
FrameWindow x = new FrameWindow();
}
}

Input / Output : File (File/Directory)


InputStream
OutputStream
FileReader
BufferedReader
InputStreamReader

Applet : Applet display TextField and TextArea. When user type a name of Directory (entire
path is expected) in TextField, the contents of that Directory is displayed in the
TextArea. If File name is typed then display “Only Directory Allowed”.
We will have to include [Link].*.

c:\students\Maya Directory
contents

import [Link].*;
import [Link].*;
import [Link].*;
class FrameFileList implements ActionListener
{
Frame f;
TextField tf1;
TextArea ta1;

FrameFileList()
{
f=new Frame("Frame 1");
tf1 = new TextField(10);
ta1 = new TextArea(20,20);

//Change in Layout Manager if necessary


[Link](new FlowLayout());
[Link](tf1);
[Link](ta1);

[Link](this);

[Link](400,400);
[Link](true);
}
public void actionPerformed(ActionEvent e)
{
File f1 = new File([Link]());
if([Link]())
{
String s[] = [Link]();
for(int i=0; i < [Link]; i++)
{
[Link](s[i]+"\n");
}
[Link](" ");
}
else
if([Link]())
{
[Link]("Only Directory Allowed");
[Link](" ");
}
}
public static void main(String [] args)
{
FrameFileList x = new FrameFileList();
}
}

Application : Applet display TextField and TextArea. When user type a name of File (entire path
is expected) in TextField, the contents of that File is displayed in the TextArea. If
Directory name is typed then display “Only File Allowed”.
We will have to include [Link].*.

import [Link].*;
import [Link].*;
import [Link].*;
class FrameFileContent implements ActionListener
{
Frame f;
TextField tf1;
TextArea ta1;
FrameFileContent()
{
f=new Frame("Frame 1");
tf1 = new TextField(10);
ta1 = new TextArea(20,20);

//Change in Layout Manager if necessary


[Link](new FlowLayout());
[Link](tf1);
[Link](ta1);

[Link](this);

[Link](400,400);
[Link](true);
}
public void actionPerformed(ActionEvent ae)
{
File f1 = new File([Link]());
if([Link]())
{
try
{
FileInputStream fi = new FileInputStream([Link]());
int i;
while((i = [Link]()) != -1)
{
[Link](""+(char)i);
}
}
catch(Exception e)
{
[Link]();
}
}
}
public static void main(String [] args)
{
FrameFileContent x = new FrameFileContent();
}
}

Application : Take source file name in first TextField and destination file name in second
TextField. On clicking “COPY” Button another Button “SHOW” and TextArea
appear on the Frame and at the same time source file contents are copied in the
destination file. On clicking “SHOW” Button, display the file content of second
TextField in the TextArea.

COPY COPY SHOW

import [Link].*;
import [Link].*;
import [Link].*;
class FrameFileContent2 implements ActionListener
{
Frame f;
TextField tf1,tf2;
TextArea ta1;
Button b1, b2;

FrameFileContent2()
{
f=new Frame("Frame 1");
tf1 = new TextField(10);
tf2 = new TextField(10);
b1 = new Button("COPY");
b2 = new Button("SHOW");
ta1 = new TextArea(20,20);

//Change in Layout Manager if necessary


[Link](new FlowLayout());
[Link](tf1);
[Link](tf2);
[Link](b1);

[Link](this);

[Link](400,400);
[Link](true);
}
public void actionPerformed(ActionEvent ae)
{
if([Link]() == b1)
{
File f1 = new File([Link]());
File f2 = new File([Link]());
[Link](b2);
[Link](ta1);
[Link](this);
if([Link]() && [Link]())
{
try
{
FileInputStream fi = new FileInputStream([Link]());
FileOutputStream fo = new FileOutputStream([Link](),true);
int i;
while((i = [Link]()) != -1)
{
[Link](i);
}
}
catch(Exception e)
{
[Link]();
}
}
}
if([Link]() == b2)
{
try
{
FileInputStream fii = new FileInputStream([Link]());
int j;
while((j = [Link]()) != -1)
{
[Link](""+(char)j);
}
[Link](" ");
[Link](" ");
[Link]();
}
catch(Exception e)
{
[Link]();
}
}
[Link]();
[Link]();
}
public static void main(String [] args)
{
FrameFileContent2 x = new FrameFileContent2();
}
}

Application : Take two numbers from user and display sum of them. This is repeated as long as
user wants to continue.
Enter First Number :

Enter Second Number :

Total is :
Do you wish to continue?[Yy/Nn] :

import [Link].*;
class InputSum
{
public static void main(String args[])
{
try
{
InputStreamReader i = new InputStreamReader([Link]);
BufferedReader br = new BufferedReader(i);
while(true)
{
[Link]("Enter First Number : ");
String s = [Link]();
[Link]("Enter Second Number : ");
String s1 = [Link]();
int x = [Link](s);
int y = [Link](s1);
int z = x+y;
[Link]("Total is : "+z);
[Link]("Do you wish to continue?[Yy/Nn] : ");
String s2 = [Link]();
if([Link]("Y"))
{
continue;
}
else
{
[Link]("Thank You");
break;
}
}
}
catch(Exception e)
{
[Link]();
}
}
}

JDBC
The steps in getting connected to a database are :
1. First create a DSN which points to a “.mdb” file.
2. Second load the driver in the memory.
3. Third is make a connection to the database via DSN.
4. Fourth is pass SQL statements.
5. Fifth is retrieve the results.

Objetcs :
Applet
AWT
Events
JDBC
Pass SQL
Retrieve
1. Data Source Name
Load the Driver
2. Connect
3. Connection
4. Statement

DDL : Data Defination Language : name char, id int


DML : Data Manipilation Language : insert, update
DCL : Data Control Language : grant, revoke

Application – 1) Create Table Student :


name char
id number
addr char

import [Link].*;
class TableCreate
{
public static void main(String[] args)
{
try
{
[Link]("[Link]");
Connection c = [Link]("Jdbc:Odbc:Maya");
Statement s = [Link]();
[Link]("create Table Student(name char, id number, addr char)");
[Link]("Table Created");
}
catch(Exception e)
{
[Link]();
}
}
}

Application – 2) Store Data In Table Student :

INSERT [Link](“insert into Student values


(‘ABC’,100,’Mumbai’)”);
[Link](“insert into Student values
Insert Data? (‘”+s1+”’,”+a+”,‘”+s3+”’)”);
Name : Id : Address : [Link](“Name : “+s1+”Id : “+s2+”Add :”+s3)
OK CANCEL

Insert Data Dialog Invisible


Clear TextField RequestFocus TextField
Dialog Invisible

Steps to create DSN and connecting it to the database :


Click  Control Panel
 Administrative Tools (Xp Operating System) / ODBC Data Sources (32 Bit)
 Add
 Double Click – Microsoft Access Driver (*.mdb)
 Write DSN Name

Then Click  Create


 select the folder where you want to store database file
 write the name of database file in place of *.mdb

import [Link].*;
import [Link].*;
import [Link].*;
class TableCreate2 implements ActionListener
{
Statement s;
Frame f;
TextField tf1, tf2, tf3;
Label l;
Button b1, b2, b3;
Dialog d;
Panel p;
String s1, s2, s3;
int a;
TableCreate2()
{
try
{
[Link]("[Link]");
Connection c = [Link]("Jdbc:Odbc:Maya");
s = [Link]();

f = new Frame();
tf1 = new TextField(10);
tf2 = new TextField(10);
tf3 = new TextField(10);
b1 = new Button("INSERT");
b2 = new Button("OK");
b3 = new Button("CANCEL");
d = new Dialog(f,"Inserting Data?");
l = new Label();
p = new Panel();
[Link](new FlowLayout());
[Link](tf1);
[Link](tf2);
[Link](tf3);
[Link](b1);
[Link](l);
[Link](b2);
[Link](b3);
[Link](p);
[Link](250,250);

[Link](this);
[Link](this);
[Link](this);
[Link](400,400);
[Link](true);
}
catch(Exception e)
{
[Link]();
}
}
public void actionPerformed(ActionEvent e)
{
if([Link]() == b1)
{
s1 = [Link]();
s2 = [Link]();
s3 = [Link]();
a = [Link](s2);
[Link]("Name : "+s1+"Id : "+a+"Address : "+s3);
[Link](true);
}
if([Link]() == b2)
{
try
{
[Link]("insert into Student values('"+s1+"',"+a+",'"+s3+"')");
[Link]("inserted");
[Link]("");
[Link]("");
[Link]("");
[Link](false);
[Link]();
}
catch(Exception ce)
{
[Link]();
}
}
if([Link]() == b3)
{
[Link](false);
[Link]();
}
[Link]();
[Link]();
}
public static void main(String[] args)
{ TableCreate2 x = new TableCreate2(); }
}

Application – 3) Store Data In Table Student :

ResultSet
INSERT Pointer to MetaData (Fields)

Insert Data?
Name: Id : Address:
OK CANCEL
INSERT VIEW CONTENTS

ResultSet rs = [Link](“select * from Student”);


While([Link]())
{
[Link]([Link](1).trim( )+”\t”+[Link](2)+”\t”+ [Link](3).trim( )+”\n”);
}

import [Link].*;
import [Link].*;
import [Link].*;
class TableCreate3 implements ActionListener
{
Statement s;
Frame f;
TextField tf1, tf2, tf3;
Button b1, b2, b3, b4;
Dialog d;
Label l;
Panel p;
String s1, s2, s3;
int a;
TextArea ta;
ResultSet rs;
TableCreate3()
{
try
{
[Link]("[Link]");
Connection c = [Link]("Jdbc:Odbc:Maya");
s = [Link]();

f = new Frame();
tf1 = new TextField(10);
tf2 = new TextField(10);
tf3 = new TextField(10);
b1 = new Button("INSERT");
b2 = new Button("OK");
b3 = new Button("CANCEL");
b4 = new Button("VIEW");
d = new Dialog(f,"Inserting Data?");
l = new Label();
p = new Panel();
ta = new TextArea(20,20);
[Link](new FlowLayout());
[Link](tf1);
[Link](tf2);
[Link](tf3);
[Link](b1);
[Link](l);
[Link](b2);
[Link](b3);
[Link](p);
[Link](250,250);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](400,400);
[Link](true);
}
catch(Exception e)
{
[Link]();
}
}
public void actionPerformed(ActionEvent e)
{
if([Link]() == b1)
{
s1 = [Link]();
s2 = [Link]();
s3 = [Link]();
a = [Link](s2);
[Link]("Name : "+s1+"Id : "+a+"Address : "+s3);
[Link](true);
}
if([Link]() == b2)
{
try
{
[Link]("insert into Student values('"+s1+"',"+a+",'"+s3+"')");
[Link]("inserted");
[Link]("");
[Link]("");
[Link]("");
[Link](false);
[Link](b4);
[Link](ta);
}
catch(Exception ce)
{
[Link]();
}
}
if([Link]() == b3)
{
[Link](false);
}
if([Link]() == b4)
{
try
{
rs = [Link]("select * from Student");
while([Link]())
{
[Link]([Link](1).trim()+"\t"+[Link](2)+"\t"+[Link](3).trim()+"\n");
}
}
catch(Exception ce1)
{
[Link]();
}
}
[Link]();
[Link]();
}
public static void main(String[] args)
{
TableCreate3 x = new TableCreate3();
}
}
Application – 4) Display Data From Student Table Base The SQL Query :

ResultSet rs = [Link]([Link]());
CONTENTS ResultSetMetaData rsm = [Link]();
int count = [Link]();
SQL Query while([Link]())
{
for(int i=1; i <= count; i++)
{
select * from Student [Link]([Link](i)+”\t”);
select name from Student }
select name, id from Student [Link](“\n”);
}

ResultSetMetaData points to data above rows and columns of ResultSet. That is it points to Field
Names.

import [Link].*;
import [Link].*;
import [Link].*;
class TableCreate4 implements ActionListener
{
Statement s;
Frame f;
TextField tf1;
TextArea ta;
ResultSet rs;
ResultSetMetaData rsm;
int count;
TableCreate4()
{
try
{
[Link]("[Link]");
Connection c = [Link]("Jdbc:Odbc:Maya");
s = [Link]();

f = new Frame();
tf1 = new TextField(30);
ta = new TextArea(10,30);

[Link](new FlowLayout());
[Link](tf1);
[Link](ta);

[Link](this);

[Link](300,300);
[Link](true);
}
catch(Exception e)
{
[Link]();
}
}
public void actionPerformed(ActionEvent e)
{
try
{
rs = [Link]([Link]());
rsm = [Link]();
count = [Link]();
while([Link]())
{
for(int i=1;i<=count;i++)
{
[Link]([Link](i)+"\t");
}
[Link]("\n");
}
}
catch(Exception ce1)
{
[Link]();
}
[Link]();
[Link]();
}
public static void main(String[] args)
{
TableCreate4 x = new TableCreate4();
}
}

[Link] Frame

REGISTER LOGIN

[Link] Frame

[Link] Frame

Login :

Password :

OK

[Link] Frame

Registered
Click here

[Link] Frame

Login :

Password :

OK

[Link] Frame [Link] Frame

Invalid Login
Welcome
Click here

1) [Link]

import [Link].*;
class TableCreateLogin
{
public static void main(String[] args)
{
try
{
[Link]("[Link]");
Connection c = [Link]("Jdbc:Odbc:Maya");
Statement s = [Link]();
[Link]("create Table Login(login char, pass char)");
[Link]("Table Created");
}
catch(Exception e)
{
[Link]();
}
}
}

2) [Link]

import [Link].*;
import [Link].*;
import [Link].*;
class Welcome implements ActionListener
{
Frame f1;
Button b1,b2;
Welcome()
{
f1= new Frame("welcome java");
b1 = new Button("Register");
b2 = new Button("Login");

[Link](b1);
[Link](b2);

[Link](new FlowLayout());

[Link](this);
[Link](this);

[Link](true);
[Link](200,200);
}
public void actionPerformed(ActionEvent e)
{
if([Link]() == b1)
{
[Link](false);
Register r = new Register();
}
if([Link]() == b2)
{
[Link](false);
LoginRegister lr = new LoginRegister();
}
}
public static void main(String [] args)
{
Welcome n = new Welcome();
}
}

3) [Link]

import [Link].*;
import [Link].*;
import [Link].*;
class Register implements ActionListener
{
Frame f2;
Button b3;
TextField tf1, tf2;
Label l1, l2;
Statement s;
Connection c;
String s1, s2;

Register()
{
try
{
[Link]("[Link]");
c = [Link]("Jdbc:Odbc:Maya");
s = [Link]();
f2= new Frame("Register");
b3 = new Button("OK");
tf1 = new TextField(10);
tf2 = new TextField(10);
l1 = new Label("Login");
l2 = new Label("Password");
[Link](l1);
[Link](tf1);
[Link](l2);
[Link](tf2);
[Link](b3);
[Link]('*');
[Link](new FlowLayout());
[Link](this);
[Link](true);
[Link](200,200);
}
catch(Exception ee)
{
[Link]();
}
}
public void actionPerformed(ActionEvent e1)
{
if([Link]() == b3)
{
try
{
s1=[Link]();
s2=[Link]();
[Link]("insert into Login values('"+s1+"','"+s2+"')");
[Link]("");
[Link]("");
[Link](false);
Register1 r = new Register1();
}
catch(Exception ee2)
{
[Link]();
}

}
}
}

4) [Link]

import [Link].*;
import [Link].*;
import [Link].*;
class Register1 implements ActionListener
{
Frame f3;
Button b4;
Label l3;
Register1()
{
f3= new Frame("Register1");
b4 = new Button("Click Here");
l3 = new Label("Registered");

[Link](l3);
[Link](b4);

[Link](new FlowLayout());

[Link](this);

[Link](true);
[Link](200,200);
}
public void actionPerformed(ActionEvent e2)
{
if([Link]() == b4)
{
[Link](false);
LoginRegister l = new LoginRegister();
}
}
}

5) [Link]

import [Link].*;
import [Link].*;
import [Link].*;
class LoginRegister implements ActionListener
{
Frame f4;
Button b5;
Label l4, l5;
TextField tf3, tf4;
Connection c1;
Statement ss;
public String s3;
ResultSet rs;

LoginRegister()
{
try
{
[Link]("[Link]");
c1 = [Link]("Jdbc:Odbc:Maya");
ss = [Link]();
f4= new Frame("Login");
b5 = new Button("OK");
l4 = new Label("Login");
l5 = new Label("Password");
tf3 = new TextField(10);
tf4 = new TextField(10);
[Link](l4);
[Link](tf3);
[Link](l5);
[Link](tf4);
[Link](b5);
[Link]('*');
[Link](new FlowLayout());
[Link](this);
[Link](true);
[Link](200,200);
}
catch(Exception ee2)
{
[Link]();
}
}
public void actionPerformed(ActionEvent e3)
{
if([Link]() == b5)
{
try
{
rs = [Link]("select * from Login where login = '"+[Link]()+"'and pass
='"+[Link]()+"'");
if([Link]())
{
[Link](false);
Valid v = new Valid([Link]());
}
else
{
InValid iv = new InValid();
}
}
catch(Exception ee1)
{
[Link]();
}
}
}
}

6) [Link]

import [Link].*;
import [Link].*;
import [Link].*;
class InValid implements ActionListener
{
Frame f6;
Label l6;
Button b6;

InValid()
{
f6= new Frame("Invalid");
l6 = new Label("Invalid Login");
b6 = new Button("Click Here");

[Link](l6);
[Link](b6);

[Link](new FlowLayout());

[Link](this);

[Link](true);
[Link](200,200);
}
public void actionPerformed(ActionEvent e4)
{
if([Link]() == b6)
{
LoginRegister l = new LoginRegister();
}
}
}

7) [Link]

import [Link].*;
import [Link].*;
import [Link].*;
class Valid
{
Frame f5;
Label l5;
TextField tf5;

Valid(String ss1)
{

f5= new Frame("Login");


l5 = new Label("Welcome");
tf5 = new TextField(ss1);

[Link](l5);
[Link](tf5);
[Link](new FlowLayout());
[Link](true);
[Link](200,200);
}
}

Advance
24/10/2004
IP Address InetAddress

DNS .DecimalAddress Socket


TCP/IP Server Socket

URL UDP

ServLet URL Connection DatagramPacket


URL Encode DatagramSocket

The InetAddress class encapsulates the IP address of your machine, which can be in a DNS
format or a .DecimalAddress format.
The InetAddress class has no constructor and there are two static methods :
A) getLocalHost( ) B) getByName( )
which returns a Handle to the InetAddress class.

Following is the program that prints Computer Name and Computer Address
import [Link].*; Output : Maya
import [Link].*; [Link]
class InetTest
{
public static void main(String[] args)
{
try
{
InetAddress i = [Link]();
[Link]([Link]());
[Link]([Link]());
}
catch(Exception e)
{ [Link](); }
}
}

Client Server
Socket ServerSocket

 
When user type “Hello” in Client System that should reflect in Server System as long as user
type “quit”. Always start server side program first.
Client side program : Always start server side program first.
import [Link].*;
import [Link].*;
class Client extends Thread
{
BufferedReader br;
Socket s;
PrintWriter pw;
Client()
{
try
{
br = new BufferedReader (new InputStreamReader([Link]));
s = new Socket([Link](),1200);
pw = new PrintWriter([Link](),true);
[Link]("Server Started");
start();
}
catch(Exception e)
{
[Link]();
}
}
public void run()
{
while(true)
{
try
{
String s1 = [Link]();
[Link](s1);
if ([Link]("quit"))
{
break;
}
}
catch(Exception ee)
{ [Link](); }
}
}
public static void main(String[] args)
{
Client c = new Client();
}
}

Server side program :


import [Link].*;
import [Link].*;
class Server extends Thread
{
ServerSocket ss;
BufferedReader br;
Socket s;
Server()
{
try
{
ss = new ServerSocket(1200);
s = [Link]();
br = new BufferedReader (new InputStreamReader([Link]()));
[Link]("Client Started");
start();
}
catch(Exception e)
{
[Link]();
}
}
public void run()
{
while(true)
{
try
{
String s1 = [Link]();
[Link](s1);
if ([Link]("quit"))
{
break;
}
}
catch(Exception ee)
{ [Link](); }
}
}
public static void main(String[] args)
{
Server sv = new Server();
}
}

Socket(Client) ServerSocket(Server)
 
When user type “Hello” in Client System that should reflect in Server System as long as user
type “quit” and vice versa. Always start server side program first.

Client side program :


import [Link].*;
import [Link].*;
class ClientWithInnerClass extends Thread
{
BufferedReader br;
Socket s;
PrintWriter pw;
ClientWithInnerClass()
{
try
{
br = new BufferedReader (new InputStreamReader([Link]));
s = new Socket([Link](),1200);
pw = new PrintWriter([Link](),true);
[Link]("Server Started");
start();
ClientInner ci = new ClientInner();
}
catch(Exception e)
{
[Link]();
}
}
public void run()
{
while(true)
{
try
{
String s1 = [Link]();
[Link](s1);
if ([Link]("quit"))
{
break;
}
}
catch(Exception ee)
{
[Link]();
}
}
}
class ClientInner extends Thread
{
BufferedReader br1;
ClientInner()
{
try
{
br1= new BufferedReader (new InputStreamReader([Link]()));
start();
}
catch(Exception eee)
{
[Link]();
}
}
public void run()
{
while(true)
{
try
{
String s1 = [Link]();
[Link](s1);
if ([Link]("quit"))
{
break;
}
}
catch(Exception ee)
{
[Link]();
}
}
}
}
public static void main(String[] args)
{
ClientWithInnerClass c = new ClientWithInnerClass();
}
}
Server side program :
import [Link].*;
import [Link].*;
class ServerWithInnerClass extends Thread
{
ServerSocket ss;
BufferedReader br;
Socket s;
ServerWithInnerClass()
{
try
{
ss = new ServerSocket(1200);
s = [Link]();
br = new BufferedReader (new InputStreamReader([Link]()));
[Link]("Client Started");
start();
ServerInner si = new ServerInner();
}
catch(Exception e)
{
[Link]();
}
}
public void run()
{
while(true)
{
try
{
String s1 = [Link]();
[Link](s1);
if ([Link]("quit"))
{
break;
}
}
catch(Exception ee)
{
[Link]();
}
}
}
class ServerInner extends Thread
{
BufferedReader br1;
PrintWriter pw;
ServerInner()
{
try
{
br1 = new BufferedReader (new InputStreamReader([Link]));
pw = new PrintWriter([Link](),true);
start();
}
catch(Exception eee)
{
[Link]();
}
}
public void run()
{
while(true)
{
try
{
String s1 = [Link]();
[Link](s1);
if ([Link]("quit"))
{
break;
}
}
catch(Exception eeee)
{
[Link]();
}
}
}
}
public static void main(String[] args)
{
ServerWithInnerClass sv = new ServerWithInnerClass();
}
}

User Datagram Program (Connectionless Protocol)


DatagramSocket
DatagramPacket (b[ ], length of array)
(b[ ], length of array, InetAddress, port)

Email Server

 
Write a program to send Email. Always start server side program first.

Client side program :


import [Link].*;
import [Link].*;
class ClientUDP extends Thread
{
DatagramSocket ds1;
DatagramPacket dp1;
BufferedReader br1;
ClientUDP()
{
try
{
br1 = new BufferedReader (new InputStreamReader([Link]));
ds1 = new DatagramSocket(1200);
[Link]("Server Started");
start();
}
catch(Exception e)
{
[Link]();
}
}
public void run()
{
while(true)
{
try
{
String s1 = [Link]();
byte b[] = [Link]();
dp1 = new DatagramPacket(b,[Link],[Link](),1600);
[Link](dp1);
if ([Link]("quit"))
{
break;
}
}
catch(Exception ee)
{
[Link]();
}
}
}
public static void main(String[] args)
{
ClientUDP cUDP = new ClientUDP();
}
}

Server side program :


import [Link].*;
import [Link].*;
class ServerUDP extends Thread
{
DatagramSocket ds2;
DatagramPacket dp2;
ServerUDP()
{
try
{
ds2 = new DatagramSocket(1600);
[Link]("client Started");
start();
}
catch(Exception e)
{
[Link]();
}
}
public void run()
{
while(true)
{
try
{
byte b[] = new byte[1024];
dp2 = new DatagramPacket(b,[Link]);
[Link](dp2);
String s1 = new String(b, 0, [Link]);
[Link]([Link]());
if ([Link]("quit"))
{
break;
}
}
catch(Exception ee)
{
[Link]();
}
}
}
public static void main(String[] args)
{
ServerUDP sUDP = new ServerUDP();
}
}

Socket(Client) ServerSocket(Server)

 
Two way chat session program : Always start server side program first.
Server side program :
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;

class server1 extends Thread


{
BufferedReader br;
PrintWriter pr;
ServerSocket ss;
Frame f;
TextArea ta;
TextField tf;
Button b1;
String s1;
Socket s;

server1()
{
f=new Frame("Server");
b1=new Button("OK");
tf=new TextField(20);
ta=new TextArea(10,25);
[Link](ta);
[Link](tf);
[Link](b1);
[Link](new FlowLayout());
[Link](300,300);
[Link](true);

try
{
ss=new ServerSocket(1200);
s=[Link]();
br=new BufferedReader(new InputStreamReader([Link]()));
InnerServer i1=new InnerServer();
start();
}
catch(Exception e)
{
[Link]();
}
}//end of constructor

public void run()


{
String s1;
try
{
while(true)
{
s1=[Link]();
if ([Link]()>0)
{
[Link]("Client : "+s1+"\n");
}
else
{
[Link]("Inside else");
}
}//end of while loop
}//end of try
catch(Exception e)
{
[Link]();
}
}//end of run
class InnerServer implements ActionListener
{
InnerServer()
{
try
{
pr=new PrintWriter([Link](),true);
}
catch(Exception e)
{
[Link]();
}
[Link](this);
[Link](this);
}
public void actionPerformed(ActionEvent e)
{
s1=[Link]();
[Link]("Server : "+s1+"\n");
[Link](s1);
[Link]("");
}//end of ActionPerformed
}//end of inner class
public static void main(String args[])
{
server1 c=new server1();
}
}//end of outer class

Client side program :


import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;

class client1 implements ActionListener


{
Socket s;
PrintWriter pr;
Frame f;
TextArea ta;
TextField tf;
Button b1;
String s1;
BufferedReader br;
client1()
{
f=new Frame("Client");
b1=new Button("OK");
tf=new TextField(20);
ta=new TextArea(10,25);
[Link](ta);
[Link](tf);
[Link](b1);
[Link](new FlowLayout());
[Link](300,300);
[Link](true);
[Link](this);
[Link](this);
try
{
InetAddress i=[Link]();
[Link]([Link]());
s=new Socket([Link](),1200);
br=new BufferedReader(new InputStreamReader([Link]()));
pr=new PrintWriter([Link](),true);
InnerClient i1=new InnerClient();
}
catch(Exception e)
{
[Link]();
}
}
public void actionPerformed(ActionEvent e)
{
s1=[Link]();
[Link]("Client : "+s1+"\n");
[Link](s1);
[Link]("");
}

class InnerClient extends Thread


{
InnerClient()
{
start();
}//end of constructor
public void run()
{
String s1;
try
{
while(true)
{
s1=[Link]();
if ([Link]()>0)
{
[Link]("Server : "+s1+"\n");
}
}//end of while loop
}//end of try
catch(Exception e)
{
[Link]();
}
}//end of run
}//end of inner class
public static void main(String args[])
{
client1 c=new client1();
}
}//end of outer class

Remote Method Invocation (RMI) 31-10-2004


Distributed Computing
3- Tier Architecture Multiple 3-Tier Technology

Client B/L Database Client B/L Database


W/S - A/S

B/L – Business Logic


W/S – Web Serve
A/S – Application Server

Multiple 3-Tier Technology is known as Distributed Computing.

When a user wants to book a ticket from Ahmedabad to Delhi, he the client in Mumbai connects
to the client in Ahmedabad through IP Address.

Client on another JVM

Client in Mumbai IP Address Client in Ahmedabad

IP Address Client in Delhi

Server Client [Link]


Remote Object

Application javac

Un-marshalling Marshalling
[Link]
Proxy
Skeleton Stub
Marshalling Un-marshalling stub skeleton

(when class file is compiled)


Remote Reference Layer
Marshalling converts
bytecode into bytes

Transport because Transport


understand byte
Byte Byte RMI Registry stores
Bytecode Bytecode IPAddress of Server
RMI is one of the techniques of Distributed Computing and the other similar technologies are :
a) Distributed Computing b) Networking c) CORBA
CORBA (Common Object Request Broker Architecture) is one of the technologies of language
independence.
For a RMI Application the first step is to create an Interface which will have all the business
logic methods.
The Server should create an Implementation class for this Interface.
Only the client can access the methods in the Interface implemented in the implementation class.
It is the Server’s responsibility to register the object with the RMI Registry.
The client will look up at the RMI Registry and get a handle to the remote object and call the
method.
The four Layers in RMI:
1. Application Layer
2. Proxy Layer (this layer contains Stubs and Skeletons of the implementation class
generated through RMI Compiler) The stubs and Skeletons are used for Marshalling and
Unmarshalling which means converting the class files (bytecode) into bytes and vice
versa.
3. Remote Reference Layer – This virtual layer ensure that the application do not comes in
direct contact with the transport layer so that changes made in one does not affect the
other.
4. Transport Layer – which takes care of the data transfer.
Remote and Serializable are the only NULL Interfaces.

Client Server
Socket ServerSocket

 
Display message randomly from Server on Client side computer & also appending time & date.

[Link] program :
import [Link].*;
import [Link].*;
public interface Inter extends Remote
{
String getMessage() throws RemoteException;
}

Server side program : [Link]


import [Link].*;
import [Link].*;
import [Link].*;
class InterImplimentation extends UnicastRemoteObject implements Inter
{
String msg[] = {"How are you", "I am fine", "What about you"};
public InterImplimentation() throws RemoteException
{
super();
}
public String getMessage() throws RemoteException
{
String s = null;
int a = (int) ([Link]() * 10);
int b = [Link];
a = a % b;
Date d = new Date();
s = msg[a]+" "+ d;
return s;
}
public static void main(String[] args)
{
try
{
InterImplimentation p = new InterImplimentation();
[Link]("rmi://localHost:1099/ABC",p);
[Link]("Object Registered");
}
catch(Exception e)
{
[Link]();
}
}
}

Client side program : [Link]


import [Link].*;
class ClientRMI
{
public static void main(String [] args)
{
try
{
Inter i = (Inter) [Link]("rmi://localHost:1099/ABC");
[Link]([Link]());
}
catch(Exception e)
{ [Link](); }
}
}

Steps to run RMI program :


Create Interface
Create Implimentation
Create Client
Compile all 3 programs
Change to DOS prompt
set path=c:\jdk1.3\bin
rmic <server side program name without extension>
start rmiregistry
java <server side program name without extension>
Change to EditPlus
Ctrl + 2  client side program

Client Server

Send Send

Receive Receive

Interface program : [Link]


import [Link].*;
import [Link].*;
public interface Inter1 extends Remote
{
void send(String s) throws RemoteException;
String receive() throws RemoteException;
}

Server side program : [Link]


import [Link].*;
import [Link].*;
import [Link].*;
class InterImplimentation1 extends UnicastRemoteObject implements Inter1
{
String s2;
public InterImplimentation1() throws RemoteException
{
super();
}
public void send(String s1) throws RemoteException
{
s2 = s1;
}
public String receive() throws RemoteException
{
return s2;
}
public static void main(String[] args)
{
try
{
InterImplimentation1 p = new InterImplimentation1();
[Link]("rmi://localHost:1099/ABC",p);
[Link]("Object Registered");
}
catch(Exception e)
{
[Link]();
}
}
}

Client side program : [Link]

import [Link].*;
import [Link].*;
import [Link].*;
class ClientRMI1 implements ActionListener
{
Frame f;
TextField tf1, tf2;
Button b1, b2;
String s1, s2;
static Inter1 i;

ClientRMI1()
{
f = new Frame();
tf1 = new TextField();
tf2 = new TextField();
b1 = new Button("Send");
b2 = new Button("Receive");
s1 = new String();
s2 = new String();

[Link](null);
[Link](50,50,150,20);
[Link](225,50,60,20);
[Link](50,100,150,20);
[Link](225,100,60,20);

[Link](tf1);
[Link](b1);
[Link](tf2);
[Link](b2);
[Link]();
[Link](this);
[Link](this);
[Link]();
[Link](300,150);
[Link](true);
}
public void actionPerformed(ActionEvent e)
{
if([Link]() == b1)
{
try
{
s1 = [Link]();
[Link](s1);
[Link](" ");
}
catch(Exception e1)
{
[Link]();
}
}
if([Link]() == b2)
{
try
{
s2 = [Link]();
[Link](s2);
}
catch(Exception e1)
{
[Link]();
}
}
}
public static void main(String [] args)
{
ClientRMI1 x = new ClientRMI1();
try
{
i = (Inter1) [Link]("rmi://localHost:1099/ABC");
}
catch(Exception e)
{
[Link]();
}
}
}

The Options available are :

1. Add
2. Subtract
3. Reversing The String
4. Length of The String

Enter Your Choice :

If Add is selected take two numbers from user and display addition of them.
If Subtract is selected take two numbers from user and display subtraction of them.
If Reverse is selected take a string from user and display the reverse of it.
If Length is selected take a string from user and display the length of it.

Interface File : [Link]


import [Link].*;
import [Link].*;
public interface Inter2 extends Remote
{
public int add(int i, int j) throws RemoteException;
public int subtract(int i, int j) throws RemoteException;
public String reverse(String s) throws RemoteException;
public int length1(String s1) throws RemoteException;
}

Implimentation Server side File : [Link]


import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
class InterImplimentation2 extends UnicastRemoteObject implements Inter2
{
int a, b, c;
String ss1;
public InterImplimentation2() throws RemoteException
{
super();
}
public int add(int i, int j) throws RemoteException
{
a = i + j;
return a;
}
public int subtract(int i, int j) throws RemoteException
{
b = i - j;
return b;
}
public String reverse(String s) throws RemoteException
{
StringBuffer sb = new StringBuffer(s);
[Link]();
return [Link]();
}
public int length1(String s1) throws RemoteException
{
c = [Link]();
return c;
}
public static void main(String[] args)
{
try
{
InterImplimentation2 p = new InterImplimentation2();
[Link]("rmi://localHost:1099/ABC",p);
[Link]("Object Registered");
}
catch(Exception e)
{
[Link]();
}
}
}

Client side File : [Link]


import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
class ClientRMI2
{
public static void main(String args[])
{
try
{
Inter2 i2 = (Inter2) [Link]("rmi://localHost:1099/ABC");
InputStreamReader i = new InputStreamReader([Link]);
BufferedReader br = new BufferedReader(i);
while(true)
{
[Link]("1. Adding Two Numbers");
[Link]("2. Subtracting Two Numbers");
[Link]("3. Reverse The String");
[Link]("4. Length Of The String");
[Link]("Enter Your Choice : ");
String c1 = [Link]();
if ([Link]().equals("1"))
{
[Link]("Enter First Number : ");
String s = [Link]();
[Link]("Enter Second Number : ");
String s1 = [Link]();
int x = [Link](s);
int y = [Link](s1);
int z = [Link](x, y);
[Link]("Total is : "+z);
}
if ([Link]().equals("2"))
{
[Link]("Enter First Number : ");
String s = [Link]();
[Link]("Enter Second Number : ");
String s1 = [Link]();
int l = [Link](s);
int m = [Link](s1);
int n = [Link](l, m);
[Link]("Difference is : "+n);
}
if ([Link]().equals("3"))
{
[Link]("Enter String : ");
String s = [Link]();
String s1 = [Link](s);
[Link]("Reverse String is : "+s1);
}
if ([Link]().equals("4"))
{
[Link]("Enter String : ");
String s = [Link]();
int o = i2.length1(s);
[Link]("Reverse String is : "+o);
}
[Link]("Do you wish to continue?[Yy/Nn] : ");
String s2 = [Link]();
if([Link]("Y"))
{
continue;
}
else
{
[Link]("Thank You");
break;
}
}
}
catch(Exception e)
{
[Link]();
}
}
}

J2EE
Steps to install Java Web Server :
Double click : jwsr2_0-win-try-gl
Install it in the folder where you are storing servlet files. For Example
D:\maya\java\JavaAll\advjava\jws<dd><mm> (this is valid for a month so <dd><mm> tells
you when you have install jws and accordingly expiry date can be calculated or found.
When it ask “Do you want to alter?” say “NO”.
Then go to DOS prompt; change the working directory to and type httpd to start server :
D:\maya\java\JavaAll\advjava\jws<dd><mm>\bin>httpd
Start explorer and type URL as [Link] and press enter
To kill the server type URL as [Link] in Explorer, then type user name as admin
and password as admin and then click shutdown.
Refresh and Reload invoke the methods again.

Save all html files in D:\maya\java\JavaAll\advjava\jws<dd><mm>\public_html and all


servlet java files in D:\maya\java\JavaAll\advjava\jws<dd><mm>\servlets directory.
Copy D:\maya\java\JavaAll\advjava\jws<dd><mm>\lib\[Link] file into c:\jdk1.3\jre\lib\
ext folder in order to compile servlet files.

All servlet should be public.


Web Server(Handle web request)  Java Web Server(JWS)  Databse
Browser Web Server

Request This is
Multy Threaded
Response
There are two types of Servlet : GenericServlet and httpServlet
There are three methods : init( ), service( ), destroy( )

Servlet is the starting point of J2E architecture whrein the browser makes a request to the web
server and the web server sends back as response in the html format.
The earlier server side technologies were
A) ASP
B) Server side Java script
C) CGI - Perl
The limitation of CGI PERL was that for every request a new application was started on the web
server whereas servlet are multy threaded by default.
All servlet should extend either GenericServlet or HttpServlet and in GenericServlet it should
over ride the service method.
The service method takes ServletRequest and ServletResponse as its parameters.

On Internet Page print Hello by creating servlet file using GenericServlet

Hello

Servlet File : [Link]


import [Link].*;
import [Link].*;
public class MyServlet extends GenericServlet
{
public void service(ServletRequest req, ServletResponse res) throws ServletException,
IOException
{
[Link]("text/html");
PrintWriter out = [Link]();
[Link]("<HTML><BODY><H1>Hello</H1></BODY></HTML>");
}
}
type [Link] to view the web file after compiling it.

Explorer File Servlet File


Name : Welcome <Name>
ID : Your ID is <ID>
OK
HTML File : [Link]
<BODY BGCOLOR="#FFFFFF">
<FORM method=GET ACTION="[Link]
NAME <INPUT TYPE = text name="L"> <BR>
ID <INPUT TYPE = text name="I"> <BR>
<INPUT TYPE = submit value = "OK" >
</FORM>
</BODY>

Servlet File : [Link]


import [Link].*;
import [Link].*;
public class WelcomeServlet extends GenericServlet
{
public void service(ServletRequest req, ServletResponse res) throws ServletException,
IOException
{
[Link]("text/html");
PrintWriter out = [Link]();
String s = [Link]("L");
String s1 = [Link]("I");
[Link]("Welcome"+s+"<BR>");
[Link]("Your ID"+s1+"<BR>");
}
}

Compile [Link] file, then start explorer and type


[Link]

[Link] [Link]

Register Login :
Login
Password :

OK

[Link]
[Link] [Link]
Login :
You are Registered
Password : click here to continue

OK

[Link]
Valid UserId & Password InValid UserId & Password

[Link] [Link]
Welcome Maya Wrong UserID & Password

Click here to continue


Creating Login Table dsn is AdvJava Database is Advance : [Link]
import [Link].*;
class TableLogin
{
public static void main(String[] args)
{
try
{
[Link]("[Link]");
Connection c = [Link]("Jdbc:Odbc:AdvJava");
Statement s = [Link]();
[Link]("create Table Login(login char, pass char)");
[Link]("Table Created");
}
catch(Exception e)
{
[Link]();
}
}
}

HTML File :[Link]

<BODY BGCOLOR="#FFFFFF">
<A href="[Link]
<A href="[Link]
</BODY>
</HTML>

HTML File : [Link]

<BODY BGCOLOR="#FFFFFF">
<FORM method=GET ACTION="[Link]
Login <INPUT TYPE = text name="L"> <BR>
Password <INPUT TYPE = text name="P"> <BR>
<INPUT TYPE = submit value = "OK" >
</FORM>
</BODY>
HTML File :[Link]

<BODY BGCOLOR="#FFFFFF">
You are Registered<BR>
<A href="[Link] here to continue</A><BR>
</BODY>
HTML File : [Link]

<BODY BGCOLOR="#FFFFFF">
<FORM method=GET ACTION="[Link]
Login <INPUT TYPE = text name="L"> <BR>
Password <INPUT TYPE = text name="P"> <BR>
<INPUT TYPE = submit value = "OK" >
</FORM>
</BODY>

HTML File: [Link]

<BODY BGCOLOR="#FFFFFF">
Wrong User ID and Password <BR>
Click here to continue
</BODY>

Servlet File : [Link]


import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
public class Register extends HttpServlet
{
Connection c;
Statement s;
ResultSet rs;
public void init(ServletConfig d)
{
try
{
[Link]("[Link]");
c =[Link]("jdbc:odbc: AdvJava ");
s=[Link]();
}
catch(Exception e)
{
[Link]();
}
}
public void doGet(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException
{
try
{
[Link]("text/html");
PrintWriter out = [Link]();
String s1 = [Link]("L");
String s2 = [Link]("P");
[Link]("insert into Login values('"+s1+"','"+s2+"')");
[Link]("[Link]
}
catch(Exception e1)
{
[Link]();
}
}
public void doPost(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException
{
doGet(req, res);
}
}

Servlet File : [Link]


import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
public class Validate extends HttpServlet
{
Connection c;
Statement s;
ResultSet rs;
public void init(ServletConfig d)
{
try
{
[Link]("[Link]");
c =[Link]("jdbc:odbc: AdvJava ");
s=[Link]();
}
catch(Exception e)
{
[Link]();
}
}
public void doGet(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException
{
try
{
[Link]("text/html");
PrintWriter out = [Link]();
String s1 = [Link]("L");
String s2 = [Link]("P");
rs=[Link]("select * from Login where name='"+s1+"'and password='"+s2+"'");
if([Link]())
{
[Link]("[Link]
}
else
{
[Link]("[Link]
}
}
catch(Exception g)
{
[Link]();
}
}
public void doPost(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException
{
doGet(req, res);
}
}

Servlet File : [Link]


import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
public class Valid extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException
{
[Link]("text/html");
PrintWriter out = [Link]();
String s1 = [Link]("abc");
[Link]("Welcome"+s1+"<BR>");
}
public void doPost(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException
{
doGet(req, res);
}
}

Servlets 28/11/20004

Servlets  G/S HTTP


Value getParameterName( )
Login

JSP
Exception Handling
MultiTreading

Import [Link].*;
Example of getParameterNames( )
Html Servlets

Name : Your Name is :


ID : Your ID is :
City : Your City is :
Nation : Your Nations is :

OK

Enumeration u = [Link]( ); ------- Collection of items


While([Link]( ))
{
String n = (String)[Link]( );
String v = [Link](n);
[Link](“Your “+n+ ” is : “+v);
}
HTML Page :
<BODY BGCOLOR="#FFFFFF">
<FORM method=GET ACTION="[Link]
Name <INPUT TYPE = text name="Name"> <BR>
ID <INPUT TYPE = text name="ID"> <BR>
City <INPUT TYPE = text name="City"> <BR>
Nation <INPUT TYPE = text name="Nation"> <BR>
<INPUT TYPE = submit value = "OK" >
</FORM>
</BODY>

Servlet Program :
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
public class EmpDisplay extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException
{
[Link]("text/html");
PrintWriter out = [Link]();
Enumeration u = [Link]();
while([Link]())
{
String n = (String)[Link]();
String v = [Link](n);
[Link]("Your " + n + " is " + v);
}
}
public void doPost(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException
{
doGet(req, res);
}
}

Example of getParameterValues( )
Html Servlets

Hobbies : Your Hobbies are :

Reading
Painting
Trekking
Playing
OK

String s[ ] = [Link](“Hobbies”); ------- Collection of items

HTML Page :
<BODY BGCOLOR="#FFFFFF">
<FORM method=GET ACTION="[Link]
<SELECT name="Hobbies" multiple>
<OPTION> Reading </OPTION>
<OPTION> Painting </OPTION>
<OPTION> Trekking </OPTION>
<OPTION> Sports </OPTION>
<INPUT TYPE = submit value = "OK" >
</SELECT>
</FORM>
</BODY>

Servlet program :
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
public class HobbiesDisplay extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException
{
[Link]("text/html");
PrintWriter out = [Link]();
String s[] = [Link]("Hobbies");
for(int i=0;i < [Link] ; i++)
{
[Link]("You" + s[i]);
}
}
public void doPost(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException
{
doGet(req, res);
}
}

COOKIES (saves information about the server)


[Link]
Client Web Server

User ID :
Passward :

Remember my User ID. Login

4
Client Cookies  adds to Registry
5
6

User ID : mayarv

Example of Cookies :
Create Cookies
3 Temporary
3 Permanent

Browser Show Cookies

Tname0 Tvalue0<BR>
Pname0 Pvalue0<BR>
Tname1 Tvalue1<BR>
Click here Pname1 Pvalue1<BR>
Tname2 Tvalue2<BR>
Pname2 Pvalue2<BR>

Client Program :
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
public class CreateCookie extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException
{
[Link]("text/html");
PrintWriter out = [Link]();
for(int i=0; i < 3; i++ )
{
Cookie c1 = new Cookie("Tname"+i, "Tvalue"+i);
[Link](10);
[Link](c1);
Cookie c2 = new Cookie("Pname"+i, "Pvalue"+i);
[Link](60*60*24);
[Link](c2);
}
[Link]("<A href=[Link] click here </A>");
}
public void doPost(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException
{
doGet(req, res);
}
}

Server Program :
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
public class ShowCookie extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException
{
Cookie c[] = [Link]();
PrintWriter out = [Link]();
for(int i=0; i < [Link]; i++ )
{
[Link](c[i].getName()+ " " + c[i].getValue()+ "<BR>");
}
}
public void doPost(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException
{
doGet(req, res);
}
}
Example of Cookie Registration :

[Link] [Link]

Register Login :
Login
Password :

OK

[Link]
[Link]
Login :
You are Registered
Password : click here to continue

OK

[Link]

Valid UserId & Password InValid UserId & Password

[Link] [Link]
Welcome Maya Wrong UserID & Password

Click here to continue

[Link] :
<BODY BGCOLOR="#FFFFFF">
<A href="[Link]
<A href="[Link]
</BODY>
[Link] :

<BODY BGCOLOR="#FFFFFF">
<FORM method=GET ACTION="[Link]
Login <INPUT TYPE = text name="L"> <BR>
Password <INPUT TYPE = text name="P"> <BR>
<INPUT TYPE = submit value = "OK" >
</FORM>
</BODY>

[Link] :
<BODY BGCOLOR="#FFFFFF">
<FORM method=GET ACTION="[Link]
Login <INPUT TYPE = text name="L"> <BR>
Password <INPUT TYPE = password name="P"> <BR>
<INPUT TYPE = submit value = "OK" >
</FORM>
</BODY>

[Link]
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
public class RegisterCookie extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException
{
[Link]("text/html");
PrintWriter out = [Link]();
String s1 = [Link]("L");
String s2 = [Link]("P");
Cookie c1 = new Cookie(s1,s2);
[Link](c1);
[Link]("[Link]
}
public void doPost(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException
{
doGet(req, res);
}
}
[Link] :

import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
public class ValidateCookie extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException
{
[Link]("text/html");
PrintWriter out = [Link]();
String s1 = [Link]("L").trim();
String s2 = [Link]("P").trim();
Cookie c[] = [Link]();
[Link]("The passed values are "+s1+" "+s2);
int i=0;
boolean b=false;
while(true)
{
String s3 = c[i].getName().trim();
String s4 = c[i].getValue().trim();
if ([Link](s1))
{
[Link]("Inside equals1");
b = true;
i++;
break;
}
else
{
[Link]("outside1");
b = false;
i++;
continue;
}
}
if (b)
{
[Link]("[Link]
}
else
{
[Link]("[Link]
}
}
public void doPost(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException
{
doGet(req, res);
}
}

[Link] :

<BODY BGCOLOR="#FFFFFF">
You are Registered<BR>
<A href="[Link] here to continue</A><BR>
</BODY>

[Link] :

<BODY BGCOLOR="#FFFFFF">
Wrong User ID and Password <BR>
<A href="[Link] here to continue</A><BR>
</BODY>

[Link] :
import [Link].*;
import [Link].*;
import [Link].*;
public class ValidCookie extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException
{
[Link]("text/html");
PrintWriter out = [Link]();
String s1 = [Link]("abc");
[Link]("Welcome "+s1+"<BR>");
}
public void doPost(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException
{ doGet(req, res); }
}

HTTP (stateless protocol)

Cookies  session Tracking


HTTP Session  putValue(String, Object);
getValue(String);  returns Object

Toys CDs Books Selection

---- ---- ---- ----


---- ----
----
----
HTTP is a stateless protocol and hence we have to manually track the sessions of the users.
Cookies is a lower level of session tracking where as HTTP session class abstract session
handling from the users.
The putValue( ) method takes a String as the key and an Object as a Value and the getValue
method returns the object from the session if we provide the Key.

Program on Cookie 1 :
Last Accessed Time was : ----- The Time Now is : -----

The Time now is Thu Dec 09 19:06:58 GMT+05:30 2004

Last Accessed Time was Thu Dec 09 19:06:58 GMT+05:30 2004


The Time now is Thu Dec 09 19:07:20 GMT+05:30 2004

[Link] :
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
public class Session1 extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException
{
HttpSession hs = [Link](true);
[Link]("text/html");
PrintWriter out = [Link]();
Date d = (Date)[Link]("ABC");
if (d != null)
{
[Link]("Last Accessed Time was "+d);
}
d = new Date();
[Link]("ABC",d);
[Link]("The Time now is "+d);
}
public void doPost(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException
{
doGet(req, res);
}
}

Program on Cookie 1 :
The Number of Hits in this page :

[Link] :
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
public class PageHitCookie extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException
{
HttpSession hs = [Link](true);
[Link]("text/html");
PrintWriter out = [Link]();
Integer i = (Integer)[Link]("ABC");
if (i == null)
{
i = new Integer(0);
[Link]("Page Number is : "+i);
}
else
{
i = new Integer([Link]() + 1);
[Link]("ABC",i);
[Link]("Page Number is : "+i);
}
}
public void doPost(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException
{ doGet(req, res); }
}

Example of selecting Books :


HTML Servlet (Cookie)

Books : Books selected are :


Java ----
VB ----
C++
.NET Total No. of Books are : ----

OK click here to make change

Book Selection HTML Page :


<BODY BGCOLOR="#FFFFFF">
<FORM method=GET ACTION="[Link]
Select Books<BR>
<SELECT name="Books" multiple>
<OPTION> Java </OPTION>
<OPTION> VB </OPTION>
<OPTION> C++ </OPTION>
<OPTION> C# </OPTION>
<OPTION> .NET </OPTION>
<INPUT TYPE = submit value = "OK" >
</SELECT>
</FORM>
</BODY>

Book Selection Servlet Page :


import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
public class BookSelectionCookie extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,
IOException
{
HttpSession hs = [Link](true);
[Link]("text/html");
PrintWriter out = [Link]();
Integer i = (Integer)[Link]("ABC");
if (i == null)
{
i = new Integer(0);
}
String s[] = [Link]("Books");
for(int j = 0; j < [Link]; j++)
{
i = new Integer([Link]() + 1);
[Link]("item"+i,s[j]);
[Link]("ABC",i);
}
[Link]("Books Selected are : ");
for(int p = 1; p <= [Link](); p++)
{
[Link]([Link]("item"+p));
}
[Link]("Total no. of Books "+[Link]("ABC"));
}
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException,
IOException
{
doGet(req, res);
}
}

Serialization 5-12-2004

Serialization  Saving the state of an Object  class variable values

If an object wants to save its state it should implement the serializable interface.
The state of an object is the value of its class variable.
We use ObjectOutputStream which will takes its parameter a FileOutputStream and used the
WriteObject method to save the state of a file.
Similarly we will use the ObjectInputStream and use the ReadObject method to get the state of
an Object.

Student Interface File :

import [Link].*;
public class Student implements Serializable
{
public String name;
public int id;
public transient int sal;
public Student(String s, int i, int j)
{
name = s;
id = i;
sal = j;
}
public void show()
{
[Link](name+" "+id+" "+sal);
}
}

SaveData File :

import [Link].*;
import [Link].*;
import [Link].*;
public class SaveData
{
public static void main(String [] args)
{
try
{
Student x = new Student("ABC",100,10000);
FileOutputStream fo = new FileOutputStream("[Link]");
ObjectOutputStream oo = new ObjectOutputStream(fo);
[Link](x);
[Link]();
}
catch(Exception e)
{
[Link]();
}
}
}

ReadData File :

import [Link].*;
import [Link].*;
import [Link].*;
public class ReadData
{
public static void main(String [] args)
{
try
{
FileInputStream fi = new FileInputStream("[Link]");
ObjectInputStream oi = new ObjectInputStream(fi);
Student s = (Student)[Link]();
[Link]();
[Link]();
}
catch(Exception e)
{
[Link]();
}
}
}

HttpTunelling
Vector v = new Vector(2,5); (2 – Starting Element, 5 – Increament vector by)
Two methods in Vector are : Size  Actual Element
Capacity  How much it can hold

[Link](new Integer(0));
[Link](new Integer(10));
[Link]([Link]( ));  3
[Link]([Link]( ));  7

The limitations of an Array are :


1. Similar data type
2. Fixed size
3. Can not Append or Insert

The two parameters in the Vector constructor are A) String size B) Increament Capacity
The size method of Vector returns the actual elements in the Vector where as the Capacity
returns the number of elements it can hold.

Application Servlet

TCP / IP

HTTP
Vector  3 Boxes
3 Boxes

Show  6 Boxes

Program of [Link] :
import [Link].*;
public class Box implements Serializable
{
int a, b;
public Box(int c, int d)
{
a = c;
b = d;
}
public String toString()
{
return "["+a+","+b+"]";
}
}

Program of [Link] :
import [Link].*;
import [Link].*;
import [Link].*;
public class TClient
{
public static void main(String [] args)
{
try
{
Box a = new Box(10,20);
Box b = new Box(30,40);
Box c = new Box(50,60);
Vector v = new Vector(2,5);
[Link](a);
[Link](b);
[Link](c);
URL u = new URL("[Link]
URLConnection uc = [Link]();
[Link](true);
[Link](true);
[Link](false);
send(uc,v);
receive(uc);
}
catch(Exception e)
{
[Link]();
}
}
public static void send(URLConnection uc1, Vector v1)
{
try
{
ObjectOutputStream oo = new ObjectOutputStream([Link]());
[Link](v1);
[Link]("Object written");
[Link]();
}
catch(Exception e)
{
[Link]();
}
}
public static void receive(URLConnection uc2)
{
try
{
ObjectInputStream oi = new ObjectInputStream([Link]());
Vector v = (Vector)[Link]();
[Link]();
[Link](v);
}
catch(Exception e)
{
[Link]();
}
}
}

Program of [Link] :
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
public class TServlet extends HttpServlet
{
public void service(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException
{
try
{
ObjectInputStream oi = new ObjectInputStream([Link]());
Vector v1 = (Vector)[Link]();
Box a1 = new Box(70,80);
Box a2 = new Box(90,100);
[Link](a1);
[Link](a2);
ObjectOutputStream oo = new ObjectOutputStream([Link]());
[Link](v1);
[Link]();
[Link]();
}
catch(Exception e)
{
[Link]();
}
}
}
Applet - Servelt Communication

Applet Servlet (Browser) Database

Query Output WWWURLEncoded Format  key = value

HTML Page :
<BODY BGCOLOR="#FFFFFF">
<APPLET CODE=[Link] WIDTH=400 HEIGHT=500>
</APPLET>
</BODY>

Client side Applet program :


import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
public class AppletCommunication extends Applet implements ActionListener
{
TextField tf1;
TextArea ta1;
String s, s1;
int j;
public void init()
{
tf1 = new TextField(20);
ta1 = new TextArea(20,20);
add(tf1);
add(ta1);
[Link]();
[Link](this);
}
public void actionPerformed(ActionEvent e)
{
try
{
s = [Link]();
s1 = [Link]("Qry")+"="+s;
URL u = new URL("[Link]
URLConnection uc = [Link]();
[Link](true);
[Link](true);
DataOutputStream dos = new DataOutputStream([Link]());
[Link](s1);
InputStreamReader i = new InputStreamReader([Link]());
while ((j = [Link]()) != -1)
{
[Link](" "+(char)j);
}
}
catch(Exception e1)
{
[Link]();
}
}
}

Server side Servlet Program :


import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
public class ServletCommunication extends HttpServlet
{
Statement st;
ResultSet rs;
public void init(ServletConfig c) throws ServletException
{
try
{
[Link]("[Link]");
Connection con= [Link]("Jdbc:Odbc:AdvJava");
st = [Link]();
}
catch(Exception ex)
{
[Link]();
}
}
public void service(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException
{
try
{
[Link]("text/html");
PrintWriter out = [Link]();
String s2 = [Link]("Qry");
rs=[Link](s2);
while([Link]())
{
[Link]([Link]("login"));
[Link]([Link]("pass"));
}
}
catch(Exception ee)
{
[Link]();
}
}
}

Page Hit Example :

This page is visited __ number of times. int count; init


DoGet {
{ FileReader
++count; BufferReader
} }

FileReader and BufferReader are used to get value.


[Link]
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
public class CounterServlet extends HttpServlet
{
int count = 0;
public void init(ServletConfig c) throws ServletException
{
try
{
FileReader fr = new FileReader("[Link]");
BufferedReader br = new BufferedReader(fr);
String s = [Link]();
count = [Link](s);
[Link](count);
}
catch(Exception e)
{ [Link]([Link]()); }
}
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,
IOException
{
[Link]("text/HTML");
PrintWriter out = [Link]();
++count;
[Link](" The count is now "+count);
}
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException,
IOException
{
doGet(req, res);
}
public void destroy()
{
try
{
FileWriter fw = new FileWriter("[Link]");
[Link](count);
}
catch(Exception e)
{ [Link]([Link]()); }
}
}
Servlet Chaining

In Servlet Chaining the output of the first servlet will be a input for the second one and in the
html form we will call the alias which will invoke the servlets to be called.
The limitation of Servlet Chaining is we need to create multiple aliases for different servlets to
be called.
In server side include multiple servlets can be embedded in a single .shtml document.

[Link] [Link] [Link]

Login : Login : maya ABC Incorporation


-----------------------------
Password : Password : maya Login : maya
Password : maya
OK -----------------------------
@copy right

<FORM method=GET ACTION="[Link]

Steps to create multiple Servlet Chains :


 In Explorer type [Link]
 User Name : admin
 Password : admin
 Double click Web Service
 Select Servlet Aliases
 Click ADD Button
 Type /ServAlias under Alias column
 Type ServerChain1, ServerChain2 under Servlet Invoked column (order is important)
 Click SAVE Button
 Click Site menu option
 Click Options
 Check Servlets Chain Enabled option

[Link] :

<BODY BGCOLOR="#FFFFFF">
<FORM method=GET ACTION="[Link]
Login <INPUT TYPE = text name="L"> <BR>
Password <INPUT TYPE = password name="P"> <BR>
<INPUT TYPE = submit value = "OK" >
</FORM>
</BODY>

[Link] :

import [Link].*;
import [Link].*;
import [Link].*;
public class ServerChain1 extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,
IOException
{
[Link]("text/html");
PrintWriter out = [Link]();
String s1 = [Link]("L");
String s2 = [Link]("P");
[Link]("Login : "+s1);
[Link]("\n");
[Link]("Password : "+s2);
}
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException,
IOException
{
doGet(req, res);
}
}

[Link] :

import [Link].*;
import [Link].*;
import [Link].*;
public class ServerChain2 extends HttpServlet
{
String s;
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,
IOException
{
[Link]("text/html");
PrintWriter out = [Link]();
BufferedReader br = [Link]();
[Link]("ABC Incorporation");
[Link]("<hr>");
while ((s = [Link]()) != null)
{
[Link](s);
}
[Link]("<hr>");
[Link]("@copy right");
}
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException,
IOException
{
doGet(req, res);
}
}

Server Side Include multiple servlets can be embedded in a single .shtml file :

[Link] :

<BODY BGCOLOR="#FFFFFF">
ABC Incorporation<BR>
<servlet Code = "[Link]">
</servlet>
<BR>
<servlet Code = "[Link]">
</servlet>
</BODY>

OUTPUT :

ABC Incorporation
Login : null Password : null
ABC Incorporation

Session Tracking without enabling Cookies

To disable cookie in Netscape Navigator :


Netscape  Edit  Preferences  Advanced  Disable Cookie (click)

[Link] :

import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
public class SessionTrackingWithoutCookie extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException
{
HttpSession hs = [Link](true);
[Link]("text/html");
PrintWriter out = [Link]();
Integer i = (Integer)[Link]("ABC");
if (i == null)
{
i = new Integer(0);
}
else
{
i = new Integer([Link]() + 1);
}
[Link]("ABC",i);
[Link]("Page Number is : "+i);
[Link]("<br>"+[Link]());
}
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException,
IOException
{
doGet(req, res);
}
}

JSP

Scripting Directive Actions


Scriplets <% %> <%@page useBin
Expressions <= %> include getProperty
Declarations <! %> setProperty
plugin
include
forward
html  embeded java. You don’t compile .jsp file.

Jsp File : [Link]


Today's date is <%= new [Link]() %>

Save this file in public_html folder and to run this file type [Link]
OUTPUT : Today's date is Wed Dec 22 23:29:58 GMT+05:30 2004
When you run any jsp file a new tempdir is created.
JWS112  Temdir  default  pagecompile  jsp  _Date1.class
_Date1.java

JSP is used when a lot of html stuff needs to be outputted from a servlet program.
The 3 types of JSP tags are :
1) Scripting Elements :
a) Scriplets <% %> : Any java code needs to be written in a scriplet.
b) Expressions <%= %> : Any [Link] statements are written in expression.
Semicolon is not needed.
c) Declarations <%! %> : Class variables and methods are written in this.

Scriplets and Expressions go inside jspService method.

2) Directives <%@page import="[Link].*"%>


These tags control the overall structure of a page and it include
a) page
b) include

3) Actions :
These XML style tags include :
 useBin
 getProperty
 setProperty
 plugin
 include
 forward

Login example which store data in file using JSP :

[Link] [Link]

Register Login :
Login
Password :

OK

[Link]
[Link]
Login :
You are Registered
Password : click here to continue

OK
[Link]

Valid UserId & Password InValid UserId & Password

[Link] [Link]
Welcome Maya Wrong UserID & Password

Click here to continue

[Link] :

<BODY BGCOLOR="#FFFFFF">
<A href="[Link]
<A href="[Link]
</BODY>

[Link] :

<BODY BGCOLOR="#FFFFFF">
<FORM method=GET ACTION="[Link]
Login <INPUT TYPE = text name="L"> <BR>
Password <INPUT TYPE = password name="P"> <BR>
<INPUT TYPE = submit value = "OK" >
</FORM>
</BODY>
[Link] :

<BODY BGCOLOR="#FFFFFF">
<FORM method=GET ACTION="[Link]
Login <INPUT TYPE = text name="L"> <BR>
Password <INPUT TYPE = password name="P"> <BR>
<INPUT TYPE = submit value = "OK" >
</FORM>
</BODY>

[Link] :

<%@page import="[Link].*"%>
<%! Statement s;%>
<%
try
{
[Link]("[Link]");
Connection c =[Link]("jdbc:odbc:AdvJava");
s=[Link]();
[Link]("text/html");
String s1 = [Link]("L");
String s2 = [Link]("P");
[Link]("insert into Login values('"+s1+"','"+s2+"')");
[Link]("[Link]
}
catch(Exception e)
{
[Link]();
}
%>

[Link] :

<BODY BGCOLOR="#FFFFFF">
You are Registered<BR>
<A href="[Link] here to continue</A><BR>
</BODY>

[Link] :

<%@page import="[Link].*"%>
<%! Statement s;%>
<%
try
{
[Link]("[Link]");
Connection c = [Link]("Jdbc:Odbc:AdvJava");
s = [Link]();
String s1 = [Link]("L");
String s2 = [Link]("P");
ResultSet rs=[Link]("select * from Login where login='"+s1+"'and pass='"+s2+"'");
if ([Link]())
{
[Link]("[Link]
}
else
{
[Link]("[Link]
}
}
catch(Exception e)
{
[Link]();
}
%>

[Link] :

<%= "Welcome "+[Link]("abc")%>

[Link] :

<BODY BGCOLOR="#FFFFFF">
Wrong User ID and Password <BR>
<A href="[Link] here to continue</A><BR>
</BODY>

Login Cookie example which store data in file using JSP :

[Link] [Link]

Register Login :
Login
Password :

OK

[Link]
[Link]
Login :
You are Registered
Password : click here to continue

OK

[Link]
Valid UserId & Password InValid UserId & Password

[Link] [Link]
Welcome Maya Wrong UserID & Password

Click here to continue

[Link] :

<BODY BGCOLOR="#FFFFFF">
<A href="[Link]
<A href="[Link]
</BODY>

[Link] :

<BODY BGCOLOR="#FFFFFF">
<FORM method=GET ACTION="[Link]
Login <INPUT TYPE = text name="L"> <BR>
Password <INPUT TYPE = password name="P"> <BR>
<INPUT TYPE = submit value = "OK" >
</FORM>
</BODY>

[Link] :

<%@page import="[Link].*"%>
<%@page import="[Link].*"%>
<%
[Link]("text/html");
String s1 = [Link]("L");
String s2 = [Link]("P");
Cookie c1 = new Cookie(s1,s2);
[Link](c1);
[Link]("[Link]
%>

[Link] :

<BODY BGCOLOR="#FFFFFF">
You are Registered<BR>
<A href="[Link] here to continue</A><BR>
</BODY>

[Link] :
<BODY BGCOLOR="#FFFFFF">
<FORM method=GET ACTION="[Link]
Login <INPUT TYPE = text name="L"> <BR>
Password <INPUT TYPE = password name="P"> <BR>
<INPUT TYPE = submit value = "OK" >
</FORM>
</BODY>

[Link] :

<%@page import="[Link].*"%>
<%! boolean b=false; %>
<%
String s1 = [Link]("L").trim();
String s2 = [Link]("P").trim();
Cookie c[] = [Link]();
for(int i = 0;i<[Link];i++)
{
try
{
String s3 = c[i].getName().trim();
String s4 = c[i].getValue().trim();
if ([Link](s1))
{
b = true;
break;
}
else
{
b = false;
}
}
catch(Exception e)
{
[Link]();
}
}
if (b)
{
[Link]("[Link]
}
else
{
[Link]("[Link]
}
%>

[Link] :

<%="Welcome "+[Link]("abc") %><BR>

[Link] :

<BODY BGCOLOR="#FFFFFF">
Wrong User ID and Password <BR>
<A href="[Link] here to continue</A><BR>
</BODY>

Example of Book Selection JSP Files :

HTML Servlet (Cookie)

Books : Books selected are :


Java ----
VB ----
C++
.NET Total No. of Books are : ----

OK click here to make change


Book Selection HTML Page : [Link]

<BODY BGCOLOR="#FFFFFF">
<FORM method=GET ACTION="[Link]
Select Books<BR>
<SELECT name="Books" multiple>
<OPTION> Java </OPTION>
<OPTION> VB </OPTION>
<OPTION> C++ </OPTION>
<OPTION> C# </OPTION>
<OPTION> .NET </OPTION>
<INPUT TYPE = submit value = "OK" >
</SELECT>
</FORM>
</BODY>

[Link] :

<%@page import="[Link].*"%>
<%@page import="[Link].*"%>
<%
Integer i = (Integer)[Link]("ABC");
if (i == null)
{
i = new Integer(0);
}
String s[] = [Link]("Books");
for(int j = 0; j < [Link]; j++)
{
i = new Integer([Link]() + 1);
[Link]("item"+i,s[j]);
[Link]("ABC",i);
}
%>
<%= "Books Selected are : " %>
<% for(int p = 1; p <= [Link](); p++)
{%>
<%= [Link]("item"+p) %>
<%}%>
<%= "Total no. of Books "+[Link]("ABC") %>

Redirecting Error Messages to one central file :

[Link] [Link] [Link]


<%@page errorPage="[Link]"%> <%@page errorPage="[Link]"%> <%@page errorPage="[Link]"%>

[Link]
<%@page isErrorPage="true"%>
<%= exception %>

The second attribute of the page directive is :


a) errorPage b) isErrorPage
Any JSP file by default is not an error page.
The exception object would be available only when isErrorPage=”true”.

Example of Error Redirection :


Distance :
Time :

OK

[Link]

Speed = Distance / Time


Passible Errors :
a) Time = 0 [Link]
b) Time = Ten
When no error : Speed is ___

[Link] :

<BODY BGCOLOR="#FFFFFF">
<FORM method=GET ACTION="[Link]
Distance <INPUT TYPE = text name="D"> <BR>
Time <INPUT TYPE = text name="T"> <BR>
<INPUT TYPE = submit value = "OK" >
</FORM>
</BODY>
[Link] :

<%@page errorPage="[Link]"%>
<%
String s1 = [Link]("D");
String s2 = [Link]("T");
int a = [Link](s1);
int b = [Link](s2);
int dist = a / b;
%>
<%= "Distance is : "+dist %>

[Link] :

<%@page isErrorPage="true"%>
<%= exception %><br>
<% if (exception instanceof [Link]) %>
The Time you have entered is is/are characters

<% if (exception instanceof [Link]) %>


The Time you have entered is 0
<% String s = [Link]("D"); %>

<A href=[Link] click here</A>


<!---
<% [Link](new PrintWriter(out)); %>
--->

[Link] :

<HTML>
</HEAD>
<BODY BGCOLOR="#FFFFFF">
<FORM method=GET ACTION="[Link]
<B>Distance</B> <INPUT TYPE = text name="D" value='<%=[Link]("a")%>'>
<B>Time </B><INPUT TYPE = text name="T">
<INPUT TYPE = submit value = "OK" >
</FORM>
</BODY>
</HTML>

Distance : 10 Time : 0 [Link]: / by zero


The Time you have entered is 0 click here
Distance : 10 Time : Zero [Link]: zero
The Time you have entered is is/are characters click here

Page Translation

Page Translation Time Include Directive


Page Request Time Include Action
The inclusion of one JSP file into another can be done in two ways :
a) At the pageTtranslation Time using include directive which is very faster way of
including.
b) At the page Request Time using include action.

[Link] [Link]

The page has been hit Header


no. of times Inclusion at Translation Time
The count is now : 12
Inclusion at Request Time
The page has been hit 3 no. of time.
Footer

[Link] :
<%@page import="[Link].*"%>
<%@page import="[Link].*"%>
<%@page import="[Link].*"%>
<%! int count = 0; %>
<% try
{ FileReader fr = new FileReader("[Link]");
BufferedReader br = new BufferedReader(fr);
String s = [Link]();
count = [Link](s);
}
catch(Exception e) { [Link](); }
++count;
%>
<%= "The page has been hit "+count+" no. of time." %> <BR>
<% try
{ FileWriter fw = new FileWriter("[Link]");
[Link](count);
}
catch(Exception e) { [Link](); }
%>

[Link] :
Header <BR>
Inclusion at Translation Time <BR>
<%@include file="[Link]" %>
Inclusion at Request Time <BR>
<jsp:include page="[Link]" flush = "true" />
Footer
Bean 25-12-2004

Action :
include
useBean
getProperty Bean  Components
setProperty All class variables are properties
Store all Bean files in classes folder.

Class should be defining public if called in Bean. All attributes are written in lower cases.

Bean Button Text Fields in VB Active X MS

Example of Bean : Write a [Link] file which will access classes\[Link] file to
initialize Student class members “name” and “id” and display their values using setProperty and
getProperty.

File [Link] : save in jws<dd><mm>\classes folder

package Core;
public class Student
{
public String name = "unknown";
public int id = 0;

public void setName(String s)


{
name = s;
}
public String getName()
{
return name;
}
public void setId(int i)
{
id = i;
}
public int getId()
{
return id;
}
public static void main(String [] args)
{
Student st = new Student();
}
}
This file contain package, hence compile it using following steps :
D:\maya\java\advjava\jws<dd><mm>\classes>set path=c:\jdk1.3\bin
D:\maya\java\advjava\jws<dd><mm>\classes>javac –d . [Link]
This create Core folder under jws<dd><mm>\classes folder and it stores [Link] in it.

File [Link] : save in jws<dd><mm>\public_html folder & run


[Link]

<jsp:useBean id = "x" class = "[Link]" />


Initial Values : <BR>
Name = <jsp:getProperty name = "x" property = "name" /> <BR>
ID = <jsp:getProperty name = "x" property = "id" /> <BR>
<% String s = "ABC"; %>
<% int a = 100; %>
<jsp:setProperty name = "x" property = "name" value = '<%=s%>'/>
<jsp:setProperty name = "x" property = "id" value = '<%=a%>'/>
New Values : <BR>
Name = <jsp:getProperty name = "x" property = "name" /> <BR>
ID = <jsp:getProperty name = "x" property = "id" /> <BR>

OUTPUT :
Initial Vales :
Name = unknown
ID = 0
New Values :
Name = ABC
ID = 100

Example 2 :
[Link] [Link]

ID : S0002 setProperty id
Quantity : 100 setProperty quantity
Discount : 100 setProperty discount

OK

DataBase Bean File

i_id i_name i_unitprice id


S0001 Colgate Tooth Brush 30 quantity
S0002 Santoor Bath Soap 25 discount
GetUnitPrice
GetName
GetTotalPrice

OUTPUT :

ID Name Unit Price Quantity Total


S0002 Santoor Bath Soap 25 100 2400

File [Link] :

<BODY BGCOLOR="#FFFFFF">
<FORM method=GET ACTION="[Link]
ID <INPUT TYPE = text name="I"> <BR>
Quantity <INPUT TYPE = text name="Q"> <BR>
Discount <INPUT TYPE = text name="D"> <BR>
<INPUT TYPE = submit value = "OK" >
</FORM>
</BODY>

File [Link] :

package shop;

import [Link].*;
import [Link].*;
public class Shop
{
Connection c;
Statement s;
ResultSet rs;

public String id = "unknown";


public int quantity = 0;
public int discount = 0;

public Shop()
{
try
{
[Link]("[Link]");
c =[Link]("jdbc:odbc:AdvJava");
s=[Link]();
}
catch(Exception e)
{
[Link]();
}
}
public void setId(String s1)
{
id = s1;
}
public String getId()
{
return id;
}
public void setQuantity(int qty)
{
quantity = qty;
}
public int getQuantity()
{
return quantity;
}
public void setDiscount(int dis)
{
discount = dis;
}
public int getDiscount()
{
return discount;
}
public String getName()
{
String name = "unknown";
String id1 = getId();

try
{
rs=[Link]("select * from Shop where i_id='"+id1+"'");
if([Link]())
{
name = [Link](2);
}
return name;
}
catch(Exception e2)
{
[Link]();
return "aaa";
}

}
public int getUnitPrice()
{
int unitprice = 0;
String id2 = getId();
try
{
rs=[Link]("select * from Shop where i_id='"+id2+"'");
if([Link]())
{
unitprice = [Link](3);
}
return unitprice;
}
catch(Exception e1)
{
[Link]();
return 0;
}

}
public int getTotalPrice()
{
int totalprice = 0;
int q = getQuantity();
int u = getUnitPrice();
int d = getDiscount();

totalprice = (q * u) - d;
return totalprice;
}
}

File [Link] :

<jsp:useBean id = "x" class = "[Link]" />

<%
String s = [Link]("I");
String s1 = [Link]("Q");
String s2 = [Link]("D");
int a = [Link](s1);
int b = [Link](s2);
%>
<jsp:setProperty name = "x" property = "id" value = '<%=s%>'/>
<jsp:setProperty name = "x" property = "quantity" value = '<%=a%>'/>
<jsp:setProperty name = "x" property = "discount" value = '<%=b%>'/>

<table border="1" width="100%">


<tr>
<td width="20%">ID</td>
<td width="20%">Name</td>
<td width="20%">Unit Price</td>
<td width="20%">Quantity</td>
<td width="20%">Total</td>
</tr>
<tr>
<td width="20%"><jsp:getProperty name = "x" property = "id" /></td>
<td width="20%"><jsp:getProperty name = "x" property = "name" /></td>
<td width="20%"><jsp:getProperty name = "x" property = "unitprice" /></td>
<td width="20%"><jsp:getProperty name = "x" property = "quantity" /></td>
<td width="20%"><jsp:getProperty name = "x" property = "totalprice" /></td>
</tr>
</table>

Action : 26/12/2004

<jsp:plugin /> Include Applet inside .jsp file.


<jsp:forward /> To forward another .jsp file.
Example : Data is taken in HTML file which is passed to .jsp file which call Applet file and
print on screen. (Save all three files in public_html folder)

[Link] [Link] [Link]

Name : Maya

X : 200
Maya
Y : 300

OK

[Link] :

<BODY BGCOLOR="#FFFFFF">
<FORM method=GET ACTION="[Link]
Name <INPUT TYPE = text name="N"> <BR>
X <INPUT TYPE = text name="X"> <BR>
Y <INPUT TYPE = text name="Y"> <BR>
<INPUT TYPE = submit value = "OK" >
</FORM>
</BODY>
[Link] :

<%
String s = [Link]("N");
String s1 = [Link]("X");
String s2 = [Link]("Y");
int x = [Link](s1);
int y = [Link](s2);
%>
<jsp:plugin type = "Applet" code = "[Link]" width = "800" height = "600">
<jsp:params>
<jsp:param name = "N" value = '<%=s%>'/>
<jsp:param name = "X" value = '<%=x%>'/>
<jsp:param name = "Y" value = '<%=b%>'/>
</jsp:params>
</jsp:plugin>

[Link] :

import [Link].*;
import [Link].*;
public class Plugin extends Applet
{
String N;
int X,Y;
public void init()
{
N = getParameter("N");
String s1 = getParameter("X");
String s2 = getParameter("Y");
X = [Link](s1);
Y = [Link](s2);
}
public void paint(Graphics g)
{
[Link](N,X,Y);
}
}

Example of Forward : [Link] prints “One” on the screen. [Link] prints


“Two” on the screen. [Link] file calls [Link] and [Link] files randomly.

[Link] [Link] [Link]

One Two One

[Link] :

<%="One"%><BR>

[Link] :

<%="Two"%><BR>

[Link] :

<%
if ([Link]() < .5)
{
%>
<jsp:forward page="[Link]"/>
<%
}
else
{
%>
<jsp:forward page="[Link]"/>
<%
}
%>
Example of Shopping Cart :

[Link] [Link] Display Session

Items Add to Cart Items Add to Cart Item Price

ABC ADD XYZ ADD ABC 20


DEF ADD TUV ADD GHI 20
GHI ADD PQR ADD XYZ 20

Next Prev Check Out Total 60

File [Link] :

<%@page import ="[Link].*;"%>


<%
ResultSet rs = null;
Statement st = null;
try
{
[Link]("[Link]");
Connection con= [Link]("Jdbc:Odbc:AdvJava");
st=[Link]();
rs = [Link]("select t_name, t_unitprice from Toys");
}
catch(Exception ex)
{
[Link]();
}
%>
<form method=get action="">
<h1 align="center"><font color="#800000">Online Toy Catalog</font></h1>
<BR>
<p align="center"><font color="#800000"><b>ITEM LIST</b></font></p>
<BR>
<div align="center">
<center>
<Table border="1" width="100%">
<tr>
<td width="33%">Name</td>
<td width="33%">Price</td>
<td width="34%">Link</td>
</tr>
<%
while([Link]())
{
String s1 = [Link](1);
String s2 = [Link](2);
%>
<tr>
<td width="33%"><%=s1%></td>
<td width="33%"><%=s2%></td>
<td width="34%"><a href="[Link]?itemName=<%=s1%>&itemValue=<%=s2%>">Add to
Shopping Cart</a></td>
</tr>
<%
}
%>
</Table>
</center>
</div>
<BR>
<div align="center">
<center>
<table border="1" width="100%">
<tr>
<td width="33%">&nbsp;</td>
<td width="33%"><p align="center">[<A HREF=[Link]?itemName=emptyCart>Empty
Shopping Cart</A>]</td></center>
<td width="34%"><p align="center">[<a href=[Link]>Shop for
CDs</a>]</td>
</tr>
</table>
</div>
<%
String item = [Link]("itemName");
String value = [Link]("itemValue");
if(item != null && [Link]("emptyCart"))
{
String [] attributeNames = [Link]();
for (int i = 0; i<[Link];i++)
{
String attributeName = attributeNames[i];
[Link](attributeName);
}
}
else if(item != null)
{
String attributeName = item;
String attributeValue = value;
[Link](item,value);
}
%>
</form>

File [Link] :

<%@page import ="[Link].*;"%>


<%
ResultSet rs = null;
Statement st = null;
try
{
[Link]("[Link]");
Connection con= [Link]("Jdbc:Odbc:AdvJava");
st=[Link]();
rs = [Link]("select cd_name, cd_unitprice from cds");
}
catch(Exception ex)
{
[Link]();
}
%>
<form method=get action="">
<h1 align="center"><font color="#800000">Online CDs Catalog</font></h1>
<BR>
<p align="center"><font color="#800000"><b>ITEM LIST</b></font></p>
<BR>
<div align="center">
<center>
<Table border="1" width="100%">
<tr>
<td width="33%">Name</td>
<td width="33%">Price</td>
<td width="34%">Link</td>
</tr>
<%
while([Link]())
{
String s1 = [Link](1);
String s2 = [Link](2);
%>
<tr>
<td width="33%"><%=s1%></td>
<td width="33%"><%=s2%></td>
<td width="34%"><a href="[Link]?itemName=<%=s1%>&itemValue=<%=s2%>">Add to
Shopping Cart</a></td>
</tr>
<%
}
%>
</Table>
</center>
</div>
<BR>
<div align="center">
<center>
<table border="1" width="100%">
<tr>
<td width="33%"><p align="center">[<a href=[Link]>Shop for Toys</a>]</td></td>
<td width="33%"><p align="center">[<A HREF=[Link]?itemName=emptyCart>Empty
Shopping Cart</A>]</td>
</center>
<td width="34%">
<p align="center">[<a href=[Link]>Check Out</a>]</td>
</tr>
</table>
</div>
<%
String item = [Link]("itemName");
String value = [Link]("itemValue");
if(item != null && [Link]("emptyCart"))
{
String [] attributeNames = [Link]();
for (int i = 0; i<[Link];i++)
{
String attributeName = attributeNames[i];
[Link](attributeName);
}
}
else if(item != null)
{
String attributeName = item;
String attributeValue = value;
[Link](item,value);
}
%>

File [Link] :
<HTML>
<%@page import="[Link].*"%>
<%@page import="[Link].*"%>
<HEAD>

<HR>
<h1 align="center"><font color="#800000">Content of Shopping Cart</font></h1>
<HR>
<BR>
<%!
int total = 0;
int price = 0;
%>
<div align="center">
<center>
<table border="1" width="75%" height="98">
<tr>
<td width="50%" align="center" height="17"><b>Item Names</b></td>
<td width="50%" align="center" height="17"><b>Unit Price</b></td>
</tr>
<%
String [] attributeNames = [Link]();
for (int i = 0; i<[Link]; i++)
{
String attributeName = attributeNames[i];
String attributeValue = (String)[Link](attributeName);
price = [Link](attributeValue);
total = total + price;
%>
<tr>
<td width="50%" align="center" height="17"><b><%=attributeName%></b></td>
<td width="50%" align="center" height="17"><b><%=attributeValue%></b></td>
</tr>
<%
}
%>
</table>
</center>
</div>
<div align="center">
<center>
<table border="1" width="75%">
<tr>
<td width="50%"><p align="center"><b>Total</b></td>
<td width="50%"><p align="center"><b><%=total%></b></td>
</tr>
</table>
</center>
</div>
</HEAD>
</HTML>

XML

Difference between XML and HTML

XML HTML

1) Data storage Data display


2) Own Tags No Tags of its own
3) Own structure Pre-defined structure
<Students> <Head>
<Student> <Body>
<Name> <Title>
</Name> </Title>
</Student> </Body>
</Students> </ Head>
4) Attribute should be quoted Not necessary to quote attributes
5) No over lapping of tags Over lapping of tags is allowed
<B><U> </U></B>
6) It is case sensitive It is not case sensitive

Parser

DOM SAX
Memory EventDriver

XML documents are basically used for data storage and allows creation of own tags in a user
defined structure.
All attributes in XML should be mandetorily quoted and does not support over lapping tags.
A parser is a application which scans through any input data.
The two types of parsers are :
a) SAX Parser  which is an event driven parser and forward only
b) DOM Parser  which is a in Memory parser which means the whole XML document
should be loaded in memory and supports searching.

XML  Extensible Markup Language


SAX  Simple API for XML parsing
DOM  Document Object Model

XML parsing can be done using


a) Every XML package should have XML declaration in its first line.
b) Every XML package can have only one root element.

JAXP 1.0 Java API for XML parsing.

The structure of the XML document is defined in DTD Data Type Defination
The ignorable white space is fired when the parser encounters a space where character need not
be fired.
The SAX2 API have name spaces included in it :
<Book : Name>
<Author : Name>
The element with the name space Name is called as qualified name and without the name space
is called local name.

Example of XML : [Link]

<?xml version="1.0"?>
<students>
<student stream="BE">
<Name> Maya </Name>
<ID> 101 </ID>
<Address> Mumbai </Address>
</student>
<student stream="MCA">
<Name> Sonal </Name>
<ID> 102 </ID>
<Address> Pune </Address>
</student>
</students>

Example of Parsing XML file : [Link]

import [Link].*;
import [Link].*;
import [Link].*;
public class XMLRead
{ public static void main(String[] args)
{ try
{
SAXParserFactory spf = [Link]();
SAXParser sp = [Link]();
[Link]("[Link]", new XMLApplication());
}
catch(Exception e)
{ [Link](); }
}
}

Example of Java file reading XML file : [Link]


import [Link].*;
import [Link].*;
import [Link].*;
public class XMLApplication extends DefaultHandler
{
int total = 0;
int betotal = 0;

public void characters(char[] ch, int start, int length1)


{ String s = new String(ch, start, length1);
[Link]("Characters : "+s);
}
public void startDocument()
{ [Link]("Start Document"); }
public void endDocument()
{
[Link]("Number of BE Students : "+betotal);
[Link]("Total Number of Students : "+total);
[Link]("End Document");
}
public void endElement(String uri, String localName, String qName)
{
[Link]("End Local Name : "+localName);
[Link]("end Q Name : "+qName);
}
public void startElement(String uri, String localName, String qName, Attributes attributes)
{
for(int i=0; i < [Link](); i++)
{
if ([Link](i).equals("BE"))
{
betotal++;
}
[Link]("Attribute Local Name : "+[Link](i));
[Link]("Attribute Q Name : "+[Link](i));
[Link]("Attribute Value : "+[Link](i));
}
[Link]("Element Local Name : "+localName);
[Link]("Element Q Name : "+qName);
if ([Link]("students"))
{
total++;
}
}
}
Plugins

Example of .dtd file : [Link]

<!ELEMENT VK:News (VK:Name, VK:Details)>


<!ELEMENT VK:Name (#PCDATA)>
<!ELEMENT VK:Details (#PCDATA)>

Example of .dtd file : [Link]

<?xml version="1.0"?>
<!DOCTYPE VK:News SYSTEM "[Link]">
<VK:News xmlns="[Link]">
<VK:Name> XYZ </VK:Name>
<VK:Details> abc </VK:Details>
</VK:News>

Over write the ignorable white spaces.


Files to import :
 [Link]
 [Link]

The top most structure in the DOM is document which will contain the set of elements in it.
We create an element using the createElement() method of the document interface which take a
string parameter.
Characters are added to the to the elements using the createTextNode() method of the document
interface which has a string parameter and which returns a text interface.
Attributes are given to an element using a setAttribute() method which takes name and value as
its parameters.
Transformer is used to convert any source (DOM, SAX or Stream) into a result.

Example of President : Java file that creats .xml file

<?xml version="1.0"?>
<President>
<Person country="India">
<Name> Abdul </Name>
<Surname> Kalam </Surname>
</Person>
<Person country="USA">
<Name> George </Name>
<Surname> Bush </Surname>
</Person>
</President>

Example of java file thata creats [Link] file


import [Link].*; import [Link].*; import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
public class CreatePresident
{ public static void main(String [] args)
{ try
{ Document d;
Element pre, per, nm, sr;
DocumentBuilderFactory dbf = [Link]();
DocumentBuilder db = [Link]();
d = [Link]();
nm = [Link]("Name");
sr = [Link]("Surname");
pre = [Link]("President");
per = [Link]("Person");
[Link]([Link]("Adbul"));
[Link]([Link]("Kalam"));
[Link](nm);
[Link](sr);
[Link]("Country","India");
[Link](per);
[Link](pre);
TransformerFactory tf = [Link]();
Transformer t = [Link]();
[Link](new DOMSource(d), new StreamResult(new FileOutputStream("[Link]")));
}
catch(Exception e) { [Link](); }
}
}
You need jdk1.4 to compile .xml file. Install jdk1.4 and then create java and javac in EditPlus
Menu text : Javac1.4
Command : c:\j2sdk1.4.0_01\bin\[Link]
Argument : $(FileName)
Initial Directory : $(FileDir)

Menu text : Java1.4


Command : c:\j2sdk1.4.0_01\bin\[Link]
Argument : $(FileNameNoExt)
Initial Directory : $(FileDir)

Contents of “[Link]” :
<?xml version="1.0" encoding="UTF-8"?>
<President><Person
Country="India"><Name>Adbul</Name><Surname>Kalam</Surname></Person></President>
JavaBeans

JavaBean Component Control


Class
Object

Set of class

Some functionality

JavaBeans are reusable components which can be visually manipulated in BDK.


Every Bean will have
a) Properties – which are class variables
b) Methods – every variable should have a get and set method.
c) Events – Beans communicate with each other via Events.

JAR  Java Archive  Collection of classes

Every class file should be package in a Jar file and one Jar can contain multiple classes.
Every Jar should have mandetorily one manifest file which will specify the name of JavaBean.
When a Jar is dropped into the beanbox, it automatically comes to know of the properties and
methods via a concept called introspection and which is made possible through the reflection
API.

Example of Jar :

Student Name

Jar Id

Address

Java Archive

File [Link] :
import [Link].*;
import [Link].*;
public class StudentBean
{
private String name = "unknown";
private int id = 0;
private String address = "not specified";
public void setName(String s)
{
name = s;
}
public String getName()
{
return name;
}
public void setId(int a)
{
id = a;
}
public int getId()
{
return id;
}
public void setAddress(String s1)
{
address = s1;
}
public String getAddress()
{
return address;
}
}
File [Link] :
Name: [Link]
Java-Bean: True // Press ENTER key after True

There is a space after “:” in both the lines.

Steps to create [Link] file and execute it :

1. Compile [Link] file and create [Link] file.


2. Goto DOS prompt and change to d:\java\advjava\bean>
3. Type jar cvfm [Link] [Link] StudentBean..class
 c – create
 v – verbose
 s – specify jar filename
 m – manifest
4. Goto another DOS prompt and change to c:\bdk1.1\beanbox>set path=c:\jdk1.3\bin
5. Type c:\bdk1.1\beanbox>run
6. Click Bean window  File  Loadjar  select [Link] file
7. Single click StudentBean component
8. Drag and drop in Bean window
[Link]

Sname
Sid
Saddress

File [Link] :
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
public class StudentBeanApplet extends Applet
{ private String name = "unknown";
private int id = 0;
private String address = "not specified";
String ss;
TextField tf1, tf2, tf3;
public void init()
{ tf1 = new TextField(10);
tf2 = new TextField(10);
tf3 = new TextField(10);
add(tf1);
add(tf2);
add(tf3);
}
public void setName(String s)
{ name = s; [Link](s); }
public String getName()
{ return name; }
public void setId(int a)
{ id = a;
Integer i = new Integer(a);
ss = [Link]();
[Link](ss);
}
public int getId()
{ return id; }
public void setAddress(String s1)
{ address = s1; [Link](s1); }
public String getAddress()
{ return address; }
}
File [Link] :
Name: [Link]
Java-Bean: True
Bound Property

A property said to be bound when any change in its value is dependent on a change in the value
of another bean.
The source bean should use the property change support class and over write the
addPropertyChangeListener() and removePropertyChangeListener() to keep a list of BoundBean.
The BundBean should over write the propertyChange() method to get the new value.
SourceBound Property

Sname abc
abc [Link] Sid
Ssal

Destd Property
abc DestBound
Dname
Did

File [Link] :
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
public class SourceBound extends Applet
{
private String sname = "unknown";
private int sid = 0;
private int ssal = 0;
String ss, si;
TextField tf1, tf2, tf3;
PropertyChangeSupport p;

public void init()


{
p = new PropertyChangeSupport(this);
tf1 = new TextField(10);
tf2 = new TextField(10);
tf3 = new TextField(10);

add(tf1);
add(tf2);
add(tf3);
}
public void setSname(String s)
{
[Link]("A", sname, s);
sname = s;
[Link](s);
}
public String getSname()
{
return sname;
}
public void setSid(int a)
{
[Link]("B", sid, a);
sid = a;
Integer i = new Integer(a);
si = [Link]();
[Link](si);
}
public int getSid()
{
return sid;
}
public void setSsal(int b)
{
[Link]("C", ssal, b);
ssal = b;
Integer j = new Integer(b);
ss = [Link]();
[Link](ss);
}
public int getSsal()
{
return ssal;
}
public void addPropertyChangeListener(PropertyChangeListener l)
{
[Link](l);
}
public void removePropertyChangeListener(PropertyChangeListener l)
{
[Link](l);
}
}
File [Link] :
Name: [Link]
Java-Bean: True
File [Link] :
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;

public class DestBound extends Applet implements PropertyChangeListener


{
private String dname = "unknown";
private int did = 0;

String si;
TextField tf1, tf2;

public void init()


{
tf1 = new TextField(10);
tf2 = new TextField(10);

add(tf1);
add(tf2);
}

public void setDname(String s)


{
dname = s;
[Link](s);
}
public String getDname()
{
return dname;
}
public void setDid(int a)
{
did = a;
Integer i = new Integer(a);
si = [Link]();
[Link](si);
}
public int getDid()
{
return did;
}
public void propertyChange(PropertyChangeEvent e)
{
String s = [Link]();
if ([Link]("A"))
{
String s1 = (String)[Link]();
setDname(s1);
}
else
if ([Link]("B"))
{
Integer i = (Integer)[Link]();
int j = [Link]();
setDid(j);
}
}
}

File [Link] :
Name: [Link]
Java-Bean: True

After adding both the jar files, click on the SourceBound component and then click
Edit  Events  PropertyChange  PropertyChange
Then drop the event on DestBound component in the middle and then select PropertyChange.
As you change the property of [Link], it reflects on TextFields of [Link] as
well as [Link] TextFields.
Constraints

A property is said to be constrained when a change in its value is dependent on the permission of
another Bean.
SourceConst SourceConst Property

Sbal

DestConst Property

Dbal

File [Link] :

import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;

public class SourceConst extends Applet


{
private int sbal = 0;

String si;
TextField tf1;
VetoableChangeSupport v;

public void init()


{
v = new VetoableChangeSupport(this);
tf1 = new TextField(10);

add(tf1);
}
public void setSbal(int a) throws PropertyVetoException
{
[Link]("A", sbal, a);
sbal = a;
Integer i = new Integer(a);
si = [Link]();
[Link](si);
}
public int getSbal()
{
return sbal;
}
public void addVetoableChangeListener(VetoableChangeListener l)
{
[Link](l);
}
public void removeVetoableChangeListener(VetoableChangeListener l)
{
[Link](l);
}
}

File [Link] :

Name: [Link]
Java-Bean: True
File [Link] :
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
public class DestConst extends Applet implements VetoableChangeListener
{ private int dbal = 0;
String si;
TextField tf1;
public void init()
{ tf1 = new TextField(10);
add(tf1);
}
public void setDbal(int a)
{ dbal = a;
Integer i = new Integer(a);
si = [Link]();
[Link](si);
}
public int getDbal()
{ return dbal;
}
public void vetoableChange(PropertyChangeEvent e) throws PropertyVetoException
{ String s = [Link]();
if ([Link]("A"))
{
Integer i = (Integer)[Link]();
int j = [Link]();
if (j < 0)
{
throw new PropertyVetoException ("can not be negative", e);
}
else
{
setDbal(j);
}
}
}
}

File [Link] :

Name: [Link]
Java-Bean: True

You might also like