You are on page 1of 93

1.

Program to find area of circle using command line argument class area { public static void main(String args[]) { int r; double p; p=3.14; r=Integer.parseInt(args[0]); System.out.println(p*r*r); } }

Output: C:\ben>javac area.java C:\ben>java area 5 78.5

Page | 1

2.To find the Greatest of three numbers class greatest { public static void main(String args[]) { int a,b,c; a=Integer.parseInt(args[0]); b=Integer.parseInt(args[1]); c=Integer.parseInt(args[2]); if((a>b)&&(a>c)) System.out.println(a+"is the greatest"); else if((b>a)&&(b>c)) System.out.println(b+"is the greatest"); else System.out.println(c+"is the greatest"); } } output: C:\ben>javac greatest.java C:\ben>java greatest 9 1 5 9is the greatest

Page | 2

3.Program to find multiplication table. class table { public static void main (String a[]) { int num,i,p; num=Integer.parseInt(a[0]); for(i=1;i<=10;i++) { p=num*i; System.out.println(num+"*"+i+"="+p); } } }

Output: C:\ben>javac table.java C:\ben>java table 5 5*1=5 5*2=10 5*3=15 5*4=20 5*5=25 5*6=30 5*7=35 5*8=40 5*9=45 5*10=50

Page | 3

4.Program to calculate power of a number. class power { public static void main(String a[]) { int p,n,res=1; n=Integer.parseInt(a[0]); p=Integer.parseInt(a[1]); for(int i=0;i<p;i++) { res=res*n; } System.out.println(n+"to the power"+p+"="+res); } } Output: C:\ben>javac power.java C:\ben>java power 5 2 5to the power2=25

Page | 4

5.Program to find fibonacci series. class fibo { public static void main(String a[]) { int T,ft,st,nt; ft=0;st=1; int i=1; T=Integer.parseInt(a[0]); System.out.println(ft); System.out.println(st); while(i<=T-2) { nt=ft+st; System.out.println(nt); ft=st; st=nt; i++; } } }

Output: C:\ben>javac fibo.java C:\ben>java fibo 5 0 1 1 2 3

Page | 5

6.Program to find the factorial of a number. class factorial { public static void main(String a[]) { int n,f,m; f=1; n=Integer.parseInt(a[0]); for(int i=1;i<=n;i++) { f=f*n; } System.out.println("factorail of"+n+"is"+f); } } Output: C:\ben>javac factorial.java C:\ben>java factorial 5 factorail of5is3125

Page | 6

7. To find the sum of numbers stored in an array. class addarray { public static void main(String args[]) { int num[]={1,2,3,4,5,6}; int a=0; System.out.println("The sum of elements are:"); for(int i=0;i<6;i++) { System.out.println(num[i]); a=a+num[i]; } System.out.println("The sum is:"+a); } }

Output: C:\ben>javac addarray.java C:\ben>java addarray The sum of elements are: 1 2 3 4 5 6 The sum is:21

Page | 7

8.Program to check whether number is prime or not. class prime { public static void main(String a[]) { int n,r,i; n=Integer.parseInt(a[0]); i=2; while(i<n) { r=n%i; if(r==0) { System.out.println("not a prime"); break; } i++; } if(i==n) { System.out.println("prime"); } } }

Output: C:\ben>javac prime.java C:\ben>java prime 5 Prime

Page | 8

9. Program to demonstrate type casting

