java programs

Post on 23-Oct-2014

22 Views

Category:

Documents

1 Downloads

Preview:

Click to see full reader

TRANSCRIPT

© www.udaysatya.blogspot.com Page 1

LIST OF JAVA PROGRAMS:-

S.No Programs PgNo. 1 Program to Demonstrate simple JAVA program 4 2 Program to compute the area of a circle 5 3 Program to demonstrate type casting in JAVA 6 4 Program to demonstrate the basic Arithmetic Operations 7 5 Program to find largest of three numbers 8 6 Program to print first 10 Fibonacci numbers 9 7 Program to Calculate the factorial of a number using RECURSION 10 8 Program to print prime numbers using CLA 11 9 Program to Demonstrate Command Line Argument 12

10 Program to convert temperature from Fahrenheit to Celsius using CLA 13 11 Program to produce conversion table dollar and rupees using CLA 14 12 Program to print area of right angled triangle using CLA 15 13 Program to print all the elements in an array using CLA 16 14 Program to find the sum of all the elements in an array 17 15 Program to print all the elements in a 2D array 18 16 Program to find the sum of two matrices 19 17 Program to find the difference of two matrices using CLA 20 18 Program to print the UPPER and LOWER triangle of a matrix 21 19 Program to find the trace of a matrix 22 20 Program to find the transpose of a matrix 23 21 Program to find the product of two matrices 24 22 Program to demonstrate a CLASS 25 23 Program to demonstrate a Constructor 26 24 Program to demonstrate a Parameterized Constructor 27 25 Program to Demonstrate THIS keyword 28 26 Program to Demonstrate Constructor Overloading 29 27 Program to pass objects as parameters 31 28 Program to Demonstrate Queue using Class 32 29 Program to Demonstrate Stack using Class 34 30 Program to Demonstrate Access Specifiers 36 31 Program to Demonstrate Static Variables 37 32 Program to Demonstrate Static Methods 38 33 Program to demonstrate an Inner class 39 34 Program to Demonstrate Type Wrapping 40 35 Program to Demonstrate Single Inheritance 41 36 Program to Demonstrate Multilevel Inheritance 43 37 Program to Demonstrate hierarchical Inheritance 45 38 Program to show SUPER Class variable to refer a sub class object 47 39 Program to Demonstrate Method Overriding 48 40 Program to Demonstrate Runtime Polymorphism 49 41 Program to Demonstrate Abstract Class 51

© www.udaysatya.blogspot.com Page 2

42 Program to Demonstrate FINAL Keyword 52 43 Program to Demonstrate FINAL Method 53 44 Program to Demonstrate FINAL Class 54 45 Program to Demonstrate INTERFACE 55 46 Program to access implementation through Interface references 56 47 Program to Demonstrate EXTENDING INTERFACE 58 48 Program to Demonstrate Stack using interface 59 49 Program to Demonstrate Queue using Interface 61 50 Program to Demonstrate a SIMPLE PACKAGE 63 51 Program to Demonstrate Exception 64 52 Program to Demonstrate TRY CATCH 65 53 Program to Demonstrate CATCH ARITHMETIC Exceptions 66 54 Program to Demonstrate Multiple CATCH 67 55 Program to Demonstrate NESTED TRY 68 56 Program to Demonstrate FINALLY clause 69 57 Program to Demonstrate User Defined EXCEPTIONS 70 58 Program to Demonstrate Throws 71 59 Program to Demonstrate MULTITHREADING 72 60 Program to Demonstrate Runnable Interface 74 61 Program to Demonstrate Thread Priorities 76 62 Program to Demonstrate Synchronized Block 78 63 Program to Demonstrate Synchronized Method 80 64 Program to Demonstrate Deadlock 82 65 Program to Demonstrate Thread Methods 84 66 Program to Create Threads using Thread Class 86 67 Program to Demonstrate Join() & isAlive() methods 88 68 Program to Show how to Get User Input from Keyboard 90 69 Program to Create a Frame Window using Applet 91 70 Program to Demonstrate Life cycle of methods in Applet 93 71 Program to display Parameters Passed from HTML 94 72 Program to Demonstrate all shapes in Graphics class 96 73 Program to Show a Hut,Mountains & Face 97 74 Program to Show Status of Applet Window 99 75 Program to Show Position of the Mouse 100 76 Program to Demonstrate Colors 102 77 Program to Pass Parameters perform Mathematical Operations 103

78 Program To Get Document Code Bases 104 79 Program to Show an Image 105 80 Program to demonstrate an Adapter 106 81 Program to Demonstrate Simple Banner 108 82 Program to Demonstrate Button 110 83 Program to Demonstrate Checkbox 112 84 Program to Demonstrate Radio Buttons (Checkbox Group) 114 85 Program to Demonstrate Choice 116

© www.udaysatya.blogspot.com Page 3

86 Program to Demonstrate File Dialog 117 87 Program to Demonstrate Labels 121 88 Program to Demonstrate Lists 122 89 Program to Demonstrate Menu 124 90 Program to Demonstrate Text Area 128 91 Program to Make a Login Window 129 92 Program to Make a Login Focus 131 93 Program to Demonstrate Mouse Adapter 133 94 Program to Demonstrate Mouse Events 134 95 Program to Demonstrate the key event handlers 136 96 Program to Demonstrate Border Layout 138 97 Program to Demonstrate Card Layout 139 98 Program to Test Fonts Using Mouse Events 141 99 Program to Demonstrate Grid Layout 143

100 Program to Demonstrate Scrollbar 144 101 Program to Check Connection to Database 146 102 Program to retrieve Records from Database 147 103 Program to demonstrate Insertion into Database 148 104 Program to demonstrate Update into Database 149 105 Program to demonstrate Prepared Statement 150 106 Program to Demonstrate Data Entry using Applet 151 107 Program to Demonstrate Result Set Meta Data 154 108 Program to Demonstrate Transaction handling 155 109 Program to Demonstrate Callable Statement 156 110 Program to Demonstrate Result Set Meta Data 157 111 Program to Demonstrate Database Meta Data 158 112 Program to add Interface 159 113 Program to add Server 159 114 Program to add Client 160 115 Program for implementation for the interface 161 116 Create a Policy to Allow Permission for Everyone 161

© www.udaysatya.blogspot.com Page 4

01 Program to Demonstrate simple JAVA program

class A

{

public static void main(String args[])

{

System.out.println("Welcome to my World");

}

}

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

Save the above Program as A.java

Compile Program in Command by using javac

C:\>javac A.java

Run the Program in Command by using java

C:\>java A

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

OUTPUT :

Welcome to my World

© www.udaysatya.blogspot.com Page 5

02 Program to compute the area of a circle

class A2

{

public static void main(String args[])

{

int r=10;

System.out.println("Radius of Circle :" + r);

System.out.println("Area of Circle :" + r*r);

}

}

OUTPUT :

Radius of Circle : 10

Area of Circle : 314

© www.udaysatya.blogspot.com Page 6

03 Program to demonstrate type casting in JAVA

class conversion

{

public static void main(String args[])

{

byte b;

int i=257;

double d=323.142;

System.out.println("\nConversion of int to byte.");

b=(byte) i;

System.out.println("i and b " +i+" "+b);

System.out.println("\nConversion of double to int.");

i=(int)d;

System.out.println("d and i " +d +" "+i);

System.out.println("\nConversion of double to byte.");

b=(byte)d;

System.out.println("d and b " +d + " " +b);

}

}

OUTPUT :

Conversion of int to byte.

i and b 257 1

Conversion of double to int.

d and i 323.142 323

Conversion of double to byte.

d and b 323.142 67

© www.udaysatya.blogspot.com Page 7

04 Program to demonstrate the basic Arithmetic Operations

class arith

{

public static void main(String args[])

{

int a=10,b=3;

System.out.println("sum is "+(a+b));

System.out.println("difference is "+(a-b));

System.out.println("product is "+(a*b));

System.out.println("quotient is "+(a/b));

System.out.println("remainder is "+(a%b));

}

}

OUTPUT :

sum is 13

difference is 7

product is 30

quotient is 3

remainder is 1

© www.udaysatya.blogspot.com Page 8

05 Program to find largest of three numbers

class large

{

public static void main(String args[])

{

int a=10,b=30,c=20;

System.out.println("Greatest of given 3 numbers");

if(a>b&&a>c)

System.out.println(+a);

else if(b>c)

System.out.println(+b);

else

System.out.println(+c);

}

}

OUTPUT :

Greatest of given 3 numbers

30

© www.udaysatya.blogspot.com Page 9

06 Program to print first 10 Fibonacci numbers

class fib

{

public static void main(String args[])

{

int i=9,f=0,s=1,temp;

System.out.println(+f);

while(i>0)

{

System.out.println(+s);

temp=f+s;

f=s;

s=temp;

i--;

}

}

}

OUTPUT :

0

1

1

2

3

5

8

13

21

34

© www.udaysatya.blogspot.com Page 10

07 Program to Calculate the factorial of a number using RECURSION

class Factorial

{

int fact(int n)

{

int result;

if(n==1)

return 1;

result=fact(n-1)*n;

return result;

}

}

class Recursion

{

public static void main(String args[]){

Factorial f=new Factorial();

System.out.println("Factorial of 3 is " +f.fact(3));

System.out.println("Factorial of 4 is " +f.fact(4));

System.out.println("Factorial of 5 is " +f.fact(5));

}

}

OUTPUT :

Factorial of 3 is 6

Factorial of 4 is 24

Factorial of 5 is 120

© www.udaysatya.blogspot.com Page 11

08 Program to print prime numbers using CLA

class primecla

{

public static void main(String s[])

{

int n,r;

n=Integer.parseInt(s[0]);

for(int i=2;i<=n;i++)

{

int c=0;

for(int j=1;j<=i;j++)

{

r=i%j;

if (r==0)

c+=1;

}

if(c==2)

System.out.println(i);

}}}

OUTPUT :

java primecla 10

2

3

5

7

© www.udaysatya.blogspot.com Page 12

09 Program to Demonstrate Command Line Argument

class CommandLine

{

public static void main(String args[])

{

for(int i=0; i<args.length; i++)

System.out.println("args[" +i + "]: "+args[i]);

}

}

OUTPUT :

java CommandLine 1 3 4 2 5

args[0]: 1

args[1]: 3

args[2]: 4

args[3]: 2

args[4]: 5

© www.udaysatya.blogspot.com Page 13

10 Program to convert temperature from Fahrenheit to Celsius scale using CLA

class ftoccla

{

public static void main(String s[])

{

int f;

double c;

f=Integer.parseInt(s[0]);

c=5*(f-32)/9;

System.out.println(f+" fahrenheit = "+c+" celsius");

}

}

OUTPUT :

java ftoccla 34

34 fahrenheit = 1.0 celsius

© www.udaysatya.blogspot.com Page 14

11 Program to produce the conversion table for dollar and rupees using CLA

class dollarcla

{

public static void main(String s[])

{

int n,d;

n=Integer.parseInt(s[0]);

System.out.println("Dollars\t\tRupees" );

for(int i=1;i<=n;i++)

{

d=Integer.parseInt(s[i]);

System.out.println(d+"\t=\t"+(d*45) );

}

}

}

OUTPUT :

java dollarcla 4 1 34 36 37

Dollars Rupees

1 = 45

34 = 1530

36 = 1620

37 = 1665

© www.udaysatya.blogspot.com Page 15

12 Program to print area of right angled triangle using CLA

class AreaTri

{

public static void main(String s[])

{

int a,b,area;

a=Integer.parseInt(s[0]);

b=Integer.parseInt(s[1]);

area=a*b/2;

System.out.println("Area of Right angled Triangle = "+area);

}

}

OUTPUT :

java AreaTri 5 4

Area of Right angled Triangle = 10

© www.udaysatya.blogspot.com Page 16

13 Program to print all the elements in an array using CLA

class matrixcla

{

public static void main(String s[])

{

int n,m;

n=Integer.parseInt(s[0]);

System.out.println("The length of the matrix is: " +n);

System.out.println("The elements of the matrix are:");

for(int i=1;i<=n;i++)

{

m=Integer.parseInt(s[i]);

System.out.println(m);

}

}

}

OUTPUT :

java matrixcla 5 10 34 36 37 99

The length of the matrix is: 5

The elements of the matrix are:

10

34

36

37

99

© www.udaysatya.blogspot.com Page 17

14 Program to find the sum of all the elements in an array

class Sum

{

public static void main(String args[])

{

double nums[]={1.1,1.2,1.3,1.4,1.5};

double result=0;

System.out.println("The Elements of Array are :");

for(int i=0;i<5;i++)

{

System.out.println(nums[i]);

result=result+nums[i];

}

System.out.println("Sum is " + result);

}

}

OUTPUT :

