Programs in Java
Programs in Java
Sl.No
Programs
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
class A
{
public static void main(String args[])
{
System.out.println("Welcome to my World");
}
}
----------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------
OUTPUT :
Welcome to my World
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
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 :
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
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 :
class fib
{
public static void main(String args[])
{
int i=9,f=0,s=1,temp;
System.out.println(+f);
while(i>0)
gkcomputers software training centrePage 10
{
System.out.println(+s);
temp=f+s;
f=s;
s=temp;
i--;
}
}
}
OUTPUT :
0
1
1
2
3
5
8
13
21
34
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
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
gkcomputers software training centrePage 13
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
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
class dollarcla
{
public static void main(String s[])
{
int n,d;
gkcomputers software training centrePage 15
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
1
Rupees
45
34
1530
36
1620
37
1665
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
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);
}
gkcomputers software training centrePage 17
}
}
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
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];
}
OUTPUT :
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 :
123
456
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++)
gkcomputers software training centrePage 20
OUTPUT :
2 3 4
4 6 6
7 8 10
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 : ");
gkcomputers software training centrePage 21
OUTPUT :
java Matrixcla 6 7 8 9 5 5 5 5
First Matrix :
67
89
Second Matrix :
55
55
Difference of two matrix :
12
34
class UppLow{
gkcomputers software training centrePage 22
OUTPUT :
The given matrix:
123
456
gkcomputers software training centrePage 23
789
Upper triangle of matrix:
123
56
9
Lower triangle of matrix:
1
45
789
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 :
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();
gkcomputers software training centrePage 25
}
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 :
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
class A
{
public static void main(String args[]) {
Democlass obj = new Democlass();
obj.showa();
}
}
OUTPUT :
a=34
class Box
gkcomputers software training centrePage 28
{
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 :
gkcomputers software training centrePage 29
Constructing Box
Constructing Box
volume of is 1000.0
volume of is 1000.0
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[]) {
OUTPUT :
volume of is 3000.0
volume of is 162.0
class Box
{
double width;
double height;
double depth;
Box(double width,double height,double depth)
{
this.width=width;
this.height=height;
this.depth=depth;
gkcomputers software training centrePage 31
}
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
26 Program to Demonstrate Constructor Overloading
class Box
{
gkcomputers software training centrePage 32
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;
}
}
class OverloadCons
{
public static void main(String args[]) {
gkcomputers software training centrePage 33
OUTPUT :
class Test
{
int a,b;
Test(int i,int j)
{
a=i;
gkcomputers software training centrePage 34
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 :
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];
}
}
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 :
class A
gkcomputers software training centrePage 37
{
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--];
}
}
class stack{
public static void main(String args[]){
A obj1 = new A();
gkcomputers software training centrePage 38
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 :
class Test
{
gkcomputers software training centrePage 39
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
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
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));
gkcomputers software training centrePage 42
System.out.println(Mymath.square(5));
}
}
OUTPUT :
200
100
25
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);
}
}
}
gkcomputers software training centrePage 43
class InnerClassDemo
{
public static void main(String args[])
{
Outer outer=new Outer();
outer.test();
}
}
OUTPUT :
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
class A
{
int i,j;
void showij()
{
System.out.println("i and j : " +i+ " " +j);
}
}
gkcomputers software training centrePage 45
class B extends A
{
int k;
void showk()
{
System.out.println("k : "+k);
}
void sum()
{
System.out.println("i+j+k: "+(i+j+k));
}
}
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;
gkcomputers software training centrePage 46
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
class Student
{
int rollno;
void getroll(int a)
{
rollno=a;
gkcomputers software training centrePage 47
}
void putroll()
{
System.out.println("Roll number : "+rollno);
}
}
total=marks1+marks2;
putroll();
putmarks();
System.out.println("Total = "+total);
}
}
class Multilevel
{
public static void main(String args[])
{
Result student1 = new Result();
result is created
//object of class
student1.getroll(34);
student1.getmarks(40,99);
student1.display();
}
}
OUTPUT :
Roll number : 34
Marks in subject1 = 40
Marks in subject2 = 99
Total = 139.0
class Student
{
int roll;
void getroll(int x)
{
roll=x;
}
void putroll()
{
System.out.println(roll);
}
}
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 :
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 :
class A {
int i,j;
A(int a,int b)
{
gkcomputers software training centrePage 53
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
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;
}
}
{
System.out.println("Inside Area for rectangle");
return dim1*dim2;
}
}
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;
gkcomputers software training centrePage 56
OUTPUT :
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.");
gkcomputers software training centrePage 57
}}
class AbstractDemo
{
public static void main(String args[]) {
B b=new B();
b.callme();
b.callmetoo();
}
}
OUTPUT :
class A
{
final int x =3;
int y;
A()
{
//x=4;this results in error
y=4;
gkcomputers software training centrePage 58
}
}
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
class A {
int i,j;
gkcomputers software training centrePage 59
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 :
class A
{
public static void main(String args[])
{
Democlass obj = new Democlass();
obj.showa();
}
OUTPUT :
a=34
class InterfaceDemo
{
public static void main(String args[])
{
A a = new A();
a.x=14;
gkcomputers software training centrePage 62
a.y=18;
System.out.println("Sum : " +a.add());
}
}
OUTPUT :
Sum : 34
interface figure
{
double area();
}
return dim1*dim2;
}
}
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;
gkcomputers software training centrePage 64
System.out.println(f.area());
}
}
OUTPUT :
5000.0
100.0
interface A {
void meth1();
void meth2();
}
interface B extends A {
void meth3();
}
}
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
interface stack
gkcomputers software training centrePage 66
{
void push(int item);
int pop();
}
return s[tos--];
}}
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 :
interface queue
{
void push(int item);
int pop();
}
System.out.println(" Q iS EMPTY");
return 0;
}
else
return s[++l];
}}
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 :
3
4
5
6
7
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
{
OUTPUT :
class Excep
{
static void meth1()
{
int d=0;
int a=10/d;
}
public static void main(String a[])
{
Excep.meth1();
}
}
gkcomputers software training centrePage 72
OUTPUT :
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 :
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
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
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);
gkcomputers software training centrePage 76
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 :
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;
gkcomputers software training centrePage 77
OUTPUT :
l=0
Please Enter Command line Arguments
This will be executed
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 :
gkcomputers software training centrePage 79
called compute(34)
normal exit
called compute(99)
caught Myexception[99]
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 :
gkcomputers software training centrePage 80
Inside throwOne.
Caught java.lang.IllegalAccessException: demo
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
gkcomputers software training centrePage 82
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
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);
gkcomputers software training centrePage 84
t3.start();
try{
Thread.sleep(10);
}
catch(InterruptedException e){
System.out.println("Exception "
}}}
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
+e);
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
gkcomputers software training centrePage 87
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
class Callme
{
void call(String msg)
{
System.out.print("[" +msg);
try {
Thread.sleep(1000);
}
catch(InterruptedException e)
{
System.out.println("Interrupted");
}
System.out.println("]");
}
}
t=new Thread(this);
t.start();
}
public void run()
{
synchronized(target) {
target.call(msg);
}}}
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");
}
}
gkcomputers software training centrePage 90
OUTPUT :
[Hello]
[Synchronized]
[World]
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;
gkcomputers software training centrePage 91
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);
}}
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)
gkcomputers software training centrePage 92
{
System.out.println("Interrupted");
}
}
}
OUTPUT :
[Hello]
[Synchronized]
[World]
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();
}
gkcomputers software training centrePage 93
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");
}}
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 :
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);
gkcomputers software training centrePage 96
notify();
}}
class PCFixed {
public static void main(String args[]) {
gkcomputers software training centrePage 97
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
class Threadtest
{
gkcomputers software training centrePage 99
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
gkcomputers software training centrePage 100
class DemoJoin {
public static void main(String args[]) {
NewThread ob1= new NewThread("One");
NewThread ob2= new NewThread("Two");
NewThread ob3= new NewThread("Three");
gkcomputers software training centrePage 101
OUTPUT :
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.
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.");
}
}
gkcomputers software training centrePage 104
OUTPUT :
What is your name? Uday Satya
Your name is Uday Satya
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;
gkcomputers software training centrePage 105
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);
}}
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>
*/
fontSize=0;
}
catch(NumberFormatException e) {
fontSize=-1;
}
param = getParameter("leading");
try {
if(param != null)
leading = Float.valueOf(param).floatValue();
else
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);
}
}
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);
}
}
import java.awt.*;
import java.applet.*;
/*
<applet code=house.class height=400 width=800>
</applet>
*/
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);
g.drawLine(520,190,580,160);
g.drawLine(580,160,640,190);
g.drawLine(530,340,580,300);
g.drawLine(580,300,630,340);
}
}
import java.awt.*;
import java.applet.*;
/*
<applet code="StatusWindow" width=400 height=200>
</applet>
*/
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
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);
}}
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);
}}
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"));
parameter value
//recieving
b=Integer.parseInt(getParameter("num2"));
parameter value
//recieving
}
public void paint(Graphics g) {
import java.awt.*;
import java.applet.*;
import java.net.*;
/*
<applet code="Bases" width=400 height=200>
</applet>
*/
import java.awt.*;
import java.applet.*;
/*
<applet code="DrawImageApp.class" height=200
width=400>
</applet>
*/
import java.awt.*;
import java.applet.*;
/*
<applet code="SimpleBanner" width=400 height=200>
</applet>
*/
// Display banner
for( ; ; ) {
try {
repaint();
Thread.sleep(250);
ch = msg.charAt(0);
msg = msg.substring(1, msg.length());
msg += ch;
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);
}
}
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="AdapterDemo" width=300 height=100>
</applet>
*/
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
{
msg="You pressed OK";
}
else
{
msg="You pressed CANCEL";
}
repaint();
}
public void paint(Graphics g){
g.drawString(msg,40,40);
}
}
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
g.drawString(msg,40,40);
}
}
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);}}}
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
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);
i1.addActionListener(handler);
i2.addActionListener(handler);
i3.addActionListener(handler);
i5.addActionListener(handler);
i6.addActionListener(handler);
gkcomputers software training centrePage 138
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);
}}
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();
}
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();
}}
b.addActionListener(this);
b1.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == b){
dispose();
f.setVisible(false);
}
else {
dispose();
}}}
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
{
public void init()
{
Label nm=new Label("Name");
Label addr=new Label("Address");
//add labels to window
add(nm);
add(addr);
}
}
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
gkcomputers software training centrePage 143
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code=DemoMenu width=350 height=250>
</applet>*/
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);
i2.addActionListener(handler);
i3.addActionListener(handler);
i5.addActionListener(handler);
i6.addActionListener(handler);
gkcomputers software training centrePage 147
i7.addActionListener(handler);
i8.addActionListener(handler);
i10.addActionListener(handler);
i11.addActionListener(handler);
workoff.addItemListener(handler);
}
else {
dispose();
}}}
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); }}
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();
}
public void paint(Graphics g){
g.drawString(msg,40,40);
}}//end of class
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")){
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
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){
gkcomputers software training centrePage 162
msg="mousepressed";
repaint();}
public void mouseReleased(MouseEvent e){
msg="mousereleased";
repaint();}
public void mouseDragged(MouseEvent e){
msg="*";
repaint();
}
public void mouseMoved(MouseEvent e){
msg="mousemoved";
repaint();
}
public void paint(Graphics g){
g.drawString(msg,10,20);
}}
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="SimpleKey" width=400 height=200>
</applet>
*/
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);
}}
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;
gkcomputers software training centrePage 168
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) {
if(e.getSource() == b1) {
cl1.show(p,"panel2");
gkcomputers software training centrePage 169
}}
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;
gkcomputers software training centrePage 171
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;
}
if(tfonts.n==4){
tfonts.n=-1;
tfonts.setFont(tfonts.f);
tfonts.repaint();
}} }
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++){
gkcomputers software training centrePage 173
int k=i*3+j;
if(k>0)
add(new Button(""+k));
}}}}
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code=TestScrollBar.class width=400 height=200>
</applet>
*/
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
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");
gkcomputers software training centrePage 178
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
gkcomputers software training centrePage 179
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 ***
gkcomputers software training centrePage 180
st.close();
c.close();
}}
OUTPUT :
1----record Updated
OUTPUT :
1--Record inserted
import java.sql.*;
import java.awt.*;
import java.awt.event.*;
: "));
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);
}
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();
}
gkcomputers software training centrePage 185
catch(Exception e)
{
System.out.println("Message: " + e);
}
}
}
*******Registraiton performed*******
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 :
gkcomputers software training centrePage 188
import java.sql.*;
import java.sql.*;
import java.util.*;
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();
}
}
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");
gkcomputers software training centrePage 191
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();
}
}
import java.sql.*;
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();
}}
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;
}
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..." );
}
}
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));
gkcomputers software training centrePage 194
}
catch( Exception e )
{
System.out.println( e );
}
}
}
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);
}
grant {
// Allow everything
permission java.security.AllPermission;
};