Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Javalab PDF

Download as pdf or txt
Download as pdf or txt
You are on page 1of 60

LABORATORY MANUAL

JAVA PROGRAMMING LAB


II YEAR II-SEM (CSE)
[COLLEGE LOGO]

Department of Computer Science and Engineering


MALLAREDDY COLLEGE OF ENGINEERING
Affiliated to JNTUH, Approved by AICTE
Maisammaguda, Dhulapally, Secunderabad

Java Programming Lab

CSE Department

COURSE NAME: Java Programming Lab

COURSE CODE: A40585


COURSE OBJECTIVES:
1. To make the student learn an object oriented way of solving problems.
2. To introduce java compiler and eclipse platform
3. To impact hand on experience with java programming
4. Be able to use java SDK environment to create, debug and run java programs.

COURSE OUTCOMES:
1.

Develop problem-solving and programming skills using OOP concept

2.

Basics of java programming, multi-threaded programs and Exception handling.

3.

Ability to access data from a DB with Java programs.

4.

Use of GUI components(Console and GUI based)

5.

Develop efficient Java applets and applications using OOP concept.

MALLA REDDY COLLEGE OF ENGINEERING

Page 1

Java Programming Lab

CSE Department

INDEX
S.No
1
2

6
7

10
11

List of Contents
Eclipse Introduction
Write a java program that works as a simple calculator. Use a
GridLayout to arrange Buttons for digits and for the + - * %
operations. Add a text field to display the result. Handle any
possible exceptions like divide by zero.
a) Write an applet program that displays a simple message
b) Develop an applet that receives an integer in one text field, and
computes its factorial Value and returns it in another text field, when the
button named Compute is clicked.
Write a program that creates a user interface to perform integer
divisions. The user enters twonumbers in the textfields, Num1 and
Num2. The division of Num1 and Num2 is displayed in theResult field
when the Divide button is clicked. If Num1 or Num2 were not an
integer, theprogram would throw NumberFormatException. If Num2
were Zero, the program would throwan ArithmeticException Display the
exception in a message dialog box
Write a Java program that implements a multithreaded program has
three threads. First thread generates a random integer every 1 second and
if the value is even, second thread computes the square of the number
and prints. If the value is odd the third thread will print the value of cube
of the number.
Write a Java program that connects to a database using JDBC and does
add, delete, modify and retrieve operations.
Write a java program to simulate a traffic light. The program lets the
user select one of the three lights: red, yellow or green. On selecting a
button, an appropriate message with Stop or Ready or Go should
appear above the buttons selected color.
Write a java program to create an abstract class named shape that
contains two integers and an empty method named printArea() Provide
three classes named Rectangle,, Triangle and Circle such that each one
of the classes extends the class shape. Each one of the class contains
only the method printArea() that print the area of the given shape
Suppose that table named Table.txt is stored in a text file. The first line
in the file is the header, and the remaining lines correspond to rows in
the table. The elements are separated by commas. Write a java program
to display the table using in Grid Layout.
Write a java program that handles all mouse events and shows the event
name at the center of the window when mouse event is fired(Use
Adapter classes).
Write a java program that loads names and phone numbers from a text
file where the data is organized as one line per record and each field in a
record are separated by tab(\t).It takes a name or phone number as input

MALLA REDDY COLLEGE OF ENGINEERING

Page.No
4
15

18
19
21

24

27
33

35

37

39
41

Page 2

Java Programming Lab

12
13
14

CSE Department

and prints the corresponding other value from the hash table(use hash
tables).
Write a java program that loads names and phone numbers from
database. It takes a name or phone number as input and prints the
corresponding other value from the hash table (use hash tables).
Write a java program that takes tab separated data (one record per line)
from text file and inserts them into a database.
Write a java program that prints the meta-data of a given table.
(Beyond the Syllabus)

43
46
48

15 Write java program for to implement client-server communication using

50

16

53

socket.
Simple Java Project

MALLA REDDY COLLEGE OF ENGINEERING

Page 3

Java Programming Lab

CSE Department

PROGRAM -1
Steps To Execute Simple Java Program Using Eclipse
Step1: Begin by creating a new Java project.
There are few different ways of accomplishing this. Click the arrow next to the leftmost icon on the toolbar and select Project from the drop-down menu. Alternately Start
a new Java Project by choosing File then New followed by Java Project. Also
use the shortcut Alt+Shift+N.

MALLA REDDY COLLEGE OF ENGINEERING

Page 4

Java Programming Lab

CSE Department

Step2: Enter a Project Name


You will see a window titled Create a Java Project. The buttons Next and
Finish at the bottom of the window will be grayed out until a project name is entered in
the first field. To processed, give project name and enter it into this field then click

Finish. New project will appear on the left-hand side of the screen under Package
Explorer among existing projects. Projects are listed in alphabetical order.

MALLA REDDY COLLEGE OF ENGINEERING

Page 5

Java Programming Lab

CSE Department

Step3: Start a new java class.


Before begin writing code, need to create a new Java class. A class is a blueprint
for an object. It defines the data stored in the object as well as its actions. Create a class by
clicking the New Java Class icon, which looks like a green circle with the letter C in
the center of it.

MALLA REDDY COLLEGE OF ENGINEERING

Page 6

Java Programming Lab

CSE Department

Step4: Enter the name of your class.


You will see a window titled Java Class. To proceed, enter the name of class
into the field Name. Since the class will be main class of the simple project, check the
selection box labeled public static void main(String[] args) to include the method
stub. Afterwards, click Finish.

MALLA REDDY COLLEGE OF ENGINEERING

Page 7

Java Programming Lab

CSE Department

Step5: Enter Java Code.


Here new class Welcome.java is created. It appears with the method stub public
static void main(String[] args) along with some automatically generated comments. A
method will contain a sequence of instructions to be executed by the program. A comment
is a statement that is ignored by the compiler. Comments are used by programmers to
document their code. Edit this file and insert the code for Java Program.

MALLA REDDY COLLEGE OF ENGINEERING

Page 8

Java Programming Lab

CSE Department

Step6: Watch out for errors in code.


Any errors will be underlined in red, and icon with an X will show up on the
left. Fix errors. By mousing over an error icon. can see a suggestion box that lists the ways
can fix the error.

MALLA REDDY COLLEGE OF ENGINEERING

Page 9