class Conversion { public static void main(String args[]) { byte b; int i=257; double d=323.142; System.out.println("\nConversion of int into 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+" "+i); } }

Output:
C:\ben>javac Conversion.java C:\ben>java Conversion

Conversion of int into 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 323

Page | 9

10. Program to demonstrate switch case class monthname { public static void main(String args[]) { int month=8; switch (month) { case 1: System.out.println("january"); break; case 2: System.out.println("february"); break; case 3: System.out.println("march"); break; case 4: System.out.println("april"); break; case 5: System.out.println("may"); break; case 6: System.out.println("june"); break; case 7: System.out.println("july"); break; case 8: System.out.println("august"); break; case 9: System.out.println("september"); break; case 10: System.out.println("october"); break; case 11: System.out.println("november"); break; case 12: System.out.println("december"); break; default: System.out.println("not a month!"); break; } } } OUTPUT:C:\ben>javac monthname.java C:\ben>java monthname August Page | 10

11.Program by using break and continue. class continuebreak { public static void main(String a[]) { LOOP1:for(int i=1;i<100;i++) { System.out.println(""); if(i>=10) break; for(int j=1;j<100;j++) { System.out.println("*"); if(j==i) continue LOOP1; } } System.out.println("Termination by break"); } } Output: C:\ben>javac continuebreak.java C:\ben>java continuebreak * * * * * * * * * * * * * * * * * * * * * * * * * * Page | 11

* * * * * * * * * * * * * * * * * * * Termination by break

Page | 12

12.Program to arrange array elements in ascending order. class Asort { public static void main(String a[]) { int num[]={55,40,80,65,71}; int n=num.length; int i,j,temp; for(i=0;i<n;i++) { for(j=i+1;j<n;j++) { if(num[i]>num[j]) { temp=num[i]; num[i]=num[j]; num[j]=temp; } } } System.out.println("number in ascending order"); for(i=0;i<n;i++) { System.out.println(num[i]); } } } Output: C:\ben>javac Asort.java C:\ben>java Asort number in ascending order 40 55 65 71 80

Page | 13

13.Program to find searching of an element in an array. class srch { public static void main(String a[]) { int num[]; num=new int[8]; int n=Integer.parseInt(a[0]); int i,s; for(i=1;i<=n;i++) { num[i]=Integer.parseInt(a[i]); } s=Integer.parseInt(a[i]); System.out.println("number to be searched is"+s); for(i=1;i<=n;i++) { if(num[i]==s) { System.out.println("number is present in the list at"+i+"location"); break; } } if(i==n+1) { System.out.println("not present"); } } } Output: C:\ben>javac srch.java C:\ben>java srch 5 4 3 2 1 6 4 number to be searched is4 number is present in the list at1location.

Page | 14

14.Program to find sum of two matrices. class addition { public static void main(String args[]) { int a[][]={{1,2,3},{4,5,6},{7,8,9}}; int b[][]={{5,6,7},{2,1,3},{2,5,9}}; int c[][]; c=new int[3][3]; for(int i=0;i<3;i++) { for(int j=0;j<3;j++) { c[i][j]=a[i][j]+b[i][j]; } } for(int i=0;i<3;i++) { for(int j=0;j<3;j++) { System.out.print(c[i][j]+"\t"); } System.out.println("\n"); } } } Output: C:\ben>javac addition.java C:\ben>java addition 6 8 10 6 6 9 9 13 18

Page | 15

15. Program to find transpose of a matrix class transposemat { public static void main(String args[]) { int a[][]={{1,2,3},{4,5,6},{7,8,9}}; int b[][]=new int[3][3]; System.out.println("matrix A:"); for(int i=0;i<3;i++) { for(int j=0;j<3;j++) { System.out.println(" "+a[i][j]+"\t"); } System.out.println(); } System.out.println("transpose ofA:"); for(int i=0;i<3;i++) { for(int j=0;j<3;j++) { b[i][j]=a[i][j]; System.out.println(" "+b[i][j]+"\t"); } System.out.println(); } } } output: C:\ben1>javac transposemat.java C:\ben1>java transposemat matrix A: 1 2 3 4 5 6 7 8 9 transpose ofA: 1 4 7 2 5 8 3 6 9

Page | 16

16.Program to find upper and lower elements of a matrix class ul { public static void main(String args[]) { int a[][]={{1,2,3},{4,5,6},{7,8,9}}; System.out.println("Matrix A:"); for(int i=0;i<3;i++) { for(int j=0;j<3;j++) { System.out.print(" "+a[i][j]+"\t"); } System.out.println("\n"); } System.out.println("upper triangle of A:"); for(int i=0;i<3;i++) { for(int j=0;j<3;j++) { if(i<=j) System.out.print(a[i][j]+"\t"); } System.out.println("\n"); } System.out.println("lower triangle of A:"); for(int i=0;i<3;i++) { for(int j=0;j<3;j++) { if(i>=j) System.out.print(a[i][j]+"\t"); } System.out.println("\n"); } } } Output: C:\ben>javac ul.java C:\ben>java ul Matrix A: 1 2 3 4 5 6 7 8 9 upper triangle of A: 1 2 3 5 6 9 lower triangle of A: 1 4 5 7 8 9 Page | 17

17.Program to demonstrate factorial using recursion class Factorial { int fact(int a) { int result; if(a==1) return 1; result=fact(a-1)*a; return result; } } class Recursion { public static void main(String s[]) { Factorial f=new Factorial(); System.out.println("Factoral of 5 is: "+f.fact(5)); System.out.println("Factoral of 7 is: "+f.fact(7)); } }

Output: C:\ben>javac Recursion.java C:\ben>java Recursion

Factoral of 5 is: 120 Factoral of 7 is: 5040

Page | 18

18.program to demonstrate constructor overloading class box { double width,height,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 constoverloading { public static void main(String args[]) { box mybox1=new box(10.20,20.10,15.25); box mybox2=new box(); box mycube=new box(7); double vol; vol=mybox1.volume(); System.out.println("volume of my box is:"+vol); } } Output: C:\ben>javac constoverloading.java C:\ben>java constoverloading volume of my box is:3126.5550000000003

Page | 19

19.Program to demonstrate method overloading. class add { int sum(int m,int n) { int z=m+n; return(z); } int sum(int m,int n,int o) { int p=m+n+o; return(p); } } class demo1 { public static void main(String a[]) { add o1=new add(); int res1=o1.sum(10,20); add o2=new add(); int res2=o2.sum(10,20,30); System.out.println(res1); System.out.println(res2); } } Output: C:\ben>javac demo1.java C:\ben>java demo1 30 60

Page | 20

20)Program to demonstrate to call super class method class A { int a,b; A(int x,int y) { a=x; b=y; } void show() { System.out.println("a is"+a+"b is"+b); } } class B extends A { int c; B(int p, int q,int r) { super(p,q); c=r; } void show() { super.show(); System.out.println("c is"+c); } } class ABcall { public static void main(String args[]) { B obj1=new B(1,2,3); obj1.show(); } }

Output:C:\ben>javac ABcall.java C:\ben>java ABcall a is1b is2 c is3

Page | 21

21.Program to pass object as parameter class test { int i,j; test(int a,int b) { i=a; j=b; } boolean equals(test t) { if(t.i==i&&t.j==j) return true; else return false; } } class objparameter { public static void main(String args[]) { test t1=new test(10,20); test t2=new test(1,2); test t3=new test(10,20); System.out.println(t1.equals(t2)); System.out.println(); System.out.println(t1.equals(t3)); } }

Output: C:\ben1>javac objparameter.java C:\ben1>java objparameter false true

Page | 22

22.Program to demonstrate "this" function. class Test { int x,y,z,vol; Test(int x,int y,int z) { this.x=x; this.y=y; this.z=z; } void volume() { vol=x*y*z; System.out.println("volume is"+vol); } } class demothis { public static void main(String a[]) { Test ob1=new Test(1,2,3); Test ob2=new Test(10,15,10); ob1.volume(); ob2.volume(); } } Output: C:\ben>javac demothis.java C:\ben>java demothis volume is6 volume is1500

Page | 23

23.Program to demonstrate static method class mathopr { static float mul(float x,float y) { return(x*y); } static float divide(float x,float y) { return x/y; } } class Static { public static void main(String args[]) { float a=mathopr.mul(4.0f,5.0f); float b=mathopr.divide(a,2.0f); System.out.println("product:"+a); System.out.println("quotient:"+b); } } Output: C:\ben1>javac Static.java C:\ben1>java Static product:20.0 quotient:10.0

Page | 24

24.Program to implement stack operation class stack { int stk[]=new int[10]; int tos; stack() { tos=-1; } void push(int item) { if(tos==9) System.out.println("overflow"); else stk[++tos]=item; } int pop() { if(tos<0) { System.out.println("empty"); return(0); } else return stk[tos--]; } void display() { int i; System.out.println("here is my stack ==>"); for(i=9;i>=0;i--) { System.out.println(stk[i]); } } } class sdemo { public static void main(String args[]) { int i; stack s1=new stack(); for(i=0;i<10;i++) { s1.push(i); } s1.display(); for(i=0;i<10;i++) { int out1=s1.pop(); System.out.println(out1+"is removed"); } } } Page | 25

Output: C:\ben>javac sdemo.java C:\ben>java sdemo here is my stack ==> 9 8 7 6 5 4 3 2 1 0 9is removed 8is removed 7is removed 6is removed 5is removed 4is removed 3is removed 2is removed 1is removed 0is removed

Page | 26

25.Program to demontrate single inheritance class one { int i,j; void showij() { System.out.println("i is:"+i+" and "+" j is:"+j); } } class two extends one { int k; void show() { System.out.println("k is:"+k); } void sum() { System.out.println("sum is:"+(i+j+k)); } } class singleinheritance { public static void main(String args[]) { two t=new two(); t.i=10; t.j=20; t.k=30; t.showij(); t.show(); t.sum(); } } Output: C:\ben>javac singleinheritance.java C:\ben>java singleinheritance i is:10 and j is:20 k is:30 sum is:60

Page | 27

26.Program to demonstrate 'super' to call 'super class constructor'. class box { private double width; private double height; private double depth; box(double w,double h,double d) { width=w; height=h; depth=d; } double volume() { return width*height*depth; } } class box2 extends box { double weight; box2(double w,double h,double d,double m) { super(w,h,d); weight=m; } } class superclassconst { public static void main(String args[]) { box2 ob1=new box2(10,20,15,34.3); double vol=ob1.volume(); System.out.println("volume of box is:"+vol); System.out.println("weight of the box is:"+ob1.weight); } } Output: C:\ben>javac superclassconst.java C:\ben>java superclassconst volume of box is:3000.0 weight of the box is:34.3

Page | 28

27.Program to demonstrate use of super to overcome name hiding. class A { int i; } class B extends A { int i; B(int a,int b) { super.i=a; i=b; } void show() { System.out.println("i in superclass:"+super.i); System.out.println("i in subclass:"+i); } } class namehide { public static void main(String args[]) { B ob1=new B(10,20); ob1.show(); } } Output: C:\ben>javac namehide.java C:\ben>java namehide i in superclass:10 i in subclass:20

Page | 29

28. Program to demonstrate multilevel inheritance class student { int roll_num; void get_roll(int a) { roll_num=a; } void display_num() { System.out.println("ROLLNO"+roll_num); } } class test extends student { int m1,m2; void get_marks(int x,int y) { m1=x; m2=y; } void display_marks() { System.out.println("M1 is"+m1+"\n"+"M2 is"+m2); } } class result extends test { float total; void display() { total=m1+m2; display_num(); display_marks(); System.out.println("Toatl is:"+total); } } class multilevel { public static void main(String args[]) { result ob1=new result(); ob1.get_roll(05); ob1.get_marks(10,74); ob1.display(); } } Output: C:\ben>javac sdemo.java C:\ben>java sdemo here is my stack ==> 9 8 Page | 30

7 6 5 4 3 2 1 0 9is removed 8is removed 7is removed 6is removed 5is removed 4is removed 3is removed 2is removed 1is removed 0is removed

Page | 31

29.Program to demonstrate runtime polymorphism class figure { double dim1,dim2; figure(double a,double b) { dim1=a; dim2=b; } double area() { System.out.println("area is undefined"); return 0; } } class rectangle extends figure { rectangle (double a,double b) { super(a,b); } double area() { System.out.println("area of rectangle"); return dim1*dim2; } } class triangle extends figure { triangle(double a,double b) { super(a,b); } double area() { System.out.println("area of triangle"); return(dim1*dim2)/2; } } class runtimepoly { 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 fr; fr=f; System.out.println(":"+fr.area()); fr=r; System.out.println(":"+fr.area()); fr=t; System.out.println(":"+fr.area()); } } Page | 32

Output: C:\ben1>javac runtimepoly.java C:\ben1>java runtimepoly area is undefined :0.0 area of rectangle :45.0 area of triangle :40.0

Page | 33

30. Program with the use abstract class and abstract method 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 absdemo { public static void main(String args[]) { B b=new B(); b.callme(); b.callmetoo(); } } Output: C:\ben>javac absdemo.java C:\ben>java absdemo B's implementation of callme this is a concrete method

Page | 34

31.program to demonstrate method overriding. class super1 { int x; super1(int x) { this.x=x; } void display() { System.out.println("super1x="+x); } } class sub extends super1 { int y; sub(int x,int y) { super(x); this.y=y; } void display() { System.out.println("super1x="+x); System.out.println("sub y="+y); } } class overidetest { public static void main(String a[]) { sub s1=new sub(100,200); s1.display(); } } Output:C:\ben>javac overidetest.java C:\ben>java overidetest super1x=100 sub y=200

Page | 35

32.Program to demonstrate final keyword class A { final void meth() { System.out.println("This is A method declared as final"); } } class B extends A { void meth() { System.out.println("illegal"); } } class finaldemo { public static void main() { B b=new B(); b.meth(); } } Output:C:\ben>javac finaldemo.java finaldemo.java:11: meth() in B cannot override meth() in A; overridden method is final

Page | 36

33. TO demonstrate Inner class class outer { int out=100; void test() { inner in=new inner(); in.display(); } class inner { void display() { System.out.println("disply out="+out); } } } class innerdemo { public static void main(String a[]) { outer ob=new outer(); ob.test(); } } Output:C:\ben>javac innerdemo.java C:\ben>java innerdemo disply out=100

Page | 37

34.Program on implementation of interface interface Area { final static float pi=3.14f; float compute(float x,float y); } class rectangle implements Area { public float compute(float x,float y) { return(x*y); } } class circle implements Area { public float compute(float x,float y) { return(pi*x*x); } } class interfacetest { public static void main(String args[]) { rectangle rect=new rectangle(); circle cir=new circle(); Area A; A=rect; System.out.println("Area of rectangle="+A.compute(10,20)); A=cir; System.out.println("Area of circle ="+A.compute(10,0)); } } OUTPUT:C:\ben>javac interfacetest.java C:\ben>java interfacetest Area of rectangle=200.0 Area of circle =314.0

Page | 38

35. program to define and implement interfaces. Interface instack { void push(int item); int pop(); } Class stack implements instack { Private int stck(); Private int tos; Stack(int size); tos=-1; } Public void push(int item) { If(tos==stck.length-1) System.out.println(stack is full); Else Stck[++tos]=item; } Public int pop { If(tos<0) { System.out.println(stack underflow); Return o; } Else Return stck[tos--]; } Void display() { For(int i=0;i<stack.length;i++) System.out.println(stack[i]); } Class defimp { Public static void main(String args[]) { Stack s1=new stack(8);for(int i=0;i<8;i++) S1.push(i); System.out.println(stack is:); S1.display(); System.out.pritnln(stack is:); For(int i=0;i<8;i++) System.out.println(s1.pop()); } }

Page | 39

Output: C:\ben>javac defimp.java C:\ben>java defimp Stack is: 0 1 2 3 4 5 6 7 Stack is: 7 6 5 4 3 2 1 0

Page | 40

36.Program to demonstrate extending of interface interface A { void meth1(); void meth2(); } interface B extends A { void meth3(); } class myclass implements B { public void meth1() { System.out.println("implements meth1"); } public void meth2() { System.out.println("implementsmeth2"); } public void meth3() { System.out.println(); } } class extendinterface { public static void main(String args[]) { myclass ob=new myclass(); ob.meth1(); ob.meth2(); ob.meth3(); } }

Output:C:\ben>javac extendinterface.java C:\ben>java extendinterface implements meth1 implementsmeth2

Page | 41

37 Program on multiple inheritance using interface pack class student { int rollnum; void getnum(int n) { rollnum=n; } void putnum() { System.out.println("roll no:"+rollnum); } } class test extends student { float part1,part2; void getmarks(float m1,float m2) { part1=m1; part2=m2; } void putmarks() { System.out.println("marks obtained:"); System.out.println("part1="+part1); System.out.println("part2="+part2); } } interface sports { float sportswt=6.0F; void putwt(); } class result extends test implements sports { float total; public void putwt() { System.out.println("sportswt="+sportswt); } void display() { total=part1+part2+sportswt; putnum(); putmarks(); putwt(); System.out.println("Total score="+total); } } Output:C:\ben>javac hybrid.java C:\ben>java hybrid roll no:1234 marks obtained: part1=27.5 part2=33.0 sportswt=6.0 Total score=66. Page | 42

38.Program for creating simple package package package1; public class classA { public void displayA() { System.out.println("classA"); } } OUTPUT:C:\ben>cd package1 C:\ben\package1>javac classA.java

package package2; public class classB { protected int m=10; public void displayB() { System.out.println("classB"); System.out.println("m="+m); } }

OUTPUT:C:\ben>cd package2 C:\ben\package2>javac classB.java

Page | 43

39.Program to create package & import in a program import package1.classA; import package2.*; class packtest { public static void main(String args[]) { classA a=new classA(); classB b=new classB(); a.displayA(); b.displayB(); } } OUTPUT:C:\ben>javac packtest.java C:\ben>java packtest classA classB m=10

Page | 44

40. program on exception handling using try-catch method. class error3 { public static void main(String args[]) { int a=3; int b=5; int c=5; int x,y; try { x=a/(b-c); } catch(ArithmeticException e) { System.out.println("Division by zero"); } y=a/(b+c); System.out.println("y="+y); } } OUTPUT:C:\ben>javac error3.java C:\ben>java error3 Division by zero y=0

Page | 45

41.Program to demonstarate multiple catch blocks class multicatch { public static void main(String args[]) { int a[]={5,10}; int b=5; try { int x=a[2]/b-a[1]; } catch(ArithmeticException e) { System.out.println("divide by 0"); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Array Implementation Error"); } catch(ArrayStoreException e) { System.out.println("wrong DataType"); } int y=a[1]/a[0]; System.out.println("Resultsis:"+y); } } OUTPUT:C:\ben>javac multicatch.java C:\ben>java multicatch Array Implementation Error Resultsis:2

Page | 46

42.To demonstarte finally block class demofinally { public static void main(String args[]) { int a[]={5,10}; int b=5; int c[]={0,2}; try { int x=a[2]/b-a[1]; int z=c[1]/c[0]; } catch(ArithmeticException e) { System.out.println("division by zero"); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("array index error"); } catch(ArrayStoreException e) { System.out.println("wrong data type"); } finally { int y=a[1]/a[0]; System.out.println("y=" +y); } } } OUTPUT:C:\ben>javac demofinally.java C:\ben>java demofinally array index error y=2

Page | 47

43.Program to demonstrate nested try class nestedtry { public static void main(String s[]) { try { int a=s.length; System.out.println("A="+a); int b=20/a; try { if(a==1) a=a/(a-a); if(a==2) { int c[]={1,2}; c[4]=92; } } catch(ArrayIndexOutOfBoundsException e) { System.out.println("array out of order"+e); } } catch(ArithmeticException e) { System.out.println("divided by zero:"+e); } } } OUTPUT:C:\ben>javac nestedtry.java C:\ben>java nestedtry A=0 divided by zero:java.lang.ArithmeticException: / by zero

Page | 48

44.program to demonstrate user defined exception import java.lang.Exception; class myexception extends Exception { myexception(String message) { super(message); } } class userdefexp { public static void main(String args[]) { int x=5,y=1000; try { float z=(float)x/(float)y; if((z<0.01)) { throw new myexception("Too small number"); } } catch(myexception e) { System.out.println("Caught MyException"); System.out.println(e.getMessage()); } Finally { System.out.println("finally is always executed"); } } } OUTPUT:C:\ben>javac userdefexp.java C:\ben>java userdefexp Caught MyException Too small number finally is always executed

Page | 49

45.program to demonstrate multithread. class newthread implements Runnable { String name; Thread t; newthread(String threadname) { name=threadname; t=new Thread(this,name); System.out.println("new thread:"+t); t.start(); } public void run() { try { for(int i=5;i>0;i--) { System.out.println(name+":"+i); Thread.sleep(1000); } } catch(InterruptedException e) { System.out.println(name+"exiting"); } } } class multithread { public static void main(String args[]) { new newthread("one"); new newthread("Two"); new newthread("Three"); try { Thread.sleep(1000); } catch(InterruptedException e) { System.out.println("main thread interrupted"); } System.out.println("main thread exiting"); } }

OUTPUT:C:\ben>javac multithread.java C:\ben>java multithread new thread:Thread[one,5,main] new thread:Thread[Two,5,main] one:5 Two:5 Page | 50

new thread:Thread[Three,5,main] Three:5 one:4 Two:4 main thread exiting Three:4 one:3 Two:3 Three:3 one:2 Two:2 Three:2 one:1 Three:1 Two:1

Page | 51

46.Program to demonstrate Synchronization method class callme { Synchronized void call(String msg) { System.out.println("["+msg); Try { Thread.sleep(1000); } catch(InterruptedException e); } 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); } } class Synchro { 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(); ob2.t.join(); } cath(InterruptedExecution e) { System.out.println("interrupted"); } } } Output: C:\ben>javac synchro.java C:\ben>java synchro [hello][synchronized][world] Page | 52

47.program to demonstrate use of join() to wait for threads to finish. class nethread implements runnable { String name; Thread t; newthread(String Theadname) { name=threadname; t=new Thread(this,name); t.start(); } public void run() { try { for(inti=5;i>0;i--) { System.out.println(name+":"+i); } } catch(Exception e) { System.out.println(name+"interupted"); } 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()); try { System.out.println("waiting for threads tofinish"); ob1.t.join(); ob2.t.join(); ob3.t.join(); } catch(InterruptedException e) { System.out.println("main thread interrupted exception"); } 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()); System.out.println("main thread exception"); } }

