0% found this document useful (0 votes)
13 views

Final Java Record

Uploaded by

Raga Priya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Final Java Record

Uploaded by

Raga Priya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 119

LOYOLA ACADEMY

(AN AUTONOMOUS COLLEGE)


A COLLEGE WITH POTENTIAL FOR EXCELLENCE
ACCREDITED BY NAAC WITH ‘A’ GRADE
(AFFILIATED TO OSMANIA UNIVERSITY)

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

CERTIFICATE
THIS IS TO CERTIFY THAT THIS IS A BONAFIDE RECORD OF THE
WORK DONE IN OBJECT ORIENTED PROGRAMMING IN JAVA LAB
DURING 2nd YEAR 3rd SEMESTER FOR THE ACADEMIC YEAR 2021-2022

NAME : ANUPOJU AMISHA

CLASS : NCS

HALL TICKET NUMBER : 111720013004

INTERNAL EXAMINER EXTERNAL EXAMINER PRINCIPAL

INDEX
SNO TITLE PAGE NO DATE SIGN
1 Program to print multiplication table
2 Program to check the eligibility of a person to
vote
3 Program to print Fibonacci series
4 Program to print factorial of a number
5 Program to print reverse of a number
6 Program to check whether the given number is a
prime or not
7 Program to print sum and average of an array
8 Program to perform addition and subtraction of
array
9 Program to display maximum and display
elements of an array
10 Program to implement relational operators
11 Program to implement logical operators
12 Program to implement ternary operator
13 Program to implement bitwise operators
14 Program to print greatest of 3 numbers
15 Program to print the grade of a student
16 Program to enroll to professional course
17 Program to print student grade according to the
rules
18 Program to implement switch case to print day
of a week
19 Program to implement switch case to print the
month
20 Program to print the pattern *
21 Program to print the pattern of numbers
22 Program to implement application of classes
,objects & methods
23 Program to implement default and
parameterized constructors
24 Program to print objects as parameter
25 Program to implement method overloading
26 Program to implement method overriding
27 Program to implement recursion
28 Program to perform arithmetic operations using
command line arguments
29 Program to implement single inheritance
30 Program to implement multiple inheritance
using interfaces concept
31 Program to implement multilevel inheritance
32 Program to implement hierarchical inheritance
33 Program to implement dynamic method
dispatch
34 Program to implement abstract classes
35 Program to implement abstract methods
SNO TITLE PAGE NO DATE SIGN
36 Program to create a package
37 Program to import a package
38 Program to implement area of rectangle and
circle using interfaces
39 Program to implement try and catch
40 Program to implement nested try
41 Program to demonstrate throw keyword
42 Program to demonstrate throws keyword
43 Program to create a thread using runnable
interface
44 Program to implement isAlive() and join()
45 Program to implement thread priorities
46 Program to print odd and even numbers using
threads
47 Program to implement inter thread
communication
48 Program to implement synchronization
49 Program to implement searching of string
50 Program to implement string to change case
51 Program to implement wrapper classes
52 Program to demonstrate date and calendar
53 Program to implement Gregorian calendar
54 Program to implement vectors
55 Program to pass parameters to applets
56 Program to change background color and show
message in a applet
57 Program to change font style in applets using
labels
58 Program to display images through applets
59 Program to implement getDocumentbase() and
getCodebase ()
60 Program to implement event classes
61 Program to implement event listerner interfaces
62 Program to implement flow layout
63 Program to implement border layout
64 Program to implement grid layout
65 Program to implement card layout
66 Program to demonstrate JLabel with images
67 Program to demonstrate JButton
68 Program to demonstrate JCheckBox
69 Program to demonstrate JRadioButton
70 Program to demonstrate JTabbedPaine
71 Program to demonstrate JTable
72 Program to demonstrate Joptionpane
73 Program to demonstrate JToggleButton
74 Program to demonstrate divison of number
using swing controls
75 Program to implement JTable
76 Program to implement JList
SNO TITLE PAGE NO DATE SIGN
77 Program to implement J Slidder
78 Program to implement J SplitPane
79 Program to implement J FileChooser
80 Program to display contents of a directory
81 Program to filter a directory
82 Program to read from a file
83 Program to write to a file

1. Program to print multiplication table


class table

public static void main(String args[])

int a,i,p=1;

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

System.out.println("The multiplication table for" +a+ "is:");

for(i=1;i<=10;i++)

p=a*i;

System.out.println(a+"*"+i+"="+p);

OUTPUT

C:\ncs20geeta>java table 899

The multiplication table for 899 is:

899*1=899

899*2=1798

899*3=2697

899*4=3596

899*5=4495

899*6=5394

899*7=6293

899*8=7192

899*9=8091

899*10=8990

2. Program to check the eligibility of a person to vote


class vote

public static void main(String args[])

int a=Integer.parseInt(args[0]);

System.out.println("The entered age is:");

System.out.println(a);

if(a>18)

System.out.println("eligible to vote");

else

System.out.println("not eligible to vote");

OUTPUT :-:-:

C:\ncs20geeta>java vote 8

The entered age is:

not eligible to vote

C:\ncs20geeta>java vote 19

The entered age is: 19

eligible to vote

3. Program to print Fibonacci series

class fib

public static void main(String arg[])

int f1=0,f2=1,f3=0;
System.out.println("The fibnaccie series are:");

System.out.println(f1);

System.out.println(f2);

while(f3<=13)

f3=f1+f2;

System.out.println(f3);

f1=f2;

f2=f3;

OUTPUT

The Fibonacci series are:

13

21

4. Program to print factorial of a number

class factorial

public static void main(String args[])

int a, i;
int f=1;

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

for(i=1;i<=a;i++)

f=f*i;

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

OUTPUT

Factorial of 5 is120

5. Program to print reverse of a number

class reverse

public static void main(String args[])

int r,n,s=0;

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

while(n>0)

r=n%10;

n=n/10;

s=(s*10)+r;

System.out.println("Reverse of a given number is:" +s);

}
OUTPUT :-:-:

Reverse of a given number is : 54321

6. Program to check whether the given number is a prime or not

import java.io.*;

class prime

public static void main(String args[])

int i;

int num=Integer.parseInt(args[0]);

int flag=0;

for(i=2;i<num;i++)

if(num%i==0)

System.out.println(num+ "is not a prime no.");

flag=1;

break;

OUTPUT :-

4 is not a prime no.

7. Program to print sum and average of an array


import java.io.*;

class arrayprog

public static void main(String args[])throws IOException,NumberFormatException

int a[]=new int[10];

int i=0,j=0,k=0;

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

System.out.println("Enter the array elements:");

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

a[i]=Integer.parseInt(br.readLine());

System.out.println("The entered elements are:");

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

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

k=k+a[i];

System.out.println("\nAverage is:" +(k/10));

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

OUTPUT :-

Enter the array elements:

3
4

10

The entered elements are:

1 2 3 4 5 6 7 8 9 10

Average is:5

sum is:55

8. Program to perform addition and subtraction & multiplication of array

import java.io.*;

class matrixdemo

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

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

int i,j;

System.out.println("Enter rows and columns for matrix A:");

int r1=Integer.parseInt(br.readLine());

int c1=Integer.parseInt(br.readLine());

System.out.println("Enter matrix A elements:");

int a[][]=new int[r1][c1];

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

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

{
a[i][j]=Integer.parseInt(br.readLine());

System.out.println("Enter rows and columns for matrix B:");

int r2=Integer.parseInt(br.readLine());

int c2=Integer.parseInt(br.readLine());

System.out.println("Enter matrix B elements:");

int b[][]=new int[r1][c1];

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

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

b[i][j]=Integer.parseInt(br.readLine());

int c[][]=new int[r1][c1];

if((r1==r2)&&(c1==c2))

System.out.println("Addition of matrix A and Bis:");

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

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

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

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

System.out.println("\n");

}
}

else

System.out.println("Addition is not possible:");