The Elements of Array are :

1.1

1.2

1.3

1.4

1.5

Sum is 6.5

© www.udaysatya.blogspot.com Page 18

15 Program to print all the elements in a 2D array

class Matrix

{

public static void main(String s[])

{

int a[][]= {{1,2,3},{4,5,6}};

System.out.println("Number of Row= " + a.length);

System.out.println("Number of Column= " + a[1].length);

System.out.println("The elements of the matrix are : ");

for(int i = 0; i <a.length; i++)

{

for(int j = 0; j < a[1].length; j++)

{

System.out.print(" "+ a[i][j]);

}

System.out.println();

}

}}

OUTPUT :

Number of Row= 2

Number of Column= 3

The elements of the matrix are :

1 2 3

4 5 6

© www.udaysatya.blogspot.com Page 19

16 Program to find the sum of two matrices

class addm

{

public static void main(String args[])

{

int a[][]={{1,2,3},{4,5,6},{7,8,9}};

int b[][]={{1,1,1},{0,1,0},{0,0,1}};

int c[][]= new int[3][3];

int i,j;

for(i=0;i<3;i++)

for( j=0;j<3;j++)

c[i][j]=a[i][j]+b[i][j];

for(i=0;i<3;i++)

{

for(j=0;j<3;j++)

System.out.print(+c[i][j]+ " ");

System.out.println();

}

}

}

OUTPUT :

2 3 4

4 6 6

7 8 10

© www.udaysatya.blogspot.com Page 20

17 Program to find the difference of two matrices using CLA

class Matrixcla {

public static void main(String s[]) {

int a[][]=new int[2][2];

int b[][]=new int[2][2];

int x,y,k=0;

System.out.println("First Matrix : ");

for(int i = 0; i < 2; i++) {

for(int j = 0; j < 2; j++) {

x=Integer.parseInt(s[k]);

a[i][j]=x;

k++;

System.out.print(" "+ a[i][j]); }

System.out.println(); }

System.out.println("Second Matrix : ");

for(int i = 0; i <2; i++) {

for(int j = 0; j <2; j++) {

y=Integer.parseInt(s[k]);

b[i][j]=y;

k++;

System.out.print(" "+b[i][j]); }

System.out.println(); }

System.out.println("Difference of two matrix : ");

for(int i = 0; i <2; i++) {

for(int j = 0; j <2; j++)

System.out.print(" "+(a[i][j]-b[i][j]));

System.out.println();

}}}

OUTPUT :

java Matrixcla 6 7 8 9 5 5 5 5

First Matrix :

6 7

8 9

Second Matrix :

5 5

5 5

Difference of two matrix :

1 2

3 4

© www.udaysatya.blogspot.com Page 21

18 Program to print the UPPER and LOWER triangle of a matrix

class UppLow{

public static void main(String arsg[]) {

int a[][]={{1,2,3},{4,5,6},{7,8,9}};

System.out.println("the given matrix:");

for(int i=0;i<3;i++) {

for(int j=0;j<3;j++)

System.out.print(" "+a[i][j]);

System.out.println(); }

System.out.println("upper triangle of matrix:");

for(int i=0;i<3;i++) {

for(int j=0;j<3;j++) {

if(i<=j)

System.out.print(a[i][j] + " ");

else

System.out.print(" "); }

System.out.println(); }

System.out.println("lower triangle of matrix:");

for(int i=0;i<3;i++) {

for(int j=0;j<3;j++) {

if(i>=j)

System.out.print(a[i][j] + " ");

else

System.out.print(" "); }

System.out.println();

}}}

OUTPUT :

The given matrix:

1 2 3

4 5 6

7 8 9

Upper triangle of matrix:

1 2 3

5 6

9

Lower triangle of matrix:

1

4 5

7 8 9

© www.udaysatya.blogspot.com Page 22

19 Program to find the trace of a matrix

class Trace

{

public static void main(String args[])

{

int a[][]={{1,2,3},{4,5,6},{7,8,9}};

int i,j,sum=0;

System.out.println("The given matrix : ");

for(int i = 0; i <3; i++)

{

for(int j = 0; j <3; j++)

System.out.print(a[i][j] + " ");

System.out.println();

}

for(i=0;i<3;i++)

{

for(j=0;j<3;j++)

if(i==j)

sum=sum+a[i][j];

}

System.out.println("Trace is : " +sum);

}

}

OUTPUT :

The given matrix :

1 2 3

4 5 6

7 8 9

Trace is : 15

© www.udaysatya.blogspot.com Page 23

20 Program to find the transpose of a matrix

class Transpose

{

public static void main(String args[])

{

int a[][]={{1,2,3},{4,5,6},{7,8,9}};

int i,j;

System.out.println("The given matrix : ");

for(int i = 0; i <3; i++)

{

for(int j = 0; j <3; j++)

System.out.print(a[i][j] + " ");

System.out.println();

}

System.out.println("Transpose of Matrix : ");

for(i=0;i<3;i++)

{

for(j=0;j<3;j++)

System.out.print(a[j][i]+ " ");

System.out.println();

}

}

}

OUTPUT :

The given matrix :

1 2 3

4 5 6

7 8 9

Transpose of Matrix :

1 4 7

2 5 8

3 6 9

© www.udaysatya.blogspot.com Page 24

21 Program to find the product of two matrices

class Mulm

{

public static void main(String args[])

{

int a[][]={{1,2,3},{4,5,6},{7,8,9}};

int b[][]={{1,1,1},{0,1,0},{0,0,1}};

int c[][]= new int[3][3];

int i,j,k;

for(i=0;i<3;i++)

for(j=0;j<3;j++)

for(k=0;k<3;k++)

c[i][j]=c[i][j]+a[i][k]*b[k][j];

for(i=0;i<3;i++)

{

for(j=0;j<3;j++)

System.out.print(+c[i][j]+ " ");

System.out.println();

}

}

}

OUTPUT :

1 3 4

4 9 10

7 15 16

© www.udaysatya.blogspot.com Page 25

22 Program to demonstrate a CLASS

class Democlass //Defining a class

{

int a=34;//Instance Variable of the class

void showa() //Method of the class

{

System.out.println("a = " +a);

}

}//End of the class

class A

{

public static void main(String args[]) {

Democlass obj = new Democlass();

obj.showa();

}

}

OUTPUT :

a=34

© www.udaysatya.blogspot.com Page 26

23 Program to demonstrate a Constructor

class Box

{

double width;

double height;

double depth;

Box()

{

System.out.println("Constructing Box");

width=10;

height=10;

depth=10;

}

double volume()

{

return width*height*depth;

}

}

class BoxDemo6

{

public static void main(String args[]) {

Box mybox1=new Box();

Box mybox2=new Box();

double vol;

vol=mybox1.volume();

System.out.println("volume of is " +vol);

vol=mybox2.volume();

System.out.println("volume of is " +vol);

}}

OUTPUT :

Constructing Box

Constructing Box

volume of is 1000.0

volume of is 1000.0

© www.udaysatya.blogspot.com Page 27

24 Program to demonstrate a Parameterized Constructor

class Box

{

double width;

double height;

double depth;

Box(double w,double h,double d)

{

width=w;

height=h;

depth=d;

}

double volume()

{

return width*height*depth;

}

}

class BoxDemo7

{

public static void main(String args[]) {

Box mybox1=new Box(10,20,15);

Box mybox2=new Box(3,6,9);

double vol;

vol=mybox1.volume();

System.out.println("volume of is " +vol);

vol=mybox2.volume();

System.out.println("volume of is " +vol);

}

}

OUTPUT :

volume of is 3000.0

volume of is 162.0

© www.udaysatya.blogspot.com Page 28

25 Program to Demonstrate THIS keyword

class Box

{

double width;

double height;

double depth;

Box(double width,double height,double depth)

{

this.width=width;

this.height=height;

this.depth=depth;

}

double volume()

{

return width* height* depth;

}

}

class BoxThis

{

public static void main(String args[])

{

double vol;

Box mybox1=new Box(10,20,15);

Box mybox2=new Box(3,6,9);

vol=mybox1.volume();

System.out.println("Volume is " +vol);

vol=mybox2.volume();

System.out.println("Volume is " +vol);

}

}

OUTPUT :

Volume is 3000.0

Volume is 162.0

© www.udaysatya.blogspot.com Page 29

26 Program to Demonstrate Constructor Overloading

class Box

{

double width;

double height;

double depth;

Box(double w,double h,double d)

{

width=w;

height=h;

depth=d;

}

Box()

{

width=-1;

height=-1;

depth=-1;

}

Box(double len)

{

width=height=depth=len;

}

double volume()

{

return width*height*depth;

}

}

© www.udaysatya.blogspot.com Page 30

class OverloadCons

{

public static void main(String args[]) {

Box mybox1=new Box(10,20,15);

Box mybox2=new Box();

Box mycube=new Box(7);

double vol;

vol=mybox1.volume();

System.out.println("volume of mybox1 is " +vol);

vol=mybox2.volume();

System.out.println("volume of mybox2 is " +vol);

vol=mycube.volume();

System.out.println("volume of mycube is " +vol);

}

}

OUTPUT :

volume of mybox1 is 3000.0

volume of mybox2 is -1.0

volume of mycube is 343.0

© www.udaysatya.blogspot.com Page 31

27 Program to pass objects as parameters

class Test

{

int a,b;

Test(int i,int j)

{

a=i;

b=j;

}

boolean equals(Test o)

{

if(o.a==a && o.b==b) return true;

else return false;

}

}

class PassOb

{

public static void main(String args[])

{

Test ob1=new Test(100,22);

Test ob2=new Test(100,22);

Test ob3=new Test(-1,-1);

System.out.println("ob1 == ob2 : " +ob1.equals(ob2));

System.out.println("ob1 == ob3 : " +ob1.equals(ob3));

}

}

OUTPUT :

ob1 == ob2 : true

ob1 == ob3 : false

© www.udaysatya.blogspot.com Page 32

28 Program to Demonstrate Queue using Class

class A

{

int q[] = new int[10];

int f,s;

A()

{

f =-1;

s=-1;

}

void push(int item)

{

if(f==9)

System.out.println("Queue is Full");

else

q[++f]=item;

}

int pop()

{

if(f==s)

{

System.out.println("Queue is Underflow");

return 0;

}

else

return q[++s];

}

}

© www.udaysatya.blogspot.com Page 33

class que{

public static void main(String args[]){

A obj1 = new A();

for(int i=0;i<10;i++)

obj1.push(i);

System.out.println("Queue elements are : ");

for(int i = 0 ;i<10;i++)

System.out.println(obj1.pop());

}

}

OUTPUT :

Queue elements are :

0

1

2

3

4

5

6

7

8

9

© www.udaysatya.blogspot.com Page 34

29 Program to Demonstrate Stack using Class

class A

{

int s[] = new int[10];

int tos;

A()

{

tos=-1;

}

void push(int item)

{

if(tos==9)

System.out.println("Stack is Full");

else

s[++tos]=item;

}

int pop()

{

if(tos<0)

{

System.out.println("Stack is Underflow");

return 0;

}

else

return s[tos--];

}

}

© www.udaysatya.blogspot.com Page 35

class stack{

public static void main(String args[]){

A obj1 = new A();

for(int i=0;i<10;i++)

obj1.push(i);

System.out.println("Stack elements are : ");

for(int i = 0 ;i<10;i++)

System.out.println(obj1.pop());

}

}

OUTPUT :

Stack elements are :

9

8

7

6

5

4

3

2

1

0

© www.udaysatya.blogspot.com Page 36

30 Program to Demonstrate Access Specifiers

class Test

{

int a;

public int b;

private int c;

void setc(int i)

{

c=i;

}

int getc() {

return c;

}

}

class AcessTest

{

public static void main(String args[])

{

Test ob=new Test();

//These are OK,a and b may be accessed directly

ob.a=10;

ob.b=20;

//This is not OK and will cause an error

//ob.c=100; //error!

//you must access c through its methods

ob.setc(100); //Ok

System.out.println("a,b,and c: " +ob.a+" " +ob.b +" "+ob.getc());

}

}

OUTPUT :

a,b,and c: 10 20 100

© www.udaysatya.blogspot.com Page 37

31 Program to Demonstrate Static Variables

class Test

{

static int count;

static

{

System.out.println("Welcome");

count=0;

}

Test()

{

count++;

}

}

class Teststaticvariable

{

public static void main(String args[])

{

Test t1=new Test();

Test t2=new Test();

Test t3=new Test();

System.out.println(Test.count + " objects are created");

}

}

OUTPUT :

Welcome

3 objects are created

© www.udaysatya.blogspot.com Page 38

32 Program to Demonstrate Static Methods

class Mymath

