Java Solved Slips For Practical

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

java slips

slip 1-
sem1
Create an abstract class shape .Derive three classes sphere, cone and cylinder from
it .Calculate area and volume of all (use method overriding)
/*
sphere =>4*3.14*r*r
cone=>4*3.14*h
cylinder=>2*3.14*r*h
box=>l*b
sphere volume=>4/3*3.14*r*r*r
cylinder 3.14*r*r*h
box=>l*b*h
*/

import java.util.*;
abstract class Shape
{
static double pi=3.14;
public abstract double cal_area();
public abstract double cal_volume();
}

class Sphere extends Shape


{
double r;

Sphere()
{

}
Sphere(double r)
{
this.r=r;
}
public double cal_area()
{
return(4*pi*r*r);
}
public double cal_volume()
{
double vol;
vol=(4/3)*pi*r*r*r;
return vol;
}
}
class Cone extends Shape
{
double h;
double r;

Scanner s=new Scanner(System.in);


Cone()
{

}
Cone(double h,double r)
{
this.h=h;
this.r=r;
}
public double cal_area()
{
return(4*pi*h);
}
public double cal_volume()
{
return(0.33*pi*r*r*h);
}
}
class Cylinder extends Shape
{
double h;
double r;
Cylinder()
{

}
Cylinder(double h,double r)
{
this.h=h;
this.r=r;
}
public double cal_area()
{
return(2*3.14*r*h);
}
public double cal_volume()
{
return(3.14*r*r*h);
}
}
class shapeDemo
{
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
double r;
double h;
System.out.println("Enter the radius :: ");
r=s.nextDouble();
System.out.println("Enter the height :: ");

h=s.nextDouble();
Sphere s1=new Sphere(r);
System.out.println("\n**** For Sphere****\n");
System.out.println("The Area of Sphere is :: "+s1.cal_area());
System.out.println("The Volume of Sphere is :: "+s1.cal_volume());

Cone c1=new Cone(h,r);


System.out.println("\n**** For Cone****\n");
System.out.println("The Area of Cone is :: "+c1.cal_area());
System.out.println("The Volume of Cone is :: "+c1.cal_volume());

Cylinder c2=new Cylinder(h,r);


System.out.println("\n**** For Cylinder****\n");
System.out.println("The Area of Cone is :: "+c2.cal_area());
System.out.println("The Volume of Cone is :: "+c2.cal_volume());
System.out.println("**************************************");

}
}

output:
[root@localhost gitanjalee]# java ShapeDemo

Enter the radius ::


5
Enter the height ::
5
Enter the length ::
5
Enter the breadth ::
5

**** For Sphere****

The Area of Sphere is :: 314.0


The Volume of Sphere is :: 392.5

**** For Cone****

The Area of Cone is :: 62.800000000000004


The Volume of Cone is :: 129.525

**** For Cylinder****

The Area of Cone is :: 157.0


The Volume of Cone is :: 392.5
**************************************

**** For Box****

The Area of Box is :: 250.0


The Volume of Box is :: 125.0
************
[root@localhost gitanjalee]#

sem 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.
*************************************************/
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class hobbie extends HttpServlet


{

public void doPost(HttpServletRequest req,HttpServletResponse res)


{
try
{
String data=req.getParameter("hobby");
res.setContentType("text/html");
PrintWriter pw=res.getWriter();
pw.println("<html>");
pw.println("<body>");

Cookie []cookies=req.getCookies();
if(cookies !=null)
{
pw.println("Existing Cookies :");
for(int i=0;i<cookies.length;i++)
{
String name=cookies[i].getName();
String value=cookies[i].getValue();
pw.println("Name = "+name+" Value= "+value+"<br>");
}
for(int i=0;i<cookies.length;i++)
{
if(cookies[i].getValue().equals(data))
{
pw.println("Cookis Exists for "+data);

}
}
}
Cookie c=new Cookie("hobby",data);
c.setMaxAge(6000);
res.addCookie(c);
pw.println("cookie added for Hobby"+data);
pw.println("</body> </html>");
}catch(Exception e){}
}
}

hobby.html
<html>
<body>
<form action=hobbie method=post>
<input type=radio name=hobby value=Painting>Painting<br>

<input type=radio name=hobby value=Drawing>Drawing<br>

<input type=radio name=hobby value=Singing>Singing<br>

<input type=radio name=hobby value=Swimming>Swimming<br>


<br><br>

<input type=submit value=Next>


</form>
</body>
</html>
slip 2
sem1
Write a menu driven program to perform the following operations on a set of
integers as shown in the following figure. The load operation should generate 10
random integers (2 digits ) and display the number on the screen .The save
operation should save the numbers to a file “numbers.txt”. The Sort 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 Numbers implements ActionListener,ItemListener


