Java University Sloved Slips
Java University Sloved Slips
1
Create an abstract class shape. Derive three classes sphere, cone and
cylinder from it. Calculate area and volume of all (use method overriding)
[30]
}
class Cone extends Shape
{
Cone(double a, double b)
{
super(a,b);
}
double area()
{
System.out.print("\nArea of Cone:");
return ((3.14*radius)*(radius+ht));
}
double volume()
{
System.out.print("\nVolume of Cone:");
return ((3.14*radius*radius*ht)/3);
}
}
s = new Cone(2,4);
System.out.print(s.area());
System.out.print(s.volume());
System.out.println();
s = new Cylinder(3,6);
System.out.print(s.area());
System.out.print(s.volume());
System.out.println("\n");
}
}
slip 1.2
Design an HTML page containing 4 option buttons (Painting, Drawing,
Singing and swimming) and 2 buttons reset and submit. When the user
clicks submit, the server responds by adding a cookie containing the
selected hobby and sends a message back to the client. Program should not
allow duplicate cookies to be written. [30]
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Choices extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest req,
HttpServletResponse res)
throws ServletException,IOException
{
res.setContentType("text/html");
PrintWriter pw = res.getWriter();
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
JLabel l;
JTextField t;
JPanel p;
StringBuffer ss=new StringBuffer();
int n;
int arr[]=new int [20];
Slip2_1()
{
p=new JPanel();
mb=new JMenuBar();
m1=new JMenu("Operation");
m2=new JMenu("Sort");
l=new JLabel("Numbers");
t=new JTextField(20);
String str[]= {"Load", "Save", "Exit", "Ascending",
"Descending" };
m=new JMenuItem[str.length];
for(int i=0;i<str.length;i++)
{
m[i]=new JMenuItem(str[i]);
m[i].addActionListener(this);
}
p.add(l);
p.add(t);
mb.add(m1);
mb.add(m2);
m1.add(m[0]);
m1.add(m[1]);
m1.addSeparator();
m1.add(m[2]);
m2.add(m[3]);
m2.add(m[4]);
setLayout(new BorderLayout());
add(mb,BorderLayout.NORTH);
add(p,BorderLayout.CENTER);
setSize(300,150);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
void sortasc()
{
for(int i=0;i<n;i++)
for(int j=0;j<n-1;j++)
{
if(arr[j]>arr[j+1])
int t=arr[j];
arr[j]=arr[j+1];
arr[j+1]=t;
}
}
StringBuffer s5=new StringBuffer();
for(int i=0;i<n;i++)
{
s5.append(new Integer(arr[i]).toString());
s5.append(" ");
}
t.setText(new String(s5));
}
void sortdesc()
{
for(int i=0;i<n;i++)
for(int j=0;j<n-1;j++)
{
if(arr[j]<arr[j+1])
{
int t=arr[j];
arr[j]=arr[j+1];
arr[j+1]=t;
}
}
StringBuffer s5=new StringBuffer();
for(int i=0;i<n;i++)
{
s5.append(new Integer(arr[i]).toString());
s5.append(" ");
}
t.setText(new String(s5));
}
int i=0;
try
{
BufferedReader r=new BufferedReader(new
FileReader("new.txt"));
String s1=r.readLine();
while(s1!=null)
ss.append(s1);
ss.append(" ");
arr[i]=Integer.parseInt(s1);
n=++i;
s1=r.readLine();
catch(Exception eee)
{ }
t.setText(new String(ss));
}
}
else if(s.equals("Save"))
{
char ch;
String sss = t.getText();
try
{
FileOutputStream br1 = new FileOutputStream
("new.txt");
for(int i=0;i<sss.length();i++)
ch=sss.charAt(i);
br1.write('\n');
else
br1.write(ch);
br1.close();}
catch(Exception eee)
{ }
}
else
if(s.equals("Ascending"))
{
sortasc();
}
else
if(s.equals("Descending"))
{
sortdesc();
}
}
public static void main(String arg[])
{
Slip2_1 c =new
Slip2_1();
}
}
slip 2.2
client.java
import java.net.*;
import java.io.*;
import java.util.*;
System.out.println("From Server:"+br.readLine());
}
}
server.java
import java.net.*;
import java.io.*;
import java.util.*;
while(true)
{
Socket s = ss.accept();
ps.println(new Date());
s.close();
}
}
}
slip 3.1
class MyDate
{
public static void main(String[]args)
{
try
{
if(args.length<3)
throw new NullPointerException();
else
{
int dd=Integer.parseInt(args[0]);
int mm=Integer.parseInt(args[1]);
int yy=Integer.parseInt(args[2]);
case 2:
if(!leap && dd>28)
throw new InvalidDateException();
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
if(dd < 1||dd>30)
throw new InvalidDateException();
case 11:
case 12:
if(dd < 1||dd >31)
throw new InvalidDateException();
}
System.out.println("Valid input");
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
/******************************Output*****************
************************
[ty14@bcs92 ass4]$ java MyDate
java.lang.NullPointerException
[ty14@bcs92 ass4]$ java MyDate 23 5 2000
Valid input
[ty14@bcs92 ass4]$ java MyDate 23 15 2000
Invalid Month given
[ty14@bcs92 ass4]$ java MyDate 30 2 2000
Invalid Date given
*/
slip 3.2
HTML FILE:
<HTML>
<BODY>
<form method=get action=”Slip3.java”>
Enter Bill Number : <input type=”text”
billnum=”billnum”>
<input type=SUBMIT>
</BODY>
</HTML>
JAVA FILE:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class Slip4 extends HttpServlet
{
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws IOException,
ServletException
{
response.setContentType(“text/html”);
PrintWriter out= res.getWriter();
String
billnum=req.getParmeter(“billnum”),msg;
int billno=Integer.parseInt(billnum);
Connection con=null;
Statement st=null;
ResultSet rs=null,rs1=null;
out.println(“<HTML>”);
out.println(“<BODY>”);
try
{
Class.forName(“org.postgresql.Driver”);
con=DriverManager.getConnection(“jdbc:postgresql://192
.168.100.254/Bill”,”oracle”,”oracle”);
if(con==null)
st=con.createStatement();
if(rs==null || rs1==null)
rs.next();
rs1.next();
int i=1;
System.out.println(“Bill Number:”+rs.getInt(1)+”
\t\t\tBill Date:”+rs.getString(3)+”\n”+”Customer
Name”+rs.getString(2)+”\n”);
int netB=0,sumT=0;
while(rs1.next())
sumT=rs1.getInt(2)*rs1.getInt(3);
System.out.println(i+”\t\t\t”+rs1.getString(1)+”\t\t”+
rs1.getInt(2)+”\t\t”+ rs1.getInt(3)+”\t\t”+sumT+”\n”);
netB=netB+sumT;
}
out.println(“\t\t\t\t\t\t\t\t\t\tNet Bill : ”+ netB);
}
}
catch(Exception e) { }
out.println(“</BODY>”);
out.println(“</HTML>”);
}
}
slip 4.1
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Slip4 extends HttpServlet
{
public void doGet(HttpServletRequest
request, HttpServletResponse response) throws
IOException, ServletException
{
response.setContentType(“text/html”);
PrintWriter out= res.getWriter();
out.println(“<HTML>”);
out.println(“<BODY>”);
out.println(“Information Of Client: ”);
out.println(“IP Address : ” + req.getRemoteAddr() +
”\n”);
out.println(“Name : ” + req.getRemoteHost() + ”\n”);
out.println(“Information Of Server: ”);
out.println(“Name : ” + req.getServerName() + ”\n”);
out.println(“Port : ” + req.getServerPort() + ”\n”);
out.println(“</BODY>”);
out.println(“</HTML>”);
}
}
slip 5.1
/*Slip 5_1. Define a class saving account (acno, name,
balance) .define appropriate and operation withdraw(),
deposit(), and viewbalance(). The minimum balance must
be 500. Create an object and perform operation. Raise
user defined InsufficientFundException when balance is
not sufficient for withdraw operation.
*/
import java.util.*;
class InsufficientFund extends Exception
{
InsufficientFund(String x)
{
super(x);
}
}
class Bank
{
int ano;
String name;
double bal;
Bank(int ano,String name,double bal)
{
this.ano=ano;
this.name=name;
this.bal=bal;
}
public void viewbal()
{
System.out.println("Balance is:"+bal);
}
public void deposit(double amt)
{
bal=bal+amt;
System.out.println("Total Balance is:"+bal);
}
public void withdraw(double amt)
{
double temp;
temp=bal-amt;
try
{
if(temp<500)
throw new InsufficientFund("Balance must be
500!!!");
else
bal=temp;
}
catch(Exception e){System.out.println(e);}
}
public static void main(String g[])
{
Scanner s1=new Scanner(System.in);
System.out.println("Enter
AccountNo,Name,Bal:");
int x=s1.nextInt();
String y=s1.next();
double z=s1.nextDouble();
Bank b1=new Bank(x,y,z);
int ch;
do
{
System.out.println("1:viewbal\n2:deposit\n3:withdr
aw\n4:exit");
System.out.println("Enter choice:");
ch=s1.nextInt();
switch(ch)
{
case 1: b1.viewbal();
break;
case 2:System.out.println("Enter amount to
deposit:");
double d=s1.nextDouble();
b1.deposit(d);
break;
case 3:System.out.println("Enter amount to
withdraw:");
double j=s1.nextDouble();
try
{
b1.withdraw(j);
}
catch(Exception e1){}
break;
}
}
while(ch!=4);
}
}
slip 5.2
/* Define a thread to move numbers inside a panel
vertically */
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.imageio.*;
import javax.swing.*;
import javax.swing.event.*;
import java.util.*;
class Thr extends Thread
{
boolean up=false;
bass2_2a parent;
int top,left;
Color c;
Thr(int t,int l,Color cr,bass2_2a p)
{
top=l;
if(top > 170)
top=170-t/8;
left=t;
c=cr;
parent=p;
}
parent.p.repaint();
}
}catch(Exception e){}
}
}
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Conversion extends JFrame
{
JLabel lblDec,lblBin,lblOct,lblHex;
JTextField txtDec,txtBin,txtOct,txtHex;
JButton btnCalc,btnClear;
Conversion()
{
lblDec = new JLabel("Decimal Number:");
lblBin = new JLabel("Binary Number:");
lblOct = new JLabel("Octal Number:");
lblHex = new JLabel("Hexadecimal Number:");
txtDec = new JTextField();
txtBin = new JTextField();
txtOct = new JTextField();
txtHex = new JTextField();
btnCalc = new JButton("Calculate");
btnClear = new JButton("Clear");
setTitle("Conversion");
setSize(300,250);
setLayout(new GridLayout(5,2));
add(lblDec);
add(txtDec);
add(lblBin);
add(txtBin);
add(lblOct);
add(txtOct);
add(lblHex);
add(txtHex);
add(btnCalc);
add(btnClear);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
btnCalc.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
int n = Integer.parseInt(
txtDec.getText());
txtBin.setText(
Integer.toBinaryString(n));
txtOct.setText(
Integer.toOctalString(n));
txtHex.setText(
Integer.toHexString(n));
}
});
btnClear.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
txtDec.setText("");
txtBin.setText("");
txtOct.setText("");
txtHex.setText("");
txtDec.requestFocus();
}
});
}
public static void main(String args[])
{
new Conversion();
}
}
slip 6.2
Writ a server program which echoes message sent by the client. The
Process continues till the client types “END” [30].
Echoclient.java
import java.io.*;
import java.net.*;
public class EchoClient {
if(message.equals("END"))
done=true;
}
s.close();
Echoserver.java
import java.net.*;
import java.io.*;
public class EchoServer
{
public static void main(String[] args) throws
Exception
{
ServerSocket ss = new ServerSocket(123);
Socket s = ss.accept();
InputStream is=s.getInputStream();
DataInputStream dis = new DataInputStream(is);
OutputStream os=s.getOutputStream();
DataOutputStream dos=new DataOutputStream(os);
boolean done=false;
while(!done)
{
String message=dis.readUTF();
dos.writeUTF(message.toUpperCase());
if((message.toUpperCase()).equals("END"))
done=true;
}
s.close();
}
slip 7.1
/*Slip 7_1. Create a package series having two different
classes to print the following series.
a.Prime number
b.Squares of numbers
Write a program to generate n terms of the above series.
*/
import Series.Prime;
import Series.Square;
import java.io.*;
class Slip7_1
{
public static void main(String a[]) throws IOException
{
BufferedReader br =new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter no :");
int no = Integer.parseInt(br.readLine());
Prime p = new Prime();
System.out.println("Prime no upto given nos are : ");
p.prime_range(no);
Square s = new Square();
System.out.println("Sqaure upto given nos are : ");
s.square_range(no);
}
}
Prime.java
package Series;
public class Prime
{
public void prime_range(int no)
{
for(int i=1;i<=no;i++)
{
int flag=0;
for(int j=2;j<=i/2;j++)
{
if(i%j==0)
{
flag=1;
break;
}
}
if(flag==0)
System.out.println(i+" ");
}
}
Square.java
package Series;
public class Square
{
public void square_range(int no)
{
for(int i=1;i<=no;i++)
{
System.out.println(i+" = "+(i*i));
}
}
}
slip 7.2
Create a table Student with the fields roll number, name, percentage using
Postgresql. Write a menu driven program (Command line interface) to
perform the following operations on student table. [30]
a) Insert
b) Modify
c) Delete
d) Search
e) View All
f) Exit
Student.java
import java.sql.*;
import java.io.*;
public class StudentMenu
{
public static void main(String[] args) throws
Exception
{
Connection con;
ResultSet rs;
Statement stmt;
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhos
t/Vaishali","root","");
do
{
System.out.println("\n1.Insert\n2.Modify\n3.Delete\n4.
Search\n5.View all\n6.Exit");
System.out.println("Enter the choice");
int ch=Integer.parseInt(br.readLine());
switch(ch)
{
case 1:
System.out.println("Enter the Rollno");
int roll=Integer.parseInt(br.readLine());
System.out.println("Enter the name");
String n=br.readLine();
System.out.println("Enter the percentage");
float per=Float.parseFloat(br.readLine());
stmt=con.createStatement();
stmt.executeUpdate("insert into student
values("+roll+",'"+n+"',"+per+")");
break;
case 2:
System.out.println("Enter the roll no for
update record");
roll=Integer.parseInt(br.readLine());
System.out.println("Enter the name");
n=br.readLine();
System.out.println("Enter the percentage");
per=Float.parseFloat(br.readLine());
stmt=con.createStatement();
stmt.executeUpdate("update student set
name='"+n+"',percentage="+per+" where rno="+roll);
break;
case 3:
System.out.println("Enter the roll no for
delete record");
int no=Integer.parseInt(br.readLine());
stmt=con.createStatement();
stmt.executeUpdate("delete from student
where rno="+no);
break;
case 4:
System.out.println("Enter the roll no for
search");
no=Integer.parseInt(br.readLine());
stmt=con.createStatement();
rs=stmt.executeQuery("select * from student
where rno="+no);
while(rs.next())
{
System.out.println("Roll
no="+rs.getInt(1)+"\tname="+rs.getString(2)+"\tpercent
age="+rs.getFloat(3));
}
break;
case 5:
stmt=con.createStatement();
rs=stmt.executeQuery("select * from
student");
while(rs.next())
{
System.out.println("Roll
no="+rs.getInt(1)+"\tname="+rs.getString(2)+"\tpercent
age="+rs.getFloat(3));
}
break;
case 6:
System.exit(0);
break;
}
}while(true);
}
slip 8.1
/*
Slip 8_1. Write a program to create the following GUI
and apply the change to text in the TextField.
*/
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
p2.setLayout(new FlowLayout());
p2.add(t);
bold.addItemListener(this);
italic.addItemListener(this);
fontcb.addItemListener(this);
sizecb.addItemListener(this);
setLayout(new BorderLayout());
add(p1,BorderLayout.NORTH);
add(p2,BorderLayout.CENTER);
setSize(200, 200);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void itemStateChanged(ItemEvent ie)
{
String f =
(String)fontcb.getSelectedItem();
System.out.println("font = "+f);
t.setFont(new Font(f,Font.BOLD,10));
String no
=(String)sizecb.getSelectedItem();
int num=Integer.parseInt(no);
if(bold.isSelected())
{
t.setFont(new Font(f,Font.BOLD,num));
}
if(italic.isSelected())
{
t.setFont(new
Font(f,Font.ITALIC,num));
}
}
public static void main(String args[])
{
new Slip8_1();
}
}
slip 8.2
Write a servlet which counts how many times a user has
visited a web page. If the 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 cookies)
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
int val=Integer.parseInt(c[0].getValue())+1;
c[0].setValue(Integer.toString(val));
response.addCookie(c[0]);
out.println("Hit Count:<b>"+val+"</b>");
}
}}
slip 9.1
MouseApplet.java
package mouse;
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code="MouseApplet.class" width=500 height=500>
</applet>
*/
public class MouseApplet extends Applet implements
MouseMotionListener, MouseListener, KeyListener
{
/**
*
*/
private static final long serialVersionUID = 1L;
String s="";
public void init()
{
addMouseListener(this);
addKeyListener(this);
addMouseMotionListener(this);
}
repaint();
}
public void mousePressed(MouseEvent me)
{
if(me.getButton()==MouseEvent.BUTTON3)
{
s="Right Button is pressed";
}
if(me.getButton()==MouseEvent.BUTTON2)
{
s="Centre Button is pressed";
}
if(me.getButton()==MouseEvent.BUTTON1)
{
s="Left Button is pressed";
}
repaint();
}
public void mouseReleased(MouseEvent me)
{
s="Mouse Button is released";
repaint();
}
public void mouseEntered(MouseEvent me)
{
s="Mouse Button is entered";
repaint();
}
public void mouseExited(MouseEvent me)
{
s="Mouse Button is exited";
repaint();
}
public void mouseDragged(MouseEvent me)
{
int x=me.getX();
int y=me.getY();
slip 9.2
Write a program which sends the name of text file from
the client to server and display the contents of that
file on the client machine. If the file does not exists
display proper error msg.
/* server_Slip9_2 */
import java.io.*;
import java.net.*;
class Slip9_Server
{
public static void main(String a[]) throws
Exception
{
ServerSocket ss = new
ServerSocket(1000);
System.out.println("Server is
waiting for client : ");
Socket s =ss.accept();
System.out.println("Client is
connected");
DataInputStream dis=new
DataInputStream(s.getInputStream() );
DataOutputStream dos=new
DataOutputStream(s.getOutputStream());
System.out.println("file is exists");
FileInputStream fin = new FileInputStream(fname);
int ch;
String msg = "";
while((ch=fin.read())!=-1)
{
msg=msg+(char)ch;
}
dos.writeUTF(msg);
}
else
dos.writeUTF("0");
}
}
/* client_Slip9_2 */
import java.io.*;
import java.net.*;
class Slip9_Client
{
public static void main(String a[]) throws
Exception
{
Socket s = new
Socket("localhost",1000);
System.out.println("client is
connected : ");
DataInputStream dis=new
DataInputStream(s.getInputStream());
DataOutputStream dos=new
DataOutputStream(s.getOutputStream());
BufferedReader br = new
BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter file
name : ");
String fname = br.readLine();
dos.writeUTF(fname);
String msg =
(String)dis.readUTF();
if(msg.equals("0"))
System.out.println(msg);
}}}
slip 10.1
1. Write a program to implement a simple arithmetic calculator. Perform
appropriate validations. [30]
Calculator.java
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public Calculator(String s)
{
super(s);
p1=new JPanel();
p2=new JPanel();
t1=new JTextField(20);
b1=new JButton("Reset");
String str[]={"1","2","3","+","4","5","6","-
","7","8","9","*","0",".","=","/"};
b=new JButton[str.length];
for(int i=0;i<str.length;i++)
b[i]=new JButton(str[i]);
p1.setLayout(new BorderLayout());
p1.add(t1,BorderLayout.NORTH);
p1.add(b1,BorderLayout.EAST);
p2.setLayout(new GridLayout(4,4));
b1.addActionListener(this);
for(int i=0;i<b.length;i++)
{
p2.add(b[i]);
b[i].addActionListener(this);
}
setLayout(new BorderLayout());
add(p1,BorderLayout.NORTH);
add(p2,BorderLayout.CENTER);
}
}
for(int i=0;i<b.length;i++)
if(e.getSource()==b[i])
{
String s=b[i].getActionCommand();
if(s.equals("+")||s.equals("-
")||s.equals("*")||s.equals("/"))
{
ch=s.charAt(0);
n1=Double.parseDouble(new
String(s1));
s1.replace(0,s1.length()," ");
}
else if(s.equals("."))
{
s1.append(".");
String s22=new String(s1);
t1.setText(s22);
}
else if(s.equals("="))
{
double res=0;
n2=Double.parseDouble(new
String(s1));
if(ch == '+')
res=n1+n2;
else if(ch == '-')
res=n1-n2;
else if(ch == '*')
res=n1*n2;
else if(ch == '/')
res=n1/n2;
t1.setText(new
Double(res).toString());
s1.replace(0,s1.length()," ");
n1=res;
res=0;ch=' ';
}
else
{
for(int j=0;j<=b.length;j++)
if(s.equals(new
Integer(j).toString()))
{
s1.append(new
Integer(j).toString());
String s22=new String(s1);
t1.setText(s22);
}
}
}
}
public static void main(String arg[])
{
Calculator c =new Calculator("My Calculator");
c.setSize(300,300);
c.setVisible(true);
c.setLocation(500,200);
c.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
slip 10.2
import java.io.*;
import java.net.*;
class Slip10_Server
{
public static void main(String a[]) throws Exception
{
ServerSocket ss = new ServerSocket(1000);
System.out.println("Server is waiting for client : ");
Socket s =ss.accept();
System.out.println("Client is connected");
DataInputStream dis=new
DataInputStream(s.getInputStream());
DataOutputStream dos=new
DataOutputStream(s.getOutputStream());
while(true)
{
String fname =(String)dis.readUTF();
if(fname.equals("End"))
{ break;
}
File f = new File(fname);
if(f.exists())
{
dos.writeUTF("1");
}
else
dos.writeUTF("0");
}
}
}
/* Client_Slip10_2 */
import java.io.*;
import java.net.*;
class Slip_Client
{
public static void main(String a[]) throws
Exception
{
Socket s = new
Socket("localhost",1000);
System.out.println("client is
connected : ");
DataInputStream dis=new
DataInputStream(s.getInputStream());
DataOutputStream dos=new
DataOutputStream(s.getOutputStream());
BufferedReader br = new
BufferedReader(new InputStreamReader(System.in));
while(true)
{
dos.writeUTF(fname);
if(fname.equals("End"))
{
break;
}
String msg = (String)dis.readUTF();
if(msg.equals("0"))
System.out.println("File Present");
//System.out.println(msg);
}
}
}
}
slip 11.1
import java.io.*;
class Slip11_1
{
public static void main(String args[]) throws Exception
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
File f=new File(args[0]);
if(f.isFile())
{
System.out.println("This is a File");
System.out.println("Name: "+f.getName()+
"\nPath: "+f.getPath()+
"\nParent: "+f.getParent()+
"\nSize: "+f.length()+
"\nCanRead: "+f.canRead()+
"\nCanWrite: "+f.canWrite());
}
else
{
if(f.isDirectory())
{
System.out.println("This is a Directory");
String names[]=f.list();
int cnt=0;
for(String s:names)
{
File f1=new File(f,s);
System.out.println(s);
if(f1.isFile())
{
cnt++;
}
}
slip 11.2
package setA3;
import java.io.*;
import java.lang.String.*;
class Mythread extends Thread
{
String msg="";
int n;
Mythread(String msg,int n)
{
this.msg=msg;
this.n=n;
}
public void run()
{
try
{ for(int i=1;i<=n;i++)
{
System.out.println(msg+" "+i);
}
}
catch(Exception e){}
}
}
slip 12.1
/*
Slip 12_1. Create the following GUI screen using
appropriate layout manager. Accept the name, class,
hobbies from the user and display the selected options
in a text box.
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
Slip12_1()
{
b1=new ButtonGroup();
p1=new JPanel();
p2=new JPanel();
b=new JButton("Clear");
b.addActionListener(this);
r1=new JRadioButton("FY");
r2=new JRadioButton("SY");
r3=new JRadioButton("TY");
b1.add(r1);
b1.add(r2);
b1.add(r3);
r1.addActionListener(this);
r2.addActionListener(this);
r3.addActionListener(this);
c1=new JCheckBox("Music");
c2=new JCheckBox("Dance");
c3=new JCheckBox("Sports");
c1.addActionListener(this);
c2.addActionListener(this);
c3.addActionListener(this);
t2=new JTextField(30);
p1.setLayout(new GridLayout(5,2));
p1.add(l1);p1.add(t1);
p1.add(l2);p1.add(l3);
p1.add(r1);p1.add(c1);
p1.add(r2); p1.add(c2);
p1.add(r3);p1.add(c3);
p2.setLayout(new FlowLayout());
p2.add(b);
p2.add(t2);
setLayout(new BorderLayout());
add(p1,BorderLayout.NORTH);
add(p2,BorderLayout.EAST);
setSize(400,200);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
if(e.getSource()==r1)
cnt++;
if(cnt==1)
String s =t1.getText();
s1.append("Name = ");
s1.append(s);
else if(e.getSource()==r2)
cnt++;
if(cnt==1)
{
String s =t1.getText();
s1.append("Name = ");
s1.append(s);
else if(e.getSource()==r3)
cnt++;
if(cnt==1)
String s =t1.getText();
s1.append("Name = ");
s1.append(s);
}
else if(e.getSource()==c1)
else if(e.getSource()==c2)
else if(e.getSource()==c3)
t2.setText(new String(s1));
// t2.setText(s2);
if(e.getSource()==b)
t2.setText(" ");
t1.setText(" ");
}}
slip 12.2
Write a program to calculate the sum and the average of
an array of 1000 integers (generate randomly) using 10
threads. Each thread calculates the sum of 100 integers.
Use these values to calculate average. [use join method]
import java.util.*;
class thread implements Runnable
{
Thread t;
int i,no,sum;
int a[]=new int[1000];
thread(String s,int n)
{
Random rs = new Random();
t=new Thread(this,s);
no=n;
int j=0;
for(i=1;i<=1000;i++)
{
a[j]=rs.nextInt()%100;;
j++;
}
t.start();
}
public void run() {
for(i=0;i<100;i++)
{
sum=sum+a[no];
no++;
}
System.out.println("Sum = "+sum);
System.out.println("Avg ="+sum/100);
}
}
public class Slip12_2
{
public static void main(String[] arg) throws
InterruptedException
{
thread t1=new thread("g",1);
t1.t.join();
thread t2=new thread("r",100);
t2.t.join();
thread t3=new thread("s",200);
t3.t.join();
thread t4=new thread("t",300);
t4.t.join();
thread t5=new thread("p",400);
t5.t.join();
thread t6=new thread("p",500);
t5.t.join();
thread t7=new thread("p",600);
t5.t.join();
thread t8=new thread("p",700);
t5.t.join();
thread t9=new thread("p",800);
t5.t.join();
thread t10=new thread("p",900);
t5.t.join();
}
}
slip 13.1
import java.io.*;
class FileDemo
{
public static void main(String args[]) throws Exception
{
BufferedReader br=(new BufferedReader(new
InputStreamReader(System.in)));
File f=new File(args[0]);
if(f.isFile())
{
System.out.println("This is a File");
System.out.println("Name: "+f.getName()+
"\nPath: "+f.getPath()+
"\nParent: "+f.getParent()+
"\nSize: "+f.length()+
"\nCanRead: "+f.canRead()+
"\nCanWrite: "+f.canWrite());
}
else
{
if(f.isDirectory())
{
System.out.println("This is a Directory");
String names[]=f.list();
int cnt=0;
for(String s:names)
{
File f1=new File(f,s);
System.out.println(s);
if(f1.isFile())
{
cnt++;
if(s.endsWith(".txt"))
{
System.out.println("Delete y/n: ");
String ch=br.readLine();
if(ch.charAt(0)=='Y' || ch.charAt(0)=='y')
f1.delete();
}
}
}
//cnt++;
System.out.println("Total Files & Directories are
: "+cnt);
}
}
}
}
slip 13.2
Create table student with fields roll
number,name,percentage using postgresql. Insert values
in the tables. Display all the details of the student
table in the tabular format on the screen(using swing).
import java.sql.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
JTable t;
JScrollPane js;
Statement stmt ;
ResultSet rs ;
ResultSetMetaData rsmd ;
int columns;
Vector columnNames = new Vector();
Vector data = new Vector();
Slip13_2()
{
t1 = new JTextField(20);
t2 = new JTextField(20);
t3 = new JTextField(20);
b1 = new JButton("Save");
b2 = new JButton("Display");
b3 = new JButton("Clear");
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
p=new JPanel();
p1=new JPanel();
p.add(l1);
p.add(t1);
p.add(l2);
p.add(t2);
p.add(l3);
p.add(t3);
p.add(b1);
p.add(b2);
p.add(b3);
add(p);
setLayout(new GridLayout(2,1));
setSize(600,800);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Class.forName(“org.postgresql.Driver”);
con=DriverManager.getConnection(“jdbc:postgresql://192
.168.100.254/Bill”,”oracle”,”oracle”);
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,"Record insered
...");
}
else
}//end of try
catch(Exception ex)
{
System.out.println(ex);
//ex.printStackTrace();
}
}//end of if
else
if((JButton)b2==e.getSource())
{
try
{
Class.forName(“org.postgresql.Driver”);
con=DriverManager.getConnection(“jdbc:postgresql://192
.168.100.254/Bill”,”oracle”,”oracle”);
System.out.println("Connected");
stmt=con.createStatement();
rs = stmt.executeQuery("select * from stud");
rsmd = rs.getMetaData();
columns = rsmd.getColumnCount();
columnNames.addElement(rsmd.getColumnName(i));
}
//Get row data
while(rs.next())
{
row.addElement(rs.getObject(i));
data.addElement(row);
}
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();
}
}
import java.io.*;
import java.util.*;
class phone
{
String name,phno;
phone (String nm,String ph)
{
name = nm;
phno=ph;
}
if(arr[i].name.equals(s))
{
System.out.println(arr[i].toString());
return;
}
}
System.out.println("No Records Found");
}
}
class Slip14_1
{
public static void main (String args[]) throws
IOException
{
String s, space = " ";
int i;
rf.writeBytes(s);
}
rf.close ();
RandomAccessFile rf1 = new RandomAccessFile (f, "r");
do
{
ch=Integer.parseInt(b.readLine());
switch (ch)
{
case 1:
phone.search (p,n);
break;
case 2:
rf.writeBytes(s1);
rf.close();
s = rf1.readLine ();
for(i=0;i<n;i++)
System.out.println(p[i].toString());
System.out.println(p1.toString());
break;
case 3 :System.exit(0);
}
}while(ch!=3);
}
}
slip 14.2
Construct a linked list containing names of colors: red, blue, yellow and
orange. Then extend your program to do the following:
i. Display the contents of the List using an Iterator;
ii. Display the contents of the List in reverse order using an Iterator
iii. Create another list containing pink and green. Insert the elements of
this list between blue and yellow.
import java.util.*;
import java.io.*;
void displayIterator()
{
int j = 1;
x = l.iterator() ;
while(li.hasNext())
li.next();
System.out.println("Display Reverse list Using
ListIterator : ") ;
while(li.hasPrevious())
{
System.out.println(j++ + " : "+li.previous()) ;
}
}
void NewList()
{
int j = 1;
y = l2.iterator();
System.out.println("Dispaly List 2 Using Iterator : ")
;
while(y.hasNext())
{
System.out.println(j++ + " : "+y.next()) ;
}
l.addAll(2,l2);
}
qty=Integer.parseInt(q);
price=Double.parseDouble(p);
total=qty*price;
}
if(arr[i].name.equals(s))
{
System.out.println(arr[i].toString());return;
}
}
System.out.println("No Records Found");
}
for(int i=0;i<n;i++)
{
c=i;
}
}
System.out.println(arr[c].toString());
}
}
class Slip15_1
{
public static void main(String[] args)throws IOException
{
String s,space=" ";
int ch,i;
BufferedReader b=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter
Records:\n<id><name><price><qty>:" );
for( i=0;i<n;i++)
{
s=b.readLine()+"\n";
rf.writeBytes(s);
}
rf.close();
s=rf1.readLine();
it[i]=new item(id,pname,price,qty);
do {
System.out.println("Menu :\n"+"1:Search for a item by
name\n"+"2:Find costliest item\n"+"3:Display all items
and total cost\n4:Exit\n"+"Choice :" );
ch=Integer.parseInt(b.readLine());
switch (ch) {
item.search(it,n);
break;
item.search_cost(it,n);
break;
case 3: for(i=0;i<n;i++)
System.out.println(it[i].toString());
break;
case 4: break;
default:System.out.println("Invalid Option");
}
}while(ch!=4);
}
}
slip 15.2
Create a Hash table containing student name and percentage. Display the
details of the hash table. Also search for a specific student and display
percentage of that student. [30]
import java.io.*;
import java.util.*;
void display()
{
Enumeration keys=ht.keys();
while(keys.hasMoreElements())
{
Enumeration values=ht.elements();
while(values.hasMoreElements())
{
System.out.print(keys.nextElement()+" ") ;
System.out.println(values.nextElement()) ;
}
}
}
public static void main(String[] arg) throws IOException
{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in)) ;
hb.add(name,per);
}
System.out.println("------------------------");
System.out.print("Enter the Student name to search
: ") ;
String s=br.readLine();
hb.search(s) ;
System.out.println("------------------------");
System.out.println("Contents of student
hashtable");
hb.display() ;
}
}
slip 16.1
/*
Slip 16_1 Define a class cricket player(name,
no_ofinings, no_of_times_notout, total_runs,
bat_avg).create an array of ‘n’ player objects.
Calculate the batting average for each player using a
static method avg(). Handle appropriate exception while
calculating average. Difine static method ‘sortPlayer’
which sorts the array on the basis of average. Display
the player details in sorted order.
*/
import java.io.*;
class Inning_Invalid extends Exception
{}
class CricketPlayer
{
int no_of_in,runs,bat_avg;
String name;
int not_out;
CricketPlayer(){}
CricketPlayer(String n,int no,int n_out,int r)
{
name=n;
no_of_in=no;
not_out=n_out;
runs=r;
}
void cal_avg()
{
try
{
if(no_of_in==0)
bat_avg=runs/no_of_in;
}
catch(Inning_Invalid ob)
{
runs=0;
bat_avg=0;
}
}
void display()
{
System.out.println(name+"\t"+no_of_in+"\t"+not_out+"\t
"+runs+"\t"+bat_avg);
}
float getavg()
{
return bat_avg;
}
for(int j=0;j<i;j++)
{
if(c[j].getavg()>c[j+1].getavg())
CricketPlayer t=c[j];
c[j]=c[j+1];
c[j+1]=t;
}
}
}
for(int i=0;i<n;i++)
c[i].display();
}
}
class Slip16_1
{
public static void main(String args[]) throws
IOException
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.print("Enter Name:");
String name=br.readLine();
System.out.print("Enter no of innings:");
int in=Integer.parseInt(br.readLine());
cp[i]=new CricketPlayer(name,in,ot,r);
cp[i].cal_avg();
}
System.out.println("===============================");
for(int i=0;i<n;i++)
cp[i].display();
CricketPlayer.sortPlayer(cp,n);
}
}
slip 16.2
Create an application to store city names and their STD
codes using an appropriate collection. The GUI should
allow the following operations:
a. add a new city and its code(No Duplicate)
b. remove a city name and display the code.
c. search for a city name and display the code.
/* Slip16_2 */
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
Hashtable ts;
Slip16_2()
{
ts=new Hashtable();
t1=new JTextField(10);
t2=new JTextField(10);
t3=new JTextField(10);
b1=new JButton("Add");
b2=new JButton("Search");
b3=new JButton("Remove");
t=new JTextArea(20,20);
p1=new JPanel();
p1.add(t);
add(p1);
add(p2);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
setLayout(new FlowLayout());
setSize(500,500);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e)
{
if(b1==e.getSource())
{
String name = t1.getText();
int code = Integer.parseInt(t2.getText());
ts.put(name,code);
Enumeration k=ts.keys();
Enumeration v=ts.elements();
String msg="";
while(k.hasMoreElements())
{
msg=msg+k.nextElement()+" = "+v.nextElement()+"\n";
}
t.setText(msg);
t1.setText("");
t2.setText("");
}
else if(b2==e.getSource())
{
String name = t3.getText();
if(ts.containsKey(name))
{
t.setText(ts.get(name).toString());
}
else
if(ts.containsKey(name))
{
ts.remove(name);
else
/*
Slip 17_1. Define an abstract class “staff” with members
name and address. Define two subclasses off this class-
‘Full Timestaff’ (department, salary) and part time
staff (number_of_hours_, rate_per_hour).
defineappropriate constructors.create ‘n’ object which
could be of either FullTimeStaff or ParttimeStaff class
by asking the users choice. Display details of all
“FulTimeStaff” objects and all “PartTimeStaff” objects.
*/
import java.io.*;
abstract class Staff
{
String name,address;
this.department=department;
this.salary=salary;
}
public void display()
{
System.out.println("Name:"+name);
System.out.println("Address:"+address);
System.out.println("Department:"+department);
System.out.println("Salary:"+salary);
}
}
class PartTime extends Staff
{
int noofhrs;
double rate;
public PartTime(String name,String address,int
noofhrs,double rate)
{
super(name,address);
this.noofhrs=noofhrs;
this.rate=rate;
}
public void display()
{
System.out.println("Name:"+name);
System.out.println("Address:"+address);
System.out.println("Number of hours:"+noofhrs);
class Slip17_1
{
public static void main(String args[]) throws Exception
{
int ch=0,n=0,noofhrs;
String name,address,department;
double salary,rate;
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
do
{
switch(ch)
{
case 1:
n=Integer.parseInt(br.readLine());
for(int i=0;i<n;i++)
System.out.println("Enter name:");
name=br.readLine();
System.out.println("Enter Address:");
address=br.readLine();
System.out.println("Enter Department:");
department=br.readLine();
System.out.println("Enter Salary:");
salary=Double.parseDouble(br.readLine());
F[i]=new FullTime(name,address,department,salary);
}
System.out.println("Full Time details:");
System.out.println("========================");
for(int i=0;i<n;i++)
F[i].display();
break;
case 2:
n=Integer.parseInt(br.readLine());
for(int i=0;i<n;i++)
System.out.println("Enter name:");
name=br.readLine();
System.out.println("Enter Address:");
address=br.readLine();
System.out.println("Enter no of hrs:");
noofhrs=Integer.parseInt(br.readLine());
System.out.println("Enter rate:");
rate=Double.parseDouble(br.readLine());
obj[i]=new PartTime(name,address,noofhrs,rate);
System.out.println("========================");
for(int i=0;i<n;i++)
obj[i].display();
break;
case 3:break;
default:
break;
}
}while(ch!=3);
}
}
slip 17.2
Design the table Login(login_name, password) using Postgresql. Also
design an HTML login screen accepting the login name and password from
the user. Write a servlet program that validates accepted login name and
password entered by user from the login table you have created. The servlet
sends back an appropriate response. [30]
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
java.sql.Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:33
06/slip17","root","123456");
Statement st= con.createStatement();
ResultSet rs=st.executeQuery("SELECT * FROM Login");
String name=req.getParameter("uname");
String password=req.getParameter("pass");
res.setContentType("text/html");
while(rs.next())
{
if(name.equals(rs.getString(1))&&
password.equals(rs.getString(2)))
res.sendRedirect("Welcome.html");
}
res.sendRedirect("error.html");
}
}
slip 18.1
Define a class MyNumber having one private integer data member. Write
a default constructor to initialize it to 0 and another constructor to initialize
it to a value (use this). Write methods isNegative, isPositive, isZero, isOdd,
isEven. Create an object in main. Use command line arguments to pass a
value to the object and perform the above tests. [30]
import java.io.*;
class MyNumber
{
private int a;
MyNumber()
{
a=0;
}
MyNumber(int n)
{
this.a=n;
}
void isNegative()
{
if(a<0)
{
System.out.println("Negetive....");
}
else
{
System.out.println("Not negative....");
}
}
void isPositive()
{
if(a>0)
{
System.out.println("Positive....");
}
else
{
System.out.println("Not Positive....");
}
}
void isZero()
{
if(a==0)
{
System.out.println("Zero....");
}
else
{
System.out.println("Not zero....");
}
}
void isEven()
{
if((a%2)==0)
{
System.out.println("Even....");
}
else
{
System.out.println("Not Even....");
}
}
void isOdd()
{
if((a%2)!=0)
{
System.out.println("Odd....");
}
else
{
System.out.println("Not odd....");
}
}
public static void main(String[] args)
{
int b=Integer.parseInt(args[0]);
MyNumber o1 = new MyNumber(b);
o1.isPositive();
o1.isNegative();
o1.isEven();
o1.isOdd();
o1.isZero();
}
}
slip 18.2
Define a thread to move alphabets inside a panel vertically. The alphabets
should be created between A – Z when user clicks on the Start Button. Each
alphabets should have a different color and vertical position (calculated
randomly).
Note: Suppose user has clicked buttons 5 times then five alphabets say A,
E, C, G, J should be created and move inside the panel. Choice of alphabets
between A-Z is random. Ensure that alphabet moving within the panel
border only. [30]
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
setLayout(new FlowLayout());
add(b);
add(p);
b.addActionListener(this);
setSize(200,200);
setVisible(true);
setTitle("Bouncing Ball");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void paint (Graphics g )
{
g.setColor(Color.white);
g.fillRect(10,10,200,200);
ball = new Thread(new Ball(this));
// Create and start the ball
ball.start();
}
package mouse;
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code="MouseApplet.class" width=500 height=500>
</applet>
*/
public class MouseApplet extends Applet implements
MouseMotionListener, MouseListener, KeyListener
{
/**
*
*/
private static final long serialVersionUID = 1L;
String s="";
public void init()
{
addMouseListener(this);
addKeyListener(this);
addMouseMotionListener(this);
}
repaint();
}
public void mousePressed(MouseEvent me)
{
if(me.getButton()==MouseEvent.BUTTON3)
{
s="Right Button is pressed";
}
if(me.getButton()==MouseEvent.BUTTON2)
{
s="Centre Button is pressed";
}
if(me.getButton()==MouseEvent.BUTTON1)
{
s="Left Button is pressed";
}
repaint();
}
public void mouseReleased(MouseEvent me)
{
s="Mouse Button is released";
repaint();
}
public void mouseEntered(MouseEvent me)
{
s="Mouse Button is entered";
repaint();
}
public void mouseExited(MouseEvent me)
{
s="Mouse Button is exited";
repaint();
}
public void mouseDragged(MouseEvent me)
{
int x=me.getX();
int y=me.getY();
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();
element=Integer.parseInt(br.readLine());
ts.add(element);
}
System.out.println("Element is found");
else
import SY.Symarks;
import TY.Tymarks;
import java.io.*;
class Slip20_1
{
int rollno,gtotal,sytotal,tytotal;
String sname,grade;
float per;
for(int i=0;i<n;i++)
{
s[i]=new Slip20_1();
sy[i]=new Symarks();
ty[i]=new Tymarks();
s[i].accept();
sy[i].accept();
ty[i].accept();
s[i].tytotal=(ty[i].theory + ty[i].practicals);
s[i].sytotal=sy[i].ctotal;
s[i].gtotal=(s[i].tytotal + s[i].sytotal);
s[i].per=((s[i].gtotal)/12);
if(s[i].per>=70)
s[i].grade="A";
else if(s[i].per<70 && s[i].per>=60)
s[i].grade="B";
else if(s[i].per<60 && s[i].per>=50)
s[i].grade="C";
else if(s[i].per<50 && s[i].per>=40)
s[i].grade="PASS";
else
s[i].grade="FAIL";
}
System.out.println("\nRollNo.\tSname\tSYTotal\tTYTotal
\tGTotal\tGPercentage\tGrade");
for(int i=0;i<n;i++)
{
System.out.println(s[i].rollno+"\t"+s[i].sname+"\t"+s[
i].sytotal+"\t"+s[i].tytotal+"\t"+s[i].gtotal+"\t"+s[i
].per+"\t"+s[i].grade);
}
}catch(Exception e){}
}
}
slip 20.2
/* Slip20_2 */
import java.sql.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
Connection con;
PreparedStatement ps;
Statement stmt ;
ResultSet rs ;
ResultSetMetaData rsmd ;
Slip20_2()
{
t1 = new JTextField(20);
t2 = new JTextField(20);
t3 = new JTextField(20);
t4 = new JTextField(20);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
p=new JPanel();
p1=new JPanel();
add(l1);
add(t1);
add(b1);
add(l2);
add(t2);
add(b2);
add(l3);
add(t3);
add(b3);
add(l4);
add(t4);
add(b4);
setLayout(new GridLayout(4,3));
setSize(400,400);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
System.out.println("Accept Values");
try
{
Class.forName(“org.postgresql.Driver”);
con=DriverManager.getConnection(“jdbc:postgresql://192
.168.100.254/Bill”,”oracle”,”oracle”);
ps.setString(1,name);
ps.setString(2,addr);
ps.setString(3,phno);
ps.setString(4,mail);
System.out.println("values set");
int n=ps.executeUpdate();
if(n!=0)
{
JOptionPane.showMessageDialog(null,"Record insered
...");
}
else
}//end of try
catch(Exception ex)
{
System.out.println(ex);
//ex.printStackTrace();
}
}//end of if
else if(b2==e.getSource())
{
try
{
Class.forName(“org.postgresql.Driver”);
con=DriverManager.getConnection(“jdbc:postgresql://192
.168.100.254/Bill”,”oracle”,”oracle”);
stmt =
con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,Re
sultSet.CONCUR_UPDATABLE);
String nm = t1.getText();
int no =
stmt.executeUpdate("delete from Phone where name =
'"+nm+"'");
if(no!=0)
JOptionPane.showMessageDialog(null,"Record Deleted");
else
JOptionPane.showMessageDialog(null,"Record NOT
Deleted");
}//end of try
catch(Exception ex)
{
System.out.println(ex);
}
}//end of if
else if(b3==e.getSource())
{
try
{
Class.forName(“org.postgresql.Driver”);
con=DriverManager.getConnection(“jdbc:postgresql://192
.168.100.254/Bill”,”oracle”,”oracle”);
stmt =
con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,Re
sultSet.CONCUR_UPDATABLE);
String nm = t1.getText();
rs = stmt.executeQuery("select * from Phone");
//while(rs.next())
{
if(rs.getString(1).equals(nm))
{ rs.next();
t1.setText(rs.getString(1));
t2.setText(rs.getString(2));
t3.setText(rs.getString(3));
t4.setText(rs.getString(4));
break;
}
}
if(rs.isLast())
JOptionPane.showMessageDialog(null,"can't move
forword");
}//end of try
catch(Exception ex)
{
System.out.println(ex);
}
}//end of if
else if(b4==e.getSource())
{
try
{
Class.forName(“org.postgresql.Driver”);
con=DriverManager.getConnection(“jdbc:postgresql://192
.168.100.254/Bill”,”oracle”,”oracle”);
stmt =
con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,Re
sultSet.CONCUR_UPDATABLE);
String nm = t1.getText();
rs = stmt.executeQuery("select * from Phone");
// while(rs.next())
{
if(rs.getString(1).equals(nm))
{ rs.previous();
t1.setText(rs.getString(1));
t2.setText(rs.getString(2));
t3.setText(rs.getString(3));
t4.setText(rs.getString(4));
break;
}
}
if(rs.isFirst())
JOptionPane.showMessageDialog(null,"can't move
backward");
}//end of try
catch(Exception ex)
{
System.out.println(ex);
}
}//end of if
}
public static void main(String a[])
{
Slip20_2 ob= new Slip20_2();
}
}
slip 21.1
import java.io.*;
class Slip21_1
{
int rollno;
String name;
float percent;
if(studentArray[i].percent<studentArray[j].percent)
{
temp=studentArray[i];
studentArray[i]=studentArray[j];
studentArray[j]=temp;
}
}
}
public String toString()
{
return "["+rollno+","+name+","+percent+"]";
}
public static void main(String args[])throws
IOException
{
int n,i;
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("enter value of n");
n=Integer.parseInt(br.readLine());
Slip21_1[] studentArray=new Slip21_1[20];
for(i=0;i<n;i++)
{
studentArray[i]=new Slip21_1();
studentArray[i].rollno=i+1;
System.out.println("enter your name");
studentArray[i].name=br.readLine();
System.out.println("enter your percentage");
studentArray[i].percent=Float.parseFloat(br.readLine()
);
System.out.println("rollno="+studentArray[i].rollno);
System.out.println("name="+studentArray[i].name);
System.out.println("percent="+studentArray[i].percent)
;
}
Slip21_1.sortStudent(studentArray,n);
for(i=0;i<n;i++)
{
System.out.println(studentArray[i]);
}
}
}
slip 21.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. [30]
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import java.sql.*;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:questjsp");
st=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE
,ResultSet.CONCUR_UPDATABLE);
}
catch(Exception e){}
}
public void doGet(HttpServletRequest req ,
HttpServletResponse res) throws
IOException,ServletException
{
res.setContentType("text/html");
PrintWriter pw= res.getWriter();
}
slip 22.1
int n;
int arr[]=new int [20];
int n1,n2,gcd,pow;
public Slip22_1()
{
mb=new JMenuBar();
m1=new JMenu("Operation");
m2=new JMenu("Compute");
String str[]={"Accept","Exit","GCD","Power"};
m=new JMenuItem[str.length];
for(int i=0;i<str.length;i++)
{
m[i]=new JMenuItem(str[i]);
m[i].addActionListener(this);
}
mb.add(m1);
mb.add(m2);
m1.add(m[0]);
m1.add(m[1]);
m2.add(m[2]);
m2.add(m[3]);
setLayout(new BorderLayout());
add(mb,BorderLayout.NORTH);
setSize(300,150);
setVisible(true);
setLocation(500,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
} // constructor
public void actionPerformed(ActionEvent e)
{
String s=e.getActionCommand();
//return the name of menu
if(s.equals("Exit"))
System.exit(0);
if(s.equals("Accept"))
{
n1=Integer.parseInt(JOptionPane.showInputDialog("Enter
1st no for Number"));
n2=Integer.parseInt(JOptionPane.showInputDialog("Enter
2nd no for Number"));
}
if(s.equals("GCD"))
{
int min;
if(n1>=n2)
min=n1;
else
min=n2;
for(int i=1;i<=min;i++)
{
gcd=i;
}
JOptionPane.showMessageDialog(null,"GCD = "+gcd);
}
if(s.equals("Power"))
{
pow=1;
for(int i=1;i<=n2;i++)
{
pow=pow*n1;
}
JOptionPane.showMessageDialog(null,"Power = "+pow);
}
}
public static void main(String a[])
{
new Slip22_1();
}
}
slip 22.2
Create a JSP page which accepts user name in a text box and greet the user
according to the time on server side.
Example:
Input : User Name ABC
Output : Good Morning ABC/Good Afternoon ABC/ Good Evening ABC
[30]
user.jsp
<%@page import="java.util.*"%>
<%
String name = request.getParameter("uname");
Date d = new Date();
if(d.getHours()<12)
{
%>
Good Morning <%=name%>
<%
}
else if(d.getHours()<16)
{
%>
Good Afternoon <%=name%>
<%
}
else
{
%>
Good Evening <%=name%>
<%
}
%>
slip 23.1
import java.io.*;
interface CreditCard
{
void viewCreditAmount();
void increaseLimit()throws IOException;
void useCard()throws IOException ;
void payCard()throws IOException;
}
SliverCardCustomer()
{
name="Noname" ;
card_no=0;
creditAmount=0;
creaditLimit=50000;
}
card_no=Integer.parseInt(br.readLine());
creditAmount=Double.parseDouble(br.readLine());
}
creditAmount=creditAmount+pay;
System.out.println("Balance is paid");
}
public void useCard()throws IOException
{
if(amount<creditAmount)
{
creditAmount=creditAmount-amount;
viewCreditAmount();
creaditLimit=creaditLimit+amt;
}
else
if(amt<=5000)
{
creaditLimit=creaditLimit+amt;
System.out.println("Amount limit to increse
Successfully : ");
}
}
else
}
class Slip23_1
{
public static void main(String
args[])throws IOException
{
int ch ;
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("0. exit") ;
ch=Integer.parseInt(br.readLine());
switch(ch)
{
case 1: sc.useCard();
break;
case 2:sc.payCard();
break ;
case 3:sc.increaseLimit();
break;
case 4:gc.useCard();
break;
case 5:gc.payCard();
break ;
case 6:gc.increaseLimit();
break;
case 0 :break;
}
}while(ch!=0);
}
}
slip 23.2
SLIP 23:
Write a program to make use of the following JSP implicit
objects.
a. Out: To display current Date and Time.
b. Request: to get header information.
c. Response: to add a cookie.
d. Config: get the parameters value defined in <init-
param>.
e. Application: get the parameter value defined in
<context-param>
/* Slip 23_2 */
<%@page import="java.util.Calendar"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%
Calendar c = Calendar.getInstance();
int dd = c.get(Calendar.DATE);
int h = c.get(Calendar.HOUR_OF_DAY);
int m = c.get(Calendar.MINUTE);
int s = c.get(Calendar.SECOND);
out.println("\nConfig");
out.println("\n"+config.getServletName());
out.println("\nApplication : ");
out.println("\n"+application.getServerInfo());
%>
slip 24.1
import java.io.*;
class Vehicle
{
String cname;
float price;
void display()
{
System.out.println("Company Name : "+cname+"\nPrice :
"+price);
}
super.accept();
void display()
{
super.display();
System.out.println("\nMileage : "+mileage);
}
super.accept();
void display()
{
super.display();
class Slip24_1
{
public static void main(String args[])
throws IOException
{
BufferedReader br = new
BufferedReader(new InputStreamReader(System.in));
no = Integer.parseInt(br.readLine());
lv[i].accept();
System.out.println("=======================");
lv[i].display();
break;
case 2
:System.out.println("Enter no of heavy motor");
no = Integer.parseInt(br.readLine());
hv[i].accept();
System.out.println("=======================");
hv[i].display();
break;
//calculate_salary(mn,no);
}
}
}
slip 24.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. [30]
testdemo.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import java.sql.*;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:questjsp");
st=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE
,ResultSet.CONCUR_UPDATABLE);
}
catch(Exception e){}
}
public void doGet(HttpServletRequest req ,
HttpServletResponse res) throws
IOException,ServletException
{
res.setContentType("text/html");
PrintWriter pw= res.getWriter();
}
slip 25.1
/*
Slip 25_1. Define a class employee having members –id,
name, department, salary. Define default and
parameterized constructors. Create a subclass called
manager with private member bonus. Define methods accept
and display in both the classes. Create “n” objects of
the manager class and display the details of the manager
having the maximum total salary (salary+bonus).
*/
import java.io.*;
class Employee
{
private int id;
private String name, department;
private float salary;
Employee()
{
id = 1;
name = "nived";
department = "bcs";
salary = 20000;
}
id = Integer.parseInt(br.readLine());
name= br.readLine();
department = br.readLine();
salary = Float.parseFloat(br.readLine());
}
void display()
{
System.out.println("\nId : "+id+"\nName :
"+name+"\nDepartment : "+department+"\nSalary :
"+salary);
}
float getsalary()
{
return salary;
}
}
Manager()
{
super();
}
Manager(int id, String name, String department, float
salary, float bonus)
{
super(id, name, department, salary);
this.bonus = bonus;
}
super.accept();
void display()
{
super.display();
System.out.println("\nBonus : "+bonus);
}
float getbonus()
{ return bonus;
}
}
class Slip25_1
{
public static void main(String args[]) throws
IOException
{
BufferedReader br = new
BufferedReader(new InputStreamReader(System.in));
mn[i].accept();
}
calculate_salary(mn,no);
}
float max = 0;
for(int i = 0; i<n; i++)
{
index = i;
}
}
shop1.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class Shop1 extends HttpServlet
{
public void doGet(HttpServletRequest
req,HttpServletResponse res)throws
IOException,ServletException
{
res.setContentType("text/html");
PrintWriter pw=res.getWriter();
String cvalue[]=req.getParameterValues("c1");
HttpSession hs=req.getSession(true);
int sum1=0;
for(int i=0;i<cvalue.length;i++)
{
sum1=sum1+Integer.parseInt(cvalue[i]);
}
hs.setAttribute("page1",sum1);
res.sendRedirect("two2.html");
}
}
shop2.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class Shop2 extends HttpServlet
{
public void doGet(HttpServletRequest
req,HttpServletResponse res)throws
IOException,ServletException
{
res.setContentType("text/html");
PrintWriter pw=res.getWriter();
String cvalue[]=req.getParameterValues("c2");
HttpSession hs1=req.getSession();
int sum2=0;
for(int i=0;i<cvalue.length;i++)
{
sum2=sum2+Integer.parseInt(cvalue[i]);
}
int total=0;
total=((Integer)hs1.getAttribute("page1")).intValue();
total=total+sum2;
pw.println("Total Bill Amount: "+total);
}
}