Java All

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 91

slip no 1

Q.1

package A1;
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();
}
}

Q.2

package A1;
import javax.swing.*;
import java.awt.*;
public class EmpDisply extends JFrame
{
public EmpDisply(String name1,String dept,String addr , int salr,long phon)
{
setVisible(true);
setSize(250,220);
String Details;
setTitle(“Emplyee Detailsâ€);
setResizable(false);

JLabel jLabel1 = new JLabel(†Employee Details “);


JLabel jLabel2 = new JLabel(†Name :- “);
JTextField jTextField1 = new JTextField(10);
JLabel jLabel3 = new JLabel(“Department :- “);
JTextField jTextField2 = new JTextField(10);
JLabel jLabel4 = new JLabel(†Address :- “);
JTextField jTextField3 = new JTextField(10);
JLabel jLabel5 = new JLabel(†Salary :- †);
JTextField jTextField4 = new JTextField(10);
JLabel jLabel6 = new JLabel(“Phone No :- “);
JTextField jTextField5 = new JTextField(10);

setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

jLabel1.setForeground(new java.awt.Color(255, 51, 255));


jTextField1.setEditable(false);
jTextField2.setEditable(false);
jTextField3.setEditable(false);
jTextField4.setEditable(false);
jTextField5.setEditable(false);
Container contentPane = getContentPane();
JPanel p=new JPanel();
p.add(jLabel1);
p.add(jLabel2);
p.add(jTextField1);
p.add(jLabel3);
p.add(jTextField2);
p.add(jLabel4);
p.add(jTextField3);
p.add(jLabel5);
p.add(jTextField4);
p.add(jLabel6);
p.add(jTextField5);
contentPane.add(p);
jTextField1.setText(name1);
jTextField2.setText(dept);
jTextField3.setText(addr);
jTextField4.setText(“â€+salr);
jTextField5.setText(“â€+phon);
}
}

slip no 2

Q.1
package A1;
public class HashSetSortingDemo{

public static void main(String args[]) {

HashSet<String> names = new HashSet<String>();

names.add("Asker");
names.add("Crak");
names.add("Bayliss");
names.add("Mohna");
names.add("Dina");

System.out.println("HashSet before sorting : " + names);

// Sorting HashSet using List


List<String> tempList = new ArrayList<String>(names);
Collections.sort(tempList);

System.out.println("HashSet element in sorted order : " + tempList);

// Sorting HashSet using TreeSet


TreeSet<String> sorted = new TreeSet<String>(names);

System.out.println("HashSet sorted using TreeSet : " + sorted);


}

Q.2

package A1;
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 no 3

Q.1

package A1;
<%@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>

Q.2

slip no 4

Q.1

import java.awt.*;
import java.awt.event.*;

class Slip8_1 extends Frame implements Runnable


{
Thread t;
Label l1;
int f;
Slip8_1()
{
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 a[])
{
new Slip8_1();
}
}

Q.2

/* Slip16_2 */
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 no 5

Q.1

import java.io.*;

import java.util.*;

import java.util.Scanner;

class HashTabble

{
public static void main(String args[])

// Create an empty Hashtable that stores integer (ID) and string (Name) values

Hashtable<Integer, String> myhashtable = new Hashtable<>();

int id;

String name;

Scanner obj1 = new Scanner(System.in);

for(int i = 0; i< 10; i++)

System.out.print("Enter the student name: ");

name = obj1.nextLine();

myhashtable.put(i+1, name);

// print the hashtable

System.out.println("Initial hash table : " + myhashtable);

// remove the id from the hash table

System.out.print("Enter an id to be deleted form hash table: ");

id = obj1.nextInt();

myhashtable.remove(id);

// print the hash table after deleting the specified record


System.out.println("Hash Table after deleting the ID : " + myhashtable);

Q.2

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>

slip no 6

Q.1

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");
}
}

Q.2

import java.applet.*;
public class signal extends Applet implements Runnable
{
int r,g1,y,i;
Thread t;
public void init()
{
r=0;g1=0;y=0;
t=new Thread(this);
t.start();
}
public void run()
{
try { for (i=24;i>=1;i--)
{
t.sleep(100);
if (i>=16 && i<24)
{
g1=1;
repaint();
}
if (i>=8 && i<16)
{
y=1;
repaint();
}
if (i>=1 && i<8)
{
r=1;
repaint();
}
}
23 if (i==0)
{
run();
}
}
catch(Exception e)
{
}
}
public void paint(Graphics g) {
g.drawOval(100,100,100,100);
g.drawOval(100,225,100,100);
g.drawOval(100,350,100,100);
g.drawString("start",200,200);
if (r==1)
{ g.setColor(Color.red);
g.fillOval(100,100,100,100);
g.drawOval(100,100,100,100);
g.drawString("stop",200,200);
r=0;
}
if (g1==1)
{ g.setColor(Color.green);
g.fillOval(100,225,100,100);
g1=0;
g.drawOval(100,225,100,100);
g.drawString("go",200,200);
}
if (y==1)
{ g.setColor(Color.yellow);
g.fillOval(100,350,100,100);
y=0;
g.drawOval(100,350,100,100);
g.drawString("slow",200,200);
}
}
}

slip no 7

Q.1

import java.util.Random;

class RandomNumberThread extends Thread {


public void run() {
Random random = new Random();
for (int i = 0; i < 10; i++) {
int randomInteger = random.nextInt(100);
System.out.println("Random Integer generated : " + randomInteger);
if((randomInteger%2) == 0) {
SquareThread sThread = new SquareThread(randomInteger);
sThread.start();
}
else {
CubeThread cThread = new CubeThread(randomInteger);
cThread.start();
}
try {
Thread.sleep(1000);
}
catch (InterruptedException ex) {
System.out.println(ex);
}
}
}
}

class SquareThread extends Thread {


int number;

SquareThread(int randomNumbern) {
number = randomNumbern;
}

public void run() {


System.out.println("Square of " + number + " = " + (number * number));
}
}

class CubeThread extends Thread {


int number;

CubeThread(int randomNumber) {
number = randomNumber;
}

public void run() {


System.out.println("Cube of " + number + " = " + number * number * number);
}
}

public class MultiThreadingTest {


public static void main(String args[]) {
RandomNumberThread rnThread = new RandomNumberThread();
rnThread.start();
}
}

Q.2

import java.sql.*;

public class connection {

// object of Connection class


// initially assigned NULL
Connection con = null;
public static Connection connectDB()

try {

// Step 2 is involved among 7 in Connection


// class i.e Load and register drivers

// 2(a) Loading drivers using forName() method


// name of database here is mysql
Class.forName("com.mysql.jdbc.Driver");

// 2(b) Registering drivers using DriverManager


Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/hotelman",
"root", "1234");
// For DB here (custom sets)
// root is the username, and
// 1234 is the password

// returning the object of Connection class


// to be used in main class (Example2)
return con;
}

// Catch block to handle the exceptions


catch (SQLException | ClassNotFoundException e) {

// Print the exceptions


System.out.println(e);

return null;
}
}
}

import java.sql.*;

// Main/App class of above Connection class


public class GFG {

// MAin driver method


public static void main(String[] args)
{
// Step 2: Showing above Connection class i.e
// loading and registering drivers

// Initially assigning NULL parameters


// to object of Connection class
Connection con = null;
PreparedStatement ps = null;

// Step 3: Establish the connection


con = connection.connectDB();

// Try block to check if exception/s occurs


try {

// Step 4: Create a statement


String sql = "insert into cuslogin values('geeksforgeeks','gfg','geeks@email.com','flat
1','1239087474',10)";

// Step 5: Execute the query


ps = con.prepareStatement(sql);

// Step 6: Process the results


ps.execute();
}

// Optional but recommended


// Step 7: Close the connection

// Catch block to handle the exception/s


catch (Exception e) {

// Print the exception


System.out.println(e);
}
}
}