{

static int add(int x,int y)

{

return(x+y);

}

static int subtract(int x,int y)

{

return (x-y);

}

static int square(int x)

{

return (x*x);}

}

class demostaticmethod

{

public static void main(String args[])

{

System.out.println(Mymath.add(100,100));

System.out.println(Mymath.subtract(200,100));

System.out.println(Mymath.square(5));

}

}

OUTPUT :

200

100

25

© www.udaysatya.blogspot.com Page 39

33 Program to demonstrate an Inner class

class Outer

{

int outer_x=100;

void test()

{

Inner inner=new Inner();

inner.display();

}

class Inner

{

void display()

{

System.out.println("display: outer_x= "+outer_x);

}

}

}

class InnerClassDemo

{

public static void main(String args[])

{

Outer outer=new Outer();

outer.test();

}

}

OUTPUT :

display: outer_x= 100

© www.udaysatya.blogspot.com Page 40

34 Program to Demonstrate Type Wrapping

class Wrap {

public static void main(String args[])

{

Integer obj = new Integer(34);

int x = obj.intValue();

System.out.println("x = " +x);

System.out.println("obj = " +obj);

}

}

OUTPUT :

x = 34

obj = 34

© www.udaysatya.blogspot.com Page 41

35 Program to Demonstrate Single Inheritance

class A

{

int i,j;

void showij()

{

System.out.println("i and j : " +i+ " " +j);

}

}

class B extends A

{

int k;

void showk()

{

System.out.println("k : "+k);

}

void sum()

{

System.out.println("i+j+k: "+(i+j+k));

}

}

© www.udaysatya.blogspot.com Page 42

class SimpleInheritance

{

public static void main(String args[])

{

A superob = new A();

B subob = new B();

superob.i=10;

superob.j=20;

System.out.println("Contents of superob: ");

superob.showij();

System.out.println();

subob.i=7;

subob.j=8;

subob.k=9;

System.out.println("Contents of subob: ");

subob.showij();

System.out.println();

System.out.println("Sum of i,j & k in subob: ");

subob.sum();

}

}

OUTPUT :

Contents of superob:

i and j : 10 20

Contents of subob:

i and j : 7 8

Sum of i,j & k in subob:

i+j+k: 24

© www.udaysatya.blogspot.com Page 43

36 Program to Demonstrate Multilevel Inheritance

class Student

{

int rollno;

void getroll(int a)

{

rollno=a;

}

void putroll()

{

System.out.println("Roll number : "+rollno);

}

}

class Test extends Student //first level inheritence

{

int marks1,marks2;

void getmarks(int x,int y)

{

marks1=x;

marks2=y;

}

void putmarks()

{

System.out.println("Marks in subject1 = "+marks1);

System.out.println("Marks in subject2 = "+marks2);

}

}

© www.udaysatya.blogspot.com Page 44

class Result extends Test //second level derivation

{

float total;

void display()

{

total=marks1+marks2;

putroll();

putmarks();

System.out.println("Total = "+total);

}

}

class Multilevel

{

public static void main(String args[])

{

Result student1 = new Result(); //object of class result is created

student1.getroll(34);

student1.getmarks(40,99);

student1.display();

}

}

OUTPUT :

Roll number : 34

Marks in subject1 = 40

Marks in subject2 = 99

Total = 139.0

© www.udaysatya.blogspot.com Page 45

37 Program to Demonstrate hierarchical Inheritance

class Student

{

int roll;

void getroll(int x)

{

roll=x;

}

void putroll()

{

System.out.println(roll);

}

}

class Result1 extends Student

{

int marks1;

void getmarks1(int y)

{

marks1=y;

}

void showmarks1()

{

System.out.print("Roll no of 1st student is = ");

putroll();

System.out.println("Marks of 1st student is = "+marks1);

}

}

© www.udaysatya.blogspot.com Page 46

class Result2 extends Student {

int marks2;

void getmarks2(int z)

{

marks2=z;

}

void showmarks2()

{

System.out.print("Rollno of 2nd student is = ");

putroll();

System.out.println("Marks of 2nd student is = "+marks2);

} }

class Hierarchial

{

public static void main(String args[])

{

Result1 r1 = new Result1();

Result2 r2 = new Result2();;

r1.getroll(36);

r1.getmarks1(99);

r1.showmarks1();

r2.getroll(34);

r2.getmarks2(40);

r2.showmarks2();

}

}

OUTPUT :

Roll no of 1st student is = 36

Marks of 1st student is = 99

Rollno of 2nd student is = 34

Marks of 2nd student is = 40

© www.udaysatya.blogspot.com Page 47

38 Program to Demonstrate SUPER Class variable to reference a sub class object

class A {

int i,j;

A(int a,int b) {

i=a;

j=b;

}

void show() {

System.out.println("i and j: " +i + " " +j);

}}

class B extends A {

int k;

B(int a,int b,int c) {

super(a,b);

k=c; }

void show() {

System.out.println("k: "+k);

}}

class Supref {

public static void main(String args[]) {

B subOb=new B(1,2,3);

A a;

a=subOb;

System.out.println("Using Sub Class Object :");

subOb.show();

System.out.println("Using Super class Variable : ");

a.show();

}}

OUTPUT :

Using Sub Class Object :

k: 3

Using Super class Variable :

k: 3

© www.udaysatya.blogspot.com Page 48

39 Program to Demonstrate Method Overriding

class A {

int i,j;

A(int a,int b)

{

i=a;

j=b;

}

void show() {

System.out.println("i and j: " +i + " " +j);

}}

class B extends A {

int k;

B(int a,int b,int c)

{

super(a,b);

k=c;

}

void show()

{

System.out.println("k: "+k);

}}

class Override {

public static void main(String args[])

{

B subOb=new B(1,2,3);

subOb.show();

}

}

OUTPUT :

k: 3

© www.udaysatya.blogspot.com Page 49

40 Program to Demonstrate Runtime Polymorphism

class figure

{

double dim1;

double dim2;

figure(double a,double b)

{

dim1=a;

dim2=b;

}

double area()

{

System.out.println("area for figure is undefined");

return 0;

}

}

class rectangle extends figure

{

rectangle(double a,double b)

{

super(a,b);

}

double area()

{

System.out.println("Inside Area for rectangle");

return dim1*dim2;

}

}

© www.udaysatya.blogspot.com Page 50

class triangle extends figure {

triangle(double a,double b)

{

super(a,b);

}

double area()

{

System.out.println("Inside area for triangle");

return (dim1*dim2)/2;

}}

class FindAreas {

public static void main(String args[]) {

figure f=new figure(10,10);

rectangle r=new rectangle(9,5);

triangle t=new triangle(10,8);

figure figref;

figref=r;

System.out.println("Area is " +figref.area());

figref=t;

System.out.println("Area is " +figref.area());

figref=f;

System.out.println("Area is " +figref.area());

}}

OUTPUT :

Inside Area for rectangle

Area is 45.0

Inside area for triangle

Area is 40.0

area for figure is undefined

Area is 0.0

© www.udaysatya.blogspot.com Page 51

41 Program to Demonstrate Abstract Class

abstract class A

{

abstract void callme();

void callmetoo(){

System.out.println("this is a concrete method.");

}}

class B extends A

{

void callme()

{

System.out.println("B's implementation of callme.");

}}

class AbstractDemo

{

public static void main(String args[]) {

B b=new B();

b.callme();

b.callmetoo();

}

}

OUTPUT :

B's implementation of callme.

this is a concrete method.

© www.udaysatya.blogspot.com Page 52

42 Program to Demonstrate FINAL Keyword

class A

{

final int x =3;

int y;

A()

{

//x=4;this results in error

y=4;

}

}

class Finaldemo {

public static void main(String args[]) {

A a = new A();

System.out.println("x = " +a.x);

System.out.println("y = " +a.y);

//a.x=5;this also results in error

a.y=6;

System.out.println("x = " +a.x);

System.out.println("y = " +a.y);

}

}

OUTPUT :

x = 3

y = 4

x = 3

y = 6

© www.udaysatya.blogspot.com Page 53

43 Program to Demonstrate FINAL Method

class A {

int i,j;

A(int a,int b) {

i=a;

j=b;

}

void show() {

System.out.println("i and j: " +i + " " +j);

}

final void display() //Cannot be Overriden

{

System.out.println("i and j: " +i + " " +j);

}}

class B extends A {

int k;

B(int a,int b,int c) {

super(a,b);

k=c;

}

void show() {

System.out.println("k: "+k);

}}

class Finalmeth {

public static void main(String args[])

{

B subOb=new B(1,2,3);

System.out.println("Overriden Method call :");

subOb.show();

System.out.println("Final Method call :");

subOb.display();

}}

OUTPUT :

Overriden Method call :

k: 3

Final Method call :

i and j: 1 2

© www.udaysatya.blogspot.com Page 54

44 Program to Demonstrate FINAL Class

final class Democlass //Cannot be inherited

{

int a=34;

void showa()

{

System.out.println("a = " +a);

}

}

class A

{

public static void main(String args[])

{

Democlass obj = new Democlass();

obj.showa();

}

}

OUTPUT :

a=34

© www.udaysatya.blogspot.com Page 55

45 Program to Demonstrate INTERFACE

interface Sum // defining Interface

{

int z=2;//final variable declared

int add();//Abstract Method declared

}

class A implements Sum // Class implementing Interface

{

int x,y;

public int add() {

return x+y+z;

}

}

class InterfaceDemo

{

public static void main(String args[])

{

A a = new A();

a.x=14;

a.y=18;

System.out.println("Sum : " +a.add());

}

}

OUTPUT :

Sum : 34

© www.udaysatya.blogspot.com Page 56

46 Program to access implementation through Interface references

interface figure

{

double area();

}

class rectangle implements figure

{

double dim1,dim2;

rectangle(double a,double b)

{

dim1=a;dim2=b;

}

public double area()

{

return dim1*dim2;

}

}

class triangle implements figure

{

double dim1,dim2;

triangle(double a,double b)

{

dim1=a;dim2=b;

}

public double area()

{

return (dim1*dim2)/2;

}

}//implements through interface

© www.udaysatya.blogspot.com Page 57

class demo

{

public static void main(String args[])

{

rectangle r=new rectangle(100,50);

triangle t=new triangle(10,20);

figure f;

f=r;

System.out.println(f.area());

f=t;

System.out.println(f.area());

}

}

OUTPUT :

5000.0

100.0

© www.udaysatya.blogspot.com Page 58

47 Program to Demonstrate EXTENDING INTERFACE

interface A {

void meth1();

void meth2();

}

interface B extends A {

void meth3();

}

class Myclass implements B {

public void meth1() {

System.out.println("method1");

}

public void meth2() {

System.out.println("method2");

}

public void meth3() {

System.out.println("method3");

}}

class Extint {

public static void main(String args[]) {

Myclass m = new Myclass();

m.meth1();

m.meth2();

m.meth3();

}}

Output :

method1

method2

method3

© www.udaysatya.blogspot.com Page 59

48 Program to Demonstrate Stack using interface

interface stack

{

void push(int item);

int pop();

}

class A implements stack

{

int s[];

int tos;

A(int size)

{

s = new int[size];

tos = -1;

}

public void push(int item)

{

if(tos == s.length-1)

System.out.println("STACK is FULL");

else

s[++tos]=item;

}

public int pop()

{

if(tos<0)

{

System.out.println("STACK IS EMPTY");

return 0;

}

else

return s[tos--];

}}

© www.udaysatya.blogspot.com Page 60

class S {

public static void main(String args[]){

int i;

A stack1 = new A(5);

for(i=0;i<5;i++)

stack1.push(i);

System.out.println("Stack elements are : ");

for(i =0;i<5;i++)

System.out.println(stack1.pop());

}

}

OUTPUT :

Stack elements are :

4

3

2

1

0

© www.udaysatya.blogspot.com Page 61

49 Program to Demonstrate Queue using Interface

interface queue

{

void push(int item);

int pop();

}

class B implements queue

{

int s[];

int f,l;

B(int size)

{

s = new int[size];

f = -1;

l = -1;

}

public void push(int item)

{

if(f == s.length-1)

System.out.println("Q is FULL");

else

s[++f]=item;

}

public int pop()

{

if(f==l)

{

System.out.println(" Q iS EMPTY");

return 0;

}

else

return s[++l];

}}

© www.udaysatya.blogspot.com Page 62

class Q

{

public static void main(String args[]){

int i;

B q1=new B(8);

for(i=0;i<8;i++)

q1.push(i);

System.out.println("Queue elements are : ");

for(i =0;i<8;i++)

System.out.println(q1.pop());

}

}

OUTPUT :

Queue elements are :

0

1

2

3

4

5

6

7

© www.udaysatya.blogspot.com Page 63

50 Program to Demonstrate a SIMPLE PACKAGE

package MyPack;

