Java Assignment

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

SHUBHAM B.

HINGADE
T.Y.BSc. Comp. Sci.
Modern College of Art’s Science and Commerce, Shivajinagar, Pune.
Sub: LAB COURSE II (JAVA PROGRAMING I AND II )
ENROLLMENT NO: 38656

ASSIGNMENT 1

Array of Objects And Packages

SET A
Q1. 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.

Program Code:

import java.io.*;
class Student {
int rollNumber;
String name;
float per;
static int count=0;
public Student(){
rollNumber=0;
name=null;
per=0.0f;
}
public Student(int rollNumber,String name,float per){
this.rollNumber=rollNumber;
this.name=name;
this.per=per;
count++;
}
public static void count(){
System.out.println("Object "+(count)+" Created");
}
public void display(){
System.out.println("Roll Number: "+rollNumber);
System.out.println("Name: "+name);
System.out.println("Percentage: "+per);
System.out.println("------------------------------");
}
}
public class StudentMain {
public static void main(String [] args)throws IOException{
Student s1=new Student(1,"Rusher",56.76f);
Student.count();
Student s2=new Student(2,"Naren",89.67f);
Student.count();
Student s3=new Student(3,"Adi",99.54f);
Student.count();
s1.display();
s2.display();
s3.display();
}

Q2. Modify the above program to create n objects of the Student class. Accept details from
the user
for each object. Define a static method “sortStudent” which sorts the array on the basis of
percentage.

Program Code:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
class Student
{
                int rollno;
                String name;
                float per;
                static int count;

                Student(){}
                Student(String n,float p)
        {
                                count++;
                                rollno=count;
                                name=n;
                                per=p;

        }
                void display()
        {
                                System.out.println(rollno+"\t"+name+"\t"+per);
        }
                float getper()
        {
                                return per;
        }
                static void counter()
        {
                                System.out.println(count+" object is created");
        }
                public static void sortStudent(Student s[],int n)
        {
                                for(int i=n-1;i>=0;i--)
                {
                                                for(int j=0;j<i;j++)
                        {
                                                                if(s[j].getper()>s[j+1].getper())
                                {
                                                                                Student t=s[j];
                                                                                s[j]=s[j+1];
                                                                                s[j+1]=t;
                                }
                        }
                }
                                for(int i=0;i<n;i++)
                                                s[i].display();

        }
}
class Studentclass
{
                public static void main(String args[]) throws IOException
        {
                                BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
                                System.out.println("Enter no. of Student:");
                                int n=Integer.parseInt(br.readLine()); 
                                Student p[]=new Student[n];
                                for(int i=0;i<n;i++)
                {
                                                System.out.print("Enter Name:");
                                                String name=br.readLine();
                                                System.out.print("Enter percentage:");
                                                float per=Float.parseFloat(br.readLine());
                                                p[i]=new Student(name,per);
                                                p[i].counter();
                }
                                Student.sortStudent(p,Student.count);
        }
}

SET B

Q1. Create a package named Series having three different classes to print series:
a. Prime numbers b. Fibonacci series c. Squares of numbers
Write a program to generate ‘n’ terms of the above series.

Program Code 1:

package series;

public class Prime {