slip no 8

Q.1

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
class InvalidBirthDateException extends Exception {

String msg = "Invalid Date Exception\n";

public String toString() {


return msg;
}

public class Cowin extends JFrame implements ActionListener {


JTextField adhar, byear, phone, hosp;
JPanel p1, p2, p3, p4;
JButton add, update, delete, view, search;
JRadioButton r1, r2, r3, r4, r5, r6, r7, r8;
ButtonGroup bg,bg1,bg2;
JComboBox hos;
String s[] = { "Tambe Hospital", "Daima Hospital", "Nighute Hospital" };

Cowin() {
setTitle("Cowin Registration");

setSize(800, 600);

setLayout(new GridLayout(8, 2, 40, 40));


setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JLabel adharno = new JLabel("Adhar Card Number: ");


add(adharno);
adhar = new JTextField(10);
add(adhar);

JLabel Byear = new JLabel("Birth Year: ");


add(Byear);
byear = new JTextField(10);
add(byear);

JLabel phoneNo = new JLabel("Mobile Number: ");


add(phoneNo);
phone = new JTextField(10);
add(phone);

// Age Radio Button


p1 = new JPanel();
p1.setLayout(new FlowLayout());

JLabel Age = new JLabel("Age Group : ");


add(Age);

r1 = new JRadioButton("18 & above");


p1.add(r1);
// to get the value of radio button
r1.setActionCommand("18 & above");

r2 = new JRadioButton("45 & above");


r2.setActionCommand("45 & above");
p1.add(r2);
add(p1);

JLabel hospital = new JLabel("Select Hospital: ");


add(hospital);

hos = new JComboBox(s);


add(hos);

// Vaccines Radio Button


p2 = new JPanel();
p2.setLayout(new FlowLayout());

JLabel Vaccines = new JLabel("Vaccines : : ");


add(Vaccines);

r3 = new JRadioButton("Covishield");
p2.add(r3);
r3.setActionCommand("Covishield");

r4 = new JRadioButton("Covaxin");
p2.add(r4);
r4.setActionCommand("Covaxin");

r5 = new JRadioButton("Sputnik V");


p2.add(r5);
r5.setActionCommand("SputnikV");
add(p2);

// TimeSlot Radio Button


p3 = new JPanel();
p3.setLayout(new FlowLayout());

JLabel Time = new JLabel("Time Slot :: ");


add(Time);
r6 = new JRadioButton("Morning");
p3.add(r6);
r6.setActionCommand("Morning");
r7 = new JRadioButton("Afternoon");
p3.add(r7);
r7.setActionCommand("Afternoon");

r8 = new JRadioButton("Evening");
p3.add(r8);
r8.setActionCommand("Evening");

add(p3);

// Button
p4 = new JPanel();
p4.setLayout(new FlowLayout());

add = new JButton("Add");


p4.add(add);
update = new JButton("Update");
p4.add(update);
delete = new JButton("Delete");
p4.add(delete);
view = new JButton("View");
p4.add(view);
search = new JButton("Search");
p4.add(search);
add(p4);

add.addActionListener(this);

bg = new ButtonGroup();
bg.add(r1);
bg.add(r2);

bg1 = new ButtonGroup();


bg1.add(r4);
bg1.add(r3);
bg1.add(r5);

bg2 = new ButtonGroup();


bg2.add(r6);
bg2.add(r7);
bg2.add(r8);

setVisible(true);
}

public void actionPerformed(ActionEvent ae) {


if (ae.getSource() == add) {
String adharno = (adhar.getText());
int year = Integer.parseInt(byear.getText());
String phNo = (phone.getText());
String hospital = (String) (hos.getSelectedItem());
String age=bg.getSelection().getActionCommand();
String vaccine=bg1.getSelection().getActionCommand();
String timestamp=bg2.getSelection().getActionCommand();

try {
if (year == 0000) {
throw new InvalidBirthDateException();
} else {
Connection conn = null;
PreparedStatement pstmt = null;
try {
// load a driver
Class.forName("org.postgresql.Driver");

// Establish Connection
// Use database name & password according to your
"dbname","pass"
conn =
DriverManager.getConnection("jdbc:postgresql://localhost/postgres", "postgres", "dsk");
pstmt = conn.prepareStatement("insert into
cowin values(?,?,?,?,?,?,?)");

pstmt.setString(1, adharno);
pstmt.setInt(2, year);
pstmt.setString(3, phNo);
pstmt.setString(4, hospital);
pstmt.setString(5, age);
pstmt.setString(6, vaccine);
pstmt.setString(7, timestamp);

int result = pstmt.executeUpdate();


if (result == 1) {

JOptionPane.showMessageDialog(null,
"Succesfully Inserted", hospital,

JOptionPane.INFORMATION_MESSAGE);
}

pstmt.close();
conn.close();

} // try
catch (Exception e) {
JOptionPane.showMessageDialog(null, e,
"ERROR OCCURED", JOptionPane.ERROR_MESSAGE);
} // catch
}
} catch (InvalidBirthDateException e) {
JOptionPane.showMessageDialog(null, e, "ERROR
OCCURED", JOptionPane.ERROR_MESSAGE);
}
}
}

public static void main(String[] args) {


new Cowin();
}// MAIN

create table cowin(adharno char(22) PRIMARY KEY,year int,phNo char(15),age


char(30),hospital char(30),vaccine char(33),timestamp char(44));

select * from cowin;

Q.2

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<form action="Slip30.jsp" method="post">
Enter Number :
<input type="text" name="num">
<input type="submit" value="Submit">
</form>
</body>
</html>

JSP FILE :Slip30.jsp


<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%
int n = Integer.parseInt(request.getParameter("num"));
intnum,i,count;
for(num=1;num<=n;num++)
{
count=0;
for(i=2;i<=num/2;i++)
{
if(num%i==0)
{
count++;
break;
}
}
if(count==0 &&num!=1)
{
%>
<html>
<body>
<font size ="14" color="blue"><%out.println("\t"+num);%>
</body>
</html>
<%
}
}
%>

slip no 9

Q.1

import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class boucingthread extends JFrame implements Runnable


{
Thread t;
int x,y;

boucingthread()
{
super();
t= new Thread(this);
x=10;
y=10;
t.start();
setSize(1000,200);
setVisible(true);
setTitle("BOUNCEING BOLL WINDOW");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void run()
{
try
{
while(true)
{
x+=10;
y+=10;
repaint();
Thread.sleep(1000);
}
}catch(Exception e)
{

}
}

public void paint(Graphics g)


{

g.drawOval(x,y,7,7);

public static void main(String a[])throws Exception


{
boucingthread t=new boucingthread();
Thread.sleep(1000);
}
}

Q.2

1st file

public class Student {


private String name;

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public void displayInfo(){


System.out.println("Hello: "+name);
}
}

2nd file

public class Student {


private String name;

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public void displayInfo(){


System.out.println("Hello: "+name);
}
}

3rd file

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

public class Test {


public static void main(String[] args) {
Resource resource=new ClassPathResource("applicationContext.xml");
BeanFactory factory=new XmlBeanFactory(resource);

Student student=(Student)factory.getBean("studentbean");
student.displayInfo();
}
}

slip no 10

Q.1

import java.util.*;

public class GFG {


public static void main(String args[])
{
Date current_Date = new Date();
//"Date" class
//"current_Date" is Date object

System.out.println(current_Date);
// print the time and date
}
}

Q.2

CREATE DATABASE

\c stud

create table student(rollno int primary key,name text,percentage float);

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 no 11

Q.1

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>
<body>
<form action="http://localhost:8080/servDb/servletDatabase" method="get">
Enter Roll No:<input type="text" name="t1">
<input type="submit">
</form>
</body>
</html>

create database stud;


Query OK, 1 row affected (0.00 sec)

create table student(rollno int primary key,name text,percentage float);


Query OK, 0 rows affected (0.07 sec)

insert into student values(1,'student1',79);


Query OK, 1 row affected (0.04 sec)

insert into student values(2,'student2',69);


Query OK, 1 row affected (0.05 sec)

insert into student values(3,'student3',58);


Query OK, 1 row affected (0.06 sec)

select * from student;


Q.2

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 12

Q.1

Index.html

<!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

<%@ 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");
}
}
%>

Q.2

import java.sql.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
class ProjectDisplay extends JFrame implements ActionListener {

Connection con;
ResultSet rs;
Statement st;

static JTable table;


// This column names are taken from database table which we have created...i.e here we
have create project table.
String[] columnNames = { "p_id", "p_name", "p_description", "p_status" };
JFrame frm;
JPanel p1;
String p_id = "", p_name = "", p_description = "", p_status = "";
JTextField txtid, txtname, txtdesc, textstatus;

JButton Insert, Update, Delete, Display, Exit;

Insert iobj;
Update uobj;
Delete dobj;

ProjectDisplay() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("PROJECT INFO");

p1 = new JPanel();

p1.setLayout(new GridLayout(5, 5, 30, 30));

Insert = new JButton("Insert");


p1.add(Insert);

Update = new JButton("Update");


p1.add(Update);

Delete = new JButton("Delete");


p1.add(Delete);

Display = new JButton("Display");


p1.add(Display);

Exit = new JButton("Exit");


p1.add(Exit);

Insert.addActionListener(this);
Update.addActionListener(this);
Delete.addActionListener(this);
Display.addActionListener(this);
Exit.addActionListener(this);

add(p1, BorderLayout.CENTER);
setVisible(true);
setSize(600, 600);
}// ProjectDetails

public void actionPerformed(ActionEvent ae) {

if (ae.getSource() == Display) {
frm = new JFrame("DISPLAY");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

setLayout(new BorderLayout());
DefaultTableModel model = new DefaultTableModel();

model.setColumnIdentifiers(columnNames);
table = new JTable();

table.setModel(model);

table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);

table.setFillsViewportHeight(true);

JScrollPane scroll = new JScrollPane(table);

scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED
);

scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);

try {
Class.forName("org.postgresql.Driver");
// Use database name & password according to your "dbname","pass"
con = DriverManager.getConnection("jdbc:postgresql://localhost/postgres",
"postgres", "dsk");

st = con.createStatement();
rs = st.executeQuery("select * from project");

while (rs.next()) {
p_id = rs.getString(1);
p_name = rs.getString(2);
p_description = rs.getString(3);
p_status = rs.getString(4);

// This all coloumn names are taken from project table.


model.addRow(new Object[] { p_id, p_name, p_description, p_status });

} // while
frm.add(scroll);

frm.setVisible(true);
frm.setSize(400, 400);
} // try

catch (Exception e) {
JOptionPane.showMessageDialog(null, e, "Error",
JOptionPane.ERROR_MESSAGE);
}
}

if (ae.getSource() == Insert) {
iobj = new Insert();
}

if (ae.getSource() == Update) {
uobj = new Update();
}

if (ae.getSource() == Delete) {
dobj = new Delete();
}

if (ae.getSource() == Exit) {

System.exit(1);

public static void main(String arg[]) {

new ProjectDisplay();
}// main
}// class

class Insert extends JFrame implements ActionListener {

JTextField txtst, txtpid, txtpname, txtdsc;


JButton btnadd, btnclear;
Insert() {
setTitle("Peoject Record Inserts");
setSize(400, 500);
setVisible(true);
setLayout(new GridLayout(6, 2, 40, 40));
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

JLabel id = new JLabel("Enter Project Number: ");


add(id);
txtpid = new JTextField(10);
add(txtpid);

JLabel name = new JLabel("Enter Project Name: ");


add(name);
txtpname = new JTextField(10);
add(txtpname);

JLabel dsc = new JLabel("Enter Project Description: ");


add(dsc);
txtdsc = new JTextField(10);
add(txtdsc);

JLabel st = new JLabel("Enter Project Status: ");


add(st);
txtst = new JTextField(10);
add(txtst);

btnadd = new JButton("Insert");


add(btnadd);
btnadd.addActionListener(this);

btnclear = new JButton("Cancel");


add(btnclear);
btnclear.addActionListener(this);

public void actionPerformed(ActionEvent ae) {

int p_id = Integer.parseInt(txtpid.getText());


String pname = (txtpname.getText());
String ds = (txtdsc.getText());
String st = (txtst.getText());

Connection conn = null;


PreparedStatement pstmt = null;
try {
// load a driver
Class.forName("org.postgresql.Driver");

// Establish Connection
conn = DriverManager.getConnection("jdbc:postgresql://localhost/postgres",
"postgres", "dsk");

if (ae.getSource() == btnadd) {
pstmt = conn.prepareStatement("insert into project values(?,?,?,?)");

pstmt.setInt(1, p_id);
pstmt.setString(2, pname);
pstmt.setString(3, ds);
pstmt.setString(4, st);

int result = pstmt.executeUpdate();


if (result == 1) {

JOptionPane.showMessageDialog(null, "Succesfully Inserted", st,


JOptionPane.INFORMATION_MESSAGE);
}

pstmt.close();
conn.close();
} // if of submit

if (ae.getSource() == btnclear) {
// System.exit(1);
txtpid.setText("");
txtdsc.setText("");
txtpname.setText("");
txtst.setText("");

} // if of clear

} // try
catch (Exception e) {
JOptionPane.showMessageDialog(null, e, "ERROR OCCURED",
JOptionPane.ERROR_MESSAGE);
System.out.println(e);
} // catch
}

}// insert

class Update extends JFrame implements ActionListener {

JTextField txtst, txtpid, txtpname, txtdsc;


JButton btnadd;

Update() {
setTitle("Peoject Record Update");
setSize(500, 500);
setVisible(true);
setLayout(new GridLayout(3, 2, 40, 40));
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

JLabel pid = new JLabel("Enter Projcet ID To Update: ");


add(pid);
txtpid = new JTextField(10);
add(txtpid);

JLabel st = new JLabel("Enter Updated Project Status: ");


add(st);
txtst = new JTextField(10);
add(txtst);

btnadd = new JButton("Update");


add(btnadd);
btnadd.addActionListener(this);

}// update()

public void actionPerformed(ActionEvent ae) {


String str = ae.getActionCommand();

int p_id = Integer.parseInt(txtpid.getText());


String st = (txtst.getText());

Connection conn = null;


PreparedStatement pstmt = null;
try {
// load a driver
Class.forName("org.postgresql.Driver");

// Establish Connection
conn = DriverManager.getConnection("jdbc:postgresql://localhost/postgres",
"postgres", "dsk");
if (str.equals("Update")) {
String SQL = "Update project set p_status=? where p_id=?";
pstmt = conn.prepareStatement(SQL);

pstmt.setString(1, st);
pstmt.setInt(2, p_id);

int update = pstmt.executeUpdate();


if (update == 1) {

JOptionPane.showMessageDialog(null, "Succesfully Updated", st,


JOptionPane.INFORMATION_MESSAGE);
} // if

txtpid.setText("");
txtst.setText("");
pstmt.close();
conn.close();
} // if

} // try
catch (Exception e) {
System.out.println(e);
} // catch

}// method
}// update class

class Delete extends JFrame implements ActionListener {

JTextField txtpid, txtst;


JButton btnadd;

Delete() {
setTitle("Peoject Record Delete");
setSize(400, 400);
setVisible(true);
setLayout(new GridLayout(3, 2, 20, 20));
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

JLabel pid = new JLabel("Enter Projcet ID To Delete: ");


add(pid);
txtpid = new JTextField(10);
add(txtpid);

JLabel st = new JLabel("Enter Updated Project Status: ");


add(st);
txtst = new JTextField(10);
add(txtst);

btnadd = new JButton("Delete");


add(btnadd);
btnadd.addActionListener(this);

}// Delete()
public void actionPerformed(ActionEvent ae) {
String str = ae.getActionCommand();

int p_id = Integer.parseInt(txtpid.getText());


String st = (txtst.getText());

Connection conn = null;


PreparedStatement pstmt = null;
try {
// load a driver
Class.forName("org.postgresql.Driver");

// Establish Connection
conn = DriverManager.getConnection("jdbc:postgresql://localhost/postgres",
"postgres", "dsk");
if (str.equals("Delete")) {
String SQL = "delete from project where p_id =?";
pstmt = conn.prepareStatement(SQL);

pstmt.setInt(1, p_id);

int delete = pstmt.executeUpdate();


if (delete == 1) {
JOptionPane.showMessageDialog(null, "Succesfully Deleted", st,
JOptionPane.INFORMATION_MESSAGE);
}
txtpid.setText("");
txtst.setText("");
pstmt.close();
conn.close();
} // if

} // try
catch (Exception e) {
System.out.println(e);
} // catch
}
}

create table project(p_id int primary key, p_name char(34),p_description char(56),p_status


char(34));

-- INSERT INTO project VALUES(1,'abc','java project','completed');


-- INSERT INTO project VALUES(2,'kpl','php project','completed');
-- INSERT INTO project VALUES(3,'lmn','c project','completed');
-- INSERT INTO project VALUES(4,'xyz','ruby project','completed');
SELECT * FROM project;

slip 13

Q.1

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();
}
}

Q.2

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

Q.1

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();
}
}
}
}
}