public class Balance {

String name;

double bal;

public Balance(string n,double b) {

name=n;

bal=b;

}

public void show() {

if(bal<0)

System.out.println("-->");

System.out.println(name+ ": $"+bal);

}}

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

import MyPack.*;

class TestBalance

{

public static void main(string args[])

{

BalanceTest=new Balance("Uday Satya",500);

test.show();

}

}

OUTPUT :

Uday Satya : $500

© www.udaysatya.blogspot.com Page 64

51 Program to Demonstrate Exception

class Excep

{

static void meth1()

{

int d=0;

int a=10/d;

}

public static void main(String a[])

{

Excep.meth1();

}

}

OUTPUT :

Exception in thread "main" java.lang.ArithmeticException: / by zero

at Excep.meth1(Excep.java:6)

at Excep.main(Excep.java:10)

© www.udaysatya.blogspot.com Page 65

52 Program to Demonstrate TRY CATCH

class TC

{

public static void main(String a[])

{

int c[]={2,4,6,8};

try

{

c[34]=99;

}

catch(ArrayIndexOutOfBoundsException e)

{

System.out.println("Array Index Out Of Bound "+e);

}

}

}

OUTPUT :

Array Index Out Of Bound java.lang.ArrayIndexOutOfBoundsException: 34

© www.udaysatya.blogspot.com Page 66

53 Program to CATCH ARITHMETIC Exceptions

class trysimple

{

public static void main(String args[])

{

int d,a;

try

{

d = 0;

a = 42/d;

System.out.println("This will not Display");

}

catch(ArithmeticException e)

{

System.out.println("Division by zero");

}

System.out.println("After try/Catch Statements");

}

}

OUTPUT :

Division by zero

After try/Catch Statements

© www.udaysatya.blogspot.com Page 67

54 Program to demonstrate Multiple CATCH

class trydemo1

{

public static void main(String args[])

{

try {

int l=args.length;

System.out.println("l = " +l);

int b = 34/l;

int c[]={0};

c[34]=100;

System.out.println("End of Try Block");

}

catch(ArithmeticException e)

{

System.out.println("Please Enter Command line Arguments");

}

catch(ArrayIndexOutOfBoundsException e)

{

System.out.println("Your Array size is small");

}

catch(Exception e)

{

System.out.println("Other type of Exception");

}

}}

OUTPUT :

l = 0

Please Enter Command line Arguments

© www.udaysatya.blogspot.com Page 68

55 Program to demonstrate NESTED TRY

class NestTry

{

public static void main(String args[])

{

try {

int a = args.length;

int b = 42 /a;

System.out.println("a = "+ a);

try {

if(a==1) a = a/(a-a);

if (a==2) {

int c[] = {1};

c[42] = 99;

}

} catch(ArrayIndexOutOfBoundsException e) {

System.out.println("Array index out-of-bounds:"+e);

}

} catch(ArithmeticException e) {

System.out.println("Divide by 0:"+e);

}

}

}

OUTPUT :

Divide by 0:java.lang.ArithmeticException: / by zero

© www.udaysatya.blogspot.com Page 69

56 Program to demonstrate FINALLY clause

class trydemo{

public static void main(String args[]){

try{

int l=args.length;

System.out.println("l = " +l);

int b = 34/l;

int c[]={0};

c[34]=100;

System.out.println("End of Try Block");

}

catch(ArithmeticException e)

{

System.out.println("Please Enter Command line Arguments");

}

catch(ArrayIndexOutOfBoundsException e)

{

System.out.println("Your Array size is small");

}

catch(Exception e)

{

System.out.println("Other type of Exception");

}

finally{

System.out.println("This will be executed");

}

}}

OUTPUT :

l = 0

Please Enter Command line Arguments

This will be executed

© www.udaysatya.blogspot.com Page 70

57 Program to Demonstrate User Defined EXCEPTIONS

class Myexception extends Exception {

private int d;

Myexception(int a)

{

d=a;

}

public String toString() {

return "Myexception["+d+"]";

}}

class UserExcep {

static void compute(int a) throws Myexception {

System.out.println("called compute("+a+")");

if(a>50)

throw new Myexception(a);

System.out.println("normal exit");

}

public static void main(String a[])

{

try {

compute(34);

compute(99);

}

catch(Myexception e)

{

System.out.println("caught "+e);

}}}

OUTPUT :

called compute(34)

normal exit

called compute(99)

caught Myexception[99]

© www.udaysatya.blogspot.com Page 71

58 Program to Demonstrate Throws

class ThrowsDemo

{

static void throwOne() throws IllegalAccessException

{

System.out.println("Inside throwOne.");

throw new IllegalAccessException("demo");

}

public static void main(String args[])

{

try

{

throwOne();

}

catch (IllegalAccessException e)

{

System.out.println("Caught "+e);

}

}

}

OUTPUT :

Inside throwOne.

Caught java.lang.IllegalAccessException: demo

© www.udaysatya.blogspot.com Page 72

59 Program to demonstrate MULTITHREADING

class A extends Thread

{

public void run()

{

for(int i=1;i<=5;i++)

System.out.println("\tfrom Thread A : i = " +i);

System.out.println("Exit from A");

}}

class B extends Thread

{

public void run()

{

for(int j=1;j<=5;j++)

System.out.println("\tfrom Thread B : j = " +j);

System.out.println("Exit from B");

}}

class C extends Thread

{

public void run()

{

for(int k=1;k<=5;k++)

System.out.println("\tfrom Thread C : k = " +k);

System.out.println("Exit from C");

}}

© www.udaysatya.blogspot.com Page 73

class Threadtest

{

public static void main(String args[])

{

new A().start();

new B().start();

new C().start();

try{

Thread.sleep(10);

}

catch(InterruptedException e){

System.out.println("Exception " +e);

}

}

}

OUTPUT :

from Thread A : i = 1

from Thread A : i = 2

from Thread A : i = 3

from Thread A : i = 4

from Thread A : i = 5

Exit from A

from Thread B : j = 1

from Thread C : k = 1

from Thread B : j = 2

from Thread C : k = 2

from Thread B : j = 3

from Thread C : k = 3

from Thread B : j = 4

from Thread C : k = 4

from Thread B : j = 5

from Thread C : k = 5

Exit from B

Exit from C

© www.udaysatya.blogspot.com Page 74

60 Program to Demonstrate Runnable Interface

class A implements Runnable

{

public void run()

{

for(int i=1;i<=5;i++)

System.out.println("\tfrom Thread A : i = " +i);

System.out.println("Exit from A");

}}

class B implements Runnable

{

public void run()

{

for(int j=1;j<=5;j++)

System.out.println("\tfrom Thread B : j = " +j);

System.out.println("Exit from B");

}}

class C implements Runnable{

public void run(){

for(int k=1;k<=5;k++)

System.out.println("\tfrom Thread C : k = " +k);

System.out.println("Exit from C");

}}

© www.udaysatya.blogspot.com Page 75

class Runnabletest{

public static void main(String args[]){

A a = new A();

B b = new B();

C c = new C();

Thread t1 = new Thread(a);

t1.start();

Thread t2 = new Thread(b);

t2.start();

Thread t3 = new Thread(c);

t3.start();

try{

Thread.sleep(10);

}

catch(InterruptedException e){

System.out.println("Exception " +e);

}}}

OUTPUT :

from Thread A : i = 1

from Thread B : j = 1

from Thread C : k = 1

from Thread A : i = 2

from Thread B : j = 2

from Thread C : k = 2

from Thread A : i = 3

from Thread B : j = 3

from Thread C : k = 3

from Thread A : i = 4

from Thread B : j = 4

from Thread C : k = 4

from Thread A : i = 5

from Thread B : j = 5

from Thread C : k = 5

Exit from A

Exit from B

Exit from C

© www.udaysatya.blogspot.com Page 76

61 Program to Demonstrate Thread Priorities

class A extends Thread

{

public void run()

{

for(int i=1;i<=5;i++)

System.out.println("\tfrom Thread A : i = " +i);

System.out.println("Exit from A");

}}

class B extends Thread{

public void run(){

for(int j=1;j<=5;j++)

System.out.println("\tfrom Thread B : j = " +j);

System.out.println("Exit from B");

}}

class C extends Thread{

public void run(){

for(int k=1;k<=5;k++)

System.out.println("\tfrom Thread C : k = " +k);

System.out.println("Exit from C");

}}

© www.udaysatya.blogspot.com Page 77

class Prioritytest {

public static void main(String args[]){

A a = new A();

B b = new B();

C c = new C();

c.setPriority(Thread.MAX_PRIORITY);

b.setPriority(a.getPriority()+1);

a.setPriority(Thread.MIN_PRIORITY);

a.start();

b.start();

c.start();

}

}

OUTPUT :

from Thread C : k = 1

from Thread B : j = 1

from Thread A : i = 1

from Thread C : k = 2

from Thread B : j = 2

from Thread A : i = 2

from Thread C : k = 3

from Thread B : j = 3

from Thread A : i = 3

from Thread C : k = 4

from Thread B : j = 4

from Thread A : i = 4

from Thread C : k = 5

from Thread B : j = 5

from Thread A : i = 5

Exit from C

Exit from B

Exit from A

© www.udaysatya.blogspot.com Page 78

62 Program to Demonstrate Synchronized Block

class Callme

{

void call(String msg)

{

System.out.print("[" +msg);

try {

Thread.sleep(1000);

}

catch(InterruptedException e)

{

System.out.println("Interrupted");

}

System.out.println("]");

}

}

class Caller implements Runnable

{

String msg;

Callme target;

Thread t;

public Caller(Callme targ, String s)

{

target=targ;

msg=s;

t=new Thread(this);

t.start();

}

public void run()

{

synchronized(target) {

target.call(msg);

}}}

© www.udaysatya.blogspot.com Page 79

class SynchBlock

{

public static void main(String args[])

{

Callme target=new Callme();

Caller ob1=new Caller(target, "Hello");

Caller ob2=new Caller(target, "Synchronized");

Caller ob3=new Caller(target, "World");

try

{

ob1.t.join();

ob2.t.join();

ob3.t.join();

}

catch(InterruptedException e)

{

System.out.println("Interrupted");

}

}

}

OUTPUT :

[Hello]

[Synchronized]

[World]

© www.udaysatya.blogspot.com Page 80

63 Program to Demonstrate Synchronized Method

class Callme

{

synchronized void call(String msg)

{

System.out.print("[" +msg);

try {

Thread.sleep(1000);

}

catch(InterruptedException e)

{

System.out.println("Interrupted");

}

System.out.println("]");

}}

class Caller implements Runnable

{

String msg;

Callme target;

Thread t;

public Caller(Callme targ, String s)

{

target=targ;

msg=s;

t=new Thread(this);

t.start();

}

public void run()

{

target.call(msg);

}}

© www.udaysatya.blogspot.com Page 81

class SynchMeth

{

public static void main(String args[])

{

Callme target=new Callme();

Caller ob1=new Caller(target, "Hello");

Caller ob2=new Caller(target, "Synchronized");

Caller ob3=new Caller(target, "World");

try

{

ob1.t.join();

ob2.t.join();

ob3.t.join();

}

catch(InterruptedException e)

{

System.out.println("Interrupted");

}

}

}

OUTPUT :

[Hello]

[Synchronized]

[World]

© www.udaysatya.blogspot.com Page 82

64 Program to Demonstrate Deadlock

class A {

synchronized void foo(B b) {

String name=Thread.currentThread().getName();

System.out.println(name+ " entered A.foo");

try {

Thread.sleep(1000);

}

catch(Exception e) {

System.out.println("A Interrupted");

}

System.out.println(name+ " trying to call B.last()");

b.last();

}

synchronized void last()

{

System.out.println("Inside A.last");

}}

class B {

synchronized void bar(A a) {

String name=Thread.currentThread().getName();

System.out.println(name+ " entered B.bar");

try {

Thread.sleep(1000);

}

catch(Exception e) {

System.out.println("B Interrupted");

}

System.out.println(name+ " trying to call A.last()");

a.last();

}

synchronized void last() {

System.out.println("Inside A.last");

}}

© www.udaysatya.blogspot.com Page 83

class Deadlock implements Runnable

{

A a=new A();

B b=new B();

Deadlock()

{

Thread.currentThread().setName("mainThread");

Thread t=new Thread(this, "RacingThread");

t.start();

a.foo(b);

System.out.println("Back in main thread");

}

public void run()

{

b.bar(a);

System.out.println("Back in other thread");

}

public static void main(String args[])

{

new Deadlock();

}

}

OUTPUT :

mainThread entered A.foo

RacingThread entered B.bar

mainThread trying to call B.last()

RacingThread trying to call A.last()

© www.udaysatya.blogspot.com Page 84

65 Program to Demonstrate Thread Methods

