P. 1
Java programs

Java programs

|Views: 60|Likes:
Published by Jemal Gutema

More info:

Published by: Jemal Gutema on Mar 13, 2011
Copyright:Attribution Non-commercial

Availability:

Read on Scribd mobile: iPhone, iPad and Android.
download as DOC, PDF, TXT or read online from Scribd
See more
See less

07/04/2011

pdf

text

original

INDEX OF PROGRAMS

S. No 1. 2. 3a. 3b. 3c. 4. 5. 6. 7. 8. 9. 10a. 10b. 10c. 10d. 11. 12a. 12b. 12c. 12d. 13a. 13b. 14a. 14b. Program Name Program to implement inheritance Program to create threads using thread class Program to create package mypackage and create package class Rect Program to create Circle class using mypackage Program using package mypackage Program to implement exception handling Program to implement String functions Program to take values from console using I/O package Program to read existing file using i/o package Program to implement tabbed_pane using swing Program to implement JTree using swing Program to create employee table using JDBC Program to insert values into table using JDBC Program to update values of employee table using JDBC Program to display employee information using JDBC Program to implement JDBC using swing Program to create remote interface using RMI Program to implement the remote interface using Unicast Remote Object Program to create server using RMI Program to create client using RMI Program to check if given id and password are valid using servlet HTML program to enter user id# and password Program to implement JDBC through JSP HTML program to enter user id and name Page No.

/*PROGRAM TO IMPLEMENT INHERITANCE*/ class Student { int rollNo; Student(int a) { rollNo = a; } void putNo() { System.out.println("Roll No: "+rollNo); }

}

class Test extends Student { int sub1,sub2; Test(int x,int y) { super(6006); sub1 = x; sub2 = y; } void putTest() { System.out.println("Marks"); System.out.println("sub1: "+sub1+" sub2: "+sub2); }

}

class Result extends Test { int total; Result() { super(79,86); total=sub1+sub2; } void putTotal() { System.out.println("total: "+total); }

}

class InheritanceImpl { public static void main(String args[]) { Result r1=new Result();

2

3 .putNo().} } r1.putTotal(). r1.putTest(). r1.