Q.2

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

Q.1

public class MainThread


{
public static void main(String arg[])
{
Thread t=Thread.currentThread();
System.out.println("Current Thread:"+t);
//Change Name t.setName("My Thread ");
System.out.println ("After the name is Changed:"+t);
try {
for(int i=2;i>0;i--)
{
System.out.println(i);
Thread.sleep(1000);
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}

Q.2

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class count extends HttpServlet


{
static int count=0,c2=0;
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String name=request.getParameter("t1");

Cookie c1=new Cookie("count",String.valueOf(count));


c2=Integer.parseInt(c1.getValue());

if(c2==0)
{
out.println("Welcome="+name);
count++;
}
else
{

c1=new Cookie("count",String.valueOf(count));
count++;
out.println("Welcome="+name+"\t"+count);
}
}
}

<html>
<body>
<form action="http://localhost:8080/serv/count" method="get">
Username:<input type="text" name="t1">
<input type="submit" >
</form>
</body>
</html>

slip 16

Q.1

import java.util.TreeSet;
public class Exercise1 {
public static void main(String[] args) {
TreeSet<String> tree_set = new TreeSet<String>();
tree_set.add("Red");
tree_set.add("Green");
tree_set.add("Orange");
tree_set.add("White");
tree_set.add("Black");
System.out.println("Tree set: ");
System.out.println(tree_set);
}
}

Q.2

Create table teacherdetails (tid number, name varchar2(20), address varchar2(40)

register.html

<!doctype html>
<body>
<form action="servlet/Register" method="post">
<fieldset style="width:20%; background-color:#ccffeb">
<h2 align="center">Registration form</h2><hr>
<table>
<tr>
<td>TId</td>
<td><input type="text" name="TId" required /></td>
</tr>
<tr>
<td>Name</td>
<td><input type="text" name="Name" required /></td>
</tr>
<tr>
<td>Address</td>
<td><textarea name="address" placeholder="Enter address
here..."></textarea></td>
</tr>
<tr>
<td><input type="reset" value="Reset"/></td>
<td><input type="submit" value="Register"/></td>
</tr>
</table>
</fieldset>
</form>
</body>
</html>

Register.java

import java.io.*;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;

public class Register extends HttpServlet


{
public void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
int id = Integer.parseInt(request.getParameter("TId"));
String name = request.getParameter("name");
String address = request.getParameter("address");
try
{
//load the driver
Class.forName("oracle.jdbc.driver.OracleDriver");
//create connection object
Connection
con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:xe","local","test");
// create the prepared statement object
PreparedStatement ps=con.prepareStatement("insert into TeacherDetails
values(?,?,?)");

ps.setInt(1, id);
ps.setString(2,name);
ps.setString(3,address);

int i = ps.executeUpdate();
if(i>0)
out.print("You are successfully registered...");
}
catch (Exception ex)
{
ex.printStackTrace();
}
out.close();
}
}

web.xml

<web-app>
<servlet>
<servlet-name>Register</servlet-name>
<servlet-class>Register</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Register</servlet-name>
<url-pattern>/servlet/Register</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>register.html</welcome-file>
</welcome-file-list>
</web-app>

slip 17

Q.1

import java.util.*;
import java.io.*;

class SortedNumbers{
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));

Set s = new TreeSet();

System.out.print("Enter no.of integers:");


int n = Integer.parseInt(br.readLine());

for(int i = 0; i < n; i++) {


System.out.print("Enter number:");
int x = Integer.parseInt(br.readLine());
s.add(x);
}
Iterator itr = s.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}

System.out.print("Enter element to be searched:");


int no = Integer.parseInt(br.readLine());

if(s.contains(no))
System.out.println("Number "+no+" found.");
else
System.out.println("Number "+no+" not found.");
}
}