class Q {

int n;

boolean valueSet= false;

synchronized int get() {

if(!valueSet)

try {

wait();

}

catch(InterruptedException ie) {

System.out.println("InterruptedException caught");

}

System.out.println("Got: " + n);

valueSet=false;

notify();

return n;

}

synchronized void put(int n) {

if(valueSet)

try {

wait();

}

catch(InterruptedException ie) {

System.out.println("InterruptedException caught");

}

this.n=n;

valueSet=true;

System.out.println("Put: " + n);

notify();

}}

class Producer implements Runnable {

Q q;

Producer(Q q) {

this.q=q;

new Thread(this, "Producer").start();

}

public void run() {

© www.udaysatya.blogspot.com Page 85

int i=0;

while(true) {

q.put(i++);

}}}

class Consumer implements Runnable {

Q q;

Consumer(Q q) {

this.q=q;

new Thread(this, "Consumer").start();

}

public void run() {

int i=0;

while(true) {

q.get();

}}}

class PCFixed {

public static void main(String args[]) {

Q q=new Q();

new Producer(q);

new Consumer(q);

System.out.println("Press Control-C to stop.");

}}

OUTPUT :

Put : 1

Got : 1

Put : 2

Got : 2

Put : 3

Got : 3

Put : 4

Got : 4

Put : 5

Got : 5

© www.udaysatya.blogspot.com Page 86

66 Program to Create Threads using Thread Class

class A extends Thread

{

public void run()

{

for(int i=1;i<=5;i++)

System.out.println("\tfrom Thread A : i = " +i);

System.out.println("Exit from A");

}

}

class B extends Thread

{

public void run()

{

for(int j=1;j<=5;j++)

System.out.println("\tfrom Thread B : j = " +j);

System.out.println("Exit from B");

}

}

© www.udaysatya.blogspot.com Page 87

class Threadtest

{

public static void main(String args[])

{

new A().start();

new B().start();

try{

Thread.sleep(10);

}

catch(InterruptedException e)

{

System.out.println("Exception " +e);

}

}

}

OUTPUT :

from Thread A : i = 1

from Thread B : j = 1

from Thread A : i = 2

from Thread B : j = 2

from Thread A : i = 3

from Thread B : j = 3

from Thread A : i = 4

from Thread B : j = 4

from Thread A : i = 5

from Thread B : j = 5

Exit from A

Exit from B

© www.udaysatya.blogspot.com Page 88

67 Program to Demonstrate Join() & isAlive() methods

class NewThread implements Runnable {

String name;

Thread t;

NewThread(String threadname) {

name=threadname;

t= new Thread(this,name);

System.out.println("New Thread: "+t);

t.start();

}

public void run() {

try {

for(int i=5;i>0;i--) {

System.out.println(name + ": " +i);

Thread.sleep(1000);

}}

catch (InterruptedException ie) {

System.out.println(name + "interrupted."); }

System.out.println(name + "exiting.");

}}

class DemoJoin {

public static void main(String args[]) {

NewThread ob1= new NewThread("One");

NewThread ob2= new NewThread("Two");

NewThread ob3= new NewThread("Three");

System.out.println("Thread One is alive: "+ ob1.t.isAlive());

System.out.println("Thread Two is alive: "+ ob2.t.isAlive());

System.out.println("Thread Three is alive: "+ ob3.t.isAlive());

try {

System.out.println("Waiting for threads to finish.");

ob1.t.join();

ob2.t.join();

ob3.t.join();

}

catch (InterruptedException ie) {

System.out.println("Main thread Interrupted"); }

System.out.println("Thread One is alive: "+ ob1.t.isAlive());

© www.udaysatya.blogspot.com Page 89

System.out.println("Thread Two is alive: "+ ob2.t.isAlive());

System.out.println("Thread Three is alive: "+ ob3.t.isAlive());

System.out.println("Main thread exiting.");

}}

OUTPUT :

New Thread: Thread[One,5,main]

New Thread: Thread[Two,5,main]

One: 5

Two: 5

New Thread: Thread[Three,5,main]

Thread One is alive: true

Three: 5

Thread Two is alive: true

Thread Three is alive: true

Waiting for threads to finish.

Two: 4

One: 4

Three: 4

Two: 3

One: 3

Three: 3

Two: 2

One: 2

Three: 2

Two: 1

One: 1

Three: 1

Twoexiting.

Oneexiting.

Threeexiting.

Thread One is alive: false

Thread Two is alive: false

Thread Three is alive: false

Main thread exiting.

© www.udaysatya.blogspot.com Page 90

68 Program to Demonstrate Get User Input from Keyboard

import java.io.*;

class GetUserInput

{

public static void main(String[] args)

{

//the data that will be entered by the user

String name;

//an instance of the BufferedReader class

//will be used to read the data

BufferedReader reader;

//specify the reader variable

//to be a standard input buffer

reader = new BufferedReader(new InputStreamReader(System.in));

//ask the user for their name

System.out.print("What is your name? ");

try{

//read the data entered by the user using

//the readLine() method of the BufferedReader class

//and store the value in the name variable

name = reader.readLine();

//print the data entered by the user

System.out.println("Your name is " + name);

}

catch (IOException ioe){

//statement to execute if an input/output exception occurs

System.out.println("An unexpected error occured.");

}

}

}

OUTPUT :

What is your name? Uday Satya

Your name is Uday Satya

© www.udaysatya.blogspot.com Page 91

69 Program to Create a Frame Window using Applet

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

/*

<applet code="AppletFrameWindowEx1" width=300 height=50>

</applet>

*/

class FrameTest extends Frame {

FrameTest(String title) {

super(title);

MyWindowAdapter adap=new MyWindowAdapter(this);

addWindowListener(adap);

}

public void paint(Graphics g) {

g.drawString("This is in frame window",10,40);

}}

class MyWindowAdapter extends WindowAdapter {

FrameTest ft;

public MyWindowAdapter(FrameTest ft) {

this.ft=ft;

}

public void WindowClosing(WindowEvent we) {

ft.setVisible(false);

}}

public class AppletFrameWindowEx1 extends Applet {

Frame f;

public void init() {

f=new FrameTest("A frame Window");

f.setSize(300,300);

f.setVisible(true);

}

public void start() {

f.setVisible(true);

}

© www.udaysatya.blogspot.com Page 92

public void stop() {

f.setVisible(false);

}

public void paint(Graphics g) {

g.drawString("This is a Test applet",10,20);

}}

© www.udaysatya.blogspot.com Page 93

70 Program to Demonstrate Life cycle of methods in Applet

import java.awt.*;

import java.applet.*;

/*

<applet code="Sample" width=400 height=200>

</applet>*/

public class Sample extends Applet {

String msg;

public void init() {

setBackground(Color.cyan);

setForeground(Color.red);

msg="Inside init()--";

}

public void start() {

msg +="Inside start()--";

}

public void paint(Graphics g) {

msg +="Inside paint()--";

g.drawString(msg,10,30);

}}

© www.udaysatya.blogspot.com Page 94

71 Program to display Parameters of HTML

import java.awt.*;

import java.applet.*;

/*

<applet code="ParamDemo" width=400 height=200>

<param name=fontName value=Courier>

<param name=fontSize value=14>

<param name=leading value=2>

<param name=accountEnabled value=true>

</applet>

*/

public class ParamDemo extends Applet {

String fontName;

int fontSize;

float leading;

boolean active;

public void start() {

String param;

fontName=getParameter("fontName");

if(fontName==null)

fontName="Not Found";

param=getParameter("fontSize");

try {

if(param != null)

fontSize=Integer.parseInt(param);

else

fontSize=0;

}

catch(NumberFormatException e) {

fontSize=-1;

}

param = getParameter("leading");

try {

if(param != null)

leading = Float.valueOf(param).floatValue();

else

© www.udaysatya.blogspot.com Page 95

leading=0;

}

catch(NumberFormatException e) {

leading=-1;

}

param=getParameter("accountEnabled");

if(param != null)

active = Boolean.valueOf(param).booleanValue();

}

public void paint(Graphics g) {

g.drawString("Font name: "+fontName,0,10);

g.drawString("Font size: "+fontSize,0,26);

g.drawString("Leading: "+leading,0,42);

g.drawString("Account Active: "+active,0,58);

}

}

© www.udaysatya.blogspot.com Page 96

72 Program to Demonstrate all shapes in Graphics class

import java.awt.*;

import java.applet.*;

/*

<applet code="FigPaint" width=400 height=200>

</applet>

*/

public class FigPaint extends Applet

{

public void paint(Graphics g)

{

g.drawLine(0,0,100,100);

g.drawRect(10,10,60,50);

g.fillRect(100,10,60,50);

g.drawOval(10,10,50,50);

g.fillOval(100,10,75,50);

g.drawArc(10,40,70,70,0,75);

g.fillArc(100,40,70,70,0,75);

}

}

© www.udaysatya.blogspot.com Page 97

73 Program to Show a Hut,Mountains & Face

import java.awt.*;

import java.applet.*;

/*

<applet code=house.class height=400 width=800>

</applet>

*/

public class house extends Applet

{

public void paint(Graphics g)

{

setBackground(Color.black);

setForeground(Color.white);

g.drawLine(330,220,400,120);

g.drawLine(400,120,470,220);

g.drawLine(349,200,349,300);

g.drawLine(450,200,450,300);

g.drawLine(349,300,450,300);

g.drawRect(385,260,20,40);

g.drawRect(420,220,15,15);

g.fillOval(80,50,40,40);

setBackground(Color.black);

g.drawLine(20,380,60,130);

g.drawLine(60,130,100,360);

g.drawLine(100,360,140,140);

g.drawLine(140,140,180,340);

g.drawLine(180,340,220,150);

g.drawLine(220,150,260,320);

g.drawLine(260,320,315,165);

g.drawLine(315,165,335,210);

g.drawOval(330,350,130,40);

g.drawOval(550,60,60,60);

g.drawOval(565,80,10,10);

g.drawOval(585,80,10,10);

g.drawArc(566,81,30,30,0,-180);

g.drawLine(580,120,580,300);

© www.udaysatya.blogspot.com Page 98

g.drawLine(520,190,580,160);

g.drawLine(580,160,640,190);

g.drawLine(530,340,580,300);

g.drawLine(580,300,630,340);

}

}

© www.udaysatya.blogspot.com Page 99

74 Program to Show Status of Applet Window

import java.awt.*;

import java.applet.*;

/*

<applet code="StatusWindow" width=400 height=200>

</applet>

*/

public class StatusWindow extends Applet {

public void init() {

setBackground(Color.cyan);

}

public void paint(Graphics g)

{

g.drawString("This is in the applet window.",10,20);

showStatus("This is shown in the status window.");

}

}

© www.udaysatya.blogspot.com Page 100

75 Program to Show Position of the Mouse in Applet Window

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

public class AppWindow extends Frame {

String keymsg = "";

String mousemsg = "";

int mouseX=30, mouseY=30;

public AppWindow()

{

addKeyListener(new MyKeyAdapter(this));

addMouseListener(new MyMouseAdapter(this));

addWindowListener(new MyWindowAdapter());

}

public void paint(Graphics g)

{

g.drawString(keymsg,10,40);

g.drawString(mousemsg,mouseX,mouseY);

}

public static void main(String args[])

{

AppWindow appwin=new AppWindow();

appwin.setSize(new Dimension(400,200));

appwin.setTitle("an AWT-Based Application");

appwin.setVisible(true);

}

}

class MyKeyAdapter extends KeyAdapter

{

AppWindow appWindow;

public MyKeyAdapter(AppWindow appWindow)

{

this.appWindow=appWindow;

}

© www.udaysatya.blogspot.com Page 101

public void keyTyped(KeyEvent ke) {

appWindow.keymsg +=ke.getKeyChar();

appWindow.repaint();

};}

class MyMouseAdapter extends MouseAdapter {

AppWindow appWindow;

public MyMouseAdapter(AppWindow appWindow) {

this.appWindow=appWindow;

}

public void mousePressed(MouseEvent me) {

appWindow.mouseX=me.getX();

appWindow.mouseY=me.getY();

appWindow.mousemsg="Mouse Down at "+appWindow.mouseX +", "+appWindow.mouseY;

appWindow.repaint();

}}

class MyWindowAdapter extends WindowAdapter {

public void windowClosing(WindowEvent we) {

System.exit(0);

}}

© www.udaysatya.blogspot.com Page 102

76 Program to Demonstrate Colors

import java.awt.*;

import java.applet.*;

/*

<applet code=colordemo width=400 height=200>

</applet>

*/