/*PROGRAM TO CREATE THREADS USING THREAD CLASS*/ class ThreadImpl extends Thread { public void run() { for(int i=1. sleep(1000).start(). t.start(). } public static void main(String ap[]) { try { ThreadImpl t =new ThreadImpl(). t2.i++) System. ThreadImpl t1=new ThreadImpl(). t1.println("main thread").println("main thread interrupted").start(). } } } 4 .out.out. System. } catch(Exception j) { System. ThreadImpl t2=new ThreadImpl().println(i).i<=3.out.

class PackageImpl { public static void main(String a[]) { Rect r=new Rect().println("AREA OF RECTANGLE: " + (l*b) ).*. c. public class Circle { public int r.out./*PROGRAM TO CREATE PACKAGE MYPACKAGE AND CREATE PACKAGE CLASS RECT*/ package mypackage. public class Rect { public int l. b=y. System. } } /*PROGRAM TO CREATE CIRCLE CLASS USING MYPACKAGE*/ package mypackage. System.out.b.println("Area of circle: "+((22/7)*r*r)). r. } } 5 . public void display(int x) { r = x.int y) { l=x. Circle c=new Circle(). } } /*PROGRAM USING PACKAGE MYPACKAGE*/ import mypackage.20). public void display(int x.display(10.display(10).

println("demo of exception handling!"). } try { int c=20.println(b[5]). } catch(ArrayIndexOutOfBoundsException e) { System.out.println("unsufficient index value: "+e.20.out.println("don't divide by zero: "+e. } catch(ArithmeticException e) { System.40}. } } } 6 .out.println(c/d).out.getMessage()). int d=0. System.30. System.out. } finally { System./*PROGRAM TO IMPLEMENT EXCEPTION HANDLING*/ class ExceptionHandlingImpl { public static void main(String a[]) { try { int b[]={10.getMessage()).

length().println(p1).out.substring(0.println(v). String s4="h". System.out.println(b).lastIndexOf("l").equalsIgnoreCase("hello")).out. } } 7 .i++) { System.out. int p1=s3. } String e=s. int p=s3. boolean b=s3. //Replace System.out. String s5=s.out.equals("hello").replace('G'.println(e). String s2=s1.out.toUpperCase(). char x[]=s.out.out.out. String s1=s.println(s3. //index from left System. //Uppercase System.'h').toLowerCase(). //equals & equalsIgnoreCase System.2).indexOf("l"). //sub string System.i<s. //comparing strings System.println(x[i]).println(s1).println(p). //lowercase System. //index from right System./*PROGRAM TO IMPLEMENT STRING FUNCTIONS*/ public class StringFunctionsImpl { public static void main(String a[]) { String s="GOOD MORNING". String s3="hello". int v=s4.println(s5).toCharArray().println(s2).compareTo("i").//char array for(int i=0.

out.out.i++) { if(s[i]. System.getMessage()).equals("*")) break.i<100.i<100./*PROGRAM TO TAKE VALUES FROM CONSOLE USING I/O PACKAGE */ import java. class ConsoleIOImpl { public static void main(String a[]) { try { BufferedReader br=new BufferedReader(new InputStreamReader(System. for(int i=0.equals("*"))break.out. } } catch(Exception e) { System.io.println("Enter some strings(* to end):"). } System.i++) { s[i]=br.out.*. String s[]=new String[100].println(s[i]).println(e.println("Strings you entered are: "). System.readLine(). if(s[i]. } } } 8 . for(int i=0.in)).

}while(i!=-1). } finally { fin. } catch(NullPointerException e) { System. try { fin=new FileInputStream(a[0]).err.*.print((char)i). class FileIOImpl { public static void main(String a[]) throws IOException { int i.println("Usage java FileIOImpl <input file name>").io. } } catch(FileNotFoundException e) { System. try { do { i=fin./*PROGRAM TO READ EXISTING FILE USING I/O PACKAGE*/ import java. } catch(Exception e) { System.println("Usage java FileIOImpl <input file name>"). FileInputStream fin=null.err.read().err.println(e. } } } 9 . if(i!=-1) System.getMessage()).println("Input file not found!").err. } catch(ArrayIndexOutOfBoundsException e) { System.out.close().

FlowerPanel() { 10 .*.awt.add(tp). tp.new FlowerPanel()).*.event.setText(a.addTab("Flower". else if(a. c.b1. import java. JButton b. b1. public void init() { tp=new JTabbedPane().new TownPanel()). } public void actionPerformed(ActionEvent a) { if(a. t=new JTextField(15).b1.addActionListener(this). add(b1). Container c=getContentPane(). TownPanel() { b=new JButton("Secunderabad"). add(b).awt. /*<applet code="JTabbedPaneImpl" height="200" width="200"></applet>*/ public class JTabbedPaneImpl extends JApplet { JTabbedPane tp.swing.*. b1=new JButton("Hyderabad"). tp. add(t). import java.getSource()==b) t. JButton b.addActionListener(this). } } class FlowerPanel extends JPanel implements ActionListener { JTextField t.getActionCommand()). b.addTab("Town".setText(a.getActionCommand()). } } class TownPanel extends JPanel implements ActionListener { JTextField t.getSource()==b1) t./*PROGRAM TO IMPLEMENT TABBED_PANE USING SWING*/ import javax.

b1.setText(a. add(b1). else if(a. t=new JTextField(15). } } 11 .getSource()==b) t. b1=new JButton("Lillis").getActionCommand()). add(t).addActionListener(this).getSource()==b1) t.addActionListener(this). b.setText(a.getActionCommand()).b=new JButton("Rose"). } public void actionPerformed(ActionEvent a) { if(a. add(b).

JScrollPane sp. top. javax.b.add(c).h)./*PROGRAM TO IMPLEMENT JTREE USING SWING*/ import import import import javax. java. public void init() { con=getContentPane().*.event. a.addMouseListener(new MouseAdapter()).tree.HORIZONTAL_SCROLLBAR_ALWAYS.v.VERTICAL_SCROLLBAR_ALWAYS. b=new DefaultMutableTreeNode("B"). b1=new DefaultMutableTreeNode("b1").awt. b.b1.a1.awt. a2=new DefaultMutableTreeNode("a2"). int v=ScrollPaneConstants.add(a1). p. a=new DefaultMutableTreeNode("A").*. b2=new DefaultMutableTreeNode("b2"). b.add(a2). f=new JTextField(15). top. t=new JTree(top).swing.a2. a. sp=new JScrollPane(t. DefaultMutableTreeNode top.swing.*.add(f). 12 . a1=new DefaultMutableTreeNode("a1"). int h=ScrollPaneConstants. top.setLayout(new BorderLayout()). con.c.add(a).add(b). JTree t. /*<applet code="JTreeImpl" width="200" height="200"></applet>*/ public class JTreeImpl extends JApplet { Container con. p. p=new JPanel(). c=new DefaultMutableTreeNode("c"). JTextField f.*.setLayout(new GridLayout()).add(b2). JPanel p. java.add(b1). top=new DefaultMutableTreeNode("Top").b2. t.a.

setText(tp. } public public public public } } void void void void mouseEntered(MouseEvent me){} mouseReleased(MouseEvent me){} mouseExited(MouseEvent me){} mousePressed(MouseEvent me){} 13 .CENTER).BorderLayout. } class MouseAdapter implements MouseListener { public void mouseClicked(MouseEvent me) { doMouseClicked(me).BorderLayout.getY()).add(p.add(sp. con.WEST). } public void doMouseClicked(MouseEvent me) { TreePath tp = t. if(tp!=null) f.toString()).getX(). me.getPathForLocation(me.con.

JdbcOdbcDriver"). import java.2). st. System. basic number(7.getMessage()).2).println("table created successfully!"). "scott".*. } } } 14 .*.err.io./*PROGRAM TO CREATE EMPLOYEE TABLE USING JDBC */ import java.2))").forName("sun.2).out. total_salary number(7. } catch(Exception e) { System.close(). st. Connection con= DriverManager.odbc. public class JDBCEmpTableCreation { public static void main(String a[]) { try { Class. pf number(7. da number(7.println(e.close().getConnection("jdbc:odbc:san".executeUpdate("create table empdb(e_roll number.sql. hra number(7.2).jdbc. ta number(7. "tiger").2).createStatement(). e_name varchar(20). Statement st=con. con.

println("Enter hra: ").i<nrows.println("enter how many rows you want to insert: "). int nrows=Integer.println("Enter basic: ").?. strTA=br.*.println("Enter da: ").ta.strTA.da.sql. rno=Integer.pf.hra. "tiger").?. strName=br.JdbcOdbcDriver").readLine().forName("sun. System. strDA=br. 15 .readLine(). Connection con = DriverManager.odbc.?)").ts. strPF=br. System.?.readLine(). System. int rno.println("Enter ta: "). System. float basic.i++) { System. System.readLine()).readLine(). public class JDBCEmpTableInsertion { public static void main(String a[]) { try { Class.getConnection( "jdbc:odbc:san".println("Enter employee name: ").parseInt(br.strName.println("Enter pf: ").strDA.*. strRno=br.out. String strRno. strHRA=br.strPF. System.out.readLine().strBasic. "scott".?.strHRA.prepareStatement("insert into empdb values(?.readLine().io.println("Enter employee roll number: ").in)). PreparedStatement ps = con.parseInt(strRno).out.jdbc.out. import java.?.out.out.readLine(). strBasic=br.out.?. BufferedReader br = new BufferedReader(new InputStreamReader(System./*PROGRAM TO INSERT VALUES INTO TABLE USING JDBC*/ import java. System. for(int i=0.out.

pf). ps.parseFloat(strDA). ps.err.setFloat(4. } System.setFloat(7.rno).ta). ps.setString(2. hra=Float.close(). ps.setFloat(8.basic).parseFloat(strHRA). da=Float.println("Values inserted at runtime!").ts).getMessage()). ps.parseFloat(strPF).close(). ts=(basic+da+ta+hra)-pf.setFloat(6. } catch(Exception e) { System.basic=Float.parseFloat(strTA).out. ta=Float.executeUpdate().setFloat(5. ps. ps. con. ps. } } } 16 .setFloat(3.println(e.da). pf=Float. ps.close(). br.parseFloat(strBasic).setInt(1. ps.strName).hra).