if((r1==r2)&&(c1==c2))

System.out.println("Subtraction of matrix A and Bis:");

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

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

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

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

System.out.println("\n");

else

System.out.println("subtraction is not possible:");

if((r1==r2)&&(c1==c2))

System.out.println("Multiplication of matrix A and Bis:");

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

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

c[i][j]=0;

for(int k=0;k<r2;k++)

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

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

System.out.println("\n");

else

System.out.println("Multiplication is not possible:");

OUTPUT :-

Enter rows and columns for matrix A:

Enter matrix A elements:

Enter rows and columns for matrix B:

Enter matrix B elements:

8
Addition of matrix A and B is:

6 8

10 12

Subtraction of matrix A and B is:

-4 -4

-4 -4

Multiplication of matrix A and B is:

15 18

31 36

9. Program to display maximum and display elements of an array

import java.io.*;

class programdemo

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

int a[]=new int[10];

int i,j,min,max;

System.out.println("enter elements into array");

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

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

a[i]=Integer.parseInt(br.readLine());

System.out.println("values in the array are");

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

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

max=min=a[0];

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

if(a[i]>max)
max=a[i];

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

if(a[i]<min)

min=a[i];

System.out.println("maximum=" +max);

System.out.println("minimum=" +min);

OUTPUT :-

Enter elements into array

10

12

11

values in the array are

1 2 3 6 8 9 10 12 4 11

maximum=12

minimum=1

10. Program to implement relational operators


class relop

public static void main(String args[])

float a=15.0F,b=20.75F,c=15.0F;

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

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

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

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

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

System.out.println("a==c is:" +(a==c));

System.out.println("a<=c is:" +(a<=c));

System.out.println("a>=c is:" +(a>=c));

System.out.println("a!=c is:" +(a!=c));

System.out.println("b==(a+c) is:" +(b==(a+c)));

OUTPUT :-

a=15.0

b=20.75

c=15.0

a>b is:false

a<b is:true

a==c is:true

a<=c is:true

a>=c is:true

a!=c is:false

b==(a+c) is:false

11. Program to implement logical operators


class boollogic

public static void main(String args[])

boolean a=true;

boolean b=false;

boolean c=a|b;

boolean d=a&b;

boolean e=(a^b);

boolean f=((!a&b)|(a&!b));

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

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

System.out.println("a|b is:" +c);

System.out.println("a&b is:" +d);

System.out.println("a^b is:" +e);

System.out.println("(!a&b)|(a&!b) is:" +f);

OUTPUT :-

a=true

b=false

a|b is:true

a&b is:false

a^b is:true

(!a&b)|(a&!b) is:true

12. Program to implement ternary operator


class Ternary

public static void main(String args[])

int i,k;

i=10;

k=i<0?-i:i;

System.out.println("absolute value of");

System.out.println(i+"is"+k);

i=-10;

k=i<10?-i:i;

System.out.println("absolute value of");

System.out.println(i+"is"+k);

OUTPUT

C:\sharathjava>javac Ternary.java

C:\sharathjava>java Ternary

absolute value of

10is10

absolute value of

-10is10

13. Program to implement bitwise operator

class Bitwise

public static void main(String args[])

int a=3,b=6,c=9;
System.out.println("NOT:"+(~a));

System.out.println("AND:"+(a&b));

System.out.println("OR:"+(a/b));

System.out.println("XOR:"+(a^b));

System.out.println("Shift left:"+(a<<2));

System.out.println("Shift right:"+(a>>2));

System.out.println("Unsigned shift right:"+(a>>>2));

c&=5;

System.out.println("AND assignment:"+c);

c|=5;

System.out.println("OR assignment:"+c);

c^=5;

System.out.println("XOR assignment:"+c);

c<<=5;

System.out.println("Shift left assignment:"+c);

c>>=5;

System.out.println("Shift right assignment:"+c);

c>>>=5;

System.out.println("Unsigned shift right assignment:"+c);

OUTPUT

NOT: -4

AND:2

OR:0

XOR:5

Shift left:12

Shift right:0
Unsigned shift right:0

AND assignment:1

OR assignment:5

XOR assignment:0

Shift left assignment:0

Shift right assignment:0

Unsigned shift right assignment:0

14. Program to print greatest of 3 numbers

class great3

public static void main(String args[])

int a=Integer.parseInt(args[0]);

int b=Integer.parseInt(args[1]);

int c=Integer.parseInt(args[2]);

System.out.println("the three numbers are:");

System.out.println(a);

System.out.println(b);

System.out.println(c);

if(a>b&&a>c)

System.out.println(a+"is greater of three numbers");

else if(b>a&&b>c)

System.out.println(b+"is greater of three numbers");

else

System.out.println(c+"is greater of three numbers");

OUTPUT :-:-:
C:\ncs20geeta>java great3 876 7845 654

the three numbers are:

876

7845

654

7845is greater of three numbers

15. Program to print the grade of a student

a) In range 81-100

b) In range 61-80

c) In range 41-61

d) In range 0-40

class marks

public static void main(String args[])

int a[]={5,15,25,35,45,55,65,75,85,95};

int i,b=0,c=0,d=0,e=0;

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

if(a[i]>=81&&a[i]<=100)

b++;

else

if(a[i]>=61&&a[i]<=80)

c++;

else

if(a[i]>=41&&a[i]<=60)

d++;

else
e++;

System.out.println("students obtained marks in 81-100 are:" +b);

System.out.println("students obtained marks in 61-100 are:" +c);

System.out.println("students obtained marks in 41-100 are:" +d);

System.out.println("students obtained marks in 0-40 are:" +e);

OUTPUT :-:-:

C:\geeta>java marks

students obtained marks in 81-100 are:2

students obtained marks in 61-100 are:2

students obtained marks in 41-100 are:2

students obtained marks in 0-40 are:4

16. Program to enroll to professional course

FOLLOWING CONDITIONS

A) MARKS IN MATHS>=60

B) MARKS IN PHYSICS>=50

C) MARKS IN CHEMISTRY>=40

D) TOTAL OF ALL SUBJECTS >=200

E) TOTAL OF PHYSICS AND MATHS>=120

class admission

public static void main(String args[])

int maths,phy,chem,tot1,tot2;

maths=Integer.parseInt(args[0]);

phy=Integer.parseInt(args[1]);
chem=Integer.parseInt(args[2]);

System.out.println("the entered marks are:");

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

System.out.println("physics=" +phy);

System.out.println("chemistry=" +chem);

tot1=maths+phy+chem;

tot2=maths+phy;

if(maths>=60&&phy>=50&&chem>=40&&tot2>=120)

System.out.println("admission is given for professional course");

else

System.out.println("admission is not given for prfessional course");

OUTPUT :-:-:

the entered marks are:

maths =80

physics =78

chemistry =64

addmission is given for professional course

17. Program to print student grade according to the rules

AVERAGE MARKS GRADE

80-100 HONOURS

60-79 FIRST DIVISION

50-59 SECOND DIVISION

40-49 THIRD DIVISION

BELOW 40 FAIL

class grade

