Javalab PDF
Javalab PDF
Javalab PDF
CSE Department
COURSE OUTCOMES:
1.
2.
3.
4.
5.
Page 1
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
Page.No
4
15
18
19
21
24
27
33
35
37
39
41
Page 2
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
50
16
53
socket.
Simple Java Project
Page 3
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.
Page 4
CSE Department
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.
Page 5
CSE Department
Page 6
CSE Department
Page 7
CSE Department
Page 8
CSE Department
Page 9
CSE Department
Page 10
CSE Department
Page 11
CSE Department
Page 12
CSE Department
Page 13
CSE Department
else if(d<0)
{
System.out.println("the d is -ve and there are no roots");
}
}
}
Page 14
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
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
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:
Page 17
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:
Page 18
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);
Page 19
CSE Department
}
}
/*<applet code="Fact.class" height=300 width=300></applet>*/
output:
Page 20
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();
Page 21
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);
}
}
Page 22
CSE Department
Output:
Page 23
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.*;
Page 24
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();
}
}
Page 25
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
Page 26
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
CSE Department
Page 28
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
CSE Department
Page 30
CSE Department
Page 31
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
Page 32
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
CSE Department
Page 34
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
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
Page 36
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
CSE Department
Table.txt
Name of The Employee;Mobile Number
Sita;9999999991
Rama;9999999992
Rani;9999999993
Raju;9999999994
Krishna;9999999995
Ramya;9999999996
Usha;9999999997
Output:
Page 38
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.*;
Page 39
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:
Page 40
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.*;
Page 41
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
Page 42
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.*;
Page 43
CSE Department
}
//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
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
Page 45
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
CSE Department
Page 47
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
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
Page 49
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
CSE Department
import java.net.*;
import java.io.*;
Page 51
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!
Page 52
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
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);
Page 54
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
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.*;
Page 56
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.*;
Page 57
CSE Department
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
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
Page 59