st. public class JDBCEmpTableUpdation { public static void main(String a[]) { try { Class.jdbc.out.io. int i=st.*. } } } 17 .close(). import java.executeUpdate("update empdb set total_salary= basic + da+ta+hra-pf"). "tiger")."). con./*PROGRAM TO UPDATE VALUES OF EMPLOYEE TABLE USING JDBC*/ import java.err.commit(). con. Connection con = DriverManager.close().odbc.getMessage()). System. } catch(Exception e) { System.*.println(e.println(i+" rows updated.forName("sun.sql. "scott".JdbcOdbcDriver").createStatement(). Statement st=con.getConnection( "jdbc:odbc:san".

} catch(Exception e) { System.out.odbc. "tiger"). System. ResultSet rs=st.out. System.out. class JDBCEmpInfoDisplay { public static void main(String a[]) { try { Class.getConnection( "jdbc:odbc:san".*. System./*PROGRAM TO DISPLAY EMPLOYEE INFORMATION USING JDBC*/ import java.jdbc.createStatement().getFloat(4)+":").forName("sun.close(). System.getFloat(6)+":").JdbcOdbcDriver").println(e.next()) { System.getFloat(5)+":").getMessage()).out. import java.out. while(rs.print(rs.io. System.print(rs. } rs.getFloat(3)+":").print(rs. System. System.getFloat(8)+":").out.out.print(rs. con.print(rs.getInt(1)+":").sql. Connection con = DriverManager.print(rs.getString(2)+":").close(). } } } 18 .executeQuery("select * from empdb"). st.out.println().err. Statement st=con.*.print(rs. System.out.print(rs.getFloat(7)+":"). "scott".close().

bSave=new JButton("Save"). PreparedStatement ps./*PROGRAM TO IMPLEMENT JDBC USING SWING*/ import import import import javax. tTA=new JTextField(10). public class JDBCSwingImpl extends JFrame implements ActionListener { Connection con.lHRA.JLabel.JLabel. bShow.*. tTotalSalary=new JTextField(10). bShow=new JButton("Show").CENTER).300). add(tEName). ResultSet rs.CENTER). lDA=new JLabel("DA".CENTER).bShow. JTextField tDA. tEId=new JTextField(10).CENTER). JLabel lDA. add(lBasic). tTotalSalary.tTA.*.tTotalSalary. JButton bSave.tHRA. tHRA=new JTextField(10). lEId=new JLabel("Employee ID".lEName.lPF.lTA.tEName. add(tBasic). add(tDA). add(lTA). lPF=new JLabel("PF".JLabel. JDBCSwingImpl() { tDA=new JTextField(10). add(tEId). lHRA=new JLabel("HRA". add(lEName).2)).addActionListener(this). setSize(300.CENTER). lEName=new JLabel("Employee Name".lTotalSalary.JLabel. lBasic=new JLabel("Basic".sql. tPF=new JTextField(10). java. java.awt.JLabel. lTotalSalary=new JLabel("Total Salary".CENTER).JLabel.*. tEName=new JTextField(10). Statement st. add(lDA).tBasic.awt. bSave. java.*.CENTER). tBasic=new JTextField(10).CENTER).setEnabled(false).tPF. setLayout(new GridLayout(9.tEId. add(lEId).addActionListener(this).event. 19 . lTA=new JLabel("TA".swing.lBasic.JLabel.JLabel.lEId.

da.getMessage()). add(tTotalSalary). ps.setInt(1.?. add(lHRA).?.parseFloat(tPF.parseFloat(tTA. } public void actionPerformed(ActionEvent a) { try { if(a.parseFloat(tBasic. add(bSave). ts=basic+da+ta+hra-pf.ts.err.setFloat(4.?.setFloat(3. 20 .?.basic).parseInt(tEId.getText()).setString(2. ps."tiger").getConnection("jdbc:odbc:san".getText()).prepareStatement("insert into empdb values(?.getText()).?. ps. da=Float.getText()).getText()). ps.getText().pf. } ps. ps.executeUpdate().name). ta=Float.eId). ps=con. "scott". name=tEName.setFloat(8.forName("sun. setVisible(true). add(tPF).getText()). add(bShow).println(e. ps.hra. try { Class.ta). add(lPF).ts). add(lTotalSalary). } catch(Exception e) { System.?. float basic.odbc.jdbc.JdbcOdbcDriver").add(tTA).hra).getSource()==bSave) { int eId. eId=Integer. String name.parseFloat(tDA.setFloat(7. ps. add(tHRA). basic=Float. ps.?)").setFloat(6.pf).da).ta.parseFloat(tHRA.setFloat(5. con = DriverManager. hra=Float. pf=Float.

setText(new Integer( rs.getInt(1)).err. toString()).getMessage()).close().getFloat(6)).next()) { tEId.setText(new Float(rs. con. tTA.println(e.getMessage()). 21 .executeQuery("select * from empdb").getSource()==bShow) { try { Class. con=DriverManager.setText(new Float(rs. } public static void main(String args[]) { new JDBCSwingImpl().getFloat(8)).getFloat(5)).close(). toString()).getFloat(7)).close(). tHRA. } finally { ps. st=con. toString()).setText(new Float(rs.setText(rs.getString(2)).setText(new Float(rs. if(rs. tDA. } } } } catch(Exception e) { System.err. } } catch(Exception e) { System.JdbcOdbcDriver"). con. toString()).toString()).setText(new Float(rs.getConnection(" jdbc:odbc:san".forName("sun.finally { ps. tEName. toString()). toString()). tTotalSalary.getFloat(4)). tBasic.createStatement().close().getFloat(3)). "tiger").println(e. rs=st. } } if(a.setText(new Float(rs. tPF.odbc. "scott".jdbc.

} } 22 .

Naming. } } /*PROGRAM TO CREATE SERVER USING RMI*/ import java. } } } 23 . import java. import java. public class AddServerImpl extends UnicastRemoteObject implements AddServerIntf { public AddServerImpl() throws RemoteException {} public double add(double d1. } /*PROGRAM TO IMPLEMENT THE REMOTE INTERFACE USING UNICAST REMOTE OBJECT*/ import java.net.double d2) throws RemoteException.rmi.rebind("AddServer".double d2) throws RemoteException { return d1+d2.getMessage()). public interface AddServerIntf extends Remote { double add(double d1.*.rmi.server.*.*.*.rmi.println(e. public class AddServer { public static void main(String args[]) { try { AddServerImpl addServerImpl=new AddServerImpl().err.rmi. } catch(Exception e) { System./*PROGRAM TO CREATE REMOTE INTERFACE USING RMI*/ import java.*.addServerImpl).

} catch(ArrayIndexOutOfBoundsException e) { System.parseDouble(args[2]).d2)).parseDouble(args[1]). } catch(Exception e) { System.*. public class AddClient { public static void main(String args[]) { try { String addServerURL="rmi://"+args[0]+"/AddServer".println(e. System. AddServerIntf addServerIntf =( AddServerIntf)Naming. double d2=Double.err.lookup(addServerURL).println("Usage java AddClient <URL> <Val1> <Val2>").out.println(addServerIntf.err.println(addServerURL).getMessage()). System./*PROGRAM TO CREATE CLIENT USING RMI*/ import java. } } } 24 . double d1=Double.rmi.add(d1.out.

io.IOException { res.close().getWriter().println("Sorry Try again").getParameter("t2").equalsIgnoreCase("Java")) { out. //validation logic if(str1. } out.http.println("<B>INVALID</B><BR>")./*PROGRAM TO CHECK IF GIVEN ID AND PASSWORD ARE VALID USING SERVLET*/ import javax.*. String str2=req.getParameter("t1"). //retrieving user’s entry values into the servlet String str1=req.*. //for servlet Exception import javax.servlet. } } 25 . //for print writer&IOException public class ValidationServlet extends HttpServlet { public void service(HttpServletRequest req. PrintWriter out=res. } else { out. out.HttpServletResponse res) throws ServletException.servlet. out.setContentType("text/html").println("<B>VALID</B><BR>").*. import java.equals("Santosh")&&str2.println("Thank you").

<!-HTML PROGRAM TO ENTER ID AND PASSWORD <html> <head> <title>Servlet example</title> </head> <body> <h3 align="center">User Name & Password</h3> <FORM METHOD="get" ACTION="http://localhost:8080/servlet/ValidationServlet"> User Name: <input type="text" name="t1"><br> Password: <input type="password" name="t2"><br> <input type="submit" value="send"> <input type="reset" value="clear"> </form> </body> </html> 26 .

jdbc.setString(2.getParameter("t2"). %> <%="one row created"%> <% ps. "scott".close()./* PROGRAM TO IMPLEMENT JDBC THROUGH JSP */ <%@ page import="java.*"%> <% try { string s1=request.n1).JdbcOdbcDriver").s2).parseInt(s1).getParameter("t1").?)"). } catch(Exception e) {} %> 27 . con.prepareStatement("insert into login values(?.forName("sun."tiger"). ps. connection con=DriverManager. int n1=Integer. ps.sql.getConnection("jdbc:odbc:san". string s2=request.close().setInt(1. PreparedStatement ps=con. class.odbc.

.jsp"> User ID: <input type=text id="t1"><br> Password: <input type=text name="t2"><br> <input type=submit value="Send"> </form> </body> </html> 28 .<!-PROGRAM TO ENTER ID AND NAME USING HTML <html> <title> JDBC Using JSP example. </title> <body> <h1><marquee>Welcome</marquee></h1> <form name="f1" method=post action="JDBC_Using_JSP..

You're Reading a Free Preview

Download
scribd
/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->