{
public static void main(String args[])

int a=Integer.parseInt(args[0]);

System.out.println("the entered average marks is:");

System.out.println(a);

if(a>=80&&a<=100)

System.out.println("HONOURS");

else if(a>=60&&a<80)

System.out.println("FIRST DIVISION");

else if(a>=50&&a<60)

System.out.println("SECOND DIVISION");

else if(a>=40&&a<50)

System.out.println("THIRD DIVISION");

else

System.out.println("FAIL");

OUTPUT :-:-:

The entered average marks is:

98

HONOURS

the entered average marks is:

35

FAIL

18. Program to implement switch case to print day of a week

import java.io.*;

class week

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

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

System.out.println("The days are:");

System.out.println("1.day1");

System.out.println("2.day2");

System.out.println("3.day3");

System.out.println("4.day4");

System.out.println("5.day5");

System.out.println("6.day6");

System.out.println("7.day7");

System.out.println("Enter your option:");

int a=Integer.parseInt(br.readLine());

switch(a)

case 1:

System.out.println("MONDAY");

break;

case 2:

System.out.println("TUESDAY");

break;

case 3:

System.out.println("WEDNESDAY");

break;

case 4:

System.out.println("THURSDAY");

break;

case 5:
System.out.println("FRIDAY");

break;

case 6:

System.out.println("SATURDAY");

break;

case 7:

System.out.println("SUNDAY");

break;

default:

System.out.println("wrong option");

OUTPUT :-

The days are:

1.day1

2.day2

3.day3

4.day4

5.day5

6.day6

7.day7

Enter your option:

FRIDAY

19. Program to implement switch case to print the month

import java.io.*;

class months

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

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

System.out.println("Enter the month number:");

int a=Integer.parseInt(br.readLine());

switch(a)

case 1:

System.out.println("JANUARY");

break;

case 2:

System.out.println("FEBRAURY");

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("wrong option");

OUTPUT :-:-:

Enter the month number:

AUGUST

20. Program to print the pattern *

class pattern

public static void main(String args[])


{

int i,j;

System.out.println("the pattern structure is:");

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

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

System.out.print("*");

System.out.println("\n");

OUTPUT :-:-:

C:\ncs20geeta>java pattern

the pattern structure is:

**

***

21. Program to print the pattern of numbers

class pattern2

public static void main(String args[])

int i,j;

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

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

System.out.print(k);

k++;

System.out.println("\n");

OUTPUT :-:-:

12

123

1234

12345

22. Program to implement application of classes , objects & methods(area of rectangle)

class rectangle

int length,width; //declaration of variables

void getData(int x, int y) //method declaration

length=x;

width=y;

int rectArea( ) //method declaration

int area=length*width;

return(area);
}

class RectArea

public static void main(String args[])

int ar1,ar2;

rectangle rect1=new rectangle();

rectangle rect2=new rectangle();

rect1.length=15;

rect1.width=10;

ar1=rect1.length*rect1.width;

rect2.getData(20,30);

ar2=rect2.rectArea();

System.out.println("area of rectangle1 is:" +ar1);

System.out.println("area of rectangle2 is:" +ar2);

OUTPUT :-:-:

area of rectangle1 is:150

area of rectangle2 is:600

23. Program to implement default and parameterized constructors

class rectangle22

int len,wid;

rectangle22( ) //default constructor

len=10;
wid=20;

rectangle22(int x,int y) //parameterised constructor

len=x;

wid=y;

int area()

return(len*wid);

class recta rea22

public static void main(String args[])

rectangle22 r1=new rectangle22();

rectangle22 r2=new rectangle22(50,80);

int ar1=r1.area();

int ar2=r2.area();

System.out.println("area of rectangle 1 is:" +ar1);

System.out.println("area of rectangle 2 is:" +ar2);

OUTPUT :-

area of rectangle 1 is:200

area of rectangle 2 is:4000

24. Program to print objects as parameter


class testob

int a,b;

testob(int i,int j)

a=i;

b=j;

boolean equals1(testob o)

if(o.a==a&&o.b==b)

return true;

else

return false;

class passob

public static void main(String args[])

testob ob1=new testob(100,22);

testob ob2=new testob(100,22);

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

System.out.println("obj1==obj2" +ob1.equals1(ob2));

System.out.println("obj1==obj3" +ob1.equals1(ob3));

OUTPUT :-
obj1==obj2true

obj1==obj3false

25. Program to implement method overloading

class overloaddemo

void test()

System.out.println("No parameters");

void test(int x)

System.out.println("Integer parameter is:" +x);

void test(double x)

System.out.println("Double parameter is:" +x);

void test(int x,int y)

System.out.println("integer parameter 1 is:"+x+ " \n integer parameter 2 is:"+y);

class parameter

public static void main(String args[])

overloaddemo o=new overloaddemo();

o.test();
o.test(5);

o.test(2.75);

o.test(15,25);

OUTPUT :-

no parameters

integer parameter is:5

double parameter is:2.75

integer parameter 1 is:15

integer parameter 2 is:25

26. Program to implement method overriding

class Super

int x;

Super(int x)

this.x=x;

void display()

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

class sub extends Super

int y;

sub(int x,int y)
{

super(x);

this.y=y;

void display()

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

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

class override

public static void main(String args[])

sub s=new sub(10,20);

s.display();

OUTPUT :-:-:

super x= 10

sub y= 20

27. Program to implement recursion

class recursionFact

int fact(int n)

int result;

if(n==1||n==0)
return 1;

else

result=n*fact(n-1);

return result;

class recursion

public static void main(String args[])

recursionFact f=new recursionFact();

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

System.out.println("factorial of 5 is:" +f.fact(6));

System.out.println("factorial of 5 is:" +f.fact(7));

System.out.println("factorial of 5 is:" +f.fact(8));

OUTPUT :-:-:

factorial of 5 is:120

factorial of 5 is:720

factorial of 5 is:5040

factorial of 5 is:40320

28. Program to perform arithmetic operations using command line arguments

import java.io.*;

class arthi2

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

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


System.out.println("Enter any two values:");

int a=Integer.parseInt(in.readLine());

int b=Integer.parseInt(in.readLine());

System.out.println("the arithmetic operations are:");

System.out.println("the addition of" +a+ "and" +b+ "is:"+(a+b));

System.out.println("the subtraction of" +a+ "and" +b+ "is:"+(a-b));

System.out.println("the multiplication of" +a+ "and" +b+ "is:"+(a*b));

System.out.println("the division of"+a+"and"+b+"is:"+(a/b));

OUTPUT :-:-:

C:\ncs20geeta>java arthi2

Enter any two values:

120

40

the arithmetic operations are:

the addition of120 and 40 is : 160

the subtraction of 120 and 40 is : 80

the multiplication of 120 and 40 is : 4800

the division of 120 and 40 is : 3

29. Program to implement single inheritance

class room1

int length,breadth;

room1(int x,int y)

length=x;

breadth=y;
}

int area()

return(length*breadth);

class room2 extends room1

int height;

room2(int x,int y,int z)

super(x,y);

height=z;

int volume()

return(length*breadth*height);

class singleInherit

public static void main(String args[])

room2 r2=new room2(10,4,12);

int a1=r2.area();

int v1=r2.volume();

System.out.println("area of room is:" +a1);

System.out.println("volume of room is:" +v1);


}

OUTPUT :-

area of room is:40

volume of room is:480

30. Program to implement multiple inheritance using interfaces concept

class student

int rollno;

void getNumber(int n)

rollno=n;

void putNumber()

System.out.println("rollno" +rollno);

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 sportWt=6.0F;

void putWt();

class results extends test implements sports

float total;

public void putWt()

System.out.println("sportswt=" +sportWt);

void display()

float total=part1+part2+sportWt;

putNumber();

putMarks();

putWt();

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

class hybrid

{
public static void main(String args[])

results student1=new results();

student1.getNumber(1234);

student1.getMarks(27.5f,33.0f);

student1.display();

OUTPUT :-:-:

C:\pooji>javac hybrid.java

C:\pooji>java hybrid

rollno1234

marks obtained

part1=27.5

part2=33.0

sportswt=6.0

total score=66.5

31. Program to implement multilevel inheritance

class test2
{
public void display()
{ test2
System.out.println("Hello1"); |
} hello
|
Multilevel
}
class hello extends test2
{
public void show()
{
System.out.println("Hello2");
}
}
class multilevel extends hello
{
public void calculate()
{
System.out.println("Hello3");
}
public static void main(String args[])
{
multilevel m=new multilevel();
m.display();
m.show();
m.calculate();
}
OUTPUT :-:-:
Hello1
Hello2
Hello3

32. Program to implement hierarchical inheritance

class A

public void methodA() A

{ B C D

System.out.println("methods of class A");

class B extends A

public void methodB()

System.out.println("methods of class B");

class C extends A

public void methodC()

{
System.out.println("method of class C");

class D extends A

public void methodD()

System.out.println("method of class D");

class Hierarchial

public static void main(String args[])

A a=new A();

B b=new B();

C c=new C();

D d=new D();

a.methodA();

b.methodB();

c.methodC();

d.methodA();

d.methodD();

} A

} B C

OUTPUT :-:-:
C:\pooji>javac Hierarchial.java

C:\pooji>java Hierarchial

methods of class A

methods of class B

method of class C

methods of class A

method of class D

33. Program to implement dynamic method dispatch

class animal

public void eat()

System.out.println("every animal has to eat to live");

class elephant extends animal

public void eat()

System.out.println("elephant eats leaves");

class lion extends animal

public void eat()

System.out.println("lion eats flesh");

}
}