{
JFrame f;
JMenu m1,m2,m3,m4;
JMenuBar mb;
JMenuItem m[];
JRadioButtonMenuItem r1,r2;
ButtonGroup b;
JLabel l;
JTextField t;
JPanel p;
StringBuffer ss=new StringBuffer();
int sel,n;
int arr[]=new int [20];
double res;

public Numbers()
{
f = new JFrame("Numbers");
sel=1;res=0;
p=new JPanel();
mb=new JMenuBar();
m1=new JMenu("File");
m2=new JMenu("Compute");
m3=new JMenu("Operation");
m4=new JMenu("Sort");
l=new JLabel("Numbers");
t=new JTextField(20);
b=new ButtonGroup();
r1=new JRadioButtonMenuItem("Ascending");
r1.addItemListener(this);
r2=new JRadioButtonMenuItem("Descending");
r2.addItemListener(this);
b.add(r1);b.add(r2);
String
str[]={"Load","Save","Exit","Sum","Average","Maximum","Minimum","Median","Search"};
m=new JMenuItem[str.length];
for(int i=0;i<str.length;i++)
{
m[i]=new JMenuItem(str[i]);
m[i].addActionListener(this);
}
f.setLayout(new BorderLayout());
p.add(l);
p.add(t);
f.add(p,BorderLayout.CENTER);

mb.add(m1);
mb.add(m2);
mb.add(m3);
m1.add(m[0]);
m1.add(m[1]);
m1.addSeparator();
m1.add(m[2]);
m2.add(m[3]);
m2.add(m[4]);
m2.add(m[5]);
m2.add(m[6]);
m2.add(m[7]);
m3.add(m[8]);
m3.add(m4);
m4.add(r1);
m4.add(r2);

f.add(mb,BorderLayout.NORTH);
f.setSize(300,200);
f.setVisible(true);
f.setLocation(500,200);
f.setDefaultCloseOperation(3);

public void itemStateChanged(ItemEvent ii)


{
if(r1.isSelected())
{
sortasc();
}

else if(r2.isSelected())
{
sortdesc();
}

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

}
public 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();
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("num.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("Sum"))
{
t.setText(new Integer(givesum()).toString());
}
else if(s.equals("Average"))
{
t.setText(new Double(giveavg()).toString());
}
else if(s.equals("Maximum"))
{
t.setText(new Integer(givemax()).toString());
}
else if(s.equals("Minimum"))
{
t.setText(new Integer(givemin()).toString());
}
else if(s.equals("Median"))
{
t.setText(new Integer(givemed()).toString());
}
else if(s.equals("Save"))
{

char ch;
String sss = t.getText();
try{
FileOutputStream br1 = new FileOutputStream("number.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("Search"))
{
int ser=Integer.parseInt(JOptionPane.showInputDialog("Enter Number To Search"));
int a=0;
for(int i=0;i<n;i++)
{
if(arr[i]==ser)
{
t.setText("Number Present");
a=1;
}
if(a==0)
t.setText("Number Not Present");
}
}

}
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 int givemax()
{
int sum=arr[0];
for(int i=0;i<n;i++)
{
if(arr[i] > sum)
sum=arr[i];
}
return sum;
}
public int givemin()
{
int sum=arr[0];
for(int i=0;i<n;i++)
{
if(arr[i] < sum)
sum=arr[i];
}
return sum;
}

public int givemed()


{
return arr[(n/2)];
}

public static void main(String arg[])


{
new Numbers();
}
}
/*Output
[student@localhost ~]$ javac Numbers.java
[student@localhost ~]$ java Numbers*/

sem 2
Accept “n” integers from the user and store them in a collection .Display them in
the sorted order .The collection should not accept duplicate elements (Use suitable
collection ).search for a particular element using predefined search method in the
collection framework .
/*---------------------------------------------------------------------------------------
1. Accept n integers from the user and store them in a collection. Display them in the
sorted order. The collection should not accept duplicate elements. (Use a suitable
collection).
------------------------------------------------------------------------------------------*/

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

class collection1
{
public static void main(String[] args) throws Exception
{
int num,ele,i;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
ArrayList al=new ArrayList();
System.out.println("Enter the no for how many element to have:");
num=Integer.parseInt(br.readLine());
for(i=0;i<num;i++)
{
System.out.println("Enter the elements in position:"+i);
ele=Integer.parseInt(br.readLine());
al.add(ele);
}

System.out.println("The elements of ArrayList before:"+al);


Collections.sort(al);
System.out.println("The elements of ArrayList after sort:"+al);
}
}
/*------------------------------output----------
[root@localhost ~]# java collection1
Enter the no for how many element to have:
5
Enter the elements in position:0
5
Enter the elements in position:1
3
Enter the elements in position:2
7
Enter the elements in position:3
2
Enter the elements in position:4
8
The elements of ArrayList before:[5, 3, 7, 2, 8]
The elements of ArrayList after sort:[2, 3, 5, 7, 8]
-------------------------------------------------------*/
slip 3
sem 1-
Define a class My Date (Day,Month,Year) with methods to accept and display a
My Date object . Accept date as dd , mm,yyyy . Throw user defined exception
“Invalid Date Exception” if the date is invalid .

Examples of invalid dates:

a. 12 15 2015

b. 31 6 1990

c .29 2 2015
import java.io.*;

class InvalidDayException extends Exception


{
InvalidDayException()
{
System.out.println("You Entered Invalid Day ........");
}
}
class InvalidMonthException extends Exception
{
InvalidMonthException()
{
System.out.println("You Entered Invalid Month ........");
}
}
class MyClass
{
int day,mon,yr;
MyClass()
{
day=1;
mon=1;
yr=1991;
}
MyClass(int a, int b, int c)
{
day=a;
mon=b;
yr=c;
System.out.println("You Entered Valid date...");
System.out.println(day+"-"+mon+"-"+yr);
}
}

class set4b1
{
public static void main(String args[]) throws IOException
{
//BufferedReader bf= new BufferedReader(new InputStreamReader(System.in));
try
{

int c = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
int a = Integer.parseInt(args[2]);
boolean leap=(c%400==0) || (c%4==0) && (c%100!=0);

if(b<13&&b>0)
{
}
else
throw new InvalidMonthException();

if(b==1||b==3||b==5||b==7||b==8||b==10||b==12)
{
if(a<32 &&a>0)
{
}
else
throw new InvalidDayException();
}

else if(b==4||b==6||b==9||b==11)
{
if(a<31&&a>0)
{
System.out.println("Accepted....");
}
else
throw new InvalidDayException();
}
else
{
if(leap && a>29)
{
System.out.println("Accepted.....");
}
else
throw new InvalidDayException();
}

MyClass m= new MyClass(a,b,c);


}
catch(InvalidMonthException m)
{
}
catch(InvalidDayException d)
{
}
}
}
/*---------------------------------------------
output =
[user@localhost ~]$ javac set4b1.java
[user@localhost ~]$ java set4b1 1991 6 23
Accepted....
You Entered Valid date...
23-6-1991
[user@localhost ~]$ java set4b1 1991 23 6
You Entered Invalid Month ........
[user@localhost ~]$ java set4b1 1991 6 31
You Entered Invalid Day ........
[user@localhost ~]$
*/
sem 2
Accept “n” integers from the user and store them in a collection .Display them in
the sorted order .The collection should not accept duplicate elements (Use suitable
collection ).search for a particular element using predefined search method in the
collection framework .
/*---------------------------------------------------------------------------------------
1. Accept n integers from the user and store them in a collection. Display them in the
sorted order. The collection should not accept duplicate elements. (Use a suitable
collection).
------------------------------------------------------------------------------------------*/

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

class collection1
{
public static void main(String[] args) throws Exception
{
int num,ele,i;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
ArrayList al=new ArrayList();
System.out.println("Enter the no for how many element to have:");
num=Integer.parseInt(br.readLine());
for(i=0;i<num;i++)
{
System.out.println("Enter the elements in position:"+i);
ele=Integer.parseInt(br.readLine());
al.add(ele);
}

System.out.println("The elements of ArrayList before:"+al);


Collections.sort(al);
System.out.println("The elements of ArrayList after sort:"+al);
}
}
/*------------------------------output----------
[root@localhost ~]# java collection1
Enter the no for how many element to have:
5
Enter the elements in position:0
5
Enter the elements in position:1
3
Enter the elements in position:2
7
Enter the elements in position:3
2
Enter the elements in position:4
8
The elements of ArrayList before:[5, 3, 7, 2, 8]
The elements of ArrayList after sort:[2, 3, 5, 7, 8]
-------------------------------------------------------*/
slip 4:
sem 1
Write a menu driven program to perform the following operations on a set of
integers as shown in the following figure. The load operation should generate 10
random integers (2 digits ) and display the number on the screen .The save
operation should save the numbers to a file “numbers.txt”. The Sort 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 Numbers implements ActionListener,ItemListener


{
JFrame f;
JMenu m1,m2,m3,m4;
JMenuBar mb;
JMenuItem m[];
JRadioButtonMenuItem r1,r2;
ButtonGroup b;
JLabel l;
JTextField t;
JPanel p;
StringBuffer ss=new StringBuffer();
int sel,n;
int arr[]=new int [20];
double res;

public Numbers()
{
f = new JFrame("Numbers");
sel=1;res=0;
p=new JPanel();
mb=new JMenuBar();
m1=new JMenu("File");
m2=new JMenu("Compute");
m3=new JMenu("Operation");
m4=new JMenu("Sort");
l=new JLabel("Numbers");
t=new JTextField(20);
b=new ButtonGroup();
r1=new JRadioButtonMenuItem("Ascending");
r1.addItemListener(this);
r2=new JRadioButtonMenuItem("Descending");
r2.addItemListener(this);
b.add(r1);b.add(r2);
String
str[]={"Load","Save","Exit","Sum","Average","Maximum","Minimum","Median","Search"};
m=new JMenuItem[str.length];
for(int i=0;i<str.length;i++)
{
m[i]=new JMenuItem(str[i]);
m[i].addActionListener(this);
}
f.setLayout(new BorderLayout());
p.add(l);
p.add(t);
f.add(p,BorderLayout.CENTER);

mb.add(m1);
mb.add(m2);
mb.add(m3);
m1.add(m[0]);
m1.add(m[1]);
m1.addSeparator();
m1.add(m[2]);
m2.add(m[3]);
m2.add(m[4]);
m2.add(m[5]);
m2.add(m[6]);
m2.add(m[7]);
m3.add(m[8]);
m3.add(m4);
m4.add(r1);
m4.add(r2);

f.add(mb,BorderLayout.NORTH);
f.setSize(300,200);
f.setVisible(true);
f.setLocation(500,200);
f.setDefaultCloseOperation(3);

}
public void itemStateChanged(ItemEvent ii)
{
if(r1.isSelected())
{
sortasc();
}

else if(r2.isSelected())
{
sortdesc();
}

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

}
public 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();
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("num.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("Sum"))
{
t.setText(new Integer(givesum()).toString());
}
else if(s.equals("Average"))
{
t.setText(new Double(giveavg()).toString());
}
else if(s.equals("Maximum"))
{
t.setText(new Integer(givemax()).toString());
}
else if(s.equals("Minimum"))
{
t.setText(new Integer(givemin()).toString());
}
else if(s.equals("Median"))
{
t.setText(new Integer(givemed()).toString());
}
else if(s.equals("Save"))
{

char ch;
String sss = t.getText();
try{
FileOutputStream br1 = new FileOutputStream("number.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("Search"))
{
int ser=Integer.parseInt(JOptionPane.showInputDialog("Enter Number To Search"));
int a=0;
for(int i=0;i<n;i++)
{
if(arr[i]==ser)
{
t.setText("Number Present");
a=1;
}
if(a==0)
t.setText("Number Not Present");
}
}

}
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 int givemax()
{
int sum=arr[0];
for(int i=0;i<n;i++)
{
if(arr[i] > sum)
sum=arr[i];
}
return sum;
}
public int givemin()
{
int sum=arr[0];
for(int i=0;i<n;i++)
{
if(arr[i] < sum)
sum=arr[i];
}
return sum;
}
public int givemed()
{
return arr[(n/2)];
}

public static void main(String arg[])


{
new Numbers();
}
}

/*Output
[student@localhost ~]$ javac Numbers.java
[student@localhost ~]$ java Numbers*/
sem 2
Accept “n” integers from the user and store them in a collection .Display them in
the sorted order .The collection should not accept duplicate elements (Use suitable
collection ).search for a particular element using predefined search method in the
collection framework .
/*---------------------------------------------------------------------------------------
1. Accept n integers from the user and store them in a collection. Display them in the
sorted order. The collection should not accept duplicate elements. (Use a suitable
collection).
------------------------------------------------------------------------------------------*/

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

class collection1
{
public static void main(String[] args) throws Exception
{
int num,ele,i;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
ArrayList al=new ArrayList();
System.out.println("Enter the no for how many element to have:");
num=Integer.parseInt(br.readLine());
for(i=0;i<num;i++)
{
System.out.println("Enter the elements in position:"+i);
ele=Integer.parseInt(br.readLine());
al.add(ele);
}

System.out.println("The elements of ArrayList before:"+al);


Collections.sort(al);
System.out.println("The elements of ArrayList after sort:"+al);
}
}
/*------------------------------output----------
[root@localhost ~]# java collection1
Enter the no for how many element to have:
5
Enter the elements in position:0
5
Enter the elements in position:1
3
Enter the elements in position:2
7
Enter the elements in position:3
2
Enter the elements in position:4
8
The elements of ArrayList before:[5, 3, 7, 2, 8]
The elements of ArrayList after sort:[2, 3, 5, 7, 8]
-------------------------------------------------------*/
slip 5
sem1
Define a class Saving Account (acno ,name ,balance ). Define appropriate
constructors and operation withdraw (), Deposit ()and viewbalance ().the
minimum balance must be 500 .Create an object and perform operations .Raise
user defined “Insufficient Funds Exception” when balance is not sufficient for
withdraw operation .
import java.util.*;

class InsufficientFundsException extends Exception


{

}
class savingAccount
{
long acNo;
String name;
double balance=500;
Scanner s=new Scanner(System.in);

savingAccount(){}
savingAccount(long acNo,String name)
{
this.acNo= acNo;
this.name=name;
}
void viewBalance()
{
System.out.println("Current Balance :: "+balance);
}
void withdraw() throws InsufficientFundsException
{
System.out.println("Enter the amount to withdraw :: ");
double amt=s.nextDouble();

if((balance-amt)<500)
{
throw new InsufficientFundsException();
//System.out.println("Current Balance :: "+balance);
}
else
{
balance=balance-amt;
System.out.println("Current Balance after withdrwal :: "+balance);
}
}
void deposit()
{
System.out.println("Enter the amount to deposit :: ");
double amt=s.nextDouble();
balance=balance+amt;
}

public static void main(String[] args)


{
int ch=1,op;
savingAccount sa=new savingAccount(648373569,"Ashwini");
Scanner s=new Scanner(System.in);

do
{
System.out.println("Enter\n1.View Balance\n2.Deposit\n3.Withdraw\n");
op=s.nextInt();
switch(op)
{
case 1:
sa.viewBalance();
break;
case 2:
sa.deposit();
break;
case 3:
try
{
sa.withdraw();
}
catch(InsufficientFundsException e)
{
System.out.println(" Insufficient Funds \n");
}
break;
}
System.out.println("Enter 1 to Continue \n2 to exit :: ");
ch=s.nextInt();
}while(ch!=2);

}
}

sem 2
Accept “n” integers from the user and store them in a collection .Display them in
the sorted order .The collection should not accept duplicate elements (Use suitable
collection ).search for a particular element using predefined search method in the
collection framework .
/*---------------------------------------------------------------------------------------
1. Accept n integers from the user and store them in a collection. Display them in the
sorted order. The collection should not accept duplicate elements. (Use a suitable
collection).
------------------------------------------------------------------------------------------*/

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

class collection1
{
public static void main(String[] args) throws Exception
{
int num,ele,i;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
ArrayList al=new ArrayList();
System.out.println("Enter the no for how many element to have:");
num=Integer.parseInt(br.readLine());
for(i=0;i<num;i++)
{
System.out.println("Enter the elements in position:"+i);
ele=Integer.parseInt(br.readLine());
al.add(ele);
}

System.out.println("The elements of ArrayList before:"+al);


Collections.sort(al);
System.out.println("The elements of ArrayList after sort:"+al);
}
}
/*------------------------------output----------
[root@localhost ~]# java collection1
Enter the no for how many element to have:
5
Enter the elements in position:0
5
Enter the elements in position:1
3
Enter the elements in position:2
7
Enter the elements in position:3
2
Enter the elements in position:4
8
The elements of ArrayList before:[5, 3, 7, 2, 8]
The elements of ArrayList after sort:[2, 3, 5, 7, 8]
-------------------------------------------------------*/
slip 6
sem 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.
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:");
lblDec=new JLabel("Binary Number:");
lblDec=new JLabel("Octal Number:");
lblDec=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();
}
}

sem 2
Accept “n” integers from the user and store them in a collection .Display them in
the sorted order .The collection should not accept duplicate elements (Use suitable
collection ).search for a particular element using predefined search method in the
collection framework .
/*---------------------------------------------------------------------------------------
1. Accept n integers from the user and store them in a collection. Display them in the
sorted order. The collection should not accept duplicate elements. (Use a suitable
collection).
------------------------------------------------------------------------------------------*/

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

class collection1
{
public static void main(String[] args) throws Exception
{
int num,ele,i;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
ArrayList al=new ArrayList();
System.out.println("Enter the no for how many element to have:");
num=Integer.parseInt(br.readLine());
for(i=0;i<num;i++)
{
System.out.println("Enter the elements in position:"+i);
ele=Integer.parseInt(br.readLine());
al.add(ele);
}

System.out.println("The elements of ArrayList before:"+al);


Collections.sort(al);
System.out.println("The elements of ArrayList after sort:"+al);
}
}
/*------------------------------output----------
[root@localhost ~]# java collection1
Enter the no for how many element to have:
5
Enter the elements in position:0
5
Enter the elements in position:1
3
Enter the elements in position:2
7
Enter the elements in position:3
2
Enter the elements in position:4
8
The elements of ArrayList before:[5, 3, 7, 2, 8]
The elements of ArrayList after sort:[2, 3, 5, 7, 8]
-------------------------------------------------------*/
slip 7
sem1
Create an abstract class shape .Derive three classes sphere, cone and cylinder from
it .Calculate area and volume of all (use method overriding)
/*
sphere =>4*3.14*r*r
cone=>4*3.14*h
cylinder=>2*3.14*r*h
box=>l*b
sphere volume=>4/3*3.14*r*r*r
cylinder 3.14*r*r*h
box=>l*b*h
*/

import java.util.*;
abstract class Shape
{
static double pi=3.14;
public abstract double cal_area();
public abstract double cal_volume();
}

class Sphere extends Shape


{
double r;

Sphere()
{

}
Sphere(double r)
{
this.r=r;
}
public double cal_area()
{
return(4*pi*r*r);
}
public double cal_volume()
{
double vol;
vol=(4/3)*pi*r*r*r;
return vol;
}
}
class Cone extends Shape
{
double h;
double r;

Scanner s=new Scanner(System.in);


Cone()
{

}
Cone(double h,double r)
{
this.h=h;
this.r=r;
}
public double cal_area()
{
return(4*pi*h);
}
public double cal_volume()
{
return(0.33*pi*r*r*h);
}
}
class Cylinder extends Shape
{
double h;
double r;
Cylinder()
{

}
Cylinder(double h,double r)
{
this.h=h;
this.r=r;
}
public double cal_area()
{
return(2*3.14*r*h);
}
public double cal_volume()
{
return(3.14*r*r*h);
}
}
class shapeDemo
{
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
double r;
double h;
System.out.println("Enter the radius :: ");
r=s.nextDouble();
System.out.println("Enter the height :: ");

h=s.nextDouble();
Sphere s1=new Sphere(r);
System.out.println("\n**** For Sphere****\n");
System.out.println("The Area of Sphere is :: "+s1.cal_area());
System.out.println("The Volume of Sphere is :: "+s1.cal_volume());

Cone c1=new Cone(h,r);


System.out.println("\n**** For Cone****\n");
System.out.println("The Area of Cone is :: "+c1.cal_area());
System.out.println("The Volume of Cone is :: "+c1.cal_volume());

Cylinder c2=new Cylinder(h,r);


System.out.println("\n**** For Cylinder****\n");
System.out.println("The Area of Cone is :: "+c2.cal_area());
System.out.println("The Volume of Cone is :: "+c2.cal_volume());
System.out.println("**************************************");

}
}

output:

[root@localhost gitanjalee]# java ShapeDemo


Enter the radius ::
5
Enter the height ::
5
Enter the length ::
5
Enter the breadth ::
5

**** For Sphere****

The Area of Sphere is :: 314.0


The Volume of Sphere is :: 392.5

**** For Cone****

The Area of Cone is :: 62.800000000000004


The Volume of Cone is :: 129.525

**** For Cylinder****

The Area of Cone is :: 157.0


The Volume of Cone is :: 392.5
**************************************

**** For Box****

The Area of Box is :: 250.0


The Volume of Box is :: 125.0
************
[root@localhost gitanjalee]#

sem 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 .

a. Insert
b. Modify
c. Delete
d. Search
e. View All
f. Exit
/************************************************************************************
ASSIGNMENT 3 Set B Q (1)

Q 1. Write a menu driven program to perform the following operations on student table.
1. Insert 2. Modify 3. Delete 4. Search 5. View All 6. Exit
**************************************************************************************/

import java.io.*;
import java.sql.*;

public class studentrecord


{
public static void main(String a[])
{
Connection con=null;
PreparedStatement ps=null;
Statement stmt=null;
ResultSet rs=null;

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

Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection
("jdbc:mysql://localhost/student","root","");

while(true)
{

System.out.println("1.Insert");
System.out.println("2.Modify");
System.out.println("3.Delete");
System.out.println("4.View all");
System.out.println("5.Search");
System.out.println("6.Exit");

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

switch(ch)
{
case 1:
ps=con.prepareStatement
("insert into student values(?,?,?)");

System.out.println("Enter Roll Name Per:");

ps.setInt(1,Integer.parseInt(br.readLine()));
ps.setString(2,br.readLine());
ps.setInt(3,Integer.parseInt(br.readLine()));
ps.executeUpdate();
break;

case 2:
ps=con.prepareStatement
("update student set per=? where roll_no=?");

System.out.println("Enter new per & Roll_no :");


ps.setInt(1,Integer.parseInt(br.readLine()));
ps.setInt(2,Integer.parseInt(br.readLine()));
ps.executeUpdate();
break;

case 3:
ps=con.prepareStatement
("delete from student where roll_no=?");
System.out.println("Enter Roll_no :");
ps.setInt(1,Integer.parseInt(br.readLine()));
ps.executeUpdate();
break;
case 4:
ps=con.prepareStatement("select * from student");
rs=ps.executeQuery();
while(rs.next())
{
System.out.print(rs.getInt("roll_no")+"\t");
System.out.print(rs.getString("sname")+"\t");
System.out.print(rs.getInt("per")+"\n");
}
break;
case 5:
System.out.print("Enter Rollno to Search:");
int rno = Integer.parseInt(br.readLine());
ps=con.prepareStatement
("select * from student where roll_no=?");
ps.setInt(1,rno);
rs=ps.executeQuery();
while(rs.next())
{
System.out.print(rs.getInt("roll_no")+"\t");
System.out.print(rs.getString("sname")+"\t");
System.out.print(rs.getInt("per")+"\n");
}
break;
case 6:
con.close();
System.exit(0);

}//end of switch
}//end of while
}//end of try
catch(Exception e){}
}//end of class

}//end of main()

/************output*************
[root@localhost JDBC]# java studentrecord
1.Insert
2.Modify
3.Delete
4.View all
5.Search
6.Exit
1
Enter Roll Name Per:
622
Anand
74
1.Insert
2.Modify
3.Delete
4.View all
5.Search
6.Exit
1
Enter Roll Name Per:
519
Gaurav
75
1.Insert
2.Modify
3.Delete
4.View all
5.Search
6.Exit
1
Enter Roll Name Per:
508
Neeeraj
75
1.Insert
2.Modify
3.Delete
4.View all
5.Search
6.Exit
1
Enter Roll Name Per:
619
Anil
76
1.Insert
2.Modify
3.Delete
4.View all
5.Search
6.Exit
4
622 ANAND 74
519 GAURAV 75
622 Anand 74
519 Gaurav 75
508 Neeeraj 75
619 Anil 76
1.Insert
2.Modify
3.Delete
4.View all
5.Search
6.Exit
2
Enter new per & Roll_no :
78
622
1.Insert
2.Modify
3.Delete
4.View all
5.Search
6.Exit
4
622 ANAND 78
519 GAURAV 75
622 Anand 78
519 Gaurav 75
508 Neeeraj 75
619 Anil 76
1.Insert
2.Modify
3.Delete
4.View all
5.Search
6.Exit
3
Enter Roll_no :
508
1.Insert
2.Modify
3.Delete
4.View all
5.Search
6.Exit
4
622 ANAND 78
519 GAURAV 75
622 Anand 78
519 Gaurav 75
619 Anil 76
1.Insert
2.Modify
3.Delete
4.View all
5.Search
6.Exit
5
Enter Rollno to Search:622
622 ANAND 78
622 Anand 78
1.Insert
2.Modify
3.Delete
4.View all
5.Search
6.Exit
6
***********************************************************************************/
slip 8
sem1:-
Write a program to create the following GUI and apply the changes to the text in
the TextField .
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class FontDemo extends JFrame{


private JLabel lblFont,lblSize,lblStyle;
private JComboBox cmbFont,cmbSize;
private JCheckBox cbBold,cbItalic;
private JTextField txtMsg;

private int valItalic = Font.PLAIN, valBold = Font.BOLD;

public FontDemo(){
lblFont = new JLabel("Font");
lblSize = new JLabel("Size");
lblStyle = new JLabel("Style");

String fontName[] = GraphicsEnvironment.getLocalGraphicsEnvironment().


getAvailableFontFamilyNames();

cmbFont = new JComboBox();

for(int i=0;i<fontName.length;i++)
cmbFont.addItem(fontName[i]);

cmbSize = new JComboBox(new String[]{"5","6","7","8","9","10"});

cbBold = new JCheckBox("Bold");


cbItalic = new JCheckBox("Italic");

txtMsg = new JTextField(100);

lblFont.setBounds(10,10,70,25);
cmbFont.setBounds(10,40,170,25);
lblSize.setBounds(10,70,70,25);
cmbSize.setBounds(10,100,170,25);
txtMsg.setBounds(10,150,250,30);
lblStyle.setBounds(200,10,70,25);
cbBold.setBounds(200,40,70,25);
cbItalic.setBounds(200,70,70,25);

setTitle("Font Demo");
setLayout(null);
setSize(450,300);
add(lblFont);
add(cmbFont);
add(lblSize);
add(cmbSize);
add(txtMsg);
add(lblStyle);
add(cbBold);
add(cbItalic);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

cbBold.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent ie){
if(cbBold.isSelected())
valBold = Font.BOLD;
else
valBold = Font.PLAIN;
change();
}
});

cbItalic.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent ie){
if(cbItalic.isSelected())
valItalic = Font.ITALIC;
else
valItalic = Font.PLAIN;
change();
}
});

