0% found this document useful (0 votes)
6 views55 pages

TSP Record

Uploaded by

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

TSP Record

Uploaded by

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

PANIMALAR ENGINEERING COLLEGE

An Autonomous Institution, Affiliated to Anna University, Chennai


(A CHRISTIAN MINORITY INSTITUTION)
JAISAKTHI EDUCATIONAL TRUST
BANGALORE TRUNK ROAD, VARADHARAJAPURAM, NASARATHPET,
POONAMALLEE, CHENNAI – 600 123
DEPARTMENT OFARTIFICIAL INTELLIGENCE AND MACHINE LEARNING

23ES1411 – TECHNICAL SKILL PRACTICES III LABORATORY


II AIML - IV SEMESTER

Name : _______________________________

Roll Number : _______________________________

Register Number : ________________________________


PANIMALAR ENGINEERING COLLEGE
An Autonomous Institution, Affiliated to Anna University, Chennai
(A CHRISTIAN MINORITY INSTITUTION)
JAISAKTHI EDUCATIONAL TRUST
BANGALORE TRUNK ROAD, VARADHARAJAPURAM, NASARATHPET,
POONAMALLEE, CHENNAI – 600 123
DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING

BONAFIDE CERTIFICATE
This is a Certified Bonafide Record Book of

Mr. /Ms. …………………………………………………………………….………….

Register Number ……………………………………………………….……………..

Submitted for END SEMESTER Practical Examinations held on _____________in

23ES1411 – TECHNICAL SKILL PRACTICES III LABORATORY during May 2025.

Staff – In charge

Internal Examiner External Examiner


INDEX
S.No. NameoftheProgram PageNo.

1 Week1:

Use eclipse or Netbean platform and acquaint with the various menus,create
a test project, add a test class and run it see how you can use
22-23
autosuggestions,autofill.Trycodeformatterandcoderefactoringlikerenaming
variables, methods and classes. Try debug step by step with asmall program
of about 10 to 15 lines which contains at least one if
elseconditionandaforloop.

2 Week2:

WriteaJavaprogramthatworksasasimplecalculator.Useagridlayoutto arrange
buttons for the digits and for the +, -,*, % operations. Add a textfield to display 24-27
the result. Handle any possible exceptions like divide byzero.

3 Week3:

a)Developanappletthatdisplaysasimplemessage.
28-30
b)DevelopanAppletthatreceivesanintegerinonetextfield&computeitsfactorialv
alue&returnsitinanothertextfiledwhenthebutton“Compute”isclicked

4. Week4:

Write a program that creates a user interface to perform integer


divisions.Theuser enters twonumbersin
thetextfields,Num1andNum2.ThedivisionofNum1and 31-33
Num2isdisplayedintheResultfieldwhentheDividebuttonisclicked.IfNum1orNu
m2werenotaninteger,theprogram would throw a NumberFormatException. If
Num2 were Zero, theprogram would throw an Arithmetic Exception Display
the exception in amessagedialogbox

5 Week5:

Write a java program that implements a multi-thread application that hasthree


threads.Firstthread generatesrandom integerevery 1 second andifthe value is 34-36
even, second thread computes the square of the number andprints.Ifthe value
is odd,thethird thread will printthe value ofcube ofthenumber.

6 Week6:
37-43
WriteajavaprogramthatconnectstoadatabaseusingJDBCanddoes
add,deletes,modifyandretrieveoperations

7 Week7:

Writeajavaprogramthatsimulatesatrafficlight.Theprogramletstheuser select
one of three lights: red, yellow, or green with radio buttons. Onselecting a 44-48
button, an appropriate message with “stop” or “ready” or
“go”shouldappearabovethebuttonsinaselectedcolor.Initiallythereisno
messageshown.
8 Week8:
Write a java program to create an abstract class named Shape that
containstwointegersandanemptymethodnamedprintArea().Providethreeclasses
named Rectangle, Triangle and Circle such that each one of theclasses extends 49-50
the class Shape. Each one of the classes contain only
themethodprintArea()thatprintstheareaofthegivenshape.

9 Week9:

Supposethata tablenamed Table.txt is stored ina text file.The


firstlineinthefileheaderandtheremaininglinescorrespondtorowinthetable.Theel 51-53
ementsareseparatedbycommas.WriteaJavaprogramtodisplaythetableusinglabel
s ingridlayout.

10 Week10:

Write a Java program that handles all mouse events and shows the 54-56
eventnameatthecenterofthewindowwhenamouseeventisfired.(Useadapterclass
es).

11 Week11:

Write a java program that loads names and phone numbers from a text
filewherethedatais organized as one lineper record and each field in arecord are 57-59
separated by a tab (\t).it takes a name or phone number as inputand prints the
corresponding other value from the hash table(hint: use hashtables)

12 Week12:
60-64
Implementtheaboveprogramwithdatabaseinsteadofatextfile.

13 Week13:

Writeajavaprogramthattakestabseparateddata(onerecordperline)fromatextfilean 65-68
dinsertsthemintoadatabase