class dynamically

public static void main(String args[])

animal a=new animal();

a.eat();

elephant e=new elephant();

a=e;

a.eat();

lion l=new lion();

a=l;

a.eat();

OUTPUT :-:-:

C:\pooji>javac dynamically.java

C:\pooji>java dynamically

every animal has to eat to live

elephant eats leaves

lion eats flesh

34. Program to implement abstract classes

abstract class figure

double dim1,dim2;

figure(double a,double b)

dim1=a;
dim2=b;

abstract double area();

class Rectangle extends figure

Rectangle(double a,double b)

super(a,b);

double area()

return(dim1*dim2);

class Triangle extends figure

Triangle(double a,double b)

super(a,b);

double area()

return(0.5*dim1*dim2);

class findAreas

{
public static void main(String args[])

Rectangle r=new Rectangle(5,6);

Triangle t=new Triangle(10,8);

figure ref;

ref=r;

System.out.println("area is:" +ref.area());

ref=t;

System.out.println("area is:" +ref.area());

OUTPUT :-:-:

C:\pooji>javac findAreas.java

C:\pooji>java findAreas

area is:30.0

area is:40.0

35. Program to implement abstract classes

abstract class hello7

public abstract void display();

public abstract void show();

public void calculate()

System.out.println("hello1");

class test7 extends hello7

{
public void display()

System.out.println("ok1");

public void show()

System.out.println("ok2");

public static void main(String args[])

test7 t=new test7();

t.calculate();

t.display();

t.show();

OUTPUT :-:-:

C:\pooji>javac test7.java

C:\pooji>java test7

hello1

ok1

36. Program to create a package

package arithmetic;

public class BasicArith

double x,y;

public BasicArith(double a,double b)

{
x=a;

y=b;

public double add()

return x+y;

public double sub()

return x-y;

public double mul()

return x*y;

public double div()

return x/y;

public double mod()

return x%y;

37. Program to import a package

import arithmetic.BasicArith;

import java.io.*;

class userpack
{

} public static void main(String args[])throws IOException

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

System.out.println("enter two values");

double x=Double.parseDouble(br.readLine());

double y=Double.parseDouble(br.readLine());

BasicArith arith=new BasicArith(x,y);

System.out.println("addition" +arith.add());

System.out.println("difference" +arith.sub());

System.out.println("multiplication" +arith.mul());

System.out.println("division" +arith.div());

System.out.println("modulus" +arith.mod());

OUTPUT :-

Enter two values

Addition 12.0

Difference 4.0

Multiplication 32.0

Division 2.0

Modulus 0.0

38. Program to implement area of rectangle and circle using interfaces

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 area;

area=rect;

System.out.println("area of rectangle=" +area.compute(10,20));

area=cir;

System.out.println("area of circle=" +area.compute(10,0));

}
OUTPUT :-:-:

C:\pooji>javac interfaceTest.java

C:\pooji>java interfaceTest

area of rectangle=200.0

area of circle=314.0

39. Program to implement try and catch

class error

public static void main(String args[])

int a=10,b=5,c=5;

try

int y=a/(b-c);

catch(ArithmeticException e)

System.out.println("exception caught:" +e.getMessage());

int y=a/(b+c);

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

OUTPUT :-

C:\pooji>javac error.java

C:\pooji>java error

exception caught:/ by zero

y=1
40. Program to implement nested try

class Nestedtry

public static void main(String args[])

try

int a=args.length;

int b=42/a;

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

try

if(a==1)

a=a/(a-a);

if(a==2)

int c[]={1};

c[2]=9;

catch(ArithmeticException e)

System.out.println(e.getMessage()+ "is out of range");

catch(ArithmeticException e)

System.out.println(e);
}

OUTPUT :-

C:\pooji>javac Nestedtry.java

C:\pooji>java Nestedtry

java.lang.ArithmeticException: / by zero

41. Program to demonstrate throw keyword

class test

void avg()

try

throw new ArithmeticException("Demo");

catch(ArithmeticException e)

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

public static void main(String args[])

test t=new test();

t.avg();

OUTPUT :-:-:
C:\pooji>javac test.java

C:\pooji>java test

exception caught

42. Program to demonstrate throws keyword

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 :-:-:

C:\pooji>javac ThrowsDemo.java

C:\pooji>java ThrowsDemo

Inside throwone
caughtjava.lang.IllegalAccessException: demo

43. Program to create a thread using runnable interface

class NewThread implements Runnable

Thread t;

NewThread()

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

System.out.println("Child thread:"+t);

t.start();

public void run()

try

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

System.out.println("Child Thread:"+i);

Thread.sleep(500);

catch(InterruptedException e)

System.out.println("Child interrupted.");

System.out.println("Exiting child thread.");

}
class ThreadDemo

public static void main(String args[])

new NewThread();

try

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

System.out.println("Main Thread:"+i);

Thread.sleep(1000);

catch(InterruptedException e)

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

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

OUTPUT :-

C:\sharathjava>java ThreadDemo

Child thread:Thread[Demo Thread,5,main]

Main Thread:5

Child Thread:5

Child Thread:4

Main Thread:4
Child Thread:3

Child Thread:2

Main Thread:3

Child Thread:1

Exiting child thread.

Main Thread:2

Main Thread:1

Main thread exiting.

44. Program to implement isAlive() and join()

class NewThread implements Runnable

String name;

Thread t;

NewThread(String threadname)

name=threadname;

t=new Thread(this,name);

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

t.start();

public void run()

try

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

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

Thread.sleep(1000);

}
catch(InterruptedException e)

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

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

class DemoJoin

public static void main(String args[])

NewThread ob1=new NewThread("One");

NewThread ob2=new NewThread("Two");

NewThread ob3=new NewThread("Three");

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

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

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

try

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

ob1.t.join();

ob2.t.join();

ob3.t.join();

catch(InterruptedException e)

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

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 exiting.");

OUTPUT :-

C:\sharathjava>java DemoJoin

New thread:Thread[One,5,main]

New thread:Thread[Two,5,main]

One;5

New thread:Thread[Three,5,main]

Two;5

Three;5

Thread One is alive:true

Thread Two is alive:true

Thread Three is alive:true

Waiting for threads to finish.

One;4

Two;4

Three;4

One;3

Two;3

Three;3

One;2

Three;2

Two;2

T-wo;1

One;1

Three;1

Oneexiting.

Twoexiting.

Threeexiting.

Thread One is alive:false


Thread Two is alive:false

Thread Three is alive:false

45. Program to implement thread priorities

class clicker implements Runnable

long click=0;

Thread t;

private volatile boolean running=true;

public clicker(int p)

t=new Thread(this);

t.setPriority(p);

public void run()

while (running)

click++;

public void stop()

running=false;

public void start()

t.start();

class HiLoPri