cmbFont.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent ie){
change();
}
});

cmbSize.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent ie){
change();
}
});
}

public void change(){


String fontName = cmbFont.getSelectedItem().toString();
int fontSize = Integer.parseInt(cmbSize.getSelectedItem().toString());
txtMsg.setFont(new Font(fontName, valBold+valItalic, fontSize));
}

public static void main(String args[]){


new FontDemo();
}
}
sem 2
Design 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 then display a massage “Welcome”. If
the user is revisiting the page ,then display the number of times page is visited
(Use Cookies)
/*-----------------------------------------------------------------------------------------
Asignment 5 set a3

Q3. 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 re-
visiting the page, display the number of times visited.

--------------------------------------------------------------------------------------------*/
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class count1 extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException
{

int j;
Cookie[] c=req.getCookies();
Cookie c1;
PrintWriter pw=res.getWriter();
res.setContentType("text/html");
if(c == null){
c1=new Cookie("count","1");
res.addCookie(c1);
j=1;
pw.println("VIEWING THE PAGE "+j+" TIME ");
}
else{
for(int i=0;i< c.length;i++)
{
if(c[i].getName().equals("count")){
c1=c[i];
j=Integer.parseInt(c1.getValue());
j++;
pw.println("VIEWING THE PAGE FOR :"+j+"time");
Integer o=new Integer(j);

c1.setValue(o.toString());
res.addCookie(c1);
}else{break;}

}
}

}
slip 9
sem1:-
Create an Applet which displays a massage in the center of the screen .The
massage indicates the events taking place on the applet window. Handle events like
mouse click ,mouse moves ,mouse dragged ,mouse pressed .The massage should
update each time an event occurs . The massage should give details of the event
such as which mouse button was pressed (Hint :Use repaint (),Mouse Listener ,
Mouse Motion Listener)
//Demonstrate Mouse Events.

import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*
<applet code="mouseeventsdemo" height=300 width=300>
</applet>
*/

public class mouseeventsdemo extends Applet implements MouseListener,MouseMotionListener


{
String msg="";
int mousex=0,mousey=0;

public void init()


{
addMouseListener(this);
addMouseMotionListener(this);
}

public void mouseClicked(MouseEvent me)


{
mousex=0;
mousey=10;
msg="Mouse Clicked";
repaint();
}

public void mouseEntered(MouseEvent me)


{
mousex = 0;
mousey = 10;
msg = " Mouse entered in applet area";
repaint();
}
public void mouseExited(MouseEvent me)
{
mousex=0;
mousey=10;
msg="Mouse exited the applet area";
repaint();
}

public void mousePressed(MouseEvent me)


{
mousex=me.getX();
mousey=me.getY();
msg="mouse pressed";
repaint();
}

public void mouseReleased(MouseEvent me)


{
mousex=me.getX();
mousey=me.getY();
msg="mouse Released";
repaint();
}

public void mouseDragged(MouseEvent me)


{
mousex=me.getX();
mousey=me.getY();
msg="*";
showStatus("Dragging mouse at "+mousex+" , "+mousey);
repaint();
}
public void mouseMoved(MouseEvent me)
{
showStatus("Moving mouse at "+me.getX()+" ,
"+me.getY());
repaint();
}

public void paint(Graphics g)


{
g.drawString(msg,mousex,mousey);
}
}

sem 2
Accept “n” integers from the user and store them in a collection .Display them in
the sorted order .The collection should not accept duplicate elements (Use suitable
collection ).search for a particular element using predefined search method in the
collection framework .
/*---------------------------------------------------------------------------------------
1. Accept n integers from the user and store them in a collection. Display them in the
sorted order. The collection should not accept duplicate elements. (Use a suitable
collection).
------------------------------------------------------------------------------------------*/

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

class collection1
{
public static void main(String[] args) throws Exception
{
int num,ele,i;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
ArrayList al=new ArrayList();
System.out.println("Enter the no for how many element to have:");
num=Integer.parseInt(br.readLine());
for(i=0;i<num;i++)
{
System.out.println("Enter the elements in position:"+i);
ele=Integer.parseInt(br.readLine());
al.add(ele);
}

System.out.println("The elements of ArrayList before:"+al);


Collections.sort(al);
System.out.println("The elements of ArrayList after sort:"+al);
}
}
/*------------------------------output----------
[root@localhost ~]# java collection1
Enter the no for how many element to have:
5
Enter the elements in position:0
5
Enter the elements in position:1
3
Enter the elements in position:2
7
Enter the elements in position:3
2
Enter the elements in position:4
8
The elements of ArrayList before:[5, 3, 7, 2, 8]
The elements of ArrayList after sort:[2, 3, 5, 7, 8]
-------------------------------------------------------*/
slip 10
sem 1
Write a program to implement a simple arithmetic calculator. Perform appropriate
validations.
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class Calculator extends JFrame{


private JPanel panButtons;
private JTextField txtDisplay;
private JButton btnDigits[],btnOp[],btnDot,btnEqual;
private float a,b,ans;
private char oper;

public Calculator(){
btnDigits = new JButton[10];

for(int i=0;i<10;i++){
btnDigits[i] = new JButton(Integer.toString(i));
}

btnOp = new JButton[4];


String op[]={"+","-","*","/"};
for(int i=0;i<4;i++){
btnOp[i] = new JButton(op[i]);
}

btnDot = new JButton(".");


btnEqual = new JButton("=");

txtDisplay = new JTextField();


txtDisplay.setEditable(false);
txtDisplay.setHorizontalAlignment(JTextField.RIGHT);

panButtons = new JPanel();


panButtons.setLayout(new GridLayout(4,4));
panButtons.add(btnDigits[1]);
panButtons.add(btnDigits[2]);
panButtons.add(btnDigits[3]);
panButtons.add(btnOp[0]);
panButtons.add(btnDigits[4]);
panButtons.add(btnDigits[5]);
panButtons.add(btnDigits[6]);
panButtons.add(btnOp[1]);
panButtons.add(btnDigits[7]);
panButtons.add(btnDigits[8]);
panButtons.add(btnDigits[9]);
panButtons.add(btnOp[2]);
panButtons.add(btnDigits[0]);
panButtons.add(btnDot);
panButtons.add(btnEqual);
panButtons.add(btnOp[3]);

setTitle("Calculator");
setSize(400,400);
add(txtDisplay,"North");
add(panButtons,"Center");
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

btnDot.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
String s = txtDisplay.getText();
int i = s.indexOf(".");
if(i==-1) s += ".";
txtDisplay.setText(s);
}
});