Page | 53

OUTPUT: C:\ben>javac demojoin.java C:\ben>java demojoin Thread one is alive:true Thread two is alive:true Waiting for threads to finish Two: 5 Two:4 Two:3 Two:2 Two:1 two exiting! One:5 One:4 One:3 One:2 One:1 One exiting! Three:5 Three:4 Three:3 Three:2 Three:1 Three exiting! Thread one is alive:false Thread two is alive:false Thread three is alive: false Main thread exiting

Page | 54

48.program to demonstrate wait() and notify() class Q { int n; boolean valueset=false; synchronized int get() { if(!valueset) try { wait(); } catch(InterruptedExeception e) { System.out.println("Interrupted exception caught"); } System.out.println("Got:"+n); valueset=false; notify(); return(n); } synchrinuzed void put(int n) { if(valuesset) try { wait(); } catch(InterruptedEceprtion e) { System.out.println("Interrupted"); } this.n=n; vlaueset=true; System.out.println("put:"+n); notify(); }} class producer implements Runnable { Q q; producer(Q q) { this.q=q; Thread t=new Thread(this,"problem"); t.start(); } public void run() { inti=0; while(true) { i=i+1; q.put(i); } Page | 55

} } class consumer implements Runnable { Q q; consumer(Q q) { this.q=q; Thread t=new Thread(this,"consumer"); t.start(); } public void run() { while(true) { q.get(); } }} class pc { public static void main(String args[]) { Q q=new Q(); producer ob1=newproducer(q); consumer ob2=new consumer(q); System.out.println("press CTRL-Z to stop"); } } OUTPUT: C:\ben>javac pc.java C:\ben>java pc put:746 got:746 put:747 got:747 put:748 got:748 put:749 got:749 put:750 got:750