 int flag;
 public void prime(int n){ 
 for(int i=2;i<n;i++){
 if(n%i==0)
 {
 flag=0;
 break;
 }
 else
 flag=1;
 }
 if(flag==1)
 System.out.println(n+" is a prime number.");
 else System.out.println(n+" is not a prime number.");
 }
 public void fibonacci(int n){
 int first=0, second=1, c, next;
 System.out.println("Fibonacci Series:");
 for(int i=0;i<=n;i++)
 {
 if(i<=1)
 next=i;
 else
 {
 next=first+second;
 first=second;
 second=next;
 }
 System.out.println(next);
 }
 }
 public void square(int n){
 System.out.println("Square of the number is "+(n*n));
 }
}

Program Code 2:

import series.*;
import java.io.*;
public class SeriesMain {
  public static void main(String [] args)throws IOException{
 Prime p=new Prime();
 int i;
 BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
 do
 {
 System.out.println("Enter a number / 0 to exit");
 i=Integer.parseInt(br.readLine());
 p.prime(i);
 p.fibonacci(i);
 p.square(i);
 }
 while(i>0);
 }
}

Q2. Write a Java program to create a Package “SY” which has a class SYMarks (members –
ComputerTotal, MathsTotal, and ElectronicsTotal). Create another package TY which has a
class TYMarks (members – Theory, Practicals). Create n objects of Student class (having
rollNumber, name, SYMarks and TYMarks). Add the marks of SY and TY computer subjects
and calculate the 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.

Program Code 1:
package Assignment2.SY;

import java.io.BufferedReader;
import java.io.*;

public class SYClass {


public int ct,mt,et;
public void get() throws IOException{
System.out.println("Enter marks of students for computer, maths and electronics subject out
of 200 ");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
ct=Integer.parseInt(br.readLine());
mt=Integer.parseInt(br.readLine());
et=Integer.parseInt(br.readLine());
}

}
Program Code 2:
package Assignment2.TY;

import java.io.*;
public class TYClass {
public int tm,pm;
public void get() throws IOException{
System.out.println("Enter the marks of the theory out of 400 and practicals out of 200: ");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
tm=Integer.parseInt(br.readLine());
pm=Integer.parseInt(br.readLine());
}

Program Code 3:

package Assignment2;
import Assignment2.SY.*;
import Assignment2.TY.*;
import java.io.*;
class StudentInfo{
int rollno;
String name,grade;
public float gt,tyt,syt;
public float per;
public void get() throws IOException{
System.out.println("Enter roll number and name of the student: ");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
rollno=Integer.parseInt(br.readLine());
name=br.readLine();
}

}
public class StudentMarks {
public static void main(String[] args) throws IOException{

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


System.out.println("Enter the number of students:");
int n=Integer.parseInt(br.readLine());
SYClass sy[]=new SYClass[n];
TYClass ty[]=new TYClass[n];
StudentInfo si[]=new StudentInfo[n];
for(int i=0;i<n;i++)
{
si[i]=new StudentInfo();
sy[i]=new SYClass();
ty[i]=new TYClass();

si[i].get();
sy[i].get();
ty[i].get();

si[i].syt=sy[i].ct+sy[i].et+sy[i].mt;
si[i].tyt=ty[i].pm+ty[i].tm;
si[i].gt=si[i].syt+si[i].tyt;
si[i].per=(si[i].gt/1200)*100;

if(si[i].per>=70) si[i].grade="A";
else if(si[i].per>=60) si[i].grade="B";
else if(si[i].per>=50) si[i].grade="C";
else if(si[i].per>=40) si[i].grade="Pass";
else si[i].grade="Fail";

}
System.out.println("Roll No\tName\tSyTotal\tTyTotal\tGrandTotal\tPercentage\tGrade");
for(int i=0;i<n;i++)
{
System.out.println(si[i].rollno+"\t"+si[i].name+"\t"+si[i].syt+"\t"+si[i].tyt+"\t"+si[i].gt+"\t\
t"+si[i].per+"\t\t"+si[i].grade);

}
}

}
ASSIGNMENT 2

Inheritance of Interfaces

SET A

Q1. Define a class Employee having private members – id, name, department, salary. Define
default and parameterized constructors. Create a subclass called “Manager” with private
member
bonus. Define methods accept and display in both the classes. Create n objects of the
Manager
class and display the details of the manager having the maximum total salary (salary+bonus)

Program Code:

import java.io.*;
class Emp{
private int id;
private double salary;
private String name,dept;
double total;
double sal=salary;
public Emp(){
id=0;
salary=0.0;
name="";
dept="";
}
public Emp(int id,double salary, String name, String dept){
this.id=id;
this.salary=salary;
this.name=name;
this.dept=dept;
}
public void accept() throws IOException{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter id of employee: ");
id=Integer.parseInt(br.readLine());
System.out.println("Enter name of employee: ");
name=br.readLine();
System.out.println("Enter salary of employee: ");
salary=Double.parseDouble(br.readLine());
System.out.println("Enter department of employee: ");
dept=br.readLine();
}
public double total(){
total=total+salary;
return total;
}
public void display(){
System.out.println("Emp Id: "+id);
System.out.println("Name: "+name);
System.out.println("Salary: "+salary);
System.out.println("Department: "+dept);
}
}

class Manager extends Emp{


private double bonus;
public void accept() throws IOException{
super.accept();
System.out.println("Enter Bonus of employee: ");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
bonus=Double.parseDouble(br.readLine());
super.total=bonus;
}
public void display(){
super.display();
System.out.println("Bonus: "+bonus);
System.out.println("Total Salary: "+total);
}
}

public class sa1 {


public static void main(String[] args) throws IOException{
Manager[] m=new Manager[10];
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the number of employees: ");
int n=Integer.parseInt(br.readLine());
for(int i=0;i<n;i++){
m[i]=new Manager();
m[i].accept();
m[i].total();
}
for(int i=0;i<n;i++){
m[i].display();
System.out.println("---------------------------------");
}
double src=m[0].total;
int temp=0;
for(int i=1;i<n;i++){
if(src<m[i].total) 
{
src=m[i].total;
temp=i;
}
}
System.out.println("The Employee having the maximum Total salary is :");
m[temp].display();
}

Q2. Create an abstract class Shape with methods calc_area and calc_volume. Derive three
classes
Sphere(radius) , Cone(radius, height) and Cylinder(radius, height), Box(length, breadth,
height)
from it. Calculate area and volume of all. (Use Method overriding).

Program Code:

import java.io.*;

abstract class Shape{


abstract public void calc_area();
abstract public void calc_volume();
final float pi=3.14f;
}

class Sphere extends Shape{


double r;
private double area;
private double volume;
public void accept() throws IOException{
System.out.println("Enter the radius of the Sphere: ");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
r=Double.parseDouble(br.readLine());
}
public void calc_area(){
area=pi*r*r;
}
public void calc_volume(){

volume=1.33333333334*pi*r*r*r;
}
public void display(){
calc_area();
calc_volume();
System.out.println("The area of sphere is: "+area);
System.out.println("The volume of sphere is: "+volume);
}
}

class Cone extends Shape{


double h,r,area,volume;

public void accept() throws IOException{


System.out.println("Enter radius and height of the Cone: ");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
r=Double.parseDouble(br.readLine());
h=Double.parseDouble(br.readLine());
}
public void calc_area(){

double sq=h*h+r*r;
area=pi*r*(r+java.lang.Math.sqrt(sq));
}
public void calc_volume(){
double d=h/3;
volume=pi*r*r*d;
}
public void display(){
calc_area();
calc_volume();
System.out.println("The area of Cone is: "+area);
System.out.println("The volume of Cone is: "+volume);
}
}

class Cylinder extends Shape{


double r,h,area,volume;
public void accept() throws IOException{
System.out.println("Enter radius and height of the Cylinder: ");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
r=Double.parseDouble(br.readLine());
h=Double.parseDouble(br.readLine());
}
public void calc_area(){
area=(2*pi*r*h)+(2*pi*r*r);
}
public void calc_volume(){
volume=pi*r*r*h;
}
public void display(){
calc_area();
calc_volume();
System.out.println("The area of Cylinder is: "+area);
System.out.println("The volume of Cylinder is: "+volume);
}
}

class Box extends Shape{


double l,b,h,area,volume;
public void accept() throws IOException{
System.out.println("Enter length, breadth and height of the Box: ");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
l=Double.parseDouble(br.readLine());
b=Double.parseDouble(br.readLine());
h=Double.parseDouble(br.readLine());
}
public void calc_area(){
area=(2*l*b)+(2*b*h)+(2*l*h);
}
public void calc_volume(){
volume=l*b*h;
}
public void display(){
calc_area();
calc_volume();
System.out.println("The area of Box is: "+area);
System.out.println("The volume of Box is: "+volume);
}
}

public class sa2 {


public static void main(String [] args)throws IOException{
Sphere s=new Sphere();
s.accept();
s.display();
Cone co=new Cone();
co.accept();
co.display();
Cylinder cy=new Cylinder();
cy.accept();
cy.display();
Box b=new Box();
b.accept();
b.display();
}
}

Q3. Write a Java program to create a super class Vehicle having members Company and
price.
Derive 2 different classes LightMotorVehicle (members – mileage) and HeavyMotorVehicle
(members – capacity-in-tons). Accept the information for n vehicles and display the
information
in appropriate form. While taking data, ask the user about the type of vehicle first.

Program Code:

import java.io.*;
class Vehicle{
String company;
double price;
public void accept() throws IOException{
System.out.println("Enter the Company and price of the Vehicle: ");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
company=br.readLine();
price=Double.parseDouble(br.readLine());

}
public void display(){
System.out.println("Company: "+company+" Price: "+price);
}

}
class LightMotorVehicle extends Vehicle{
double mileage;
public void accept() throws IOException{
super.accept();
System.out.println("Enter the mileage of the vehicle: ");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
mileage=Double.parseDouble(br.readLine());
}
public void display(){
super.display();
System.out.println("Mileage: "+mileage);
}
}
class HeavyMotorVehicle extends Vehicle{
double captons;
public void accept() throws IOException{
super.accept();
System.out.println("Enter the capacity of vehicle in tons: ");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
captons=Double.parseDouble(br.readLine());
}
public void display(){
super.display();
System.out.println("Capacity in tons: "+captons);
}
}

public class sa3 {


public static void main(String [] args) throws IOException{
int i;
System.out.println("Enter the type of vehicle: ");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("1.Light Vehicle");
System.out.println("2.Heavy Vehicle");
int ch=Integer.parseInt(br.readLine());
switch(ch){
case 1:
System.out.println("Enter the number of Light vehicles: ");
int n=Integer.parseInt(br.readLine());
LightMotorVehicle [] l=new LightMotorVehicle[n];
for(i=0;i<n;i++){
l[i]=new LightMotorVehicle();
l[i].accept();
}
for(i=0;i<n;i++){
l[i].display();
}
break;
case 2:
System.out.println("Enter the number of Heavy vehicles: ");
int m=Integer.parseInt(br.readLine());
HeavyMotorVehicle [] h=new HeavyMotorVehicle[m];
for(i=0;i<m;i++){
h[i]=new HeavyMotorVehicle();
h[i].accept();
}
for(i=0;i<m;i++){
h[i].display();
}
break;
}
}

}
SET B

Q1. Define an abstract class “Staff” with members name and address. Define two sub-classes
of this class – “FullTimeStaff” (department, salary) and “PartTimeStaff” (number-of-hours,
rate-per- hour). Define appropriate constructors. Create n objects which could be of either
FullTimeStaff or PartTimeStaff class by asking the user’s choice. Display details of all
“FullTimeStaff” objects and all “PartTimeStaff” objects.

Program Code:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
abstract class Staff{
String name,address;
}
class FullTimeStaff extends Staff{
String department;
double salary;
public void accept() throws IOException{
System.out.println("Enter the name, address, department and salary: ");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
name=br.readLine();
address=br.readLine();
department=br.readLine();
salary=Double.parseDouble(br.readLine());
}
public void display(){
System.out.println("Name: "+name);
System.out.println("Address: "+address);
System.out.println("Department: "+department);
System.out.println("Salary: "+salary);
System.out.println("----------------------");
}
}
class PartTimeStaff extends Staff{
int hours, rate;
public void accept() throws IOException{
System.out.println("Enter the name, address, No of working hours and rate per hour: ");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
name=br.readLine();
address=br.readLine();
hours=Integer.parseInt(br.readLine());
rate=Integer.parseInt(br.readLine());
}
public void display(){
System.out.println("Name: "+name);
System.out.println("Address: "+address);
System.out.println("No of Working Hours: "+hours);
System.out.println("Rate per hour: "+rate);
System.out.println("----------------------");
}
}

public class sb1 {


public static void main(String [] args) throws IOException{
int i;
System.out.println("Select Any One: ");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("1.Full Time Staff");
System.out.println("2.Part Time Satff");
int ch=Integer.parseInt(br.readLine());
switch(ch){
case 1:
System.out.println("Enter the number of Full Time Staff: ");
int n=Integer.parseInt(br.readLine());
FullTimeStaff [] l=new FullTimeStaff[n];
for(i=0;i<n;i++){
l[i]=new FullTimeStaff();
l[i].accept();
}
for(i=0;i<n;i++){
l[i].display();
}
break;
case 2:
System.out.println("Enter the number of Part Time Staff: ");
int m=Integer.parseInt(br.readLine());
PartTimeStaff [] h=new PartTimeStaff[m];
for(i=0;i<m;i++){
h[i]=new PartTimeStaff();
h[i].accept();
}
for(i=0;i<m;i++){
h[i].display();
}
break;

}
}
}

Q2. Create an interface “CreditCardInterface” with methods : viewCreditAmount(),


useCard(), payCredit() and increaseLimit(). Create a class SilverCardCustomer (name,
cardnumber (16 digits), creditAmount – initialized to 0, creditLimit - set to 50,000 ) which
implements the above interface. Inherit class GoldCardCustomer from SilverCardCustomer
having the same methods but creditLimit of 1,00,000. Create an object of each class and
perform operations. Display appropriate messages for success or failure of transactions. (Use
method overriding)
i. useCard() method increases the creditAmount by a specific amount upto creditLimit
ii. payCredit() reduces the creditAmount by a specific amount.
iii. increaseLimit() increases the creditLimit for GoldCardCustomers (only 3 times, not more
than 5000Rs. each time)

Program Code:

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

class SliverCardCustomer implements CreditCard


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

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

public void viewCreditAmount()


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

public void getdata()throws IOException


{
System.out.println("Enter the name : ");
String name=(br.readLine());
System.out.println("Enter the card number :");
card_no=Integer.parseInt(br.readLine());
System.out.println("Enter Credit amount : ");
creditAmount=Double.parseDouble(br.readLine());
}

public void payCard()throws IOException


{
System.out.println("Enter amount to be pay");
double pay=Double.parseDouble(br.readLine()) ;
creditAmount=creditAmount+pay;
System.out.println("Balance is paid");
}
public void useCard()throws IOException
{

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


double amount=Double.parseDouble(br.readLine());
if(amount<creditAmount)
{
creditAmount=creditAmount-amount;
viewCreditAmount();
System.out.println("Thanks for using the service") ;
}
else System.out.println("\nerror!");
}

public void increaseLimit()throws IOException


{
cnt++;
if(cnt<=3)
{
System.out.println("Enter amount limit to increse : ");
double amt=Double.parseDouble(br.readLine());
if(amt<=2500)
{
creaditLimit=creaditLimit+amt;
System.out.println("Amount limit to increse
Successfully : ");
}
System.out.println("You can't increse creadit amount more than
2500 at a time ");

}
else
System.out.println("You can't increse limit more than 3 times
");
}
}//end of class

class GoldCardCustomer extends SliverCardCustomer


{
static int cnt;
public void increaseLimit()throws IOException
{
cnt++;
if(cnt<=3)
{
System.out.println("Enter amount limit to increse : ");
double amt=Double.parseDouble(br.readLine());
if(amt<=5000)
{
creaditLimit=creaditLimit+amt;
System.out.println("Amount limit to increse
Successfully : ");
}
System.out.println("You can't increse creadit amount more than
2500 at a time ");

}
else
System.out.println("You can't increse limit more than 3 times
");
}

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

System.out.println("Enter the info for silver card holder : ");


SliverCardCustomer sc=new SliverCardCustomer();
sc.getdata();

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


GoldCardCustomer gc=new GoldCardCustomer();
gc.getdata();
do
{
System.out.println("1.Use silver card \n2.Pay credit for Silver
card\n3.Increse limit for silver card ") ;
System.out.println("4.Use Gold card \n5.Pay credit for Gold
card\n6.Increse limit for Gold card ") ;

System.out.println("0. exit") ;
System.out.println("Enter your choice : ") ;
ch=Integer.parseInt(br.readLine());

switch(ch)
{
case 1: sc.useCard();
break;
case 2:sc.payCard();
break ;
case 3:sc.increaseLimit();
break;
case 4:gc.useCard();
break;
case 5:gc.payCard();
break ;
case 6:gc.increaseLimit();
break;

case 0 :break;
}
}while(ch!=0);
}
}

ASSIGNMENT 3
Exception Handling

SET A

Q1. Define a class CricketPlayer (name, no_of_innings, no_times_notout, total_runs,


bat_avg).
Create an array of n player objects. Calculate the batting average for each player using a
static
method avg(). Handle appropriate exception while calculating average. Define a static
method
“sortPlayer” which sorts the array on the basis of average. Display the player details in sorted
order.

Program Code:

import java.io.*;
class Cricket {
String name;
int inning, tofnotout, totalruns;
float batavg;
public Cricket(){
name=null;
inning=0;
tofnotout=0;
totalruns=0;
batavg=0;

}
public void get() throws IOException{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the name, no of innings, no of times not out, total runs: ");
name=br.readLine();
inning=Integer.parseInt(br.readLine());
tofnotout=Integer.parseInt(br.readLine());
totalruns=Integer.parseInt(br.readLine());
}
public void put(){
System.out.println("Name="+name);
System.out.println("no of innings="+inning);
System.out.println("no times notout="+tofnotout);
System.out.println("total runs="+totalruns);
System.out.println("bat avg="+batavg);

}
static void avg(int n, Cricket c[]){
try{
for(int i=0;i<n;i++){
c[i].batavg=c[i].totalruns/c[i].inning;
}
}catch(ArithmeticException e){
System.out.println("Invalid arg");
}
}
static void sort(int n, Cricket c[]){
String temp1;
int temp2,temp3,temp4;
float temp5;
for(int i=0;i<n;i++){
for(int j=i+1;j<n;j++){
if(c[i].batavg<c[j].batavg){
temp1=c[i].name;
c[i].name=c[j].name;
c[j].name=temp1;

temp2=c[i].inning;
c[i].inning=c[j].inning;
c[j].inning=temp2;

temp3=c[i].tofnotout;
c[i].tofnotout=c[j].tofnotout;
c[j].tofnotout=temp3;

temp4=c[i].totalruns;
c[i].totalruns=c[j].totalruns;
c[j].totalruns=temp4;

temp5=c[i].batavg;
c[i].batavg=c[j].batavg;
c[j].batavg=temp5;
}
}
}
}
}

public class a4sa1 {


public static void main(String args[])throws IOException{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the limit:");
int n=Integer.parseInt(br.readLine());
Cricket c[]=new Cricket[n];
for(int i=0;i<n;i++){
c[i]=new Cricket();
c[i].get();
}
Cricket.avg(n,c);
Cricket.sort(n, c);
for(int i=0;i<n;i++){
c[i].put();
}

Q2. Define a class SavingAccount (acNo, name, balance). Define appropriate constructors
and operations withdraw(), deposit() and viewBalance(). The minimum balance must be 500.
Create an object and perform operations. Raise user defined InsufficientFundsException
when balance is not sufficient for withdraw operation.

Program Code:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.naming.InsufficientResourcesException;

class SavingAccount{
int acNo;
String name;
double balance;
public SavingAccount(){
acNo=0;
name=null;
balance=500.0;
}
public void accept()throws IOException{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the account number, name, and balance for the customer: ");
acNo=Integer.parseInt(br.readLine());
name=br.readLine();
balance=Double.parseDouble(br.readLine());

}
public void withdraw() throws IOException{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the amount you want to withdraw: ");
double wamt=Double.parseDouble(br.readLine());
try{
double bal=balance; bal=bal-wamt;
if(bal<500)
throw new InsufficientResourcesException("Insufficient Balance");
balance=balance-wamt;
System.out.println("Withdrawal Successful...!!!");
}
catch(InsufficientResourcesException e){
System.out.println("Exception: "+e.getMessage());
}
}
public void deposit() throws IOException{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the amount you want to deposit: ");
double damt=Double.parseDouble(br.readLine());
balance=balance+damt;
System.out.println("Deposit Successful....!!");
}
public void viewBalance(){
System.out.println("The balance is "+balance);
}

public class a4sa2 {


public static void main(String [] args) throws IOException{
System.out.println("Enter the number of customers: ");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int n=Integer.parseInt(br.readLine());
SavingAccount[] sa=new SavingAccount[n];
for(int i=0;i<n;i++){
sa[i]=new SavingAccount();
sa[i].accept();
}
int no=0;
System.out.println("Enter the customer Number");
no=Integer.parseInt(br.readLine());
no--;
int ch=0;
while(ch!=4){
System.out.println("1. Withdraw");
System.out.println("2. Deposit");
System.out.println("3. View Balance");
System.out.println("4. Quit");
System.out.println("Select Any Option:");
ch=Integer.parseInt(br.readLine());
switch(ch){
case 1: sa[no].withdraw();
break;
case 2: sa[no].deposit();
break;
case 3: sa[no].viewBalance();
break;
}
}
}

SET B

Q1. Define a class MyDate (day, month, year) with methods to accept and display a MyDate
object. Accept date as dd, mm, yyyy. Throw user defined exception “InvalidDateException”
if the date is invalid.
Examples of invalid dates : 12 15 2015, 31 6 1990, 29 2 2001

Program Code:

import java .io.*;


class InvalidDateException extends Exception
{
}
class MyDate
{
int day,mon,yr;

void accept(int d,int m,int y)


{
day=d;
mon=m;
yr=y;
}
void display()
{
System.out.println("Date is valid : "+day+"/"+mon+"/"+yr);
}
}
class DateMain
{
public static void main(String arg[]) throws Exception
{
System.out.println("Enter Date : dd mm yyyy ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int day=Integer.parseInt(br.readLine());
int mon=Integer.parseInt(br.readLine());
int yr=Integer.parseInt(br.readLine());
int flag=0;
try
{
if(mon<=0 || mon>12)

throw new InvalidDateException();


else
{
if(mon==1 || mon==3 || mon==5 || mon==7 || mon==8 || mon==10 || mon==12)
{
if(day>=1 && day <=31)
flag=1;
else
throw new InvalidDateException();
}
else if (mon==2)
{
if(yr%4==0)
{
if(day>=1 && day<=29)
flag=1;
else throw new InvalidDateException();
}
else
{
if(day>=1 && day<=28)
flag=1;
else throw new InvalidDateException();
}
}
else
{
if(mon==4 || mon == 6 || mon== 9 || mon==11)
{
if(day>=1 && day <=30)
flag=1;
else throw new InvalidDateException();
}
}
}
if(flag== 1)
{
MyDate dt = new MyDate();
dt.accept(day,mon,yr);
dt.display();
}
}
catch (InvalidDateException mm)
{
System.out.println("Invalid Date");
}

ASSIGNMENT 4
GUI Designing, Event Handling Applets

SET A

Q1. Write a program to create the following GUI and apply the changes to the text in the
TextField.

Program Code:

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

class Swing1 extends JFrame implements ItemListener


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

fontcb = new JComboBox();


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

bold = new JCheckBox("Bold");


size = new JLabel("Size");
italic = new JCheckBox("Italic");

sizecb = new JComboBox();


sizecb.addItem("10");
sizecb.addItem("12");
sizecb.addItem("16");
t = new JTextField(10);

p1.setLayout(new GridLayout(4,2));
p1.add(font);
p1.add(style);
p1.add(fontcb);
p1.add(bold);
p1.add(size);
p1.add(italic);
p1.add(sizecb);

p2.setLayout(new FlowLayout());
p2.add(t);

bold.addItemListener(this);
italic.addItemListener(this);
fontcb.addItemListener(this);
sizecb.addItemListener(this);

setLayout(new BorderLayout());
add(p1,BorderLayout.NORTH);
add(p2,BorderLayout.CENTER);

setSize(200, 200);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void itemStateChanged(ItemEvent ie)
{
String f = (String)fontcb.getSelectedItem();
System.out.println("font = "+f);
t.setFont(new Font(f,Font.BOLD,10));
String no =(String)sizecb.getSelectedItem();
int num=Integer.parseInt(no);

if(bold.isSelected())
{
t.setFont(new Font(f,Font.BOLD,num));
}
if(italic.isSelected())
{
t.setFont(new Font(f,Font.ITALIC,num));
}

}
public static void main(String args[])
{
Swing1 f1 = new Swing1();
}
}

Q2. Create the following GUI screen using appropriate layout managers. Accept the name,
class ,
hobbies of the user and display the selected options in a text box.

Program Code:

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

class Swing2 extends JFrame implements ActionListener


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

Swing2()
{

b1=new ButtonGroup();
p1=new JPanel();
p2=new JPanel();
b=new JButton("Clear");
b.addActionListener(this);

r1=new JRadioButton("FY");
r2=new JRadioButton("SY");
r3=new JRadioButton("TY");

b1.add(r1);
b1.add(r2);
b1.add(r3);
r1.addActionListener(this);
r2.addActionListener(this);
r3.addActionListener(this);

c1=new JCheckBox("Music");
c2=new JCheckBox("Dance");
c3=new JCheckBox("Sports");

c1.addActionListener(this);
c2.addActionListener(this);
c3.addActionListener(this);

l1=new JLabel("Your Name");


l2=new JLabel("Your Class");
l3=new JLabel("Your Hobbies");
t1=new JTextField(20);
t2=new JTextField(30);

p1.setLayout(new GridLayout(5,2));
p1.add(l1);p1.add(t1);
p1.add(l2);p1.add(l3);
p1.add(r1);p1.add(c1);
p1.add(r2); p1.add(c2);
p1.add(r3);p1.add(c3);

p2.setLayout(new FlowLayout());
p2.add(b);
p2.add(t2);

setLayout(new BorderLayout());
add(p1,BorderLayout.NORTH);
add(p2,BorderLayout.EAST);

setSize(400,200);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public void actionPerformed(ActionEvent e)


{

if(e.getSource()==r1)
{
cnt++;
if(cnt==1)
{
String s =t1.getText();
s1.append("Name = ");
s1.append(s);
}
s1.append(" Class = FY");
}
else if(e.getSource()==r2)
{
cnt++;
if(cnt==1)
{
String s =t1.getText();
s1.append("Name = ");
s1.append(s);
}
s1.append(" Class = SY");
}
else if(e.getSource()==r3)
{
cnt++;
if(cnt==1)
{
String s =t1.getText();
s1.append("Name = ");
s1.append(s);
}
s1.append(" Class = TY");
}

else if(e.getSource()==c1)
{
s1.append(" Hobbies = Music");
}
else if(e.getSource()==c2)
{
s1.append(" Hobbies = Dance");
}
else if(e.getSource()==c3)
{
s1.append(" Hobbies = Sports");
}

t2.setText(new String(s1));
// t2.setText(s2);

if(e.getSource()==b)
{
t2.setText(" ");
t1.setText(" ");
}

}
public static void main(String arg[])
{
Swing2 s=new Swing2();

}
}

Q3. Create an Applet which displays a message in the center of the screen. The message indicates
the events taking place on the applet window. Handle events like mouse click, mouse moved,
mouse dragged, mouse pressed, and key pressed. The message should update each time an event
occurs. The message should give details of the event such as which mouse button was pressed,
which key is pressed etc. (Hint: Use repaint(), KeyListener, MouseListener, MouseEvent method
getButton, KeyEvent methods getKeyChar)

Program Code:

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

/*
<applet code="ass8b1.class" width=400 height=200>

</applet>
*/

public class ass8b1 extends Applet implements MouseMotionListener,MouseListener,KeyListener


{

String msg="";

public void init()


{

setBackground(Color.cyan);
addMouseMotionListener(this);
addMouseListener(this);
addKeyListener(this);

public void paint(Graphics g)


{

g.drawString(msg,10,10);

public void mouseDragged(MouseEvent e)


{

msg="Mouse Dragged.";
repaint();

public void mouseMoved(MouseEvent e)


{

msg="Mouse Moved.";
repaint();

public void mouseClicked(MouseEvent e)


{

msg="Mouse Button "+e.getButton()+"clicked.";


repaint();

public void mousePressed(MouseEvent e)


{

msg="Mouse Button "+e.getButton()+"pressed.";


repaint();

public void mouseReleased(MouseEvent e)


{

msg="Mouse Button Released.";


repaint();

public void mouseEntered(MouseEvent e)


{

public void mouseExited(MouseEvent e)


{

public void keyTyped(KeyEvent e)


{
msg="Key Typed "+ e.getKeyChar();
repaint();

public void keyPressed(KeyEvent e)


{

msg="Key pressed "+ e.getKeyChar();


repaint();

public void keyReleased(KeyEvent e)


{

SET B
Q1.Write a java program to implement a simple arithmetic calculator. Perform appropriate
validations.

Program Code:

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

public class Calculator extends JFrame implements ActionListener


{
String msg=" ";
int v1,v2,result;
JTextField t;
JButton b[]=new JButton[10];
JButton add,sub,mul,div,clear,equals;
char choice;
JPanel p,p1;
Calculator()
{
setLayout(new BorderLayout());
p =new JPanel();
t=new JTextField(20);
p.add(t);

p1=new JPanel();
p1.setLayout(new GridLayout(5,4));
for(int i=0;i<10;i++)
{
b[i]=new JButton(""+i);
}
equals=new JButton("=");
add=new JButton("+");
sub=new JButton("-");
mul=new JButton("*");
div=new JButton("/");
clear=new JButton("C");

for(int i=0;i<10;i++)
{
p1.add(b[i]);
}

p1.add(equals);
p1.add(add);
p1.add(sub);
p1.add(mul);
p1.add(div);
p1.add(clear);

for(int i=0;i<10;i++)
{
b[i].addActionListener(this);
}
add.addActionListener(this);
sub.addActionListener(this);
mul.addActionListener(this);
div.addActionListener(this);
clear.addActionListener(this);
equals.addActionListener(this);

add(p,BorderLayout.NORTH);
add(p1);
setVisible(true);
setSize(500,500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

public void actionPerformed(ActionEvent ae)


{
String str = ae.getActionCommand();
char ch = str.charAt(0);
if ( Character.isDigit(ch))
t.setText(t.getText()+str);
else
if(str.equals("+"))
{
v1=Integer.parseInt(t.getText());
choice='+';
t.setText("");
}
else if(str.equals("-"))
{
v1=Integer.parseInt(t.getText());
choice='-';
t.setText("");
}
else if(str.equals("*"))
{
v1=Integer.parseInt(t.getText());
choice='*';
t.setText("");
}
else if(str.equals("/"))
{
v1=Integer.parseInt(t.getText());
choice='/';
t.setText("");
}

if(str.equals("="))
{
v2=Integer.parseInt(t.getText());
if(choice=='+')
result=v1+v2;
else if(choice=='-')
result=v1-v2;
else if(choice=='*')
result=v1*v2;
else if(choice=='/')
result=v1/v2;

t.setText(""+result);
}
if(str.equals("C"))
{
t.setText("");
}
}
public static void main(String a[])
{
Calculator ob = new Calculator();
}
}

Q2. Write a menu driven program to perform the following operations on a set of integers. The
Load operation should generate 50 random integers (2 digits) and display the numbers on the
screen. The save operation should save the numbers to a file “numbers.txt”. The Compute menu
provides various operations and the result is displayed in a message box. The Search operation
accepts a number from the user in an input dialog and displays the search result in a message
dialog. The sort operation sorts the numbers and displays the sorted data on the screen.

Program Code:

class Sc extends JFrame implements ActionListener


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

JLabel l;
JTextField t;
JPanel p;

StringBuffer ss=new StringBuffer();

int n;
int arr[]=new int [20];
Sc()
{
p=new JPanel();
mb=new JMenuBar();
m1=new JMenu("Operation");
m2=new JMenu("Sort");

l=new JLabel("Numbers");
t=new JTextField(20);

String str[]={"Load","Save","Exit","Ascending","Descending"};
m=new JMenuItem[str.length];
for(int i=0;i<str.length;i++)
{
m[i]=new JMenuItem(str[i]);
m[i].addActionListener(this);
}
p.add(l);
p.add(t);

mb.add(m1);
mb.add(m2);

m1.add(m[0]);
m1.add(m[1]);
m1.addSeparator();
m1.add(m[2]);

m2.add(m[3]);
m2.add(m[4]);

setLayout(new BorderLayout());
add(mb,BorderLayout.NORTH);
add(p,BorderLayout.CENTER);
setSize(300,150);
setVisible(true);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}
void sortasc()
{
for(int i=0;i<n;i++)
for(int j=0;j<n-1;j++)
{
if(arr[j]>arr[j+1])
{
int t=arr[j];
arr[j]=arr[j+1];
arr[j+1]=t;
}
}
StringBuffer s5=new StringBuffer();
for(int i=0;i<n;i++)
{
s5.append(new Integer(arr[i]).toString());
s5.append(" ");
}
t.setText(new String(s5));
}

void sortdesc()
{
for(int i=0;i<n;i++)
for(int j=0;j<n-1;j++)
{
if(arr[j]<arr[j+1])
{
int t=arr[j];
arr[j]=arr[j+1];
arr[j+1]=t;
}
}
StringBuffer s5=new StringBuffer();
for(int i=0;i<n;i++)
{
s5.append(new Integer(arr[i]).toString());
s5.append(" ");
}
t.setText(new String(s5));
}

public void actionPerformed(ActionEvent e)


{
String s=e.getActionCommand(); //return the name of menu
if(s.equals("Exit"))
System.exit(0);
else if(s.equals("Load"))
{
if(arr[0]==0)
{
int i=0;
try
{
BufferedReader r=new BufferedReader(new
FileReader("new.txt"));
String s1=r.readLine();
while(s1!=null)
{
ss.append(s1);
ss.append(" ");
arr[i]=Integer.parseInt(s1);
n=++i;
s1=r.readLine();
}
}
catch(Exception eee)
{ }
t.setText(new String(ss));
}
}
else if(s.equals("Save"))
{
char ch;
String sss = t.getText();
try
{
FileOutputStream br1 = new FileOutputStream("new.txt");
for(int i=0;i<sss.length();i++)
{
ch=sss.charAt(i);
if(ch == ' ')
br1.write('\n');
else
br1.write(ch);
}
br1.close();}
catch(Exception eee)
{}
}
else if(s.equals("Ascending"))
{
sortasc();
}
else if(s.equals("Descending"))
{
sortdesc();
}
}
public static void main(String arg[])
{
Sc c =new Sc();
}
}

Q3. Write a java program to create the following GUI for user registration form. Perform the
following validations:
i. Password should be minimum 6 characters containing atleast one uppercase letter, one
digit and one symbol.
ii. Confirm password and password fields should match.
iii. The Captcha should generate two random 2 digit numbers and accept the sum from the
user.
If above conditions are met, display “Registration Successful” otherwise “Registration Failed”
after the user clicks the Submit button.
Program Code:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class e6b3 extends JFrame implements ActionListener
{
JLabel l1,l2,l3,l4,l5,l6;
JTextField t1,t2,t3,t4,t5;
JButton b1,b2;
JPasswordField p1,p2;
e6b3()
{
setVisible(true);
setSize(700,700);
setLayout(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Registration Form");
l1=new JLabel("Registration form ");
l1.setForeground(Color.blue);
l1.setFont(new Font("Serif",Font.BOLD,20));
l2=new JLabel("Name");
l3=new JLabel("Login Name");
l4=new JLabel("Password");
l5=new JLabel("Confirm Password");
l6=new JLabel("Captcha");
t1=new JTextField();
t2=new JTextField();
t3=new JTextField();
p1=new JPasswordField();
p2=new JPasswordField();
b1=new JButton("Submit");
b1.addActionListener(this);
l1.setBounds(100,30,400,30);
l2.setBounds(80,70,200,30);
l3.setBounds(80,70,200,30);
l4.setBounds(80,110,200,30);
l5.setBounds(80,190,200,30);
l6.setBounds(80,230,200,30);
t1.setBounds(300,70,200,30);
t2.setBounds(300,110,200,30);
// t3.setBounds(300,150,200,30);
p1.setBounds(300,190,200,30);
p2.setBounds(300,230,200,30);
b1.setBounds(50,350,100,30);
add(l1);
add(l2);
add(t1);
add(l3);
add(t2);
add(l4);
add(p1);
add(l5);
add(p2);
add(l6);
// add(t3);
add(b1);
}
public void actionPerformed(ActionEvent e)
{
/* if(e.getsource()==Submit)
{
String a=t4.getText();
int an=Integer.parseInt(a);
if(an==ansR)
JOptionPane.showMessageDialog(null,"Captcha Matching");
}
else
{
JOptionPane.showMessageDialog(null,"Captcha not Matching");
}
String p1=ps1.getText();
String p2=ps2.getText();
System.out.println(p2);
int len=p1.length();
if(len>=6)
{
pmat=true;
}
if(p1.equals(p2) && pmat==true)
{
if(p1.matches("[a-zA-Z]*+[0-9]*+[@#$%!]*+[a-zA-Z]*+[0-9]*+[@#$
%!]*"))
{
JOptionPane.showMessageDialog(null,"Password ok");
}
else
{
JOptionpane.showMessageDialog(null,"Password Not ok");
}
}*/
}

public static void main(String args[])


{
e6b3 m=new e6b3();
}
}
ASSIGNMENT 5

Collection

SET A

Q1. Accept ‘n’ integers from the user and store them in a collection. Display them in the
sorted order. The collection should not accept duplicate elements. (Use a suitable
collection). Search for an particular element using predefined search method in the
Collection framework.

Program Code:

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

class ass1setA1
{
public static void main(String args[]) throws Exception
{
int s=1,no,element,i;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
TreeSet ts=new TreeSet();
System.out.println("Enter how many numbers you want:");
no=Integer.parseInt(br.readLine());
System.out.println("Enter "+no+" numbers:");
for(i=0;i<no;i++)
{
element=Integer.parseInt(br.readLine());
ts.add(element);
}
System.out.println("The elements in the sorted order:"+ts);

while(s==1)
{
System.out.println("Enter the element to search:");
element=Integer.parseInt(br.readLine());
if(ts.contains(element))
System.out.println("Element is found!");
else
System.out.println("Element not found!");
System.out.println("Search Again?");
s=Integer.parseInt(br.readLine());
}
}

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

Program Code:

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

public class ass1setA2


{
public static void main(String args[])
{
LinkedList t=new LinkedList();
t.add("Red");
t.add("Blue");
t.add("Yellow");
t.add("Orange");
Iterator i=t.iterator();
System.out.println("Elements:");
while(i.hasNext())
System.out.println(i.next());
ListIterator i1=t.listIterator();
System.out.println("\n");
while(i1.hasNext())
i1.next();
System.out.println("Elements in reversed order:");
while(i1.hasPrevious())
System.out.println(i1.previous());
System.out.println("\n");
LinkedList t1=new LinkedList();
t1.add("Pink");
t1.add("Green");
i=t1.iterator();
t.add(2,i.next());
t.add(3,i.next());
Iterator i2=t.iterator();
System.out.println("Total Elements:");
while(i2.hasNext())
System.out.println(i2.next());
}
}

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

Program Code:
import java.util.*;
import java.io.*;
import java.util.Map.Entry;

public class ass1setA3


{
public static void main(String[] args) throws Exception
{
int w=1;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
Hashtable hm=new Hashtable();
hm.put("Aishwarya",new Double(84.55));
hm.put("Aish",new Double(75.65));
hm.put("Aishu",new Double(90.02));
hm.put("Rohini",new Double(65.35));
hm.put("Yash",new Double(95.15));
hm.put("Radhika",new Double(48.02));
hm.put("Amruta",new Double(58.28));
hm.put("Raj",new Double(78));
hm.put("Rani",new Double(84));
Set s=hm.entrySet();
Iterator i=s.iterator();
System.out.println("Name Percentage");
while(i.hasNext())
{
Map.Entry me=(Entry)i.next();
System.out.println(" "+me.getKey()+" "+me.getValue());
}
while(w==1)
{
System.out.println("Enter the student name for searching:");
String nm=br.readLine();
Iterator i1=s.iterator();
while(i1.hasNext())
{
Map.Entry me=(Entry)i1.next();
if(nm.equalsIgnoreCase((String)me.getKey()))
System.out.println("The percentage : "+me.getValue());
}
System.out.println("Search Again?");
w=Integer.parseInt(br.readLine());
}
}
}

SET B
Q1. Create a java application to store city names and their STD codes using an appropriate
collection. The GUI ahould allow the following operations:
i. Add a new city and its code (No duplicates)
ii. Remove a city from the collection
iii. Search for a cityname and display the code

Program Code:

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

class ass1setB1 extends JFrame implements ActionListener


{
JTextField t1,t2,t3;
JButton b1,b2,b3;
JTextArea t;
JPanel p1,p2;
Hashtable ts;
ass1setB1()
{
ts=new Hashtable();
t1=new JTextField(10);
t2=new JTextField(10);
t3=new JTextField(10);
b1=new JButton("Add");
b2=new JButton("Search");
b3=new JButton("Remove");
t=new JTextArea(20,20);
p1=new JPanel();
p1.add(t);
p2=new JPanel();
p2.setLayout(new GridLayout(2,3));
p2.add(t1);
p2.add(t2);
p2.add(b1);
p2.add(t3);
p2.add(b2);
p2.add(b3);
add(p1);
add(p2);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
setLayout(new FlowLayout());
setSize(500,500);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e)
{
if(b1==e.getSource())
{
String name=t1.getText();
int code=Integer.parseInt(t2.getText());
ts.put(name,code);
Enumeration k=ts.keys();
Enumeration v=ts.elements();
String msg="";
while(k.hasMoreElements())
{
msg=msg+k.nextElement()+"="+v.nextElement()+"\n";
}
t.setText(msg);
t1.setText("");
t2.setText("");
}
else if(b2==e.getSource())
{
String name=t3.getText();
if(ts.containsKey(name))
JOptionPane.showMessageDialog(null,"City Found..");
//t.setText(ts.get(name).toString());
else
JOptionPane.showMessageDialog(null,"City not Found..");
}
else if(b3==e.getSource())
{
String name=t3.getText();
if(ts.containsKey(name))
{
ts.remove(name);
JOptionPane.showMessageDialog(null,"City Deleted..");
}
else
JOptionPane.showMessageDialog(null,"City not Deleted..");
}
}
public static void main(String args[])
{
new ass1setB1();
}
}

SET C

Q1. Read a text file, specified by the first command line argument, into a list. The
program should then display a menu which performs the following operations on the list:
1. Insert line 2. Delete line 3. Append line 4. Modify line 5. Exit
When the user selects Exit, save the contents of the list to the file and end the program.

Program Code:

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

public class ass1setC1


{
public static void main(String[] args)throws Exception
{
try
{
String filename=args[0];
String line;
BufferedReader br1=new BufferedReader(new
InputStreamReader(System.in));
LinkedList l=new LinkedList();
FileReader f=new FileReader(filename);
BufferedReader br=new BufferedReader(f);
do
{
line=br.readLine();
if(line==null)
break;
l.add(line);
}while(true);
br.close();
do
{
System.out.println("1. Insert line");
System.out.println("2. Delete line");
System.out.println("3. Append line");
System.out.println("4. Modify line");
System.out.println("5. Exit");
System.out.println("Enter your choice");
int ch=Integer.parseInt(br1.readLine());
switch(ch)
{
case 1:
System.out.println("Enter the position");
int po=Integer.parseInt(br1.readLine());
System.out.println("Enter the Line");
String line1=br1.readLine();
l.add(po-1,line1);
break;

case 2:
System.out.println("Enter the position");
int po1=Integer.parseInt(br1.readLine());
l.remove(po1-1);
break;

case 3:
System.out.println("Enter the position");
int po2=Integer.parseInt(br1.readLine());
System.out.println("Enter the Line");
String line2=br1.readLine();
l.add(po2,line2);
break;

case 4:
System.out.println("Enter the position");
int po3=Integer.parseInt(br1.readLine());
System.out.println("Enter the Line");
String line3=br1.readLine();
l.add(po3-1,line3);
break;

case 5:
FileWriter fw=new FileWriter(filename);
PrintWriter pr=new PrintWriter(fw);
ListIterator i=l.listIterator();
ListIterator i1=l.listIterator();
while(i1.hasNext())
{
System.out.println(i1.next());
}
while(i.hasNext())
{
pr.println(i.next());
}
pr.close();
System.exit(0);
break;
}
}while(true);
}
catch(Exception e)
{}
}
}

ASSIGNMENT 6

Database Programing

SET A

Q1. Create a student table with fields roll number, name, percentage. Insert values in the
table. Display all the details of the student table in a tabular format on the screen (using
swing).

Program Code:

import java.io.*;
import java.sql.*;
public class ass2setA1
{
public static void main(String args[]) throws ClassNotFoundException
{
Connection conn=null;
Statement stmt=null;
ResultSet rs=null;
int n;
try
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
String driver="org.postgresql.Driver";
String url="jdbc:postgresql://192.168.0.254/";
String db="testty54241";
try
{
Class.forName(driver);

conn=DriverManager.getConnection(url+db,"ty54241","modern");
stmt=conn.createStatement();
System.out.println("Connected");
}catch(SQLException e)
{
System.out.println(e);
}
System.out.println("Creating a student table:");
try
{
stmt.executeUpdate("Create table student12(roll_no int primary
key,name varchar(20),per int);");
System.out.println("Table created SUCCESSFULLY");
n=Integer.parseInt(br.readLine());
for(int i=0;i<n;i++)
{
System.out.println("Enter the Roll No.:");
int r=Integer.parseInt(br.readLine());
System.out.println("Enter the Student Name:");
String nm=br.readLine();
System.out.println("Enter the Percentage:");
double pr=Double.parseDouble(br.readLine());
stmt.executeUpdate("insert into student
values("+r+",'"+nm+"',"+pr+")");
}
stmt.close();
conn.close();
}catch(SQLException s)
{
System.out.println(s);
}
}catch(Exception ee)
{
System.out.println(ee);
}
}
}

Q2. Write a program to display information about the database and list all the tables in the
database. (Use DatabaseMetaData).

Program Code:

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

public class ass2setA2{


public static void main(String args[])
{
Connection conn=null;
Statement stmt=null;
ResultSet rs=null;

try
{

String driver="org.postgresql.Driver";
String url="jdbc:postgresql://192.168.0.254/";
String db="testty54241";

try
{
Class.forName(driver);

conn=DriverManager.getConnection(url+db,"ty54241","modern");
stmt=conn.createStatement();
System.out.println("connected");
}catch(SQLException e)
{
System.out.println(e);
}
DatabaseMetaData dbmd=conn.getMetaData();
System.out.println("Database product
name:"+dbmd.getDatabaseProductName());
System.out.println("Database user
name:"+dbmd.getUserName());
System.out.println("Database driver
name:"+dbmd.getDriverName());
System.out.println("Database driver version
name:"+dbmd.getDriverVersion());
System.out.println("Database catalog
name:"+dbmd.getCatalogs());
ResultSet rs1=dbmd.getProcedures(null,null,null);
//while(rs1.next())
//System.out.println(rs1.getString(1));
System.out.println("Database version
name:"+dbmd.getDriverMajorVersion());
rs=dbmd.getTables(null,null,null,new String[]{"TABLE"});
System.out.println("List of Tables:");
while(rs.next())
{

System.out.println("Table:"+rs.getString("TABLE_NAME"));
}
conn.close();

}catch(Exception o)
{
System.out.println(o);
}
}
}
Q3. Write a program to display information about all columns in the student table. (Use
ResultSetMetaData).

Program Code:

import java.io.*;
import java.sql.*;
public class ass2setA3{
public static void main(String args[])throws ClassNotFoundException
{
Connection conn=null;
Statement stmt=null;
ResultSet rs=null;
int i;
try
{
//BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
String driver="org.postgresql.Driver";
String url="jdbc:postgresql://192.168.0.254/";
String db="testty54241";
try
{
Class.forName(driver);

conn=DriverManager.getConnection(url+db,"ty54241","modern");
stmt=conn.createStatement();
}catch(SQLException e)
{
System.out.println(e);
}
String q="Select * from student";
rs=stmt.executeQuery(q);
ResultSetMetaData rsmd=rs.getMetaData();
System.out.println(" RESULT SET META DATA");
System.out.println("\nnumber of
columns="+rsmd.getColumnCount());
for(i=0;i<=rsmd.getColumnCount();i++)
{
System.out.println("\nColumn no:"+i);
System.out.println("\nColumn
name:"+rsmd.getColumnName(i));
System.out.println("\nColumn
label:"+rsmd.getColumnLabel(i));
System.out.println("\nColumn
type:"+rsmd.getColumnTypeName(i));
System.out.println("\nRead Only:"+rsmd.isReadOnly(i));
System.out.println("\nWriterable:"+rsmd.isWritable(i));

System.out.println("Nullable:"+rsmd.isNullable(i));
System.out.println("Column display
size:"+rsmd.getColumnDisplaySize(i));

//stmt.close();
//conn.close();
}
}catch(SQLException s)
{
System.out.println(s);
}
}
}

SET B

Q1. Write a menu driven program (Command line interface) to perform the following
operations on student table.
1. Insert 2. Modify 3. Delete 4. Search 5. View All 6. Exit

Program Code:

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

class ass2setB1
{
public static void main(String args[]) throws Exception
{
Connection conn=null;
Statement stmt=null;
ResultSet rs=null;
PreparedStatement ps1=null,ps2=null;
String name;
int r,choice,per;
try
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
String driver="org.postgresql.Driver";
String url="jdbc:postgresql://192.168.0.254/";
String db="testty54241";
try
{
Class.forName(driver);

conn=DriverManager.getConnection(url+db,"ty54241","modern");
stmt=conn.createStatement();
ps1=conn.prepareStatement("Insert into student values(?,?,?)");
ps2=conn.prepareStatement("Update student set sname=?
where roll_no=?");
do{
System.out.println("1:Insert");
System.out.println("2:Modify");
System.out.println("3:Delete");
System.out.println("4:Search");
System.out.println("5:View all");
System.out.println("6:Exit");
System.out.println("Enter your choice:");
choice=Integer.parseInt(br.readLine());
switch(choice)
{
case 1:
System.out.println("Enter the roll
no,name,percentage to be inserted:");
r=Integer.parseInt(br.readLine());
name=br.readLine();
per=Integer.parseInt(br.readLine());
ps1.setInt(1,r);
ps1.setString(2,name);
ps1.setInt(3,per);
ps1.executeUpdate();
break;

case 2:
System.out.println("Enter the roll no to
be Modified:");
r=Integer.parseInt(br.readLine());
System.out.println("Enter new name:");
name=br.readLine();
ps2.setInt(2,r);
ps2.setString(1,name);
ps2.executeUpdate();
break;

case 3:
System.out.println("Enter the roll no to
be deleted:");
r=Integer.parseInt(br.readLine());
stmt.executeUpdate("Delete from student
where roll_no="+r);
break;
case 4:
System.out.println("Enter the roll no to
be searched:");
r=Integer.parseInt(br.readLine());
rs=stmt.executeQuery("select * from
student where roll_no="+r);
if(rs.next())
{
System.out.print("Roll
Number="+rs.getInt(1));

System.out.println("Name="+rs.getString(2));
}
else
System.out.println("Student not
found!");
break;
case 5:
rs=stmt.executeQuery("Select * from
student");
while(rs.next())
{
System.out.print("Roll
Number="+rs.getInt(1));

System.out.println("Name="+rs.getString(2));
}
break;
}
}
while(choice!=6);
}
catch(SQLException s)
{
System.out.println(s);
}
}
catch(Exception ee)
{
System.out.println(ee);
}
conn.close();
}
}

Q2. Design a following Phone Book Application Screen using swing & write a code for
various operations like Delete, Update, Next, Previous. Raise an appropriate
exception if invalid data is entered like name left blank and negative phone Number.
Program Code:

import java.sql.*;
import java.io.*;
class SetB2
{
public static void main(String args[]) throws SQLException,IOException
{
Connection con=null;
Statement stmt=null;
ResultSet rs=null;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
try
{
String driver="org.postgresql.Driver";
String url="jdbc:postgresql://192.168.0.254/";
String db="testty54241";
Class.forName(driver);
con=DriverManager.getConnection(url+db,"ty54241","modern");
if(con==null)
{
System.out.println("Connection Failed");
System.exit(0);
}
else
{
System.out.println("Connection Successful...!!!\n");
stmt=con.createStatement();
String Choice=args[0];
char Op=Choice.charAt(0);
switch(Op)
{
case 'R':
String query1="select * from Elements";
rs=stmt.executeQuery(query1);
while(rs.next())
{
System.out.println("Atomic
Weight :"+rs.getFloat(1));
System.out.println("Name :"+rs.getString(2));
System.out.println("Symbol :"+rs.getString(3));

System.out.println("--------------------------------------------------------------");
}
break;
case 'U':
String name=args[1];
float at_wt=Float.parseFloat(args[2]);
String Sym=args[3];
String query2="update Elements set
Atomic_weight="+at_wt+",Chemical_Symbol='"+Sym+"' where Name='"+name+"'";
stmt.executeUpdate(query2);
System.out.println("Record Updated Sucessfully...!!!");
break;
case 'D':
String name1=args[1];
String query3="delete from Elements where
Name='"+name1+"'";
stmt.executeUpdate(query3);
System.out.println("Record Deleted Successfully...!!!");
break;
default:
System.out.println("Invalid Choice");
}
}
}
catch(Exception e)
{
System.out.println("Hello Exception Found :"+e);
}
con.close();
stmt.close();
}
}

SET C

Q1. Create tables : Course (id, name, instructor) and Student (id, name). Course and
Student have a many to many relationship. Create a GUI based system for performing the
following operations on the tables:
Course: Add Course, View All students of a specific course
Student: Add Student, Delete Student, View All students, Search student
Program Code:

Q2. Design a GUI to perform the following operations on Telephone user data.
i. Add record ii. Display current bill
Add record stores the details of a telephone user in a database. User has the following
attributes: User (id, name, telephone number, number of calls, month, year).
Display current bill should Calculate and display the bill for a specific user (search by
name or phone number) using the following rules. Provide button to Search user on basis
of telephone number or name.
Rules: The first 100 calls are free and rent is Rs. 300)

No. Of Calls Charge (per call)


> 100 and <=500 Rs. 1.00
> 500 Rs. 1.30

Program Code:

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

class ass2setC2 extends JFrame implements ActionListener


{
JFrame f;
JTextField t1,t2,t3,t4,t5,t6;
JLabel l1,l2,l3,l4,l5,l6,l7,l8;
JButton b1,b2;

public ass2setC2()
{
f=new JFrame("c2");
f.setBounds(330,250,250,380);
/* t1=new JTextField(20);
t2=new JTextField(20);
t3=new JTextField(20);
t4=new JTextField(20);
t5=new JTextField(20);
*/
t6=new JTextField(20);
/*l1=new JLabel("Id: ");
l2=new JLabel("Name: ");
l3=new JLabel("Telephone No.: ");
l4=new JLabel("Category: ");
l5=new JLabel("No. of calls: ");
*/
l6=new JLabel("Enter id for bill: ");
l7=new JLabel(" \n");
l8=new JLabel(" ");
b1=new JButton("Bill");
b1.addActionListener(this);
b2=new JButton("Search");
b2.addActionListener(this);
/* f.add(l1);
f.add(t1);
f.add(l2);
f.add(t2);
f.add(l3);
f.add(t3);
f.add(l4);
f.add(t4);
f.add(l5);
f.add(t5);
f.add(l8);
f.add(l7);
*/
f.add(l6);
f.add(t6);
f.add(b1);
f.add(b2);
f.setLayout(new FlowLayout());
f.setVisible(true);
f.setDefaultCloseOperation(EXIT_ON_CLOSE);

}
public static void main(String args[])
{
new ass2setC2();
}
public void actionPerformed(ActionEvent e)
{
try
{
String name,category,category2="";
int id,id2,no,noc;
double bill,noc2=0;
String driver="org.postgresql.Driver";
String url="jdbc:postgresql://192.168.0.254:8080/";
String db="testty54241";
Class.forName(driver);
Connection
con=DriverManager.getConnection(url+db,"ty54241","modern");
Statement stmt=con.createStatement();
ResultSet rs;
Object src=e.getSource();
PreparedStatement ps1=con.prepareStatement("select
id,name,tele_no,cat,no_of_calls from User where id=? from Telephone where id=?");
PreparedStatement ps2=con.prepareStatement("select no_of_calls from
User where id=?");
if(src.equals(b1))
{
id2=Integer.parseInt(t6.getText());
rs=stmt.executeQuery("select no_of_calls,cat from User where
id="+id2);
while(rs.next())
{
category2=rs.getString(2);
noc2=rs.getInt(1);
}
if(category2.equals("Urban"))
{
if(noc2<100)
{
JOptionPane.showMessageDialog(f,"Your bill:
700");

}
if(noc2>100)
{
if(noc2<=500)
{
noc2=noc2-100;
bill=noc2*1.30;
bill=bill+700;

JOptionPane.showMessageDialog(f,"Your bill: "+bill);

}
if(noc2>500)
{
noc2=noc2-100;
bill=noc2*1.70;
bill=bill+700;

JOptionPane.showMessageDialog(f,"Your bill: "+bill);


}
}
}
else
{ if(noc2<=300)
{
JOptionPane.showMessageDialog(f,"Your bill:
400");

}
if(noc2>300)
{
if(noc2<=500)
{
noc2=noc2-100;
bill=noc2*0.80;
bill=bill+700;

JOptionPane.showMessageDialog(f,"Your bill: "+bill);


}
if(noc2>500)
{
noc2=noc2-100;
bill=noc2*1.00;
bill=bill+700;

JOptionPane.showMessageDialog(f,"Your bill: "+bill);


}
}

}
}
if(src.equals(b2))
{
String data=null;
id2=Integer.parseInt(t6.getText());
rs=stmt.executeQuery("select name,tele_no,cat,no_of_calls
from User where id="+id2);
while(rs.next())
{
data="Name :"+rs.getString(1)+"\nTelephone No :
"+rs.getString(2)+"\nCategory: "+rs.getString(3)+"\nNo. of Calls: "+rs.getInt(4);

}
JOptionPane.showMessageDialog(f,data);

}
}
catch(Exception exc)
{
System.out.println("Database error");
}
}
}

ASSIGNMENT 7

Servlets

SET A

Q1. Design a servlet that provides information about a HTTP request from a client, such as
IP address and browser type. The servlet also provides information about the server on
which the servlet is running, such as the operating system type, and the names of
currently loaded servlets.

Program Code:

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ass3setA1 extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res)throws
ServletException,IOException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.println("<html>");
out.println("<body>");
java.util.Properties p=System.getProperties();
out.println("Server Name: "+req.getServerName()+"<BR>");
out.println("Remote address: "+req.getRemoteAddr()+"<BR>");
out.println("Remote user: "+req.getRemoteUser()+"<BR>");
out.println("Server port: "+req.getServerPort()+"<BR>");
out.println("Remote host: "+req.getRemoteHost()+"<BR>");
out.println("Local name: "+req.getLocalName()+"<BR>");
out.println("Local Address: "+req.getLocalAddr()+"<BR>");
out.println("Servlet Name: "+this.getServletName()+"<BR>");
out.println("OS name: "+p.getProperty("os.name")+"<BR>");
out.println("/body");
out.println("/html");
}
}

Q2. 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. (Use cookies)

Program Code:

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

public class ass3setA2 extends HttpServlet


{
Integer count;
public void doGet(HttpServletRequest request,HttpServletResponse response) throws
ServletException,IOException
{
response.setContentType("text/html");
Cookie c=new Cookie("Count",count+"");
response.addCookie(c);
String heading="";
String strCount=c.getValue();
PrintWriter out=response.getWriter();
if(count==null)
{
count=new Integer(0);
heading="Welcome ...";

}
else
{
count=Integer.parseInt(strCount);
heading="Welcome Back";
count=new Integer((count.intValue())+1);

}
c.setValue(count+" ");
// c.setValue(count+" ");
out.println(
"<html><body>" + "<h1>" + heading + "</h1>\n"+"<br>
Number of previous accesses: "+count+"<br></body></html>");
}
}

Q3. Design an HTML page which passes student roll number to a search servlet. The
servlet searches for the roll number in a database (student table) and returns student
details if found or error message otherwise.

Program Code:

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

public class ass3setA3 extends HttpServlet


{
Statement ps=null;
Connection con=null;
ResultSet rs=null;
String qury;

public void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter prn=response.getWriter();
try
{}
catch(ClassNotFoundException e){prn.println(e);
}
catch(SQLException ee){prn.println(ee);
}
String rollno=request.getParameter("roll");
int roll=Integer.valueOf(rollno);
try
{
//qury="select * from stud";
String driver="org.postgresql.Driver";
String url="jdbc:postgresql://192.168.0.254/";
String db="testty54241";
Class.forName(driver);
Connection
con=DriverManager.getConnection(url+db,"ty54241","modern");
ps=con.createStatement();
rs=ps.executeQuery("select * from student where roll_no
="+roll);
prn.println("inside");
while(rs.next())
{
prn.println("<table border=1>");
prn.println("<tr>");
prn.println("<td>"+rs.getInt(1)+"</td>");
prn.println("<td>"+rs.getString(2)+"</td>");
prn.println("<td>"+rs.getInt(3)+"</td>");
prn.println("</tr>");
prn.println("</table>");
}
con.close();
}catch(Exception e){}
}
}
SET B

Q1. 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)

Program Code:
Java File:
import java.io.*;
import java.sql.*;
import javax.servlet.http.*;
import javax.servlet.*;
public class ass3setB11 extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res) throws
ServletException, IOException
{

int sum=0;
String[] values=req.getParameterValues("item");
if(values!=null)
{
for(int i=0;i<values.length;i++)
sum=sum+Integer.parseInt(values[i]);
}
HttpSession hs=req.getSession(true);
hs.setAttribute("shop1",sum);
res.sendRedirect("shop2.html");
}
}

HTML file:

<html>
<head>
<title>Shopping</title></head>
<body>
<form method=get action="http://192.0.254:8080/aish/prac3/ass3setB11">
<input type=checkbox name="item" value=100>book-100<br>
<input type=checkbox name="item" value=200>cd-200<br>
<input type=checkbox name="item" value=300>tape-300<br>
<input type=submit>
<input type=reset>
</form></body></html>

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

Program Code:
Java File:

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

public class ass3setB2 extends HttpServlet


{

public void doGet(HttpServletRequest req,HttpServletResponse res)throws


ServletException,IOException
{

res.setContentType("text/html");
PrintWriter out=res.getWriter();
String data=req.getParameter("item");
out.println(data);
Cookie[] c=req.getCookies();

out.println("<html><head><title>hobby</title></head>");
out.println("<body bgcolor=skyblue>");
if(c!=null)
{
out.println("Length:"+c.length+"<br>Existing cookies:<br> ");
for(int i=0;i<c.length;i++)
{ String name=(String)c[i].getName();
String val=(String)c[i].getValue();
out.println("Name : "+name+" "+"Value : "+val+"<br>");
}

for(int i=0;i<c.length;i++)
{
if(c[i].getValue().equals(data))
{
out.println("<br>Cookie exist for "+data);
return;
}
}
}

Cookie c1=new Cookie("hobby",data);


c1.setMaxAge(6000);
res.addCookie(c1);
out.println("<br>Cookie add for hobby "+data);
out.println("</body></html>");
}
}

HTML File:
<html>
<head><title>Hobby</title></head>
<body>
<br><br>
<form method GET action="http://192.168.0.254:8080/aish/prac3/ass3setB2">
<table align=center>
<tr><th colspan=2>Select Your Hobby</th></tr>
<tr><td align=center><input type=radio name=item
value=Painting></td><td>Painting</td></tr>
<tr><td align=center><input type=radio name=item
value=Drawing></td><td>Drawing</td></tr>
<tr><td align=center><input type=radio name=item
value=Singing></td><td>Singing</td></tr>
<tr><td align=center><input type=radio name=item
value=Swimming></td><td>Swimming</td></tr>
<tr><td><input type=Submit></td><td><input type=Reset></td></tr>
</table>
</form>
</body>
</html>
SET C
Q1. Consider the following entities and their relationships
Movie (movie_no, movie_name, release_year)
Actor(actor_no, name)
Relationship between movie and actor is many – many with attribute rate in Rs.
Create a RDB in 3 NF answer the following:
a) Accept an actor name and display all movie names in which he has acted along
with his name on top.
b) Accept a movie name and list all actors in that movie along with the movie name
on top.

Program Code:

ASSIGNMENT 8

Multithreading

SET A
Q1. Write a program that create 2 threads – each displaying a message (Pass the message
as a parameter to the constructor). The threads should display the messages continuously
till the user presses ctrl-c. Also display the thread information as it is running.

Program Code:

import java.io.*;
class RunnableThread extends Thread{
String msg;
public RunnableThread()
{
}
public RunnableThread(String message)
{
this.msg=message;
}
public void run()
{
try
{
while(true)

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

catch(Exception ie){

}
}
}
public class ass5setA1
{
public static void main(String args[])
{
RunnableThread thread1=new RunnableThread("Hi..");
RunnableThread thread2=new RunnableThread("How are you.?");
System.out.println(thread1);
System.out.println(thread2);
thread1.start();
thread2.start();
}
}

Q2. Write a java 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 ]

Program Code:

import java.io.*;

class thread extends Thread


{
int pos=0;
int ar[];
int sum=0;
thread(int p,int arr[])
{
pos=p;
ar=arr;
}
public void run()
{
try
{
for(int i=pos;i<pos+100;i++)
{
sum=sum+ar[i];
}
}
catch(Exception e){}
}
int getsum()
{
return sum;
}

}
class ass5setA2
{
public static void main(String args[])throws InterruptedException
{
int j=0,sum=0;
int arr[]=new int[1000];
thread[] t=new thread[10];
for(int i=0;i<1000;i++)
arr[i]=i+1;
for(int i=0;i<10;i++)
{
t[i]=new thread(j,arr);
t[i].start();
t[i].join();
j=j+100;
}

for(int i=0;i<10;i++)
System.out.println(t[i]);

for(int i=0;i<10;i++)
{
System.out.println("sum of "+t[i]+"=="+t[i].getsum());
System.out.println("average="+(float)t[i].getsum()/100);
sum=sum+t[i].getsum();
}
System.out.println("Sum of 100 no is"+sum);
}
}

SET B

Q1. Write a program for a simple search engine. Accept a string to be searched. Search for
the string in all text files in the current folder. Use a separate thread for each file. The
result should display the filename, line number where the string is found.

Program Code:

Q2. Define a thread to move a ball inside a panel vertically. The Ball should be created
when user clicks on the Start Button. Each ball should have a different color and vertical
position (calculated randomly). Note: Suppose user has clicked buttons 5 times then five
balls should be created and move inside the panel. Ensure that ball is moving within the
panel border only.
Program Code:

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.imageio.*;
import javax.swing.*;
import javax.swing.event.*;
/*<applet code="Ball.class" width="300" height="300"></applet>*/
class Thr extends Thread
{
boolean up=false;
Ball parent;int top,left;
Color c;
Thr(int t,int l,Color cr,Ball p)
{
top=l;
if(top>170)
top=170-(t/8);
left=t;
c=cr;
parent=p;
}
public void run()
{
try
{
while(true)
{
Thread.sleep(37);
if(top>=100)
up=true;
if(top<=0)
up=false;
if(!up)
top=top+2;
else
top=top-2;
parent.p.repaint();
}
}catch(Exception e){}
}
}
public class Ball extends JFrame implements ActionListener
{
int top=0,left=0,n=0,radius=50;
Color
C[]={Color.black,Color.cyan,Color.red,Color.orange,Color.yellow,Color.pink,Color.gray,Col
or.blue,Color.green,Color.magenta};
Thr t[]=new Thr[10];
GPanel p;JButton b;Panel p1;

Ball()
{
setSize(700,300);
setLayout(new BorderLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(p=new GPanel(this),BorderLayout.CENTER);
b=new JButton("start");
b.addActionListener(this);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(p1=new Panel(),BorderLayout.SOUTH);
p1.setBackground(Color.lightGray);
p1.add(b);
setVisible(true);
}
public static void main(String[] args)
{
new Ball();
}
public void actionPerformed(ActionEvent e)
{
t[n]=new Thr(left+(radius+13)*n+89,top+n*25,C[n],this);
t[n].start();
n++;
p.repaint();
if(n>9)
b.setEnabled(false);
}
}
class GPanel extends JPanel
{
Ball parent;
GPanel(Ball p)
{
parent=p;
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
setBackground(Color.white);
for(int i=0;i<parent.n;i++)
{
g.setColor(parent.t[i].c);
g.fillOval(parent.t[i].left,parent.t[i].top,parent.radius,parent.radius);
}
}
}

SET C
Q1. Write a java program to create a class called FileWatcher that can be given several
filenames. The class should start a thread for each file name. If the file exists, the thread
will write a message to the console and then end. If the filw does not exist, the thread will
check for the existence of its file after every 5 seconds till the file gets created.

Program Code:

import java.io.*;
class FileThread extends Thread
{
String name;
public FileThread(String name)
{
this.name=name;
}
public void run()
{
File f=new File(name);
while(!f.exists())
{
try
{
System.out.println("File does not exists....- "+name);
Thread.sleep(200);
}
catch(InterruptedException ie)
{
System.out.println("File not exits...!"+ie);
}
System.out.println("File Exists....! "+name);
}
}
}
public class b1
{
public static void main(String args[])
{
FileThread f[]=new FileThread[args.length];
for(int i=0;i<args.length;i++)
{
f[i]=new FileThread(args[i]);
f[i].start();
}
}
}
Q2. Write a program to simulate traffic signal using threads.

Program Code:

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

Q3. Write a program to show how three thread manipulate same stack , two of them are
pushing elements on the stack, while the third one is popping elements off the
stack.

Program Code:
import java.awt.*;
import java.io.*;
import javax.swing.*;
class RunnableThread implements Runnable {

Thread runner;
public RunnableThread() {
}
public RunnableThread(String threadName) {
runner = new Thread(this, threadName); // (1) Create a new thread.
System.out.println(runner.getName());
runner.start(); // (2) Start the thread.
}
public void run() {
//Display info about this particular thread
System.out.println(Thread.currentThread());
}
}

public class RunnableExample {

public static void main(String[] args) {


Thread thread1 = new Thread(new RunnableThread(), "thread1");
Thread thread2 = new Thread(new RunnableThread(), "thread2");
RunnableThread thread3 = new RunnableThread("thread3");
//Start the threads
thread1.start();
thread2.start();
try {
//delay for one second
Thread.currentThread().sleep(1000);
} catch (InterruptedException e) {
}
//Display info about the main thread
System.out.println(Thread.currentThread());
}
}

***************************************************************************

You might also like