for(int i=0;i<10;i++){
btnDigits[i].addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
String s = txtDisplay.getText();
s += ae.getActionCommand();
txtDisplay.setText(s);
}
});
}

for(int i=0;i<4;i++){
btnOp[i].addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
oper = ae.getActionCommand().charAt(0);
a = Float.parseFloat(txtDisplay.getText());
txtDisplay.setText("");
}
});
}

btnEqual.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
b = Float.parseFloat(txtDisplay.getText());
switch(oper)
{
case '+':
ans = a+b;
break;
case '-':
ans = a-b;
break;
case '*':
ans = a*b;
break;
case '/':
ans = a/b;
}
txtDisplay.setText(Float.toString(ans));
}
});
}

public static void main(String args[]){


new Calculator();
}
}
sem 2
Accept “n” integers from the user and store them in a collection .Display them in
the sorted order .The collection should not accept duplicate elements (Use suitable
collection ).search for a particular element using predefined search method in the
collection framework .
/*---------------------------------------------------------------------------------------
1. Accept n integers from the user and store them in a collection. Display them in the
sorted order. The collection should not accept duplicate elements. (Use a suitable
collection).
------------------------------------------------------------------------------------------*/

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

class collection1
{
public static void main(String[] args) throws Exception
{
int num,ele,i;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
ArrayList al=new ArrayList();
System.out.println("Enter the no for how many element to have:");
num=Integer.parseInt(br.readLine());
for(i=0;i<num;i++)
{
System.out.println("Enter the elements in position:"+i);
ele=Integer.parseInt(br.readLine());
al.add(ele);
}

System.out.println("The elements of ArrayList before:"+al);


Collections.sort(al);
System.out.println("The elements of ArrayList after sort:"+al);
}
}
/*------------------------------output----------
[root@localhost ~]# java collection1
Enter the no for how many element to have:
5
Enter the elements in position:0
5
Enter the elements in position:1
3
Enter the elements in position:2
7
Enter the elements in position:3
2
Enter the elements in position:4
8
The elements of ArrayList before:[5, 3, 7, 2, 8]
The elements of ArrayList after sort:[2, 3, 5, 7, 8]
-------------------------------------------------------*/
slip 11
sem 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 names 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 set5a1
{
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String dirname=args[0],ext;
int ch,i,cnt=0;
File f1=new File(dirname);
ext="txt";
if(f1.isFile())
{
System.out.println(f1+" is a File\n");
System.out.println("Path : "+f1.getPath());
System.out.println("File Size : "+f1.length()+" bytes\n");
}

else if(f1.isDirectory())
{
System.out.println(args[0]+" Is a Directory\n");
System.out.println("Contents Of : "+dirname);
String s[]=f1.list();

for(i=0;i<s.length;i++)
{
File f=new File(dirname,s[i]);
if(f.isFile())
{
cnt++;
System.out.println(s[i]+" is a File\n");
}
else
System.out.println(s[i]+" is a Directory\n");
}

System.out.println("Total Number Of Files :"+cnt);


System.out.println("Do You Want To Delete Files With Extension 'txt' (1/0) : ?");
ch=Integer.parseInt(br.readLine());
if(ch==1)
{
for(i=0;i<s.length;i++)
{
File f=new File(dirname,s[i]);
if(f.isFile() && s[i].endsWith(ext))
{
System.out.println(s[i]+" -> deleted");
f.delete();
}
}
}
}
}
}
/*---------------------------------------------------------------------------------
output =
[user@localhost ~]$ javac set5a1.java
[user@localhost ~]$ java set5a1 Diya
Diya Is a Directory

Contents Of : Diya
abc.txt is a File

def.txt is a File

soyal is a Directory

Total Number Of Files :2


Do You Want To Delete Files With Extension 'txt' (1/0) : ?
0
[user@localhost ~]$ java set5a1 Diya
Diya Is a Directory

Contents Of : Diya
abc.txt is a File

def.txt is a File

soyal is a Directory

Total Number Of Files :2


Do You Want To Delete Files With Extension 'txt' (1/0) : ?
1
abc.txt -> deleted
def.txt -> deleted
[user@localhost ~]$ java set5a1 Diya
Diya Is a Directory

Contents Of : Diya
soyal is a Directory

Total Number Of Files :0


Do You Want To Delete Files With Extension 'txt' (1/0) : ?
0
[user@localhost ~]$
*/

sem 2
Define a thread called “Print Text Thread” for printing text on command prompt
for ‘n’ number of times. Create three threads and run them. Pass the text and ‘n’ as
parameters to the thread constructor.

Example:

a. First thread prints “I am in FY” 10 times

b. Second thread prints “I am in SY” 20 times

c.Third thread prints “I am in TY”30 times


/*------------------------------------------------------------------------------------
ASSGN 2: SET A:3
3. Define a thread called “PrintText_Thread” for printing text on command prompt for
n number of times. Create three threads and run them. Pass the text and n as
parameters to the thread constructor. Example:
i. First thread prints “I am in FY” 10 times
ii. Second thread prints “I am in SY” 20 times
iii. Third thread prints “I am in TY” 30 times
-------------------------------------------------------------------------------------*/

import java.io.*;
import java.lang.String.*;

class Ass_seta3 extends Thread


{
String msg="";
int n;
Ass_seta3(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+" times");
}
}
catch(Exception e){}
}
}
public class seta3
{
public static void main(String a[])
{
int n=Integer.parseInt(a[0]);
Ass_seta3 t1=new Ass_seta3("I am in FY",n);
t1.start();
Ass_seta3 t2=new Ass_seta3("I am in SY",n+10);
t2.start();
Ass_seta3 t3=new Ass_seta3("I am in TY",n+20);
t3.start();
}
}
/*---------------------------------------output---------------------------------
I am in FY 1 times
I am in SY 1 times
I am in SY 2 times
I am in TY 1 times
I am in FY 2 times
I am in TY 2 times
I am in FY 3 times
I am in TY 3 times
I am in FY 4 times
I am in TY 4 times
I am in FY 5 times
I am in TY 5 times
I am in FY 6 times
I am in TY 6 times
I am in FY 7 times
I am in TY 7 times
I am in FY 8 times
I am in TY 8 times
I am in TY 9 times
I am in TY 10 times
I am in TY 11 times
I am in TY 12 times
I am in TY 13 times
I am in TY 14 times
I am in TY 15 times
I am in TY 16 times
I am in TY 17 times
I am in TY 18 times
I am in TY 19 times
I am in TY 20 times
I am in TY 21 times
I am in TY 22 times
I am in TY 23 times
I am in TY 24 times
I am in TY 25 times
I am in TY 26 times
I am in TY 27 times
I am in TY 28 times
I am in TY 29 times
I am in TY 30 times
I am in FY 9 times
I am in SY 3 times
I am in SY 4 times
I am in SY 5 times
I am in SY 6 times
I am in SY 7 times
I am in SY 8 times
I am in SY 9 times
I am in SY 10 times
I am in SY 11 times
I am in SY 12 times
I am in SY 13 times
I am in SY 14 times
I am in SY 15 times
I am in SY 16 times
I am in SY 17 times
I am in SY 18 times
I am in SY 19 times
I am in SY 20 times
I am in FY 10 times
---------------------------------------------------------------------------*/
slip 12
sem 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 seta3 extends JFrame implements ActionListener


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

public seta3(String s)
{
super(s);
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);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==r1)
{
String s =t1.getText();
s1.append("Name = ");
s1.append(s);
s1.append(" Class = FY");
}
else if(e.getSource()==r2)
{
String s =t1.getText();
s1.append("Name = ");
s1.append(s);
s1.append(" Class = SY");
}
else if(e.getSource()==r3)
{
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[])
{
seta3 s=new seta3("Profile");
s.setSize(400,200);
s.setVisible(true);
s.setLocation(400,400);
s.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

sem 2:-
Write a program to calculate the sum and average of an array of 1000 integers
(Generated randomly) using 10 threads. Each thread calculates the sum of 100
integers.Use these values to calculate average. [Use join method]
class SumThread extends Thread{
private int x[],start,end,sum;

public SumThread(int a[], int s, int e){


x = a;
start = s;
end = e;
}

public void run(){


for(int i=start;i<=end;i++){
sum+=x[i];
try{
Thread.sleep((int)(Math.random()*1000));
}catch(Exception e){}
}
}

public int getSum(){


return sum;
}
}

class ThreadEx5{
public static void main(String args[]){
int nos[] = new int[100];

for(int i=0;i<100;i++)
nos[i] = i+1;

SumThread t[] = new SumThread[5];

for(int i=0;i<5;i++)
{
t[i] = new SumThread(nos,i*20,(i+1)*20-1);
t[i].start();
}
for(int i=0;i<5;i++)
{
try{
t[i].join();
}
catch(Exception e){}
}

float avg=0;
for(int i=0;i<5;i++){
avg+=t[i].getSum();
}
System.out.println("Sum:"+avg+
"\nAvg:"+(avg/100));
}
}
slip 13
sem1-
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, delete all text file in that directory confirm delete


operation from user before deleting text files. Also, display a count showing
the number of files deleted, if any, from the directory.
b. If it is a file display various details of that file.
(slip 13 and 11)
import java.io.*;

class set5a1
{
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String dirname=args[0],ext;
int ch,i,cnt=0;
File f1=new File(dirname);
ext="txt";
if(f1.isFile())
{
System.out.println(f1+" is a File\n");
System.out.println("Path : "+f1.getPath());
System.out.println("File Size : "+f1.length()+" bytes\n");
}

else if(f1.isDirectory())
{
System.out.println(args[0]+" Is a Directory\n");
System.out.println("Contents Of : "+dirname);
String s[]=f1.list();

for(i=0;i<s.length;i++)
{
File f=new File(dirname,s[i]);
if(f.isFile())
{
cnt++;
System.out.println(s[i]+" is a File\n");
}
else
System.out.println(s[i]+" is a Directory\n");
}

System.out.println("Total Number Of Files :"+cnt);


System.out.println("Do You Want To Delete Files With Extension 'txt' (1/0) : ?");
ch=Integer.parseInt(br.readLine());
if(ch==1)
{
for(i=0;i<s.length;i++)
{
File f=new File(dirname,s[i]);
if(f.isFile() && s[i].endsWith(ext))
{
System.out.println(s[i]+" -> deleted");
f.delete();
}
}
}
}
}
}
/*---------------------------------------------------------------------------------
output =
[user@localhost ~]$ javac set5a1.java
[user@localhost ~]$ java set5a1 Diya
Diya Is a Directory

Contents Of : Diya
abc.txt is a File

def.txt is a File

soyal is a Directory

Total Number Of Files :2


Do You Want To Delete Files With Extension 'txt' (1/0) : ?
0
[user@localhost ~]$ java set5a1 Diya
Diya Is a Directory

Contents Of : Diya
abc.txt is a File

def.txt is a File

soyal is a Directory

Total Number Of Files :2


Do You Want To Delete Files With Extension 'txt' (1/0) : ?
1
abc.txt -> deleted
def.txt -> deleted
[user@localhost ~]$ java set5a1 Diya
Diya Is a Directory

Contents Of : Diya
soyal is a Directory

Total Number Of Files :0


Do You Want To Delete Files With Extension 'txt' (1/0) : ?
0
[user@localhost ~]$
*/

sem2
Create a table student with fields roll number, name, percentage using postgresql.
Insert values in the table .Display all the details of the student table in a tabular
format on the screen. (Using Swing)
/*************************************************************

1. Create a student table with fields roll number, name, percentage.


Insert values in the table. Display all the details of the student table using JDBC.
*************************************************************/
import java.sql.*;
import java.io.*;
class Mit
{
public static void main(String a[])
{
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost/student","root","");

Statement smt=con.createStatement();

smt.executeUpdate("insert into student values(34,'anand',80)");


smt.executeUpdate("insert into student values(35,'anil',90)");
smt.executeUpdate("insert into student values(36,'sanket',99)");
smt.executeUpdate("insert into student values(37,'swapnil',100)");

ResultSet rs=smt.executeQuery("select * from student");


while(rs.next())
{
System.out.print( rs.getInt("roll_no")+"\t");

System.out.print(rs.getString("sname")+"\t");

System.out.print(rs.getInt("per")+"\n");
}
con.close();
}catch(Exception e){}
}
}
/******output******************
34 anand 80
35 anil 90
36 sanket 99
37 swapnil 100
/******************************/
slip 14
sem 1-
Write a menu driven program to perform the following operations on a text file
“phone .txt” Which contains 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.util.*;
import java.io.*;