Page | 56

49. Program on life cycle of applet import java.applet.*; import java.awt.*; /*<applet code="lifecycle.class" width=200 height=200></applet>*/ public class lifecycle extends Applet { String msg; public void init() { msg="inside init()--->"; } public void start() { msg+="inside start()--->"; } public void paint(Graphics g) { msg+="inside print()---//" ; g.drawString(msg,10,30); } }

OUTPUT: C:\Users\Ben\Downloads>javac lifecycle.java C:\Users\Ben\Downloads>appletviewer lifecycle.java

Page | 57

50.program to implement welcome applet import java.applet.*; import java.awt.*; /*<applet code="welcome.class" width=200 height=200></applet>*/ public class welcome extends Applet { public void paint(Graphics g) { g.drawString("welcome to my applet",100,100); } } OUTPUT: C:\ben>javac welcome.java C:\ben>appletviewer.java

Page | 58

51.program to draw an image in an applet import java.awt.*; import java.applet.*; /*<applet code="demoimage.class" width=400 height=200></applet>*/ public class demoimage extends Applet { Image i; public void init() { i=getImage(getDocumentBase(),"Water lilies.jpg"); } public void paint(Graphics g) { g.drawImage(i,0,0,this); } }

Output: C:\ben>javac demoimage.java C:\ben>appletviewer demoimage.java

