TYBCS Java-II Practical Slip Solutions
TYBCS Java-II Practical Slip Solutions
Slip 2)
1. Write a java program to read ‘N’ names of your friends, store it into HashSet and display
them in ascending order.
import java.util.*;
public class GFG
{
public static void main(String args[])
{
HashSet<String> set = new HashSet<String>();
set.add("geeks");
set.add("practice");
set.add("contribute");
set.add("ide");
System.out.println("Original HashSet: "+ set);
ListList<String> list = new ArrayList<String>(set);
Collections.sort(list);
System.out.println("HashSet elements "+ "in sorted order "+ "using List: "+ list);
}
}
2. Design a servlet that provides information about a HTTP request from a client, such as IP-
Address and browser type. The servlet also provides information about the server on which
the servlet is running, such as the operating system type, and the names of currently loaded
servlets.
serverInfo.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class serverInfo extends HttpServlet implements Servlet
{
protected void doGet(HttpServletRequest req,HttpServletResponse res)throws
IOException,ServletException
{
res.setContentType("text/html");
PrintWriter pw=res.getWriter();
pw.println("<html><body><h2>Information about Http Request</h2>");
pw.println("<br>Server Name: "+req.getServerName());
pw.println("<br>Server Port: "+req.getServerPort());
pw.println("<br>Ip Address: "+req.getRemoteAddr());
//pw.println("<br>Server Path: "+req.getServerPath()); pw.println("<br>Client Browser:
"+req.getHeader("User-Agent"));
pw.println("</body></html>");
pw.close();
}
}
Web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app>
<servlet>
<servlet-name>serverInfo</servlet-name>
<servlet-class>ServerInfo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>serverInfo</servlet-name>
<url-pattern>/server</url-pattern>
</servlet-mapping>
</web-app>
Slip 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.*;" %>
<%! Int pno;
String pname,address; %>
<%
try{
Class.forName("org.postgresql.Driver");
Connection cn=DriverManager.getConnection("jdbc:postgresql:patient ","postgres","");
Statement st=cn.createStatement();
ResultSe trs=st.executeQuery("select * from Patient");
%>
<table border="1" width="40%"> <tr> <td>Patient No</td> <td>Name</td>
<td>Address</td> <td>Age</td> <td>disease</td> </tr> <% while(rs.next()) { %>
<tr><td><%= rs.getInt("pno") %></td> <td><%= rs.getString("pname") %></td> <td><%=
rs.getString("address") %><td><%= rs.getInt("age") %></td><td><%= rs.getString("disease
") %><td> </tr> <%
}
cn.close();
}catch(Exception e)
{
out.println(e);
}
%>
</body>
</html>
2 .Write a Java program to create LinkedList of String objects and perform the following:
i. Add element at the end of the list
ii. Delete first element of the list
iii. Display the contents of list in reverse order
import java.util.*;
public class LinkedList3 {
Slip 4)
1. Write a Java program using Runnable interface to blink Text on the frame.
import java.awt.*;
import java.awt.event.*;
public class BlinkText extends Frame implements Runnable
{
Thread t;
Label l1;
int f;
public BlinkText()
{
t=new Thread(this);
t.start();
setLayout(null);
l1=new Label("Hello JAVA");
l1.setBounds(100,100,100,40);
add(l1);
setSize(300,300);
setVisible(true);
f=0;
}
public void run()
{
try
{
if(f==0)
{
t.sleep(200);
l1.setText("");
f=1;
}
if(f==1)
{
t.sleep(200);
l1.setText("Hello Java");
f=0;
}
}catch(Exception e)
{
System.out.println(e);
}
run();
}
public static void main(String args[])
{
new BlinkText();
}
}
2. Write a Java program to store city names and their STD codes using an appropriate
collection and perform following operations:
i. Add a new city and its code (No duplicates)
ii. Remove a city from the collection
iii. Search for a city name and display the code
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
class Slip16_2 extends JFrame implements ActionListener
{
JTextField t1,t2,t3;
JButton b1,b2,b3;
JTextArea t;
JPanel p1,p2;
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);
p2= new JPanel();
p2.setLayout(new GridLayout(2,3));
p2.add(t1);
p2.add(t2);
p2.add(b1);
p2.add(t3);
p2.add(b2);
p2.add(b3);
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 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.
// Java Program to Demonstrate Getting Keys// as an Enumeration of Hashtable class//
Importing required classes
import java.io.*;
import java.util.*;
// Main class
class GFG
{
// Main driver method
public static void main(String[] args)
{
// Creating an empty hashtable
Hashtable<String, String> ht= new Hashtable<String, String>();
// Inserting key-value pairs into hashtable// using put() method
ht.put("Name", "Rohan");
ht.put("Mpbile_Nos", "8446049402");
// Now creating an Enumeration object
// to store keys
Enumeration<String> e = ht.keys();
// Condition holds true till there is// single key remaining
while (e.hasMoreElements())
{
// Getting key
String key = e.nextElement();
// Printing key and valuecorresponding to// that key
System.out.println(key + ":" +ht.get(key));
}
}
}
2. Create a JSP page for an online multiple choice test. The questions are randomly selected
from a database and displayed on the screen. The choices are displayed using radio buttons.
When the user clicks on next, the next question is displayed. When the user clicks on submit,
display the total score on the screen.
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 * fromquestions 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 * fromquestions 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 fromquestions 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>
Slip 6)
1. Write a Java program to accept ‘n’ integers from the user and store them in a collection.
Display them in the sorted order. The collection should not accept duplicate elements. (Use a
suitable collection). Search for a particular element using predefined search method in the
Collection framework.
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(newInputStreamReader(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");
}
}
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”.
Slip 10)
1. Write a Java program to display the Current Date using spring.
import java.text.*;
import java.util.*;
public class GFG
{
public static void main(String args[])
{
SimpleDateFormat formatDate = newSimpleDateFormat("dd/MM/yyyy HH:mm:ss z");
Date date = new Date();
formatDate.setTimeZone(TimeZone.getTimeZone("IST"));
System.out.println(formatDate.format(date));
}
}
2. 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).
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
class StudendAwtJdbc extends Frame implements ActionListener
{
Label l1,l2;
TextField t1,t2;
Button b1;
public StudendAwtJdbc()
{
setLayout(null);
setSize(800,600);
setTitle("Record Display");
setVisible(true);
l1=new Label("ENTER ENO");
l1.setBounds(100,200,150,50);
add(l1);
//l2=new Label("Answer");
//l2.setBounds(100,100,150,50);
//add(l2);
t1=new TextField();
t1.setBounds(500,200,150,50);
add(t1);
t2=new TextField();
t2.setBounds(300,300,150,50);
add(t2);
b1=new Button("DISPLAY");
b1.setBounds(300,400,150,50);
add(b1);
b1.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
String cap=ae.getActionCommand();
if(cap.equals("DISPLAY"))
{
try
{
Connection con;
PreparedStatement ps;
String query;
ResultSet rs;
int a;
String d;
/*Scanner sc=new Scanner(System.in);
System.out.println("Pls Enter ENAME");
b=sc.next();
*/
a=Integer.parseInt(t1.getText());
Class.forName("com.mysql.jdbc.Driver"); //step 2 load & register the db driver
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/testdb","root","");
//step 3 create the connection
query="select * from student where rno like ?"; //step 5 - make the query
ps=con.prepareStatement(query); //step 4 create the statement
ps.setInt(1,a);
rs=ps.executeQuery(); // step 6 fire the query
if(rs.next())
{
t2.setText(rs.getInt("rno") + " " + rs.getString("sname") + " " +
rs.getFloat("percentage"));
}
ps.close(); //step 7 close the statement and connections
con.close();
}
catch(Exception e){}
}
}
}
public class Slip19_q2
{
public static void main(String args[])
{
new StudendAwtJdbc();
}
}
Slip 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 servletDatabaseextends 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>");
2. Write a Java program to display information about all columns in the DONAR table using
ResultSetMetaData.
import java.sql.*;
public class DONOR {
public static void main(String[] args) {
try {
// load a driver
Class.forName("org.postgresql.Driver");
// Establish Connection
Connection conn =
DriverManager.getConnection("jdbc:postgresql://localhost/postgres", "postgres", "dsk");
Statement stmt = null;
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select * from donor");
ResultSetMetaData rsmd = rs.getMetaData();
System.out.println("\t-------------------------------------------------");
int count = rsmd.getColumnCount();
System.out.println("\t No. of Columns: " + rsmd.getColumnCount());
System.out.println("\t-------------------------------------------------");
for (int i = 1; i <= count; i++)
{
System.out.println("\t\tColumn No : " + i);
System.out.println("\t\tColumn Name : " + rsmd.getColumnName(i));
System.out.println("\t\tColumn Type : " + rsmd.getColumnTypeName(i));
System.out.println("\t\tColumn Display Size : " + rsmd.getColumnDisplaySize(i));
System.out.println();
} // for
System.out.println("\t--------------------------------------------------");
rs.close();
stmt.close();
conn.close();
} // try
catch (Exception e) {
System.out.println(e);
} // catch
}
}
Slip 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:
<%@ page import="java.util.*" %>
<%
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");
}
}
%>
2. 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.*;
class Slip13_2 extends JFrame implements ActionListener
{
JLabel l1,l2,l3;
JTextField t1,t2,t3;
JButton b1,b2,b3;
String sql;
JPanel p,p1;
Connection con;
PreparedStatement ps;
JTable t;
JScrollPane js;
Statement stmt;
ResultSet rs ;
ResultSetMetaData rsmd ;
int columns;
Vector columnNames = new Vector();
Vector data = new Vector();
Slip13_2()
{
l1 = new JLabel("Enter no :");
l2 = new JLabel("Enter name :");
l3 = new JLabel("percentage :");
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);
}
public void actionPerformed(ActionEvent e)
{
if((JButton)b1==e.getSource())
{
int no = Integer.parseInt(t1.getText());
String name = t2.getText();
int p = Integer.parseInt(t3.getText());
System.out.println("Accept Values");
try
{
Class.forName(“org.postgresql.Driver”);
con=DriverManager.getConnection(“jdbc:postgresql://192.168.100.254/Bill”,”oracle”,”oracl
e”);
sql = "insert into stud values(?,?,?)";
ps = con.prepareStatement(sql);
ps.setInt(1,no);
ps.setString(2, name);
ps.setInt(3,p);
System.out.println("values set");
int n=ps.executeUpdate();
if(n!=0)
{
JOptionPane.showMessageDialog(null,"Recordinsered ...");
}
else
JOptionPane.showMessageDialog(null,"RecordNOT 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”,”oracl
e”);
System.out.println("Connected");
stmt=con.createStatement();
rs = stmt.executeQuery("select * from stud");
rsmd = rs.getMetaData();
columns = rsmd.getColumnCount(); //Get Columns name
for(int i = 1; i <= columns; i++)
{
columnNames.addElement(rsmd.getColumnName(i));
} //Get row data
while(rs.next())
{
Vector row = new Vector(columns);
for(int i = 1; i <= columns; i++)
{
row.addElement(rs.getObject(i));
}
data.addElement(row);
}
t = new JTable(data, columnNames);
js = new JScrollPane(t);
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
public static void main(String a[])
{
Slip13_2 ob = new Slip13_2();
}
}
Slip 13)
1. Write a Java program to display information about the database and list all the tables in the
database. (Use DatabaseMetaData).
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.DatabaseMetaData;
public class GetAllTables
{
public static void main(String[] args) throws SQLException
{
Connection conn = null;
try {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (Exception e) {
System.out.println(e);
}
conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/test",
"Manish", "123456");
System.out.println("Connection is created succcessfully:");
} catch (Exception e) {
System.out.println(e);
}
ResultSet rs = null;
DatabaseMetaData meta = (DatabaseMetaData) conn.getMetaData();
rs = meta.getTables(null, null, null, new String[] {
"TABLE"
});
int count = 0;
System.out.println("All table names are in test database:");
while (rs.next()) {
String tblName = rs.getString("TABLE_NAME");
System.out.println(tblName);
count++;
}
System.out.println(count + " Rows in set ");
}
}
2. 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.
Class MyThread extends Thread
{
public MyThread(String s)
{
super(s);
}
public void run()
{
System.out.println(getName()+"thread created.");
while(true)
{
System.out.println(this);
int s=(int)(math.random()*5000);
System.out.println(getName()+"is sleeping for :+s+"msec");
try{
Thread.sleep(s);
}
catch(Exception e)
{
}
}
}
Class ThreadLifeCycle
{
public static void main(String args[])
{
MyThread t1=new MyThread("shradha"),t2=new MyThread("pooja");
t1.start();
t2.start();
try
{
t1.join();
t2.join();
}
catch(Exception e)
{
}
System.out.println(t1.getName()+"thread dead.");
System.out.println(t2.getName()+"thread dead.");
}
}
Slip 14)
1. 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.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.Scanner;
class Mythread extends Thread
{
String str;
String filename;
Mythread(String str, String filename)
{
this.str = str;
this.filename = filename;
}
public void run()
{
try
{
int flag = 0;
File f = new File(filename);
BufferedReader br = new BufferedReader(new FileReader(f));
String line = "";
while ((line = br.readLine()) != null)
{
if (line.contains(str) == true)
{
flag = 1;
break;
}
}
if (flag == 1)
{
System.out.println("String found in folder/file :" + filename);
}
else
{
System.out.println("String not found in folder/file :" + filename);
}
br.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
public class B2 {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter Search string :");
String str = sc.nextLine();
//Your folder name
String dirname = "thread";
File d = new File(dirname);
if (d.isDirectory())
{
String s[] = d.list();
for (int i = 0; i < s.length; i++)
{
File f = new File(dirname + "/" + s[i]);
if (f.isFile() && s[i].endsWith(".txt"))
{
Mythread t = new Mythread(str, dirname + "/" + s[i]);
t.start();
}
}
}
sc.close();
}
}
2. 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
<html>
<body>
<form method=post action="Slip7.jsp">
Enter Any Number : <Input type=text name=num>
<input type=submit value=Display>
</form>
</body>
</html>
JSP FILE:
<%@page contentType="text/html" pageEncoding="UTF-8">
<!DOCTYPE html>
<html>
<body>
<%! intn,rem,r; %>
<% n=Integer.parseInt(request.getParameter("num"));
if(n<10)
{
out.println("Sum of first and last digit is ");
%><font size=18 color=red><%= n %>
<%
}
else
{
rem=n%10;
do
{
r=n%10;
n=n/10;
}while(n>0);
n=rem+r;
out.println("Sum of first and last digit is ");
%><font size=18 color=red><%= n %>
<%
}
%>
</body>
</html>
Slip 15)
1. Write a java program to display name and priority of a Thread.
class Slip15_1
{
public static void main(String a[])
{
String S;
int p;
Thread t = Thread.currentThread();
S = t.getName();
System.out.println("\n Current Thread name : "+S);
p = t.getPriority();
System.out.println("\n Current thread priority : "+p);
t.setName("My Thread");
S = t.getName();
System.out.println("\nChanged Name : "+S);
t.setPriority(2);
p = t.getPriority();
System.out.println("\nChanged Priority : "+p);
}
}
2. 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)
Index.html file:
<html>
<title>april</title>
<body>
<form name="f1" action="april" method="get">
<!--<b>User Name : </b> <input type="text" name="s1"> <br><br>
<b>Password : </b> <input type="text" name="s2"> <br><br>-->
<input type="Submit" value="login " name="b1">
</form>
</body>
</html>
Web.xml file:
<web-app>
<servlet>
<servlet-name>details</servlet-name>
<servlet-class>login</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>details</servlet-name>
<url-pattern>/april</url-pattern>
</servlet-mapping>
</web-app>
Login.java file:
import jakarta.servlet.http.*;
import jakarta.servlet.*;
import java.io.*;
public class login extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res) throws
IOException,ServletException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
Cookie ca[]=req.getCookies();
if(ca==null)
{
out.println("First Visit");
Cookie visit=new Cookie("vcnt","1");
visit.setMaxAge(24*3600);
res.addCookie(visit);
}
else
{
int counter=Integer.parseInt(ca[0].getValue());
counter++; //3 "3"
out.println(counter +" Visit");
ca[0].setValue(Integer.toString(counter));
res.addCookie(ca[0]);
}
}
}