Sei sulla pagina 1di 98

MAEERs MIT School of Management | Pune | India

Java Programming IT-41


MCA-II Sem-IV

Samarpit gandhi (14MCA041)

Lab Work -1
Topic: Chapter-1(Fundamentals of Java)
1 Write a program to check whether a given number is armstrong or
not.
import java.io.*;
public class Program1
{
static int power(int n, int r)
{
int c, p = 1;
for (c = 1; c <= r; c++)
p = p*n;
return p;
}
public static void main(String args[])throws
Exception

{
int n, sum=0, temp, remainder, count=0;
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
System.out.print("\n\n\t\t\t Enter number :- ");
n = Integer.parseInt(br.readLine());
temp = n;
while(temp!=0)
{
count++;
temp = temp/10;
}
temp = n;
while(temp!=0)
{
remainder = temp%10;
sum = sum + power(remainder,count);
temp = temp/10;
}
if( n == sum )
System.out.print("\n\n\t\t\t
Number
is
Armstrong...!\n\n");
else
System.out.print("\n\n\t\t\t Number is not
Armstrong...!\n\n");
}
}

2.Write a program to calculate and print the first n Fibonacci numbers.

import java.io.*;
public class Program3
{
public static void main(String args[])throws Exception
{
int febCount = 15;
int[] feb = new int[febCount];
feb[0] = 0;
feb[1] = 1;
for(int i=2; i<febCount ; i++)

{
feb[i] = feb[i-1] + feb[i-2];
}
System.out.print("\n\n\t\t\t first 15 fibonecci series :");
for(int i=2; i<febCount ; i++)
{
System.out.print("\n\n\t\t\t\t"+feb[i]);
}
System.out.print("\n\n");
}
}

2 Write a program to print the following outputs using for loops.


a *********

****
***
***
**
**
**
**
***
***
*********

****

import java.io.*;
public class Program4
{
public static void main(String args[])throws Exception
{
int n;
BufferedReader
br
=
new
BufferedReader(new
InputStreamReader(System.in));
System.out.print("\n\n\n\t\t\t Enter length of the pattern :- ");
n = Integer.parseInt(br.readLine());
for (int i = 1; i <= n; i++)
{
for (int j = 0; j < (n - i); j++)
System.out.print("*");
for (int j = 1; j <= i; j++)
System.out.print(" ");
for (int k = 1; k < i; k++)
System.out.print(" ");
System.out.println();
}
for (int i = n - 1; i >= 1; i--)
{
for (int j = 0; j < (n - i); j++)
System.out.print("*");
for (int j = 1; j <= i; j++)
System.out.print(" ");
for (int k = 1; k < i; k++)
System.out.print(" ");
System.out.println();
}
for (int i = 1; i <= n; i++)

{
for (int j = 0; j < (n - i); j++)
System.out.print(" ");
for (int j = 1; j <= i; j++)
System.out.print("*");
for (int k = 1; k < i; k++)
System.out.print("*");
System.out.println();
}
for (int i = 1 ; i<=n; i++)
{
for (int j = 0; j < (n - i); j++)
System.out.print(" ");
for (int j = 1; j <= i; j++)
System.out.print("*");
for (int k = 1; k < i; k++)
System.out.print("*");
System.out.println();
}
}
}

Lab Work -2
Topic: Chapter-1(Fundamentals of Java)

1 Write a program to accept employee information such as Emp_id,


Name, Designation and Salary using parameterized constructor and
display the same.
import java.io.*;
public class Program1
{
int empID;
String name, designation;
double salary;
Program1(int eID, String name, String designation, double sal)
{
this.empID = eID;
this.name = name;
this.designation = designation;
this.salary = sal;
}
public void display()
{
System.out.print("\n\n\t\t Employee details :- ");
System.out.print("\n\n\n\t\t\t\t
Employee
ID
"+empID);
System.out.print("\n\n\t\t\t\t Name :- "+name);
System.out.print("\n\n\t\t\t\t
Designation
"+designation);
System.out.println("\n\n\t\t\t\t salary :- "+salary);
}

::-

public static void main(String args[])


{
try
{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
System.out.print("\n\n\t\t\t Employee name :- ");
String name = br.readLine();
System.out.print("\n\n\t\t\t Employee ID :- ");
int empID = Integer.parseInt(br.readLine());
System.out.print("\n\n\t\t\t Designation :- ");
String designation = br.readLine();
System.out.print("\n\n\t\t\t salary :- ");

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


Program1

new

Program1(empID,

name,

designation, sal);
p.display();
}
catch(Exception e)
{}
}
}

2.Write a program to accept five elements in an array and find the


median from given numbers.
import java.io.*;
import java.util.*;

public class Program2


{
int[] arr = new int[5] ;

public static void main(String args[])


{

int medianPos;
try
{
BufferedReader
InputStreamReader(System.in));

br

new

BufferedReader(new

Scanner sc = new Scanner(System.in);

System.out.print("\n\n\n\t\t Enter an array of 5 :- ");

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


{

arr[i] = sc.nextInt();

if(i==4)
{
medianPos = 5/2;
System.out.print("\n\n\n\t\t\t
"+arr[medianPos]);
}
}

}
catch(Exception e)
{}
}
}

3.Write a program to multiply 3*3 matrices.

Median

:-

import java.io.*;
import java.util.*;
public class Program3
{
public static void main(String args[])
{
int m,n,p,q;
int sum = 0,c,d,k;
int firstM[][] = new int[3][3];
int secondM[][] = new int[3][3];
int mult[][] = new int[3][3];
try
{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
Scanner sc = new Scanner(System.in);
System.out.print("\n\n\n\t\t Enter elements in First
matrix :- \n\n");
for( c = 0 ; c < 3 ; c++ )
{
for( d = 0; d<3; d++ )
firstM[c][d] = sc.nextInt();
}
System.out.print("\n\n\n\t\t Enter elements
Second matrix :- \n\n");
for( c = 0 ; c < 3 ; c++ )
{
for( d = 0; d<3; d++ )
secondM[c][d] = sc.nextInt();
}

in

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


{
for( d=0 ; d<3 ; d++ )
{
for( k=0 ; k < 3 ; k++ )
{
sum
= sum + firstM[c][k] *
secondM[k][d];
}
mult[c][d] = sum;
sum = 0;
}
}

System.out.print("\n\n\n\t\t\t

Multiplication

of

matrices :- \n\n");
for( c = 0 ; c < 3 ; c++ )
{
for( d = 0; d<3; d++ )
System.out.print("\t "+mult[c][d]);
System.out.print("\n");
}
}
catch(Exception e)
{}
}
}

Lab Work -3
Topic: Chapter-1(Inheritance Polymorphism )
1

Write a Java program can contain two classes: Computer and Laptop. Both
classes have their own constructors and a method. In main method create object
of two classes and call their methods.

import java.io.*;

class Computer
{
Computer()
{

}
public void display()
{
System.out.print("\n\n\t\t This is Computer...!");
}
}

class Laptop
{
Laptop()
{

}
public void display()
{
System.out.print("\n\n\t\t This is Laptop...!\n\n");
}
}

public class Program1


{
public static void main(String args[])
{
Computer c = new Computer();

Laptop l = new Laptop();

c.display();
l.display();
}
}

Create person class with data members as person_id & name. Derive two classes
Student & faculty from it. The fields of Student are course name & fees paid.
The fields of faculty are subject name & number of years experience. Use proper
method to accept values & override display method. (Using parameterized
constructor)
import java.io.*;
class Person
{
int personID;
String name;

public void getData()throws Exception


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

BufferedReader(new

System.out.print("\n\n\n\t\t Enter person ID :- ");


personID = Integer.parseInt(br.readLine());
System.out.print("\n\n\n\t\t Name:- ");
name = br.readLine();
}
public void display()
{
System.out.print("\n\n\t\t\t Person ID :- "+personID);
System.out.print("\n\n\t\t\t Name :- "+name);
}
}
class Student extends Person
{
String courseName;
double feesPaid;

public void getData()throws Exception


{
super.getData();
BufferedReader
br
=
new
InputStreamReader(System.in));

BufferedReader(new

System.out.print("\n\n\n\t\t Course Name :- ");


courseName = br.readLine();
System.out.print("\n\n\n\t\t Fees paid :- ");
feesPaid = Double.parseDouble(br.readLine());
}
public void display()
{
super.display();
System.out.print("\n\n\t\t\t Course :- "+courseName);
System.out.print("\n\n\t\t\t Fees Paid :- "+feesPaid);
}
}
class Faculty extends Person
{

String subjectName;
int experience;

public void getData()throws Exception


{
super.getData();
BufferedReader
br
=
new
InputStreamReader(System.in));

BufferedReader(new

System.out.print("\n\n\n\t\t Subject Name :- ");


subjectName = br.readLine();
System.out.print("\n\n\n\t\t Experience :- ");
experience = Integer.parseInt(br.readLine());
}
public void display()
{
super.display();
System.out.print("\n\n\t\t\t Subject :- "+subjectName);
System.out.print("\n\n\t\t\t Experience :- "+experience);
}
}
public class Program2
{
public static void main(String args[])throws Exception
{
Student s = new Student();
Faculty f = new Faculty();
s.getData();
f.getData();
s.display();
f.display();
}
}

3.Your program will consist of the following classes: Shape, Circle, Square, Cube,
Sphere, Cylinder, and Glome and two interfaces Area and Volume (Area.java
and Volume.java are given below).
Your classes may only have the class variable specified in the table below and the
methods defined in the two interfaces Area and Volume. You will implement the
methods specified in the Area and Volume interfaces and have them return the
appropriate value for each shape. Class Shape will have a single public method
called getName that returns a string.
import java.io.*;
interface Area
{
public void getArea();
}
interface Volume
{
public void getVolume();
}
class Shape
{
String name;
Shape(String n)

{
this.name = n;
}
public void getName()
{
}
}
class Circle extends Shape implements Area
{
double radius;
Circle(double r, String n)
{
super(n);
this.radius = r;
}
public void getArea()
{
}
}
class Square extends Shape implements Area
{
double side;
Square(double s, String n)
{
super(n);
this.side = s;
}
public void getArea()
{
}
}
class Cylinder extends Circle implements Volume
{
double heigth;
Cylinder(double h, String n)
{
super(h,n);
}
public void getVolume()
{
}
}
class Sphere extends Circle implements Volume
{
Sphere(double r, String n)

{
super(r,n);
}
public void getVolume()
{
}
}
class Cube extends Square implements Volume
{
Cube(double s, String n)
{
super(s,n);
}
public void getVolume()
{
}
}
class Glome extends Sphere implements Volume
{
Glome(double r, String n)
{
super(r,n);
}
public void getVolume()
{
}
}

Lab Work - 4
Topic: Chapter-1(Polymorphism)
1

Create 3 classes Circle, Rectangle & Triangle. Use area() method to display
area of respective shape.( Use method overloading)
import java.io.*;

class Circle
{
public void area(double r)
{
double area = 3.14*r*r;
System.out.print("\n\n\t\t\t Area of Circle :- "+area);
}
}

class Rectangle
{
public void area(double length, double width)
{
double area = length * width;
System.out.print("\n\n\t\t\t Area of Rectangle :- "+area);
}
}

class Triangle
{
public void area(double h, double base)
{
double area = (h*base)/2;
System.out.print("\n\n\t\t\t Area of Circle :- "+area);
}
}

public class Program1


{
public static void main(String args[])
{
Circle c = new Circle();
Rectangle r = new Rectangle();
Triangle t = new Triangle();

c.area(10);
r.area(15,15);
t.area(20,20);

2.Create a class mobile containing company name, mobile number & cost and write
necessary member functions for the following:
a. Search the mobile number with given name.
b. Search the name with given telephone number. (Use method overloading)
import java.io.*;
class Mobile
{
String[] name;
int[] mobNo;
double[] cost;
int n;
public void getData()throws Exception
{
BufferedReader
br
=
new
InputStreamReader(System.in));

BufferedReader(new

System.out.print("n\n\t\t How many contacts?");


n = Integer.parseInt(br.readLine());

name = new String[n];


mobNo = new int[n];
cost = new double[n];
System.out.print("\n\n\t\t Enter details of customer :- ");
for(int i =0 ; i<n ; i++)
{
System.out.print("\n\n\t\t\t Name :- ");
name[i] = br.readLine();
System.out.print("\n\n\t\t\t Mobile number :- ");
mobNo[i] = Integer.parseInt(br.readLine());
System.out.print("\n\n\t\t\t Cost :- ");
cost[i] = Double.parseDouble(br.readLine());
}
}
public void search(String nm)
{
for(int i =0 ; i<n ; i++)
{
if(name[i].equals(nm))
{
System.out.print("\n\n\t\t Record found...!");
System.out.print("\n\n\t\t\t
Name
:"+name[i]);
System.out.print("\n\n\t\t\t Mobile number :"+mobNo[i]);
System.out.print("\n\n\t\t\t cost :- "+cost[i]);
}
else
{
System.out.print("\n\n\t\t

Record

not

found...!");
}
}
}
public void search(int mno)
{
for(int i=0 ; i<n ; i++)
{
if(mobNo[i]==mno)
{
System.out.print("\n\n\t\t Record found...!");

System.out.print("\n\n\t\t\t

Name

:-

"+name[i]);
System.out.print("\n\n\t\t\t Mobile number :"+mobNo[i]);
System.out.print("\n\n\t\t\t cost :- "+cost[i]);
}
else
{
System.out.print("\n\n\t\t

Record

not

found...!");
}
}
}
}
public class Program2
{
public static void main(String args[])throws Exception
{
Mobile m = new Mobile();
m.getData();
BufferedReader
br
InputStreamReader(System.in));

new

BufferedReader(new

System.out.print("\n\n\t\t\t 1) search by name ");


System.out.print("\n\n\t\t\t 2) search by Mobile number
");
System.out.print("\n\n\t\t\t Enter yout choice :- ");
int ch = Integer.parseInt(br.readLine());
switch(ch)
{
case 1:
System.out.print("\n\n\t\t\t Enter Name :- ");
String n = br.readLine();
m.search(n);
break;
case 2:
System.out.print("\n\n\t\t\t
Enter
Mobile
Number :- ");
int mno = Integer.parseInt(br.readLine());
m.search(mno);
break;
}
}
}

Lab Work -5
Topic: Chapter-1 (Interfaces and Package)

Write a program to Design a Shape as an interface and then Design class for
Rectangle, Triangle and Hexagon which implements the interface and override
method drawShape().

import java.io.*;

interface Shape
{

public void drawShape();


}

class Rectangle implements Shape


{
public void drawShape()
{
System.out.print("\n\n\t\t\t Shape :- Rectange...!");
}
}

class Triangle implements Shape


{
public void drawShape()
{
System.out.print("\n\n\t\t\t Shape :- Triangle...!");
}
}

class Hexagon implements Shape


{
public void drawShape()
{
System.out.print("\n\n\t\t\t Shape :- Hexagon...!\n\n");
}
}

public class Program1


{
public static void main(String args[])

{
Rectangle r = new Rectangle();
Triangle t = new Triangle();
Hexagon h = new Hexagon();

r.drawShape();
t.drawShape();
h.drawShape();
}
}

Lab Work -6
Topic: Chapter-1(Exception Handling).

1 .Accept two numbers a & b from command line argument & print
output as a/b and handle all possible system defined exceptions.
import java.io.*;
import java.lang.*;
public class Program1
{
public static void main(String args[])
{
try
{
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
int div = a/b;
System.out.print("\n\n\t\t\t"+a+" / "+b+" :- "+div+"
\n\n");
}
catch(ArrayIndexOutOfBoundsException ai)
{
}
catch(ArithmeticException ae)
{
}
}
}

2.Write a class Driver with attributes vehicle no, name & age. Initialize values
through parameterized constructor. If age of driver is less than 18 then generate
user-defined exception Age Not Within the Range.
import java.lang.*;
import java.io.*;

class AgeLimitException extends Exception


{
int age;
AgeLimitException(int a)
{
this.age = a;
}
public int getAge()
{
return age;

}
}

class Driver
{
String name;
int age;
String vehicleNo;

public void getData()throws Exception


{
BufferedReader
br
InputStreamReader(System.in));

new

BufferedReader(new

System.out.print("\n\n\t\t Enter Driver details :-");


try
{
System.out.print("\n\n\t\t\t Name :- ");
name = br.readLine();
System.out.print("\n\n\t\t\t Age :- ");
age = Integer.parseInt(br.readLine());

if(age<18)
{
throw new AgeLimitException(age);
}

System.out.print("\n\n\t\t\t Vehicle Number :- ");


vehicleNo = br.readLine();
}
catch(AgeLimitException a)

{
System.out.print("\n\n\t\t\t
"+a.getAge()+"\n\n");

ERROR

:-

invalid

}
}
}

public class Program2


{
public static void main(String args[])throws Exception
{
Driver d = new Driver();
d.getData();
}
}

age...!

3.Write a program to demonstrate use of user-defined exception, the


CheckingAccount class contains a withdraw() method that throws an
InsufficientFundsException.

import java.io.*;
import java.lang.*;

class InsufficientAmountException extends Exception


{
double withdrawAmount;

InsufficientAmountException(double wAmt)
{
this.withdrawAmount = wAmt;
}
public double getAmount()
{
return withdrawAmount;
}
}

class CheckingAmount
{
int accNo;
String name;
double amount,withdrawAmount;

public void withdraw()throws Exception


{
BufferedReader
br
InputStreamReader(System.in));

new

BufferedReader(new

try
{
System.out.print("\n\n\t\t Enter Account details :");
System.out.print("\n\n\t\t\t account number :- ");
accNo = Integer.parseInt(br.readLine());
System.out.print("\n\n\t\t\t Name :- ");
name = br.readLine();
System.out.print("\n\n\t\t\t Amount :- ");
amount = Double.parseDouble(br.readLine());
System.out.print("\n\n\t\t\t Withdraw Amount :- ");
withdrawAmount
Double.parseDouble(br.readLine());

if(withdrawAmount >= amount)


{
throw
InsufficientAmountException(withdrawAmount);

new

}
}
catch(InsufficientAmountException ie)
{
System.out.print("\n\n\t\t\t ERROR :- Insufficient
account balance...!"+ie.getAmount()+"\n\n");
}
}
}

public class Program3

{
public static void main(String args[])throws Exception
{
CheckingAmount c = new CheckingAmount();
c.withdraw();
}
}

4.Define an exception called No equal Exception that is thrown when a float value is
not equal to 3.14. Write a program that uses the above user defined exception.

import java.io.*;

class NoEqualException extends Exception


{
double value;

NoEqualException(double val)

{
this.value = val;
}
public double getValue()
{
return value;
}
}

public class Program4


{
public static void main(String args[])throws Exception
{
BufferedReader
br
InputStreamReader(System.in));

new

BufferedReader(new

System.out.print("\n\n\t\t Enter Float value :- ");


double val = Double.parseDouble(br.readLine());
try
{
if(val!=3.14)
{
throw new NoEqualException(val);
}
}
catch(NoEqualException ne)
{
System.out.print("\n\n\t\t\t
3.14...!"+ne.getValue()+"\n\n");
}
}

ERROR

:-

not

equal

to

Lab Work -7
Topic: Chapter-7(Multithreading)

1 Write java program to create and run following threads


a Display first 10 even numbers.
b Display any String for 10 time.

import java.io.*;

public class Program1


{
public static void main(String args[])throws Exception
{
Thread t1 = new Thread();
Thread t2 = new Thread();

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


{
t1.sleep(100);
System.out.print("\n\t"+i);
}

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


{
t2.sleep(100);
System.out.print("\n\t Eshwar");
}
}
}

2.Write a program to implement the concept of threading by extending


Thread Class and also by implementing interfaces.

import java.io.*;

class ExtendThread extends Thread implements Runnable


{
public void run()
{
for( int i = 0 ; i<10 ; i++)
{
try
{
System.out.print("\n\n\t\t

Extending

Thread...!

"+i);
Thread.sleep(100);
}
catch(Exception e)
{}
}
}
}

class ImplementThread implements Runnable


{
public void run()
{
for( int i = 0 ; i<10 ; i++)
{
try
{
System.out.print("\n\n\t\t Implementing Thread...!
"+i);
Thread.sleep(100);

}
catch(Exception e)
{}
}
}
}

public class Program2


{
public static void main(String args[])
{
ExtendThread t1 = new ExtendThread();
ImplementThread t2 = new ImplementThread();

t1.start();
t2.run();
}
}

2 Write a program to set the priority of two above threads and


check which thread executes first.

import java.io.*;
class ExtendThread extends Thread implements Runnable
{
public void run()
{
for( int i = 0 ; i<10 ; i++)
{
try
{
System.out.print("\n\n\t\t
Thread...! "+i);
Thread.sleep(100);
}
catch(Exception e)
{}
}
}
}
class ImplementThread implements Runnable
{
public void run()
{
for( int i = 0 ; i<10 ; i++)
{
try
{
System.out.print("\n\n\t\t
Thread...! "+i);
Thread.sleep(100);
}
catch(Exception e)
{}
}
}

Extending

Implementing

}
public class Program3
{
public static void main(String args[])
{
ExtendThread t1 = new ExtendThread();
ImplementThread t2 = new ImplementThread();
t1.setPriority(1);

t1.start();
t2.run();

Lab Work -8
Topic: Chapter-7 (Multithreading)

Write a program to print name, priority of a thread and change name of current
to java thread and display the details of current thread.
import java.io.*;

public class Program1 extends Thread


{
public static void main(String args[])throws Exception
{
Thread t1 = new Thread("First Thread");
t1.setPriority(1);
System.out.print("\n\n\t\t Thread details :- ");
System.out.print("\n\n\t\t\t Name :- "+t1.getName());
System.out.print("\n\n\t\t\t Priority :- "+t1.getPriority());
t1.setName("New Thread");
System.out.print("\n\n\t\t\t New Name :- "+t1.getName()
+"\n\n");
}
}

Lab Work -9
Topic: Chapter- (Applets)

1 Write a program to create an applet to draw various shapes like oval,


rectangle and fill them with different color.

/*
<applet code="Program1.class" height=550 width=550>
</applet>
*/
import java.applet.*;
import java.awt.*;
public class Program1 extends Applet
{
public void init()
{}
public void paint(Graphics g)
{
g.setColor(Color.red);
g.fillOval(100,100,100,100);
g.setColor(Color.yellow);
g.fillRect(200,200,100,100);
g.setColor(Color.orange);
g.fillRect(300,100,100,100);
}
}

Write a java program to draw a national flag.

/*
<applet code="Program2.class" height=550 width=500>
</applet>
*/
import java.applet.*;
import java.awt.*;
public class Program2 extends Applet
{
public void paint(Graphics g)
{
Color c;
c=Color.black;
g.setColor(c);
g.fillRect(237,114,10,500);
c=Color.red;
g.setColor(c);
g.fillRect(248,125,200,25);
c=Color.white;
g.setColor(c);
g.fillRect(248,150,200,25);
c=Color.green;
g.setColor(c);
g.fillRect(248,175,200,25);
c=Color.blue;
g.setColor(c);
g.drawOval(342,149,25,25);
int l=0;
int x=355,y=162;
double x1,y1;
double d;
c=Color.black;
g.setColor(c);
for(int i=1;i<=24;i++)
{
d=(double)l*3.14/180.0;

x1=x+(double)10*Math.cos(d);
y1=y+(double)10*Math.sin(d);
g.drawLine(x,y,(int)x1,(int)y1);
l=l+(360/24);
}
}
}

3.Write a program to create an applet to accept two numbers from user in


two different textboxes and display the sum on a button click event.
/*
<applet code="Program3.class" height=550 width=550>
</applet>
*/
import java.awt.event.*;
import java.awt.*;
import java.applet.*;
public class Program3 extends Applet implements ActionListener
{
TextField t1, t2;
Button b1, b2;
Label l1, l2, l3, l4;
public void init()
{
l1 = new Label("number 1 ");

l2 = new Label("number 2 ");


l3 = new Label("Addition");
l4 = new Label("");
t1 = new TextField(20);
t2 = new TextField(20);
b1 = new Button("Add");
b2 = new Button("clear");
Panel p1 = new Panel();
p1.setLayout(new GridLayout(4,2));
p1.add(l1);
p1.add(t1);
p1.add(l2);
p1.add(t2);
p1.add(l3);
p1.add(l4);
p1.add(b1);
p1.add(b2);
add(p1);
b1.addActionListener(this);
b2.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
Button bt = (Button) ae.getSource();
if(bt==b1)
{
int a = Integer.parseInt(t1.getText().toString());
int b = Integer.parseInt(t2.getText().toString());
int sum = a+b;
l4.setText(""+sum);
}
if(bt==b2)
{
t1.setText("");
t2.setText("");
}
}
}

Lab Work -10


Topic: Chapter- (Applets & multithreading)
1 Write a java code for moving banner.
/* <applet code="movingBanner" height=50 width=300> </applet>
*/
import java.awt.*;
import java.applet.*;
public class movingBanner extends Applet implements Runnable
{
String msg=" A moving Banner. ";
char ch;
boolean stopFlag= true;
Thread t= null;
public void start(){
t = new Thread(this);
stopFlag=false;
t.start();
}

public void run(){


for(;;){
try{
repaint();
Thread.sleep(250);
ch = msg.charAt(0);
msg = msg.substring(1,msg.length());
msg = msg + ch;
if(stopFlag)
break;
}catch(InterruptedException e) {}
}
}
public void stop(){
stopFlag=true;
t = null;
}
public void paint(Graphics g){
g.drawString(msg,60,30);
}
}

2 Write a code for bouncing ball.


// Bouncing Ball example
import java.awt.event.*;
import java.awt.Graphics;
import java.awt.Color;

import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.Timer;
public class Ball
{
// execute application
public static void main( String args[] )
{
JFrame frame = new JFrame( "Bouncing Ball" );
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
BallPanel bp = new BallPanel();
frame.add( bp );
frame.setSize( 300, 300 ); // set frame size
frame.setVisible( true ); // display frame
} // end main
}
// class BallPanel
class BallPanel extends JPanel implements ActionListener
{
private int delay = 10;
protected Timer timer;
private int x = 0;
private int y = 0;
private int radius = 15;

// x position
// y position
// ball radius

private int dx = 2;
private int dy = 2;

// increment amount (x coord)


// increment amount (y coord)

public BallPanel()
{
timer = new Timer(delay, this);
timer.start();
// start the timer
}
public void actionPerformed(ActionEvent e)
// will run when the timer fires
{
repaint();
}
// draw rectangles and arcs
public void paintComponent( Graphics g )
{

super.paintComponent( g ); // call superclass's paintComponent


g.setColor(Color.red);
// check for boundaries
if (x < radius)
if (x > getWidth() - radius)
if (y < radius)
if (y > getHeight() - radius)

dx
dx
dy
dy

=
=
=
=

Math.abs(dx);
-Math.abs(dx);
Math.abs(dy);
-Math.abs(dy);

// adjust ball position


x += dx;
y += dy;
g.fillOval(x - radius, y - radius, radius*2, radius*2);
}
}

3 Write a program to simulate traffic signal.

/* <applet code=signal.class
width=1200></applet>
*/
import java.applet.*;
import java.awt.*;
public class signal extends Applet

height=1200

{
int i;
public void init()
{
i=1;
}
public void paint(Graphics g)
{
if(i==1)
{
g.setColor(Color.red);
g.fillOval(30,30,50,50);
g.setColor(Color.black);
g.fillOval(30,130,50,50);
g.fillOval(30,230,50,50);
}
if(i==2)
{
g.setColor(Color.black);
g.fillOval(30,30,50,50);
g.setColor(Color.yellow);
g.fillOval(30,130,50,50);
g.setColor(Color.black);
g.fillOval(30,230,50,50);
}
if(i==3)
{
g.setColor(Color.black);
g.fillOval(30,30,50,50);
g.fillOval(30,130,50,50);
g.setColor(Color.green);
g.fillOval(30,230,50,50);
}
try
{

Thread.sleep(500);
}
catch(Exception ex){} i++;
if(i==4)
i=1;
repaint();
}
}

Lab Work -11


Topic: Chapter- (AWT)
1 Write a program to design a form as follows:
First Name

Last Name

ABC

XYZ

ABC XYZ

Display
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public
class
Program1
ActionListener
{
JTextField t1, t2, t3;
JLabel l1,l2;
JButton b1;

extends

Program1()
{
t1 = new JTextField(20);
t2 = new JTextField(20);
t3 = new JTextField(20);
l1 = new JLabel("First Name");
l2 = new JLabel("Last Name");
b1 = new JButton("Display");
Panel p1 = new Panel();
p1.setLayout(new GridLayout(3,2));
p1.add(l1);
p1.add(t1);
p1.add(l2);
p1.add(t2);
p1.add(b1);
p1.add(t3);
setLayout(new FlowLayout());
add(p1);
setVisible(true);
setLocation(200,300);

JFrame

implements

setSize(550,550);
b1.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
JButton b = (JButton) ae.getSource();
if(b==b1)
{
t3.setText(t1.getText().toString()+"
"+t2.getText().toString());
}
}
public static void main(String args[])
{
new Program1();
}
}

2 Design a form with one textbox & 3 buttons for selecting


colors. Change the textbox color depending on button click.

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

public class Program2 extends JFrame implements ActionListener


{
JTextField t1;
JButton b1, b2, b3;

Program2()
{
t1 = new JTextField(20);
b1 = new JButton("Red");
b2 = new JButton("Yellow");
b3 = new JButton("Orange");

Panel p1 = new Panel();


p1.setLayout(new GridLayout(4,1));
p1.add(t1);
p1.add(b1);
p1.add(b2);
p1.add(b3);

setLayout(new FlowLayout());
add(p1);
setVisible(true);
setLocation(200,300);
setSize(550,550);

b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
JButton b = (JButton) ae.getSource();

if(b==b1)
{
t1.setBackground(Color.red);
}
if(b==b2)
{
t1.setBackground(Color.yellow);

}
if(b==b3)
{
t1.setBackground(Color.orange);
}
}

public static void main(String args[])


{
new Program2();
}

3.Design an applet to create two buttons labeled Fruits and


Vegetables. Each of these buttons when clicked invokes one of the
two panels. One panel contains four checkboxes with fruit names
as their labels. Second panel contains three checkboxes with
vegetable names as their labels. When user selects the checkboxes
message will be displayed like You selected Mango, Orange. (Use
CardLayout)
/*
<applet code="Program3.class" height=550 width=550>
</applet>
*/
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class Program3 extends Applet implements ActionListener
{
Button fruitButton, vegButton;
Container mainPanel;
Panel fruitPanel, vegPanel;
Checkbox fruit1, fruit2, fruit3, fruit4;
Checkbox veg1, veg2, veg3, veg4;
CardLayout card;
public void init()
{
card = new CardLayout(50,50);
fruitButton = new Button("Fruits");
vegButton = new Button("Vegetables");
mainPanel = new Container();
fruitPanel = new Panel();
vegPanel = new Panel();
fruit1
fruit2
fruit3
fruit4

=
=
=
=

new
new
new
new

Checkbox("Mango");
Checkbox("Grapes");
Checkbox("Watermelon");
Checkbox("Apple");

veg1 = new Checkbox("veg1");

veg2 = new Checkbox("veg2");


veg3 = new Checkbox("veg3");
veg4 = new Checkbox("veg4");
fruitPanel.setLayout(new GridLayout(4,1));
fruitPanel.add(fruit1);
fruitPanel.add(fruit2);
fruitPanel.add(fruit3);
fruitPanel.add(fruit4);
fruitPanel.setVisible(false);
vegPanel.setLayout(new GridLayout(4,1));
vegPanel.add(veg1);
vegPanel.add(veg2);
vegPanel.add(veg3);
vegPanel.add(veg4);
mainPanel.add("fruit",fruitPanel);
mainPanel.add("veg",vegPanel);
setLayout(new FlowLayout());
add(fruitButton);
add(vegButton);
fruitButton.addActionListener(this);
vegButton.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
Button b = (Button) ae.getSource();
if(b==fruitButton)
{
card.next(mainPanel);
}
}
}

Lab Work -12


Topic: Chapter- (AWT)
1 Write a program to create Menu Color on menu bar containing

items .
Red, Green, Blue, Black in color. Depending on which menu item
was selected the background color of the frame window is set to
that color.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Program1 extends JFrame implements ItemListener
{
JMenuBar mainMenuBar;
JMenu mainMenu;
JMenuItem redItem, greenItem, blueItem, blackItem;
JFrame mainFrame;

Program1()
{
mainFrame = new JFrame("Color Menu");
mainMenuBar = new JMenuBar();
mainMenu = new JMenu("Color");
redItem = new JMenuItem("Red");
greenItem = new JMenuItem("Green");
blueItem = new JMenuItem("Blue");
blackItem = new JMenuItem("Black");
mainMenu.add(redItem);
mainMenu.add(greenItem);
mainMenu.add(blueItem);
mainMenu.add(blackItem);
mainMenuBar.add(mainMenu);
mainFrame.setJMenuBar(mainMenuBar);
mainFrame.setLocation(350,150);
mainFrame.setSize(350,350);
mainFrame.setVisible(true);
mainFrame.setDefaultCloseOperation(EXIT_ON_CLOSE);
redItem.addItemListener(this);
greenItem.addItemListener(this);
blueItem.addItemListener(this);
blackItem.addItemListener(this);
}
/*

public void actionPerformed(ActionEvent ae)


{
String menuItem = ae.getActionCommand();

if(menuItem.equals("Red"))
{
mainFrame.setBackground(Color.red);
}
if(menuItem.equals("Green"))
{
mainFrame.setBackground(Color.green);
}
if(menuItem.equals("Blue"))
{
mainFrame.setBackground(Color.blue);
}
if(menuItem.equals("Black"))
{
mainFrame.setBackground(Color.black);
}
}
*/
public void itemStateChanged(ItemEvent ie)
{
String menuItem = (String)ie.getItem();
if(menuItem.equals("Red"))
{
mainFrame.setBackground(Color.red);
}
if(menuItem.equals("Green"))
{
mainFrame.setBackground(Color.green);
}
if(menuItem.equals("Blue"))
{
mainFrame.setBackground(Color.blue);
}

if(menuItem.equals("Black"))
{
mainFrame.setBackground(Color.black);
}
}
public static void main(String args[])
{
new Program1();
}
}

2.Write a Java program to create a menu same as notepad. File


New, Open, Save, Save As, and Exit.

import java.awt.*;
import javax.swing.*;
public class Program2 extends JFrame
{
JMenuBar mainMenuBar;
JMenu fileMenu, editMenu;

Edit Cut, Copy, and Paste.

JMenuItem newItem, openItem, saveItem, saveAsItem, exitItem,


cutItem, copyItem, pasteItem;
Program2()
{
mainMenuBar = new JMenuBar();
fileMenu = new JMenu("File");
editMenu = new JMenu("Edit");
mainMenuBar.add(fileMenu);
mainMenuBar.add(editMenu);
newItem = new JMenuItem("new");
openItem = new JMenuItem("open");
saveItem = new JMenuItem("save");
saveAsItem = new JMenuItem("save As");
exitItem = new JMenuItem("Exit");
cutItem = new JMenuItem("cut");
copyItem = new JMenuItem("copy");
pasteItem = new JMenuItem("paste");
fileMenu.add(newItem);
fileMenu.add(openItem);
fileMenu.add(saveItem);
fileMenu.add(saveAsItem);
fileMenu.add(exitItem);
editMenu.add(copyItem);
editMenu.add(cutItem);
editMenu.add(pasteItem);
setJMenuBar(mainMenuBar);
setLocation(350,250);
setSize(350,350);
setVisible(true);
}
public static void main(String args[])
{
new Program2();
}
}

3 Write a java code to draw line & display co-ordinates


according to mouse move.
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
class MML extends JFrame implements MouseMotionListener
{
JLabel l;
MML()
{
super("MouseMotionListener");
l=new JLabel("
");
l.setFont(new Font("Arial",Font.BOLD,20));
setLayout(new FlowLayout());
add(l);
addMouseMotionListener(this);
setSize(400,400);
setVisible(true);
}
public void mouseMoved(MouseEvent e)
{
l.setText("x="+e.getX()+" "+"y="+e.getY());
}
public void mouseDragged(MouseEvent e)

{
}

l.setText("x="+e.getX()+" "+"y="+e.getY());

public static void main(String args[])


{
new MML();
}
}

Lab Work -13


Topic: Chapter- (I/O)
1.Design a employee form (empno, name& sal) & save the data in
emp.dat file on click of button.
import java.io.*;
public class Program1
{
public static void main(String args[])throws Exception
{
int empID;
String name;
double salary;
BufferedReader
br
InputStreamReader(System.in));

new

BufferedReader(new

PrintWriter fout = new PrintWriter("emp.dat");


System.out.print("\n\n\t\t Enter employee details :- ");
System.out.print("\n\n\t\t\t Name :- ");
name = br.readLine();
System.out.print("\n\n\t\t\t employee ID :- ");
empID = Integer.parseInt(br.readLine());
System.out.print("\n\n\t\t\t salary :- ");
salary = Double.parseDouble(br.readLine());
fout.print(empID);
fout.print(name);
fout.print(salary);
System.out.print("\n\n\t\t
successfully...!\n\n");
}
}

Record

saved

2.Write a program to check whether the file is


readable, Writable or hidden.
import java.io.*;
public class Program3
{
public static void main(String args[])throws Exception
{
File f = new File("emp.dat");
if(f.exists())
{
System.out.print("\n\n\t\t\t File exist...!\n\n");
}
else
{
System.out.print("\n\n\t\t\t
File
does
not
exist...!\n\n");
}
if(f.canRead())
{
System.out.print("\n\n\t\t\t
File
is
readable...!\n\n");
}
else
{
System.out.print("\n\n\t\t\t
File
is
not
readable...!\n\n");
}
if(f.canWrite())
{
System.out.print("\n\n\t\t\t
File
is
writable...!\n\n");
}
else
{
System.out.print("\n\n\t\t\t
File
is
not
writable...!\n\n");
}
if(f.isHidden())
{

System.out.print("\n\n\t\t\t
Hidden...!\n\n");
}
else
{
System.out.print("\n\n\t\t\t
Hidden...!\n\n");
}
}
}

File

File

is

is

not

3.Write a program to show how file class is used to display information


about a directory and all the files included in current directory.
import java.io.*;
public class Program4
{
public static void main(String args[])throws Exception
{
File f = new File("E:\\Important Files");
String[] content = f.list();
if(f.isDirectory())
{
System.out.print("\n\n\n\t\t\t It is directory...!\n\n");
}
else
{
System.out.print("\n\n\n\t\t\t It is not directory...!\n\n");
}

System.out.print("\n\n\n\t\t Directory consist :- ");


for( int i = 0 ; i<content.length ; i++ )
{
System.out.print("\n\n\t\t\t "+content[i]);
}
System.out.print("\n\n\n");
}
}

Lab Work -15


Topic: Chapter-6(Networking)
1

Write a java code for chatting application .

/*To implement a CLIENT*/

import java.io.*;
import java.net.*;

class Client
{
static DataInputStream din, dis;
static DataOutputStream dos;

public static void main(String args[])


{
try
{
Socket

new

Socket(InetAddress.getLocalHost(),

8080);

din = new DataInputStream(s.getInputStream());


dis = new DataInputStream(System.in);

dos = new DataOutputStream(s.getOutputStream());

while(true)
{
dos.writeUTF(dis.readLine());
System.out.println("SERVER : " + din.readUTF());
}
}

catch(Exception e)
{
System.out.println("EXCEPTION : " + e);
}
}
}

/*To implement a SERVER*/

import java.io.*;
import java.net.*;

class Server
{
public static void main(String args[])
{
try
{
Socket s;
ServerSocket ss = new ServerSocket(8080);

while(true)
{
s = ss.accept();
(new MyThread(s)).start();
}
}

catch(Exception e)
{
System.out.println("EXCEPTION : " + e);
}
}
}

class MyThread extends Thread


{
DataInputStream din, dis;
DataOutputStream dos;

MyThread(Socket s) throws Exception


{
dis = new DataInputStream(s.getInputStream());
din = new DataInputStream(System.in);
dos = new DataOutputStream(s.getOutputStream());
}

public void run()


{

try
{
while(true)
{

System.out.println("CLIENT : " + dis.readUTF());


dos.writeUTF(din.readLine());

}
}

catch(Exception e)
{
System.out.println("EXECPTION IN SERVER :" + e);
}
}
}

2.Write a java code in which client will send file name to server
and server will send content of that file to client.

/*To implement a SERVER*/

import java.io.*;
import java.net.*;

class Server

{
public static void main(String args[])
{
try
{
Socket s;
ServerSocket ss = new ServerSocket(8080);

while(true)
{
s = ss.accept();
(new MyThread(s)).start();
}
}

catch(Exception e)
{
System.out.println("EXCEPTION : " + e);
}
}
}

class MyThread extends Thread


{
DataInputStream din, dis;
DataOutputStream dos;

MyThread(Socket s) throws Exception


{
dis = new DataInputStream(s.getInputStream());

din = new DataInputStream(System.in);


dos = new DataOutputStream(s.getOutputStream());
}

public void run()


{

try
{
while(true)
{

System.out.println("CLIENT : " + dis.readUTF());


dos.writeUTF(din.readLine());

}
}

catch(Exception e)
{
System.out.println("EXECPTION IN SERVER :" + e);
}
}
}

import java.io.*;
import java.net.*;

class Server
{
public static void main(String args[]) throws Exception
{
ServerSocket ss = new ServerSocket(4000);
Socket s;

while(true)
{
s = ss.accept();
(new MyThread(s)).start();
}
}
}

class MyThread extends Thread


{

DataInputStream dis;
DataOutputStream dos;
FileInputStream fin;

String fname;
String data="";

public MyThread(Socket s) throws Exception


{
dis = new DataInputStream(s.getInputStream());
dos = new DataOutputStream(s.getOutputStream());
}

public void run()


{
try
{
fname = dis.readUTF();
fin = new FileInputStream(fname);

byte ch = (byte)fin.read();

while (ch!=-1)
{
data = data + (char)ch;
ch = (byte)fin.read();
}

dos.writeUTF(data);
}

catch(Exception e)
{
}
}
}

3.Write a program for client and server to send and receive message using
connectionless networking.
import java.io.*;
import java.net.*;
class Client
{
public static void main(String[ ] args)
{
try{
InetAddress
ia
InetAddress.getByName("172.16.64.221");
int port = Integer.parseInt("2000");
DatagramSocket ds = new DatagramSocket();
String str1 = "Hello.......";
byte buffer[ ] = new byte[1024];
buffer = str1.getBytes();
DatagramPacket
dp
=
DatagramPacket(buffer,buffer.length,ia,2000);

new

ds.send(dp);
}
catch(Exception e)
{
System.out.println("Exception : " + e);
}
}
}

import java.net.*;
import java.io.*;
class Server
{
//public static DatagramSocket ds;
public static void main(String args[])
{
try
{
DatagramSocket ds = new DatagramSocket(2000);
byte buffer[] = new byte[20];
while( true )
{
DatagramPacket
dp
=
new
DatagramPacket(buffer,buffer.length);
ds.receive(dp);
String str = new String (dp.getData( ));
System.out.println("Data from Client is " + str);
}
}
catch(Exception e)
{
//System.out.println(e);
e.printStackTrace();
}
}
}

Lab Work -16


Topic: Chapter-7(JDBC)

Write a program for JDBC to insert, update and delete a record on click of buttons
from Book table having fields Bookno ,Bookname and BookPrice

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

public class Program1 extends JFrame implements ActionListener


{
Connection con;
Statement st;

JButton save,update;
JLabel bnoLabel, nameLabel, priceLabel;
JTextField bnoTextField, nameTextField, priceTextField;
Panel p1;
JFrame f1;
Program1()
{
f1 = new JFrame("Book details");
p1 = new Panel();
save = new JButton("save");
update = new JButton("update");

bnoLabel = new JLabel("Book number");


nameLabel = new JLabel("Name");
priceLabel = new JLabel("price");

bnoTextField = new JTextField(20);


nameTextField = new JTextField(20);
priceTextField = new JTextField(20);
p1.setLayout(new GridLayout(4,2));
p1.add(bnoLabel);
p1.add(bnoTextField);
p1.add(nameLabel);
p1.add(nameTextField);
p1.add(priceLabel);
p1.add(priceTextField);
p1.add(save);
p1.add(update);

f1.setLayout(new FlowLayout());
f1.add(p1);
f1.setSize(500,500);
f1.setVisible(true);
f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

save.addActionListener(this);
update.addActionListener(this);
}

public void actionPerformed(ActionEvent ae)


{
JButton b = (JButton) ae.getSource();

if(b==save)
{
int bno = Integer.parseInt(bnoTextField.getText());

String name = nameTextField.getText();


double
Double.parseDouble(bnoTextField.getText());

price

try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection
con=DriverManager.getConnection("jdbc:odbc:Book");

st = con.createStatement();

st.executeUpdate("insert
values(bno,'name',price)");
System.out.print("\n\n\n\t\t\t

into
Record

Book
saved

successfully...!");

}
catch(Exception e)
{}
}
if(b==update)
{
int bno = Integer.parseInt(bnoTextField.getText());
String name = nameTextField.getText();
double
Double.parseDouble(bnoTextField.getText());

price

try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection
con=DriverManager.getConnection("jdbc:odbc:Book");

st = con.createStatement();

st.executeUpdate("update

Book

SET

price="+price);
System.out.print("\n\n\n\t\t\t

Record

successfully...!");

}
catch(Exception e)
{}
}
}
public static void main(String args[])throws Exception
{
new Program1();
}
}

PreparedStatement program use student table

import java.io.*;

saved

import java.sql.*;

public class Program3


{

public static void main(String args[])


{
try
{
Connection con;
PreparedStatement ps;
Class.forName("jdbc.odbc.JdbcOdbcDriver");

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

ps = con.prepareStatement("insert into Book values(?,?,?)");


ps.setInt(1,1231);
ps.setString(2,"Maharashtra");
ps.setDouble(3,2500);
ps.executeUpdate();

System.out.print("\n\n\t\t Record updated successfully...!");


}
catch(Exception ce)
{
}
}
}

Lab Work -17


Topic: Chapter-7(JDBC)

Write a program for JDBC to insert, update and delete a record in a table using
methods of ResultsetMetadta with buttons and frames.

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

public class Program1 extends JFrame implements ActionListener


{
JTextField bno, name, price;
JLabel bnoLabel, nameLabel, priceLabel;
JButton insert, update, delete;

Program1()
{
JPanel p1 = new JPanel();
JPanel p2 = new JPanel();

bno = new JTextField(20);


name = new JTextField(20);
price = new JTextField(20);

bnoLabel = new JLabel("Book number");


nameLabel = new JLabel("Name");
priceLabel = new JLabel("price");

insert = new JButton("Insert");


update = new JButton("Update");

delete = new JButton("Delete");

p1.setLayout(new GridLayout(3,2));
p1.add(bnoLabel);
p1.add(bno);
p1.add(nameLabel);
p1.add(name);
p1.add(priceLabel);
p1.add(price);

p2.setLayout(new GridLayout(1,3));
p2.add(insert);
p2.add(update);
p2.add(delete);

setLayout(new FlowLayout());
add(p1);
add(p2);
setVisible(true);
setLocation(350,250);
setSize(550,350);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

insert.addActionListener(this);
}

public void actionPerformed(ActionEvent ae)


{
int bNo = Integer.parseInt(bno.getText());
String name = bno.getText();

double price = Double.parseDouble(bno.getText());


try
{
JButton b = (JButton) ae.getSource();
Connection con;
Statement st;
ResultSetMetaData rs;

Class.forName("com.mysql.jdbc.Driver");
con
DriverManager.getConnection("jdbc:mysql://localhost/Book","root","");

st = con.createStatement();

if(b == insert)
{
st.executeUpdate("insert
values(bNo,'name',price)");
System.out.print("\n\n\n\t\t\t

into
Record

Book
saved

successfully...!");
}
if(b == delete)
{
st.executeUpdate("insert
values(bNo,'name',price)");
System.out.print("\n\n\n\t\t\t
successfully...!");
}
}
catch(Exception e)
{}
}

into
Record

Book
saved

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


{
new Program1();

}
}

2.Write a program for JDBC to insert, update and delete a record in a table using
prepared and callable statements.
import
import
import
import
import

java.io.*;
java.sql.*;
java.awt.*;
javax.swing.*;
java.awt.event.*;

public class Program3 extends JFrame implements ActionListener


{
JTextField bno, name, price;
JLabel bnoLabel, nameLabel, priceLabel;
JButton insert, update, delete;
JFrame f1;

Program3()
{
f1 = new JFrame("Book details");
JPanel p1 = new JPanel();
JPanel p2 = new JPanel();
bno = new JTextField(20);
name = new JTextField(20);
price = new JTextField(20);
bnoLabel = new JLabel("Book number");
nameLabel = new JLabel("Name");
priceLabel = new JLabel("price");
insert = new JButton("Insert");
update = new JButton("Update");
delete = new JButton("Delete");
p1.setLayout(new GridLayout(3,2));
p1.add(bnoLabel);
p1.add(bno);
p1.add(nameLabel);
p1.add(name);
p1.add(priceLabel);
p1.add(price);
p2.setLayout(new GridLayout(1,3));
p2.add(insert);
p2.add(update);
p2.add(delete);
f1.setLayout(new FlowLayout());
f1.add(p1);
f1.add(p2);
f1.setVisible(true);
f1.setLocation(350,250);
f1.setSize(550,350);
f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
insert.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
int bNo = Integer.parseInt(bno.getText());
String nm = name.getText();
double cost = Double.parseDouble(price.getText());
try
{
JButton b = (JButton) ae.getSource();

Connection con;
Statement st;
PreparedStatement ps;
Class.forName("com.mysql.jdbc.Driver");
con
=
DriverManager.getConnection("jdbc:mysql://localhost/Book","root","");
st = con.createStatement();
if(b == insert)
{
ps = con.prepareStatement("insert into Book
values(?,'?',?)");
ps.setInt(1,bNo);
ps.setString(2,nm);
ps.setDouble(3,cost);
ps.executeUpdate();
JOptionPane.showMessageDialog(f1,"Record
saved...!");
}
if(b == delete)
{
st.executeUpdate("insert
into
Book
values(bNo,'name',price)");
System.out.print("\n\n\n\t\t\t
Record
saved
successfully...!");
}
}
catch(Exception e)
{}
}
public static void main(String args[])throws Exception
{
new Program3();
}
}

Lab Work -18


Topic: Chapter-8(RMI)

Write a RMI application to check whether the given number is Prime or not . Write
all interfaces and required classes.
ClientPrime
import java.io.*;
import java.rmi.*;
import java.rmi.server.*;

public class clientPrime


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

{
BufferedReader
br
InputStreamReader(System.in));

new

BufferedReader(new

remotePrime rp = (remotePrime)Naming.lookup("prime");

System.out.print("\n\n\n\t\t\t Enter number :- ");


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

rp.prime(n);
}
}

RemotePrime
import java.rmi.*;

public interface remotePrime extends Remote


{
public void prime(int n)throws Exception;
}

ServerPrime

import java.rmi.*;
import java.rmi.server.*;
import java.io.*;

public class
remotePrime

serverPrime

extends

UnicastRemoteObject

implements

{
public serverPrime()throws Exception
{
super();
}
public void prime(int number) throws Exception
{
int n = number;
int result=1;
int temp;
for(int i=2;i<=n/2;i++)
{
temp=n%i;
if(temp==0)
{
result = 0;
break;
}
else
{
result = 1;
}
}
if(result == 1)
{
System.out.print("\n\n\t\t\t Number is prime...!");
}
else

{
System.out.print("\n\n\t\t\t Number is not prime...!");
}
}

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


{
serverPrime sp = new serverPrime();
Naming.bind("prime",sp);
}
}

Write a RMI application to reverse the given string . Write all interfaces and
required classes.
ClientReverse
import java.rmi.*;
import java.rmi.server.*;
import java.io.*;
public class clientReverse
{
public static void main(String args[])throws Exception
{
BufferedReader
br
=
new
BufferedReader(new
InputStreamReader(System.in));
remoteReverse
r
=
(remoteReverse)
Naming.lookup("reverse");
System.out.print("\n\n\t\t\t Enter String :- ");
String str = br.readLine();
r.result(str);
}
}

RemoteReverse

import java.rmi.*;

public interface remoteReverse extends Remote


{
public void result(String str)throws Exception;
}

ServerReverse
import java.io.*;
import java.rmi.*;
import java.rmi.server.*;

public class serverReverse extends UnicastRemoteObject implements


remoteReverse
{
public serverReverse()throws Exception
{
super();
}

public void result(String s)throws Exception


{
StringBuffer sb = new StringBuffer(s);
String rstr = sb.reverse().toString();
System.out.print("\n\n\t\t\t Revrse of string :- "+rstr);
}

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


{
serverReverse sr = new serverReverse();

Naming.bind("reverse",sr);
}
}

Potrebbero piacerti anche