Page | 59

52. Program to demonstrate arithmetic operation in applet

import java.awt.*; import java.applet.*; import java.io.*; public class SumOfTwo extends Applet { TextField T1,T2; public void init() { T1 = new TextField(10); T2 = new TextField(10); add(T1); add(T2); T1.setText("0"); T2.setText("0"); } public void paint(Graphics g) { int a, b, result; String str; g.drawString("Enter Number in TextField to Find addition of 2 No ",10,50); g.setColor(Color.red); str=T1.getText(); a=Integer.parseInt(str); str=T2.getText(); b=Integer.parseInt(str); result=a+b; g.drawString("After Addition the Result is : "+result,10,80); showStatus("Addition of 2 Numbers"); } public boolean action(Event e, Object o){ repaint(); return true; } } <!--html--> <applet code="SumOfTwo.class" height=150 width =350> </applet>

Page | 60

Output: C:\ben>javac SumOfTwo.java C:\ben>appletviewer SumOfTwo.html

Page | 61

53. Program to demonstrate simple moving banner applet

import java.awt.*; import java.applet.*; import java.io.*; public class SimpleBanner extends Applet implements Runnable { String msg=" --A moving banner-- "; Thread t=null; boolean stopFlag; public void init() { setBackground(Color.yellow); setForeground(Color.red); } public void start() { t=new Thread(this); stopFlag=false; t.start(); } public void run() { char ch; for(;;) { try { repaint(); Thread.sleep(250); ch=msg.charAt(0); msg=msg.substring(1,msg.length()); msg=msg+ch; if(stopFlag) break; } catch(InterruptedException e) { } } } public void stop() { stopFlag=true; t=null; } public void paint(Graphics g) {
Page | 62

g.drawString(msg,50,50); } } <!--html--> <applet code=SimpleBanner.class width=400 height=400> </applet>