{
public static void main(String args[])

Thread.currentThread().setPriority(Thread.MAX_PRIORITY);

clicker hi=new clicker(Thread.NORM_PRIORITY+2);

clicker lo=new clicker(Thread.NORM_PRIORITY-2);

lo.start();

hi.start();

try

Thread.sleep(1000);

catch(InterruptedException e)

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

lo.stop();

hi.stop();

try

hi.t.join();

lo.t.join();

catch(InterruptedException e)

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

OUTPUT :-

C:\sharathjava>java HiLoPri

Low-priority thread:321533645

High-priority thread : 354761379

46. Program to print odd and even numbers using threads


class even extends Thread

public void run1()

int i;

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

if(i%2==0)

System.out.println("it is a even number");

class odd extends Thread

public void run2()

int j;

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

if(j%2!=0)

System.out.println("it is a odd number");

class MyThread

public static void main(String args[])

even et=new even();

odd od=new odd();

et.run1();
od.run2();

OUTPUT :-

C:\sharathjava>java MyThread

it is a even number

it is a even number

it is a odd number

it is a odd number

it is a odd number

47. Program to implement inter thread communication

class Q

int n;

synchronized int get()

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

return n;

synchronized void put(int n)

this.n=n;

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

class Producer implements Runnable

Q q;

Producer(Q q)

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

public void run()

int i=0;

while(true)

q.put(i++);

class Consumer implements Runnable

Q q;

Consumer(Q q)

this.q=q;

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

public void run()

OUTPUT :-

Put:1189

Put:1190

Put:1191

Put:1192

Put:1193

Put:1194

Put:1195

Put:1196

Put:1197

Put:1198
Put:1199

Put:1200

Put:1201

Got:1201

Got:1201

Got:1201

Got:1201

Got:1201

Got:1201

Got:1201

Got:1201

Got:1201

Got:1201

Got:1201

Got:1201

Got:1201

Got:1201

Got:1201

48. Program to implement synchronization

class Callme

void call(String msg)

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

try

Thread.sleep(1000);

catch(InterruptedException e)

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

System.out.println("]");

class Caller implements Runnable

String msg;

Callme target;

Thread t;

public Caller(Callme targ,String s)

target=targ;

msg=s;

t=new Thread(this);

t.start();

public void run()

synchronized(target)

target.call(msg);

class Synch1

public static void main(String args[])

Callme target=new Callme();

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

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


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

try

ob1.t.join();

ob2.t.join();

ob3.t.join();

catch(InterruptedException e)

System.out.println("Interrupted");

OUTPUT :-

C:\sharathjava>java Synch1

[Hello]

[World]

[Synchronized]

49. Program to implement searching of string

class indexOfDemo

public static void main(String args[])

String s="Now is the time for all good men"+"to fullfill all their desires";

System.out.println(s);

System.out.println("indexOf(t)="+ s.indexOf('t'));

System.out.println("indexof(the)="+s.indexOf("the"));

System.out.println("lastIndexOf(the)="+s.lastIndexOf("the"));

System.out.println("indexOf(t,10)="+s.indexOf('t',10));

System.out.println("lastIndexOf(t,60)="+s.lastIndexOf('t',60));

System.out.println("indexOf(the,10)="+s.indexOf("the",10));
System.out.println("lastIndexOf(the,60)="+s.lastIndexOf("the",60));

OUTPUT

C:\sharathjava>javac indexOfDemo.java

C:\sharathjava>java indexOfDemo

Now is the time for all good mento fullfill all their desires

indexOf(t)=7

indexof(the)=7

lastIndexOf(the)=48

indexOf(t,10)=11

lastIndexOf(t,60)=48

indexOf(the,10)=48

lastIndexOf(the,60)=48

50. Program to implement string to change case

class Changecase

public static void main(String args[])

String s="This is a test.";

System.out.println("Original:"+s);

String upper=s.toUpperCase();

String lower=s.toLowerCase();

System.out.println("Uppercase:"+upper);

System.out.println("Lowercase:"+lower);

OUTPUT

C:\sharathjava>javac Changecase.java

C:\sharathjava>java Changecase

Original:This is a test.
Uppercase:THIS IS A TEST.

Lowercase:this is a test.

51. Program to implement wrapper classes

class Wrap

public static void main(String args[])

Integer iob=new Integer(100);

int i=iob.intValue();

System.out.println(i+" "+iob);

OUTPUT :-

C:\sharathjava>java Wrap

100 100

52. Program to demonstrate date and calendar

import java.util.Calendar;

class calendarDemo{

public static void main(String args[]) {

String months[] = {"jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"};

Calendar calendar=Calendar.getInstance();

System.out.print("date:");

System.out.print(months[calendar.get(Calendar.MONTH)]);

System.out.print(" " +calendar.get(Calendar.DATE)+" ");

System.out.print(calendar.get(Calendar.YEAR));

System.out.print("time:");

System.out.print(calendar.get(Calendar.HOUR)+":");

System.out.print(calendar.get(Calendar.MINUTE)+":");

System.out.println(calendar.get(Calendar.SECOND));

calendar.set(Calendar.HOUR,10);

calendar.set(Calendar.MINUTE,29);
calendar.set(Calendar.SECOND,22);

System.out.print("update time:");

System.out.print(calendar.get(Calendar.HOUR)+":");

System.out.print(calendar.get(Calendar.MINUTE)+":");

System.out.println(calendar.get(Calendar.SECOND));

OUTPUT :-

C:\sharathjava>java calendarDemo

date:feb 28 2018time:10:59:4

update time:10:29:22

53. Program to implement Gregorian calendar

import java.io.*;

import java.awt.*;

import java.util.*;

class GregorianCalendarDemo

public static void main(String args[])

String months[]={"jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"};

int year;

GregorianCalendar gcalendar=new GregorianCalendar();

System.out.print("Date");

System.out.print(months[gcalendar.get(Calendar.MONTH)]);

System.out.print(" "+gcalendar.get(Calendar.DATE) +" ");

System.out.println(year=gcalendar.get(Calendar.YEAR));

System.out.print("Time");

System.out.print(gcalendar.get(Calendar.HOUR) +":");

System.out.print(gcalendar.get(Calendar.MINUTE) +":");

System.out.println(gcalendar.get(Calendar.SECOND));

if(gcalendar.isLeapYear(year))
{

System.out.println("the current year is leap year");

else

System.out.println("the current year is not leap year");

OUTPUT :-

C:\sharathjava>java GregorianCalendarDemo

Datejan 1 2010

Time1:41:17

the current year is not leap year

54. Program to implement vectors

import java.util.*;

class VectorDemo

public static void main(String args[])

Vector<Integer> v=new Vector<Integer>(3,2);

System.out.println("Initial size:"+v.size());

System.out.println("Initial capacity:"+v.capacity());

v.addElement(1);

v.addElement(2);

v.addElement(3);

v.addElement(4);

System.out.println("Capacity after four additions:"+v.capacity());

v.addElement(5);

System.out.println("Current capacity:"+v.capacity());

v.addElement(6);
v.addElement(7);

System.out.println("Current capacity:"+v.capacity());

v.addElement(9);

v.addElement(10);

System.out.println("Current capacity:"+v.capacity());

v.addElement(11);

v.addElement(12);

System.out.println("First element:"+v.firstElement());

System.out.println("Last element:"+v.lastElement());

if(v.contains(3))

System.out.println("Vector contains 3.");

Enumeration vEnum=v.elements();

System.out.println("\nElements in vector:");

while(vEnum.hasMoreElements())

System.out.print(vEnum.nextElement()+" ");

System.out.println();

OUTPUT :-

C:\sharathjava>java VectorDemo

Initial size:0

Initial capacity:3

Capacity after four additions:5

Current capacity:5

Current capacity:7

Current capacity:9

First element:1

Last element:12

Vector contains 3

Elements in vector:

1 2 3 4 5 6 7 9 10 11 12
55. Program to pass parameters to applets

import java.awt.*;

import java.applet.*;

/*<applet code="ParamApplet width=300 heigth=80>

<param name=fontName value=Courier>

<param name=fontSize value=14>

<param nameleading value=2>

<param name=accountEnabled value=true>

</applet>

*/

public class ParamApplet extends Applet

String fontName;

int fontSize;

float leading;

boolean active;

public void start()

String param;

fontName=getParameter("fontName");

if(fontName==null)

fontName="not found";

param=getParameter("fontSize");

try

if(param!=null)

fontSize=Integer.parseInt(param);

else

fontSize=0;

catch(NumberFormatException e)
{

fontSize=-1;

param=getParameter("leading");

try

if(param!=null)

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

else

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,20);

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

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

OUTPUT
56. Program to change background color and show message in a applet

import java.awt.*;

import java.applet.*;

import java.io.*;

/*<applet code="xyz.class"height=100 width=100></applet>*/

public class xyz extends Applet

public void init()

setBackground(Color.green);

public void paint(Graphics g)

g.drawString("Hello world",100,100);

showStatus("How are you");

OUTPUT

C:\sharath ncs48>javac xyz.java

C:\sharath ncs48>appletviewer xyz.java


57. Program to change font style in applets using labels

import java.io.*;

import java.awt.*;

import java.applet.*;

/*<applet code="changefont.class" height=1000 width=1000></applet>*/

public class changefont extends Applet

public void init()

setBackground(Color.cyan);

setForeground(Color.red);

Label L1=new Label("L1");

Label L2=new Label("L2");

add(L1);

add(L2);

Font F=new Font("serif",Font.BOLD,18);

L1.setFont(F);

OUTPUT
C:\sharath ncs48>javac changefont.java

C:\sharath ncs48>appletviewer changefont.java


58. Program to display images through applets

import java.awt.*;

import java.applet.*;

public class ImageGrpcsEx extends Applet {

Image picture;

public void init()

picture = getImage(getDocumentBase(),"sonoo.jpg");

public void paint(Graphics g) {

g.drawImage(picture, 30,30, this);

OUTPUT
59. Program to implement getDocumentbase() and getCOdebase

import java.awt.*;

import java.applet.*;

import java.net.*;

/*

<applet code="javaapp" width=300 heigth=80>

</applet>

*/

public class Bases extends Applet

public void paint(Graphics g)

String msg;

URL url=getCodeBase();

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

g.drawString(msg,10,40);

url=getDocumentBase();

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

g.drawString(msg,10,40);

}
OUTPUT

60. Program to implement event classes

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

/*<applet code="Key.class" width=300 height=400> </applet>*/

public class Key extends Applet implements KeyListener

int X=20,Y=30;

String msg="This is an example of KeyEvents";

public void init()

addKeyListener(this);

requestFocus();

setBackground(Color.green);

setForeground(Color.blue);

public void keyPressed(KeyEvent k)

showStatus("KeyDown");

int key=k.getKeyCode();

switch(key)
{

case KeyEvent.VK_UP:

showStatus("Move to Up");

break;

case KeyEvent.VK_DOWN:

showStatus("Move to Down");

break;

case KeyEvent.VK_LEFT:

showStatus("Move to Left");

break;

case KeyEvent.VK_RIGHT:

showStatus("Move to Right");

break;

repaint();

public void keyReleased(KeyEvent k)

showStatus("Key Up");

public void keyTyped(KeyEvent k)

msg+=k.getKeyChar();

repaint();

public void paint(Graphics g)

g.drawString(msg,X,Y);

OUTPUT
61. Program to implement event listener interfaces

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

/*<applet code="Mouse1.class" width=500 height=500></applet>*/

public class Mouse1 extends Applet implements MouseListener , MouseMotionListener

int X=0,Y=20;

String msg="MouseEvents";

public void init()

addMouseListener(this);

addMouseMotionListener(this);

setBackground(Color.black);

setForeground(Color.red);

public void mouseEntered(MouseEvent m)

setBackground(Color.magenta);

showStatus("Mouse Entered");
repaint();

public void mouseExited(MouseEvent m)

setBackground(Color.black);

showStatus("Mouse Exited");

repaint();

public void mousePressed(MouseEvent m)

X=10;

Y=20;

msg="NEC";

setBackground(Color.green);

repaint();

public void mouseReleased(MouseEvent m)

X=10;

Y=20;

msg="Engineering";

setBackground(Color.blue);

repaint();

public void mouseMoved(MouseEvent m)

X=m.getX();

Y=m.getY();

msg="College";

setBackground(Color.white);

showStatus("Mouse Moved");
repaint();

public void mouseDragged(MouseEvent m)

msg="CSE";

setBackground(Color.yellow);

showStatus("Mouse Moved"+m.getX()+" "+m.getY());

repaint();

public void mouseClicked(MouseEvent m)

msg="Students";

setBackground(Color.pink);

showStatus("Mouse Clicked");

repaint();

public void paint(Graphics g)

g.drawString(msg,X,Y);

OUTPUT
62. Program to implement flow layout

import java.awt.*;

import java.applet.*;

public class flowoutdemo extends Applet

public void init()

setLayout(new FlowLayout(FlowLayout. RIGHT));

add(new Button("one"));

add(new Button("two"));

add(new Button("three"));
add(new Button("four"));

add(new Button("five"));

add(new Button("six"));

add(new Button("seven"));

add(new Button("eight"));

add(new Button("nine"));

add(new Button("ten"));

/*<applet code="flowoutdemo.class" width=500 height=500></applet>*/

OUTPUT:

63. Program to implement border layout

import java.applet.*;

import java.awt.*;

public class borderlayoutdemo extends Applet

public void init()


{

setLayout(new BorderLayout());

add(new Button("NORTH"),BorderLayout.NORTH);

add(new Button("SOUTH"),BorderLayout.SOUTH);

add(new Button("WEST"),BorderLayout.WEST);

add(new Button("EAST"),BorderLayout.EAST);

String msg="hello how are you";

add(new TextArea(msg),BorderLayout.CENTER);

/*<applet code="borderlayoutdemo.class" width=500 height=500></applet>*/

OUTPUT:

62. Program to implement grid layout


import java.awt.*;

import java.applet.*;

public class gridlayoutdemo extends Applet

static final int n=4;

public void init()

setLayout(new GridLayout(n,n));

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

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

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

int k=(i*n)+j;

if(k>0)

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

/*<applet code="gridlayoutdemo.class" height=800 width=800></applet>*/

OUTPUT:
65. Program to implement card layout

import java.awt.*;

import java.applet.*;

public class cardlayoutdemo extends Applet

CardLayout cl=new CardLayout();

public void init()

String fonts[]=Toolkit.getDefaultToolkit.getFontlist();

setLayout(cl);

panel p1=new panel();

panel p2=new panel();

p1.setLayout(new GridLayout(3,2));

list l=new list(4,false);

Choice c=new Choice();

for(i=0;i<=Fonts.list;i++)

p1.add(new Checkbox(fonts[i]));

l.addItem(fonts[i]);

c.addItem(fonts[i]);
}

p2.add(l);

p2.add(c);

add("one",p1);

add("two",new Button("click here"));

add("three",p2);

public boolean action(Event e,object o)

cl.next(this);

return true;

/*<applet code="cardlayoutdemo.class" height=800 width=800></applet>*/

66. Program to demonstrate JLabel with images

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class JLabelDemo extends JApplet

public void init()

Container c=getContentPane();

String labelText1="<html><h1>WELCOME TO MY WEBSITE</h1><p><i>GUI Programming through


Swings</i></p></html>";

JLabel j1=new JLabel(labelText1);

j1.setBorder(BorderFactory.createTitledBorder("Welcome"));

c.add(j1,BorderLayout.NORTH);
String
labelText2="<html><b>Courses</b><ul><li>B.Sc<li>B.Com<li>B.A<li>M.Sc<li>M.C.A</ul></html>"
;

JLabel j2=new JLabel(labelText2,JLabel.CENTER);

j2.setBorder(BorderFactory.createTitledBorder("Courses"));

c.add(j2,BorderLayout.CENTER);

JLabel j3=new JLabel("This is a test with an image",new ImageIcon("image.jpg"),JLabel.CENTER);

j3.setBorder(BorderFactory.createTitledBorder("Text with image"));

c.add(j3,BorderLayout.SOUTH);

<!—JLabelDemo.html--->

<html>

<applet code="JLabelDemo.class" width=200 height=500>

</applet>

</html>

OUTPUT :-

C:\ncs>javac JLabelDemo.java

C:\ncs>appletviewer JLabelDemo.html

67. Program to demonstrate JButton

import java.applet.*;

import java.awt.*;

import java.awt.event.*;
import javax.swing.*;

public class ColorsDemo extends JApplet implements ActionListener

JButton b1,b2,b3;

Container cp;

public void init()

cp=getContentPane();

cp.setLayout(new FlowLayout());

b1=new JButton("Red");

b2=new JButton("Blue");

b3=new JButton("Green");

b1.addActionListener(this);

b2.addActionListener(this);

b3.addActionListener(this);

cp.add(b1);

cp.add(b2);

cp.add(b3);

public void actionPerformed(ActionEvent e)

if(e.getSource()==b1)

cp.setBackground(Color.RED);

if(e.getSource()==b2)

cp.setBackground(Color.BLUE);

if(e.getSource()==b3)

cp.setBackground(Color.GREEN);

}
}

<!—ColorsDemo.html--->

<html>

<applet code="ColorsDemo.class" width=250 height=100>

</applet>

</html>

OUTPUT :-

C:\ncs>javac ColorsDemo.java

C:\ncs>appletviewer ColorsDemo.html

68. Program to demonstrate JCheckBox

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class jcheckboxdemo extends JApplet implements ActionListener

JLabel jlab;

JCheckBox cb1,cb2,cb3;

Container c;

boolean s1,s2,s3;

String selection;

public void init()

{
c=getContentPane();

c.setLayout(new FlowLayout());

jlab=new JLabel("Which OS is installed in your system ?");

cb1=new JCheckBox("WIN XP");

cb2=new JCheckBox("WIN 7");

cb3=new JCheckBox("WIN 8.1");

cb1.addActionListener(this);

cb2.addActionListener(this);

cb3.addActionListener(this);

c.add(cb1);

c.add(cb2);

c.add(cb3);

c.add(jlab);

public void actionPerformed(ActionEvent e)

s1=cb1.isSelected();

s2=cb2.isSelected();

s3=cb3.isSelected();

if(s1 | s2 |s3)

selection=" ";

if(s1)

selection=cb1.getText();

if(s2)

selection=selection+cb2.getText();

if(s3)

selection=selection+cb3.getText();
}

if(selection!=null)

jlab.setText(selection.trim()+" OS installed");

selection=null;

else

jlab.setText("Nothing is Selected");

<!—jcheckboxdemo.html-->

<html>

<applet code="jcheckboxdemo.class" width=270 height=50>

</applet>

</html>

OUTPUT :-

C:\ncs>javac jcheckboxdemo.java

C:\ncs>appletviewer jcheckboxdemo.html

69. Program to demonstrate JRadioButton

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

public class jradiobutton extends JApplet implements ActionListener

JLabel jlab;

public void init()

Container c=getContentPane();

c.setLayout(new FlowLayout());

JRadioButton b1=new JRadioButton("Java");

b1.addActionListener(this);

c.add(b1);

JRadioButton b2=new JRadioButton("C");

b2.addActionListener(this);

c.add(b2);

JRadioButton b3=new JRadioButton("C++");

b3.addActionListener(this);

c.add(b3);

ButtonGroupbg=new ButtonGroup();

bg.add(b1);

bg.add(b2);

bg.add(b3);

jlab=new JLabel("Select a language:");

c.add(jlab);

public void actionPerformed(ActionEvent e)

jlab.setText("you selected:"+e.getActionCommand());

}
}

<!—jradiobutton.html-->

<html>

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

</applet>

</html>

OUTPUT :-

C:\ncs>javac jradiobutton.java

C:\ncs>appletviewer jradiobutton.html

70. Program to demonstrate JTabbedPaine

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

public class JTabbedPaneDemo extends JApplet

public void init()

Container c=getContentPane();

JTabbedPanejtp=new JTabbedPane();

jtp.addTab("Cities",newCitiesPanel());

jtp.addTab("Colors",newColorsPanel());

c.add(jtp);

}
classCitiesPanel extends JPanel

publicCitiesPanel()

JButton b1=new JButton("Hyderabad");

add(b1);

JButton b2=new JButton("Secunderabad");

add(b2);

classColorsPanel extends JPanel

publicColorsPanel()

JCheckBox cb1=new JCheckBox("YELLOW");

add(cb1);

JCheckBox cb2=new JCheckBox("GREEN");

add(cb2);

<!—JtabbePaneDemo.html--->

<html>

<applet code="JTabbedPaneDemo.class" width=400 height=100>

</applet>

</html>

OUTPUT:

C:\ncs>javac JTabbedPaneDemo.java

C:\ncs>appletviewer JTabbedPaneDemo.html
71. Program to demonstrate JTable

import java.awt.*;

import javax.swing.*;

importjavax.swing.table.*;

importjava.util.*;

importjavax.swing.border.*;

public class JTableDemo extends JApplet

public void init()

String[] cols={"SNO","ClassName","Room No"};

Object[][] data={

{"1","ACS","CS-51"},{"2","NCS","CS-51"},{"3","DCS","CS-51"}};

JTable tab=new JTable(data,cols);

tab.setBorder(BorderFactory.createLineBorder(Color.blue,2));

tab.setFont(new Font("Arial",Font.PLAIN,20));

tab.setRowHeight(30);

tab.setGridColor(Color.red);

JTableHeader head=tab.getTableHeader();

Container c=getContentPane();

c.setLayout(new BorderLayout());

c.add("North",head);

c.add("Center",tab);
}