class Phone
{
public static void main(String[] args)throws IOException
{
Scanner s=new Scanner(System.in);
RandomAccessFile raf=new RandomAccessFile("phone.txt","rw");
boolean found=false;

System.out.println("Enter number of records to be inserted :: ");


int n=s.nextInt();

String[] name=new String[n];


long[] pno=new long[n];

System.out.println("Enter "+n+" records :: ");


for(int i=0;i<n;i++)
{
System.out.println("Enter name :: ");
name[i]=s.next();
raf.writeUTF(name[i]);
System.out.println("Enter phone number :: ");
pno[i]=s.nextLong();
raf.writeLong(pno[i]);
}
System.out.println("Data Inserted ");
System.out.println("Enter name to search :: ");
String sname=s.next();
for(int i=0;i<n;i++)
{
if(sname.equals(name[i]))
{
System.out.println("Record Found");
found=true;
}
}
if(found==false)
System.out.println("Record not Found");
}
}

sem 2
Construct a Linked List containing name of colors: red, blue, yellow and

Orange. Then extend your program to do the following:


a. Display the contents of the list using an Iterator.
b. Display the contents of the list in reverse order using a listIterator.
c. Create another list containing pink and green .Insert the elements of this
list between blue and yellow.
/*-------------------------------------------------------------------------------------------------
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 a ListIterator;
iii. Create another list containing pink and green. Insert the elements of this list
between blue and yellow.
------------------------------------------------------------------------------------------------*/
import java.util.*;

class collection2
{
public static void main(String[] args)
{
LinkedList ll=new LinkedList();
ll.add("Red");
ll.add("Blue");
ll.add("Yellow");
ll.add("Orange");
Iterator i=ll.iterator();
System.out.println("contents of the List using an Iterator:");
while(i.hasNext())
{
String s=(String)i.next();
System.out.println(s);
}
ListIterator litr = ll.listIterator();
while(litr.hasNext())
{
String elt = (String)litr.next();
}
System.out.println("contents of the List in reverse order using a ListIterator : ");
while(litr.hasPrevious())
{
System.out.println(litr.previous());
}
ll.add(2,"Pink");
ll.add(3,"Green");
System.out.println("list between blue and yellow is:");
System.out.println(ll);
}
}
/*---------------------output-----------
[root@localhost ~]# java collection2
contents of the List using an Iterator:
Red
Blue
Yellow
Orange
contents of the List in reverse order using a ListIterator :
Orange
Yellow
Blue
Red
list between blue and yellow is:
[Red, Blue, Pink, Green, Yellow, Orange]
-----------------------------------------------------*/
slip 15
sem 1-
Write the 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 item and total cost
import java.io.*;
import java.lang.*;