Java Programming Lab

CSE Department

Step7: Ensure that entire program is free of errors.


There are three types of errors must beware of: syntax errors, run-time errors and
logic errors. The compiler will alert syntax errors. Examples of syntax errors are
misspelled variable names or missing semi-colons. Until remove all syntax errors from
code program will not compile. The compiler will not catch run-time errors or logic errors.

MALLA REDDY COLLEGE OF ENGINEERING

Page 10

Java Programming Lab

CSE Department

Step8: Compile Java Program.


Now the program is free for errors, click the triangular icon to run program. Another
way to run program is to select Run from the main menu and then select Run
again from the drop-down menu. The shortcut is Ctrl+F11.

MALLA REDDY COLLEGE OF ENGINEERING

Page 11

Java Programming Lab

CSE Department

Step9: Verify the output is what you expected.


When program runs, the output will be displayed on console at the bottom of the
screen.

Step10: Fix any run-time or logic errors.


If the output is different from what you excepted, then there might have been an
error even though the program compiled. For example, if the output was zero instead of
four, then there was a mistake in the programs calculation.

MALLA REDDY COLLEGE OF ENGINEERING

Page 12

Java Programming Lab

CSE Department

Quadratic Equation Program


Aim: Write a java program that prints all real solutions to the quadratic equation
2
2
ax +bx+c=0.Read in a, b, c and use the quadratic formula, if the discriminate b 4ac is negative, display a message stating that there are no real roots using eclipse.
Program:
// Class to find the roots of Quadratic equation .
class quad
{
public static void main(String args[])
{
int a,b,c,d;
double r1,r2;
// Taking the a , b, c values at run time.
a=Integer.parseInt(args[0]);
b=Integer.parseInt(args[1]);
c=Integer.parseInt(args[2]);
// Calculating the determinant.
d=(b*b)-(4*a*c);
// Loop to find the roots if determinant is greater than zero.
if(d>0)
{ System.out.println("the roots are");
r1=(-b+Math.sqrt(d))/(2*a);
r2=(-b-Math.sqrt(d))/(2*a);
System.out.println(r1+" "+r2);
}
// Loop to find the roots if determinant is equal to zero.
if(d==0)
{
System.out.println("the roots are
equal"); r1=(-b)/(2*a);
r2=(-b)/(2*a);
System.out.println(r1+" "+r2);
}
// Loop to display message if determinant is less than zero.
MALLA REDDY COLLEGE OF ENGINEERING

Page 13

Java Programming Lab

CSE Department

else if(d<0)
{
System.out.println("the d is -ve and there are no roots");
}
}
}

Input : java quad 1 2 3


Output: the d is -ve and there are no roots
Input : java quad 1 5 2
Output: the roots are -0.4384471871911697 -4.561552812808831
Input: java quad 1 2 1
Output: The roots are -1.0 -1.0

MALLA REDDY COLLEGE OF ENGINEERING

Page 14

Java Programming Lab

CSE Department

PROGRAM -2
Design of Simple Calculator
Aim: Write a java program that works as a simple calculator. Use a GridLayout to arrange
Buttons for digits and for the + - * % operations. Add a text field to display the
result. Handle any possible exceptions like divide by zero.
Program:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code="Cal" width=300 height=300></applet>*/
public class Cal extends Applet implements ActionListener
{
String msg=" ";
int v1,v2,result;
TextField t1;
Button b[]=new Button[10];
Button add,sub,mul,div,clear,mod,EQ;
char OP;
public void init()
{
Color k=new Color(120,89,90);
setBackground(k);
t1=new TextField(10);
GridLayout gl=new
GridLayout(4,5); setLayout(gl);
for(int i=0;i<10;i++)
{
b[i]=new Button(""+i);
}
add=new Button("add");
sub=new Button("sub");
mul=new Button("mul");
div=new Button("div");
mod=new Button("mod");
clear=new Button("clear");
EQ=new Button("EQ");
t1.addActionListener(this);
add(t1);
for(int i=0;i<10;i++)
{
add(b[i]);}
MALLA REDDY COLLEGE OF ENGINEERING

Page 15

Java Programming Lab

CSE Department

add(add);
add(sub);
add(mul);
add(div);
add(mod);
add(clear);
add(EQ);
for(int i=0;i<10;i++)
{
b[i].addActionListener(this);
}
add.addActionListener(this);
sub.addActionListener(this);
mul.addActionListener(this);
div.addActionListener(this);
mod.addActionListener(this);
clear.addActionListener(this);
EQ.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
String str=ae.getActionCommand();
char ch=str.charAt(0);
if ( Character.isDigit(ch))
t1.setText(t1.getText()+str);
else
if(str.equals("add"))
{
v1=Integer.parseInt(t1.getText());
OP='+';
t1.setText("");
}
else if(str.equals("sub"))
{
v1=Integer.parseInt(t1.getText());
OP='-';
t1.setText("");
}
else if(str.equals("mul"))
{
v1=Integer.parseInt(t1.getText());
OP='*';
t1.setText("");
}
else if(str.equals("div"))
{
MALLA REDDY COLLEGE OF ENGINEERING

Page 16

Java Programming Lab

CSE Department

v1=Integer.parseInt(t1.getText());
OP='/';
t1.setText("");
}
else if(str.equals("mod"))
{
v1=Integer.parseInt(t1.getText());
OP='%';
t1.setText("");
}
if(str.equals("EQ"))
{
v2=Integer.parseInt(t1.getText());
if(OP=='+')
result=v1+v2;
else if(OP=='-')
result=v1-v2;
else if(OP=='*')
result=v1*v2;
else if(OP=='/')
result=v1/v2;
else if(OP=='%')
result=v1%v2;
t1.setText(""+result);
}
if(str.equals("clear"))
{
t1.setText("");
}
}
}
Output:

MALLA REDDY COLLEGE OF ENGINEERING

Page 17

Java Programming Lab

CSE Department

PROGRAM -3(a)
Simple Applet Creation
Aim: Write an applet program that displays a simple message
Program:
Applet1.java:
// Import the packages to access the classes and methods in awt and applet classes.
import java.awt.*;
import java.applet.*;
public class Applet1 extends Applet
{
// Paint method to display the message.
public void paint(Graphics g)
{
g.drawString("HELLO WORLD",20,20);
}}
Applet1.html:
/* <applet code="Applet1" width=200 height=300></applet>*/
Output:

MALLA REDDY COLLEGE OF ENGINEERING

Page 18

Java Programming Lab

CSE Department

PROGRAM -3(b)
Factorial using applet
Aim: Write a java program that Develop an applet that receives an integer in one text field,
and computes its factorial Value and returns it in another text field, when the button
named Compute is clicked.
Program:
import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
public class Fact extends Applet implements ActionListener
{
Label l1,l2;
TextField t1,t2;
Button b1;
public void init(){
l1=new Label("enter the
value"); add(l1);
t1=new TextField(10);
add(t1);
b1=new Button("Factorial");
add(b1);
b1.addActionListener(this);
l2=new Label("Factorial of given no is");
add(l2);
t2=new TextField(10);
add(t2);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==b1)
{
int fact=fact(Integer.parseInt(t1.getText()));
t2.setText(String.valueOf(fact));
}
}
int fact(int f)
{
int s=0;
if(f==0)
return 1;
else
return f*fact(f-1);

MALLA REDDY COLLEGE OF ENGINEERING

Page 19

Java Programming Lab

CSE Department

}
}
/*<applet code="Fact.class" height=300 width=300></applet>*/
output:

MALLA REDDY COLLEGE OF ENGINEERING

Page 20

Java Programming Lab

CSE Department

PROGRAM -4
Creates a User Interface to perform Integer Divisions
Aim: Write a program that creates a user interface to perform integer divisions. The user
enters twonumbers in the textfields, Num1 and Num2. The division of Num1 and
Num2 is displayed in theResult field when the Divide button is clicked. If Num1 or
Num2 were not an integer, theprogram would throw NumberFormatException. If
Num2 were Zero, the program would throwan ArithmeticException Display the
exception in a message dialog box.
Program:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code="Div"width=230 height=250></applet>*/
public class Div extends Applet implements ActionListener
{
String msg;
TextField num1,num2,res;Label
l1,l2,l3; Button div;
public void init()
{
l1=new Label("Number 1");
l2=new Label("Number 2");
l3=new Label("result");
num1=new TextField(10);
num2=new TextField(10);
res=new TextField(10);
div=new Button("DIV");
div.addActionListener(this);
add(l1);
add(num1);
add(l2);
add(num2);
add(l3);
add(res);
add(div);
}
public void actionPerformed(ActionEvent ae)
{
String arg=ae.getActionCommand();
if(arg.equals("DIV"))
{
String s1=num1.getText();

MALLA REDDY COLLEGE OF ENGINEERING

Page 21

Java Programming Lab

CSE Department

String s2=num2.getText();
int num1=Integer.parseInt(s1);
int num2=Integer.parseInt(s2);
if(num2==0)
{
try
{
System.out.println(" ");
}
catch(Exception e)
{
System.out.println("ArithematicException"+e);
}
msg="Arithemetic";
repaint();
}
else if((num1<0)||(num2<0))
{
try
{
System.out.println("");
}
catch(Exception e)
{
System.out.println("NumberFormat"+e);
}
msg="NumberFormat";
repaint();
}
else
{
int num3=num1/num2;
res.setText(String.valueOf(num3));
}
}
}
public void paint(Graphics g)
{
g.drawString(msg,30,70);
}
}

MALLA REDDY COLLEGE OF ENGINEERING

Page 22

Java Programming Lab

CSE Department

Output:

MALLA REDDY COLLEGE OF ENGINEERING

Page 23

Java Programming Lab

CSE Department

PROGRAM -5
Multithreaded Program
Aim: Write a Java program that implements a multithreaded program has three threads.
First thread generates a random integer every 1 second and if the value is even, second
thread computes the square of the number and prints. If the value is odd the third thread
will print the value of cube of the number.
Program:
import java.io.*;
import java.util.*;

class First extends Thread


{
public void run()
{
for(;;)
{
int r;
Random d = new Random();
roll = d.nextInt(200) + 1;
System.out.println(r);
Thread t2=new Second(r);
Thread t3=new Third(r);
try
{
Thread.sleep(1000);
if(roll%2==0)
t2.start();
else
t3.start();
}
catch(InterruptedException e){}
}
}
}
class Second extends Thread
{
int r1;
Second(int r)
{
MALLA REDDY COLLEGE OF ENGINEERING

Page 24

Java Programming Lab

CSE Department

r1=r;
}
public void run()
{
System.out.println("The square of number"+r1+"is:"+r1*r1);
}
}
class Third extends Thread
{
int r1;
Third(int r)
{
r1=r;
}
public void run()
{
System.out.println("The Cube of the Number"+r1+"is: "+r1*r1*r1);
}
}
class Mthread
{
public static void main(String[] args)
{
Thread t1=new First();
System.out.println("press Ctrl+c to
stop......"); t1.start();
}
}

MALLA REDDY COLLEGE OF ENGINEERING

Page 25

Java Programming Lab

CSE Department

Output:
press Ctrl+c to stop......
192
82
The square of number192is:36864
66
The square of number82is:6724
157
The square of number66is:4356
99
The Cube of the Number157is: 3869893
137
The Cube of the Number99is: 970299
21
The Cube of the Number137is: 2571353
138
The Cube of the Number21is: 9261
37
The square of number138is:19044
14
The Cube of the Number37is: 50653
23
The square of number14is:196
61
The Cube of the Number23is: 12167
39
The Cube of the Number61is: 226981
116
The Cube of the Number39is: 59319
39
The square of number116is:13456
56
The Cube of the Number39is: 59319
47
The square of number56is:3136
78
The Cube of the Number47is: 103823

MALLA REDDY COLLEGE OF ENGINEERING

Page 26

Java Programming Lab

CSE Department

PROGRAM -6
Add, Delete, Update and Modify operations using JDBC
Aim: Write a Java program that connects to a database using JDBC and does add,
delete, modify and retrieve operations.
Program:
import java. util.*;
import java. io.*;
import java.sql.*;
class DataBaseTotal
{
public static void main(String args[])
{
menu();
}
static void menu()
{
System.out.println("1.INSERT");
System.out.println("2.DELETE");
System.out.println("3.DISPLAY");
System.out.println("4.UPDATE");
System.out.println("5.EXIT");
Scanner s=new Scanner(System.in);
int ch=Integer.parseInt(s.nextLine());
switch(ch)
{
case 1:insert();
break;
case 2:delete();
break;
case 3:display();
break;
case 4:update();
break;
}
}
static void insert()
{
Scanner s=new Scanner(System.in);
try
{
//loading the driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
MALLA REDDY COLLEGE OF ENGINEERING

Page 27

Java Programming Lab

CSE Department

System.out.println("Connecting to a selected database...");


Connection con =DriverManager.getConnection("jdbc:odbc:radha");
System.out.println("Connected database successfully...");
System.out.println("Enter name");
String name=s.nextLine();
System.out.println("Enter no");
String no=s.nextLine();
System.out.println("Enter
Branch"); String b=s.nextLine();
System.out.println("Enter Age");
String a=s.nextLine();
System.out.println("Inserting records into the table...");
PreparedStatement pstm=con.prepareStatement("insert into student
values(?,?,?,?)"); pstm.setString(1,name);
pstm.setString(2,no);
pstm.setString(3,b);
pstm.setString(4,a);
//execute method to execute the
query pstm.executeUpdate();
System.out.println("Details have been added to database");
//closing the prepared statement and connection object
pstm.close();
con.close();
}
catch(SQLException sqe)
{
System.out.println("SQl error");
}
catch(ClassNotFoundException cnf)
{
System.out.println("Class not found error");
}
menu();
}//closing the insert
method() static void display()
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); //loading the driver
System.out.println("Connecting to a selected database...");
Connection con =DriverManager.getConnection("jdbc:odbc:radha");
System.out.println("Connected database successfully...");
System.out.println("Creating statement...");

MALLA REDDY COLLEGE OF ENGINEERING

Page 28

Java Programming Lab

CSE Department

Statement
stmt = con.createStatement();
String sql ="select sname,sno,branch,age from student;";
System.out.println(sql);
ResultSet rs = stmt.executeQuery(sql);
// Extract data from result set
while(rs.next())
{
//Retrieve by column name
String name = rs.getString("sname");
String no = rs.getString("sno");
String bran = rs.getString("branch");
String age = rs.getString("age");
//Display values
System.out.print("Student Name is: " + name);
System.out.print(", Roll Number is: " + no);
System.out.print(", Branch is: " + bran);
System.out.println(", Age is: " + age);
}
//closing the prepared statement and connection object
stmt.close();
con.close();
}
catch(SQLException sqe)
{
System.out.println("SQl error");
}
catch(ClassNotFoundException cnf)
{
System.out.println("Class not found error");
}
catch(Exception se)
{
se.printStackTrace();
System.out.println(se);
}
menu();
}//closing the display()
static void delete()
{
Scanner s=new Scanner(System.in);
System.out.println("Enter Delete Roll
Number:"); String no=s.nextLine();
try
{
MALLA REDDY COLLEGE OF ENGINEERING

Page 29

Java Programming Lab

CSE Department

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); //loading the driver


System.out.println("Connecting to a selected database..."); Connection
con =DriverManager.getConnection("jdbc:odbc:radha");
System.out.println("Connected database successfully...");
System.out.println("Creating statement...");
Statement stmt = con.createStatement();
String sql ="DELETE FROM student WHERE sno ='"+no+"'";
stmt.executeUpdate(sql);
System.out.println("Data is Deleted
successfully..."); stmt.close();
con.close();
}
catch(SQLException sqe)
{
System.out.println("SQl error");
}
catch(ClassNotFoundException cnf)
{
System.out.println("Class not found error");
}
catch(Exception se)
{
se.printStackTrace();
System.out.println(se);
}
menu();
}//closing delete function
static void update()
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); //loading the driver
System.out.println("Connecting to a selected database..."); Connection
con =DriverManager.getConnection("jdbc:odbc:radha");
System.out.println("Connected database successfully...");
System.out.println("Creating statement...");
Statement stmt = con.createStatement();
Scanner s=new Scanner(System.in);
System.out.println("Enter the Updated Record Roll Number");
String no=s.nextLine();
System.out.println ("\n\n\n");
System.out.println ("\t\t\t [1] TO MODIFY THE NAME\n\n");
System.out.println ("\t\t\t [2] TO MODIFY THE ROLL NUMBER\n\n");
System.out.println ("\t\t\t [3] TO MODIFY THE BRANCH\n\n");
System.out.println ("\t\t\t [4] TO MODIFY AGE\n\n");
System.out.println ("\t\t\t [5] TO EXIT THE SCREEN\n\n");
MALLA REDDY COLLEGE OF ENGINEERING

Page 30

Java Programming Lab

CSE Department

System.out.println("\t\t\t ENTER YOUR OPTION: \t");


String sql=null;
int op=Integer.parseInt(s.nextLine());
switch (op)
{
case 1:
System.out.println("\t\t\tENTER THE NAME
:\t"); String name=s.nextLine();
sql ="update student set sname='"+name+"' WHERE
sno='"+no+"'"; stmt.executeUpdate(sql);
System.out.println("Updated
Successfully"); break;
case 2:
System.out.println ("\t\t\tENTER THE Roll Number :\t");
String no1=s.nextLine();
sql ="update student set sno='"+no1+"' WHERE sno ='"+no+"'";
stmt.executeUpdate(sql);
System.out.println("Updated
Successfully"); break;
case 3:
System.out.println ("\t\t\tENTER THE Branch :\t");
String b=s.nextLine();
sql ="update student set branch='"+b+"' WHERE sno ='"+no+"'";
stmt.executeUpdate(sql);
System.out.println("Updated
Successfully"); break;
case 4:
System.out.println ("\t\t\tENTER THE AGE
:\t"); String a=s.nextLine();
sql ="update student set age='"+a+"' WHERE
sno='"+no+"'"; stmt.executeUpdate(sql);
System.out.println("Updated
Successfully"); break;
}
stmt.close();
con.close();
}
catch(SQLException sqe)
{
System.out.println("SQl error");
}
catch(ClassNotFoundException cnf)
{
System.out.println("Class not found error");
}
MALLA REDDY COLLEGE OF ENGINEERING

Page 31

Java Programming Lab

CSE Department

catch(Exception se)
{
se.printStackTrace();
System.out.println(se);
}
menu();
}
}//class close
Output:
javac DataBaseTotal.java
java DataBaseTotal
1.INSERT
2.DELETE
3.DISPLAY
4.UPDATE
5.EXIT
1
Connecting to a selected database...
Connected database successfully...
Enter name
ramya
Enter no
3
Enter Branch
IT
Enter Age
19
Inserting records into the table...
Details have been added to database
1.INSERT
2.DELETE
3.DISPLAY
4.UPDATE
5.EXIT
3
Connecting to a selected database...
Connected database successfully...
Creating statement...
select sname,sno,branch,age from student;
Student Name is: radha, Roll Number is: 1, Branch is: cse, Age is: 30
Student Name is: sita, Roll Number is: 2, Branch is: ECE, Age is: 24
Student Name is: ramya, Roll Number is: 3, Branch is: IT, Age is: 19

MALLA REDDY COLLEGE OF ENGINEERING

Page 32

Java Programming Lab

CSE Department

PROGRAM -7
Traffic Light Simulation
Aim: Write a java program to simulate a traffic light. The program lets the user select one
of the three lights: red, yellow or green. On selecting a button, an appropriate message
with Stop or Ready or Go should appear above the buttons selected color.

Program:
import java.awt.event.*;
import java.applet.*;
import java.awt.*;
/*
<applet code="TrafficLight" width=250 height=200> </applet>
*/
public class TrafficLight extends Applet implements ItemListener {
String msg = "";
Checkbox red,green,yellow;
CheckboxGroup cbg;
public void init() {
cbg = new CheckboxGroup();
red = new Checkbox("Red", cbg, false); green
= new Checkbox("Green", cbg, false);
yellow = new Checkbox("Yellow", cbg,
false); add(red);
add(yellow);
add(green);
red.addItemListener(this);
yellow.addItemListener(this);
green.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie) {
repaint();
}
// Display current state of the check boxes.
public void paint(Graphics g) {
Color color;
color=Color.BLACK;
g.setColor(color);
g.drawOval(50, 50, 52, 52);
g.drawOval(50, 103, 52, 52);
MALLA REDDY COLLEGE OF ENGINEERING

Page 33

Java Programming Lab

CSE Department

g.drawOval(50, 156, 52, 52);


String col = cbg.getSelectedCheckbox().getLabel();
System.out.println(col);
if(col.equalsIgnoreCase("Green"))
{
color= Color.GREEN;
g.setColor(color);
g.fillOval(50, 156, 52, 52);
g.drawString("GO",110,190);
}
if(col.equalsIgnoreCase("Red"))
{
color=Color.RED;
g.setColor(color);
g.fillOval(51, 51, 51, 51);
g.drawString("STOP",110,80);
}
if(col.equalsIgnoreCase("Yellow"))
{
color=Color.YELLOW;
g.setColor(color);
g.fillOval(50, 103, 51, 51);
color= Color.BLACK;
g.setColor(color);
g.drawString("READY",110,140);
}
}
}
Output:

MALLA REDDY COLLEGE OF ENGINEERING

Page 34

Java Programming Lab

CSE Department

PROGRAM -8
Abstract Class
Aim: Write a java program to create an abstract class named shape that contains two
integers and an empty method named printArea() Provide three classes named
Rectangle,, Triangle and Circle such that each one of the classes extends the class
shape. Each one of the class contains only the method printArea() that print the
area of the given shape.
Program:
// Abstract class that contains abstract method.
abstract class Shape
{
int h=10,w=5;
abstract void printArea();
}
// Classes that illustrates the abstract method.
class Rectangle extends Shape
{
void printArea()
{
float area=0.5*h*w;
System.out.println("The Area of rectangle is"+area);
}
}
class Triangle extends Shape
{
void printArea()
{
float area=h*w;
System.out.println("The Area of Triangle is"+area);
}
}
class Circle extends Shape
{
void printArea()
{
System.out.println("Circle area is not possibles ");
MALLA REDDY COLLEGE OF ENGINEERING

Page 35

Java Programming Lab

CSE Department

}
}
// Class that create objects and call the method.
class ShapeDemo
{
public static void main(String args[])
{
Rectangle obj1 = new Rectangle ();
Triangle obj2 = new Triangle ();
Circle obj3 = new Circle ();
obj1. printArea ();
obj2. printArea ();
obj3. printArea ();
}
}
Output:
The Area of rectangle is25.0
The Area of Triangle is50.0
Circle area is not possible

MALLA REDDY COLLEGE OF ENGINEERING

Page 36

Java Programming Lab

CSE Department

PROGRAM -9
Display Table using Grid Layout
Aim: Suppose that table named Table.txt is stored in a text file. The first line in the file is
the header, and the remaining lines correspond to rows in the table. The elements
are separated by commas. Write a java program to display the table using in Grid
Layout.
Program:
import java.applet.Applet;
import java.awt.*;
import java.io.*;
import java.util.*;
public class Grid extends Applet
{
public void init()
{
String name,num,s;
try
{
int i=lineCount();
setLayout (new GridLayout(i,2));
File fr=new File("Table.txt");
BufferedReader freader=new BufferedReader(new FileReader(fr));
while((s=freader.readLine())!=null)
{
String[] st=s.split(";");
name=st[0];
num=st[1];
add (new TextField(" " + name));
add (new TextField(" " + num));
}
}
catch(Exception e)
{
System.out.println("error from file");
}
}
int lineCount() throws Exception
{
int count = 0;
File f = new File("Table.txt");
MALLA REDDY COLLEGE OF ENGINEERING

Page 37

Java Programming Lab

CSE Department

Scanner input = new Scanner(f);


while (input.hasNextLine()) {
String line = input.nextLine();
count++;
}
return count;
}
}
/*<applet code="Grid.java" width=300 height=300></applet> */

Table.txt
Name of The Employee;Mobile Number
Sita;9999999991
Rama;9999999992
Rani;9999999993
Raju;9999999994
Krishna;9999999995
Ramya;9999999996
Usha;9999999997
Output:

MALLA REDDY COLLEGE OF ENGINEERING

Page 38

Java Programming Lab

CSE Department

PROGRAM -10
Mouse Events
Aim: Write a java program that handles all mouse events and shows the event name at the
center of the window when mouse event is fired(Use Adapter classes).
Program:
import java.awt.*; import
java.awt.event.*; import
java.applet.*;

/* <applet code="AdapterDemo1" width=300 height=100> </applet>*/


public class AdapterDemo1 extends Applet
{
String msg="welcome";
int mouseX=30,mouseY=30;
public void init()
{
addMouseListener(new MyMouseAdapter1(this));
addMouseMotionListener(new MyMouseMotionAdapter1(this));
}
public void paint(Graphics g)
{
g.drawString(msg, mouseX, mouseY);
}
}
class MyMouseAdapter1 extends MouseAdapter
{
AdapterDemo1 adapterDemo;
public MyMouseAdapter1(AdapterDemo1 adapterDemo)
{
this.adapterDemo = adapterDemo;
}
// Handle mouse clicked.
public void mouseClicked(MouseEvent me)
{
adapterDemo.msg="Mouse clicked.";
adapterDemo.repaint();
}
public void mouseEntered(MouseEvent me)
{
adapterDemo.msg = "Mouse
entered."; adapterDemo.repaint();
MALLA REDDY COLLEGE OF ENGINEERING

Page 39

Java Programming Lab

CSE Department

}
}
class MyMouseMotionAdapter1 extends MouseMotionAdapter
{
AdapterDemo1 adapterDemo;
int mouseX,mouseY;
public MyMouseMotionAdapter1(AdapterDemo1 adapterDemo)
{
this.adapterDemo = adapterDemo;
}
// Handle mouse dragged.
public void mouseDragged(MouseEvent
me) { // save coordinates
mouseX = me.getX();
mouseY = me.getY();
adapterDemo.msg = "Mouse Dragged";
adapterDemo.showStatus("Dragging mouse at " + mouseX +" " + mouseY);
adapterDemo.repaint();
}
}
Output:

MALLA REDDY COLLEGE OF ENGINEERING

Page 40

Java Programming Lab

CSE Department

PROGRAM -11
Using File and Hash Table
Aim: Write a java program that loads names and phone numbers from a text file where the
data is organized as one line per record and each field in a record are separated by
tab(\t).It takes a name or phone number as input and prints the corresponding
other value from the hash table(use hash tables).
Program:
import java.lang.*;
import java.util.*;
import java.io.*;

public class HashTablepro1


{
public static void main(String ar[])
{
String s,str,name,num; Hashtable
ht = new Hashtable();
ht.put("Sita","9999999991");
ht.put("Rama","9999999992");
ht.put("Rani","9999999993" );
ht.put("Raju","9999999994");
ht.put("Usha","9999999997");
try
{
File fr=new File("file.txt");
BufferedReader freader=new BufferedReader(new FileReader(fr));
while((s=freader.readLine())!=null)
{
String[] st=s.split("
"); name=st[0];
num=st[1];
searchHash(ht,name,num);
}
}
catch(Exception e)
{
System.out.println("error from file");
MALLA REDDY COLLEGE OF ENGINEERING

Page 41

Java Programming Lab

CSE Department

}
}
static void searchHash(Hashtable ht,String name,String num)
{
String str;
Enumeration names = ht.keys();
int f=0;
System.out.println("The searched Name is:
"+name); while(names.hasMoreElements())
{
//next element retrieves the next element in the dictionary
str = (String) names.nextElement();
if(name.equals(str))
{
//.get(key) returns the value of the key stored in the hashtable
System.out.println(str + ": " + ht.get(str) + "\n");
}
}
}
}
Output:
The searched Name is:
Sita Sita: 9999999991
The searched Name is: Rama
Rama: 9999999992
The searched Name is: Rani
Rani: 9999999993
The searched Name is: Raju
Raju: 9999999994
The searched Name is: Krishna
The searched Name is: Ramya
The searched Name is: Usha
Usha: 9999999997

MALLA REDDY COLLEGE OF ENGINEERING

Page 42

Java Programming Lab

CSE Department

PROGRAM -12
Using Database and Hash Table
Aim: Write a java program that loads names and phone numbers from database. It takes a
name or phone number as input and prints the corresponding other value from the
hash table (use hash tables).
Program:
import java.lang.*;
import java.util.*;
import java.io.*;
import java.sql.*;

public class HashTableData


{
public static void main(String ar[])
{
String s,str,name,num;
Hashtable ht = new Hashtable();
ht.put("Sita","9999999991");
ht.put("Rama","9999999992");
ht.put("Rani","9999999993" );
ht.put("Raju","9999999994");
ht.put("Usha","9999999997");
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); //loading the driver
System.out.println("Connecting to a selected database...");
Connection con =DriverManager.getConnection("jdbc:odbc:radha");
System.out.println("Connected database successfully...");
System.out.println("Creating statement...");
Statement stmt = con.createStatement();
String sql ="select * from emp;";
ResultSet rs = stmt.executeQuery(sql);
//Extract data from result set
while(rs.next())
{
MALLA REDDY COLLEGE OF ENGINEERING

Page 43

Java Programming Lab

CSE Department

//Retrieve by column name


name = rs.getString(1);
String no = rs.getString(2);
searchHash(ht,name,no);

}
//closing the prepared statement and connection object
stmt.close();
con.close();
}
catch(SQLException sqe)
{
System.out.println("SQl error");
}
catch(ClassNotFoundException cnf)
{
System.out.println("Class not found error");
}
catch(Exception se)
{
se.printStackTrace();
System.out.println(se);
}
}
static void searchHash(Hashtable ht,String name,String num)
{
String str;
Enumeration names = ht.keys();
int f=0;
System.out.println("The searched Name is:"+name);
while(names.hasMoreElements())
{
//next element retrieves the next element in the dictionary
str = (String) names.nextElement();
if(name.equals(str))
{
//.get(key) returns the value of the key stored in the hashtable
System.out.println(str + ": " + ht.get(str) + "\n");
}
MALLA REDDY COLLEGE OF ENGINEERING

Page 44

Java Programming Lab

CSE Department

}
}
}
Output:
Connecting to a selected database
Connected database successfully
Creating statement
The searched Name is:Sita
Sita:9999999991
The searched Name is:Ramya
The searched Name is:Rama
Sita:9999999992

MALLA REDDY COLLEGE OF ENGINEERING

Page 45

Java Programming Lab

CSE Department

PROGRAM -13
Using File and Database
Aim: Write a java program that takes tab separated data (one record per line) from text file
and inserts them into a database.
Program:
import java.io.*;
import java.util.*;
import java.sql.*;

class FileIntoDataBase
{
PreparedStatement pt = null;
Connection con=null;
public static void main(String[] args) throws IOException , SQLException,Exception
{
FileIntoDataBase b = new
FileIntoDataBase(); b.database();
}
public void database()throws SQLException,Exception
{
String s,name,num;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con =DriverManager.getConnection("jdbc:odbc:radha");
File f=new File("file.txt");
BufferedReader fr=new BufferedReader(new FileReader(f));
while((s=fr.readLine())!=null)
{
String[] st=s.split("
"); name=st[0];
num=st[1];
add(con,name,num);
}
}
catch(Exception e)
{
System.out.println(e);
}
//pt.close();
con.close();
}
MALLA REDDY COLLEGE OF ENGINEERING

Page 46

Java Programming Lab

CSE Department

public void add(Connection con,String name,String no) throws Exception


{ System.out.println(name+" "+no);
pt=con.prepareStatement("insert into emp(ename,pno) values(?,?)");//just specified
inserting field names in query,
//otherwise throwing exception
preparedstatement fields and destination fields not matching
// System.out.println(pt);
pt.setString(1,name);
pt.setString(2,no);
pt.executeUpdate();
System.out.println("one record inserted in to database");
}
}
//Source code for file.txt
Sita 9999999991
Rama 9999999992
Raju 9999999993
Output:
Sita 9999999991
one record inserted in to database
Rama 9999999992
one record inserted in to database
Raju 9999999993
one record inserted in to database

MALLA REDDY COLLEGE OF ENGINEERING

Page 47

Java Programming Lab

CSE Department

PROGRAM -14
Display Meta-Data of a given Table
Aim: Write a java program that prints the meta-data of a given table.
Program:
import java.sql.*;
import java.util.StringTokenizer;
public class TableMetadata {
public static void main(java.lang.String[] args)
{
System.out.println("--- Table Viewer ---");
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con =DriverManager.getConnection("jdbc:odbc:radha");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM student");
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
for(int col = 1; col <= columnCount; col++) {
System.out.print(rsmd.getColumnLabel(col));
System.out.print(" (" +
rsmd.getColumnTypeName(col)+")"); if(col < columnCount)
System.out.print(", ");
}
System.out.println();

while(rs.next()) {
for(int col = 1; col <= columnCount; col++)
{ System.out.print(rs.getString(col));
if(col < columnCount)
System.out.print(", ");
}
System.out.println();
}
rs.close();
stmt.close();
con.close();
MALLA REDDY COLLEGE OF ENGINEERING

Page 48

Java Programming Lab

CSE Department

}
catch (ClassNotFoundException e) {
System.out.println("Unable to load database driver class");
}
catch (SQLException e) {
System.out.println("SQL Exception: " + e.getMessage());
}
}
}
//Student table information

sname
radha
sita
ramya

student
sno branch
1 cse
2 ECE
3 IT

age
20
19
19

Output:
--- Table Viewer --sname(VARCHAR),sno(VARCHAR),branch(VARCHAR),age(VARCHAR)
radha, 1, cse, 20
sita, 2, ECE, 19
ramya, 3, IT, 19

MALLA REDDY COLLEGE OF ENGINEERING

Page 49

Java Programming Lab

CSE Department

PROGRAM -15
Client-Server Communication
Aim: Write a java program to implement client-server communication using socket.
Program:
// File Name GreetingClient.java
// Import the packages.
import java.net.*;
import java.io.*;
public class GreetingClient
{
public static void main(String [] args)
{
String serverName = args[0];
int port = Integer.parseInt(args[1]);
try
{
System.out.println("Connecting to " + serverName
+ " on port " + port);
Socket client = new Socket(serverName,
port); System.out.println("Just connected to "
+ client.getRemoteSocketAddress());
OutputStream outToServer =
client.getOutputStream(); DataOutputStream out =
new DataOutputStream(outToServer);
out.writeUTF("Hello from "
+ client.getLocalSocketAddress());
InputStream inFromServer = client.getInputStream();
DataInputStream in =
new DataInputStream(inFromServer);
System.out.println("Server says " +
in.readUTF()); client.close();
}catch(IOException e)
{
e.printStackTrace();
}
}
}
// File Name GreetingServer.java
MALLA REDDY COLLEGE OF ENGINEERING

Page 50

Java Programming Lab

CSE Department

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

public class GreetingServer extends Thread


{
private ServerSocket serverSocket;
public GreetingServer(int port) throws IOException
{
serverSocket = new ServerSocket(port);
serverSocket.setSoTimeout(10000);
}
public void run()
{
while(true)
{
try
{
System.out.println("Waiting for client on port " +
serverSocket.getLocalPort() + "...");
Socket server = serverSocket.accept();
System.out.println("Just connected to "
+ server.getRemoteSocketAddress());
DataInputStream in =
new DataInputStream(server.getInputStream());
System.out.println(in.readUTF());
DataOutputStream out =
new DataOutputStream(server.getOutputStream());
out.writeUTF("Thank you for connecting to "
+ server.getLocalSocketAddress() +
"\nGoodbye!"); server.close();
}catch(SocketTimeoutException s)
{
System.out.println("Socket timed
out!"); break;
}catch(IOException e)
{
e.printStackTrace();
break;
}
}
}
public static void main(String [] args)
{
int port = Integer.parseInt(args[0]);
MALLA REDDY COLLEGE OF ENGINEERING

Page 51

Java Programming Lab

CSE Department

try
{
Thread t = new
GreetingServer(port); t.start();
}catch(IOException e)
{
e.printStackTrace();
}
}
}
Output:
Compile client and server and then start server as follows:
$ java GreetingServer 6066
Waiting for client on port 6066...
Check client program as follows:
$ java GreetingClient localhost 6066
Connecting to localhost on port 6066
Just connected to localhost/127.0.0.1:6066
Server says Thank you for connecting to
/127.0.0.1:6066 Goodbye!

MALLA REDDY COLLEGE OF ENGINEERING

Page 52

Java Programming Lab

CSE Department

PROGRAM -16
Simple Project
AIM: To develop a simple java application for generation of Aadhar Card
Program:
//Source code for Start.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
class Start extends JFrame //implements ActionListener
{
JButton badd,bsearch,bdel;
JLabel ladd,lsearch,ldel,ltitle;
Start()
{
super("Aadharcard");
setSize(800,800);
setVisible(true);
setLayout(null);
ltitle=new JLabel("Aadharcard");
ltitle.setBounds(20,150,210,50);
add(ltitle);
ladd=new JLabel("add aadharcard
information"); ladd.setBounds(30,200,335,20);
add(ladd);
lsearch=new JLabel("search candidate");
lsearch.setBounds(30,250,335,20);
add(lsearch);
ldel=new JLabel("del aadharcard information");
ldel.setBounds(30,300,335,20);
add(ldel);
badd=new JButton("add");
badd.setBounds(400,250,130,30);
add(badd);
bsearch=new JButton("search");
bsearch.setBounds(400,300,130,30);
add(bsearch);
bdel=new JButton("del");
bdel.setBounds(400,350,130,30);
add(bdel);
badd.addActionListener(new add1());
bsearch.addActionListener(new search1());
MALLA REDDY COLLEGE OF ENGINEERING

Page 53

Java Programming Lab

CSE Department

bdel.addActionListener(new del1());
}
class add1 implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
new add();
}
}
class search1 implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
new search();
}
}
class del1 implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
new del();
}
}
public static void main(String args[])
{
Start s1=new Start();
}
}
//Source code for add.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.sql.*;
class add extends JFrame implements ActionListener
{
JLabel lname,ldob,lgender,lmsg;
JTextField tname,tdob,tgender;
JButton bsubmit;
Connection con;
add()
{
setLayout(null);
setSize(800,800);
setVisible(true);

MALLA REDDY COLLEGE OF ENGINEERING

Page 54

Java Programming Lab

CSE Department

lmsg=new JLabel();
lname=new JLabel("name");
lname.setBounds(50,50,200,30);
tname=new JTextField(10);
tname.setBounds(250,50,250,30);
ldob=new JLabel("dob");
ldob.setBounds(100,80,200,30);
tdob=new JTextField(10);
tdob.setBounds(255,100,200,30);
lgender=new JLabel("gender");
lgender.setBounds(200,150,210,50);
tgender=new JTextField(10);
tgender.setBounds(350,170,250,30);

add(lname);
add(tname);
add(ldob);
add(tdob);
add(lgender);
add(tgender);
bsubmit=new JButton("submit");
bsubmit.setBounds(400,250,130,30);
add(bsubmit);
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:card","","");
}
catch(Exception e)
{
System.out.println("no connected");
}
bsubmit.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==bsubmit)
submit();
}
void submit()
{
String s1=tname.getText();
int s2=Integer.parseInt(tdob.getText());
MALLA REDDY COLLEGE OF ENGINEERING

Page 55

Java Programming Lab

CSE Department

String s3=tgender.getText();
System.out.println(s1+s2+s3);
try
{
Statement st=con.createStatement();
int i=st.executeUpdate("insert into cardtable(aname,dob,gender)
values('"+s1+"','"+s2+"','"+s3+"')");
if(i!=0)
JOptionPane.showMessageDialog(lmsg,"Data saved successfully");
}
catch(Exception e)
{
System.out.println("datais not inserted"+e);
}
}
}
//Source code for del.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.sql.*;

