Java Assignment
Java Assignment
Java Assignment
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
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;
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.*;
}
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{
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);
}
}
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.*;
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);
}
}
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);
}
}
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);
}
}
}
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("----------------------");
}
}
}
}
}
Program Code:
import java.io.*;
interface CreditCard
{
void viewCreditAmount();
void increaseLimit()throws IOException;
void useCard()throws IOException ;
void payCard()throws IOException;
}
SliverCardCustomer()
{
name="Noname" ;
card_no=0;
creditAmount=0;
creaditLimit=50000;
}
}
else
System.out.println("You can't increse limit more than 3 times
");
}
}//end of class
}
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("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
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;
}
}
}
}
}
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);
}
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:
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.*;
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.*;
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);
p1.setLayout(new GridLayout(5,2));
p1.add(l1);p1.add(t1);
p1.add(l2);p1.add(l3);
p1.add(r1);p1.add(c1);
p1.add(r2); p1.add(c2);
p1.add(r3);p1.add(c3);
p2.setLayout(new FlowLayout());
p2.add(b);
p2.add(t2);
setLayout(new BorderLayout());
add(p1,BorderLayout.NORTH);
add(p2,BorderLayout.EAST);
setSize(400,200);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
if(e.getSource()==r1)
{
cnt++;
if(cnt==1)
{
String s =t1.getText();
s1.append("Name = ");
s1.append(s);
}
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>
*/
String msg="";
setBackground(Color.cyan);
addMouseMotionListener(this);
addMouseListener(this);
addKeyListener(this);
g.drawString(msg,10,10);
msg="Mouse Dragged.";
repaint();
msg="Mouse Moved.";
repaint();
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.*;
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);
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:
JLabel l;
JTextField t;
JPanel p;
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));
}
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");
}
}*/
}
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.*;
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;
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.*;
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.*;
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.*;
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)
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.*;
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;
}
if(noc2>500)
{
noc2=noc2-100;
bill=noc2*1.70;
bill=bill+700;
}
if(noc2>300)
{
if(noc2<=500)
{
noc2=noc2-100;
bill=noc2*0.80;
bill=bill+700;
}
}
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.*;
}
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.*;
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.*;
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;
}
}
}
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 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());
}
}
***************************************************************************