Q.2

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class MultiThread extends JFrame implements ActionListener
{
Container cc;
JButton b1,b2;
JTextField t1;
MultiThread()
{
setVisible(true);
setSize(1024,768);
cc=getContentPane();
setLayout(null);
t1=new JTextField(500);
cc.add(t1);
t1.setBounds(10,10,1000,30);
b1=new JButton("start");
cc.add(b1);
b1.setBounds(20,50,100,40);
b1.addActionListener(this);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==b1)
{
new Mythread();
}
}
class Mythread extends Thread
{
Mythread()
{
start();
}
public void run()
{
for(int i=1;i<=100;i++)
{
try {
Thread.sleep(1000);
}
catch (InterruptedException e) {
}
t1.setText(t1.getText()+""+i+"\n");
//System.out.println() }
}
}
public static void main(String arg[])
{
new MultiThread().show();
}
}

slip 18

Q.1

public class MainThread


{
public static void main(String arg[])
{
Thread t=Thread.currentThread();
System.out.println("Current Thread:"+t);
//Change Name t.setName("My Thread ");
System.out.println ("After the name is Changed:"+t);
try {
for(int i=2;i>0;i--)
{
System.out.println(i);
Thread.sleep(1000);
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}

Q.2

Student.html
<html>
<body>
<form name="f1" method="Post" action="http://localhost:8080/Servlet/Student">
<fieldset>
<legend><b><i>Enter Student Details :</i><b></legend>
Enter Roll No :&nbsp <input type="text" name="txtsno"><br><br>
Enter Name :&nbsp &nbsp <input type="text" name="txtnm"><br><br>
Enter class :&nbsp &nbsp &nbsp <input type="text" name="txtclass"><br><br>
<fieldset>
<legend><b><i>Enter Student Marks Details :</i><b></legend>
Subject 1 :&nbsp &nbsp &nbsp <input type="text" name="txtsub1"><br><br>
Subject 2 :&nbsp &nbsp &nbsp <input type="text" name="txtsub2"><br><br>
Subject 3 :&nbsp &nbsp &nbsp <input type="text" name="txtsub3"><br><br>
</fieldset>
</fieldset>
<div align=center>
<input type="submit" value="Result">
</div>
</form>
</body>
</html>

Student.php

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Student extends HttpServlet
{
public void doPost(HttpServletRequest req,HttpServletResponse res)throws
IOException,ServletException
{
int sno,s1,s2,s3,total;
String snm,sclass;
float per;
40 res.setContentType("text/html");
PrintWriter out=res.getWriter();
sno=Integer.parseInt(req.getParameter("txtsno"));
snm=req.getParameter("txtnm");
sclass=req.getParameter("txtclass");
s1=Integer.parseInt(req.getParameter("txtsub1"));
s2=Integer.parseInt(req.getParameter("txtsub2"));
s3=Integer.parseInt(req.getParameter("txtsub3"));
total=s1+s2+s3;
per=(total/3);
out.println("<html><body>");
out.print("<h2>Result of student</h2><br>");
out.println("<b><i>Roll No :</b></i>"+sno+"<br>");
out.println("<b><i>Name :</b></i>"+snm+"<br>");
out.println("<b><i>Class :</b></i>"+sclass+"<br>");
out.println("<b><i>Subject1:</b></i>"+s1+"<br>");
out.println("<b><i>Subject2:</b></i>"+s2+"<br>");
out.println("<b><i>Subject3:</b></i>"+s3+"<br>");
out.println("<b><i>Total :</b></i>"+total+"<br>");
out.println("<b><i>Percentage :</b></i>"+per+"<br>");
if(per<50)
out.println("<h1><i>Pass Class</i></h1>");
else if(per<55 && per>50)
out.println("<h1><i>Second class</i></h1>");
else if(per<60 && per>=55)
out.println("<h1><i>Higher class</i></h1>");
out.close();
}
}

Web.xml

<?xml version="1.0" encoding="ISO-8859-1"?>


<web-app>
<servlet>
<servlet-name>Student</servlet-name>
<servlet-class>Student</servlet-class>
</servlet>
41<servlet-mapping>
<servlet-name>Student</servlet-name>
<url-pattern>/Student</url-pattern>
</servlet-mapping>
</web-app>
slip 19

Q.1

import java.util.*;
public class Gfg {

public static void move(int[] arr)


{
Arrays.sort(arr);
}

// Driver code
public static void main(String[] args)
{
int[] arr = { -1, 2, -3, 4, 5, 6, -7, 8, 9 };
move(arr);
for (int e : arr)
System.out.print(e + " ");
}
}

Q.2

UserPass.html

<html>
<body>
<form method=post action="http://localhost:4141/Program/servlet/UserPass">
User Name :<input type=text name=user><br><br>
Password :<input type=text name=pass><br><br>
<input type=submit value="Login">
</form>
</body>
</html>

UserPass.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class UserPass extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
PrintWriter out = response.getWriter();
try{
String us=request.getParameter("user");
String pa=request.getParameter("pass");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection cn=DriverManager.getConnection("jdbc:odbc:dsn2","","");
Statement st=cn.createStatement();
ResultSet rs=st.executeQuery("select * from UserPass");
while(rs.next())
{
if(us.equals(rs.getString("user"))&&pa.equals(rs.getString("pass")))
out.println("Valid user");
else
out.println("Invalid user");
}
}catch(Exception e)
{
out.println(e);
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
doGet(request, response);
}
}

Web.xml file(servlet entry)

<?xml version="1.0" encoding="ISO-8859-1"?>


<web-app>
<servlet>
<servlet-name>UserPass</servlet-name>
<servlet-class>UserPass</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UserPass</servlet-name>
<url-pattern>/servlet/UserPass</url-pattern>
</servlet-mapping>
</web-app>
slip 20

Q.1

NumberWord.html

<html>
<body>
<form method=get action="NumberWord.jsp">
Enter Any Number : <input type=text name=num><br><br>
<input type=submit value="Display">
</form>
<body>
</html>

NumberWord.jsp

<html>
<body>
<font color=red>
<%! int i,n;
String s1;
%>
<% s1=request.getParameter("num");
n=s1.length();
i=0;
do
{
char ch=s1.charAt(i);
switch(ch)
{
case '0': out.println("Zero ");break;
case '1': out.println("One ");break;
case '2': out.println("Two ");break;
case '3': out.println("Three ");break;
case '4': out.println("Four ");break;
case '5': out.println("Five ");break;
case '6': out.println("Six ");break;
case '7': out.println("Seven ");break;
case '8': out.println("Eight ");break;
case '9': out.println("Nine ");break;
}
i++;
}while(i<n);
%>
</font>
</body>
</html>

Q.2

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Image;
import java.awt.image.BufferedImage;

import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;

public class BlinkingLabel extends JLabel implements Runnable{

private boolean show=false,blink=true;


private Icon iconImg;
private JLayeredPane parent;

public BlinkingLabel(Icon icon, JLayeredPane pane)


{
super(icon);
this.iconImg = icon;
this.parent = pane;

this.setVisible(true);
new Thread(this).start();

public void run() {


while (blink) {
show=!show;

if(show)
parent.moveToFront(this);
else
parent.moveToBack(this);

repaint();
try { Thread.sleep(400); } catch (Exception e) { }
}
}

public boolean isBlink() {


return blink;
}

public void setBlink(boolean blink) {


this.blink = blink;
}

slip 21

Q.1

import java.util.ArrayList;
import java.util.Iterator;

public class MyClass {


public static void main(String[] args)
{
// create a list of Integers
ArrayList<Integer> numbers
= new ArrayList<Integer>();
numbers.add(12);
numbers.add(8);
numbers.add(2);
numbers.add(23);

// get the iterator on the list


Iterator<Integer> it = numbers.iterator();
while (it.hasNext()) {

// gives the next element


// and iterator moves to next
// element
Integer i = it.next();

if (i < 10) {
// removes the current element
it.remove();
}
}
System.out.println(numbers);
}
}

Q.2

import java.util.LinkedList;

public class Threadexample {


public static void main(String[] args)
throws InterruptedException
{
// Object of a class that has both produce()
// and consume() methods
final PC pc = new PC();

// Create producer thread


Thread t1 = new Thread(new Runnable() {
@Override
public void run()
{
try {
pc.produce();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
});

// Create consumer thread


Thread t2 = new Thread(new Runnable() {
@Override
public void run()
{
try {
pc.consume();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
});

// Start both threads


t1.start();
t2.start();

// t1 finishes before t2
t1.join();
t2.join();
}

// This class has a list, producer (adds items to list


// and consumer (removes items).
public static class PC {

// Create a list shared by producer and consumer


// Size of list is 2.
LinkedList<Integer> list = new LinkedList<>();
int capacity = 2;

// Function called by producer thread


public void produce() throws InterruptedException
{
int value = 0;
while (true) {
synchronized (this)
{
// producer thread waits while list
// is full
while (list.size() == capacity)
wait();

System.out.println("Producer produced-"
+ value);

// to insert the jobs in the list


list.add(value++);

// notifies the consumer thread that


// now it can start consuming
notify();

// makes the working of program easier


// to understand
Thread.sleep(1000);
}
}
}

// Function called by consumer thread


public void consume() throws InterruptedException
{
while (true) {
synchronized (this)
{
// consumer thread waits while list
// is empty
while (list.size() == 0)
wait();

// to retrieve the first job in the list


int val = list.removeFirst();

System.out.println("Consumer consumed-"
+ val);

// Wake up producer thread


notify();

// and sleep
Thread.sleep(1000);
}
}
}
}
}

slip 22

Q.1

import java.io.*;
import java.sql.*;
class Menu
{
public static void main(String args[])
{
DataInputStream din=new DataInputStream(System.in);
int rno,k,ch,per;
String nm;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection cn=DriverManager.getConnection("jdbc:odbc:BCA");
Statement st=cn.createStatement();
do {
System.out.println(" 1. Insert \n 2. Update \n 3. Delete \n 4. Search \n 5. Display \n
6. Exit");
System.out.print("Enter your choice: ");
ch=Integer.parseInt(din.readLine());
System.out.println("............................................");
switch(ch)
{
case 1:
System.out.print("How many records you want to inserted ? ");
Int n=Integer.parseInt(din.readLine());
for(int i=0;i<n;i++)
{
System.out.println("Enter Roll No : ");
rno=Integer.parseInt(din.readLine());
System.out.println("Enter Name : ");
nm=din.readLine();
System.out.println("Enter Percentage: ");
per=Integer.parseInt(din.readLine());
18 k=st.executeUpdate("insert into Stud values(" + rno +
",'"+ nm + "'," + per +")");
if(k>0)
{
System.out.println("Record Inserted Successfully..!!");
System.out.println("..............................................");
}
}
break;
case 2:
System.out.print("Enter the Roll no: ");
rno=Integer.parseInt(din.readLine());
System.out.print("Enter the Sname: ");
nm=din.readLine();
k=st.executeUpdate("update Stud set sname='" + nm + "' where rno="+rno);
if(k>0)
{
System.out.println("Record Is Updated..!!");
}
System.out.println("...............................................");
break;
case 3:
System.out.print("Enter the Roll no: ");
rno=Integer.parseInt(din.readLine());
k=st.executeUpdate("delete from Stud where rno=" +rno);
if(k>0)
{
System.out.println("Record Is Deleted..!!");
}
System.out.println(".............................................");
break;
case 4:
System.out.print("Enter the Roll no Whoes search record: ");
rno=Integer.parseInt(din.readLine());
System.out.println(".............................................");
ResultSet rs1=st.executeQuery("select * from Stud where rno=" +rno);
while(rs1.next())
{
System.out.println(rs1.getInt(1) +"\t" +rs1.getString(2)+"\t"+rs1.getInt(3));
}
19 System.out.println(".........................................");
break;
case 5:
ResultSet rs=st.executeQuery("select * from Stud");
while(rs.next())
{
System.out.println(rs.getInt(1) +"\t" +rs.getString(2)+"\t"+rs.getInt(3));
}
System.out.println(".............................................");
break;
case 6:
System.exit(0);
}
}
while(ch!=6);
}
catch(Exception e)
{
System.out.println("Error");
}
}
}

Q.2

JSP File:

<html>
<body>
<%
String name=request.getParameter("username");
java.util.Date d=new java.util.Date();
int hr=d.getHours();
if(hr<12)
{
out.println("Good Morning:"+name);
}
if(hr>12 && hr<16)
{
out.println("Good Afternoon:"+name);
}
if(hr>16)
{
out.println("Good Evening:"+name);
}
%>
</body>
</html>

HTML File:

<html>
<body>
<form action="wishuser.jsp" method="post">
<input type="text" name="username">
<input type="submit">
</form>
</body>
</html>

slip 23

Q.1

import java.util.Scanner;
class VowelsInaString
{
void vowels(String str)
{
char ch;
for(int j=0;j<str.length();j++)
{
ch=str.charAt(j);
if(ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u'||ch=='A'||ch=='E'||ch=='I'||ch=='O'||
ch=='U')
{

System.out.println(ch);
}
}
}
public static void main(String[ ] arg)
{
CharInaString c=new CharInaString();
String s;
Scanner sc=new Scanner(System.in);
System.out.print("Enter a string : ");
s=sc.nextLine();
System.out.println("Vowels in a string are :");
c.vowels(s);
}

Q.2

import java.util.ArrayList;
import java.util.ListIterator;

// Main class
public class Test {
// Main driver method
public static void main(String[] args)
{
// Creating an object of ArrayList class
ArrayList al = new ArrayList();

// Iterating over Arraylist object


for (int i = 0; i < 10; i++)

// Adding elements to the Arraylist object


al.add(i);

// Print and display all elements inside object


// created above
System.out.println(al);

// At beginning ltr(cursor) will point to


// index just before the first element in al
ListIterator ltr = al.listIterator();

// Checking the next element availability


while (ltr.hasNext()) {
// Moving cursor to next element
int i = (Integer)ltr.next();

// Getting even elements one by one


System.out.print(i + " ");

// Changing even numbers to odd and


// adding modified number again in
// iterator
if (i % 2 == 0) {
// Change to odd
i++;
// Set method to change value
ltr.set(i);
// To add
ltr.add(i);
}
}

// Print and display statements


System.out.println();
System.out.println(al);
}
}

slip 24

Q.1

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
/* <APPLET CODE=ScrollingText.class WIDTH=400 HEIGHT=200 > </APPLET> */
public class ScrollingText extends Applet implements Runnable
{
String msg="Welcome to Java Programming Language ....... ";
Thread t=null;
public void init()
{
setBackground(Color.cyan);
setForeground(Color.red);
t=new Thread(this);
t.start();
}
public void run()
{
char ch;
for(; ;)
{
try
{
repaint();
Thread.sleep(400);
ch=msg.charAt(0);
msg=msg.substring(1,msg.length());
msg+=ch;
}
catch(InterruptedException e)
{}
}
}
public void paint(Graphics g)
{
g.drawString(msg,10,10);
}
}

Q.2

login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"


pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login page</title>

</head>
<script type="text/javascript">
var value= "${msg}";/* Is a general representation of an EL expression to get the values of
the objects (parameters, objects, etc.) specified in {} */
if(value!="")
{alert(value);}
/* Used here to receive the error message from the filter */

</script>
<body>
<form action="<%=request.getContextPath()%>/loginServlet" method="post">
User name:<input type="text" name="userName" /> <br />
Password: <input type="password" name="userPwd" /> <br />
<input type="submit" value="Sign in" />
</form>
</body>
</html>

package Servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

doPost(request, response);

public void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
request.setCharacterEncoding("utf-8");

System.out.println(request.toString());
// Receiving parameters
String userName = request.getParameter("userName");

String userPwd = request.getParameter("userPwd");


System.out.println("Full name"+userName+"Password:"+userPwd);
String forward = null;
// Judge whether the login is successful
if (userName.equals("1") && userPwd.equals("2")) {
// The login is successful. Here you can call JDBC to query the user
password from the database to verify the login
System.out.println("Login successfully");
/*response.sendRedirect(request.getContextPath()+"/indexServlet");*/
// Redirection: all variables stored in the previous response are invalid
and enter a new response scope. Times cannot be used

// Create session object


HttpSession session = request.getSession();
// Save user data in session domain object
session.setAttribute("loginName", userName);
// Forward: the variables stored in the previous request will not fail. It is
like putting two pages together and successfully forwarding the login to the personal
interface
forward = "/index.jsp";
RequestDispatcher dis = request.getRequestDispatcher(forward);
dis.forward(request, response);
return;

// Jump to user home page

// response.sendRedirect(request.getContextPath() + "/indexServlet");
} else {
// Login failed, request redirection
String userName1 = request.getParameter("userName");

String userPwd1 = request.getParameter("userPwd");


System.out.println("Full name"+userName1+"Password:"+userPwd1);
forward = "/fail.html";
RequestDispatcher dis = request.getRequestDispatcher(forward);
dis.forward(request, response);
//response.sendRedirect(request.getContextPath() + "/fail.html");
}

slip 25
Q.1

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<form action="Slip29.jsp" method="post">
Name : <input type="text" name="name">

Age : <input type="text" name="age">

<input type="submit" value="Check">


</form>
</body>
</html>

JSP FILE:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<%
String name = request.getParameter("name");
int age = Integer.parseInt(request.getParameter("age"));
if(age >=18)
{
out.println(name + "\nAllowed to vote");
}
else
{
out.println(name + "\nNot allowed to vote");
}
%>

slip 26

Q.1
importjava.sql.*;
class Slip27_1
{
public static void main(String a[])
{
Connection con;
PreparedStatementps;
ResultSetrs;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:dsn");
if(con==null)
{
System.out.println("Connection Failed....");
System.exit(1);
}
System.out.println("Connection Established...");
ps=con.prepareStatement("select * from employee where eid=?");
int id = Integer.parseInt(a[0]);
ps.setInt(1,id);

rs=ps.executeQuery();
System.out.println("eno\t"+"ename\t"+"department\t"+"sal"); while(rs.next())
{
System.out.println("\n"+rs.getInt(1)+"\t"+rs.getString(2)+"\t"+rs.getString(3)+"\t"+rs.ge tInt(4));
}
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}

Q.2

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:

<%@page contentType="text/html" pageEncoding="UTF-8"%>


<!DOCTYPE html>
<html>
<body>
<%! int n,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 %></font>
<%
}
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 %></font>
<%
}
%>
</body>
</html>

slip 27

Q.1

import java.io.*;
import java.sql.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class College extends JFrame implements ActionListener
{
JLabel lblid,lblname,lbladdr,lblyr;
JTextField txtid,txtname,txtaddr,txtyr;
JButton btninsert,btnclear,btnexit;
College()
{
setLayout(null);
lblid=new JLabel("College id");
lblname=new JLabel("College Name");
lbladdr=new JLabel("College Address");
lblyr=new JLabel("Year");
txtid=new JTextField();
txtname=new JTextField();
txtaddr=new JTextField();
txtyr=new JTextField();
btninsert=new JButton("Insert");
btnclear=new JButton("Clear");
btnexit=new JButton("Exit");
lblid.setBounds(20,30,100,20);
lblname.setBounds(20,70,150,30);
lbladdr.setBounds(20,110,150,30);
lblyr.setBounds(20,150,150,30);
txtid.setBounds(120,30,150,30);
txtname.setBounds(120,70,150,30);
14 txtaddr.setBounds(120,110,150,30);
txtyr.setBounds(120,150,150,30);
btninsert.setBounds(10,200,100,50);
btnclear.setBounds(120,200,100,50);
btnexit.setBounds(230,200,100,50);
btninsert.addActionListener(this);
btnclear.addActionListener(this);
btnexit.addActionListener(this);
add(lblid); add(txtid);
add(lblname); add(txtname);
add(lbladdr); add(txtaddr);
add(lblyr); add(txtyr);
add(btninsert);
add(btnclear);
add(btnexit);
setSize(500,400);
}
public void actionPerformed(ActionEvent a)
{
try {
if(a.getSource()==btninsert)
{
int id,yr;
String nm,add;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("Jdbc:Odbc:BCA");
PreparedStatement pst=con.prepareStatement("insert into College
values(?,?,?,?)");
id=Integer.parseInt(txtid.getText());
nm=txtname.getText();
add=txtaddr.getText();
15 yr=Integer.parseInt(txtyr.getText());
pst.setInt(1,id);
pst.setString(2,nm);
pst.setString(3,add);
pst.setInt(4,yr);
pst.executeUpdate();
//int k= JOptionPane.showMessageDialog(null,"Record Inserted Successfully");
con.close();
/*if(k>0){System.out.println("Record Inserted..!!!");}else{System.out.println("Error..!!!");}*/
}
if(a.getSource()==btnclear)
{
txtid.setText("");
txtname.setText("");
txtaddr.setText("");
txtyr.setText("");
}
if(a.getSource()==btnexit)
{
System.exit(0);
}
}
catch(Exception e)
{
System.out.println("Error is :"+e);
}
}
public static void main(String args[])
16 {
new College().show();
}
}

Q.2

import java.util.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
// Get the current session object, create one if necessary
HttpSession session = req.getSession();
out.println("<HTML><HEAD><TITLE>SessionTimer</TITLE></HEAD>");
out.println("<BODY><H1>Session Timer<</H1>");
// Display the previous timeout
out.println("The previous timeout was " +
session.getMaxInactiveInterval());
out.println("<BR>");
// Set the new timeout
session.setMaxInactiveInterval(2*60*60); // two hours
// Display the new timeout
out.println("The newly assigned timeout is " + session.getMaxInactiveInterval());
out.println("</BODY></HTML>");
}
}

xml code

<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"


"http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">
<web-app>
<servlet><servlet-name>MyServletName</servlet-name>
<servlet-class>MyServlet</servlet-class>
</servlet>
<servlet-mapping><servlet-name>MyServletName</servlet-name>
<url-pattern>/index.html</url-pattern>
</servlet-mapping>
</web-app>

build .xml

<project name="MyProject" default="compile" basedir=".">


<property name="sourcedir" value="${basedir}/src"/>
<property name="webdir" value="${basedir}/build"/> <property name="javaSourcedir"
value="${sourcedir}/WEB-INF/classes"/>
<property name="webClassdir" value="${webdir}/WEB-INF/classes"/>
<property name="webClassLib" value="${webdir}/WEB-INF/lib"/>
<property name="compileLibDir" value="${basedir}/lib"/>
<path id="libraries">
<fileset dir="${compileLibDir}">
<include name="*.jar"/>
</fileset>
</path>
<target name="clean">
<delete dir="${webdir}"/>
<mkdir dir="${webClassdir}"/>
</target>
<target name="copy">
<copy todir="${webdir}">
<fileset dir="${sourcedir}">
<exclude name="**/*.java"/>
</fileset>
</copy>
</target>
<target name="compile" depends="clean, copy">
<javac srcdir="${javaSourcedir}"
destdir="${webClassdir}"
classpathref="libraries"/>

<!-- one for deployment, another one for reference -->


<war warfile="demo.war" basedir="${webdir}" webxml="${webdir}/WEB-INF/web.xml">
<exclude name="WEB-INF/web.xml"/>
</war>
<war warfile="../demo.war" basedir="${webdir}" webxml="${webdir}/WEB-INF/web.xml">
<exclude name="WEB-INF/web.xml"/>
</war>
<delete dir="${webdir}"/>
</target>
</project>

slip 28

Q.1

import java.io.*;
import java.lang.*;
import java.util.*;

class GFG {
static String wordReverse(String str)
{
int i = str.length() - 1;
int start, end = i + 1;
String result = "";

while (i >= 0) {
if (str.charAt(i) == ' ') {
start = i + 1;
while (start != end)
result += str.charAt(start++);

result += ' ';

end = i;
}
i--;
}

start = 0;
while (start != end)
result += str.charAt(start++);

return result;
}

// Driver code
public static void main(String[] args)
{
String str = "I AM A GEEK";

System.out.print(wordReverse(str));
}
}

Q.2

import java.io.*;

// Class 1
// Helper class
class ThreadNaming extends Thread {

// Parameterized constructor
ThreadNaming(String name)
{
// Call to constructor of
// the Thread class as super keyword
// refers to parent class
super(name);
}

// run() method for thread


@Override public void run()
{
// Print statement when thread is called inside
// main()
System.out.println("Thread is running.....");
}
}

// Class 2
// Main class
class GFG {

// main driver method


public static void main(String[] args)
{

// Creating two threads


ThreadNaming t1 = new ThreadNaming("geek1");
ThreadNaming t2 = new ThreadNaming("geek2");

// Getting the above created threads names.


System.out.println("Thread 1: " + t1.getName());
System.out.println("Thread 2: " + t2.getName());

// Starting threads using start() method


t1.start();
t2.start();
}
}

slip 29

Q.1

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
}

create table donor(did int, dname char(22),daddr varchar(22));

-- insert into donor VALUES(1,'AAA','zzz');


-- insert into donor VALUES(2,'BBB','yyy');
-- insert into donor VALUES(3,'CCC','xxx');
-- insert into donor VALUES(4,'DDD','www');

SELECT * from donor;

Q.2
import java.io.*;

// Java program to implement


// a Singly Linked List
public class LinkedList {

Node head; // head of list

// Linked list Node.


// Node is a static nested class
// so main() can access it
static class Node {

int data;
Node next;

// Constructor
Node(int d)
{
data = d;
next = null;
}
}

// **************INSERTION**************

// Method to insert a new node


public static LinkedList insert(LinkedList list,
int data)
{
// Create a new node with given data
Node new_node = new Node(data);
new_node.next = null;

// If the Linked List is empty,


// then make the new node as head
if (list.head == null) {
list.head = new_node;
}
else {
// Else traverse till the last node
// and insert the new_node there
Node last = list.head;
while (last.next != null) {
last = last.next;
}
// Insert the new_node at last node
last.next = new_node;
}

// Return the list by head


return list;
}

// **************TRAVERSAL**************

// Method to print the LinkedList.


public static void printList(LinkedList list)
{
Node currNode = list.head;

System.out.print("\nLinkedList: ");

// Traverse through the LinkedList


while (currNode != null) {
// Print the data at current node
System.out.print(currNode.data + " ");

// Go to next node
currNode = currNode.next;
}
System.out.println("\n");
}

// **************DELETION BY KEY**************

// Method to delete a node in the LinkedList by KEY


public static LinkedList deleteByKey(LinkedList list,
int key)
{
// Store head node
Node currNode = list.head, prev = null;

//
// CASE 1:
// If head node itself holds the key to be deleted

if (currNode != null && currNode.data == key) {


list.head = currNode.next; // Changed head

// Display the message


System.out.println(key + " found and deleted");

// Return the updated List


return list;
}

//
// CASE 2:
// If the key is somewhere other than at head
//

// Search for the key to be deleted,


// keep track of the previous node
// as it is needed to change currNode.next
while (currNode != null && currNode.data != key) {
// If currNode does not hold key
// continue to next node
prev = currNode;
currNode = currNode.next;
}

// If the key was present, it should be at currNode


// Therefore the currNode shall not be null
if (currNode != null) {
// Since the key is at currNode
// Unlink currNode from linked list
prev.next = currNode.next;

// Display the message


System.out.println(key + " found and deleted");
}

//
// CASE 3: The key is not present
//

// If key was not present in linked list


// currNode should be null
if (currNode == null) {
// Display the message
System.out.println(key + " not found");
}

// return the List


return list;
}

// **************DELETION AT A POSITION**************

// Method to delete a node in the LinkedList by POSITION


public static LinkedList
deleteAtPosition(LinkedList list, int index)
{
// Store head node
Node currNode = list.head, prev = null;

//
// CASE 1:
// If index is 0, then head node itself is to be
// deleted

if (index == 0 && currNode != null) {


list.head = currNode.next; // Changed head

// Display the message


System.out.println(
index + " position element deleted");

// Return the updated List


return list;
}

//
// CASE 2:
// If the index is greater than 0 but less than the
// size of LinkedList
//
// The counter
int counter = 0;

// Count for the index to be deleted,


// keep track of the previous node
// as it is needed to change currNode.next
while (currNode != null) {

if (counter == index) {
// Since the currNode is the required
// position Unlink currNode from linked list
prev.next = currNode.next;

// Display the message


System.out.println(
index + " position element deleted");
break;
}
else {
// If current position is not the index
// continue to next node
prev = currNode;
currNode = currNode.next;
counter++;
}
}

// If the position element was found, it should be


// at currNode Therefore the currNode shall not be
// null
//
// CASE 3: The index is greater than the size of the
// LinkedList
//
// In this case, the currNode should be null
if (currNode == null) {
// Display the message
System.out.println(
index + " position element not found");
}

// return the List


return list;
}

// **************MAIN METHOD**************

// method to create a Singly linked list with n nodes


public static void main(String[] args)
{
/* Start with the empty list. */
LinkedList list = new LinkedList();

//
// ******INSERTION******
//

// Insert the values


list = insert(list, 1);
list = insert(list, 2);
list = insert(list, 3);
list = insert(list, 4);
list = insert(list, 5);
list = insert(list, 6);
list = insert(list, 7);
list = insert(list, 8);

// Print the LinkedList


printList(list);
//
// ******DELETION BY KEY******
//

// Delete node with value 1


// In this case the key is ***at head***
deleteByKey(list, 1);

// Print the LinkedList


printList(list);

// Delete node with value 4


// In this case the key is present ***in the
// middle***
deleteByKey(list, 4);

// Print the LinkedList


printList(list);

// Delete node with value 10


// In this case the key is ***not present***
deleteByKey(list, 10);

// Print the LinkedList


printList(list);

//
// ******DELETION AT POSITION******
//

// Delete node at position 0


// In this case the key is ***at head***
deleteAtPosition(list, 0);

// Print the LinkedList


printList(list);

// Delete node at position 2


// In this case the key is present ***in the
// middle***
deleteAtPosition(list, 2);

// Print the LinkedList


printList(list);

// Delete node at position 10


// In this case the key is ***not present***
deleteAtPosition(list, 10);
// Print the LinkedList
printList(list);
}
}

slip 30

Q.1

TestSynchronization1.java

class Table{
void printTable(int n){//method not synchronized
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}

}
}

class MyThread1 extends Thread{


Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5);
}

}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}
class TestSynchronization1{
public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}

Q.2

import java.util.Scanner;

class Teacher{

public String Tid , Tname , Designation , Subject;

public int salary;

Teacher(int s , String id , String name , String desig , String sub){

salary = s;

Tid = id;

Tname = name;

Designation = desig;

Subject = sub;

public String toString(){

return "Name: " + Tname + "\n" + "Designation: " + Designation + "\n" + "Subject: " +
Subject + "\nTeacher id: " + Tid + "\nSalary: " + salary;

public class Main

{
public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.print("Enter the number of teachers:");

int n = sc.nextInt();

Teacher[] teachers = new Teacher[n];

for(int i = 0; i < teachers.length; i++){

System.out.print("Enter the name of the teacher " + (i+1) + ":");

String name = sc.next();

System.out.print("Enter the teacher id for " + name + ":");

String id = sc.next();

System.out.print("Enter the Designation of " + name + ":");

String Designation = sc.next();

System.out.print("Enter the salary for " + name + ":");

int salary = sc.nextInt();

System.out.print("Enter the Subject which " + name + " teaches:");

String sub = sc.next();

Teacher t = new Teacher(salary , id , name , Designation , sub);

teachers[i] = t;

System.out.println();

System.out.println("\n---TEACHERS DETAILS---");

for(int i = 0; i < teachers.length; i++){

System.out.println("Details of Teacher " + (i+1));

System.out.println(teachers[i]);
System.out.println();

You might also like