public class Colordemo extends Applet{

public void paint(Graphics g){

Color c1 = new Color(255,100,100);

Color c2 = new Color(10,255,100);

Color c3 = new Color(100,200,255);

g.setColor(c1);

g.drawLine(110,50,100,100);

g.drawLine(130,100,100,40);

g.setColor(c2);

g.fillRect(60,120,50,50);

g.setColor(c3);

g.fillOval(20,30,70,70);

g.setColor(Color.black);

g.fillRect(120,50,180,90);

}}

© www.udaysatya.blogspot.com Page 103

77 Program to Pass Parameters perform Mathematical Operations

import java.awt.*;

import java.applet.*;

/*<APPLET CODE = "HelloJavaParam1.class" WIDTH=400 HEIGHT=200>

<Param Name="num1" value="55">

<Param Name="num2" value="35">

</APPLET>*/

public class HelloJavaParam1 extends Applet {

int a,b;

public void start() {

a=Integer.parseInt(getParameter("num1")); //recieving parameter value

b=Integer.parseInt(getParameter("num2")); //recieving parameter value

}

public void paint(Graphics g) {

g.drawString(" a = "+a +" b = "+b,20,50);

g.drawString("Mathematical Operation",20,70);

g.drawString("Sum = "+(a+b),20,100);

g.drawString("Difference = "+(a-b),20,120);

g.drawString("Product = "+(a*b),20,140);

g.drawString("Mod = "+(a%b),20,160);

}

}

© www.udaysatya.blogspot.com Page 104

78 Program To Get Document Code Bases

import java.awt.*;

import java.applet.*;

import java.net.*;

/*

<applet code="Bases" width=400 height=200>

</applet>

*/

public class Bases extends Applet{

// Display code and document bases.

public void paint(Graphics g) {

String msg;

URL url = getCodeBase(); // get code base

msg = "Code base: " + url.toString();

g.drawString(msg, 10, 20);

url = getDocumentBase(); // get document base

msg = "Document base: " + url.toString();

g.drawString(msg, 10, 40);

}

}

© www.udaysatya.blogspot.com Page 105

79 Program to Show an Image

import java.awt.*;

import java.applet.*;

/*

<applet code="DrawImageApp.class" height=200 width=400>

</applet>

*/

public class DrawImageApp extends Applet {

Image i;

public void start()

{

i = getImage(getDocumentBase(),"sunflower.jpg");

}

public void paint(Graphics g)

{

g.drawImage(i,50,50,this);

}

}

© www.udaysatya.blogspot.com Page 106

80 Program to Show an Image

import java.awt.*;

import java.applet.*;

/*

<applet code="SimpleBanner" width=400 height=200>

</applet>

*/

public class SimpleBanner extends Applet implements Runnable

{

String msg = " A Simple Moving Banner.";

Thread t = null;

int state;

boolean stopFlag;

// Set colors and initialize thread.

public void init() {

setBackground(Color.cyan);

setForeground(Color.red);

}

// Start thread

public void start() {

t = new Thread(this);

stopFlag = false;

t.start();

}

// Entry point for the thread that runs the banner.

public void run() {

char ch;

// Display banner

for( ; ; ) {

try {

repaint();

Thread.sleep(250);

ch = msg.charAt(0);

msg = msg.substring(1, msg.length());

msg += ch;

© www.udaysatya.blogspot.com Page 107

if(stopFlag)

break;

} catch(InterruptedException e) {}

}

}

// Pause the banner.

public void stop() {

stopFlag = true;

t = null;

}

// Display the banner.

public void paint(Graphics g) {

g.drawString(msg, 50, 30);

}

}

© www.udaysatya.blogspot.com Page 108

81 Program to demonstrate an Adapter

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

/*

<applet code="AdapterDemo" width=300 height=100>

</applet>

*/

public class AdapterDemo extends Applet {

public void init() {

addMouseListener(new MyMouseAdapter(this));

addMouseMotionListener(new MyMouseMotionAdapter(this));

}}

class MyMouseAdapter extends MouseAdapter{

AdapterDemo adapterDemo;

public MyMouseAdapter(AdapterDemo adapterDemo) {

this.adapterDemo = adapterDemo;

}

public void mouseClicked(MouseEvent me) {

adapterDemo.showStatus("Mouse clicked");

}}

class MyMouseMotionAdapter extends MouseMotionAdapter{

AdapterDemo adapterDemo;

public MyMouseMotionAdapter(AdapterDemo adapterDemo) {

this.adapterDemo = adapterDemo;

}

public void mouseDragged(MouseEvent me) {

adapterDemo.showStatus("Mouse dragged");

}}

© www.udaysatya.blogspot.com Page 109

© www.udaysatya.blogspot.com Page 110

82 Program to Demonstrate Button

import java.applet.*;

import java.awt.*;

import java.awt.event.*;

/*<applet code=demobutton.class height=200 width=400>

</applet>*/

public class demobutton extends Applet implements ActionListener

{

String msg="";

Button b1,b2;

public void init()

{

b1=new Button("OK");

b2=new Button("CANCEL");

add(b1);

add(b2);

b1.addActionListener(this);

b2.addActionListener(this);

}

public void actionPerformed(ActionEvent e)

{

String s=e.getActionCommand();

if(s.equals("OK"))

{

msg="You pressed OK";

}

else

{

msg="You pressed CANCEL";

}

repaint();

}

public void paint(Graphics g){

g.drawString(msg,40,40);

}

}

© www.udaysatya.blogspot.com Page 111

© www.udaysatya.blogspot.com Page 112

83 Program to Demonstrate Checkbox

import java.applet.*;

import java.awt.*;

import java.awt.event.*;

/*<applet code=democheckbox.class height=200 width=400>

</applet>*/

public class democheckbox extends Applet implements ItemListener {

String msg="";

Checkbox c1,c2,c3;

public void init() {

c1=new Checkbox("JAVA",null,true);

c2=new Checkbox("VB");

c3=new Checkbox("ORACLE");

add(c1);

add(c2);

add(c3);

c1.addItemListener(this);

c2.addItemListener(this);

c3.addItemListener(this);

}

public void itemStateChanged(ItemEvent e) {

repaint();

}

public void paint(Graphics g) {

msg="JAVA:"+c1.getState();

g.drawString(msg,40,40);

msg="VB:"+c2.getState();

g.drawString(msg,40,60);

msg="ORACLE:"+c3.getState();

g.drawString(msg,40,80);

}}

© www.udaysatya.blogspot.com Page 113

© www.udaysatya.blogspot.com Page 114

84 Program to Demonstrate Radio Buttons (CheckboxGroup)

import java.applet.*;

import java.awt.*;

import java.awt.event.*;

/*<applet code=democheckboxgrp.class height=200 width=400>

</applet>*/

public class democheckboxgrp extends Applet implements ItemListener {

String msg="";

Checkbox c1,c2,c3;

CheckboxGroup cg;

public void init() {

cg=new CheckboxGroup();

c1=new Checkbox("JAVA",cg,true);

c2=new Checkbox("VB",cg,false);

c3=new Checkbox("ORACLE",cg,false);

add(c1);

add(c2);

add(c3);

c1.addItemListener(this);

c2.addItemListener(this);

c3.addItemListener(this);

}

public void itemStateChanged(ItemEvent e) {

repaint();

}

public void paint(Graphics g) {

msg="curently selected:"+cg.getSelectedCheckbox().getLabel();

g.drawString(msg,40,40);

}

}

© www.udaysatya.blogspot.com Page 115

© www.udaysatya.blogspot.com Page 116

85 Program to Demonstrate Choice

import java.applet.*;

import java.awt.*;

import java.awt.event.*;

/*<applet code=demochoice.class height=200 width=400>

</applet>*/

public class demochoice extends Applet implements ItemListener {

Choice c;

public void init() {

c=new Choice();

c.addItem("Red");

c.addItem("Green");

c.addItem("Blue");

add(c);

c.addItemListener(this); }

public void itemStateChanged(ItemEvent e) {

String st=c.getSelectedItem();

if(st.equals("Red")) {

setBackground(Color.red); }

if(st.equals("Green")) {

setBackground(Color.green); }

if(st.equals("Blue")) {

setBackground(Color.blue);}}}

© www.udaysatya.blogspot.com Page 117

86 Program to Demonstrate File Dialog

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

/*<applet code=DemoMenu width=400 height=200>

</applet>*/

class TestMenu extends Frame {

String msg="";

CheckboxMenuItem workoff;

TestMenu(String title) {

super(title);

MenuBar mbar=new MenuBar();

setMenuBar(mbar);

Menu file=new Menu("File");

MenuItem i1,i2,i3,i4,i5;

file.add(i1=new MenuItem("New...."));

file.add(i2=new MenuItem("Open...."));

file.add(i3=new MenuItem("Save...."));

file.add(i4=new MenuItem("-"));

file.add(i5=new MenuItem("Quit...."));

mbar.add(file);

Menu edit=new Menu("Edit");

MenuItem i6,i7,i8,i9;

edit.add(i6=new MenuItem("Cut...."));

edit.add(i7=new MenuItem("Copy...."));

edit.add(i8=new MenuItem("Paste...."));

edit.add(i9=new MenuItem("-"));

Menu submenu1=new Menu("Text Size...");

MenuItem i10,i11;

submenu1.add(i10=new MenuItem("Large...."));

submenu1.add(i11=new MenuItem("Small...."));

edit.add(submenu1);

workoff=new CheckboxMenuItem("Work Offline");

edit.add(workoff);

mbar.add(edit);

Mymenuhandler handler=new Mymenuhandler(this);

© www.udaysatya.blogspot.com Page 118

i1.addActionListener(handler);

i2.addActionListener(handler);

i3.addActionListener(handler);

i5.addActionListener(handler);

i6.addActionListener(handler);

i7.addActionListener(handler);

i8.addActionListener(handler);

i10.addActionListener(handler);

i11.addActionListener(handler);

workoff.addItemListener(handler);

}

public void paint(Graphics g) {

g.drawString(msg,10,100);

if(workoff.getState())

g.drawString("Checked",10,200);

else

g.drawString("Unchecked",10,200);

}}

class Mymenuhandler implements ActionListener,ItemListener{

TestMenu tm;

Mymenuhandler(TestMenu tm) {

this.tm=tm;

}

public void actionPerformed(ActionEvent ae) {

String msg=" You selected";

String s=ae.getActionCommand();

if(s.equals("New...."))

msg="New";

else if(s.equals("Quit....")) {

TestDialog d=new TestDialog(tm,"Confirm Exit Dialog");

d.setVisible(true);

}

else if(s.equals("Open....")) {

FileDialog fopen=new FileDialog(tm,"Open a File",FileDialog.LOAD);

fopen.setVisible(true);

msg="You selected "+fopen.getDirectory()+" "+fopen.getFile();

}

© www.udaysatya.blogspot.com Page 119

else if(s.equals("Save....")) {

FileDialog fsave=new FileDialog(tm,"Save a File",FileDialog.SAVE);

fsave.setVisible(true);

}}

public void itemStateChanged(ItemEvent ie) {

tm.repaint();

}}

class TestDialog extends Dialog implements ActionListener {

Frame f;

String s;

Button b,b1;

TestDialog(Frame f,String title) {

super(f,title,false);

this.f=f;

this.s=title;

setLayout(new FlowLayout());

setSize(200,400);

add(new Label("Are you sure you want to exit"));

add(b=new Button("Yes"));

add(b1=new Button("No"));

b.addActionListener(this);

b1.addActionListener(this);

}

public void actionPerformed(ActionEvent e) {

if(e.getSource() == b){

dispose();

f.setVisible(false);

}

else {

dispose();

}}}

public class DemoFileDialog extends Applet {

Frame f;

public void init() {

f=new TestMenu("My Menu Frame");

f.setSize(300,500);

f.setVisible(true); }

© www.udaysatya.blogspot.com Page 120

public void start() {

f.setVisible(true);

}

public void stop() {

f.setVisible(false);

}}

© www.udaysatya.blogspot.com Page 121

87 Program to Demonstrate Labels

import java.applet.*;

import java.awt.*;

import java.awt.event.*;

/*<applet code=demolabel.class height=200 width=400>

</applet>*/

public class demolabel extends Applet

{

public void init()

{

Label nm=new Label("Name");

Label addr=new Label("Address");

//add labels to window

add(nm);

add(addr);

}

}

© www.udaysatya.blogspot.com Page 122

88 Program to Demonstrate Lists

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

/*

<applet code="ListDemo" width=400 height=200>

</applet>

*/