Output:
C:\ben>javac SimpleBanner.java C:\ben>appletviewer SimpleBanner.java

Page | 63

54. Program to demonstrate MouseEvent.

import java.awt.*; import java.awt.event.*; import java.applet.*; import java.io.*; public class MouseEventsApplet extends Applet implements MouseListener,MouseMotionListener { String msg; public void init() { msg=""; addMouseListener(this); addMouseMotionListener(this); } public void mouseClicked(MouseEvent e) { msg="mouse Clicked"; repaint(); } public void mouseEntered(MouseEvent e) { msg="mouse Entered"; repaint(); } public void mouseExited(MouseEvent e) { msg="mouse Exit"; repaint(); } public void mousePressed(MouseEvent e) { msg="mouse Pressed"; repaint(); } public void mouseReleased(MouseEvent e) { msg="mouse Released"; repaint(); } public void mouseDragged(MouseEvent e) { msg="*"; repaint(); } public void mouseMoved(MouseEvent e)
Page | 64

{ msg="mouse Moved"; repaint(); } public void paint(Graphics g) { g.drawString(msg,10,20); } } <!--html--> <Applet code=MouseEventsApplet width=500 height=100> </Applet> Output: C:\ben>javac MouseEventsApplet.java C:\ben>appletviewer MouseEventsApplet.java

Page | 65

55. Program to draw lines and rectangles using applet window

import java.awt.*; import java.applet.*; import java.io.*; public class Rectangles extends Applet { public void paint(Graphics g) { g.drawRect(10, 10, 60, 50); g.fillRect(100, 10, 60, 50); g.drawRoundRect(190, 10, 60, 50, 15, 15); g.fillRoundRect(70, 90, 140, 100, 30, 40); } } <!--html--> <applet code="Rectangles.class" width=100 height=200> </applet> Output: C:\ben>javac Rectangles.java C:\ben>appletviewer Rectangles.html

Page | 66

56. Program to demonstrate control label class import java.applet.*; import java.awt.*; import java.awt.event.*; /* <applet code=demolabel.class height=100 width=200> </applet> */ public class demolabel extends Applet { public void init() { Label one = new Label("one"); Label two = new Label("two"); Label three = new Label("three"); add(one); add(two); add(three); } }

Output: C:\ben>javac demolabel.java C:\ben>appletviewer demolabel.java

Page | 67

57. Program to demonstrate button class

import import import import

java.applet.*; java.awt.*; java.awt.event.*; java.io.*;

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); } } <!--html--> <applet code=DemoButton.class height=200 width=200> </applet> */

Page | 68

Output: C:\ben>javac DemoButton.java C:\ben>appletviewer DemoButton.java

Page | 69

58. Program to demonstrate Text Area.

import java.applet.*; import java.awt.*; import java.awt.event.*; import java.io.*; public class DemoTextArea extends Applet implements ActionListener { TextArea remark; Button b1; String msg=""; public void init() { remark=new TextArea("Enter your remarks",5,30); 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,40,150); } } <!--html--> <applet code=DemoTextArea.class height=200 width=400> </applet>

Page | 70

Output: C:\ben>javac DemoTextArea.java C:\ben>appletviewer DemoTextArea.java

Page | 71

