0% found this document useful (0 votes)
80 views

Java University Sloved Slips

The document describes a program that defines a MyDate class with day, month and year members and default and parameterized constructors. It accepts values from the command line to create a MyDate object, throwing custom exceptions for invalid day or month. If the date is valid, it displays a message.

Uploaded by

Omkar Bhate
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
80 views

Java University Sloved Slips

The document describes a program that defines a MyDate class with day, month and year members and default and parameterized constructors. It accepts values from the command line to create a MyDate object, throwing custom exceptions for invalid day or month. If the date is valid, it displays a message.

Uploaded by

Omkar Bhate
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 166

slip 1.

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]

abstract class Shape


{
double radius,ht;
Shape(double a, double b)
{
radius = a;
ht= b;
}
abstract double area();
abstract double volume();
}

class Sphere extends Shape


{
Sphere(double a)
{
super(a,0);
}
double area()
{
System.out.print("\nArea of Sphere:");
return (4*3.14*radius*radius);
}
double volume()
{
System.out.print("\nVolume of Sphere:");
return (4*3.14*radius*radius*radius)/3;
}

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

class Cylinder extends Shape


{
Cylinder(double a, double b)
{
super(a,b);
}
double area()
{
System.out.print("\nArea of Cylinder:");
return (2*3.14*radius*(ht+radius));
}
double volume()
{
System.out.print("\nVolume of Cylinder:");
return (3.14*radius*radius*ht);
}
}
class AbstractDemo
{
public static void main(String args[])
{
Shape s;
s = new Sphere(5);
System.out.print(s.area());
System.out.print(s.volume());
System.out.println();

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

Cookie []c = req.getCookies();


int id=1;
if(c!=null)
id = c.length+1;

String value = req.getParameter("ch");


Cookie newCookie = new Cookie("choice"+id," "+value);
res.addCookie(newCookie);
pw.println("<h4>Cookie added with value
"+value+"</h4>");
pw.println("<a href='View'>View Cookies</a>"); }}
slip 2.1

/*Slip 2_1. Write a menu driven program to perform the


following operations on a set of integers
as shown in the following fig. the load operation should
generate 10 random integer(2 digit) and
display the number on screen. The save operation should
save the number to a file number.txt.
The short menu provides various operations and the
result is displayed on the screen.
*/

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

class Slip2_1 extends JFrame implements ActionListener


{
JMenu m1,m2;
JMenuBar mb;
JMenuItem m[];

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

public void actionPerformed(ActionEvent e)


{
String s=e.getActionCommand(); //return the
name of menu
if(s.equals("Exit"))
System.exit(0);
else if(s.equals("Load"))
{
if(arr[0]==0)
{

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

if(ch == ' ')

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

Write a client-server program which displays the server machine”s date


and time on the client machine [30]

client.java

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

public class Client


{
public static void main(String args[])
throws Exception
{
Socket s = new Socket("localhost",4444);

BufferedReader br = new BufferedReader(new


InputStreamReader(s.getInputStream()));

System.out.println("From Server:"+br.readLine());
}
}

server.java

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

public class Server


{
public static void main(String args[])
throws Exception
{
ServerSocket ss = new ServerSocket(4444);

while(true)
{
Socket s = ss.accept();

PrintStream ps = new PrintStream(s.getOutputStream());

ps.println(new Date());

s.close();
}
}
}
slip 3.1

/*Define class MyDate with members day, month, year.


Define default and parameterized constructors. Accept
values from the command line and create a date object.
Throw user defined exceptions – “InvalidDayException” or
“InvalidMonthException” if the day and month are
invalid. If the date is valid, display message “Valid
date”.
*/

class InvalidDateException extends Exception


{
public String toString()
{
return "Invalid Date given";
}
}

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]);

boolean leap=((yy%400==0)||(yy%4==0 && yy%100!=0));

if(mm < 1||mm >12)


throw new InvalidDateException();
switch(mm)
{
case 1:

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

Consider the following entity and their relationships


BillMaster(billno,custename,billdate)
BillDetails(itemname,qty,rate)
BillMaster and BilDetails are related with one-many
relationship. Create a RDB in 3NF using Postgresql for
the above and solve the following:
Desing HTML page that accept the bill number from user
and print the corresponding bill in the following format
using servlet programming.

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)

msg=”Connection to databse failed”;


else
{

st=con.createStatement();

rs=st.executeQuery(“select * from BillMaster where


billno =”+billno);

rs1=st.executeQuery(“select * from BillDetails where


billno =”+billno);

if(rs==null || rs1==null)

System.out.println(“Invalid bill number”);


else
{

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”);

System.out.println(“Sr No.\t\t Item Name \t\t Quantity


\t\t Rate \t\tTotal\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

/*Slip 4_1. Write a menu driven program to perform the


following operations on a set of integers as shown in
the following figure. A load operation should generate
10 random integers (2 digit) and display the no on
screen. The save operation should save the no to a file
number.txt. The short menu provides various operations
and the result is displayed on the screen.
*/

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

class Slip4_1 extends JFrame implements ActionListener


{
JMenu m1,m2;
JMenuBar mb;
JMenuItem m[];
JLabel l;
JTextField t;
JPanel p;

StringBuffer ss=new StringBuffer();


int n;
int arr[]=new int [20];
Slip4_1()
{
p=new JPanel();
mb=new JMenuBar();
m1=new JMenu("Operation");
m2=new JMenu("Compute");
l=new JLabel("Numbers");
t=new JTextField(20);
String
str[]={"Load","Save","Exit","Sum","Average"};
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);
}

public int givesum()


{
int sum=0;
for(int i=0;i<n;i++)
{
sum=sum+arr[i];
}
return sum;
}
public double giveavg()
{
int sum=0;
for(int i=0;i<n;i++)
{
sum=sum+arr[i];
}
return sum/n;
}

public void actionPerformed(ActionEvent e)


{
String s=e.getActionCommand();
//return the name of menu
if(s.equals("Exit"))
System.exit(0);
else if(s.equals("Load"))
{
if(arr[0]==0)
{
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);
if(ch == ' ')
br1.write('\n');
else
br1.write(ch);
}
br1.close();
}
catch(Exception eee)
{ }
}
else if(s.equals("Sum"))
{
t.setText(new Integer(givesum()).toString());
}
else if(s.equals("Average"))
{
t.setText(new Double(giveavg()).toString());
}
}
public static void main(String arg[])
{
Slip4_1 ob = new Slip4_1();
}
}
slip 4.2
Design a servlet that provides information about a http
request from client, such as IP address and browser type.
The servlet also provides information about the server
on which the servlet is running, such as the operating
system type, and the names of currently loaded servlet.

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

public void run()


{
try{
while(true)
{
Thread.sleep(37);
if(top >= 188)
up=true;
if(top <= 0)
up=false;
if(!up)
top=top+2;
else
top=top-2;

parent.p.repaint();
}
}catch(Exception e){}
}
}

class bass2_2a extends JFrame implements ActionListener


{
int top=0,left=0,n=0,radius=50;
Color
C[]={Color.black,Color.cyan,Color.orange,Color.red,Col
or.yellow,Color.pink,Color.gray,Color.blue,Color.green
,Color.magenta};
Thr t[]=new Thr[10];
int x[]=new int[10];
GPanel p;JButton b;Panel p1;
Random r1=new Random();
bass2_2a()
{
setSize(700,300);
setLayout( new BorderLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(p=new GPanel(this),BorderLayout.CENTER);
b= new JButton("Start");
b.addActionListener(this);
setVisible(true);setDefaultCloseOperation(JFrame.EXIT_
ON_CLOSE);
add(p1=new Panel(),BorderLayout.SOUTH);
p1.setBackground(Color.lightGray);
p1.add(b);
setVisible(true);
}
public static void main(String args[])
{
new bass2_2a();
}
public void actionPerformed(ActionEvent e)
{
t[n]=new Thr(left+(radius+13)*n+29,top+n*25,C[n],this);
x[n]=r1.nextInt(9);
t[n].start();
n++;
p.repaint();
if(n >9)
b.setEnabled(false);
}
}

class GPanel extends JPanel{


bass2_2a parent;
GPanel(bass2_2a p)
{
parent=p;
}
public void paintComponent(Graphics g){
super.paintComponent(g);
setBackground(Color.white);
for(int i=0;i< parent.n;i++)
{
g.setColor(parent.t[i].c);
//g.fillOval(parent.t[i].left,parent.t[i].top,parent.r
adius,parent.radius);
g.drawString(""+parent.x[i],parent.t[i].left,parent.t[
i].top);
}
}}
slip 6.1
Write a program to accept a decimal number in the TextField. After clicking
Calculate button, program should display the binary, octal, hexadecimal
equivalent for the entered decimal number. [30]

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 {

public static void main(String[] args) throws


Exception
{
Socket s = new Socket("localhost", 123);
InputStreamReader isr=new
InputStreamReader(System.in);
BufferedReader br =new BufferedReader(isr);
InputStream is=s.getInputStream();
DataInputStream dis = new DataInputStream(is);
OutputStream os= s.getOutputStream();
DataOutputStream dos = new
DataOutputStream(os);
boolean done=false;
while(!done)
{
System.out.println("Enter text (END to
stop)");
String message = br.readLine();
dos.writeUTF(message);
String servermessage=dis.readUTF();
System.out.println("server says--
"+servermessage);

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.*;

class Slip8_1 extends JFrame implements ItemListener


{
JLabel font, style, size;
JComboBox fontcb, sizecb;
JCheckBox bold, italic;
JTextField t;
JPanel p1, p2;
Slip8_1()
{ p1 = new JPanel();
p2 = new JPanel();
font = new JLabel("Font");
style = new JLabel("Style");

fontcb = new JComboBox();


fontcb.addItem("Arial");
fontcb.addItem("Sans");
fontcb.addItem("Monospace");

bold = new JCheckBox("Bold");


size = new JLabel("Size");
italic = new JCheckBox("Italic");
sizecb = new JComboBox();
sizecb.addItem("10");
sizecb.addItem("12");
sizecb.addItem("16");
t = new JTextField(10);
p1.setLayout(new GridLayout(4,2));
p1.add(font);
p1.add(style);
p1.add(fontcb);
p1.add(bold);
p1.add(size);
p1.add(italic);
p1.add(sizecb);

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.*;

public class HitCount extends HttpServlet


{
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws
ServletException,IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Cookie c[]=request.getCookies();
if(c==null)
{
Cookie cookie = new Cookie("count","1");
response.addCookie(cookie);
out.println("<h3>Welcome Servlet<h3>"+ "Hit
Count:<b>1</b>");
}
else
{

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

public void keyTyped(KeyEvent ke)


{
char c;
c=ke.getKeyChar();
s="Key is Typed"+""+c;
repaint();
}
public void keyPressed(KeyEvent ke)
{
char c;
c=ke.getKeyChar();
s="Key is Pressed"+""+c;
repaint();
}
public void keyReleased(KeyEvent ke)
{
char c;
c=ke.getKeyChar();
s="Key is Released"+""+c;
repaint();
}

public void mouseClicked(MouseEvent me)


{
if(me.getButton()==MouseEvent.BUTTON3)
{
s="Right Button is clicked";
}
if(me.getButton()==MouseEvent.BUTTON2)
{
s="Centre Button is clicked";
}
if(me.getButton()==MouseEvent.BUTTON1)
{
s="Left Button is clicked";
}

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

s="The is Dragged at "+"X axis="+x+""+"Y


axis="+y;
repaint();
}
public void mouseMoved(MouseEvent me)
{
int x=me.getX();
int y=me.getY();
s="The is moved at"+"X axis="+x+""+"Y axis="+y;
repaint();
}
public void paint(Graphics g)
{
g.drawString(s,100,100);
}
}

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

String fname =(String)dis.readUTF();


File f = new File(fname);
if(f.exists())
{

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("File not present ");


else
{
System.out.println("Content of the file is : \n");

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.*;

class Calculator extends JFrame implements


ActionListener
{
private JPanel p1,p2;
private JTextField t1;
private JButton b[],b1;
StringBuffer s1 = new StringBuffer();
double n1,n2;
char ch;

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

public void actionPerformed(ActionEvent e)


{
if(e.getSource()==b1)
{
t1.setText(" ");
n1=n2=0;
ch=' ';

}
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

Write a program to accept a list of file names on the


client machine and check how many exist on the server.
Display appropriate message on the client side.
/* Server_Slip10_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)
{

System.out.println("Stop proceesing enter End");

System.out.println("Enter file name : ");


String fname =
br.readLine();

dos.writeUTF(fname);

if(fname.equals("End"))
{
break;
}
String msg = (String)dis.readUTF();

if(msg.equals("0"))

System.out.println("File not present ");


else
{

System.out.println("File Present");

//System.out.println(msg);
}
}
}
}

slip 11.1

/*write a program to accept a string as command line


argument and check whether it is a file or directory.
Also perform operations as follows.
a. If it is a directory, list the name of text
files. Also, display a count showing the number of files
in the directory.

b. If it is a file display various details of that


file.
*/

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++;
}
}

System.out.println("Total Files & Directories are :


"+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){}
}
}

public class PrintThread


{
public static void main(String a[])
{
int n=Integer.parseInt(a[0]);
String s1=a[1];
String s2=a[2];
String s3=a[3];
Mythread t1=new Mythread("I am in "+s1,n);
t1.start();
Mythread t2=new Mythread("I am in "+s2,n+10);
t2.start();
Mythread t3=new Mythread("I am in "+s3,n+20);
t3.start();
}
}

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.*;

class Slip12_1 extends JFrame implements ActionListener


{
JLabel l1,l2,l3;
JButton b;
JRadioButton r1,r2,r3;
JCheckBox c1,c2,c3;
JTextField t1,t2;
ButtonGroup b1;
JPanel p1,p2;
static int cnt;
private StringBuffer s1=new StringBuffer();

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

l1=new JLabel("Your Name");

l2=new JLabel("Your Class");

l3=new JLabel("Your Hobbies");


t1=new JTextField(20);

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

public void actionPerformed(ActionEvent e)


{

if(e.getSource()==r1)

cnt++;

if(cnt==1)

String s =t1.getText();

s1.append("Name = ");

s1.append(s);

s1.append(" Class = FY");

else if(e.getSource()==r2)

cnt++;

if(cnt==1)
{

String s =t1.getText();

s1.append("Name = ");

s1.append(s);

s1.append(" Class = SY");

else if(e.getSource()==r3)

cnt++;

if(cnt==1)

String s =t1.getText();

s1.append("Name = ");

s1.append(s);

s1.append(" Class = TY");

}
else if(e.getSource()==c1)

s1.append(" Hobbies = Music");

else if(e.getSource()==c2)

s1.append(" Hobbies = Dance");

else if(e.getSource()==c3)

s1.append(" Hobbies = Sports");

t2.setText(new String(s1));

// t2.setText(s2);

if(e.getSource()==b)

t2.setText(" ");
t1.setText(" ");

public static void main(String arg[])


{
Slip12_1 s=new Slip12_1();

}}

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

/*Write a program to accept a string as command line


argument and check whether it is a file or directory. A.
If it is a directory, list the contents of the directory,
count how many files the directory has and delete all
files in that directory having extension .txt. (Ask the
user if the files have to be deleted). B. If it is a
file, display all information about the file(path, size,
attributes etc).
*/

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.*;

class Slip13_2 extends JFrame implements ActionListener


{
JLabel l1,l2,l3;
JTextField t1,t2,t3;
JButton b1,b2,b3;
String sql;
JPanel p,p1;
Connection con;
PreparedStatement ps;

JTable t;
JScrollPane js;
Statement stmt ;
ResultSet rs ;
ResultSetMetaData rsmd ;
int columns;
Vector columnNames = new Vector();
Vector data = new Vector();

Slip13_2()
{

l1 = new JLabel("Enter no :");


l2 = new JLabel("Enter name :");
l3 = new JLabel("percentage :");

t1 = new JTextField(20);
t2 = new JTextField(20);
t3 = new JTextField(20);

b1 = new JButton("Save");
b2 = new JButton("Display");
b3 = new JButton("Clear");

b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);

p=new JPanel();
p1=new JPanel();
p.add(l1);
p.add(t1);
p.add(l2);
p.add(t2);
p.add(l3);
p.add(t3);

p.add(b1);
p.add(b2);
p.add(b3);

add(p);
setLayout(new GridLayout(2,1));
setSize(600,800);
setVisible(true);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

public void actionPerformed(ActionEvent e)


{
if((JButton)b1==e.getSource())
{
int no = Integer.parseInt(t1.getText());
String name = t2.getText();
int p = Integer.parseInt(t3.getText());
System.out.println("Accept Values");
try
{

Class.forName(“org.postgresql.Driver”);
con=DriverManager.getConnection(“jdbc:postgresql://192
.168.100.254/Bill”,”oracle”,”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

JOptionPane.showMessageDialog(null,"Record NOT inserted


");

}//end of try
catch(Exception ex)
{

System.out.println(ex);

//ex.printStackTrace();
}

}//end of if
else
if((JButton)b2==e.getSource())
{
try
{

Class.forName(“org.postgresql.Driver”);
con=DriverManager.getConnection(“jdbc:postgresql://192
.168.100.254/Bill”,”oracle”,”oracle”);

System.out.println("Connected");

stmt=con.createStatement();
rs = stmt.executeQuery("select * from stud");
rsmd = rs.getMetaData();

columns = rsmd.getColumnCount();

//Get Columns name

for(int i = 1; i <= columns; i++)


{

columnNames.addElement(rsmd.getColumnName(i));
}
//Get row data

while(rs.next())
{

Vector row = new Vector(columns);

for(int i = 1; i <= columns; i++)


{

row.addElement(rs.getObject(i));

data.addElement(row);
}

t = new JTable(data, columnNames);


js = new JScrollPane(t);

p1.add(js);

add(p1);

setSize(600, 600);

setVisible(true);
}
catch(Exception e1)
{

System.out.println(e1);
}
}
else
{
t1.setText(" ");
t2.setText(" ");
t3.setText(" ");

}
}//end of method
public static void main(String a[])
{
Slip13_2 ob = new Slip13_2();
}
}

Slip 14_1. Write a menu driven program to perform the


following operations on a text file “phone.txt” which
contain name and phone number pairs. The menu should
have options:
a. Search name and display phone number
b. Add new name-phone number pair.

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

class phone
{
String name,phno;
phone (String nm,String ph)
{
name = nm;
phno=ph;
}

public String toString ()


{
String s = name + " " + phno ;
return (s);
}

public static void search(phone[] arr,int n)throws


IOException
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
String s=br.readLine();
for(int i=0;i<n;i++)
{

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;

File f = new File ("phone.dat");


RandomAccessFile rf = new RandomAccessFile (f, "rw");

BufferedReader b = new BufferedReader (new


InputStreamReader (System.in));
System.out.println ("Enter no.of Customer");
int ch,n;
n = Integer.parseInt (b.readLine ());
System.out.println ("Enter Records:\n <name><phone no>
:");

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


{
s = b.readLine () + "\n";

rf.writeBytes(s);
}
rf.close ();
RandomAccessFile rf1 = new RandomAccessFile (f, "r");

phone p[] = new phone[n];


for (i = 0; i < n; i++)
{
s = rf1.readLine ();

StringTokenizer t = new StringTokenizer (s, space);


String sn = new String (t.nextToken ());
String sp = new String (t.nextToken ());
p[i] = new phone(sn,sp);

do
{

System.out.println("Menu :\n"+"1:Search for a phone no


by name\n"+"2:Add a new Record \n"+"3:Exit\n"+"Enter
your Choice :" );

ch=Integer.parseInt(b.readLine());

switch (ch)
{
case 1:

System.out.println ("Enter name to be searched");

phone.search (p,n);

break;

case 2:

rf = new RandomAccessFile (f, "rw");

System.out.println ("Enter Records:\n <name><phone no>


:");

String s1 = b.readLine () + "\n";

rf.writeBytes(s1);

rf.close();

rf1 = new RandomAccessFile (f, "r");

s = rf1.readLine ();

StringTokenizer t = new StringTokenizer (s, space);

String sn = new String (t.nextToken ());

String sp = new String (t.nextToken ());

phone p1 = new phone(sn,sp);

System.out.println(" Records are ");

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.*;

public class ColorList


{
LinkedList l, l2 ;
Iterator x,y ;
ListIterator li ;
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in)) ;
public ColorList()
{
l = new LinkedList() ;
l.add("Red") ;
l.add("Blue") ;
l.add("Yellow") ;
l.add("Orange") ;
l2 = new LinkedList() ;
l2.add("Pink") ;
l2.add("Green") ;
}

void displayIterator()
{
int j = 1;
x = l.iterator() ;

System.out.println("Dispaly List 1 Using


Iterator : ") ;
while(x.hasNext())
{
System.out.println(j++ + " : "+x.next()) ;
}
}
void reverseListIterator()
{
li = l.listIterator() ;
int j = 1 ;

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

public static void main(String []arg)


{
ColorList c = new ColorList() ;
c.displayIterator() ;
c.reverseListIterator() ;
c.NewList() ;
c.displayIterator() ;
}
}
slip 15.1

/*Slip 15_1. Write a program to read item information(


id, name, price, qty) from the file ‘item.dat’. write a
menu driven program to perform the following operations
using random access file:
a. Search for a specific item by name
b. Find costliest item
c. Display all items and total cost.
*/
import java.io.*;
import java.util.*;
class item
{
String name,id;
int qty;
double price,total;

item(String i,String n,String p,String q)


{
name=n;
id=i;

qty=Integer.parseInt(q);

price=Double.parseDouble(p);
total=qty*price;
}

public String toString()


{

String s=name+" "+id+" "+qty+" "+price+" "+total;


return(s);
}
public static void search(item[] arr,int n)throws
IOException
{

BufferedReader br=new BufferedReader(new


InputStreamReader(System.in));
String s=br.readLine();
for(int i=0;i<n;i++)
{

if(arr[i].name.equals(s))
{
System.out.println(arr[i].toString());return;
}

}
System.out.println("No Records Found");
}

public static void search_cost(item[] arr,int n)


{

double max=0;int c=0;

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

if(arr[i].price > max){

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 no. of records");


Int n=Integer.parseInt(b.readLine());

System.out.println("Enter
Records:\n<id><name><price><qty>:" );

File f = new File ("item.dat");


RandomAccessFile rf = new RandomAccessFile (f, "rw");

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

s=b.readLine()+"\n";

rf.writeBytes(s);
}
rf.close();

item it[]=new item[20];


RandomAccessFile rf1 = new RandomAccessFile (f, "r");
for(i=0;i<n;i++)
{

s=rf1.readLine();

StringTokenizer t = new StringTokenizer(s,space);


String id=new String(t.nextToken());
String pname=new String(t.nextToken());
String price=new String(t.nextToken());
String qty=new String(t.nextToken());

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) {

case 1: System.out.println("Enter item name to be


searched:");

item.search(it,n);

break;

case 2: System.out.println("Costliest Item :");

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.*;

public class HashDemo


{
Hashtable ht ;
public HashDemo()
{
ht = new Hashtable() ;
}

public void add(String i,Double n)


{
ht.put(i,n);
}

public void search(String i)


{
if(ht.containsKey(i))
{
System.out.println("Student Percentage is :
"+ht.get(i)) ;
}
else
{
System.out.println("Student doesn't Exist") ;
}
}

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

HashDemo hb = new HashDemo() ;


System.out.println("How many elements to be
inserted in hashtable");
int n=Integer.parseInt(br.readLine());
for(int i=0;i<n;i++)
{ System.out.print("Enter Student name : ") ;
String name=br.readLine();
System.out.print("Enter Percentage : ");
Double per=Double.parseDouble(br.readLine());

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)

throw new Inning_Invalid();

bat_avg=runs/no_of_in;
}
catch(Inning_Invalid ob)
{

System.out.println("no of inning can not be zero");

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

public static void sortPlayer(CricketPlayer c[],int n)


{
for(int i=n-1;i>=0;i--)
{

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.println("Enter no. of Player:");


int n=Integer.parseInt(br.readLine());
CricketPlayer cp[]=new CricketPlayer[n];
for(int i=0;i<n;i++)
{

System.out.print("Enter Name:");
String name=br.readLine();

System.out.print("Enter no of innings:");
int in=Integer.parseInt(br.readLine());

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


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

System.out.print("Enter total runs:");


int r=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.*;

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 17.1

/*
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;

public Staff(String name,String address)


{
this.name=name;
this.address=address;
}
abstract public void display();
}

class FullTime extends Staff


{
String department;
double salary;

public FullTime(String name,String address,String


department,double salary)
{
super(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);

System.out.println("Rate per hour:"+rate);


}
}

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
{

System.out.println("\n1:Full Time \n2:Part Time


\n3:Exit");

System.out.println("Enter your choice:");


ch=Integer.parseInt(br.readLine());

switch(ch)
{

case 1:

System.out.println("Enter how many staff members:");

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

FullTime F[]=new FullTime[n];

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:

System.out.println("Enter how many staff members:");

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

PartTime obj[]=new PartTime[n];

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("Part Time details:");

System.out.println("========================");

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

obj[i].display();

break;

case 3:break;

default:

System.out.println(" invalid input ");

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.*;

public class validateServlet extends HttpServlet


{
public void doGet(HttpServletRequest req,
HttpServletResponse res)
throws ServletException,IOException
{
Class.forName("com.mysql.jdbc.Driver");

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.*;

class Ball extends Thread implements Runnable


{
public static final int SIZE = 5;
// Diameter of the ball
private static final int DY = 5;
// Number of pixels to move the ball
private static final int BORDER = 10;
// A 10 pixel border around drawing area
private JFrame f;
// Reference to the applet
private int topWall, bottomWall;
// Boundaries
private Point location;
// Current location of the ball

private int directionX = 1, directionY = 1;

public Ball(JFrame app)


{
f = app;
Dimension gameArea = f.getSize();
topWall = BORDER + 1;
bottomWall = gameArea.height - BORDER - SIZE;
int xLoc = BORDER + (int)(Math.random() *
(gameArea.width - BORDER));
// Pick a random xLoc
location = new Point(xLoc, gameArea.height/2);
// Set initial location
f.getGraphics().setColor(Color.green);
}

public void draw()


{
Graphics g = f.getGraphics();
g.setXORMode(Color.white);
g.fillOval(location.x, location.y, SIZE, SIZE);
}

public void move() {


location.y = location.y + DY * directionY;
if (location.y > bottomWall)
{
directionY = -directionY;
location.y = bottomWall;
}
if (location.y < topWall)
{
directionY = -directionY;
location.y = topWall;
}
}
public void run()
{
while (true)
{
draw();
try
{
sleep(100);
}
catch (InterruptedException e)
{}
draw();
move();
}
}
}

public class BouncingBall extends JFrame implements


ActionListener
{
Thread ball;
JFrame f;
JButton b=new JButton("Start");
JPanel p=new JPanel();
BouncingBall()
{
ball=new Thread();

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

public void actionPerformed(ActionEvent ae)


{
if (ae.getSource() == b)
{
ball = new Thread(new Ball(this));
ball.start();
}
}
public static void main(String[] args)
{
new BouncingBall();
}
}
slip 19.1
Create an Applet which displays a message in the center of the screen. The
message indicates the event taking place on the applet window. Handle
various keyboard related events. The message should update each time an
event occurs. The message should give details of the event such as which
key was pressed, related, typed etc. (Hint: Use repaint(), KeyListener). [30]

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

public void keyTyped(KeyEvent ke)


{
char c;
c=ke.getKeyChar();
s="Key is Typed"+""+c;
repaint();
}
public void keyPressed(KeyEvent ke)
{
char c;
c=ke.getKeyChar();
s="Key is Pressed"+""+c;
repaint();
}
public void keyReleased(KeyEvent ke)
{
char c;
c=ke.getKeyChar();
s="Key is Released"+""+c;
repaint();
}

public void mouseClicked(MouseEvent me)


{
if(me.getButton()==MouseEvent.BUTTON3)
{
s="Right Button is clicked";
}
if(me.getButton()==MouseEvent.BUTTON2)
{
s="Centre Button is clicked";
}
if(me.getButton()==MouseEvent.BUTTON1)
{
s="Left Button is clicked";
}

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

s="The is Dragged at "+"X axis="+x+""+"Y axis="+y;


repaint();
}
public void mouseMoved(MouseEvent me)
{
int x=me.getX();
int y=me.getY();
s="The is moved at"+"X axis="+x+""+"Y axis="+y;
repaint();
}
public void paint(Graphics g)
{
g.drawString(s,100,100);
}
}
slip 19.2
Accept “n” integers from the user and store them into
the collection. Display them in the sorted order. The
collection should not accept duplicate elements (Use
suitable collection). Search for the particular element
using predefined search method in the collection
framework.
/* Slip 19_2 : */

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


}
}
slip 20.1
Write a program to create a package “SY” which has a class SYMARKS
(Computer Total, MathsTotal, ElectronicsTotal). Create another package
“TY” which has a class TYMarks (Theory, Practical). Create another
package “TY” which has a class TYMarks(Theory, Practical). Create “n”
objects of student class having roll number, name, SYMakrs and TYMarks.
Add the marksof SY and TY Computer subjects and calculate grade („A‟
for >=70, „B‟ for >=60, „C‟ for >=50, “Pass Class” for >=40 else “Fail”) and
display the result of the student in proper format. [30]

import SY.Symarks;
import TY.Tymarks;
import java.io.*;

class Slip20_1
{
int rollno,gtotal,sytotal,tytotal;
String sname,grade;
float per;

public void accept()


{
try
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter student roll no: ");
rollno=Integer.parseInt(br.readLine());
System.out.println("Enter student name: ");
sname=br.readLine();
}catch(Exception e){}
}
public static void main(String a[])
{
try
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));

System.out.println("How many object you want to


create:");
int n=Integer.parseInt(br.readLine());

Symarks sy[]=new Symarks[n];


Tymarks ty[]=new Tymarks[n];
Slip20_1 s[]=new Slip20_1[n];

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

Design a following Phone Book Application screen using


swing. Display proper msg if invalid data inserted like
name left blank and negative phone number. Using
postgresql store the values in the table Phone(Name,
Address, Phone) if valid data is entered for all the
fields and perform the various operations like Add,
Delete, Next and previous.

/* Slip20_2 */

import java.sql.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;

class Slip20_2 extends JFrame implements ActionListener


{
JLabel l1,l2,l3,l4;
JTextField t1,t2,t3,t4;
JButton b1,b2,b3,b4;
String sql;
JPanel p,p1;

Connection con;
PreparedStatement ps;
Statement stmt ;
ResultSet rs ;
ResultSetMetaData rsmd ;

Slip20_2()
{

l1 = new JLabel(" Name :");


l2 = new JLabel(" Address:");
l3 = new JLabel(" Phone :");
l4 = new JLabel(" Email :");

t1 = new JTextField(20);
t2 = new JTextField(20);
t3 = new JTextField(20);
t4 = new JTextField(20);

b1 = new JButton(" Add ");


b2 = new JButton(" Delete ");
b3 = new JButton(" Next ");
b4 = new JButton(" Previous ");

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

public void actionPerformed(ActionEvent e)


{
if((JButton)b1==e.getSource())
{
String name = t1.getText();
String addr = t2.getText();
String phno = t3.getText();
String mail = t4.getText();

System.out.println("Accept Values");

try
{

Class.forName(“org.postgresql.Driver”);
con=DriverManager.getConnection(“jdbc:postgresql://192
.168.100.254/Bill”,”oracle”,”oracle”);

sql = "insert into Phone values(?,?,?,?)";


ps = con.prepareStatement(sql);

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

JOptionPane.showMessageDialog(null,"Record NOT inserted


");

}//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

/* Define a Student class (roll number, name,


percentage). Define a default and parameterized
constructor. Keep a count objects created.
Create objects using parameterized constructor and
display the object count after each object is created.
(Use static member and method). Also display the
contents of each object.
*/

import java.io.*;
class Slip21_1
{
int rollno;
String name;
float percent;

static void sortStudent(Slip21_1[]studentArray,int n)


{
Slip21_1 temp;
for(int i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)

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.*;

public class testdemo extends HttpServlet


{
int x=0,cnt=0,y=0;
Connection con;
Statement st;
Random r1;
public void init()
{
try
{

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

r1= new Random();


x= r1.nextInt(10);
y=x;
try
{
ResultSet rs=st.executeQuery("select * from quest where
qno="+x);
if(rs.next())
{
String x2=rs.getString(7);
pw.println("<html><body><form
action=http://localhost:8080/setb2.jsp>");
//pw.println("<div id=one
value="+rs.getString(2)+"></div>");
//pw.println("<input type=text size=50 name=text1
value="+rs.getString(2)+"/><br>");
pw.println("<textarea width=60
height=20>"+rs.getString(2)+"</textarea><br>");
pw.println("<input type=radio name=r2
value="+rs.getString(3)+">"+rs.getString(3)+"<br>");
pw.println("<input type=radio name=r2
value="+rs.getString(4)+">"+rs.getString(4)+"<br>");
pw.println("<input type=radio name=r2
value="+rs.getString(5)+">"+rs.getString(5)+"<br>");
pw.println("<input type=radio name=r2
value="+rs.getString(6)+">"+rs.getString(6)+"<br>");
pw.println("<input type=submit value=next
name=submit1/>");
pw.println("<input type=submit value=total score
name=submit2/>");
pw.println("</form></body></html>");
}
}
catch(Exception e){}
}

}
slip 22.1

/* Write a menu driven program to perform following


operations. Accept operation accept the two number using
input dialog box. GCD will compute the GCD of two numbers
and display in the message box and power operation will
calculate the value of an and display it in message box
where “a” and “n” are two inputted values.
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;

class Slip22_1 extends JFrame implements ActionListener


{
JMenu m1,m2;
JMenuBar mb;
JMenuItem m[];

StringBuffer ss=new StringBuffer();

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++)
{

if(n1%i==0 && n2%i==0)

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

/*Slip 23_1. Create an interface”CreditCardInterface”


with methods: viewcreditamount(),PayCard(). Create a
class “silverCardCustomer”(name, cardnumber)(16 digit),
creditamount-initialized to 0, credit limit set to
50,000) which implement above interface. Inherit class
GoldCardCustomer from SilverCardCustomer having same
method but creditLimit of 1,00,000. Create an object of
each class and perform operations. Display appropriate
message for success or failure of transaction. ( use
method overriding)

a.useCard() method increase the credit amount by a


specific amount upto creditLimit.
b.payCredit() reduces the credit Amount by a specific
amount.
c. increaseLimit() increase the credit limit for
GoldCardCustomer (only 3 times, not mor than 5000 rupees
each time.)
*/

import java.io.*;
interface CreditCard
{
void viewCreditAmount();
void increaseLimit()throws IOException;
void useCard()throws IOException ;
void payCard()throws IOException;
}

class SliverCardCustomer implements CreditCard


{
String name;
int card_no ;
double creditAmount;
double creaditLimit;
static int cnt;
BufferedReader br=new BufferedReader(new
BufferedReader(new InputStreamReader(System.in)));

SliverCardCustomer()
{
name="Noname" ;
card_no=0;
creditAmount=0;
creaditLimit=50000;
}

public void viewCreditAmount()


{

System.out.println("Your amount is : "+creditAmount) ;


}

public void getdata()throws IOException


{

System.out.println("Enter the name : ");


String name=(br.readLine());

System.out.println("Enter the card number :");

card_no=Integer.parseInt(br.readLine());

System.out.println("Enter Credit amount : ");

creditAmount=Double.parseDouble(br.readLine());
}

public void payCard()throws IOException


{

System.out.println("Enter amount to be pay");


double pay=Double.parseDouble(br.readLine()) ;

creditAmount=creditAmount+pay;

System.out.println("Balance is paid");
}
public void useCard()throws IOException
{

System.out.println("Enter amount : ");


double amount=Double.parseDouble(br.readLine());

if(amount<creditAmount)
{

creditAmount=creditAmount-amount;

viewCreditAmount();

System.out.println("Thanks for using the service") ;


}
else
System.out.println("\nerror!");
}

public void increaseLimit()throws IOException


{
cnt++;
if(cnt<=3)
{

System.out.println("Enter amount limit to increse : ");


double amt=Double.parseDouble(br.readLine());
if(amt<=2500)
{

creaditLimit=creaditLimit+amt;

System.out.println("Amount limit to increse


Successfully : ");
}

System.out.println("You can't increse creadit amount


more than 2500 at a time ");

}
else

System.out.println("You can't increse limit more than 3


times ");
}
}//end of class

class GoldCardCustomer extends SliverCardCustomer


{
static int cnt;
public void increaseLimit()throws IOException
{
cnt++;
if(cnt<=3)
{

System.out.println("Enter amount limit to increse : ");


double amt=Double.parseDouble(br.readLine());

if(amt<=5000)
{

creaditLimit=creaditLimit+amt;
System.out.println("Amount limit to increse
Successfully : ");
}

System.out.println("You can't increse creadit amount


more than 2500 at a time ");

}
else

System.out.println("You can't increse limit more than 3


times ");
}

}
class Slip23_1
{
public static void main(String
args[])throws IOException
{
int ch ;
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));

System.out.println("Enter the info for silver card


holder : ");

SliverCardCustomer sc=new SliverCardCustomer();


sc.getdata();

System.out.println("Enter the info for Gold card holder


: ");

GoldCardCustomer gc=new GoldCardCustomer();


gc.getdata();
do
{

System.out.println("1.Use silver card \n2.Pay credit for


Silver card\n3.Increse limit for silver card ") ;

System.out.println("4.Use Gold card \n5.Pay credit for


Gold card\n6.Increse limit for Gold card ") ;

System.out.println("0. exit") ;

System.out.println("Enter your choice : ") ;

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("\nDate : "+dd+"\nTime : "+h+" : "+m+"


: "+s);

String path = request.getContextPath();


out.println("\nPath : "+path);

Cookie cookie = new Cookie("p", path);


response.addCookie(cookie);
out.println("\nCookie Added");

out.println("\nConfig");
out.println("\n"+config.getServletName());
out.println("\nApplication : ");
out.println("\n"+application.getServerInfo());
%>
slip 24.1

/*Slip 24_1. create a super class vehicle having members


company and price. Drive two different classes
LightMotorVehicle(mileage) and heavyMoterVehicle
(Capacity_in_tons). Accept the information for ‘n’
vehicle and .display the information in appropriate form
while taking data, ask user about the type of vehicle
first.
*/

import java.io.*;
class Vehicle
{
String cname;
float price;

void accept() throws IOException


{
BufferedReader br = new
BufferedReader(new InputStreamReader(System.in));

System.out.println("Enter vehicle information");

System.out.println("Enter Company name : ");


cname= br.readLine();

System.out.println("Enter price : ");


price =
Float.parseFloat(br.readLine());
}

void display()
{
System.out.println("Company Name : "+cname+"\nPrice :
"+price);
}

class LightMotorVehicle extends Vehicle


{
int mileage;

void accept() throws IOException


{
BufferedReader br = new
BufferedReader(new InputStreamReader(System.in));

super.accept();

System.out.println("Enter mileage : ");


mileage =
Integer.parseInt(br.readLine());
}

void display()
{
super.display();

System.out.println("\nMileage : "+mileage);
}

class HeavyMotorVehicle extends Vehicle


{
int capacity;
void accept() throws IOException
{
BufferedReader br = new
BufferedReader(new InputStreamReader(System.in));

super.accept();

System.out.println("Enter capacity in tones : ");


capacity =
Integer.parseInt(br.readLine());
}

void display()
{
super.display();

System.out.println("\nCapacity int tones : "+capacity);


}

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

System.out.println("Enter type of vehicle \n1. for light


motor vehicle \n2. for heavy motor vehicle ");
int ch =
Integer.parseInt(br.readLine());
int no;
switch(ch)
{
case 1
:System.out.println("Enter no of light motor");

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

LightMotorVehicle lv[] = new LightMotorVehicle[no];

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

lv[i] = new LightMotorVehicle();

lv[i].accept();

System.out.println("Information of light motor are");

System.out.println("=======================");

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

//lv[i] = new LightMotorVehicle();

lv[i].display();

break;
case 2
:System.out.println("Enter no of heavy motor");
no = Integer.parseInt(br.readLine());

HeavyMotorVehicle hv[] = new HeavyMotorVehicle[no];

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

hv[i] = new HeavyMotorVehicle();

hv[i].accept();

System.out.println("Information of heavy motor are");

System.out.println("=======================");

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

//lv[i] = new LightMotorVehicle();

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.*;

public class testdemo extends HttpServlet


{
int x=0,cnt=0,y=0;
Connection con;
Statement st;
Random r1;
public void init()
{
try
{

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

r1= new Random();


x= r1.nextInt(10);
y=x;
try
{
ResultSet rs=st.executeQuery("select * from quest where
qno="+x);
if(rs.next())
{
String x2=rs.getString(7);
pw.println("<html><body><form
action=http://localhost:8080/setb2.jsp>");
//pw.println("<div id=one
value="+rs.getString(2)+"></div>");
//pw.println("<input type=text size=50 name=text1
value="+rs.getString(2)+"/><br>");
pw.println("<textarea width=60
height=20>"+rs.getString(2)+"</textarea><br>");
pw.println("<input type=radio name=r2
value="+rs.getString(3)+">"+rs.getString(3)+"<br>");
pw.println("<input type=radio name=r2
value="+rs.getString(4)+">"+rs.getString(4)+"<br>");
pw.println("<input type=radio name=r2
value="+rs.getString(5)+">"+rs.getString(5)+"<br>");
pw.println("<input type=radio name=r2
value="+rs.getString(6)+">"+rs.getString(6)+"<br>");
pw.println("<input type=submit value=next
name=submit1/>");
pw.println("<input type=submit value=total score
name=submit2/>");
pw.println("</form></body></html>");
}
}
catch(Exception e){}
}

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

Employee(int id, String name, String department, float


salary)
{
this.id = id;
this.name = name;
this.department = department;
this.salary = salary;
}

void accept() throws IOException


{
BufferedReader br = new
BufferedReader(new InputStreamReader(System.in));

System.out.println("Enter employee information: id,


name, department, salary");

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

class Manager extends Employee


{
private float bonus;

Manager()
{
super();
}
Manager(int id, String name, String department, float
salary, float bonus)
{
super(id, name, department, salary);
this.bonus = bonus;
}

void accept() throws IOException


{
BufferedReader br = new
BufferedReader(new InputStreamReader(System.in));

super.accept();

System.out.println("Enter bonus : ");


bonus = Float.parseFloat(br.readLine());
}

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

System.out.println("Enter Number Of Employees: ");


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

Manager mn[] = new Manager[no];


for(int i = 0 ; i < no; i++)
{
mn[i] = new Manager();

mn[i].accept();
}

calculate_salary(mn,no);
}

static void calculate_salary(Manager mn[],int n)


{
int index = 0;
float sal[] = new float[n];

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


{
sal[i] = mn[i].getsalary() + mn[i].getbonus();

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

if(sal[i] > max)


{
max = sal[i];

index = i;
}
}

System.out.println("Employee with max salary is: ");


mn[index].display();
}
}
slip 25.2
Write a program to create a shopping mall. User must be allowed to do
purchase from two pages. Each page should have a page total. The third
page should display a bill, which consists of page total of whatever the
purchase has been done and print the total. (Use HttpSession). [30]

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

You might also like