class del extends JFrame implements ActionListener


{
JButton bdel; JLabel
lsearch,lmsg;
JTextField tsearch;
Connection con;
del()
{
super("delete aadhar card");
setLayout(null);
setSize(1024,768);
setVisible(true);
lsearch = new JLabel("aname");
add(lsearch);
lsearch.setBounds(50,100,100,30);
tsearch = new JTextField(11);
add(tsearch);
tsearch.setBounds(150,100,100,30);
bdel = new JButton("del");
add(bdel);

MALLA REDDY COLLEGE OF ENGINEERING

Page 56

Java Programming Lab

CSE Department

bdel.setBounds(50,150,100,30);
lmsg = new JLabel("");
add(lmsg);
lmsg.setBounds(50,200,100,30);
bdel.addActionListener(this);
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:card","","");
}catch(Exception ae)
{
System.out.println("not connecd"+ae);
}
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==bdel)
del1();
}
public void del1()
{
String caname=tsearch.getText();
try{
String qaname = "delete * from cardtable
where aname='"+caname+"';";
Statement st=con.createStatement();
int i=st.executeUpdate(qaname);
}
catch(Exception e){
System.out.println(e);
}
}
}
//Source code for search.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.sql.*;

MALLA REDDY COLLEGE OF ENGINEERING