public class ListDemo extends Applet implements ActionListener {

List os,browser;

String msg= "";

public void init() {

os=new List(4,true);

browser=new List(4,false);

os.add("windows 98");

os.add("Windows NT");

os.add("Solaris");

os.add("MacOS");

browser.add("Netscape 1.1");

browser.add("Netscape 2.x");

browser.add("Netscape 3.x");

browser.add("Netscape 4.x");

browser.add("Internet Explorer 2.0");

browser.add("Internet Explorer 3.0");

browser.add("Internet Explorer 4.0");

browser.add("Lynx 2.4");

browser.select(1);

add(os);

add(browser);

os.addActionListener(this);

browser.addActionListener(this);

}

© www.udaysatya.blogspot.com Page 123

public void actionPerformed(ActionEvent ae) {

repaint();

}

public void paint(Graphics g) {

int idx[];

msg="Current OS:";

idx=os.getSelectedIndexes();

for(int i=0; i<idx.length; i++)

msg += os.getItem(idx[i]) + " ";

g.drawString(msg,6,120);

msg="Current Browser: ";

msg += browser.getSelectedItem();

g.drawString(msg,6,140);

}}

© www.udaysatya.blogspot.com Page 124

89 Program to Demonstrate Menu

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

/*<applet code=DemoMenu width=350 height=250>

</applet>*/

class TestMenu extends Frame {

String msg="";

CheckboxMenuItem workoff;

TestMenu(String title) {

super(title);

MenuBar mbar=new MenuBar();

setMenuBar(mbar);

Menu file=new Menu("File");

MenuItem i1,i2,i3,i4,i5;

file.add(i1=new MenuItem("New...."));

file.add(i2=new MenuItem("Open...."));

file.add(i3=new MenuItem("Close...."));

file.add(i4=new MenuItem("-"));

file.add(i5=new MenuItem("Quit...."));

mbar.add(file);

Menu edit=new Menu("Edit");

MenuItem i6,i7,i8,i9;

edit.add(i6=new MenuItem("Cut...."));

edit.add(i7=new MenuItem("Copy...."));

edit.add(i8=new MenuItem("Paste...."));

edit.add(i9=new MenuItem("-"));

Menu submenu1=new Menu("Text Size...");

MenuItem i10,i11;

submenu1.add(i10=new MenuItem("Large...."));

submenu1.add(i11=new MenuItem("Small...."));

edit.add(submenu1);

workoff=new CheckboxMenuItem("Work Offline");

edit.add(workoff);

mbar.add(edit);

Mymenuhandler handler=new Mymenuhandler(this);

i1.addActionListener(handler);

© www.udaysatya.blogspot.com Page 125

i2.addActionListener(handler);

i3.addActionListener(handler);

i5.addActionListener(handler);

i6.addActionListener(handler);

i7.addActionListener(handler);

i8.addActionListener(handler);

i10.addActionListener(handler);

i11.addActionListener(handler);

workoff.addItemListener(handler);

}

public void paint(Graphics g)

{

g.drawString(msg,10,200);

if(workoff.getState())

g.drawString("Checked",10,200);

else

g.drawString("Unchecked",10,200);

}}

class Mymenuhandler implements ActionListener,ItemListener {

TestMenu tm;

Mymenuhandler(TestMenu tm) {

this.tm=tm;

}

public void actionPerformed(ActionEvent ae) {

String msg=" You selected";

String s=ae.getActionCommand();

if(s.equals("New...."))

msg="New";

else if(s.equals("Quit....")) {

//activate a dialog box

TestDialog d=new TestDialog(tm,"Confirm Exit Dialog");

d.setVisible(true);

} }

public void itemStateChanged(ItemEvent ie) {

tm.repaint();

}}

© www.udaysatya.blogspot.com Page 126

class TestDialog extends Dialog implements ActionListener {

Frame f;

String s;

Button b,b1;

TestDialog(Frame f,String title){

super(f,title,false);

this.f=f;

this.s=title;

setLayout(new FlowLayout());

setSize(300,200);

add(new Label("Are you sure you want to exit"));

add(b=new Button("Yes"));

add(b1=new Button("No"));

b.addActionListener(this);

b1.addActionListener(this);

}

public void actionPerformed(ActionEvent e) {

if(e.getSource() == b){

dispose();

f.setVisible(false);

}

else {

dispose();

}}}

public class DemoMenu extends Applet {

Frame f;

public void init() {

f=new TestMenu("My Menu Frame");

f.setSize(300,500);

f.setVisible(true);

}

public void start() {

f.setVisible(true);

}

public void stop() {

f.setVisible(false);

}}

© www.udaysatya.blogspot.com Page 127

© www.udaysatya.blogspot.com Page 128

90 Program to Demonstrate Text Area

import java.applet.*;

import java.awt.*;

import java.awt.event.*;

public class DemoTextArea extends Applet implements ActionListener {

TextArea remark;

Button b1;

String msg="";

public void init() {

remark=new TextArea("Enter your remarks",5,50);

b1=new Button("Show");

add(remark);

add(b1);

b1.addActionListener(this);}

public void actionPerformed(ActionEvent e) {

String s=e.getActionCommand();

if(s.equals("Show")) {

msg=remark.getText();

repaint(); }}

public void paint(Graphics g){

g.drawString(msg,130,160); }}

© www.udaysatya.blogspot.com Page 129

91 Program to Make a Login Window

import java.applet.*;

import java.awt.*;

import java.awt.event.*;

public class login extends Applet implements ActionListener{

TextField un,pass;

Button b1,b2;

String msg="";

public void init(){

un=new TextField(12);

pass=new TextField(8);

pass.setEchoChar('*');

b1=new Button("Verify");

b2=new Button("Cancel");

add(un);

add(pass);

add(b1);

add(b2);

b1.addActionListener(this);

b2.addActionListener(this);

}

public void actionPerformed(ActionEvent e){

String s=e.getActionCommand();

if(s.equals("Verify")){

String user=un.getText();

String pwd=pass.getText();

if(user.equals("student") && pwd.equals("loyola")){

msg="Login Successful";

}

else

msg="You cannot login.Check your username and password";

}

else{

un.setText("");

pass.setText("");

msg="";

}

repaint();

© www.udaysatya.blogspot.com Page 130

}

public void paint(Graphics g){

g.drawString(msg,40,40);

}}//end of class

© www.udaysatya.blogspot.com Page 131

92 Program to Make a Login Focus

import java.applet.*;

import java.awt.*;

import java.awt.event.*;

/*<applet code=loginFocus.class height=200 width=400>

</applet>*/

public class loginFocus extends Applet implements ActionListener,FocusListener {

TextField un,pass;

Button b1,b2;

String msg="";

public void init() {

un=new TextField(12);

pass=new TextField(8);

pass.setEchoChar('*');

b1=new Button("Verify");

b2=new Button("Cancel");

add(un);

add(pass);

add(b1);

add(b2);

un.addFocusListener(this);

pass.addFocusListener(this);

b1.addActionListener(this);

b2.addActionListener(this);

}

public void focusGained(FocusEvent fe) {

if(fe.getSource()==un) {

un.setText("Enter UserName");

}}

public void focusLost(FocusEvent fe) {

if(fe.getSource()==pass) {

if(pass.getText().equals("")) {

msg="Enter the password to login";

repaint();

}}}

public void actionPerformed(ActionEvent e) {

String s=e.getActionCommand();

if(s.equals("Verify")){

© www.udaysatya.blogspot.com Page 132

String user=un.getText();

String pwd=pass.getText();

if(user.equals("student") && pwd.equals("loyala")) {

msg="Login Successful";

}

else

msg="You cannot login.Check your username and password";

}

else {

un.setText("");

pass.setText("");

msg="";

}

repaint();

}

public void paint(Graphics g){

g.drawString(msg,40,40);

}}//end of class

© www.udaysatya.blogspot.com Page 133

93 Program to Demonstrate Mouse Adapter

import java.awt.event.*;

import java.applet.*;

public class MouseAdapterApplet extends Applet {

public void init() {

addMouseListener(new MouseAdapter(){

public void mousePressed(MouseEvent e){

showStatus("Mouse Pressed");}});}}

© www.udaysatya.blogspot.com Page 134

94 Program to Demonstrate Mouse Events

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

/*

<Applet code=MouseEventsApplet width=400 height=100>

</Applet>

*/

public class MouseEventsApplet extends Applet implements MouseListener,MouseMotionListener {

String msg;

public void init() {

msg="";

addMouseListener(this);

addMouseMotionListener(this);

}

public void mouseClicked(MouseEvent e){

msg="mouseClicked";

repaint();

}

public void mouseEntered(MouseEvent e){

msg="mouseentered";

repaint();

}

public void mouseExited(MouseEvent e){

msg="mouseexit";

repaint();}

public void mousePressed(MouseEvent e){

msg="mousepressed";

repaint();}

public void mouseReleased(MouseEvent e){

msg="mousereleased";

repaint();}

public void mouseDragged(MouseEvent e){

msg="*";

repaint();

}

public void mouseMoved(MouseEvent e){

© www.udaysatya.blogspot.com Page 135

msg="mousemoved";

repaint();

}

public void paint(Graphics g){

g.drawString(msg,10,20);

}}

© www.udaysatya.blogspot.com Page 136

95 Program to Demonstrate the key event handlers

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

/*

<applet code="SimpleKey" width=400 height=200>

</applet>

*/

public class SimpleKey extends Applet

implements KeyListener {

String msg = "";

int X = 10, Y = 20; // output coordinates

public void init() {

addKeyListener(this);

requestFocus(); // request input focus

}

public void keyPressed(KeyEvent ke) {

showStatus("Key Down");

}

public void keyReleased(KeyEvent ke) {

showStatus("Key Up");

}

public void keyTyped(KeyEvent ke) {

msg += ke.getKeyChar();

repaint();

}

// Display keystrokes.

public void paint(Graphics g) {

g.drawString(msg, X, Y);

}

}

© www.udaysatya.blogspot.com Page 137

© www.udaysatya.blogspot.com Page 138

96 Program to Demonstrate Border Layout

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

/*

<applet code=TestBL width=400 height=200>

</applet>

*/

public class TestBL extends Applet {

public void init() {

setLayout(new BorderLayout());

add(new Scrollbar(Scrollbar.HORIZONTAL),BorderLayout.NORTH);

add(new Scrollbar(Scrollbar.HORIZONTAL),BorderLayout.SOUTH);

add(new Scrollbar(Scrollbar.VERTICAL),BorderLayout.EAST);

add(new Scrollbar(Scrollbar.VERTICAL),BorderLayout.WEST);

add (new TextArea("I am in the center"),BorderLayout.CENTER);

}}

© www.udaysatya.blogspot.com Page 139

97 Program to Demonstrate Card Layout

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

/*

<applet code=TestCL width=400 height=150>

</applet>

*/