59. Program to demonstrate checkbox class import java.applet.*; import java.awt.*; import java.awt.event.*; /* <applet code="CheckBoxDemo.class" height=100 width=400> </applet> */ public class CheckBoxDemo extends Applet implements ItemListener { String msg=""; Checkbox c1,c2,c3; public void init() { c1=new Checkbox("Java",null,true); c2=new Checkbox("C"); c3=new Checkbox("C++"); add(c1); add(c2); add(c3); c1.addItemListener(this); c2.addItemListener(this); c3.addItemListener(this); } public void itemStateChanged(ItemEvent ie) { repaint(); } public void paint(Graphics g) { msg="current state:"; g.drawString(msg,6,80); msg="Java:"+c1.getState(); g.drawString(msg,6,100); msg="C:"+c2.getState(); g.drawString(msg,6,120); msg="C++:"+c3.getState(); g.drawString(msg,6,140); } }

Page | 72

Output:

C:\ben>javac CheckBoxDemo.java C:\ben>appletviewer CheckBoxDemo.java

Page | 73

60.Program to demonstrate checkbox group(Radio) class import java.awt.*; import java.awt.event.*; class Qualification extends Applet { CheckboxGroup cg = new CheckboxGroup(); Checkbox radUnder = new Checkbox("Undergraduate", cg, false); Checkbox radGra = new Checkbox("Graduate", cg, false); Checkbox radPost = new Checkbox("Post Graduate", cg, false); Checkbox radDoc = new Checkbox("Doctorate", cg, false); Label lblQts = new Label("What's your Qualification?"); public Qualification(String str) { super(str); setLayout(new GridLayout(6,1)); add(lblQts); add(radUnder); add(radGra); add(radPost); add(radDoc); addWindowListener (new WindowAdapter() { public void windowClosing(WindowEvent we) { setVisible(false); System.exit(0); } }); } public static void main(String args[]) Page | 74

{ Qualification ObjQualification = new Qualification("Literacy!!"); ObjQualification.pack(); ObjQualification.show(); } } Output:

C:\ben>javac Qulification.java C:\ben>appletviewer Qulification.java

Page | 75

61. Program to demonstrate scroll bar class. import java.awt.*; import java.awt.event.*; import java.util.*; import java.applet.*; import java.io.*; /*<applet code=TestScrollBar.class width=200 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); s1.addAdjustmentListener(this); s2.addAdjustmentListener(this); s3.addAdjustmentListener(this); } public void adjustmentValueChanged(AdjustmentEvent e) { repaint(); } 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); } } Output: C:\ben >javac TestScrollBar.java C:\ben >appletviewer TestScrollBar.java

Page | 76

62.Program to Demonstrate choice class import java.awt.*; import java.awt.event.*; import java.util.*; import java.applet.*; import java.io.*; /*<applet code=demochoice.class height=100 width=200></applet>*/ public class demochoice extends Applet implements ItemListener { Choice os,browser; Label l1,l2; String msg=" "; public void init() { os=new Choice(); browser=new Choice(); l1=new Label("choose os"); os.add("win 98"); os.add("win xp"); os.add("win 7"); l2=new Label("choose browser"); browser.add("netscape"); browser.add("chrome"); browser.add("firefox"); browser.select(0); os.select(1); add(l1); add(os); add(l2); add(browser); os.addItemListener(this); browser.addItemListener(this); } public void itemStateChanged(ItemEvent ie) { repaint(); } public void paint(Graphics g) { msg="current os:"; msg+=os.getSelectedItem(); g.drawString(msg,6,120); msg="current browser:"; msg+=browser.getSelectedItem(); g.drawString(msg,6,140); } }

Output: C:\Users\Ben\Downloads>javac demochoice.java Page | 77

C:\Users\Ben\Downloads>appletviewer demochoice.java

Page | 78

63. Program to demonstrate colour class import java.awt.*; import java.applet.*; /*<applet code=colordemo.class height=200 width=400></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(130,100,100,40); g.setColor(c2); g.fillRect(60,120,160,40); g.setColor(c3); g.fillOval(20,30,70,70); g.setColor(Color.blue); g.fillRect(120,50,180,90); } } Output: C:\Ben >javac colordemo.java C:\Ben>appletviewer colordemo.java

Page | 79

64.Program to demonstrate list class import java.awt.*; import java.awt.event.*; import java.applet.*; /*<applet code=demolist.class height=100 width=200></applet>*/ public class demolist extends Applet implements ItemListener { List l; public void init() { l=new List(); l.add("red"); l.add("green"); l.add("orange"); add(l); l.addItemListener(this); } public void itemStateChanged(ItemEvent ie) { String st=l.getSelectedItem(); if(st.equals("red")) { setBackground(Color.red); } if(st.equals("green")) { setBackground(Color.green); } if(st.equals("orange")) { setBackground(Color.orange); } }} Output: C:\Users\Ben\Downloads>javac demolist.java C:\Users\Ben\Downloads>appletviewer demolist.java

Page | 80

65.Program to demonstrate font class import java.awt.*; import java.applet.*; /*<applet code=demofont.class height=300 width=400></applet>*/ public class demofont extends Applet { Font f; String msg; public void init() { f=new Font("dialog",Font.PLAIN,12); msg="BEN-2013.14"; setFont(f); } public void paint(Graphics g) { g.drawString(msg,10,40); f=new Font("Times New Roman",Font.BOLD,10); setFont(f); g.drawString(msg,10,40); } } Output: C:\Users\Ben\Downloads>javac demofont.java C:\Users\Ben\Downloads>appletviewer demofont.java

Page | 81