class ItemInfo
{
int id,quantity;
String name;
long price;

ItemInfo()
{
}

ItemInfo(int id,String name,long price,int quantity)


{
this.id=id;
this.name=name;
this.price=price;
this.quantity=quantity;
}

long store(RandomAccessFile f) throws Exception


{
String sid="",sprice="",squantity="";

sid+=id;
sprice+=price;
squantity+=quantity;

long pos=f.getFilePointer();

f.writeUTF(sid);
f.writeUTF(name);
f.writeUTF(sprice);
f.writeUTF(squantity);

return pos;
}

void access(RandomAccessFile f) throws Exception


{
id=Integer.parseInt(f.readUTF());
name=f.readUTF();
price=Long.parseLong(f.readUTF());
quantity=Integer.parseInt(f.readUTF());

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

public String toString()


{
return "Id = "+id+"\tName= "+name+"\tPrice= "+price+"\tQuantity = "+quantity;
}
}

class set5b1
{
public static void main(String args[])throws Exception
{
RandomAccessFile f=new RandomAccessFile("Item.dat","rw");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

ItemInfo I;

long max=0,total=0;

System.out.println("How many records :");


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

String nameTable[]=new String[n];


long posTable[]=new long[n];
long costTable[]=new long[n];

for(int i=0;i<n;i++)
{
System.out.println("Enter Details");

System.out.println("Enter Item Id : ");


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

System.out.println("Enter Item Name : ");


String name=br.readLine();

System.out.println("Enter Item Price : ");


long price=Long.parseLong(br.readLine());

System.out.println("Enter Item Quantity : ");


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

I=new ItemInfo(id,name,price,quantity);

nameTable[i]=name;

costTable[i]=(price*quantity);
posTable[i]=I.store(f);
}
f.close();

boolean done=false;

RandomAccessFile f1=new RandomAccessFile("Item.dat","r");

ItemInfo I1=new ItemInfo();

while(!done)
{
System.out.println("1.Search by name");
System.out.println("2.Find costliest item");
System.out.println("3.Display all item and total cost");
System.out.println("Enter choice");
int choice=Integer.parseInt(br.readLine());
switch(choice)
{
case 1 :
System.out.println("Enter Name to search :");
String name=br.readLine();
boolean found=false;
for(int i=0;i<n;i++)
{
if(nameTable[i].equals(name))
{
found=true;
f1.seek(posTable[i]);
I1.access(f1);
}
}
if(!found)
System.out.println("Sorry , record not found . . . ");
break;
case 2 :
for(int i=0;i<n;i++)
{
if(costTable[i] > max)
max=costTable[i];
}
for(int i=0;i<n;i++)
{
if(costTable[i]==max)
{
f1.seek(posTable[i]);
I1.access(f1);
}
}
break;
case 3 :
for(int i=0;i<n;i++)
{
f1.seek(posTable[i]);
I1.access(f1);
total+=costTable[i];
}
System.out.println("\t\t\t\tTatal Amount : "+total);
break;
}
System.out.println("Do you want to continue (Y/N) :");
String ans=br.readLine();
if(ans.equals("N"))
done=true;
}
}
}
/*-----------------------------------------------------------------------------------
output =
[user@localhost ~]$ javac set5b1.java
[user@localhost ~]$ java set5b1
How many records :
2
Enter Details
Enter Item Id :
101
Enter Item Name :
Mango
Enter Item Price :
150
Enter Item Quantity :
12
Enter Details
Enter Item Id :
102
Enter Item Name :
Pinapal
Enter Item Price :
100
Enter Item Quantity :
123
1.Search by name
2.Find costliest item
3.Display all item and total cost
Enter choice
1
Enter Name to search :
Mango
Id = 101 Name= Mango Price= 150 Quantity = 12
Do you want to continue (Y/N) :
Y
1.Search by name
2.Find costliest item
3.Display all item and total cost
Enter choice
1
Enter Name to search :
Banana
Sorry , record not found . . .
Do you want to continue (Y/N) :
Y
1.Search by name
2.Find costliest item
3.Display all item and total cost
Enter choice
2
Id = 102 Name= Pinapal Price= 100 Quantity = 123
Do you want to continue (Y/N) :
Y
1.Search by name
2.Find costliest item
3.Display all item and total cost
Enter choice
3
Id = 101 Name= Mango Price= 150 Quantity = 12
Id = 102 Name= Pinapal Price= 100 Quantity = 123
Tatal Amount : 14100
Do you want to continue (Y/N) :
N
[user@localhost ~]$

*/

sem2
Create a Hash table containing student name and percentage .Display the

Details of the hash table .Also search for a specific and display percentage of
that student.
/*-------------------------------------------------------------------------------------
3. 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.
-------------------------------------------------------------------------------------*/
import java.util.*;

class Collection3
{
public static void main(String[] args) throws Exception
{
Scanner s=new Scanner(System.in);
Hashtable ht=new Hashtable();
ht.put("Anand",66.2);
ht.put("Anil",65.7);
ht.put("Shashank",64.8);
Enumeration keys=ht.keys();
Enumeration values=ht.elements();
while(keys. hasMoreElements())
{
while(values. hasMoreElements())
{
System.out.println("student name:"+keys.nextElement()+"\tpercentage:"+values.nextElement());
}
}
System.out.println("enter specific name:");
String str=s.next();
System.out.println("specific student name is "+str+"& percentage is:"+ht.get(str));
}
}

/*-----------------output---------------------------
[root@localhost ~]# java collection3
student name:Anand percentage:66.2
student name:Shashank percentage:64.8
student name:Anil percentage:65.7
specific student name is Anand & percentage is:66.2
---------------------------------------------------------*/
slip 16
sem1
Define a class cricket player (name, no_ of_ innings, no_ of_ times_ not out, total
_runs, bat_ avg ).Create an array of “n” player object. Calculate the batting average
for each player using a static method avg (). Handle appropriate exception while
calculating average .Define static method “short player” Which short array on the
basis of average .Display the player detail in sorted order.

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

class CricketPlayer
{
String name;
int inn;
int notout;
int trun;
static int batavg1;
int batavg;

public CricketPlayer(String name,int inn,int notout,int trun,int batavg)


{
this.name=name;
this.inn = inn;
this.notout = notout;
this.trun = trun;
this.batavg = batavg;
}
static int avg(int inn,int notout,int trun)
{
try
{
batavg1 = (trun/(inn-notout));
return batavg1;
}
catch(ArithmeticException e)
{
System.out.println(e);
return 0;
}

}
public String toString()
{
return("name="+name+"\ninn="+inn+"\nnot out="+notout+"\ntrun="+trun+"\nbatavg="+batavg);
}
static void sort(CricketPlayer[] c)
{
int temp ,i; //= new CricketPlayer();
for(i=0;i<c.length;i++)
{
for(int j=0;j<c.length-1;j++)
{
if(c[j].batavg > c[j+1].batavg)
{
temp = c[j].batavg;
c[j].batavg = c[j+1].batavg;
c[j+1].batavg = temp;
}
}

}
for(i=0;i<c.length;i++)
{
System.out.println(c[i]);
}
}
}
public class CricketPlay
{
public static void main(String[] args)
{
int n,i;
Scanner s =new Scanner(System.in);
System.out.println("Enter Size");
n = s.nextInt();
String name;
int inn,notout,trun,batavg;

CricketPlayer[] c1 = new CricketPlayer[n];


for(i =0; i<n;i++)
{
System.out.println("name, no of inning notout totla run");
name = s.next();
inn = s.nextInt();
notout = s.nextInt();
trun = s.nextInt();

batavg = CricketPlayer.avg(inn,notout,trun);

c1[i] = new CricketPlayer(name, inn,notout,trun,batavg);


System.out.println(c1[i]);
}
CricketPlayer.sort(c1);
/*System.out.println("Sorted data = \n");
for(i=0;i<n;i++)
{
System.out.println(c1[i]);
}*/
}
}

sem2:-
Create a application to store city names and there STD coded using an

Appropriate collection. Display the GUI should allow the following operations:

a. Add a new city and its code (no duplicated )


b. Remove a city from the collection
c. Search for a city name and display the code

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

class Collection4
{
public static void main(String[] args) throws Exception
{
//Scanner s=new Scanner(System.in);
int op1;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
Hashtable ht=new Hashtable();
ht.put("Pune",6622);
ht.put("Mumbai",6577);
ht.put("Delhi",6488);
ht.put("chennai",6699);

do
{
System.out.println("1.add city");
System.out.println("2.remove city");
System.out.println("3.search city");
System.out.println("4.display");
System.out.println("5.exit");

System.out.println("Enetr your option:");


int op=Integer.parseInt(br.readLine());
switch(op)
{
case 1:System.out.println("Enetr city");
String str=br.readLine();
System.out.println("Enetr city code");
int code=Integer.parseInt(br.readLine());
ht.put(str,code);
break;
case 2:System.out.println("Enter city name to remove:");
//ht.remove(str);
System.out.println("Successful");
break;
case 3:
System.out.println("Enetr city to search");
String str1=br.readLine();
System.out.println("city name: "+str1);
System.out.println("city code :"+ht.get(str1));
break;

case 4:System.out.println("********CITY-CODE********");
Enumeration keys=ht.keys();
Enumeration values=ht.elements();
while(keys.hasMoreElements())
{
while(values.hasMoreElements())
{
System.out.println("city
name:"+keys.nextElement());
System.out.println("city
code:"+values.nextElement());
}
}
break;
}
System.out.println("enter 1 to continue:");
op1=Integer.parseInt(br.readLine());
}while(op1==1);
}}

slip 17
sem 1
Define an abstract class “Staff” with member name and address .Define two sub-
class of this class - “Fulltimestaff” or (department, salary) and part time
staff (number _of_ hours ,rate _per_ hour).Define appropriate constructors.

Create “n” object which could be of either FullTimeStaff or PartTimeStaff class


asking the user’s choice .Display details of all “FullTimeStaff” object and all
PartTimeStaff object.
import java.util.*;

abstract class Staff


{
String name;
String addr;
Scanner s=new Scanner(System.in);
Staff()
{

Staff(String name,String addr)


{
this.name=name;
this.addr=addr;
}
}

class FullTimeStaff extends Staff


{
String dept;
double sal;
String name;
String addr;
Scanner s=new Scanner(System.in);

FullTimeStaff()
{

FullTimeStaff(String name,String addr,String dept,double sal)


{
super(name,addr);

this.dept=dept;
this.sal=sal;
}

void display()
{
System.out.println(" Name :: "+name);
System.out.println(" Address :: "+addr);
System.out.println("Department :: "+dept);
System.out.println("Salary :: "+sal);
}
}

class PartTimeStaff extends Staff


{
int hrs;
double rate;
double sal1;
Scanner s=new Scanner(System.in);

PartTimeStaff()
{

PartTimeStaff(String name,String addr,int hrs,double rate)


{
super(name,addr);

this.hrs=hrs;
this.rate=rate;
}

void display()
{
sal1=hrs*rate;
System.out.println(" Name :: "+name);
System.out.println(" Address :: "+addr);
System.out.println("Number of hours worked :: "+hrs);
System.out.println("Salary :: "+sal1);
}
}

class staffDemo
{
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);

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


String name=s.next();
System.out.println("Enter Address :: ");
String addr=s.next();

System.out.println("For Full Time Staff:: ");


System.out.println("Enter Dept :: ");
String dept=s.next();
System.out.println("Enter Salary :: ");
double sal=s.nextDouble();
FullTimeStaff f=new FullTimeStaff(name,addr,dept,sal);
f.display();

System.out.println("Enter number of hours worked :: ");


int hrs=s.nextInt();
System.out.println("Enter Rate per hour :: ");
double rate=s.nextDouble();

PartTimeStaff p=new PartTimeStaff(name,addr,hrs,rate);


p.display();
}
}
sem 2
Design the table Login (login_ name, password) using Postgreql . Also design an
HTML login screen accepting the login name and the password for the user .write
a servlet program that validates accepted login name and pass

word entered by user from the login table you have created. The servlet sends back
an appropriate response.
a1.html
<html>
<head>
<title>1st program</title></head>
<body>
<FORM ACTION="a1.java" method=GET>
<h1>Komal Shinge</h1>

<INPUT TYPE="text" name="uname">


<INPUT TYPE="password" name="pwd">
<INPUT TYPE="submit" value=" CLICK ">

</FORM>
</body>
</html>

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

public class Login extends HttpServlet


{
public void doGet(HttpServletRequest req,HttpServletResponse resp)
{
doPost(req,resp);
}
public void doPost(HttpServletRequest req,HttpServletResponse resp)
{
try
{

PrintWriter pw = resp.getWriter();
resp.setContentType("text/html");

String u = req.getParameter("uname");
String p = req.getParameter("pwd");

if(u.equals("admin") && p.equals("admin"))


pw.println("<h1> WELCOME");
else
pw.println("<h1> error");
pw.close();

}
catch(Exception e){}
}}

slip 18
sem 1
Define a class my number having one positive integer data member .Write a
difficult constructer to initialize it to 0 and other constructor to initialize it to a
value (Use this ).Write a method is Negative ,isZero, isOdd , isEven. Create an
object in main . Use command line adguments to pass a value to the object and
perform the above test
class MyNumber
{ int n;
MyNumber()
{
n=0;
}
MyNumber(int n)
{
this.n=n;
}
void isNegative()
{
if(n<0)
System.out.println(n+"is negative");
}
void isPositive()
{
if(n>0)
System.out.println(n+"is positive");
}
void isZero()
{
if(n==0)
System.out.println(n+"is zero");
}
void isOdd()
{
if(n%2!=0)
System.out.println(n+"is odd");
}
void isEven()
{
if(n%2==0)
System.out.println(n+"is even");
}
public static void main(String args[])
{
int n=Integer.parseInt(args[0]);
MyNumber m=new MyNumber();
m.isNegative();
m.isPositive();
m.isZero();
m.isOdd();
m.isEven();

MyNumber m1=new MyNumber(10);


m1.isNegative();
m1.isZero();
m1.isEven();
m1.isOdd();
}
}

sem 2
Accept “n” integers from the user and store them in a collection .Display them in
the sorted order .The collection should not accept duplicate elements (Use suitable
collection ).search for a particular element using predefined search method in the
collection framework .
/*---------------------------------------------------------------------------------------
1. Accept n integers from the user and store them in a collection. Display them in the
sorted order. The collection should not accept duplicate elements. (Use a suitable
collection).
------------------------------------------------------------------------------------------*/

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

class collection1
{
public static void main(String[] args) throws Exception
{
int num,ele,i;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
ArrayList al=new ArrayList();
System.out.println("Enter the no for how many element to have:");
num=Integer.parseInt(br.readLine());
for(i=0;i<num;i++)
{
System.out.println("Enter the elements in position:"+i);
ele=Integer.parseInt(br.readLine());
al.add(ele);
}

System.out.println("The elements of ArrayList before:"+al);


Collections.sort(al);
System.out.println("The elements of ArrayList after sort:"+al);
}
}
/*------------------------------output----------
[root@localhost ~]# java collection1
Enter the no for how many element to have:
5
Enter the elements in position:0
5
Enter the elements in position:1
3
Enter the elements in position:2
7
Enter the elements in position:3
2
Enter the elements in position:4
8
The elements of ArrayList before:[5, 3, 7, 2, 8]
The elements of ArrayList after sort:[2, 3, 5, 7, 8]
-------------------------------------------------------*/
slip 19

sem1:-
. Create a Applet which display a massage in the center of the screen . the massage
indicated the events taking place on the applet window .Handle various keyboard
related event .The massage should update each time an event occurs. The massage
should give details of the event such as which key was pressed, released, typed etc.

(Hint: Use repaint (), key listener ).

//Demonstrate Mouse Events.

import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*
<applet code="mouseeventsdemo" height=300 width=300>
</applet>
*/

public class mouseeventsdemo extends Applet implements MouseListener,MouseMotionListener


{
String msg="";
int mousex=0,mousey=0;

public void init()


{
addMouseListener(this);
addMouseMotionListener(this);
}

public void mouseClicked(MouseEvent me)


{
mousex=0;
mousey=10;
msg="Mouse Clicked";
repaint();
}

public void mouseEntered(MouseEvent me)


{
mousex = 0;
mousey = 10;
msg = " Mouse entered in applet area";
repaint();
}
public void mouseExited(MouseEvent me)
{
mousex=0;
mousey=10;
msg="Mouse exited the applet area";
repaint();
}

public void mousePressed(MouseEvent me)


{
mousex=me.getX();
mousey=me.getY();
msg="mouse pressed";
repaint();
}

public void mouseReleased(MouseEvent me)


{
mousex=me.getX();
mousey=me.getY();
msg="mouse Released";
repaint();
}

public void mouseDragged(MouseEvent me)


{
mousex=me.getX();
mousey=me.getY();
msg="*";
showStatus("Dragging mouse at "+mousex+" , "+mousey);
repaint();
}
public void mouseMoved(MouseEvent me)
{
showStatus("Moving mouse at "+me.getX()+" ,
"+me.getY());
repaint();
}

public void paint(Graphics g)


{
g.drawString(msg,mousex,mousey);
}
}

sem 2
Accept “n” integers from the user and store them in a collection .Display them in
the sorted order .The collection should not accept duplicate elements (Use suitable
collection ).search for a particular element using predefined search method in the
collection framework .
/*---------------------------------------------------------------------------------------
1. Accept n integers from the user and store them in a collection. Display them in the
sorted order. The collection should not accept duplicate elements. (Use a suitable
collection).
------------------------------------------------------------------------------------------*/
import java.util.*;
import java.io.*;

class collection1
{
public static void main(String[] args) throws Exception
{
int num,ele,i;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
ArrayList al=new ArrayList();
System.out.println("Enter the no for how many element to have:");
num=Integer.parseInt(br.readLine());
for(i=0;i<num;i++)
{
System.out.println("Enter the elements in position:"+i);
ele=Integer.parseInt(br.readLine());
al.add(ele);
}

System.out.println("The elements of ArrayList before:"+al);


Collections.sort(al);
System.out.println("The elements of ArrayList after sort:"+al);
}
}
/*------------------------------output----------
[root@localhost ~]# java collection1
Enter the no for how many element to have:
5
Enter the elements in position:0
5
Enter the elements in position:1
3
Enter the elements in position:2
7
Enter the elements in position:3
2
Enter the elements in position:4
8
The elements of ArrayList before:[5, 3, 7, 2, 8]
The elements of ArrayList after sort:[2, 3, 5, 7, 8]
-------------------------------------------------------*/
slip 20
sem 1-
Write a program to create a package “SY” which has a class SY Marks (computer
total, maths total, Electronics total) create another package “TY” Which has a class
TY marks (theory ,Practical ). Create “n” objects of Student class having roll
number, name, SYM Marks and TYM Marks. Add the marks of 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.
package sy

package SY;
public class symark
{
int ct,mt,et;
public symark()
{
ct=0;mt=0;et=0;
}
public symark(int c,int m,int e)
{
this.ct=c;
this.mt=m;
this.et=e;
}

package ty

package TY;
public class tymark
{
int tt,pt;
public tymark()
{
tt=0;pt=0;
}
public tymark(int t,int p)
{
this.tt=t;
this.pt=p;
}
}

prog

import java.io.*;
import SY.symark;
import TY.tymark;
public class set2b2
{
private int rno;
private String name;
private symark sy1;
private tymark ty1;
private String grade;

public set2b2()
{
rno=0;
name="";
sy1=new symark();
ty1=new tymark();
grade="";
}
public set2b2(int r,String na,int ct1,int mt1,int et1,int t1,int p,String g)
{
rno=r;
name=na;
sy1=new symark(ct1,mt1,et1);
ty1=new tymark(t1,p);
grade=g;

}
public void display(int ct1,int mt1,int et1,int t1,int p,String g)
{
System.out.println("roll no\t"+rno);
System.out.println("name\t"+name);
System.out.println("total of computer for sy: "+ct1);
System.out.println("total of maths for sy: "+mt1);
System.out.println("total of electronic for sy: "+et1);
System.out.println("total of theory for ty: "+t1);
System.out.println("total of practicals for ty: "+p);
System.out.println("grade:\n"+g);
}

public static void main(String args[]) throws IOException


{
String g;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("How many records to be created:");
int n=Integer.parseInt(br.readLine());
set2b2 s[]=new set2b2[n+1];
for(int i=0;i<n;i++)
{
System.out.println("Enter details of record no.:"+(i+1));
System.out.println("Roll Number:");
int r=Integer.parseInt(br.readLine());
System.out.println("Name:");
String na=br.readLine();
System.out.println("Computer Total of SY:");
int ct1=Integer.parseInt(br.readLine());
System.out.println("Maths Total of SY:");
int mt1=Integer.parseInt(br.readLine());
System.out.println("Electronics Total of SY:");
int et1=Integer.parseInt(br.readLine());
System.out.println("Theory Total of TY:");
int t1=Integer.parseInt(br.readLine());
System.out.println("Practical Total of TY");
int p=Integer.parseInt(br.readLine());
double avg=((ct1+mt1+et1+t1+p)/5);
if (avg>=70.0)
g="A";
else if(avg<70.0 && avg>=60.0)
g="B";
else if(avg<60.0 && avg>=50.0)
g="C";
else if(avg<50.0 && avg>=40.0)
g="Pass Class";
else
g="Fail";
s[i]=new set2b2(r,na,ct1,mt1,et1,t1,p,g);
s[i].display(ct1,mt1,et1,t1,p,g);
}
}
}
/*
OUTPUT =
How many records to be created:
2
Enter details of record no.:1
Roll Number:
509
Name:
NADAF
Computer Total of SY:
89
Maths Total of SY:
75
Electronics Total of SY:
74
Theory Total of TY:
222
Practical Total of TY
247
roll no 509
name NADAF
total of computer for sy: 89
total of maths for sy: 75
total of electronic for sy: 74
total of theory for ty: 222
total of practicals for ty: 247
grade:
A
Enter details of record no.:2
Roll Number:
506
Name:
MALI
Computer Total of SY:
90
Maths Total of SY:
58
Electronics Total of SY:
76
Theory Total of TY:
216
Practical Total of TY
220
roll no 506
name MALI
total of computer for sy: 90
total of maths for sy: 58
total of electronic for sy: 76
total of theory for ty: 216
total of practicals for ty: 220
grade:
A
*/
sem 2
Accept “n” integers from the user and store them in a collection .Display them in
the sorted order .The collection should not accept duplicate elements (Use suitable
collection ).search for a particular element using predefined search method in the
collection framework .
/*---------------------------------------------------------------------------------------
1. Accept n integers from the user and store them in a collection. Display them in the
sorted order. The collection should not accept duplicate elements. (Use a suitable
collection).
------------------------------------------------------------------------------------------*/

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

class collection1
{
public static void main(String[] args) throws Exception
{
int num,ele,i;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
ArrayList al=new ArrayList();
System.out.println("Enter the no for how many element to have:");
num=Integer.parseInt(br.readLine());
for(i=0;i<num;i++)
{
System.out.println("Enter the elements in position:"+i);
ele=Integer.parseInt(br.readLine());
al.add(ele);
}

System.out.println("The elements of ArrayList before:"+al);


Collections.sort(al);
System.out.println("The elements of ArrayList after sort:"+al);
}
}
/*------------------------------output----------
[root@localhost ~]# java collection1
Enter the no for how many element to have:
5
Enter the elements in position:0
5
Enter the elements in position:1
3
Enter the elements in position:2
7
Enter the elements in position:3
2
Enter the elements in position:4
8
The elements of ArrayList before:[5, 3, 7, 2, 8]
The elements of ArrayList after sort:[2, 3, 5, 7, 8]
-------------------------------------------------------*/

slip 21
sem 1
Define a Student class (roll number, name, percentage).Define a default and
parameterized constructor. Keep a count of 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. Modify
program to create “n” objects of the Student class. Accept details for each object.
Define static method “sort Student” which sorts the array on the basis of
percentage.

import java.io.*;

class Student
{
int rollno;
String name;
float perc;
static int count;

Student()//defoult constructor
{
rollno=0;
name=" ";
perc=0.0f;
}

Student(int rollno,String name,float perc)//parameterized constructor


{

this.rollno=rollno;
this.name=name;
this.perc=perc;
count++;
System.out.println("Object created No ="+count);

static void display()//satic method


{
System.out.println("Total number of objects created now is ="+count);

public String toString()


{
return("Roll no = "+rollno+" "+"Name = "+name+" "+"Per = "+perc);
}
}

class set2a1 //main


{
public static void main(String args[]) throws IOException
{
int i,n;
Student s[]=new Student[5];//memory allocation
BufferedReader br=new BufferedReader (new InputStreamReader(System.in));
System.out.println("Enter how many records");
n=Integer.parseInt(br.readLine());
for( i=0;i<n;i++)
{
System.out.println("Enter rollno,name,percntage");
int rno=Integer.parseInt(br.readLine());
String name=br.readLine();
float perc=Float.parseFloat(br.readLine());
s[i]=new Student(rno,name,perc);
Student.display();//static method called

System.out.println("The details of each objects");


for(i=0;i<n;i++)
{
System.out.println(s[i]);
}
}
}
/*
OUTPUT =
Enter how many records
2
Enter rollno,name,percntage
509
NADAF
61
Object created No =1
Total number of objects created now is =1
Enter rollno,name,percntage
506
MALI
55
Object created No =2
Total number of objects created now is =2
The details of each objects
Roll no = 509 Name = NADAF Per = 61.0
Roll no = 506 Name = MALI Per = 55.0
*/

sem 2
Accept “n” integers from the user and store them in a collection .Display them in
the sorted order .The collection should not accept duplicate elements (Use suitable
collection ).search for a particular element using predefined search method in the
collection framework .
/*---------------------------------------------------------------------------------------
1. Accept n integers from the user and store them in a collection. Display them in the
sorted order. The collection should not accept duplicate elements. (Use a suitable
collection).
------------------------------------------------------------------------------------------*/

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

class collection1
{
public static void main(String[] args) throws Exception
{
int num,ele,i;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
ArrayList al=new ArrayList();
System.out.println("Enter the no for how many element to have:");
num=Integer.parseInt(br.readLine());
for(i=0;i<num;i++)
{
System.out.println("Enter the elements in position:"+i);
ele=Integer.parseInt(br.readLine());
al.add(ele);
}

System.out.println("The elements of ArrayList before:"+al);


Collections.sort(al);
System.out.println("The elements of ArrayList after sort:"+al);
}
}
/*------------------------------output----------
[root@localhost ~]# java collection1
Enter the no for how many element to have:
5
Enter the elements in position:0
5
Enter the elements in position:1
3
Enter the elements in position:2
7
Enter the elements in position:3
2
Enter the elements in position:4
8
The elements of ArrayList before:[5, 3, 7, 2, 8]
The elements of ArrayList after sort:[2, 3, 5, 7, 8]
-------------------------------------------------------*/
slip 22:-
sem1:-
Write a menu driven program to perform the following operations. Accept
operation accept the two numbers using input dialog box. GCD will compute the
GCD of two numbers and display it in 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 Numbers implements ActionListener,ItemListener


{
JFrame f;
JMenu m1,m2,m3,m4;
JMenuBar mb;
JMenuItem m[];
JRadioButtonMenuItem r1,r2;
ButtonGroup b;
JLabel l;
JTextField t;
JPanel p;
StringBuffer ss=new StringBuffer();
int sel,n;
int arr[]=new int [20];
double res;

public Numbers()
{
f = new JFrame("Numbers");
sel=1;res=0;
p=new JPanel();
mb=new JMenuBar();
m1=new JMenu("File");
m2=new JMenu("Compute");
m3=new JMenu("Operation");
m4=new JMenu("Sort");
l=new JLabel("Numbers");
t=new JTextField(20);
b=new ButtonGroup();
r1=new JRadioButtonMenuItem("Ascending");
r1.addItemListener(this);
r2=new JRadioButtonMenuItem("Descending");
r2.addItemListener(this);
b.add(r1);b.add(r2);
String
str[]={"Load","Save","Exit","Sum","Average","Maximum","Minimum","Median","Search"};
m=new JMenuItem[str.length];
for(int i=0;i<str.length;i++)
{
m[i]=new JMenuItem(str[i]);
m[i].addActionListener(this);
}
f.setLayout(new BorderLayout());
p.add(l);
p.add(t);
f.add(p,BorderLayout.CENTER);

mb.add(m1);
mb.add(m2);
mb.add(m3);
m1.add(m[0]);
m1.add(m[1]);
m1.addSeparator();
m1.add(m[2]);
m2.add(m[3]);
m2.add(m[4]);
m2.add(m[5]);
m2.add(m[6]);
m2.add(m[7]);
m3.add(m[8]);
m3.add(m4);
m4.add(r1);
m4.add(r2);

f.add(mb,BorderLayout.NORTH);
f.setSize(300,200);
f.setVisible(true);
f.setLocation(500,200);
f.setDefaultCloseOperation(3);

public void itemStateChanged(ItemEvent ii)


{
if(r1.isSelected())
{
sortasc();
}

else if(r2.isSelected())
{
sortdesc();
}

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

public 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();
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("num.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("Sum"))
{
t.setText(new Integer(givesum()).toString());
}
else if(s.equals("Average"))
{
t.setText(new Double(giveavg()).toString());
}
else if(s.equals("Maximum"))
{
t.setText(new Integer(givemax()).toString());
}
else if(s.equals("Minimum"))
{
t.setText(new Integer(givemin()).toString());
}
else if(s.equals("Median"))
{
t.setText(new Integer(givemed()).toString());
}
else if(s.equals("Save"))
{

char ch;
String sss = t.getText();
try{
FileOutputStream br1 = new FileOutputStream("number.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("Search"))
{
int ser=Integer.parseInt(JOptionPane.showInputDialog("Enter Number To Search"));
int a=0;
for(int i=0;i<n;i++)
{
if(arr[i]==ser)
{
t.setText("Number Present");
a=1;
}
if(a==0)
t.setText("Number Not Present");
}
}
}

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 int givemax()


{
int sum=arr[0];
for(int i=0;i<n;i++)
{
if(arr[i] > sum)
sum=arr[i];
}
return sum;
}

public int givemin()


{
int sum=arr[0];
for(int i=0;i<n;i++)
{
if(arr[i] < sum)
sum=arr[i];
}
return sum;
}

public int givemed()


{
return arr[(n/2)];
}

public static void main(String arg[])


{
new Numbers();
}
}

/*Output
[student@localhost ~]$ javac Numbers.java
[student@localhost ~]$ java Numbers*/

sem 2
Accept “n” integers from the user and store them in a collection .Display them in
the sorted order .The collection should not accept duplicate elements (Use suitable
collection ).search for a particular element using predefined search method in the
collection framework .
/*---------------------------------------------------------------------------------------
1. Accept n integers from the user and store them in a collection. Display them in the
sorted order. The collection should not accept duplicate elements. (Use a suitable
collection).
------------------------------------------------------------------------------------------*/

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

class collection1
{
public static void main(String[] args) throws Exception
{
int num,ele,i;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
ArrayList al=new ArrayList();
System.out.println("Enter the no for how many element to have:");
num=Integer.parseInt(br.readLine());
for(i=0;i<num;i++)
{
System.out.println("Enter the elements in position:"+i);
ele=Integer.parseInt(br.readLine());
al.add(ele);
}

System.out.println("The elements of ArrayList before:"+al);


Collections.sort(al);
System.out.println("The elements of ArrayList after sort:"+al);
}
}
/*------------------------------output----------
[root@localhost ~]# java collection1
Enter the no for how many element to have:
5
Enter the elements in position:0
5
Enter the elements in position:1
3
Enter the elements in position:2
7
Enter the elements in position:3
2
Enter the elements in position:4
8
The elements of ArrayList before:[5, 3, 7, 2, 8]
The elements of ArrayList after sort:[2, 3, 5, 7, 8]
-------------------------------------------------------*/

slip 23
sem 1
Create an interface “CrediteCardInterface” with methods: view credit amount (),
use Card(),pay Card (),and increaseLimit(). Create a class “SilverCardCustemer”
(name, card number (16 digit),credit amount –initialized to 0 ,credit Limit –set to
50000 ) which implements above interface . Inherit class GoldCardCustmer from
SilverCardCustemer having same methods but credit Limit of 100000 .Create an
object of each class and perform operations .Display appropriate a massages for
success or failure of transaction (Use method overriding)

a. Use Card ()method increases the credit Amount by a specific amount up to

Credit Limit.

b .Pay Credit () reduces the credit Amount by a specific amount .

c. Increase Limit () increases the credit Limit for a Gold Card Customer (only
3

Times, not more than 5000 rupees each time)

import java.util.*;

interface CreditCardInterface
{
public void viewAmount();
public void useCard();
public void payCredit();
public void increaseLimit();

class SilverCardCustomer implements CreditCardInterface


{
String name;
long cardnumber;
double creditAmount=0;
double creditLimit=50000;
Scanner s=new Scanner(System.in);

SilverCardCustomer()
{

}
SilverCardCustomer(String n,long cnumber)
{
name=n;
cardnumber=cnumber;
}

public void viewAmount()


{
System.out.println("Your Credit Card Amount is :: "+creditAmount);
}

public void useCard()


{
System.out.println("Enter amount to be credited :: ");
double amt=s.nextDouble();
// creditAmount=creditAmount+amt;
if(creditAmount+amt>creditLimit)
{
System.out.println("Transaction is not possible\nYourCredit Card Amount is ::
"+creditAmount);

}
else
{
creditAmount=creditAmount+amt;
System.out.println("Your Credit Card Amount is :: "+creditAmount);
}

public void payCredit()


{
System.out.println("Enter amount to be paid :: ");
double amt=s.nextDouble();
creditAmount=creditAmount-amt;
System.out.println("Your Credit Card Amount is :: "+creditAmount);
}

public void increaseLimit()


{
System.out.println("Can not increase credit card limit for Silver Card Customers\n");
}
}

class GoldCardCustomer extends SilverCardCustomer


{
String name;
long cardnumber;
double creditAmount=0;
double creditLimit=100000;
static int count=0;
Scanner s=new Scanner(System.in);

GoldCardCustomer()
{

}
GoldCardCustomer(String n,long cnumber)
{
name=n;
cardnumber=cnumber;
}

public void viewAmount()


{
System.out.println("Your Credit Card Amount is :: "+creditAmount);
}

public void useCard()


{
System.out.println("Enter amount to be credited :: ");
double amt=s.nextDouble();
// creditAmount=creditAmount+amt;
if(creditAmount+amt>creditLimit)
{
System.out.println("Transaction is not possible\nYourCredit Card Amount is ::
"+creditAmount);

}
else
{
creditAmount=creditAmount+amt;
System.out.println("Your Credit Card Amount is :: "+creditAmount);
}

public void payCredit()


{
System.out.println("Enter amount to be paid :: ");
double amt=s.nextDouble();
creditAmount=creditAmount-amt;
System.out.println("Your Credit Card Amount is :: "+creditAmount);
}

public void increaseLimit()


{
count++;
System.out.println("Attempt:: "+count);
if(count<4)
{
creditLimit=creditLimit+5000;
System.out.println("Credit Limit Increased...");
}
else
{
System.out.println("Can not increase cresdit limit anymore...");
}
}
}

class CreditCard
{
public static void main(String[] args)
{
int op,ch;
Scanner s=new Scanner(System.in);

SilverCardCustomer scc=new SilverCardCustomer("Ashwini",1011);


GoldCardCustomer gcc=new GoldCardCustomer("Sonal",20173);
do
{
System.out.println("For Silvar card Customers :-\n");
System.out.println("Enter\n1.View Balance\n2.To use card\n3.To Pay amount
\n4.Increase credit card limit\n");

op=s.nextInt();

switch(op)
{
case 1:
scc.viewAmount();
break;
case 2:
scc.useCard();
break;
case 3:
scc.payCredit();
break;
case 4:
scc.increaseLimit();
break;
}
System.out.println("Enter 1 to continue...");
ch=s.nextInt();
}while(ch==1);

do
{
System.out.println("For Gold card Customers :-\n");
System.out.println("Enter\n1.View Balance\n2.To use card\n3.To Pay amount
\n4.Increase credit card limit\n");

op=s.nextInt();

switch(op)
{
case 1:
gcc.viewAmount();
break;
case 2:
gcc.useCard();
break;
case 3:
gcc.payCredit();
break;
case 4:
gcc.increaseLimit();
break;
}
System.out.println("Enter 1 to continue...");
ch=s.nextInt();
}while(ch==1);
}

sem 2
Accept “n” integers from the user and store them in a collection .Display them in
the sorted order .The collection should not accept duplicate elements (Use suitable
collection ).search for a particular element using predefined search method in the
collection framework .
/*---------------------------------------------------------------------------------------
1. Accept n integers from the user and store them in a collection. Display them in the
sorted order. The collection should not accept duplicate elements. (Use a suitable
collection).
------------------------------------------------------------------------------------------*/

import java.util.*;
import java.io.*;
class collection1
{
public static void main(String[] args) throws Exception
{
int num,ele,i;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
ArrayList al=new ArrayList();
System.out.println("Enter the no for how many element to have:");
num=Integer.parseInt(br.readLine());
for(i=0;i<num;i++)
{
System.out.println("Enter the elements in position:"+i);
ele=Integer.parseInt(br.readLine());
al.add(ele);
}

System.out.println("The elements of ArrayList before:"+al);


Collections.sort(al);
System.out.println("The elements of ArrayList after sort:"+al);
}
}
/*------------------------------output----------
[root@localhost ~]# java collection1
Enter the no for how many element to have:
5
Enter the elements in position:0
5
Enter the elements in position:1
3
Enter the elements in position:2
7
Enter the elements in position:3
2
Enter the elements in position:4
8
The elements of ArrayList before:[5, 3, 7, 2, 8]
The elements of ArrayList after sort:[2, 3, 5, 7, 8]
-------------------------------------------------------*/
slip 24
sem 1
write a program to create a super class Vehicle having members Company and
price. Derive two different classes Light Motor Vehicle (mileage) and Heavy
motor Vehicle (capacity _in_ tons). Accept the information for “n” vehicles and
display the information in appropriate form. While taking data, asked user about
the type of vehicle first.
import java.util.*;

class Vehicle
{
String company;
double price;
Scanner s=new Scanner(System.in);

void accept()
{
System.out.println("Enter Company Name :: ");
company=s.next();
System.out.println("Enter Price :: ");
price=s.nextDouble();
}
void display()
{
System.out.println("Company Name ::"+company);
System.out.println("Price ::"+price);
}

class LightMotorVehicle extends Vehicle


{
double mileage;

void accept()
{
super.accept();
System.out.println("Enter Mileage :: ");
mileage=s.nextDouble();
}

void display()
{
System.out.println("For Light Motor Vehicle :: ");
super.display();
System.out.println("Mileage ::"+mileage);
}

class HeavyMotorVehicle extends Vehicle


{
double capacity;

void accept()
{
super.accept();
System.out.println("Enter Capacity in tons :: ");
capacity=s.nextDouble();
}

void display()
{
System.out.println("For Heavy Motor Vehicle :: ");
super.display();
System.out.println("Capacity in tons :: "+capacity);
}

class vehicleDemo
{
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
System.out.println("Enter how many objects to be created :: ");
int n=s.nextInt();

LightMotorVehicle[] l=new LightMotorVehicle[n];


HeavyMotorVehicle[] h=new HeavyMotorVehicle[n];

int lcnt=0;
int hcnt=0;

for(int i=0;i<n;i++)
{
System.out.println("Enter \n 1.Light Motor Vehicle\n 2.Heavy Motor Vehicle");
int ch=s.nextInt();

if(ch==1)
{
l[lcnt]=new LightMotorVehicle();
l[lcnt].accept();
lcnt++;
}
else if(ch==2)
{
h[hcnt]=new HeavyMotorVehicle();
h[hcnt].accept();
hcnt++;
}
}

for(int i=0;i<lcnt;i++)
{
l[i].display();

}
for(int i=0;i<hcnt;i++)
{
h[i].display();
}
}
}

sem 2
Accept “n” integers from the user and store them in a collection .Display them in
the sorted order .The collection should not accept duplicate elements (Use suitable
collection ).search for a particular element using predefined search method in the
collection framework .
/*---------------------------------------------------------------------------------------
1. Accept n integers from the user and store them in a collection. Display them in the
sorted order. The collection should not accept duplicate elements. (Use a suitable
collection).
------------------------------------------------------------------------------------------*/

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

class collection1
{
public static void main(String[] args) throws Exception
{
int num,ele,i;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
ArrayList al=new ArrayList();
System.out.println("Enter the no for how many element to have:");
num=Integer.parseInt(br.readLine());
for(i=0;i<num;i++)
{
System.out.println("Enter the elements in position:"+i);
ele=Integer.parseInt(br.readLine());
al.add(ele);
}

System.out.println("The elements of ArrayList before:"+al);


Collections.sort(al);
System.out.println("The elements of ArrayList after sort:"+al);
}
}
/*------------------------------output----------
[root@localhost ~]# java collection1
Enter the no for how many element to have:
5
Enter the elements in position:0
5
Enter the elements in position:1
3
Enter the elements in position:2
7
Enter the elements in position:3
2
Enter the elements in position:4
8
The elements of ArrayList before:[5, 3, 7, 2, 8]
The elements of ArrayList after sort:[2, 3, 5, 7, 8]
-------------------------------------------------------*/
slip 25
sem 1
/*Define a class employee having private menmbers int id,name,dept,salary.Define default and parametrised
cTOR.create a subclass called manager with private member bonus.Define methods accept and display in both the
classes.create n objects of manager class & display the details of manager having maximum total
salary=salary+bonus.
*/
import java.util.*;

class Emp
{
private int id;
private String ename,dept;
double salary;
Emp()
{

}
Emp(int id,String ename,String dept,double salary)
{
this.id=id;
this.ename=ename;
this.dept=dept;
this.salary=salary;
}
void accept()
{
Scanner s=new Scanner(System.in);
System.out.println("Enter the Employee id : ");
id=s.nextInt();

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


ename=s.next();

System.out.println("Enter the Employee salary : ");


salary=s.nextDouble();

System.out.println("Enter the Employee department : ");


dept=s.next();
}

void display()
{
System.out.println(" Employee id : "+id);
System.out.println(" Employee name : "+ename);
System.out.println(" Employee department : "+dept);
System.out.println(" Employee salary : "+salary);
}
}
class Manager extends Emp
{
private double bonus;
double totalsal;

void accept()
{
super.accept();
System.out.println("Enter the bonus amount : ");
Scanner s=new Scanner(System.in);
bonus=s.nextDouble();
totalsal=salary+bonus;
}
void display()
{
System.out.println("***********************************");
super.display();
System.out.println("The total salary amount = "+totalsal);
System.out.println("***********************************");
}

static void sort(Manager[] m)


{
for(int i=1;i<m.length;i++)
{
for(int j=0;j<m.length-i;j++)
{
if(m[j].totalsal<m[j+1].totalsal)
{
Manager temp=m[j];
m[j]=m[j+1];
m[j+1]=temp;
}
}
}
}
}

class EmpInfo
{
public static void main(String[] args)
{
Manager m[]=new Manager[3];
Scanner s=new Scanner(System.in);
System.out.println("Enter number of Employee");
int n=s.nextInt();
System.out.println("Enter information of "+n+" Employees");
for(int i=0;i<m.length;i++)
{
m[i]=new Manager();
m[i].accept();
}
Manager.sort(m);

for(int i=0;i<m.length;i++)
{
m[i].display();
}
System.out.println("Maximum salary = ");
m[0].display();

}
}
sem 2
/*
1.1. 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 a page total of what ever the purchase has been done and
print the total. (Use HttpSession)
*/

->first.html

<html>
<head>
<title>Insert title here</title>
</head>
<body>
<form action="Shop1" action="get">
<h3>Plz, Fill the following Cutomer Information </h3><br>
Name<input type="text" name="cname"> <br>
Address<input type="text" name="cadd"><br>
Mobile No<input type="text" name="cmob"><br>
<hr>
<h3> ****** Product List PAGE 1*****</h3>
<input type="checkbox" name="page1" value="300"> C programming <br>
<input type="checkbox" name="page1" value="400"> C++ programming<br>
<input type="checkbox" name="page1" value="700"> JAVA programming<br>
<input type="checkbox" name="page1" value="300"> Data Structure<br>
<input type="submit" value="Next">
</form>
</body>
</html>

->shop1.java

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

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class Shop1 extends HttpServlet {


private static final long serialVersionUID = 1L;

public Shop1() {
super();
// TODO Auto-generated constructor stub
}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
PrintWriter pw=response.getWriter();
String cname=request.getParameter("cname");
String cadd=request.getParameter("cadd");
String cmob=request.getParameter("cmob");
String page1[]=request.getParameterValues("page1");

HttpSession hs=request.getSession(true);
hs.setAttribute("cname",cname);
hs.setAttribute("cadd",cadd);
hs.setAttribute("cmob",cmob);
hs.setAttribute("page1",page1);
pw.println("<html>");
pw.println("<body>");
pw.println("<form action=Shop2 method=post>");
pw.println("<h3> ****** Products List Page2 *********</h3>");
pw.println("<input type=checkbox name=page2 value=200> PHP <br>");
pw.println("<input type=checkbox name=page2 value=500> HTML <br>");
pw.println("<input type=checkbox name=page2 value=600> PL/SQL <br>");
pw.println("<input type=checkbox name=page2 value=700> Advance JAVA <br>");
pw.println("<input type=submit name=Submit value= Next <br>");
pw.println("</form>");
pw.println("</body></html>");
}

->shop2.java

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

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class Shop2 extends HttpServlet {


private static final long serialVersionUID = 1L;

public Shop2() {
super();
// TODO Auto-generated constructor stub
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
PrintWriter pw=response.getWriter();
HttpSession hs=request.getSession(true);
String cname=(String) hs.getAttribute("cname");
String cadd=(String) hs.getAttribute("cadd");
String cmob=(String) hs.getAttribute("cmob");
String page1[]=(String[]) hs.getAttribute("page1");
String page2[]=request.getParameterValues("page2");

double page1total=0,page2total=0;
for(int i=0;i<page1.length;i++)
page1total=page1total+Double.parseDouble(page1[i]);
for(int i=0;i<page2.length;i++)
page2total=page2total+Double.parseDouble(page2[i]);
double total=0;
total=page1total+page2total;

pw.println("<html>");
pw.println("<body>");
pw.println("<h2>Customer Information</h2>");
pw.println("<h3>Customer Name:"+cname);
pw.println("<h3>Customer Address:"+cadd);
pw.println("<h3>Customer Phone No:"+cmob);
pw.println("<h3>Page 1 Total:"+page1total);
pw.println("<h3>Page 2 Total:"+page2total);
pw.println("<h3>Total Amount:"+total);

pw.println("</body>");
pw.println("</html>");

}
}

You might also like