public class TestCL extends Applet implements ActionListener {

Panel p,p1,p2;

CardLayout cl1;

Label l1;

Button b1,b2;

CheckboxGroup cbg;

Checkbox c1,c2;

public void init() {

l1=new Label("Licesence Agreement");

b1=new Button("Accept");

b2=new Button("Exit");

cl1=new CardLayout();

p=new Panel();

p.setLayout(cl1);

p1=new Panel();

p1.add(l1);

p1. add(b1);

p1.add(b2);

p2=new Panel();

cbg=new CheckboxGroup();

c1=new Checkbox("Typical",cbg,true);

c2=new Checkbox("Custom",cbg,false);

p2.add(c1);

p2.add(c2);

p.add(p1,"panel1");

p.add(p2,"panel2");

add(p);

b1.addActionListener(this);

}

public void actionPerformed(ActionEvent e) {

© www.udaysatya.blogspot.com Page 140

if(e.getSource() == b1) {

cl1.show(p,"panel2");

}}

© www.udaysatya.blogspot.com Page 141

98 Program to Test Fonts Using Mouse Events

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

public class TestFonts extends Applet{

int n=0;

Font f;

String msg;

public void init(){

f=new Font("Dialog",Font.PLAIN,12);

msg="Hello World";

setFont(f);

addMouseListener(new MyMouseAdapter(this));

}

public void paint(Graphics g){

g.drawString(msg,10,40);

}}

class MyMouseAdapter extends MouseAdapter{

TestFonts tfonts;

public MyMouseAdapter(TestFonts f){

tfonts=f;

}

public void mousePressed(MouseEvent e){

tfonts.n++;

switch(tfonts.n){

case 1:

tfonts.f=new Font("DialogInput",Font.BOLD,20);

break;

case 2:

tfonts.f=new Font("SansSerif",Font.BOLD,22);

break;

case 3:

tfonts.f=new Font("Serif",Font.BOLD,24);

break;

case 4:

tfonts.f=new Font("Monospaced",Font.BOLD,26);

break;

}

© www.udaysatya.blogspot.com Page 142

if(tfonts.n==4){

tfonts.n=-1;

tfonts.setFont(tfonts.f);

tfonts.repaint();

}} }

© www.udaysatya.blogspot.com Page 143

99 Program to Demonstrate Grid Layouts

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

/*

<applet code=TestGL width=400 height=200>

</applet>

*/

public class TestGL extends Applet{

public void init(){

setLayout(new FlowLayout(FlowLayout.CENTER));

add(new TextField("0"));

setLayout(new GridLayout(3,3));

setFont(new Font("SansSerif",Font.BOLD,16));

for(int i=0;i<3;i++){

for(int j=0;j<3;j++){

int k=i*3+j;

if(k>0)

add(new Button(""+k));

}}}}

© www.udaysatya.blogspot.com Page 144

100 Program to Demonstrate Scrollbar

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

/*

<applet code=TestScrollBar.class width=400 height=200>

</applet>

*/

public class TestScrollBar extends Applet implements AdjustmentListener

{

Scrollbar s1,s2,s3;

public void init()

{

s1=new Scrollbar(Scrollbar.HORIZONTAL,100,10,0,255);

s2=new Scrollbar(Scrollbar.VERTICAL,50,10,0,255);

s3=new Scrollbar(Scrollbar.VERTICAL,150,10,0,255);

setLayout(new BorderLayout());

add(s1,BorderLayout.SOUTH);

add(s2,BorderLayout.EAST);

add(s3,BorderLayout.WEST);

//register to recieve adjustment events

s1.addAdjustmentListener(this);

s2.addAdjustmentListener(this);

s3.addAdjustmentListener(this);

}

public void adjustmentValueChanged(AdjustmentEvent e)

{

repaint();

}

© www.udaysatya.blogspot.com Page 145

public void paint(Graphics g)

{

int r=s1.getValue();

int g1=s2.getValue();

int b=s3.getValue();

Color c=new Color(r,g1,b);

setBackground(c);

}

}

© www.udaysatya.blogspot.com Page 146

101 Program to Check JDBC Connection

import java.sql.*;

import java.util.*;

public class JDBCDemo1

{

public static void main(String[]args) throws Exception

{

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Connection c = DriverManager.getConnection("jdbc:odbc:MyDSN");

System.out.println("Connection Successfull");

c.close();

}

}

OUTPUT :

Connection Successful

© www.udaysatya.blogspot.com Page 147

102 Program to retrieve Records from Database

import java.sql.*;

public class TestRetrieveRecords {

public static void main(String[] args) throws Exception {

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Connection con=DriverManager.getConnection("jdbc:odbc:mdbTEST");

Statement st = con.createStatement();

ResultSet rs = st.executeQuery("select * from emp");

System.out.println("*** Employee's Details *** \n");

while(rs.next()) {

System.out.println("Employee Number: " + rs.getInt(1));

System.out.println("Employee Name: " + rs.getString(2));

System.out.println("Employee Salary: " + rs.getInt(3) + "\n");

}

rs.close();

st.close();

con.close();

} }

OUTPUT :

*** Employee's Details ***

Employee Number: 1

Employee Name: Uday

Employee Salary: 6000

Employee Number: 2

Employee Name: Venkat

Employee Salary: 4500

Employee Number: 3

Employee Name: Satish

Employee Salary: 7000

Employee Number: 4

Employee Name: Vijay

Employee Salary: 2000

© www.udaysatya.blogspot.com Page 148

103 Program to demonstrate Insertion into Database

import java.sql.*;

import java.io.*;

public class InsertDemo {

public static void main(String[] args) throws Exception {

int no=9;

String name="Satya";

double sal=10000;

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Connection con = DriverManager.getConnection("jdbc:odbc:mdbTEST");

Statement st=con.createStatement();

st.executeUpdate("insert into Emp values("+ no + ",'"+ name +"',"+ sal +")");

System.out.println("*** Record Inserted Successfully ***\n");

st.close();

con.close();

} }

OUTPUT :

*** Record Inserted Successfully ***

© www.udaysatya.blogspot.com Page 149

104 Program to demonstrate Update into Database

import java.util.*;

import java.sql.*;

import java.io.*;

public class JDBCUpdateDemo {

public static void main(String[]args) throws Exception{

int eno=9;

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Connection c = DriverManager.getConnection("jdbc:odbc:mdbTEST");

Statement st=c.createStatement();

int i = st.executeUpdate("update Emp set Salary = Salary +1000 where Empid="+eno);

System.out.println(i+"----record Updated");

st.close();

c.close();

}}

OUTPUT :

1----record Updated

© www.udaysatya.blogspot.com Page 150

105 Program to demonstrate Prepared Statement

import java.sql.*;

import java.io.*;

public class JDBCPrepareDemo {

public static void main(String[] args)throws Exception {

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Connection con = DriverManager.getConnection("jdbc:odbc:mdbTEST");

PreparedStatement pst = con.prepareStatement("insert into Emp(Empid,Name,Salary) values(?,?,?)");

int no=104;

pst.setInt(1,no);

String name="RUVN";

pst.setString(2,name);

int sal=14000;

pst.setInt(3,sal);

int i = pst.executeUpdate();

System.out.println(i+"--Record inserted");

pst.close();

con.close();

} }

OUTPUT :

1--Record inserted

© www.udaysatya.blogspot.com Page 151

106 Program to Demonstrate Data Entry using Applet

import java.sql.*;

import java.awt.*;

import java.awt.event.*;

public class JDBCDataEntry extends Frame implements ActionListener

{

Button ok,cancel;

TextField t1,t2,t3;

JDBCDataEntry()

{

setLayout(new FlowLayout());

ok=new Button("OK");

cancel=new Button("Cancel");

t1=new TextField(20);

t2=new TextField(20);

t3=new TextField(20);

add(new Label("Employee Number : "));

add(t1);

add(new Label("Employee Name : "));

add(t2);

add(new Label("Employee Salary : "));

add(t3);

add(ok);

add(cancel);

ok.addActionListener(this);

cancel.addActionListener(this);

setTitle("Employee's Registration Form");

setSize(350,300);

setVisible(true);

}

public void actionPerformed(ActionEvent ae)

{

if(ae.getSource()==cancel)

{

t1.setText("");

t2.setText("");

© www.udaysatya.blogspot.com Page 152

t3.setText("");

}

if(ae.getSource()==ok)

{

int no=Integer.parseInt(t1.getText());

String name=t2.getText();

int sal=Integer.parseInt(t3.getText());

try {

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Connection con = DriverManager.getConnection("jdbc:odbc:mdbTEST");

Statement st=con.createStatement();

st.executeUpdate("insert into Emp values("+ no + ",'" + name + "' , " + sal + ")");

System.out.println("*******Registraiton performed*******");

st.close();

con.close();

}

catch(Exception e)

{

System.out.println("Message: " + e);

}

}

}

public static void main(String[] args) throws Exception

{

new JDBCDataEntry();

}

}

© www.udaysatya.blogspot.com Page 153

*******Registraiton performed*******

© www.udaysatya.blogspot.com Page 154

107 Program to Demonstrate Result Set Meta Data

import java.sql.*;

public class JDBCRSMetaDataDemo

{

public static void main(String[] args) throws Exception

{

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Connection c = DriverManager.getConnection("jdbc:odbc:mdbTEST","scott","tiger");

String s="select * from emp";

Statement st=c.createStatement();

ResultSet rs=st.executeQuery(s);

ResultSetMetaData rsm=rs.getMetaData();

rs.next();

System.out.println("No of columns in the table: "+ rsm.getColumnCount());

System.out.println(rsm.getColumnName(1)+" : "+rsm.getColumnTypeName(1));

System.out.println(rsm.getColumnName(2)+" : "+rsm.getColumnTypeName(2));

System.out.println(rsm.getColumnName(3)+" : "+rsm.getColumnTypeName(3));

rs.close();

st.close();

c.close();

}

}

OUTPUT :

No of columns in the table: 3

Empid : INTEGER

Name : VARCHAR

Salary : INTEGER

© www.udaysatya.blogspot.com Page 155

108 Program to Demonstrate Transaction handling

import java.sql.*;

public class JDBCTransDemo

{

public static void main(String a[])

{

try{

Properties p=new Properties();

p.setProperty("uid","scott");

p.setProperty("password","tiger");

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Connection con = DriverManager.getConnection("jdbc:odbc:MyDSN",p);

//set the auto commit mode to false

con.setAutoCommit(false);

//create a transaction

Statement st=con.createStatement();

int i= st.executeUpdate("insert into Emp values("+ no + ",'"+ name +"',"+ sal +")");

System.out.println("first row inserted but not commited");

//create another transaction

Statement st=con.createStatement();

int j= st.executeUpdate("insert into Emp values("+ no + ",'"+ name +"',"+ sal +")");

System.out.println("second row inserted but not commited");

//commit the trans

con.commit();

System.out.println("trans commited");

st.close();

con.close();

}catch(Exception e)

{

System.out.println("Error: "+e);

}

}

}

© www.udaysatya.blogspot.com Page 156

109 Program to Demonstrate Callable Statement

import java.sql.*;

import java.util.*;

public class JDBCCallableDemo

{

public static void main(String[]args) throws Exception

{

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Connection c = DriverManager.getConnection("jdbc:odbc:MyDSN1");

String str= "{call emp_job(?,?,?)}";

//call a stored procedure

CallableStatement cs=c.prepareCall(str);

//pass the IN parameter

cs.setInt(1,7839);

//register the out parameters

cs.registerOutParameter(2,Types.VARCHAR);

cs.registerOutParameter(3,Types.VARCHAR);

//process the stored procedure

cs.execute();

//retrieve the data

ename=cs.getString(2);

ejob=cs.getString(3);

//display the data

System.out.println("Employee name: "+ename);

System.out.println("Employee Job: "+ejob);

cs.close();

c.close();

}

}

© www.udaysatya.blogspot.com Page 157

110 Program to Demonstrate Result Set Meta Data

import java.sql.*;

import java.util.*;

import java.io.*;

public class Rsmeta1

{

public static void main(String[]args) throws Exception

{

Properties p=new Properties();

p.setProperty("uid","scott");

p.setProperty("password","tiger");

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Connection c = DriverManager.getConnection("jdbc:odbc:student",p);

Statement st=c.createStatement();

ResultSet rs=st.executeQuery("select * from student");

ResultSetMetaData rsmd = rs.getMetaData();

for(int i=0; i< rsmd.getColumnCount();i++)

{

System.out.print(rsmd.getColumnLabel(i+1)+" ");

}

System.out.println();

while(rs.next())

{

System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getInt(3)+" "+rs.getInt(4));

}

st.close();

c.close();

}

}

© www.udaysatya.blogspot.com Page 158

111 Program to Demonstrate Database Meta Data

import java.sql.*;

public class JDBCDBMetaDataDemo

{

public static void main(String[]args) throws Exception

{

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Connection c = DriverManager.getConnection("jdbc:odbc:MyDSN1","scott","tiger");

//create a DB metadata object

DatabaseMetaData dbm=con.getMetaData();

//String[] tabtypes={"TABLES"};

ResultSet tabrs=dbm.getTables(null,null,null,"TABLE");

while(tabrs.next())

{

System.out.println(tabrs.getString("TABLE_NAME"));

}

con.close();

}

}

© www.udaysatya.blogspot.com Page 159

112 Program to Demonstrate Add Interface

import java.util.*;

import java.rmi.*;

public interface RMIAddInterface extends java.rmi.Remote

{

int add(int a,int b ) throws RemoteException;

}

113 Program to Demonstrate Add S erver

import java.rmi.*;

import java.rmi.server.UnicastRemoteObject;

public class RMIAddServer

{

public static void main(String[] args) throws Exception

{

if(System.getSecurityManager() == null)

{

System.setSecurityManager( new RMISecurityManager() );

}

RMIAddImpl myObject = new RMIAddImpl( "MYADDSERVER" );

System.out.println( "RMI Server ready..." );

}

}

© www.udaysatya.blogspot.com Page 160

114 Program to add Client

import java.rmi.*;

import java.rmi.registry.*;

public class RMIAddClient

{

public static void main(String[] args)

{

try

{

if(System.getSecurityManager() == null)

{

System.setSecurityManager( new RMISecurityManager() );

}

RMIAddInterface a = (RMIAddInterface)Naming.lookup("rmi://localhost/MYADDSERVER");

System.out.println( "The sum is:"+a.add(2,2));

}

catch( Exception e )

{

System.out.println( e );

}

}

}

© www.udaysatya.blogspot.com Page 161

115 implementation for the interface

import java.rmi.*;

import java.rmi.server.UnicastRemoteObject;

public class RMIAddImpl extends UnicastRemoteObject implements RMIAddInterface

{

public RMIAddImpl( String name ) throws RemoteException

{

try {

Naming.rebind( name, this );

}

catch( Exception e )

{

System.out.println( e );

}

}

public int add( int a,int b )

{

return (a+b);

}

}

116 Create a Policy to Allow Permission for Everyone

grant {

// Allow everything

permission java.security.AllPermission;

};

top related