Page 57

Java Programming Lab

CSE Department

class search extends JFrame implements ActionListener


{
JLabel lname,ldob,lgender;
JTextField tname,tdob,tgender;
JButton bsearch;
Connection con;
search()
{
setLayout(null);
setSize(1024,768);
setVisible(true);
lname = new JLabel("aname");
lname.setBounds(50,100,100,30);
add(lname);
tname = new JTextField(11);
tname.setBounds(150,100,100,30);
add(tname);
bsearch = new JButton("Search");
bsearch.setBounds(100,150,100,30);
add(bsearch);
ldob = new JLabel("dob");
ldob.setBounds(50,200,100,30);
add(ldob);
tdob = new JTextField(15);
tdob.setBounds(150,200,100,30);
add(tdob);
lgender = new JLabel("gender");
lgender.setBounds(50,250,100,30);
add(lgender);
tgender = new JTextField(30);
tgender.setBounds(150,250,100,30);
add(tgender);

bsearch.addActionListener(this);
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:card","","");
}catch(Exception ae)
MALLA REDDY COLLEGE OF ENGINEERING

Page 58

Java Programming Lab

CSE Department

{
System.out.println("not connected"+ae);
}
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==bsearch)
getDetails();
}
void getDetails()
{
String caname=
tname.getText(); ResultSet rs;
try{
Statement st=con.createStatement();
String cname= "select * from cardtable where aname = '"+caname+"'";
rs=st.executeQuery(cname);
while(rs.next())
{
tdob.setText(rs.getString(2));
tgender.setText(rs.getString(3));
System.out.println(rs.getString(2)+rs.getString(3));
}
}
catch(Exception e){
System.out.println(e);
}

}
}
//Sample database db4.mdb
Table Name: cardtable
Fields: aname varchar, dob varchar, gender varchar

MALLA REDDY COLLEGE OF ENGINEERING

Page 59

You might also like