66.Program to demonstrate message in status bar import java.awt.*; import java.applet.*; /*<applet code=msgstatus.class height=200 width=400></applet>*/ public class msgstatus extends Applet { public void init() { setBackground(Color.yellow); } public void paint(Graphics g) { g.drawString("this is in the applet window",10,20); showStatus("this is in the status bar of an applet"); } } Output: C:\Users\Ben\Downloads>javac msgstatus.java C:\Users\Ben\Downloads>appletviewer msgstatus.java

Page | 82

67.Program to make login window import java.awt.*; import java.applet.*; import java.awt.event.*; /*<applet code=lon.class height=200 width=200></applet>*/ public class lon extends Applet implements ActionListener { TextField un,pass,res; Button b1,b2; Label l1,l2,l3; String msg=" "; public void init() { l1 = new Label("enter username"); l2 = new Label("enter enter password"); l3 = new Label("enter status"); un = new TextField(12); pass=new TextField(8); res=new TextField(); pass.setEchoChar('*'); b1=new Button("verify"); b2=new Button("cancel"); setLayout(new GridLayout(4,2)); add(l1); add(un); add(l2); add(pass); add(l3); add(res); add(b1); add(b2); b1.addActionListener(this); b2.addActionListener(this); } public void actionPerformed(ActionEvent ae) { String s=ae.getActionCommand(); if(s.equals("verify")); { String user=un.getText(); String password=pass.getText(); if(user.equals("student") && password.equals("loyola")) res.setText("successful"); else res.setText("your username or password is incorrect"); un.setText(" ");

pass.setText(" "); res.setText(" "); msg=" "; Page | 83

} repaint(); } public void paint(Graphics g) { g.drawString(msg,40,40); } }

Output: C:\Users\Ben\Downloads>javac lon.java C:\Users\Ben\Downloads>appletviewer lon.java

Page | 84

68.Program to demonstrate border layout. import java.awt.*; import java.awt.event.*; import java.applet.*; /* <applet code=TestBorder.class width=300 height=200> </applet> */ public class TestBorder 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("BEN JAVA RECORD"),BorderLayout.WEST); } }

Output:
C:\Users\Ben\Downloads>javac TestBorder.java C:\Users\Ben\Downloads>appletviewer TestBorder.java

Page | 85

69. Program to demonstrate grid layout. import java.awt.*; import java.applet.*; /* <applet code=Grid.class width=300 height=200> </applet> */ public class Grid extends Applet { public void init() { final int n=3; setLayout(new GridLayout(n,n)); setFont(new Font("Calibri",Font.BOLD,24)); for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { int k=i*n+j; if(k>0) add(new Button("Tile"+k)); } } } } Output: C:\Users\Ben\Downloads>javac Grid.java C:\Users\Ben\Downloads>appletviewer Grid.java

Page | 86

Data base created in MS Access. Table name is customer. Main DATABASE

Page | 87

70. program to retrieve record from Database import java.sql.*; class SelectDB { public static void main(String args[]) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con=DriverManager.getConnection("jdbc:odbc:mycustomer","",""); Statement st=con.createStatement(); ResultSet rs=st.executeQuery("select * from customer"); System.out.println("ID FN LN"); System.out.println("---------------------"); while(rs.next()) { int id=rs.getInt(1); String fn=rs.getString(2); String ln=rs.getString(3); String row=id+" "+fn+" "+ln; System.out.println(row); } }catch(Exception ex) { System.out.println(ex.getMessage()); }}}

OUTPUT

Page | 88

71.Program to INSERT RECORD in DataBase import java.sql.*; class InsertDB { public static void main(String args[]) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con=DriverManager.getConnection("jdbc:odbc:mycustomer","",""); Statement st=con.createStatement(); String id=args[0]; String fn=args[1]; String ln=args[2]; String query="insert into customer(id,firstname,lastname) values(' "+id+" ',' "+fn+" ',' "+ln+" ')"; int k=st.executeUpdate(query); System.out.println(k+"row inserted"); ResultSet rs=st.executeQuery("select * from customer"); System.out.println("ID FN LN"); System.out.println("---------------------"); while(rs.next()) { id=rs.getString(1); fn=rs.getString(2); ln=rs.getString(3); String row=id+" "+fn+" "+ln; System.out.println(row); } }catch(Exception ex) { System.out.println(ex.getMessage()); } } }

Page | 89

OUTPUT

Page | 90

72.Program to DELETE RECORD from DataBase import java.sql.*; class DeleteDB { public static void main(String args[]) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con=DriverManager.getConnection("jdbc:odbc:mycustomer","",""); Statement st=con.createStatement(); String id=args[0]; String query="delete from customer where id='"+id+"' "; int k=st.executeUpdate(query); System.out.println(k+"row deleted"); ResultSet rs=st.executeQuery("select * from customer"); System.out.println("ID FN LN"); System.out.println("---------------------"); while(rs.next()) { id=rs.getString(1); String fn=rs.getString(2); String ln=rs.getString(3); String row=id+" "+fn+" "+ln; System.out.println(row); } }catch(Exception ex) { System.out.println(ex.getMessage()); } } }

Page | 91

OUTPUT

Page | 92

73. Program to UPDATE RECORD in DataBase ** In the Database firstname of id 6 Blessy is Updated to Jessy. ** import java.sql.*; class UpdateDB { public static void main(String args[]) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con=DriverManager.getConnection("jdbc:odbc:mycustomer","",""); Statement st=con.createStatement(); String query="update customer set firstname='Jessy'where id='6'"; st.executeUpdate(query); ResultSet rs=st.executeQuery("select * from customer"); System.out.println("ID FN LN"); System.out.println("---------------------"); while(rs.next()) { String id=rs.getString(1); String fn=rs.getString(2); String ln=rs.getString(3); String row=id+" "+fn+" "+ln; System.out.println(row); } }catch(Exception ex) { System.out.println(ex.getMessage()); } } }

OUTPUT

Page | 93