JAVA_SLips_Solutions
JAVA_SLips_Solutions
Q1. Write a Java program to display all the alphabets between ‘A’ to
‘Z’ after every 2 seconds
Public class Slip26_1 extends Thread
{
char c;
public void run()
{
for(c = 'A'; c<='Z';c++)
{
System.out.println(""+c);
try
{
Thread.sleep(3000);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
public static void main(String args[])
{
Slip26_1 t = new Slip26_1();
t.start();
}
2. Write a Java program to accept the details of
Employee (Eno, EName, Designation, Salary)
from a user and store it into the database. (Use
Swing)
i
mport java.awt.*;
JOptionPane.showMessageDialog(null,”Record Is Added”);
Slip Nos - 2
import java.util.*;
Slip Nos 3
1. Write a JSP program to display the details of Patient
(PNo, PName, Address, age, disease) in tabular form on
browser.
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<body>
<%@ page import="java.sql.*;" %>
<%! inthno;
String hname,address; %>
<%
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection
cn=DriverManager.getConnection("jdbc:odbc:hospital_data","","");
Statement st=cn.createStatement();
ResultSetrs=st.executeQuery("select * from Hospital");
%>
<table border="1" width="40%"> <tr> <td>Hospital No</td>
<td>Name</td> <td>Address</td> </tr> <% while(rs.next()) { %>
<tr><td><%= rs.getInt("hno") %></td> <td><%= rs.getString("hname")
%></td> <td><%= rs.getString("address") %> </tr> <%
}
cn.close();
}catch(Exception e)
{
out.println(e);
}
%>
</body>
</html>
import java.io.*;
int data;
Node next;
// Constructor
Node(int d)
{
data = d;
next = null;
}
}
System.out.print("LinkedList: ");
// Go to next node
currNode = currNode.next;
}
System.out.println();
}
// **************DELETION BY KEY**************
//
// CASE 1:
// If head node itself holds the key to be deleted
//
// CASE 2:
// If the key is somewhere other than at head
//
//
// CASE 3: The key is not present
//
// **************MAIN METHOD**************
//
// ******INSERTION******
//
import java.awt.*;
import java.awt.event.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
Hashtable ts;
Slip16_2()
{
ts=new Hashtable();
t1=new JTextField(10);
t2=new JTextField(10);
t3=new JTextField(10);
b1=new JButton("Add");
b2=new JButton("Search");
b3=new JButton("Remove");
t=new JTextArea(20,20);
p1=new JPanel();
p1.add(t);
add(p1);
add(p2);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
setLayout(new FlowLayout());
setSize(500,500);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e)
{
if(b1==e.getSource())
{
String name = t1.getText();
int code = Integer.parseInt(t2.getText());
ts.put(name,code);
Enumeration k=ts.keys();
Enumeration v=ts.elements();
String msg="";
while(k.hasMoreElements())
{
msg=msg+k.nextElement()+" = "+v.nextElement()+"\n";
}
t.setText(msg);
t1.setText("");
t2.setText("");
}
else if(b2==e.getSource())
{
String name = t3.getText();
if(ts.containsKey(name))
{
t.setText(ts.get(name).toString());
}
else
JOptionPane.showMessageDialog(null,"City not found ...");
}
else if(b3==e.getSource())
{
String name = t3.getText();
if(ts.containsKey(name))
{
ts.remove(name);
JOptionPane.showMessageDialog(null,"City Deleted ...");
}
else
JOptionPane.showMessageDialog(null,"City not found ...");
}
}
public static void main(String a[])
{
new Slip16_2();
}
}
Slip Nos-5
1) Write a Java Program to create the hash table that will
maintain the mobile number and student name. Display
the details of student using Enumeration interface
// Main class
class GFG {
// Getting key
String key = e.nextElement();
Exam.jsp
<%@page import="java.sql.*,java.util.*"%>
<%
Class.forName("org.postgresql.Driver");
Connection con = DriverManager.getConnection(
"jdbc:postgresql:ty1","postgres","");
Set s = new TreeSet();
while(true){
int n = (int)(Math.random()*11+1);
s.add(n);
if(s.size()==5) break;
}
PreparedStatement ps = con.prepareStatement("select * from questions where qid=?");
%>
<form method='post' action='accept_ans.jsp'>
<table width='70%' align='center'>
<%
int i=0;
Vector v = new Vector(s);
session.setAttribute("qids",v);
int qid = Integer.parseInt(v.get(i).toString());
ps.setInt(1,qid);
ResultSet rs = ps.executeQuery();
rs.next();
%>
<tr>
<td><b>Question:<%=i+1%></b></td>
</tr>
<tr>
<td><pre><b><%=rs.getString(2)%></pre></b></td>
</tr>
<tr>
<td>
<b>
<input type='radio' name='op' value=1><%=rs.getString(3)%><br>
<input type='radio' name='op' value=2><%=rs.getString(4)%><br>
<input type='radio' name='op' value=3><%=rs.getString(5)%><br>
<input type='radio' name='op' value=4><%=rs.getString(6)%><br><br>
</b>
</td>
</tr>
<tr>
<td align='center'>
<input type='submit' value='Next' name='ok'>
<input type='submit' value='Submit' name='ok'>
</td>
</tr>
</table>
<input type='hidden' name='qno' value=<%=qid%>>
<input type='hidden' name='qid' value=<%=i+1%>>
</form>
</body>
Acceptans.jsp
<%@page import="java.sql.*,java.util.*"%>
<%
Class.forName("org.postgresql.Driver");
Connection con = DriverManager.getConnection(
"jdbc:postgresql:ty1","postgres","");
Vector answers = (Vector)session.getAttribute("answers");
if(answers==null)
answers = new Vector();
int qno = Integer.parseInt(request.getParameter("qno"));
int ans = Integer.parseInt(request.getParameter("op"));
int i = Integer.parseInt(request.getParameter("qid"));
answers.add(qno+" "+ans);
session.setAttribute("answers",answers);
String ok = request.getParameter("ok");
if(ok.equals("Submit") || i==5){
response.sendRedirect("result.jsp");
return;
}
PreparedStatement ps = con.prepareStatement("select * from questions where qid=?");
%>
<form method='post' action='accept_ans.jsp'>
<table width='70%' align='center'>
<%
Vector v = (Vector)session.getAttribute("qids");
int qid = Integer.parseInt(v.get(i).toString());
ps.setInt(1,qid);
ResultSet rs = ps.executeQuery();
rs.next();
%>
<tr>
<td><b>Question:<%=i+1%></b></td>
</tr>
<tr>
<td><pre><b><%=rs.getString(2)%></pre></b></td>
</tr>
<tr>
<td>
<b>
<input type='radio' name='op' value=1><%=rs.getString(3)%><br>
<input type='radio' name='op' value=2><%=rs.getString(4)%><br>
<input type='radio' name='op' value=3><%=rs.getString(5)%><br>
<input type='radio' name='op' value=4><%=rs.getString(6)%><br><br>
</b>
</td>
</tr>
<tr>
<td align='center'>
<input type='submit' value='Next' name='ok'>
<input type='submit' value='Submit' name='ok'>
</td>
</tr>
</table>
<input type='hidden' name='qno' value=<%=qid%>>
<input type='hidden' name='qid' value=<%=i+1%>>
</form>
</body>
Result.jsp
<%@page import="java.sql.*,java.util.*,java.text.*"%>
<%
Class.forName("org.postgresql.Driver");
Connection con = DriverManager.getConnection(
"jdbc:postgresql:ty1","postgres","");
Vector v = (Vector)session.getAttribute("answers");
if(v==null){
%>
<h1>No questions answered</h1>
<%
return;
}
PreparedStatement ps = con.prepareStatement("select ans from questions where qid=?");
int tot=0;
for(int i=0;i<v.size();i++){
String str = v.get(i).toString();
int j = str.indexOf(' ');
int qno = Integer.parseInt(str.substring(0,j));
int gans = Integer.parseInt(str.substring(j+1));
ps.setInt(1,qno);
ResultSet rs = ps.executeQuery();
rs.next();
int cans = rs.getInt(1);
if(gans==cans) tot++;
}
session.removeAttribute("qids");
session.removeAttribute("answers");
session.removeAttribute("qid");
%>
<h3>Score:<%=tot%></h1>
<center><a href='exam.jsp'>Restart</a></center>
</body>
SQL File
create table questions(qid serial primary key, question text, option1 text, option2 text, option3 text, option4 text, ans int);
insert into questions
(question,option1,option2,option3,option4,ans)
values
('Who is prime minister of India?','Rahul Gandhi','Narendra Modi','Sonia Gandhi','Manmohan Singh',2),
('Who is finance minister of India','Rahul Gandhi','P Chidambaram','Manmohan Singh','Arun Jately',4),
('What is square root of 16?','2','4','1','256',4),
('Who is chief minister of Maharashtra','Uddhav Tharakey','Devendra Fadanavis','Raj Thakarey','Sharad Pawar',2),
('What is full for of LIFO?','Last In First Out','Late In First Out','Long In First Out','Large In First Out',1),
('Which is capital of India','Delhi','Maharashtra','Kolkata','Goa',1), ('What is currency of India','Dollar','Rupee','Pound','Yen',2),
('Who Invented C?','Kim Thompson','Bill Joy','Dennis Ritche','Balaguru Swamy',3),
('Where was Java invented?','Microsoft','Oracle','Sun Microsystem','Intel',3),
('What is cube root of 8?','2','3','4','5',1),('What is full form of FIFO','Fast In Fast Out','First in First Out','Fast In First Out','First In Fast Out',2);
Slip Nos-6
import java.util.*;
import java.io.*;
class Slip19_2
{
public static void main(String[] args) throws Exception
{
int no,element,i;
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
TreeSet ts=new TreeSet();
System.out.println("Enter the of elements :");
no=Integer.parseInt(br.readLine());
for(i=0;i<no;i++)
{
System.out.println("Enter the element : ");
element=Integer.parseInt(br.readLine());
ts.add(element);
}
System.out.println("The elements in sorted order :"+ts);
System.out.println("Enter element to be serach : ");
element = Integer.parseInt(br.readLine());
if(ts.contains(element))
System.out.println("Element is found");
else
System.out.println("Element is NOT found");
}
}
import java.applet.*;
import java.awt.*;
class Slip3_2 extends Applet implements Runnable
{
Thread t;
int r,g1,y,i;
public void init()
{
T=new Thread(this);
t.start();
r=0; g1=0;I=0; y=0;
}
public void run()
{
try
{
for(I =24; I >=1;i--)
{
if (I >16&& I <=24)
{
t.sleep(200);
r=1;
repaint();
}
if (I >8&& I <=16)
{
t.sleep(200);
y=1;
repaint();
}
if(I >1&& I <=8)
{
t.sleep(200);
g1=1;
repaint();
}
}
if (I ==0)
{
run();
}
}
catch(Exception e)
{ System.out.println(e);
}
} public void paint(Graphics g)
{
g.drawRect(100,100,100,300);
if (r==1)
{
g.setColor(Color.red);
g.fillOval(100,100,100,100);
g.setColor(Color.black);
g.drawOval(100,200,100,100);
g.drawOval(100,300,100,100);
r=0;
}
if (y==1)
{
g.setColor(Color.black);
g.drawOval(100,100,100,100);
g.drawOval(100,300,100,100);
g.setColor(Color.yellow);
g.fillOval(100,200,100,100);
y=0;
}
if (g1==1)
{
g.setColor(Color.black);
g.drawOval(100,100,100,100);
g.drawOval(100,200,100,100);
g.setColor(Color.green);
g.fillOval(100,300,100,100);
g1=0;
}
}
}
Slip Nos-7
{
int x;
Square(int n)
{
x = n;
}
{
}
}
{
int x;
Cube(int n)
{x = n;
}
{
}
}
{
{
{
int randomInteger = random.nextInt(100);
s.start();
c.start();
try {
Thread.sleep(1000);
System.out.println(ex);
}
}
}
}
{
n.start();
}
}
Q2. Write a java program for the following: i. To create a Product(Pid, Pname, Price) table. ii. Insert at least five records into the
table. iii. Display all the records from a table.
{
{
String id = "id1";
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
int x = stmt.executeUpdate(q1);
if (x > 0)
System.out.println("Successfully Inserted");
else
System.out.println("Insert Failed");
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
SLip Nops-8
1) Write a java program to define a thread for printing text on output screen for ‘n’ number of times. Create 3 threads and run
them. Pass the text ‘n’ parameters to the thread constructor. Example: i. First thread prints “COVID19” 10 times. ii. Second
thread prints “LOCKDOWN2020” 20 times iii. Third thread prints “VACCINATED2021” 30 times
String str;
int n;
this.str = str;
this.n = n;
}
try {
}
} catch (Exception e) {
e.printStackTrace();
}
}
t1.start();
t2.start();
t3.start();
}
}
2.Write a JSP program to check whether a given number is prime or not. Display the result in red color.
<html>
</h2></center>
Slip no - 9
1. Write a Java program to create a thread for moving a ball inside a panel vertically. The ball should be created when the user
clicks on the start button
classBouncingBallPanelextendsJPanelimplementsMouseListener
{
//createanempty array for 20Ballobjects
publicBall[] array;
privateint count =0;
Randomgenerator =new Random();
publicBouncingBallPanel()
{
array =new Ball[20];
}
publicvoidmouseClicked(MouseEvent event)
{
array[count] =new Ball(this);
count++;
if( count ==1)
{
finalRunnableupdate=new Runnable()
{
publicvoidrun()
{
for (int j=0;j<array.length;j++)
{
if(array[j] !=null)
{
array[j].move();
}//endof if
}//endof for
}//endof runmethod
};//endof runnalbeupdate
(new Thread(new Ball(this))).start();
Runnablegraphic=new Runnable()
{
publicvoidrun()
{
while(true)
{
try
{
EventQueue.invokeLater(update);
Thread.sleep(generator.nextInt(10+100));
}catch(InterruptedExceptionexp){}
}//endof while
}//endof run
};//endof runnable
new Thread(graphic).start();
}//endof if
}//endof mouseClickedmethod
Randomrandom=new Random();
publicBall(BouncingBallPanela)
{
x =random.nextInt(400);
y =random.nextInt(300);
deltaX =1+random.nextInt(10);
deltaY =1+random.nextInt(10);
diameter =5+random.nextInt(20);
color =new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256));
BBP2=a;
}//endof constructor
publicdoublegetX()
{
returnx;
}
publicdoublegetY() {
returny;
}
publicdoublegetDiameter() {
returndiameter;
}
publicColor getColor() {
returncolor;
}
publicvoidmove() {
x +=deltaX;
y +=deltaY;
}//endof methodmove
@Override
publicvoidrun()
{
while(true)
{
move();
BBP2.repaint();
try{
Thread.currentThread().sleep(10+random.nextInt(100));
}catch(InterruptedExceptionexp){}
}//endof while
}//endof runmethod
}//endof Ball
2.Write a Java program using Spring to display the message “If you can't explain it simply, you don't understand it well enough”
Ans:-
// Here's an example:
/*
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.8</version>
</dependency>
</dependencies>
*/
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
private String message = "If you can't explain it simply, you don't
understand it well enough.";
@RequestMapping("/message")
@ResponseBody
return message;
}
}
// Step 8: Run the Spring application and navigate to the URL mapped in step
5 to see the message.
Q1) Write a Java program to display the Current Date using spring
import java.text.*;
import java.util.*;
{
formatDate.setTimeZone(TimeZone.getTimeZone("IST"));
// converting to IST or format the Date as IST
System.out.println(formatDate.format(date));
}
}
Q2 )
Write a Java program to display first record from student table (RNo, SName, Per) onto the TextFields by clicking on button.
(Assume Student table is already created).
postgres=# \c stud
package studdb;
import javax.swing.table.*;
import java.sql.*;
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class StudDb extends JFrame implements ActionListener
{
JTextField t1,t2,t3;
JLabel l1,l2,l3;
JButton b1,b2;
int row,column;
StudDb()
{
setLayout(new FlowLayout());
setSize(500,500);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
l1=new JLabel("RollNo");
add(l1);
t1=new JTextField(10);
add(t1);
l2=new JLabel("Name");
add(l2);
t2=new JTextField(10);
add(t2);
l3=new JLabel("Percentage");
add(l3);
t3=new JTextField(10);
add(t3);
b1=new JButton("Insert");
add(b1);
b1.addActionListener(this);
b2=new JButton("Display");
add(b2);
b2.addActionListener(this);
try
{
Class.forName("org.postgresql.Driver");
}
catch(Exception e)
{
System.out.println("Error"+e.getMessage());
}
}
public void actionPerformed(ActionEvent e2)
{
if(e2.getSource()==b1)
{
try
{
int eno=Integer.parseInt(t1.getText());
String ename=t2.getText();
float percentage=Float.parseFloat(t3.getText());
Connection conn = DriverManager.getConnection("jdbc:postgresql://localhost/stud","postgres","password");
PreparedStatement st=conn.prepareStatement("insert into student values(?,?,?)");
st.setInt(1, eno);
st.setString(2,ename);
st.setFloat(3,percentage);
st.executeUpdate();
st.close();
JOptionPane.showMessageDialog(this,"Inserted");
}catch(Exception e)
{
System.out.println("Error"+e.getMessage());
}
}
if(e2.getSource()==b2)
{
try
{
Object[] data=new Object[3];
DefaultTableModel dtm=new DefaultTableModel();
JTable jt=new JTable(dtm);
ResultSet rs;
System.out.println("hello");
jt.setBounds(20,20,50,50);
String[] darr={"RollNo","Name","Percentage"};
for(int column=0;column<3;column++)
{
dtm.addColumn(darr[column]);
}
Connection conn = DriverManager.getConnection("jdbc:postgresql://localhost/stud","postgres","password");
Statement st=conn.createStatement();
rs=st.executeQuery("select * from student");
for(row=0;rs.next();row++)
{
for(int column=0;column<3;column++)
{
data[column]=rs.getObject(column+1);
}
dtm.addRow(data);
}
rs.close();
getContentPane().add(new JScrollPane(jt));
}catch(Exception e)
{
}
}
}
public static void main(String[] args)
{
new StudDb();
}
}
Slip NOs -11
1) Design an HTML page which passes customer number to a search servlet. The servlet searches for the customer number
in a database (customer table) and returns customer details if found the number otherwise display error message.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class servletDatabase extends HttpServlet
{
Connection cn;
public void init()
{
try
{
Class.forName("org.gjt.mm.mysql.Driver");
cn=DriverManager.getConnection("jdbc:mysql://localhost/stud","root","password");
System.out.println("Hii");
}
catch(Exception ce)
{
System.out.println("Error"+ce.getMessage());
}
}
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
resp.setContentType("text/html");
PrintWriter pw=resp.getWriter();
try
{
int rno=Integer.parseInt(req.getParameter("t1"));
String qry="Select * from student where rollno="+rno;
Statement st=cn.createStatement();
ResultSet rs=st.executeQuery(qry);
while(rs.next())
{
pw.print("<table border=1>");
pw.print("<tr>");
pw.print("<td>" + rs.getInt(1) + "</td>");
pw.print("<td>" + rs.getString(2) + "</td>");
pw.print("<td>" + rs.getFloat(3) + "</td>");
pw.print("</tr>");
pw.print("</table>");
}
}
catch(Exception se){}
pw.close();
}
}
HTML File
<html>
<body>
<form action="http://localhost:8080/servDb/servletDatabase" method="get">
Enter Roll No:<input type="text" name="t1">
<input type="submit">
</form>
</body>
</html>
pssql> create database stud;
Query OK, 1 row affected (0.00 sec)
pssql> create table student(rollno int primary key,name text,percentage float);
Query OK, 0 rows affected (0.07 sec)
pssql> insert into student values(1,'student1',79);
Query OK, 1 row affected (0.04 sec)
pssql> insert into student values(2,'student2',69);
Query OK, 1 row affected (0.05 sec)
pssql> insert into student values(3,'student3',58);
Query OK, 1 row affected (0.06 sec)
pssql> select * from student;
2.Write a Java program to display information about all columns in the DONAR table using ResultSetMetaData.
import java.sql.*;
import java.io.*;
public class ResultSetMetaData
{
public static void main(String[] args) throws Exception
{
Statement stmt;
Class.forName("org.postgresql.Driver");
Connection conn = DriverManager.getConnection("jdbc:postgresql://localhost/stud","postgres","password");
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("Select * from student");
java.sql.ResultSetMetaData rsmd = rs.getMetaData();
int noOfColumns = rsmd.getColumnCount();
System.out.println("Number of columns = " + noOfColumns);
for(int i=1; i<=noOfColumns; i++)
{
System.out.println("Column No : " + i);
System.out.println("Column Name : " + rsmd.getColumnName(i));
System.out.println("Column Type : " + rsmd.getColumnTypeName(i));
System.out.println("Column display size : " + rsmd.getColumnDisplaySize(i));
}
conn.close();
}
}
Slip Nos -12
1) Write a JSP program to check whether given number is Perfect or not. (Use Include directive)
Index.html file:
<!DOCTYPE html>
<html>
<head>
<title>PERFECT NUMBER</title>
</head>
<body>
<form action="perfect.jsp" method="post">
Enter Number :<input type="text" name="num">
<input type="submit" value="Submit" name="s1">
</form>
</body>
</html>
Perfect.jsp file:
<%
if(request.getParameter("s1")!=null)
{
Integer num,a,i,sum = 0;
num = Integer.parseInt(request.getParameter("num"));
a = num;
for(i=1;i<a;i++)
{
if(a%i==0)
{
sum=sum + i;
}
}
if(sum==a)
{
out.println(+num+ "is a perfect number");
}
else
{
out.println(+num+ "is not a perfect number");
}
}
%>
Q2) Write a Java Program to create a PROJECT table with field’s project_id, Project_name, Project_description, Project_Status.
Insert values in the table. Display all the details of the PROJECT table in a tabular format on the screen.(using swing)
import java.sql.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
JTable t;
JScrollPane js;
Statement stmt ;
ResultSet rs ;
ResultSetMetaData rsmd ;
int columns;
Vector columnNames = new Vector();
Vector data = new Vector();
Slip13_2()
{
t1 = new JTextField(20);
t2 = new JTextField(20);
t3 = new JTextField(20);
b1 = new JButton("Save");
b2 = new JButton("Display");
b3 = new JButton("Clear");
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
p=new JPanel();
p1=new JPanel();
p.add(l1);
p.add(t1);
p.add(l2);
p.add(t2);
p.add(l3);
p.add(t3);
p.add(b1);
p.add(b2);
p.add(b3);
add(p);
setLayout(new GridLayout(2,1));
setSize(600,800);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
else
JOptionPane.showMessageDialog(null,"Record NOT
inserted ");
}//end of try
catch(Exception ex)
{
System.out.println(ex);
//ex.printStackTrace();
}
}//end of if
else if((JButton)b2==e.getSource())
{
try
{
Class.forName(“org.postgresql.Driver”);
con=DriverManager.getConnection(“jdbc:postgresql://
192.168.100.254/Bill”,”oracle”,”oracle”);
System.out.println("Connected");
stmt=con.createStatement();
rs = stmt.executeQuery("select * from stud");
rsmd = rs.getMetaData();
columns = rsmd.getColumnCount();
p1.add(js);
add(p1);
setSize(600, 600);
setVisible(true);
}
catch(Exception e1)
{
System.out.println(e1);
}
}
else
{
t1.setText(" ");
t2.setText(" ");
t3.setText(" ");
}
}//end of method
Q1) Write a Java program to display information about the database and list all the tables in the
database. (Use DatabaseMetaData).
import java.sql.*;
import java.io.*;
public class DBMetaData
{
public static void main(String[] args) throws Exception
{
ResultSet rs = null;
Class.forName("org.postgresql.Driver");
Connection conn = DriverManager.getConnection("jdbc:postgresql://localhost/dbtry","postgres","redhat");
DatabaseMetaData dbmd = conn.getMetaData();
System.out.println("Database Product name = " + dbmd.getDatabaseProductName());
System.out.println("User name = " + dbmd.getUserName());
System.out.println("Database driver name= " + dbmd.getDriverName());
System.out.println("Database driver version = "+ dbmd.getDriverVersion());
System.out.println("Database product name = " + dbmd.getDatabaseProductName());
System.out.println("Database Version = " + dbmd.getDriverMajorVersion());
rs = dbmd.getTables(null,null,null, new String[]{"TABLE"});
System.out.println("List of tables...");
while(rs.next())
{
String tblName = rs.getString("TABLE_NAME");
System.out.println("Table : "+ tblName);
}
conn.close();
}
}
Q2) Write a Java program to show lifecycle (creation, sleep, and dead) of a thread. Program should print randomly the name of
thread and value of sleep time. The name of the thread should be hard coded through constructor. The sleep time of a thread
will be a random integer in the range 0 to 4999.
Q1) Write a Java program for a simple search engine. Accept a string to be searched. Search the string in all text files in the current folder. Use a separate
thread for each file. The result should display the filename and line number where the string is found.
import java.io.*;
public class SearchThread extends Thread
{
File f1;
String fname;
static String str;
String line;
LineNumberReader reader = null;
SearchThread(String fname)
{
this.fname=fname;
f1=new File(fname);
}
public void run()
{
try
{
FileReader fr=new FileReader(f1);
reader=new LineNumberReader(fr);
while((line=reader.readLine())!=null)
{
if(line.indexOf(str)!=-1)
{
System.out.println("string found in "+fname+"at "+reader.getLineNumber()+"line");
stop();
}
}
}
catch(Exception e)
{
}
}
public static void main(String[] args) throws IOException
{
Thread t[]=new Thread[20];
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter String to search");
str=br.readLine();
FilenameFilter filter = new FilenameFilter()
{
public boolean accept(File file, String name)
{
if (name.endsWith(".txt"))
{
return true;
}
else
{
return false;
}
}
};
File dir1 = new File(".");
File[] files = dir1.listFiles(filter);
if (files.length == 0)
{
System.out.println("no files available with this extension");
}
else
{
for(int i=0;i<files.length;i++)
{
for (File aFile : files)
{
t[i]=new SearchThread(aFile.getName());
t[i].start();
}
}
}
}
}
Q2 ) Write a JSP program to calculate sum of first and last digit of a given number. Display sum in Red Color with font size 18.
HTML FILE
<!DOCTYPE html>
<html>
<body>
<form method=post action="Slip7.jsp">
Enter Any Number : <Input type=text name=num><br><br>
<input type=submit value=Display>
</form>
</body>
</html>
JSP FILE:
Slip Nos 15
Q1) Write a java program to display name and priority of a Thread
{
{
Thread t=Thread.currentThread();
try {
for(int i=2;i>0;i--)
{
System.out.println(i);
Thread.sleep(1000);
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Q2) Write a SERVLET program which counts how many times a user has visited a web page. If user is visiting the page for the first time, display a welcome
message. If the user is revisiting the page, display the number of times visited. (Use Cookie)
import java.io.*;
import javax.servlet.*;
{
throws IOException,ServletException
{
response.setContentType("text/html");
PrintWriter out=response.getWriter();
String k=String.valueOf(i);
response.addCookie(c);
int j=Integer.parseInt(c.getValue());
if(j==1)
{
}
else {
}
i++;
}
}Web.xml
<web-app>
<servlet>
<servlet-name>VisitServlet</servlet-name>
<servlet-class>VisitServlet</servlet-class>
</servlet>
36<servlet-mapping>
<servlet-name>VisitServlet</servlet-name>
<url-pattern>/VS</url-pattern>
</servlet-mapping>
</web-app>
Slip NO-16