Week14:
69-71
Writeajavaprogramthatprintsthemeta-dataofagiventable.
Solutions:-
Use eclipse or Netbean platform and acquaint with the
various menus, create a testproject, add a test class and
run it see howyou can use auto suggestions,auto fill.
Trycode formatter and code refactoring like renaming
variables, methods and classes. Trydebug step by step
with a smallprogram of about
10to15lineswhichcontains at leastoneif
elseconditionanda forloop.
Program:-
publicclassProg1
{

publicstaticvoidmain(String[]args)
{
System.out.println("\nProg.isshowingevenno");for(int
i=2;i<=20;i++)
{
if(i%2==0)
{
System.out.print("\n"+i);
}

}
}
}

Compile:-

D:>javacProg1.java

Run:-

D:>javaProg1
Output:-

InNetbeansIDE:-

InCommandPrompt:-
1. WriteaJavaprogramthatworksasasimplecalculator.Useagridlayouttoarrangebuttonsforthe
digitsandforthe+,-
,*,%operations.Addatextfieldtodisplaytheresult.Handleanypossibleexceptionslikedividebyze
ro.

Program:-

importjavax.swing.*;im
portjava.awt.*;importjav
a.awt.event.*;
//<appletcode=Calculatorheight=300width=200></applet>pub
licclassCalculatorextendsJApplet
{
publicvoidinit()
{
CalculatorPanelcalc=newCalculatorPanel();getContentPane().add(calc);
}
}
classCalculatorPanelextendsJPanelimplementsActionListener
{
JButtonn1,n2,n3,n4,n5,n6,n7,n8,n9,n0,plus,minus,mul,div,dot,equal;stati
cJTextFieldresult=newJTextField("0",45);
staticStringlastCommand=null;JOpti
onPanep=newJOptionPane();doublep
reRes=0,secVal=0,res;privatestaticvo
idassign(Stringno)
{
if((result.getText()).equals("0"))res
ult.setText(no);
elseif(lastCommand=="=")
{
result.setText(no);lastCommand
=null;

else

result.setText(result.getText()+no);

publicCalculatorPanel()
{
setLayout(newBorderLayout());result.setEditable(false);

result.setSize(300,200);add(result,Border

Layout.NORTH);JPanelpanel=newJPane

l();panel.setLayout(newGridLayout(4,4))

;
n7=newJButton("7");panel.add(n7)
;n7.addActionListener(this);n8=ne
wJButton("8");panel.add(n8);n8.ad
dActionListener(this);n9=newJBut
ton("9");panel.add(n9);n9.addActi
onListener(this);div=newJButton("
/");panel.add(div);div.addActionLi
stener(this);n4=newJButton("4");p
anel.add(n4);n4.addActionListener
(this);n5=newJButton("5");panel.a
dd(n5);n5.addActionListener(this);
n6=newJButton("6");panel.add(n6)
;n6.addActionListener(this);mul=n
ewJButton("*");panel.add(mul);mu
l.addActionListener(this);n1=newJ
Button("1");panel.add(n1);n1.addA
ctionListener(this);n2=newJButton
("2");panel.add(n2);n2.addActionL
istener(this);
n3=newJButton("3");panel.add(n3);
n3.addActionListener(this);minus=n
ewJButton("-
");panel.add(minus);minus.addActio
nListener(this);dot=newJButton(".")
;panel.add(dot);dot.addActionListen
er(this);n0=newJButton("0");panel.a
dd(n0);n0.addActionListener(this);e
qual=newJButton("=");panel.add(eq
ual);equal.addActionListener(this);p
lus=newJButton("+");panel.add(plu
s);plus.addActionListener(this);add(
panel,BorderLayout.CENTER);
}
publicvoidactionPerformed(ActionEventae)
{
if(ae.getSource()==n1)assign("1");
else if(ae.getSource()==n2)
assign("2");else if(ae.getSource()==n3)
assign("3");else if(ae.getSource()==n4)
assign("4");else if(ae.getSource()==n5)
assign("5");else if(ae.getSource()==n6)
assign("6");else if(ae.getSource()==n7)
assign("7");else if(ae.getSource()==n8)
assign("8");else if(ae.getSource()==n9)
assign("9");else if(ae.getSource()==n0)
assign("0");elseif(ae.getSource()==dot)
{
if(((result.getText()).indexOf("."))==-
1)result.setText(result.getText()+".");
}
elseif(ae.getSource()==minus)
{
preRes=Double.parseDouble(result.getText());l
astCommand="-";
result.setText("0");
}
elseif(ae.getSource()==div)
{
preRes=Double.parseDouble(result.getText());lastCo
mmand="/";
result.setText("0");
}
elseif(ae.getSource()==equal)
{
secVal=Double.parseDouble(result.getText());if(lastCommand.equal
s("/"))
res=preRes/secVal;
elseif(lastCommand.equals("*"))res=p
reRes*secVal;
elseif(lastCommand.equals("-
"))res=preRes-secVal;
elseif(lastCommand.equals("+"))res=p
reRes+secVal;
result.setText(""+res);lastComm
and="=";
}
elseif(ae.getSource()==mul)
{
preRes=Double.parseDouble(result.getText());lastCo
mmand="*";
result.setText("0");
}
elseif(ae.getSource()==plus)
{
preRes=Double.parseDouble(result.getText());lastCo
mmand="+";
result.setText("0");
}
}
}
Output:-
2. a)Developanappletthatdisplaysasimplemessage.

Program:-

importjava.awt.*;impor

tjava.applet.*;

/*<appletcode=“HelloJava” width=200

height=60></applet>*/publicclassHelloJ

avaextendsApplet{

publicvoidpaint(Graphicsg){

g.drawString(“HelloJava”,10,100);

Output:-
3.b)DevelopanAppletthatreceivesanintegerinonetextfield&computeitsfactorialvalue&returnsit
inanothertextfiledwhenthebutton“Compute”isclicked.

Program:-

importjava.awt.*;import

java.lang.String;importj

ava.awt.event.*;

importjava.applet.Applet;

publicclassFactextendsAppletimplementsActionListener

Stringstr;Bu

ttonb0;

TextFieldt1,t2;

Labell1;

publicvoidinit(){Pane

lp=newPanel();

p.setLayout(newGridLayout());

add(newLabel("EnteranyIntegervalue"));add(t1=ne

wTextField(20));

add(newLabel("Factorialvalueis:

"));

add(t2=newTextField(20));

add(b0=newButton("compute"));b0.addActionListen

er(this);

publicvoidactionPerformed(ActionEvente)

inti,n,f=1;

n=Integer.parseInt(t1.getText());
for(i=1;i<=n;i++)f

=f*i;

t2.setText(String.valueOf(f));re

paint();

Output:-
4.Write aprogram that creates auserinterfacetoperform integerdivisions.The userenters two
numbers in the text fields, Num1 and Num2. The division of Num1 and Num2
isdisplayedintheResultfieldwhentheDividebuttonisclicked.IfNum1orNum2werenotan integer,
the program would throw a NumberFormatException. If Num2 were Zero, theprogram
wouldthrow an Arithmetic Exception Displaytheexception in amessage dialogbox.

Program:-

importjava.awt.*;import
java.awt.event.*;importj
ava.applet.*;
publicclassAdd1extendsAppletimplementsActionListener
{
Stringmsg;
TextField num1,
num2,res;Labell1,l2,l3;
Buttondiv;public
voidinit()
{
l1=newLabel("Number1");l2
=newLabel("Number2");l3=ne
wLabel("result");num1=newT
extField(10);num2=newTextF
ield(10);res=newTextField(30)
;
div=newButton("DIV");div.a
ddActionListener(this);add(l
1);
add(num1);a
dd(l2);add(nu
m2);add(l3);
add(res);
add(div);
}

publicvoidactionPerformed(ActionEventae)
{
Stringarg=ae.getActionCommand();if(
arg.equals("DIV"))
{
Strings1=num1.getText();St
rings2=num2.getText();
intnum1=Integer.parseInt(s1);
intnum2=Integer.parseInt(s2);if(n
um2==0)
{
msg="ArithemeticException";rep
aint();
}
elseif((num1<0)||(num2<0))
{
msg="NumberFormatException";repaint
();
}
else
{
intnum3=num1/num2;msg=St
ring.valueOf(num3);
}
res.setText(msg);
}
}
publicvoidpaint(Graphicsg)
{
//g.drawString(msg,30,70);
}
}

APPLET.HTML

<html>

<head>

</head>

<body>

/*<appletcode="Add1.class"width=350height=300>

</applet>*/

</body>

</html>

Output:-
5.)Writeajavaprogramthatimplementsamulti-threadapplicationthathasthreethreads.First thread
generates 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
thirdthreadwillprintthevalueofcubeofthenumber.

Program:-

classRandomGenThreadimplementsRunnable
{
doublenum;publi
cvoidrun()
{
try{
SquareThreadsqt=newSquareThread();Threadsq
uareThread=newThread(sqt);CubeThreadcbt=ne
wCubeThread();ThreadcubeThread=newThread(
cbt);squareThread.start();
cubeThread.start();fo
r(inti=0;i<10;i++)
{
System.out.println("t1-
"+i);if(i%2 ==0)
{
sqt.setNum(newDouble(i));
}
else
{
cbt.setNum(newDouble(i));
}
Thread.sleep(1000);
}
}catch(InterruptedExceptione)
{
e.printStackTrace();
}
}

}
classSquareThreadimplementsRunnable
{
Doublenum;publi
cvoidrun()
{

try{
int
i=0;do
{ i++;
if(num!=null&&num%2==0)
{
System.out.println("t2---
>squareof"+num+"="+(num*num));num= null;
}
Thread.sleep(1000);
}while(i<=5);
}
catch(Exceptione)
{
e.printStackTrace();
}
}

publicDoublegetNum()
{
returnnum;
}

publicvoidsetNum(Doublenum)
{
this.num=num;
}
}

classCubeThreadimplementsRunnable
{
Doublenum;publi
cvoidrun()
{
try{
int
i=0;do
{ i++;
if(num!=null&&num%2!=0)
{
System.out.println("t3--
>Cubeof"+num+"="+(num*num*num));num=null;

Thread.sleep(1000);
}
while(i<=5);
}
catch(Exceptione)
{
e.printStackTrace();
}
}
publicDoublegetNum()
{
returnnum;
}

publicvoidsetNum(Doublenum)
{
this.num=num;
}
}
publicclassMultiThreaded
{
publicstaticvoidmain(String[]args)throwsInterruptedException
{
ThreadrandomThread=newThread(newRandomGenThread());randomThread.start();
}

}
Output:-
6).WriteajavaprogramthatconnectstoadatabaseusingJDBCanddoesadd,deletes,modifyandretrieve
operations?

Program:-

ConnectionUtil.java

importjava.sql.Connection;impor

tjava.sql.DriverManager;importja

va.sql.SQLException;publicclass

ConnectionUtil

publicstaticConnectiongetConnection()throwsSQLException

Connectionconnection=null;try

Class.forName("com.mysql.jdbc.Connection");

connection=DriverManager.getConnection("jdbc:mysql://192.168.216.250:3306/vijju","root","root"
);

catch(ClassNotFoundExceptione)

e.printStackTrace();

catch(SQLExceptione)

e.printStackTrace();

System.out.println("messageforconnectionopen"+connection);return

connection;

}
}

StudentDetails.java

publicclassStudentDetails

privatelongst_id;private

String

st_name;privatelongst_

mobile;

publicStudentDetails(longst_id,Stringst_name,longst_mobile)

this.st_id=st_id;this.st_nam

e=st_name;this.st_mobile=s

t_mobile;

publiclonggetSt_id()

returnst_id;

publicvoidsetSt_id(longst_id)

this.st_id=st_id;

publicStringgetSt_name()

returnst_name;

publicvoidsetSt_name(Stringst_name)

{
this.st_name=st_name;

publiclonggetSt_mobile()

returnst_mobile;

publicvoidsetSt_mobile(longst_mobile)

this.st_mobile=st_mobile;

Prog6.java

importjava.sql.Connection;

importjava.sql.PreparedStatement;import

java.sql.ResultSet;

importjava.sql.SQLException;p

ublicclassProg6

StringcreateTableQuery="createtabletest.student_details(st_namevarchar(50),st_mobilenumeric(10),st_i
dnumeric(10))";

publicstaticvoidmain(String[]args)

Connectionconn=

null;try

conn=ConnectionUtil.getConnection();Prog6

prog6=newProg6();

System.out.println("Student_details table
databeforeinserting:");prog6.retrieveData(conn);

StudentDetailsst1=newStudentDetails(1,"GNIT",23232323);StudentDetails

st2= newStudentDetails(2,

"GNEC",24242424);StudentDetailsst3=newStudentDetails(3,"GNITC",2525

2525);prog6.insertData(conn,st1);

prog6.insertData(conn,st2);p

rog6.insertData(conn,st3);

System.out.println("Student_detailstabledataafterinserting:");prog6.retrieveData(c

onn);

prog6.deleteARow(conn,2);System.out.println("Student_detailst

abledataafterdeleting:");prog6.retrieveData(conn);

prog6.modifyData(conn,26262626,3);System.out.println("Student_details

table dataaftermodifying:");prog6.retrieveData(conn);

}catch(SQLExceptione)

e.printStackTrace();

}finally

try{conn.close();

}catch(SQLExceptione)

e.printStackTrace();

privatevoidmodifyData(Connectionconn,longst_mobile,longst_id)

Stringquery="updatestudent_detailssetst_mobile=?wherest_id=?";try{
PreparedStatementpstmt=

conn.prepareStatement(query);pstmt.setLong(1,st_mobile);

pstmt.setLong(2,st_id);

introw=pstmt.executeUpdate();

//System.out.println(row);

}catch(SQLExceptione)

{ e.printStackTrace();

privatevoiddeleteARow(Connectionconn,longst_id)

Stringquery="deletefromstudent_detailswherest_id=?";try

PreparedStatementpstmt=

conn.prepareStatement(query);pstmt.setLong(1,st_id);

introw=pstmt.executeUpdate();

//System.out.println(row);

catch(SQLExceptione)

e.printStackTrace();

privatevoidinsertData(Connectionconn,StudentDetailsdetails)

String query = "insert intotest.student_details

values(?,?,?)";try

{
PreparedStatementpstmt=

conn.prepareStatement(query);pstmt.setString(1,details.getSt_name());

pstmt.setLong(2,details.getSt_mobile());pstmt.setLon

g(3,details.getSt_id());

introw=pstmt.executeUpdate();

//System.out.println(row);

catch(SQLExceptione)

e.printStackTrace();

privatevoidretrieveData(Connectionconn)

try{

Stringquery="select*fromtest.student_details";PreparedStatem

entpstmt=conn.prepareStatement(query);ResultSetrs=pstmt.exe

cuteQuery();System.out.println("ST_ID\tST_NAME\t\tST_M

OBILE");while(rs.next())

System.out.println(rs.getString("st_id")+"\t"+rs.getString("st_name")+"\t\t"+rs.getString("st_mo
bile"));

catch(SQLExceptione)

e.printStackTrace();

}
}

Output:-
7) Writeajavaprogramthatsimulatesatrafficlight.Theprogramletstheuserselectoneofthreeligh
ts:red,yellow,orgreenwithradiobuttons.Onselectingabutton,anappropriatemessagewith“stop
”or“ready”or“go”shouldappearabovethebuttonsinaselected
color.Initiallythereisnomessageshown.

Program:-

TrafficSignal.java

importjava.awt.*;import

java.applet.*;importjava.

awt.event.*;

publicclassTrafficSignalextendsAppletimplementsRunnable

Threadt;Font

f,f1;

inti=0,a=0,j=0;public

voidinit()

setBackground(Color.lightGray);

f=newFont("TimesNewRoman",f.ITALIC,28);

f1=newFont("TimesNewRoman",Font.ITALIC+Font.BOLD,28);

publicvoidstart()

t=newThread(this);t.s

tart();

publicvoidrun()

for(i=10;i>=0;i--)//countdown

{
try

Thread.sleep(1000);

catch(Exceptione)

System.out.println(e);

if(i<=10&&i>3)//red

a=1;

repaint();

elseif(i<=3&&i>0)//yellow

a=2;

repaint();

elseif(i==0)//green

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

a=3;

try

Thread.sleep(1000);

catch(Exceptione)
{

System.out.println(e);

repaint();

if(j==10)//endofgreen(returntored)

run();

repaint();

publicvoidpaint(Graphicsg)

setBackground(Color.lightGray);//ROAD

g.setColor(Color.black);//POLEUPg.fillR

ect(150,150,50,150);

g.drawRect(150,150,50,150);

g.setColor(Color.black);//POLEDOWNg.

fillRect(165,300,20,155);

g.drawRect(165,300,20,155);

g.drawOval(150,150,50,50);//RED

g.drawOval(150,200,50,50);//YELLOW

g.drawOval(150,250,50,50);//GREENg.setColor(Color.r

ed);//COUNTDOWNSTOPg.setFont(f);

g.drawString(""+i,50,50);
if(a==1)//REDSIGNAL

{
g.setColor(Color.red);g.fillOval(
150,150,50,50);

g.drawOval(150,150,50,50);

g.drawString("STOP",50,150);

if(a==2)//YELLOWSIGNAL

g.setColor(Color.yellow);g.fillO

val(150,200,50,50);

g.drawOval(150,200,50,50);

g.drawString("READY",50,200);

if(a==3)//GREENSIGNAL

{
g.setColor(Color.blue);//countdowng.s
etFont(f);

g.drawString(""+j,150,50);g.s

etColor(Color.green);g.fillOv

al(150,250,50,50);

g.drawOval(150,250,50,50);

g.drawString("GO",50,250);
}
intx1[]={220,300,300,280};
inty1[]={250,150,250,150};

intn1=4;in

tn2=3;

intx2[]={340,380,380};

inty2[]={150,100,150};

intx3[]={460,460,500};
inty3[]={150,100,150};

TrafficSignal.html

<html>
<head>
</head>
<body>
/*<appletcode="TrafficSignal.class"height=500width=300></applet>*/
</body>
</html>
Output:-
8) Write a java program to create an abstract class named Shape that contains two integersand
an empty method named printArea(). Provide three classes named Rectangle, Triangleand
Circle such that each one of the classes extends the class Shape. Each one of the
classescontainonlythemethodprintArea()thatprintstheareaofthegivenshape.

Program:-

abstractclassShape

abstractvoidnumberOfSides();

classTrapezoidextendsShape

voidnumberOfSides()

System.out.println("Trapezoidalhasfoursides");

classTriangleextendsShape

voidnumberOfSides()

System.out.println("Trianglehasthreesides");

classHexagonextendsShape

voidnumberOfSides()

{
System.out.println("Hexagonhassixsides");
}
}
classShapeDemo
{
publicstaticvoidmain(Stringargs[])
{
Trapezoid
t=newTrapezoid();Triangler=n
ewTriangle();Hexagonh=newH
exagon();Shapes;
s=t;s.numberOfSides(
);s=r;s.numberOfSide
s();s=h;s.numberOfSi
des();
}
}

Output:-
9) SupposethatatablenamedTable.txtisstoredinatextfile.Thefirstlineinthefileheaderandthere
maininglinescorrespondtorowinthetable.Theelementsareseparatedbycommas.WriteaJavapr
ogramtodisplaythetableusinglabelsingridlayout.

Program:-

importjava.awt.*;import

java.awt.event.*;importj

avax.swing.*;importjava

.util.*;importjava.io.*;

publicclassTable1extendsJFrame

inti=0;

intj=0,k=0;

Object

data[][]=newObject[5][4];Objectlist[][]

=newObject[5][4];JButtonsave;

JTabletable1;FileInp

utStreamfis;DataInpu

tStreamdis;publicTab

le1()

Stringd="";

Containercon=getContentPane();con.set

Layout(newBorderLayout());

finalString[]colHeads={"Name","RollNumber","Department","Percentage"};tr

Strings=JOptionPane.showInputDialog("EntertheFilenamepresentinthecurrentdirectory");FileInputStrea
m fis=newFileInputStream(s);
DataInputStreamdis=newDataInputStream(fis);
while((d=dis.readLine())!=null)
{
StringTokenizerst1=newStringTokenizer(d,",");whil
e(st1.hasMoreTokens())
{
for(j=0;j<4;j++)
{
data[i][j]=st1.nextToken();System.out.pr
intln(data[i][j]);
}i+
+;
}
System.out.println(" ");
}
}catch(Exceptione)
{
System.out.println("Exceptionraised"+e.toString());
}
table1=newJTable(data,colHeads);
intv=ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
inth=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;JS
crollPanescroll=newJScrollPane(table1,v,h);con.add(scroll,BorderLayout.CE
NTER);
}
publicstaticvoidmain(Stringargs[])
{

Table1t=newTable1();t.setBack

ground(Color.green);t.setTitle(

"DisplayData");t.setSize(500,3

00);t.setVisible(true);

t.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}}

Abc.txt:-

a,123,der,23b,456,frg,4

5
Output:-
10.WriteaJavaprogramthathandlesallmouseeventsandshowstheeventnameatthecenterofthewind
owwhenamouseeventisfired.(Useadapterclasses).

Program:-

importjava.awt.*;import

java.applet.*;importjava.

awt.event.*;

/*<appletcode="MouseDemo"width=300height=300>

</applet>*/

publicclassMouseDemoextendsAppletimplementsMouseListener,MouseMotionListener

intmx=0;i

ntmy=0;

Stringmsg="";pu

blicvoidinit()

addMouseListener(this);addMouseMotio

nListener(this);

publicvoidmouseClicked(MouseEventme)

mx=20;m

y=40;

msg="MouseClicked";re

paint();

publicvoidmousePressed(MouseEventme)

mx=30;m
y=60;

msg="MousePressed";

repaint();

publicvoidmouseReleased(MouseEventme)

mx=30;m

y=60;

msg="MouseReleased";repa

int();

publicvoidmouseEntered(MouseEventme)

mx=40;m

y=80;

msg="MouseEntered";re

paint();

publicvoidmouseExited(MouseEventme)

mx=40;m

y=80;

msg="MouseExited";r

epaint();

publicvoidmouseDragged(MouseEventme)

mx=me.getX();
my=me.getY();

showStatus("Currentlymousedragged"+mx+""+my);

repaint();}

publicvoidmouseMoved(MouseEventme)
{
mx=me.getX();
my=me.getY();
showStatus("Currentlymouseisat"+mx+""+my);repaint(
);
}
publicvoidpaint(Graphicsg)
{
g.drawString("HandlingMouseEvents",30,20);g.drawString(m
sg,60,40);
}
}

Output:-
11).Write a javaprogramthatloadsnamesandphonenumbersfromatextfile wherethedata is
organized as one line per record and each field in a record are separated by a tab(\t).ittakesa
nameorphonenumber asinputandprintsthecorrespondingothervaluefrom

thehashtable(hint: usehash
tables)

Program:-

importjava.io.BufferedReader;i

mportjava.io.File;

importjava.io.FileNotFoundException;i

mportjava.io.FileReader;

importjava.io.IOException;i

mportjava.util.Hashtable;im

portjava.util.Iterator;importj

ava.util.Set;

publicclassHashTab

publicstaticvoidmain(String[]args)

HashTabprog11=newHashTab();

Hashtable<String,String>hashData=prog11.readFromFile("HashTab.txt");System.out.pri

ntln("FiledataintoHashtable:\n"+hashData);prog11.printTheData(hashData,"vbit");

prog11.printTheData(hashData,"123");p

rog11.printTheData(hashData," ------ ");

privatevoidprintTheData(Hashtable<String,String>hashData,Stringinput)

Stringoutput=null;if(

hashData!=null)

{
Set<String>keys=hashData.keySet();if(keys.contains(

input))

output=hashData.get(input);

else

Iterator<String>iterator=keys.iterator();while(i

terator.hasNext()){

Stringkey=iterator.next();

Stringvalue=hashData.get(key);if(valu

e.equals(input))
{
output=key;brea
k;
} } } }
System.out.println("Inputgiven:"+input);if(out
put !=null)
{

else{
System.out.println("DatafoundinHashTable:"+output);
}

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

privateHashtable<String,String>readFromFile(StringfileName){Hashtable<String,

String>hashData=newHashtable<String,String>();try{

Filef=newFile("D:\\java\\"+fileName);

BufferedReaderbr= new BufferedReader(new

FileReader(f));Stringline=null;

while((line=br.readLine())!=null){String[]det

ails=line.split("\t");hashData.put(deta
ils[0],details[1]);

}catch(FileNotFoundExceptione){

e.printStackTrace();

}catch(IOExceptione){e.printStackTra

ce(); }

returnhashData; }}

HashTab.txt

vbit 123

abc 345

edrf 567

Output:-

12. Implementtheaboveprogramwithdatabaseinsteadofatextfie
Program:-

ConnectionUtil.Java

packageLabProgs;

importjava.sql.Connection;impor

tjava.sql.DriverManager;importja

va.sql.SQLException;publicclass

ConnectionUtil
{

publicstaticConnectiongetConnection()throwsSQLException

Connectionconnection=null;try

Class.forName("com.mysql.jdbc.Connection");

connection=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test","root",
"system");

catch(ClassNotFoundExceptione)

e.printStackTrace();

catch(SQLExceptione)

e.printStackTrace();

returnconnection;

packageLabProgs;

importjava.sql.Connection;
importjava.sql.PreparedStatement;import

java.sql.ResultSet;

importjava.sql.SQLException;i

mportjava.util.Hashtable;impor

java.util.Iterator;importjava.util

.Set;
publicclassProg12

publicstaticvoidmain(String[]args)

Stringquery="select*fromtest.student_details";Connection

conn=null;

try

conn=ConnectionUtil.getConnection();Prog1

2prog12=newProg12();

Hashtable<String,String>hashData=prog12.retrieveData(conn,query);

System.out.println("Student_detailsTabledataintoHashtable:\n"+hashData);

prog12.printTheData(hashData,"GNIT");prog12.print

TheData(hashData,"26262626");prog12.printTheData

(hashData,"****");

catch(SQLExceptione)

{
}

finally

{
e.printStackTrace();

try

conn.close();

catch(SQLExceptione)

e.printStackTrace();

PrivatevoidprintTheData(Hashtable<String,String>hashData,Stringinput)

Stringoutput=null;if(

hashData!=null)

Set<String>keys=hashData.keySet();if(keys.contains(input)){
output=hashData.get(input);

else

{ Iterator<String>iterator=keys.iterator();while(iterator.

hasNext()){
Stringkey=iterator.next();Stringvalue=hashData.get(key)

;if(value.equals(input)){

output=key;break;

} } }}

System.out.println("Inputgiven:"+input);if(out

put !=null)

else

{
System.out.println("DatafoundinHashTable:"+output);

System.out.println("DatanotfoundinHashTable");

} }

privateHashtable<String,String>retrieveData(Connectionconn,Stringquery)

Hashtable<String,String>hashData =

newHashtable<String,String>();try

PreparedStatementpstmt=conn.prepareStatement(query);Result

Setrs=pstmt.executeQuery();

while(rs.next())

hashData.put(rs.getString("st_name"),rs.getString("st_mobile"));

catch(SQLExceptione)

e.printStackTrace();

47 | P a g e
returnhashData;

}}

Output:-

48 | P a g e
13. Writeajavaprogramthattakestabseparateddata(onerecordperline
)froma textfileandinsertsthemintoa database.
Program:-
ConnectionUtil.Java
packageLabProgs;
importjava.sql.Connection;impor
tjava.sql.DriverManager;importja
va.sql.SQLException;publicclass
ConnectionUtil
{

publicstaticConnectiongetConnection()throwsSQLException
{
Connectionconnection=null;try
{
Class.forName("com.mysql.jdbc.Connection");connec
tion =
DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test","root","system");
}catch(ClassNotFoundExceptione)
{
e.printStackTrace();
}
catch(SQLExceptione){
e.printStackTrace();
}
returnconnection;
}
}

importjava.io.BufferedReader;i
mportjava.io.File;
importjava.io.FileNotFoundException;i
mportjava.io.FileReader;
importjava.io.IOException;i
mportjava.sql.Connection;
importjava.sql.PreparedStatement;import
java.sql.ResultSet;
importjava.sql.SQLException;i
mportjava.sql.Statement;import
java.util.Hashtable;importjava.
util.Iterator;

publicclassLab1{

publicstaticvoidmain(String[]args){Conn

49 | P a g e
ectionconn=null;
try{
conn=ConnectionUtil.getConnection();

Lab1prog13=newLab1();
Hashtable<String,String>hashData=prog13.readFromFile("prog11.txt");Syst
em.out.println("FiledataintoHashtable:\n"+hashData);System.out.println("Stu
dentdetailstabledatabeforeinsertingfiledata:");prog13.retrieveData(conn);
prog13.writeDataToDatabase(conn,hashData);System.out.println("Student
detailstabledataafterinsertingfiledata:");prog13.retrieveData(conn);
}catch(SQLExceptione){e.p
rintStackTrace();
}finally{try{
conn.close();
}catch(SQLExceptione){e.p
rintStackTrace();
}
}
}

privatevoidwriteDataToDatabase(Connection
conn,Hashtable<String,String>hashData){
Stringquery="insertintostudent_detailsvalues(?,?,?)";try{
PreparedStatementpstmt=
conn.prepareStatement(query);if(hashData!=null){
Iterator<String>iterator
=hashData.keySet().iterator();while(iterator.hasNext()){
Stringkey=iterator.next();Stringva
lue=hashData.get(key);
longid=getNextId("student_details");ps
tmt.setString(1,key);pstmt.setLong(2,ne
wLong(value));pstmt.setLong(3,id);pst
mt.executeUpdate();
}
}
}catch(SQLExceptione){e.p
rintStackTrace();
}
}

privatelonggetNextId(StringtableName){
Stringquery="selectmax(st_id)from"+tableName;Connection
conn;
longid=-
1;try{
conn=ConnectionUtil.getConnection();Statemen
tstatement=conn.createStatement();
ResultSetresultSet=statement.executeQuery(query);resultSet.n
ext();
id=resultSet.getLong(1);
}catch(SQLExceptione){

50 | P a g e
e.printStackTrace();
}
return++id;
}

privatevoidretrieveData(Connectionconn){try{
Stringquery="select*fromstudent_details";PreparedStatement
pstmt=conn.prepareStatement(query);ResultSetrs=pstmt.exec
uteQuery();System.out.println("ST_ID\tST_NAME\t\tST_M
OBILE");while(rs.next()){
System.out.println(rs.getString("st_id")+"\t"+rs.getString("st_name")+"\t\t"+rs.getString("st_mobile
"));
}
}catch(SQLExceptione){e.p
rintStackTrace();
}
}
privateHashtable<String,String>readFromFile(StringfileName){Hashtable<S
tring,String>hashData=newHashtable<String,String>();BufferedReaderbr=
null;
try{
Filef=newFile("D:\\java//"+fileName);
br=newBufferedReader(newFileReader(f));Stri
ngline=null;
while((line=br.readLine())!=null){String
[]details=line.split("\t");hashData.put(det
ails[0],details[1]);
}
}catch(FileNotFoundExceptione){e.print
StackTrace();
}catch(IOExceptione){e.p
rintStackTrace();
}finally{tr
y{br.close
();
}catch(IOExceptione){e.p
rintStackTrace();
}
}
returnhashData;
}
}

51 | P a g e
Output:-

52 | P a g e
14. Writeajavaprogramthatprintsthemeta-dataofagiventable.
Program:-

ConnectionUtil.Java
packageLabProgs;
importjava.sql.Connection;impor
tjava.sql.DriverManager;importja
va.sql.SQLException;publicclass
ConnectionUtil
{
publicstaticConnectiongetConnection()throwsSQLException{Connectio
nconnection=null;
try{
Class.forName("com.mysql.jdbc.Connection");
connection=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test","root",
"system");
}catch(ClassNotFoundExceptione){e.printStac
kTrace();
}catch(SQLExceptione){e.p
rintStackTrace();
}
returnconnection;
}

importjava.io.BufferedReader;i

mportjava.io.File;

importjava.io.FileNotFoundException;i

mportjava.io.FileReader;

importjava.io.IOException;i

mportjava.sql.Connection;

importjava.sql.PreparedStatement;import

53 | P a g e
java.sql.ResultSet;

importjava.sql.ResultSetMetaData;i

mportjava.sql.SQLException;impor

tjava.sql.Statement;

importjava.util.Hashtable;impo

rtjava.util.Iterator;importjava.u

til.logging.Level;

importjava.util.logging.Logger;p

ublicclassProg14{

publicstaticvoidmain(Stringargs[]){

try{

Connectionconn=null;

conn=ConnectionUtil.getConnection();Pro

g14prog14=newProg14();

prog14.printMetaData(conn,"student_details");

catch(SQLExceptionex){Logger.getLogger(Prog14.class.getName()).log(Level.SEVERE,null,ex);

privatevoidprintMetaData(Connectionconn,StringtableName){Stringquer

y="select*from"+tableName;

Statementstatement;tr

y{

statement=conn.createStatement();

ResultSetMetaDatametaData=statement.executeQuery(query).getMetaData();longcolSize

=metaData.getColumnCount();

System.out.println("Thereare"+colSize+"columnsintable
54 | P a g e
"+tableName);

System.out.println("Columnsare:");for(inti=1;i<=colS

ize;i++){

StringcolName=metaData.getColumnLabel(i);Stringc

olType=

metaData.getColumnTypeName(i);System.out.println

(colName+"-->"+colType);

}catch(SQLExceptione){e.p

rintStackTrace();

Output:-

55 | P a g e

You might also like