pgms
TRANSCRIPT
JAVA PROGRAMS
1
PROGRAM TO FIND THE SUM OF ARRAY USING RECURSIONimport java.io.*;
class Arraysum
{
int temp;
int sum(int a[],int n)
{
if(n==1)
return a[0];
else
temp =sum(a,n-1);
temp=temp+a[n-1];
return temp;
}
}
class Newarray
{
public static void main(String args[])throws IOException
{
DataInputStream dis=new DataInputStream(System.in);
System.out.println("Enter limit");
int n=Integer.parseInt(dis.readLine());
int a[]=new int[10];
System.out.println("Enter the array");
for(int i=0;i<n;i++)
{
a[i]=Integer.parseInt(dis.readLine());
}
2
Arraysum a1=new Arraysum();
System.out.println("Array sum is"+ a1.sum(a,n));
}
}
OUTPUT
E:\3msc\veena>java Newarray
Enter limit
3
Enter the array
2
3
4
Array sum is 9
3
PROGRAM TO FIND FACTORIAL OF NUMBER USING RECURSION
import java.io.*;
class Factorial
{
int fact(int n)
{
if(n<=1)
return 1;
else
return (n*fact(n-1));
}
}
class Newfact
{
public static void main(String args[])throws IOException
{
DataInputStream dis=new DataInputStream(System.in);
System.out.println("Enter the number");
int i=Integer.parseInt(dis.readLine());
Factorial f=new Factorial();
System.out.println("Factorial is"+f.fact(i));
}
}
OUTPUT
E:\3msc\veena>javac Newfact.java
Note: Newfact.java uses or overrides a deprecated API.
4
Note: Recompile with -Xlint:deprecation for details.
E:\3msc\veena>java Newfact
Enter the number
5
Factorial is 120
5
PROGRAM TO PRINT FIBONACCI NUMBERS
import java.io.*;
class Fib
{
public static void main(String arg[])throws IOException
{
DataInputStream dim=new DataInputStream(System.in);
System.out.println("Enter the limit");
int n=Integer.parseInt(dim.readLine());
int f1=0,f2=1,f3=0;
while(f3<=n)
{
f1=f2;
f2=f3;
System.out.println(f3);
f3=f1+f2;
}
}
}
OUTPUT
E:\3msc\java\joby>java Fib
Enter the limit
6
0
6
1
1
2
3
5
7
PROGRAM TO INPUT THE RADIUS AND HEIGHT OF A CYLINDER AND FIND SURFACE AREA, VOLUME AND TOTAL AREA
import java.io.*;
class Cylin
{
double radius,height;
double sidearea(int r,int h) //side area of cylinder
{
double sa=2*3.14*r*h;
return(sa);
}
double volume(int r,int h) //volume of cylinder
{
double vol=3.14*r*r*h;
return(vol);
}
double totalarea(int r,int h) //total area of cylinder
{
double ta=2*3.14*r*(h+r);
return(ta);
}
}
class Cylinder
{
8
public static void main(String arg[]) throws IOException
{
DataInputStream obj=new DataInputStream(System.in);
System.out.println("Enter the radius");
int r=Integer.parseInt(obj.readLine());
System.out.println("Enter the height");
int h=Integer.parseInt(obj.readLine());
Cylin c=new Cylin();
System.out.println("Side area of cylinder="+c.sidearea(r,h));
System.out.println("Volume of cylinder="+c.volume(r,h));
System.out.println("Total area of cylinder="+c.totalarea(r,h));
}
}
OUTPUT
E:\3msc\sruthy>java Cylinder
Enter the radius
5
Enter the height
10
Side area of cylinder=314.0
Volume of cylinder=785.0
Total area of cylinder=471.00000000000006
9
DEFINE CLASS BABY WITH FOLLOWING ATTRIBUTE (NAME, DATE OF BIRTH, DATE ON WHICH BY INJECTION HAS TO BE GIVEN ,DATE ON WHICH POLIO DROPS TO BE GIVEN). WRITE A CONSTRUCTOR TO CONSTRUCT THE BABY OBJECT.THE CONSTRUCTOR MUST FIND OUT BCG AND POLIO DROPS DATES FROM THE DATE OF BIRTH
import java.util.*;
class Baby
{
String name;
Date dob,bcgdate,poliodate;
long bcgtime,poliotime;
Baby(String name,Date d)
{
this.name=name;
dob=d;
bcgdate=new Date();
poliodate=new Date();
bcgtime=dob.getTime()+(60*24*24*60*10001);
poliotime=dob.getTime()+(45*24*60*60*10001);
poliodate.setTime(poliotime);
bcgdate.setTime(bcgtime);
}
void display()
{
System.out.println("\nName:"+name+"\nDate ofBirth: "+dob.getDate()+
"/"+dob.getMonth()+"/"+dob.getYear()+"\nPolio Drops on: "+
poliodate.getDate() +"/"+dob.getMonth()+"/"+dob.getYear()+
" \nbcgdate on:"+bcgdate.getDate()+"/"+dob.getMonth()+"/"+dob.getYear());
}
10
public static void main(String args[])
{
Baby b=new Baby("Gouri",new Date(2011,1,1));
b.display();
}
}
OUTPUT
E:\msc3\anu>javac Baby.java
Note: Baby.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
E:\msc3\anu>java Baby
Name:Gouri
Date ofBirth: 1/1/2011
Polio Drops on: 3/1/2011
bcgdate on:23/1/2011
PRINT THE DETAILS OF FIVE EMPLOYEES AS PER THEIR DATE OF APPOINTMENT
11
import java.util.*;
public class Employee
{
Date doa;
String name;
String empcode;
Employee(String name,Date doa,String empcode)
{
this.name=name;
this.doa=doa;
this.empcode=empcode;
}
void displayEmployee()
{
System.out.println("\n Name :"+name+" \n Employee code :"+empcode+" \n date of appoinment :"+doa.getDate()+"/"+doa.getMonth()+"/"+doa.getYear());
}
public static void main(String args[])
{
Employee e[];
int k;
e=new Employee[5];
e[0]=new Employee("Deepa",new Date(98,3,22),"D323");
e[1]=new Employee("Catharine",new Date(96,3,22),"E278");
e[2]=new Employee("Boby",new Date(95,3,22),"B428");
e[3]=new Employee("Ebenezer",new Date(98,4,22),"K172");
e[4]=new Employee("Akila",new Date(98,3,20),"A821");
for(int i=0;i<=3;i++)
{
12
for(int j=i+1;j<=4;j++)
{
if(e[i].doa.after(e[j].doa))
{
Employee temp;
temp=e[i];
e[i]=e[j];
e[j]=temp;
}
}
}
for( k=0;k<5;k++)
{
e[k].displayEmployee();
}
}
}
OUTPUT
E:\msc3\jilu\java>javac Employee.java
Note: Employee.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
E:\msc3\jilu\java>java Employee
Name :Boby
Employee code :B428
date of appoinment :22/3/95
13
Name :Catharine
Employee code :E278
date of appoinment :22/3/96
Name :Akila
Employee code :A821
date of appoinment :20/3/98
Name :Deepa
Employee code :D323
date of appoinment :22/3/98
Name :Ebenezer
Employee code :K172
date of appoinment :22/4/98
E:\msc3\jilu\java>
DEFINE CLASS TELEVISION, DEFINE A METHOD FOR DISPLAYING ATTRIBUTES OF TELEVISION
import java.util.*;
14
class Television
{
String make;
int size;
Date dop;
boolean iscolor;
Television(String m,int s,Date d,boolean c)
{
make=m;
size=s;
dop=d;
iscolor=c;
}
void display()
{
System.out.println("\n make : "+make+"\n size: "+size+"\n date of purchase:"+dop.getDate()+"/"+dop.getMonth()+"/"+dop.getYear());
if(iscolor)
System.out.println("color tv");
else
System.out.println("black & white tv");
}
public static void main(String args[])
{
Television t,t1;
t=new Television("BPL",53,new Date(92,1,1),true);
t1=new Television("DYANORA",51,new Date(90,11,11),false);
t.display();
t1.display();
15
}
}
OUTPUT
E:\msc3\jilu\java>javac Television.java
Note: Television.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
E:\msc3\jilu\java>java Television
make : BPL
size: 53
date of purchase:1/1/92
color tv
make : DYANORA
size: 51
date of purchase:11/11/90
black & white tv
DEFINE A ROOM WITH ATTRIBUTES (LENGTH, BREADTH, HEIGHT, FLOOR AREA, WALL AREA, NUMBER OF FANS, NUMBER OF WINDOWS, AND NUMBER OF DOORS).DEFINE A CONSTRUCTOR AND
16
METHOD TO DISPLAY DETAILS OF A ROOM. ASSUME THAT 20% OF THE TOTAL WALL AREA IS OCCUPIED BY DOORS AND WINDOWS
import java.io.*;
class Room
{
double length,breadth,height;
double farea,warea;
int fans,lights,windows,doors;
Room(double len,double br,double ht,int fn,int lt,int wd,int dr)
{
length=len;
breadth=br;
height=ht;
farea=length*breadth;
warea=2*(length*height + breadth*height)*0.80;
fans=fn;
lights=lt;
windows=wd;
doors=dr;
}
void display()
{
System.out.println("Length:"+length+"\nBreadth:"+breadth+"\nHeight:"+height);
System.out.println("FloorArea is:"+farea+"\nWallArea is:"+warea);
System.out.println("Doors:"+doors+"\nWindows:"+windows+
"\nLights:"+lights+"\nFans:"+fans);
}
}
class Room1
17
{
public static void main(String args[])throws IOException
{
DataInputStream dis=new DataInputStream(System.in);
System.out.println("enter length, breadth and height:");
double l=Double.parseDouble(dis.readLine());
double b=Double.parseDouble(dis.readLine());
double h=Double.parseDouble(dis.readLine());
System.out.println("enter the no.of fans:");
int f=Integer.parseInt(dis.readLine());
System.out.println("enter the no.of lights:");
int lg=Integer.parseInt(dis.readLine());
System.out.println("enter the no.of windows:");
int w=Integer.parseInt(dis.readLine());
System.out.println("enter the no.of doors:");
int d=Integer.parseInt(dis.readLine());
Room r=new Room(l,b,h,f,lg,w,d);
r.display();
}
}
OUTPUT
E:\msc3\anu>javac Room1.java
E:\msc3\anu>java Room1
enter length, breadth and height:
10
10
10
enter the no.of fans:
18
2
enter the no.of lights:
1
enter the no.of windows:
2
enter the no.of doors:
1
Length:10.0
Breadth:10.0
Height:10.0
FloorArea is:100.0
WallArea is:320.0
Doors:1
Windows:2
Lights:1
Fans:2
PROGRAM TO DISPLAY STACK OPERATIONSimport java.io.*;
import java.util.*;
19
class Demo
{
static final int max=4;
int a[]=new int[max];
int top;
Demo()
{
top=-1;
}
void push(int item)
{
if(top==max)
System.out.println("Stack is full");
else
a[++top]=item;
}
int pop()
{
if(top==-1)
return 0;
else
return a[top--];
}
void display()
{
System.out.println("New Stack Is:");
for(int i=0;i<=top;i++)
System.out.println(a[i]);
20
}
}
class Stacks
{
public static void main(String args[])throws IOException
{
DataInputStream dim=new DataInputStream(System.in);
Demo s=new Demo();
int op;
do
{
System.out.println("\n1.push\n2.pop\n3.display4.exit\n");
op=Integer.parseInt(dim.readLine());
switch(op)
{
case 1:System.out.println("enter item to push");
int n=Integer.parseInt(dim.readLine());
s.push(n);
break;
case 2:int f=s.pop();
if(f==0)
{
System.out.println("empty stack:");
}
else
{
System.out.println("poped element is"+f);
}
21
break;
case 3:s.display();break;
case 4:break;
default:System.out.println("wrong choice?");
}
}while(op!=4);
}
}
OUTPUT
E:\3msc\java\joby>java Stacks
1.push
2.pop
3.display
4.exit
1
enter item to push
1
1.push
2.pop
3.display
4.exit
1
enter item to push
2
1.push
2.pop
3.display
4.exit
22
3
New Stack Is:
1
2
1.push
2.pop
3.display
4.exit
2
poped element is2
1.push
2.pop
3.display
4.exit
3
New Stack Is:
1
1.push
2.pop
3.display
4.exit
4
PROGRAM TO CONSTRUCT PYRAMID OF DIGITS
class Number
{
23
public static void main(String arg[])
{
int n=8,i,j,k;
for(i=0;i<=n;i++)
{
for(j=0;j<n-i;j++)
System.out.print(" ");
for(k=0;k<i;k++)
System.out.print(i+" ");
System.out.println(" ");
}
}
}
OUTPUT
E:\3msc\java\liya>java Number
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
6 6 6 6 6 6
7 7 7 7 7 7 7
8 8 8 8 8 8 8 8
PROGRAM TO FIND VOLUME OF YOUR BEDROOM AND KITCHEN USING INHERITANCE
import java.io.*;
24
class Broom
{
int length,width,height;
Broom(int l,int w,int h)
{
length=l;
width=w;
height=h;
}
int volume()
{
return(length*width*height);
}
}
class Kroom extends Broom
{
Kroom(int l,int w,int h)
{
super(l,w,h);
}
void display()
{
System.out.println("Volume is:"+volume());
}
}
class Nbroom1
{
public static void main(String args[])throws IOException
25
{
DataInputStream dis=new DataInputStream(System.in);
System.out.println("enter the parametrs of bedroom");
System.out.println("enter length");
int a=Integer.parseInt(dis.readLine());
System.out.println("enter width");
int b=Integer.parseInt(dis.readLine());
System.out.println("enter height");
int c=Integer.parseInt(dis.readLine());
Kroom k=new Kroom(a,b,c);
k.display();
System.out.println("enter the parametrs of kitchen");
System.out.println("enter length");
int g=Integer.parseInt(dis.readLine());
System.out.println("enter width");
int h=Integer.parseInt(dis.readLine());
System.out.println("enter height");
int i=Integer.parseInt(dis.readLine());
Kroom k1=new Kroom(g,h,i);
k1.display();
}
}
OUTPUT
E:\msc3\jilu\java>javac Nbroom1.java
E:\msc3\jilu\java>java Nbroom1
enter the parametrs of bedroom
26
enter length
10
enter width
20
enter height
30
Volume is:6000
enter the parametrs of kitchen
enter length
1
enter width
3
enter height
2
Volume is:6
PROGRAM TO FIND THE VOLUME OF A CLASS ROOM USING CONSTRUCTOR OVERLOADING
import java.io.*;
27
class Vroom
{
int length,width,height;
Vroom()
{
length=width=height=0;
}
Vroom(int l,int w,int h)
{
length=l;
width=w;
height=h;
}
Vroom(Vroom v)
{
length=v.length;
width=v.width;
height=v.height;
}
int volume()
{
return(length*width*height);
}
}
class Newv
{
public static void main(String args[])throws IOException
{
28
DataInputStream dis=new DataInputStream(System.in);
System.out.println("enter the length");
int i=Integer.parseInt(dis.readLine());
System.out.println("enter the width");
int j=Integer.parseInt(dis.readLine());
System.out.println("enter the height");
int k=Integer.parseInt(dis.readLine());
Vroom v1=new Vroom(i,j,k);
int vol=v1.volume();
System.out.println("Volume="+vol);
}
}
OUTPUT
E:\vee>java New
enter the length
2
enter the width
3
enter the height
4
Volume=24
PROGRAM TO FIND AREA OF DIFFERENT SHAPES USING METHOD OVERLOADING
29
import java.io.*;
class Area
{
void area(int l,int b)
{
int ar=l*b;
System.out.println("Area of rectangle="+ar);
}
void area(double r,double h)
{
double ar=(3.14*r*r*h);
System.out.println("Area of circle="+ar);
}
void area(int a)
{
int ar=a*a;
System.out.println("Area of square="+ar);
}
void area(float b,float h)
{
double ar=0.5*b*h;
System.out.println("Area of triangle="+ar);
}
}
class Newar
{
public static void main(String args[])throws IOException
30
{
Area r=new Area();
DataInputStream dis=new DataInputStream(System.in);
System.out.println("enter length");
int i=Integer.parseInt(dis.readLine());
System.out.println("enter breadth");
int j=Integer.parseInt(dis.readLine());
r.area(i,j);
System.out.println("enter radius");
double k=Double.parseDouble(dis.readLine());
System.out.println("enter height");
double l=Double.parseDouble(dis.readLine());
r.area(k,l);
System.out.println("enter the length of one side");
int m=Integer.parseInt(dis.readLine());
r.area(m);
System.out.println("enter base");
float n=Float.parseFloat(dis.readLine());
System.out.println("enter height");
float o=Float.parseFloat(dis.readLine());
r.area(n,o);
}}
OUTPUT
E:\vee>java Newar
enter length
2
enter breadth
2
31
Area of rectangle=4
enter radius
2
enter height
2
Area of circle=25.12
enter the length of one side
2
Area of square=4
enter base
2
enter height
2
Area of triangle=2.0
PROGRAM TO DISPLAY QUEUE OPERATIONS
32
import java.io.*;
class Demo
{
static final int max=4;
int a[]=new int[max];
int top,it,rear,front;
Demo()
{
rear=-1;
front=-1;
}
void insert(int item)
{
if(rear==max)
System.out.println("Queue is full");
else
{
if(rear==-1)
{
front=0;
rear=0;
}
a[rear++]=item;
}
}
int del()
{
if(front==-1)
33
{
it=0;
}
else
{
it=a[front];
if(front==rear)
{
rear=-1;
front=-1;
}
else
front=front+1;
}
return(it);
}
void display()
{
System.out.println("New Queue Is:");
for(int i=front;i<rear;i++)
System.out.println(a[i]);
}
}
class Queue
{
public static void main(String args[])throws IOException
{
DataInputStream dim=new DataInputStream(System.in);
34
Demo s=new Demo();
int op;
do
{
System.out.println("\n1.insert\n2.delete\n3.display4.exit\n");
op=Integer.parseInt(dim.readLine());
switch(op)
{
case 1:System.out.println("enter the item to insert");
int n=Integer.parseInt(dim.readLine());
s.insert(n);
break;
case 2:int f=s.del();
System.out.println(f);
if(f==0)
{
System.out.println("empty queue:");
}
else
{
System.out.println("Deleted element is:"+f);
}
break;
case 3:s.display();break;
case 4:break;
default:System.out.println("wrong choice?");
}
35
}while(op!=4);
}
}
OUTPUT
E:\3msc\java\joby>java Queue
1.insert
2.delete
3.display4.exit
1
enter the item to insert
1
1.insert
2.delete
3.display4.exit
1
enter the item to insert
2
1.insert
2.delete
3.display4.exit
1
enter the item to insert
3
1.insert
2.delete
3.display4.exit
3
New Queue Is:
36
1
2
3
1.insert
2.delete
3.display4.exit
2
1
Deleted element is:1
1.insert
2.delete
3.display4.exit
3
New Queue Is:
2
3
1.insert
2.delete
3.display4.exit
4
PROGRAM TO FIND THE AREA OF DIFFERENT SHAPES USING METHOD OVERRIDING
37
import java.io.*;
class Figure
{
double x,y;
Figure(double l, double m)
{
x=l;
y=m;
}
}
class Rectangle extends Figure
{
Rectangle(double l, double m)
{
super(l,m);
}
double area()
{
return(x*y);
}
}
class Circle extends Figure
{
final float pi=3.14f;
Circle(double l,double m)
{
super(l,m);
38
}
double area()
{
return(pi*x);
}
}
class Triangle extends Figure
{
Triangle(double d1,double d2)
{
super(d1,d2);
}
double area()
{
return((x*y)/2);
}
}
class Over
{
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
Figure f;
System.out.println("enter the length and breadth");
Rectangle r=new Rectangle(Integer.parseInt(br.readLine()), Integer.parseInt(br.readLine()));
f=r;
System.out.println("the area of the rectangle is"+r.area());
39
System.out.println("enter the radius" );
Circle ci=new Circle(Integer.parseInt(br.readLine()),Integer.parseInt(br.readLine()));
f=ci;
System.out.println("The area of circle is"+ci.area());
System.out.println("Enter the breadth and height");
Triangle t=new Triangle(Integer.parseInt(br.readLine()),Integer.parseInt(br.readLine()));
f=t;
System.out.println("the area of triangle is "+t.area());
}
}
OUTPUT
E:\111msc\java>java Over
enter the length and breadth
2
3
the area of the rectangle is6.0
enter the radius
2
1
The area of circle is6.28000020980835
Enter the breadth and height
3
4
the area of triangle is 6.0
40
AN EXAMPLE FOR DYNAMIC METHOD DISPATCH
class A
{
void display()
{
System.out.println("Inside A");
}
}
class B extends A
{
void display()
{
System.out.println("Inside B");
}
}
class C extends B
{
void display()
{
System.out.println("Inside C");
}
}
class OverrideDemo
{
public static void main(String arg[])
{
A a=new A();
B b=new B();
41
C c=new C();
A r;
r=a;
r.display();
r=b;
r.display();
r=c;
r.display();
}
}
OUTPUT
E:\111msc\java>java OverrideDemo
Inside A
Inside B
Inside C
42
PROGRAM TO FIND ROOTS OF QUADRATIC EQUATION BY USING PACKAGE AND INTERFACE
QuadEqn.java
package p;
interface Quadratic
{
void process();
}
public class QuadEqn implements Quadratic
{
double a,b,c,d;
public QuadEqn(double x,double y,double z)
{
a=x;
b=y;
c=z;
}
public void process()
{
d=b*b-(4*a*c);
if(d==0)
{
double r=-b/2*a;
System.out.println("Roots are equal.Root=\t"+r);
}
else
if(d>0)
43
{
double sq=Math.sqrt(d);
double r1=(-b+sq)/2*a;
double r2=(-b-sq)/2*a;
System.out.println("Root1=\t"+r1+"\nRoot2=\t"+r2);
}
else
System.out.println("Roots are imaginary\n");
}
}
QuadM.java
import java.io.*;
import p.QuadEqn;
class QuadM
{
public static void main(String arg[])throws IOException
{
try
{
DataInputStream dis=new DataInputStream(System.in);
System.out.println("Enter the values of a,b,c\n");
double p=Double.parseDouble(dis.readLine());
double q=Double.parseDouble(dis.readLine());
double r=Double.parseDouble(dis.readLine());
QuadEqn ob=new QuadEqn(p,q,r);
ob.process();
}
catch(Exception e)
44
{
System.out.println("Error..."+e);
}
}
}
OUTPUT
E:\3msc\java\liya>java QuadM
Enter the values of a,b,c
1
3
2
Root1= -1.0
Root2= -2.0
45
PROGRAM TO DISPLAY MARK LIST OF N STUDENTS USING PACKAGE
StudPack.java
package p;
public class StudPack
{
int id,m1,m2,tot;
String n;
public void getdata(int num,String name,int mark1,int mark2)
{
id=num;
n=name;
m1=mark1;
m2=mark2;
tot=m1+m2;
}
public void display()
{
System.out.println("\n*******Student's Details*******");
System.out.println("Roll no:"+id+"\nName="+n+"\nEnglish="+m1+"\nScience="+m2+"\nTotal="+tot);
}
}
Student.java
import p.StudPack;
import java.io.*;
class Student
{
46
public static void main(String arg[])throws IOException
{
StudPack obj=new StudPack();
DataInputStream dis=new DataInputStream(System.in);
System.out.println("Enter the total no:of students\n");
int n=Integer.parseInt(dis.readLine());
for(int i=0;i<n;i++)
{
System.out.println("Enter the Roll no:,Name,Mark1,Mark2of student of\t"+(i+1));
int a=Integer.parseInt(dis.readLine());
String b=dis.readLine();
int c=Integer.parseInt(dis.readLine());
int d=Integer.parseInt(dis.readLine());
obj.getdata(a,b,c,d);
obj.display();
}
}
}
OUTPUT
E:\3msc\java\liya>java Student
Enter the total no:of students
2
Enter the Roll no:,Name,Mark1,Mark2of student of 1
102
Emilu
50
47
46
*******Student's Details*******
Roll no:102
Name=Emilu
English=50
Science=46
Total=96
Enter the Roll no:,Name,Mark1,Mark2of student of 2
103
Sandra
50
50
*******Student's Details*******
Roll no:103
Name=Sandra
English=50
Science=50
Total=100
PROGRAM TO SORT N STRINGS USING IOSTREAM
48
import java.io.*;
class Dem21
{
public static void main(String args[])throws IOException
{
BufferedReader b=new BufferedReader(new InputStreamReader(System.in));
int i,j,n=0;
String s1;
System.out.println("enter the array size:");
try
{
n=Integer.parseInt(b.readLine());
String s[]=new String[n];
System.out.println("enter the strings:");
for(i=0;i<n;i++)
{
s[i]=b.readLine();
}
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(s[i].compareTo(s[j])>0)
{
String tmp=s[i];
s[i]=s[j];
s[j]=tmp;
}
49
}
}
System.out.println("sorted names are:");
for(i=0;i<n;i++)
{
System.out.println(s[i]+"\t");
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
OUTPUT
E:\3msc\java\meenu>java Dem21
enter the array size:
3
enter the strings:
Rini
Geethu
Arya
sorted names are:
Arya
Geethu
Rini
50
PROGRAM TO CHECK WHETHER THE STRINGS ARE PALINDROME OR NOTimport java.io.*;
class Dem20
{
public static void main(String args[])throws IOException
{
BufferedReader b=new BufferedReader(new InputStreamReader(System.in));
int i,n=0;
String s1;
try
{
System.out.println("enter the size of array:");
n=Integer.parseInt(b.readLine());
String s=new String[n];
System.out.println("enter the string:");
for(i=0;i<n;i++)
{
s[i]=b.readLine();
}
for(i=0;i<n;i++)
{
StringBuffer sb=new StringBuffer(s[i]) ;
s1=new String(sb.reverse());
if(s[i].equals(s1))
{
System.out.println("String is"+s[i]+""+"palindrome");
}
51
else
{
System.out.println("String is"+s[i]+""+"not palindrome");
}
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
OUTPUT
E:\3msc\java\meenu>java Dem20
enter the size of array:
3
enter the string:
aba
joby
jiss
String is aba palindrome
String is joby not palindrome
String is jiss snot palindrome
. PROGRAM TO FIND PRODUCT OF TWO METRICES
52
import java.io.*;
class Mult
{
int c[][]=new int[3][3];
void process(int a[][],int b[][],int m,int n,int p,int q)
{
for(int i=0;i<m;i++)
for(int j=0;j<q;j++)
{
c[i][j]=0;
for(int k=0;k<n;k++)
{
c[i][j]+=a[i][k]*b[k][j];
}
}
System.out.print("Product of two metrices is"+"\n");
for(int i=0;i<m;i++)
{
for(int j=0;j<q;j++)
{
System.out.print(c[i][j]+"\t");
}
System.out.print("\n");
}
}
};
class MatrixMult
{
53
public static void main(String arg[])throws IOException
{
Mult am=new Mult();
int m,n,p,q,i,j,k;
int a[][]=new int[3][3];
int b[][]=new int[3][3];
DataInputStream dis=new DataInputStream(System.in);
System.out.println("Enter the order of first matrix");
m=Integer.parseInt(dis.readLine());
n=Integer.parseInt(dis.readLine());
System.out.println("Enter the first matrix");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
a[i][j]=Integer.parseInt(dis.readLine());
System.out.println("Enter the order of second matrix");
p=Integer.parseInt(dis.readLine());
q=Integer.parseInt(dis.readLine());
System.out.println("Enter the second matrix");
for(i=0;i<p;i++)
for(j=0;j<q;j++)
b[i][j]=Integer.parseInt(dis.readLine());
am.process(a,b,m,n,p,q);
}
}
OUTPUT
E:\3msc\java\liya>java MatrixMult
Enter the order of first matrix
54
2
2
Enter the first matrix
2
2
2
2
Enter the order of second matrix
2
2
Enter the second matrix
2
2
2
2
Product of two metrices is
8 8
8 8
55
AN EXAMPLE FOR MULTITHREADING AND VARIOUS THREAD METHODSclass A extends Thread
{
public void run()
{
try
{
for(int i=0;i<=15;i++)
{
System.out.println("In thread A\t"+i);
if(i==10)
sleep(100);
}
}
catch(Exception e)
{
System.out.println("Exception"+e);
}
}
}
class B extends Thread
{
public void run()
{
for(int j=0;j<=15;j++)
{
System.out.println("In thread B\t"+j);
56
if(j==0) yield();
}
}
}
class C extends Thread
{
public void run()
{
for(int k=0;k<=15;k++)
{
System.out.println("In thread C\t"+k);
if(k==10) stop();
}
}
}
class Multthread
{
public static void main(String arg[])
{
A obj1=new A();
B obj2=new B();
C obj3=new C();
obj1.start();
obj2.start();
obj3.start();
}
57
}
OUTPUT
E:\3msc\java\liya>java Multthread
In thread B 0
In thread A 0
In thread C 0
In thread B 1
In thread A 1
In thread C 1
In thread B 2
In thread A 2
In thread C 2
In thread B 3
In thread A 3
In thread C 3
In thread B 4
In thread A 4
In thread C 4
In thread B 5
In thread A 5
In thread C 5
In thread B 6
In thread A 6
In thread C 6
In thread B 7
In thread A 7
In thread C 7
In thread B 8
58
In thread A 8
In thread C 8
In thread B 9
In thread A 9
In thread C 9
In thread B 10
In thread A 10
In thread C 10
In thread B 11
In thread B 12
In thread B 13
In thread B 14
In thread B 15
In thread A 11
In thread A 12
In thread A 13
In thread A 14
In thread A 15
59
PROGRAM TO THROW AN USER DEFINED EXCEPTIONimport java.*;
class Myexception extends Exception
{
Myexception(String n)
{
super(n);
}
}
class Throwdemo
{
public static void main(String arg[])
{
Myexception me=new Myexception("This is from me");
try
{
throw me;
}
catch(Myexception g)
{
System.out.println(g);
}
}
}
OUTPUT
E:\3msc\java\joby>java Throwdemo
Myexception: This is from me
60
PROGRAM TO DISPLAY A MOVING BANNER USING APPLETimport java.awt.*;
61
import java.applet.*;
//<applet code=Movingb width=100 height=100></applet>
public class Movingb extends Applet implements Runnable
{
String s="MOVING BANNER";
Thread t=null;
boolean flag;
public void init()
{
setBackground(Color.red);
setForeground(Color.blue);
}
public void start()
{
t=new Thread(this);
flag=false;
t.start();
}
public void run()
{
char ch;
for(; ;)
try
{
repaint();
Thread.sleep(1000);
ch=s.charAt(0);
s=s.substring(1,s.length());
62
s=s+ch;
if(flag==true)
break;
}
catch(InterruptedException ie)
{
}
}
public void stop()
{
flag=true;
t=null;
}
public void paint(Graphics g)
{
g.drawString(s,200,200);
}
}
OUTPUT
PROGRAM TO DRAW A HUMAN FACE USING APPLET
63
import java.applet.*;
import java.awt.*;
import java.util.*;
import java.awt.event.*;
//<applet code=Face width=300 height=300></applet>
public class Face extends Applet
{
public void init()
{
setBackground(Color.red);
setForeground(Color.green);
}
public void paint(Graphics g)
{
Font f=new Font("Arial",Font.BOLD,20);
g.setFont(f);
g.drawOval(40,40,120,150);
g.drawOval(57,75,30,20);
g.drawOval(110,75,30,20);//eye
g.fillOval(68, 81,10,10);
g.fillOval(121, 81,10,10);
g.drawOval(85, 100,30,30);
g.drawOval(25, 92,15,30);
g.drawOval(160,90,15,30);
64
g.fillArc(60,125,80,40,180,180);
g.drawOval(160,90,15,30);
}
}
OUTPUT
E:\msc3\jiss\java>javac Face.java
E:\msc3\jiss\java>appletviewer Face.java
65
PROGRAM TO PERFORM ARITHMETIC OPERATIONS USING AWT CONTROLS
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.Choice.*;
//<applet code=Awte width=500 height=555></applet>
public class Awte extends Applet implements TextListener,ActionListener
{
int a,b,c;
String s;
TextField f1,f2,f3;
Label l1,l2,l3;
Button Add,Sub,Mul,Div;
public void init()
{
//setBackground(Color.green);
setForeground(Color.red);
l1=new Label("First number");
l2=new Label("Second number");
l3=new Label("Result");
f1=new TextField(10);
f2=new TextField(20);
f3=new TextField(20);
//f3=new TextField(20);
//f2.setEchochar("*");
add(l1);
add(f1);
add(l2);
66
add(f2);
add(l3);
add(f3);
Add=new Button("Add");
Sub=new Button("Sub");
Mul=new Button("Mult");
Div=new Button("Div");
add(Add);
add(Sub);
add(Mul);
add(Div);
f1.addTextListener(this);
f2.addTextListener(this);
f3.addTextListener(this);
Add.addActionListener(this);
Sub.addActionListener(this);
Mul.addActionListener(this);
Div.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
a=Integer.parseInt(f1.getText());
b=Integer.parseInt(f2.getText());
if(ae.getActionCommand().equals("Add"))
c=a+b;
else if(ae.getActionCommand().equals("Sub"))
c=a-b;
67
else if(ae.getActionCommand().equals("Mult"))
c=a*b;
else
c=a/b;
s=String.valueOf(c);
repaint();
}
public void textValueChanged(TextEvent te)
{
}
public void paint(Graphics g)
{
f3.setText(s);
//g.drawString(String.valueOf(c),355,355);
}
}
OUTPUT
E:\msc3\jiss\java>javac awte.java
E:\msc3\jiss\java>appletviewer awte.java
68
69
PROGRAM TO DISPLAY MOUSE EVENTSimport java.applet.*;
import java.awt.*;
import java.awt.event.*;
//<applet code=Eventapplet width=100 height=150></applet>
public class Eventapplet extends Applet implements MouseListener,MouseMotionListener
{
String msg=" ";
int x=0;
int y=0;
public void init()
{
setBackground(Color.pink);
addMouseListener(this);
addMouseMotionListener(this);
}
public void mousePressed(MouseEvent me)
{
x=me.getX();
y=me.getY();
msg="pressed";
repaint();
}
public void mouseExited(MouseEvent me)
{
}
public void mouseEntered(MouseEvent me)
{
}
70
public void mouseReleased(MouseEvent me)
{
}
public void mouseClicked(MouseEvent me)
{
}
public void mouseDragged(MouseEvent me)
{
}
public void mouseMoved(MouseEvent me)
{
}
public void paint(Graphics g)
{
g.drawString(msg,100,200);
}
}
OUTPUT
E:\msc3\jilu\java>javac Eventapplet.java
E:\msc3\jilu\java>appletviewer Eventapplet.java
71
PROGRAM TO DISLAY THE SUM OF TWO NUMBERS USING RMI
AddServerInf .java
import java.rmi.*;
public interface AddServerInf extends Remote
{
public double add(double d1,double d2) throws RemoteException;
}
AddServerImpl.java
import java.rmi.*;
import java.rmi.server.*;
public class AddServerImpl extends UnicastRemoteObject implements AddServerInf
{
AddServerImpl()throws RemoteException
{
}
public double add(double d1,double d2)throws RemoteException
{
return(d1+d2);
}
}
AddServer.java
import java.rmi.*;
import java.net.*;
public class AddServer
72
{
public static void main(String arg[])
{
try
{
AddServerImpl asi=new AddServerImpl();
Naming.rebind("addserver",asi);
}
catch(Exception e)
{
System.out.print("Error......addserver "+e);
}
}
}
AddClient.java
import java.rmi.*;
public class AddClient
{
public static void main(String arg[])
{
try
{
String url="rmi://"+arg[0]+"/addserver";
AddServerInf asi=(AddServerInf) Naming.lookup(url);
System.out.println("The first no is"+arg[1]);
System.out.println("The second no is"+arg[2]);
double d1=Double.parseDouble(arg[1]);
73
double d2=Double.parseDouble(arg[2]);
System.out.println("The sum is"+asi.add(d1,d2));
}
catch(Exception e)
{
System.out.print("Error....addclient"+e);
}
}
}
OUTPUT
E:\3msc>cd java
E:\3msc\java>cd liya
E:\3msc\java\liya>path=e:\jdk1.5.0\bin
E:\3msc\java\liya>javac AddServerInf.java
E:\3msc\java\liya>javac AddServerImpl.java
E:\3msc\java\liya>javac AddServer.java
E:\3msc\java\liya>javac AddClient.java
E:\3msc\java\liya>rmic AddServerImpl
E:\3msc\java\liya>start rmiregistry
74
E:\3msc\java\liya>java AddServer
E:\3msc\java\liya>java AddClient 127.0.0.1 5.0 5.0
The first no is5.0
The second no is5.0
The sum is10.0
75
PROGRAM TO FIND THE FACTORIAL OF A NUMBER USING RMI
FactServerInf.java
import java.rmi.*;
public interface FactServerInf extends Remote
{
public double fact(double d1) throws RemoteException;
}
FactServerImpl.java
import java.rmi.*;
import java.rmi.server.*;
public class FactServerImpl extends UnicastRemoteObject implements FactServerInf
{
FactServerImpl()throws RemoteException
{
}
public double fact(double d1)throws RemoteException
{
double f=1;
for(int i=1;i<=d1;i++)
{
f=f*i;
}
return(f);
}
}
FactServer.java
import java.rmi.*;
76
import java.net.*;
public class FactServer
{
public static void main(String arg[])
{
try
{
FactServerImpl asi=new FactServerImpl();
Naming.rebind("factserver",asi);
}
catch(Exception e)
{
System.out.print("Error......factserver "+e);
}
}
}
FactClient.java
import java.rmi.*;
import java.net.*;
public class FactClient
{
public static void main(String arg[])
{
double v1=Double.parseDouble(arg[1]);
try
{
77
String url="rmi://"+arg[0]+"/factserver";
FactServerInf asi=(FactServerInf) Naming.lookup(url);
System.out.println("The factorial is"+(asi.fact(v1)));
}
catch(Exception e)
{
System.out.print("Error....addclient"+e);
}
}
}
OUTPUT
E:\3msc\java\liya>javac FactServerInf.java
E:\3msc\java\liya>javac FactServerImpl.java
E:\3msc\java\liya>javac FactServer.java
E:\3msc\java\liya>javac FactClient.java
E:\3msc\java\liya>rmic FactServerImpl
E:\3msc\java\liya>start rmiregistry
E:\3msc\java\liya>java FactServer
E:\3msc\java\liya>java FactClient 127.0.0.1 5.0
The factorial is120.0
78
ORACLE
79
80
QUERY EXAMPLE 1
consider the following schema:-
student1(rollno,name,mark)
1.create a table
2.insert values into the table
3.update a row
4.delete a row
5.aggregate functions
6.alter table
7.drop table
OUT PUT
1.Create a table
SQL> create table student1(rollno int,name varchar(10),mark int);
Table created.
2.Inserting values into the table
SQL> insert into student1 values(1,'anu',320);
1 row created.
SQL> insert into student1 values(2,'jilu',330);
1 row created.
SQL> insert into student1 values(3,'jiss',340);
1 row created.
SQL> insert into student1 values(4,'joby',350);
1 row created.
SQL> insert into student1 values(5,'liya',325);
81
1 row created.
SQL> insert into student1 values(6,'meenu',326);
1 row created.
SQL> select * from student1;
ROLLNO NAME MARK
---------- ---------- ----------
1 anu 320
2 jilu 330
3 jiss 340
4 joby 350
5 liya 325
6 meenu 326
6 rows selected.
3.Update a row
SQL> update student1 set name='sruthi' where rollno=1;
1 row updated.
SQL> select * from student1;
ROLLNO NAME MARK
---------- ---------- ----------
1 sruthi 320
2 jilu 330
3 jiss 340
4 joby 350
82
5 liya 325
6 meenu 326
6 rows selected.
4.Delete a row
SQL> delete student1 where rollno=2;
1 row deleted.
SQL> select * from student1;
ROLLNO NAME MARK
---------- ---------- ----------
1 sruthi 320
3 jiss 340
4 joby 350
5 liya 325
6 meenu 326
5. Aggregate functions
SQL> insert into student1 values(7,'shaney',300);
1 row created.
83
SQL> select * from student1;
ROLLNO NAME MARK
---------- ---------- ----------
1 sruthi 320
3 jiss 340
4 joby 350
5 liya 325
6 meenu 326
7 shaney 300
6 rows selected.
SQL> select * from student1 where mark>340;
ROLLNO NAME MARK
---------- ---------- ----------
4 joby 350
SQL> select max(mark) from student1;
MAX(MARK)
----------
350
SQL> select min(mark) from student1;
84
MIN(MARK)
----------
300
SQL> select avg(mark)from student1;
AVG(MARK)
----------
326.833333
SQL> select count(rollno) from student;
COUNT(ROLLNO)
-------------
6
SQL> select count(rollno) from student1;
COUNT(ROLLNO)
-------------
6
SQL> select sum(mark) from student1;
SUM(MARK)
----------
85
1961
6. Alter table
SQL> alter table student1 add(address varchar(20));
Table altered.
SQL> select * from student1;
ROLLNO NAME MARK ADDRESS
---------- ---------- ---------- --------------------
1 sruthi 320
3 jiss 340
4 joby 350
5 liya 325
6 meenu 326
7 shaney 300
6 rows selected.
SQL> alter table student1 drop column address;
Table altered.
SQL> select * from student1;
86
ROLLNO NAME MARK
---------- ---------- ----------
1 sruthi 320
3 jiss 340
4 joby 350
5 liya 325
6 meenu 326
7 shaney 300
6 rows selected.
SQL> alter table student1 modify(name varchar(20));
Table altered.
SQL> select * from student1;
ROLLNO NAME MARK
---------- -------------------- ----------
1 sruthi 320
3 jiss 340
4 joby 350
5 liya 325
6 meenu 326
7 shaney 300
87
6 rows selected.
7. Drop table
SQL> drop table student1;
Table dropped.
SQL> select * from student1;
select * from student1
*
ERROR at line 1:
ORA-00942: table or view does not exist
88
QUERY EXAMPLE 2
Consider the following schema:-
emp1(empno,empname,salary)
dept(deptno,deptname,manager)
Write the following queries in oracle and find the output
OUT PUT
table 1: emp1
empno deptn empname salary
------ -------- ----------------- ----------
101 d1 aaa 1000
102 d2 bbb 2000
103 d3 ccc 3000
104 d2 ddd 40000
105 d1 eee 30000
106 cr 20000
Table 2:dept
deptn deptname manager
----- --------------- -------------
d1 accounts mr.x
d2 management mr.y
d3 computer mr.z
1.List the employees working in accounts department
SQL>select empname from emp1 where deptno=(select deptno from dept1 where deptname='accounts');
89
empname
-------------------
aaa
eee
2.Find the employees drawing salary higher than the lowest salary in accounts department
SQL> select empname from emp1 where salary>(select min(salary) from emp1 where deptno=(select deptno
from dept1 where deptname='accounts'));
empname
--------------------
bbb
ccc
ddd
eee
3.List the employees working under the manager mr.x
SQL> select empname,empno from emp1 where deptno=(select deptno from dept1 where manager='mr.x');
empname empno
-------------------- ----------
aaa 101
eee 105
4.find the avg salary of accounts department
90
SQL> select avg(salary) from emp1 where deptno=(select deptno from dept1 where deptname='accounts');
AVG(salary)
-----------
15500
5.List the employees who have not assigned to any department
SQL> select empname from emp1 where deptno = ' ';
empname
--------------------
cr
91
QUERY EXAMPLE 3
Consider the following schema
Employee(employeename,street,city)
Works(employeename,companyname,salary)
Company(companyname,city)
Manager(employeename,managername)
Write the following queries in oracle and find the output
OUTPUT
EMPLOYEENAME STREET CITY
-------------------- -------------------- ----------
Raju springvally kumily
Sumesh rosegarden Kottayam
Sunil bluerose pala
Anil songlers mavalikara
Denny maxiano kayamkulam
John backhills idukki
Deepak springvally kumily
Table 2.WORKS
EMPLOYEENAME COMPANYNAME SALARY
-------------------- -------------------- ----------
Raju firstbank 9000
Sumesh infovista 12500
Sunil infovista 11000
Anil focus 12300
92
Denny focus 10800
John focus 10800
Denny indiaoptions 8800
Deepak firstbank 12700
Table 3.COMPANY
COMPANYNAME CITY
-------------------- -------------
firstbank kumily
infovista thodupuzha
focus attingal
indiaoptions thiruvalla
Table 4.MANAGER
EMPLOYEENAME MANAGERNAME
-------------------- --------------
Raju mr x
Sunil mr y
Sumesh mr z
Anil mr a
Denny mr b
John mr c
Deepak mr d
(1) Find the names of all employees who work for 'first bank'
Ans;
SQL> select employeename from Works where companyname='firstbank';
93
EMPLOYEENAME
--------------------
Raju
Deepak
(2) Find names ,street address and coties of residence of all employee who work for 'first bak' and earn more than 10,000 per annum
SQL> select employeename,street ,city from Employee where employeename=(select employeename from
Works where companyname='firstbank' and salary>10000);
Ans;
EMPLOYEENAME STREET CITY
-------------------- -------------------- --------------------
Deepak springvally kumily
(3)Find the names of all employees in this databae who ilive in same city as the company for wich they work
SQL> select e.employeename from Employee e, company c where e.city=c.city;
EMPLOYEENAME
--------------------
Raju
Deepak
94
QUERY EXAMPLE 4
Consider the following schema
Employee(emp_name,street,city)
Work1(emp_name,com_name,salary)
Company(com_name,city)
Write the following queries in oracle and find the output
OUT PUT
SQL> select * from Work1;
EMPNAME COMPANYNAME SALARY
----------------- ----------------------------- -------------------------
johan hcl 20000
ishan ipsr 60000
jennifer satyam 300000
kathi wipro 10000
saira infosys 12000
SQL> select * from Employe1;
EMPNAME STREET CITY
------------------- ------------- ----------
johan rosestreet ktm
ishan backstret ekm
jennifer crossroad tvm
kathi heavenly pala
saira bluerose idk
SQL> select *from Company1;
95
COMPANYNAME CITY
-------------------- --------------------
hcl tvm
ipsr ktm
satyam ekm
Retrieving data from multiple table
Find all the employees in the database who lived in the same city and as the company for which they work
SQL> select Employe1.empname from Employe1,Company1,Work1 where Employe1.empname=Work1.empname and Work1.companyname=Company1.companyname and Employe1.city=Company1.city;
EMPNAME
-----------------
Mishel
Subquery
Find all employees in the database who earn more than employee of ipsr who earn the minimum salary
SQL> select empname from Work1 where salary>(select min(salary) from Work1 where companyname='ipsr');
EMPNAME
----------
ishan
Jennifer
Group-by/Having
Find the company that has the most employes
96
SQL> select companyname from Work1 group by companyname having count(empname)>=(select max(count(empname))from Work1 group by companyname);
COMPANYNAME
---------------------------
ipsr
97