<html>

<applet code="JTableDemo" width=500 height=200>

</applet>

</html>

OUTPUT: -

C:\ncs>javac JTableDemo.java

C:\ncs>appletviewer JTableDemo.html

72. Program to demonstrate Joptionpane

import javax.swing.*;

import java.awt.*;

/*<applet code="InputDemo" width=400 height=100>

</applet

*/

public class InputDemo extends JApplet

String value;

doubledollars,amt;

int repeat;

public void init()


{

do

value=JOptionPane.showInputDialog("Enter amount in dollars:");

dollars=Double.parseDouble(value);

amt=60.4*dollars;

JOptionPane.showMessageDialog(null,"value in rupees"+amt,"dollar-to-rupee
conversion",JOptionPane.INFORMATION_MESSAGE);

repeat=JOptionPane.showConfirmDialog(null,"Would you like to test again","Please


Confirm",JOptionPane.YES_NO_OPTION);

}while(repeat==JOptionPane.YES_OPTION);

public void paint(Graphics g)

g.drawString(dollars+"$ is Rs"+amt,20,100);

OUTPUT:-

C:\ncs 25>javac JOptionPaneDemo.java

C:\ncs 25>appletviewer JOptionPaneDemo.html


73. Program to demonstrate JToggleButton

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class jtogglebutton extends JApplet implements ActionListener

JLabel jlab;

JToggleButtonjbtn;

Container c;

public void init()

c=getContentPane();

c.setLayout(new FlowLayout());

jlab=new JLabel("Button is OFF");

jbtn=new JToggleButton("ON/OFF");

jbtn.addActionListener(this);

c.add(jbtn);

c.add(jlab);

public void actionPerformed(ActionEvent e)

if(jbtn.isSelected())

jlab.setText("Button is ON");

else

jlab.setText("Button is OFF");

<!—JtoggleButtonDemo.html--->
<html>

<applet code="jtogglebutton.class" width=270 height=50>

</applet>

</html>

OUTPUT

C:\ncs>javac jtogglebutton.java C:\ncs>appletviewer jtogglebutton.html

74. Program to demonstrate divison of number using swing controls

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

public class DivideDemo extends JApplet implements ActionListener

JLabel l1,l2,l3;

JButton div;

JTextField t1,t2;

Container c;

public void init()

l1=new JLabel("Enter first number:");

l2=new JLabel("Enter next number:");

l3=new JLabel();

t1=new JTextField(10);

t2=new JTextField(10);

div=new JButton("Divide");
c=getContentPane();

c.setLayout(new GridLayout(3,2));

c.add(l1);

c.add(t1);

c.add(l2);

c.add(t2);

c.add(div);

c.add(l3);

div.addActionListener(this);

public void actionPerformed(ActionEvent e1)

try

String n1=t1.getText();

String n2=t2.getText();

if(n1.equals("")||n2.equals(""))

l3.setText("Enter numeric data, data not found");

else

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

int b=Integer.parseInt(t2.getText());

int c=a/b;

l3.setText("Value is"+c);

catch(NumberFormatException e2)

{
l3.setText("Integer values need to be entered, Improper data type");

catch(ArithmeticException e3)

l3.setText("Division by zero is not allowed”);

/*<applet code="DivideDemo.class" width=340 height=110>

</applet>

*/

OUTPUT:

C:\ncs>javac DivideDemo.java

C:\ncs>appletviewer DivideDemo.java

75. Program to implement JTable

import java.awt.*;

import javax.swing.*;

importjavax.swing.table.*;

importjava.util.*;

importjavax.swing.border.*;

public class JTableDemo extends JApplet

{
public void init()

String[] cols={"SNO","ClassName","Room No"};

Object[][] data={

{"1","ACS","CS-51"},{"2","NCS","CS-51"},{"3","DCS","CS-51"}};

JTable tab=new JTable(data,cols);

tab.setBorder(BorderFactory.createLineBorder(Color.blue,2));

tab.setFont(new Font("Arial",Font.PLAIN,20));

tab.setRowHeight(30);

tab.setGridColor(Color.red);

JTableHeader head=tab.getTableHeader();

Container c=getContentPane();

c.setLayout(new BorderLayout());

c.add("North",head);

c.add("Center",tab);

<html>

<applet code="JTableDemo" width=500 height=200>

</applet>

</html>

OUTPUT: -

C:\ncs>javac JTableDemo.java

C:\ncs>appletviewer JTableDemo.html
76. Program to implement JList

import java.awt.*;

import javax.swing.*;

importjavax.swing.event.*;

import java.awt.event.*;

public class JListDemo extends JApplet implements ListSelectionListener

JList<String>jlist;

JLabel jlab;

JScrollPanejsp;

String
cities[]={"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","w","x",
"y","z"};

public void init()

Container c=getContentPane();

c.setLayout(new BorderLayout());

jlist=new JList<String>(cities);

jlist.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

jsp=new JScrollPane(jlist);

jlab=new JLabel("Choose a city");

jlist.addListSelectionListener(this);

c.add(jsp,BorderLayout.CENTER);
c.add(jlab,BorderLayout.SOUTH);

public void valueChanged(ListSelectionEventlse)

int index=jlist.getSelectedIndex();

jlab.setText("Current selection is"+cities[index]);

<!—JlistDemo.html--->

<html>

<applet code="JListDemo.class" width=300 height=200>

</applet>

</html>

OUTPUT:

C:\ncs>javac JListDemo.java

C:\ncs>appletviewer JListDemo.html

77. Program to implement JSlidder

import javax.swing.*;
import java.awt.*;
public class jslider
{
public JFrame f;
public JSlider s;
public jslider()
{
f=new JFrame("My JSlider");
s=new JSlider(10,150,38);
s.setMajorTickSpacing(20);
s.setMinorTickSpacing(5);
s.setPaintTicks(true);
s.setPaintLabels(true);
f.setSize(250,150);
f.getContentPane().add(s);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String args[])
{
new jslider();
}
}

OUTPUT-

78. Program to implement JSplitPane

import javax.swing.*;
import java.awt.*;
public class jsplitpane
{
public JFrame f;
public JPanel p1,p2;
public JSplitPane sp;
public jsplitpane()
{
f=new JFrame("My JSplitPane");
p1=new JPanel();
p2=new JPanel();
p1.setBackground(Color.green);
p1.add(new Label("Component ONE"));
p2.setBackground(Color.red);
p2.add(new Label("Component TWO"));
sp=new JSplitPane(JSplitPane.VERTICAL_SPLIT,true,p1,p2);
sp.setDividerSize(20);
sp.setOneTouchExpandable(true);
sp.setDividerLocation(120);
f.setSize(300,200);
f.getContentPane().add(sp);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
new jsplitpane();
}
}

OUTPUT-

79. Program to implement JFileChooser

import javax.swing.*;

import java.awt.*;

import java.io.*;

import java.awt.event.*;

public class JFileChooser extends JPanel

JFrame f;

JLabel l=new JLabel("press open");

JButton b=new JButton("open");

public JFileChooser()

f=new JFrame(" My JFame");

WindowListener w1=new WindowAdapter();

public void WindowClosing(WindowEvent we);

System.exit(0);

};

b.addActionListener(new AL());

f.addWindowListener(w1);
f.setSize(400,150);

f.getContentPane().setLayout(new FlowLayout());

f.getContentPane().add(b);

f.getContentPane().add(l);

f.pack();

f.setVisible(true);

public class AL implements ActionListener

public void actionPerformed(ActionEvent ae)

JFileChooser fc=new JFileChooser();

fc.setFont(new Font("comic sans MS",Font.PLAIN,9));

int choice=fc.showOpenDialog(f);

if(choice==JFileChooser.APPROVE_OPTION)

try

String filename=fc.getSelectedFile().getAbsolutePath();

l.setText("selected file:" +filename);

catch(Exception e)

System.out.println(e);

public static void main(String [] s)

JFileChooser app=new JFileChooser();


}

80. Program to display contents of a directory

import java.io.File;

class DirList

public static void main(String args[])

String dirname="/bhanu";

File f1=new File(dirname);

if(f1.isDirectory())

System.out.println("Directory of"+dirname);

String s[]=f1.list();

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

File f=new File(dirname+"/"+s[i]);

if(f.isDirectory())

System.out.println(s[i]+"is a directory");

else

System.out.println(s[i]+"is afile");

OUTPUT

c:\jeevan>javac DirList.java
c:\jeevan>java DirList

Directory of /ncs28

.java is a file

a.class is afile

81. Program to filter a directory

import java.io.*;

class OnlyExt implements Filenamefilter

String ext;

public OnlyExt(String ext)

this.ext="."+ext;

public boolean accept(File dir,String name)

return name.endsWith(ext);

class DirListOnly

public static void main(String args[])

String dirname="/jeevan";

File f1=new File(dirname);

FilenameFilter Only=new OnlyExt("java");

Strings s[]=f1.list(Only);

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

{
System.out.println(s[i]);

OUTPUT

c:\jeevan>javac DirListOnly.java

c:\jeevan>java DirListOnly

.java

DirList.java

FileWriterDemo.java

ShowFile.java

82. Program to read from a file

import java.io.*;

class ShowFile

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

int i; FileInputStream fin;

try

fin=new FileInputStream(args[0]);

catch(FileNotFoundException e)

System.out.println("File not found");

return;

do

{
i=fin.read();

if(i!=-1)

System.out.print((char)i);

while(i!=-1);

fin.close();

OUTPUT

C:\bhanu>javac ShowFile.java

C:\bhanu>java ShowFile

83. Program to write to a file

import java.io.*;

class FileWriterDemo

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

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

String text;

FileWriter fw=new FileWriter("sampledemo.txt",true);

BufferedWriter bw=new BufferedWriter(fw);

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

System.out.println("enter a name");

text=br.readLine();

bw.write(text+"\n");

bw.close();

fw.close();

}
}

OUTPUT

c:\bhanu> javac FileWriterDemo.java

c:\bhanu> java FileWriterDemo

enter a name

bhanu

enter a name

bhanu

enter a name

bhanu

You might also like