0% found this document useful (0 votes)
2 views34 pages

Java Practicals

The document contains multiple programming tasks involving Java, including printing prime numbers from an array, calculating BMI, sorting city names, handling exceptions, and performing matrix operations. It also covers concepts like multilevel inheritance, abstract classes, and user input handling through command line arguments and GUI. Each task is accompanied by code snippets illustrating the implementation of the described functionalities.

Uploaded by

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

Java Practicals

The document contains multiple programming tasks involving Java, including printing prime numbers from an array, calculating BMI, sorting city names, handling exceptions, and performing matrix operations. It also covers concepts like multilevel inheritance, abstract classes, and user input handling through command line arguments and GUI. Each task is accompanied by code snippets illustrating the implementation of the described functionalities.

Uploaded by

kdkomal2005
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Slip 1 class OfficeStaff extends

Q1) Write a Program to Staff {


print all Prime
String department;
numbers in an array of ‘n’
elements. OfficeStaff(int id, String
(use command line name, String dept) {
arguments)
[10 marks] super(id, name);
class PrimeArray {
public static void department = dept;
main(String args[]) {
int n = [Link]; }
int arr[] = new int[n]; void display() {
for(int i = 0; i < n; i++) {
arr[i] = [Link](id +
[Link](args[i]); " " + name + " " +
} department);
[Link]("Prime }}
numbers are:"); class StaffMain {
for(int i = 0; i < n; i++) {
int num = arr[i]; public static void
int count = 0; main(String args[]) {
for(int j = 1; j <=
num; j++) { Scanner sc = new
if(num % j == 0) Scanner([Link]);
count++;
} [Link]("Enter
if(count == 2) number of staff: ");
[Link](num); int n = [Link]();
}
} OfficeStaff arr[] = new
} OfficeStaff[n];
Q2) Define an abstract for(int i = 0; i < n; i++) {
class Staff with protected
members id and name.
[Link]("Enter id,
Define a parameterized
name, department: ");
constructor. Define one
subclass OfficeStaff with int id = [Link]();
member department.
String name =
Create n objects of
[Link]();
OfficeStaff and display all
details. String dept =
[Link]();
import [Link].*;
arr[i] = new
abstract class Staff {
OfficeStaff(id, name, dept);
protected int id;
}
protected String name;

Staff(int id, String name) { [Link]("Staff


Details:");
[Link] = id;
for(int i = 0; i < n; i++) {
[Link] = name;
arr[i].display();
}
}
abstract void display();
}
}
}
Slip 2 & 18. 2 Q2) Define a class if(arr[i].bat_avg <
CricketPlayer arr[j].bat_avg) {
Q1) Write a program to read (name,no_of_innings,no_of
the First Name and Last _times_notout, totatruns, CricketPlayer temp =
Name of a person, his bat_avg). Create an array arr[i];
weight and height using
of n player
command line arguments. arr[i] = arr[j];
Calculate the BMI Index objects .Calculate the
which is defined as the batting average for each arr[j] = temp;
individual's body mass player using static method
divided by the square of avg(). Define a static sort }}}}
their height. method which sorts the
(Hint : BMI = Wts. In kgs / array on the basis of void display() {
(ht)2)
average. Display the player
details in sorted order. [Link](name +
class BMI { "\t" + innings + "\t" +
import [Link].*; notout + "\t" + totalruns +
public static void "\t" + bat_avg);
main(String args[]) { class CricketPlayer {
}}
if([Link] != 4) {
String name;
class PlayerMain {
[Link]("Usage: int innings, notout,
totalruns; public static void
java BMI FirstName
main(String args[]) {
LastName Weight(Kg)
Height(m)"); double bat_avg;
Scanner sc = new
return; } CricketPlayer(String n, int Scanner([Link]);
in, int no, int runs) {
String fname = args[0]; [Link]("Enter
name = n; number of players: ");
String lname = args[1];

double weight = innings = in; int n = [Link]();


[Link](args[2]
notout = no; CricketPlayer arr[] = new
);
CricketPlayer[n];
double height = totalruns = runs;
[Link](args[3] for(int i = 0; i < n; i++) {
); bat_avg = avg(in, no,
runs); } [Link]("Enter
double bmi = weight / name, innings, notout,
(height * height); static double avg(int in, int totalruns: ");
no, int runs) {
String name = [Link]();
[Link]("Name:
int out = in - no;
" + fname + " " + lname); int in = [Link]();
if(out == 0) int no = [Link]();
return runs; int runs = [Link]();
[Link]("Weight:
" + weight + " kg"); arr[i] = new
return (double) runs / out;}
CricketPlayer(name, in, no,
static void runs); }
[Link]("Height:
sort(CricketPlayer arr[]) { [Link](arr);
" + height + " m");

for(int i = 0; i < [Link] - [Link]("Name\


[Link]("BMI: " 1; i++) { tInnings\tNotOut\tRuns\
+ bmi); tAverage");
for(int j = i + 1; j < for(int i = 0; i < n; i++) {
}} [Link]; j++) {
arr[i].display(); }}}
class CovidException Scanner sc = new
extends Exception { Scanner([Link]);
Slip 3
CovidException(String [Link]("Enter
Q1) Write a program to msg) { name, age, oxygen level,
accept ‘n’ name of cities HRCT report: ");
from the user and sort super(msg);
them in ascending String name = [Link]();
order. }
[10 marks] int age = [Link]();
}
import [Link].*; double oxy =
class Patient { [Link]();
class CitySort {
public static void String name; double hrct =
main(String args[]) { [Link]();
Scanner sc = new int age;
Scanner([Link]); Patient p = new
double oxy_level; Patient(name, age, oxy,
[Link]("Enter hrct);
number of cities: ");
double hrct;
int n = [Link]();
try {
String cities[] = new
String[n];
Patient(String n, int a,
double o, double h) { [Link]();
[Link]("Enter
city names:"); name = n; } catch(CovidException e)
for(int i = 0; i < n; i++) {
{ age = a;
cities[i] = [Link](); [Link]([Link]
} oxy_level = o; ssage());
[Link](cities);
hrct = h; }
[Link]("Cities in
ascending order:"); } }
for(int i = 0; i < n; i++)
{ void check() throws }
CovidException {
[Link](cities[i]);
} if(oxy_level < 95 && hrct
} > 10)
}
throw new
Q2) Define a class patient
CovidException("Patient is
(patient_name,
Covid Positive(+) and
patient_age,
Need to Hospitalized");
patient_oxy_level,patient_
HRCT_report). Create an
object of patient. Handle else
appropriate exception
while patient oxygen level [Link](name +
less than 95% and HRCT " " + age + " " + oxy_level
scan report greater than + " " + hrct);
10, then throw user
defined Exception “Patient }
is Covid Positive(+) and
Need to Hospitalized” }
otherwise display its
information. class PatientMain {

public static void


main(String args[]) {
import [Link].*;
[Link](); add(l2); add(t2);
}
} add(b1); add(b2);
}
add(l3);
Slip 4 [Link](this);
Q2) Write a program to
Q1) Write a program to design a screen using Awt [Link](this);
print an array after that will take a user name setSize(300,200);
changing the rows and
and password. If the user
columns of a given setVisible(true);
name and password are
two-dimensional array.
[10 marks] not same, raise an }
Exception with appropriate
import [Link].*; message. User can have 3 public void
login chances only. Use actionPerformed(ActionEve
class TransposeMatrix { clear button to clear the nt e) {
public static void TextFields.
main(String args[]) { if([Link]() == b2) {
Scanner sc = new import [Link].*; [Link]("");
Scanner([Link]);
import [Link].*; [Link]("");
[Link]("Enter
number of rows: "); class LoginException [Link]("");
int r = [Link](); extends Exception {
} else if([Link]()
LoginException(String == b1) {
[Link]("Enter
number of columns: "); msg) {
int c = [Link](); try {
super(msg);
int arr[][] = new int[r] String u =
[c]; }} [Link]();
public class LoginAWT
[Link]("Enter String p =
extends Frame implements
elements:");
ActionListener { [Link]();
for(int i = 0; i < r; i++)
{ Label l1, l2, l3; if(![Link](p)) {
for(int j = 0; j < c; j+
+) { TextField t1, t2; count++;
arr[i][j] =
[Link](); Button b1, b2; throw new
} LoginException("Invalid
} int count = 0; Login Attempt " + count);
LoginAWT() {
[Link]("Original } else {
setLayout(new
Matrix:");
FlowLayout()); [Link]("Login
for(int i = 0; i < r; i++)
{ Successful!");
l1 = new Label("User
for(int j = 0; j < c; j+ }
Name:");
+) {
l2 = new if(count >= 3) {
[Link](arr[i][j] + " Label("Password:");
"); [Link]("No
} l3 = new Label(""); more attempts!");
[Link](); [Link](false);
} t1 = new TextField(20); } }
t2 = new TextField(20); catch(LoginException ex) {
[Link]("Transpo
se Matrix:"); [Link]('*');
for(int i = 0; i < c; i++) [Link]([Link]())
{ b1 = new ; } }}
for(int j = 0; j < r; j+ Button("Login");
+) { public static void
b2 = new main(String args[]) {
[Link](arr[j][i] + " Button("Clear");
"); new LoginAWT();
} add(l1); add(t1);
}} ie matrices : for(int i=0;i<r;i++) {
for(int j=0;j<c;j++) {
import [Link].*; mul[i][j] = 0;
for(int k=0;k<c;k+
Slip 5 class MatrixOperations { +)
public static void main(String mul[i][j] +=
Q1) Write a program for
args[]) { mat1[i][k]*mat2[k][j];
multilevel inheritance such that
Scanner sc = new
Country is inherited from
Scanner([Link]); [Link](mul[i][j] + " ");
Continent.
[Link]("Enter }
State is inherited from Country.
number of rows: "); [Link]();
Display the place, State, Country
int r = [Link](); }
and Continent.
[Link]("Enter } else if(ch==3) {
[10 marks]
number of columns: ");
int c = [Link](); [Link]("Exit");
class Continent {
int mat1[][] = new int[r][c]; break;
String continent;
int mat2[][] = new int[r][c]; } else {
Continent(String c) {
[Link]("Enter
continent = c;
elements of first matrix:"); [Link]("Invalid
}
for(int i=0;i<r;i++) Choice");
}
for(int j=0;j<c;j++) }
mat1[i][j] = [Link](); }
class Country extends Continent {
[Link]("Enter }
String country;
elements of second matrix:");
Country(String c, String co) {
for(int i=0;i<r;i++)
super(c);
for(int j=0;j<c;j++)
country = co;
mat2[i][j] = [Link]();
}
while(true) {
}
[Link]("\
nMenu:");
class State extends Country {
[Link]("1. }
String state, place;
Addition");
State(String c, String co, String
[Link]("2.
s, String p) {
Multiplication");
super(c, co);
[Link]("3.
state = s;
Exit");
place = p;
[Link]("Enter
}
choice: ");
void display() {
int ch = [Link]();
[Link]("Place: " +
if(ch==1) {
place);
[Link]("State: " +
[Link]("Addition:");
state);
int sum[][] = new int[r]
[Link]("Country:
[c];
" + country);
for(int i=0;i<r;i++) {
for(int j=0;j<c;j++) {
[Link]("Continent: " +
sum[i][j] = mat1[i]
continent);
[j] + mat2[i][j];
}
}
[Link](sum[i][j] + " ");
}
class MultiLevelMain {
[Link]();
public static void main(String
}
args[]) {
} else if(ch==2) {
State s = new State("Asia",
if(r != c) {
"India", "Maharashtra", "Pune");
[Link]();
[Link]("Matrix
}
multiplication not possible");
}
continue;
}
Q2) Write a menu driven
[Link]("Multiplication:
program to perform the
");
following operations on
int mul[][] = new int[r]
multidimensional array
[c];
respectively. Define description: ");
methods accept and description =
display in all cases. Create [Link]();
3 objects each of Purchase
Order and Sales Order and [Link]("Enter
Slip 6 accept and display details. vendor name: ");
Q1) Write a program to
vendorName =
display the [Link]();
Employee(Empid, import [Link].*;
Empname, Empdesignation, }
Empsal) information using abstract class Order {
toString(). void display() {
int id;
[10 marks] [Link]("Sales
String description; Order -> Id: " + id + "
class Employee {
Desc: " + description + "
int Empid; abstract void
String Empname;
Vendor: " + vendorName);
accept(Scanner sc);
String Empdesignation;
double Empsal; }}
abstract void display(); class OrderMain {
Employee(int id, String
} public static void
name, String desig, double
class PurchaseOrder main(String args[]) {
sal) {
Empid = id; extends Order {
Empname = name; String customerName; Scanner sc = new
Empdesignation = void accept(Scanner sc) { Scanner([Link]);
desig; [Link]("Enter id: PurchaseOrder po[] = new
Empsal = sal; "); PurchaseOrder[3];
} id = [Link]();
public String toString() { [Link](); SalesOrder so[] = new
return "Empid: " + [Link]("Enter SalesOrder[3];
Empid + " Name: " + description: ");
Empname + " Designation: description = [Link]("Enter
" + Empdesignation + " [Link](); Purchase Orders:");
Salary: " + Empsal; [Link]("Enter
} customer name: "); for(int i=0;i<3;i++) {
} customerName =
[Link](); po[i] = new
class EmployeeMain {
public static void PurchaseOrder();
}
main(String args[]) { void display() {
Employee e1 = new po[i].accept(sc); }
Employee(1, "Rahul", [Link]("Purcha
"Manager", 50000); [Link]("Enter
se Order -> Id: " + id + " Sales Orders:");
Employee e2 = new
Desc: " + description + " for(int i=0;i<3;i++) {
Employee(2, "Sneha",
Customer: " +
"Developer", 40000);
Employee e3 = new
customerName); so[i] = new SalesOrder();
Employee(3, "Amit",
"Tester", 35000); }} so[i].accept(sc);
class SalesOrder extends } [Link]("\
[Link](e1); Order { nPurchase Orders:");
[Link] for(int i=0;i<3;i++)
String vendorName; po[i].display();
Q2) Create an abstract
class “order” having void accept(Scanner sc) { [Link]("\nSales
members id, description. Orders:");
Create two subclasses [Link]("Enter id: for(int i=0;i<3;i++)
“Purchase Order” and "); so[i].display();
“Sales Order” having id = [Link]();
members customer name [Link](); }}
and Vendor name [Link]("Enter
Scanner sc = new BufferedReader br =
Scanner([Link]); new BufferedReader(new
[Link]("Enter FileReader(file));
Slip 7 Account Name, Account
Q1) Design a class for No, Initial Balance: "); ArrayList<String>
Bank. Bank Class should lines = new
support following String name = ArrayList<String>();
operations; [Link]();
String line;
import [Link].*; int no = [Link]();
class Bank { while((line =
String accName; double bal = [Link]()) != null) {
int accNo; [Link]();
double balance; [Link](line);
Bank(String name, int no, Bank b = new
double bal) { Bank(name, no, bal); }
accName = name; [Link]();
accNo = no; [Link](5000);
balance = bal; [Link](2000);
[Link](lines);
} [Link](); [Link]("File
void deposit(double amt) content in reverse order
{ }} with case changed:");
for(String l : lines) {
balance += amt; Q2) Write a program to
accept a text file from StringBuilder sb =
[Link](amt + " user and display the new StringBuilder();
deposited."); contents of a file in
for(char ch :
} import [Link].*; [Link]()) {
if([Link](c
void withdraw(double import [Link].*; h))
amt) { class FileReverse { [Link]([Link]
werCase(ch));
if(amt <= balance) { public static void
main(String args[]) throws else
balance -= amt; IOException { if([Link](
ch))
Scanner sc = new [Link]([Link]
[Link](amt + " Scanner([Link]); erCase(ch));
withdrawn."); [Link]("Enter
file name: "); else
} else
{ [Link] String fname = [Link](ch);
("Insufficient balance."); [Link]();
} }
} File file = new
void display() File(fname);
{ [Link]("Ac [Link]([Link]
count No: " + accNo + " if(![Link]()) { ing());
Name: " + accName + "
Balance: " + balance); }
} [Link]("File
not found."); }
}
class BankMain { return; }
public static void }
main(String args[]) {
Slip 8 class MouseEventDemo public void
extends Frame implements mouseEntered(MouseEvent
Q1) Create a class Sphere, MouseListener, e) {}
to calculate the volume and MouseMotionListener {
surface area of sphere. public void
(Hint : Surface TextField tf; mouseExited(MouseEvent
area=4*3.14(r*r), e) {}
Volume=(4/3)3.14(r*r*r))
[10 marks] public void
MouseEventDemo() {
mouseDragged(MouseEven
import [Link].*; setLayout(new t e) {}
FlowLayout());
class Sphere {
double radius; tf = new TextField(20);
public static void
Sphere(double r) { add(tf); main(String args[]) {
radius = r;
} new
addMouseListener(this); MouseEventDemo();
double surfaceArea() {
}
return 4 * 3.14 * radius
* radius; addMouseMotionListener(t
}
} his);

setSize(300,200);
double volume() {
return (4.0/3.0) * 3.14 setVisible(true);
* radius * radius * radius;
} }
}

class SphereMain {
public void
public static void
main(String args[]) { mouseClicked(MouseEvent
Scanner sc = new e) {
Scanner([Link]);
[Link]("Clicked at:
[Link]("Enter X=" + [Link]() + " Y=" +
radius of sphere: "); [Link]());
double r =
}
[Link]();
Sphere s = new
Sphere(r);
public void
[Link]("Surface mouseMoved(MouseEvent
Area: " + [Link]()); e) {
[Link]("Volume
: " + [Link]()); [Link]("Mouse
} moved at: X=" + [Link]() + "
}
Y=" + [Link]());
Q2) Design a screen to }
handle the Mouse Events
such as MOUSE_MOVED
and MOUSE_CLICKED and
public void
display the position of the
mousePressed(MouseEvent
Mouse_Click in a TextField
e) {}
import [Link].*;
public void
import [Link].*; mouseReleased(MouseEven
t e) {}
void displayTime() { product_id = 0;
product_name = "";
Slip 9 [Link]("Time: product_cost = 0;
%02d:%02d:%02d %s\n", product_quantity = 0;
Q1) Define a “Clock” class hours, minutes, seconds, count++;
that does the following ; period); }
} Product(int id, String
import [Link].*; public static void name, double cost, int qty)
main(String args[]) { {
class Clock {
Scanner sc = new product_id = id;
Scanner([Link]);
int hours, minutes,
[Link]("Enter product_name =
seconds;
Hours Minutes Seconds: name;
");
String period;
product_cost = cost;
int h = [Link]();
Clock(int h, int m, int s)
{ product_quantity =
int m = [Link](); qty;
hours = h;
int s = [Link](); count++;
minutes = m;
Clock c = new }
Clock(h, m, s); void display() {
seconds = s;
[Link]("ID: " +
[Link](); product_id + " Name: " +
checkValidity();
} product_name + " Cost: " +
product_cost + " Qty: " +
setAMPM();
} product_quantity);
}
Q2) Write a program to }
void checkValidity() {
using marker interface
create a class Product }
if(hours < 0 || hours >
(product_id,
23) hours = 0;
product_name, class ProductMain {
product_cost,
if(minutes < 0 ||
product_quantity) default public static void
minutes > 59) minutes = 0;
and parameterized main(String args[]) {
constructor. Create objects
if(seconds < 0 ||
of class Product p1 = new
seconds > 59) seconds = 0;
Product();
product and display the
}
contents of each object and Product p2 = new
void setAMPM() {
Also display the object Product(101, "Laptop",
count. 50000, 2);
if(hours >= 12) {
interface Marker {} Product p3 = new
period = "PM";
Product(102, "Phone",
class Product implements 20000, 5);
if(hours > 12)
Marker { [Link]();
hours -= 12;
int product_id; [Link]();
} else {
String product_name; [Link]();
period = "AM";
double product_cost; [Link]("Total
if(hours == 0)
objects created: " +
hours = 12;
int product_quantity; [Link]);
}
static int count = 0; }
}
Product() { }
import [Link].*; }
}
public class StudentInfo {
Slip 10 #3
int rollno; // Main class to run the
Q1) Write a program to program
find the cube of given String name;
number using functional import [Link].*;
interface. String sclass;
import student.*;
import [Link].*; double percentage; class StudentMain {
interface CubeInterface {
public void accept(int r, public static void
int cube(int n); String n, String c, double main(String args[]) {
p) {
} Scanner sc = new
class CubeMain { rollno = r; Scanner([Link]);
public static void name = n;
main(String args[]) { [Link]("Enter
sclass = c; Roll No, Name, Class: ");
Scanner sc = new
Scanner([Link]); percentage = p; int roll = [Link]();
[Link]("Enter a
number: "); } String name =
public void display() { [Link]();
int num = [Link]();
[Link]("Roll String sclass =
CubeInterface ci = (n) No: " + rollno + " Name: " [Link]();
-> n * n * n; + name + " Class: " +
sclass + " Percentage: " +
percentage);
[Link]("Cube int marks[] = new
of " + num + " is: " + } int[6];
[Link](num));
}
} [Link]("Enter
#2 marks of 6 subjects:");
} // Save this file as
[Link] inside for(int i=0;i<6;i++)
Q2) Write a program to folder "student" marks[i] = [Link]();
create a package name
student. Define class package student; StudentPer sp = new
StudentInfo with method StudentPer();
to display information import [Link].*;
about student such as double per =
rollno, class, and [Link](marks);
percentage. Create
another class StudentPer public class StudentPer { StudentInfo si = new
with method to find StudentInfo();
percentage of the student. public double
Accept student details like calcPercentage(int [Link](roll, name,
rollno, name, class and marks[]) { sclass, per);
marks of 6 subject from
user [Link]();
double sum = 0;
// Save this file as }
for(int i = 0; i <
[Link] inside [Link]; i++) sum +=
folder "student" }
marks[i];
package student; return (sum /
[Link]);
Scanner sc = new Scanner sc = new
Scanner([Link]); Scanner([Link]);
Slip 11
[Link]("Enter [Link]("Enter
Q1) Define an interface
radius and height of username: ");
“Operation” which has
cylinder: ");
method volume( ).Define a
String user =
constant PI having a value
double r = [Link]();
3.142 Create a class
[Link]();
cylinder which implements
this interface (members –
double h = [Link]("Enter
radius, height). Create one
[Link](); password: ");
object and calculate the
volume.
Cylinder c = new String pass =
Cylinder(r, h); [Link]();
import [Link].*;

[Link]("Volum
e of Cylinder: " + try {
interface Operation {
[Link]());
if(!
double PI = 3.142;
} [Link](pass)) {
double volume();
} throw new
InvalidPasswordException
}
Q2) Write a program to ("Invalid Password");
accept the username and
password from user if } else {
username and password
class Cylinder implements
are not same then raise
Operation {
"Invalid Password" with [Link]("Login
appropriate msg. Successful");
double radius, height;
}

import [Link].*; }
Cylinder(double r,
catch(InvalidPasswordExc
double h) {
eption e) {
radius = r;
class
InvalidPasswordException [Link]([Link]
height = h;
extends Exception { ssage());
}
}
InvalidPasswordException
(String msg) { }
public double volume()
super(msg); }
{
}
return PI * radius *
radius * height;
}
}

class Login {
public static void
public static void
main(String args[]) {
main(String args[]) {
-, *, % operations. Add a if([Link]("+") ||
text field to display the [Link]("-") ||
result. [Link]("*") ||
Slip 12 [Link]("%")) {
import [Link].*; import [Link].*;
class College { import [Link].*; num1 =
int cno; class SimpleCalculator [Link]([Link]
String cname; extends Frame implements Text());
String caddr; ActionListener { op = s;
College(int no, String TextField tf;
name, String addr) { String op = ""; operatorPressed =
cno = no; double num1 = 0, num2 true;
cname = name; = 0;
caddr = addr; boolean operatorPressed [Link]("");
} = false;
void displayCollege() { SimpleCalculator() { } else
if([Link]("=")) {
[Link]("Colleg tf = new
e No: " + cno + " Name: " TextField(20); num2 =
+ cname + " Address: " +
[Link]([Link]
caddr); setLayout(new Text());
}} BorderLayout()); double res = 0;
class Department extends
switch(op) {
College { add(tf, "North"); case "+": res =
int dno;
num1 + num2; break;
Panel p = new
String dname; Panel(); case "-": res =
Department(int cno,
num1 - num2; break;
String cname, String caddr,
[Link](new
int dno, String dname) {
GridLayout(4, 4, 5, 5)); case "*": res =
String buttons[] = { num1 * num2; break;
super(cno, cname,
caddr);
"1","2","3","+", case "%": res =
num1 % num2; break;
[Link] = dno;
"4","5","6","-", }
[Link]("" + res);
[Link] = dname;
"7","8","9","*", operatorPressed =
false;
}
"0",".","=","%" } else {
void
if(operatorPressed)
displayDepartment() {
}; {
displayCollege();
for(String s : buttons) [Link](s);
[Link]("Depart
{
ment No: " + dno + "
operatorPressed
Name: " + dname);
Button b = new = false;
Button(s);
}
[Link](this); } else {
public static void
[Link](b);
main(String args[]) {
}
add(p, "Center"); [Link]([Link]() + s);
Department d = new
setSize(300, 300);
Department(101, "ABC
setVisible(true); } } }
College", "Mumbai", 201,
}
"Computer Science");
public void public static void
[Link]();
actionPerformed(ActionEv main(String args[]) {
}}
ent e) {
Q2) Write a java program new
String s = SimpleCalculator();}
that works as a simple
[Link]();
calculator. Use a grid
layout to arrange buttons }
for the digits and for the +,
words += [Link]; SimpleDateFormat f4
= new
} SimpleDateFormat("EEE
Slip 13 MMMM dd HH:mm:ss z
[Link](); yyyy");
Q1) Write a program to
accept a file name from SimpleDateFormat f5
command prompt, if the = new
file exits then display SimpleDateFormat("dd/M
[Link]("Numb M/yy hh:mm:ss a Z");
import [Link].*; er of lines: " + lines);
import [Link].*;
[Link]("Numb
class FileCount { er of words: " + words); [Link]("Curren
t date is : " + [Link](d));
public static void }
main(String args[]) throws
IOException { } [Link]("Curren
[10 marks] t date is : " + [Link](d));
if([Link] != 1) {
Q2) Write a program to
display the system date [Link]("Curren
[Link]("Usage: and time in various t date is : " + [Link](d));
java FileCount formats shown below:
<filename>"); Current date is :
31/08/2021 [Link]("Curren
return; t date and time is : " +
Current date is : 08-31- [Link](d));
} 2021
File file = new import [Link].*; [Link]("Curren
File(args[0]); t date and time is : " +
import [Link].*; [Link](d));
if(![Link]()) {
}

[Link]("File class DateTimeFormats { }


does not exist.");
public static void
return; main(String args[]) {
} Date d = new Date();
BufferedReader br =
new BufferedReader(new
FileReader(file)); SimpleDateFormat f1
= new
String line; SimpleDateFormat("dd/M
M/yyyy");
int lines = 0, words =
0; SimpleDateFormat f2
= new
SimpleDateFormat("MM-
dd-yyyy");
while((line =
[Link]()) != null) { SimpleDateFormat f3
= new
lines++; SimpleDateFormat("EEEE
MMMM dd yyyy");
String w[] =
[Link]().split("\\s+");
Q2) Write a Java program >= 50) grade = "C";
Slip 14 to create a Package “SY” else if(totalComputer
which has a class SYMarks >= 40) grade = "Pass
Q1) Write a program to accept a (members – Class";
number from the user, if number else grade = "FAIL";
is zero then throw user defined package SY;
public class SYMarks { [Link]("Grade:
import [Link].*; " + grade);
int ComputerTotal;
class ZeroNumberException int MathsTotal; [Link]("--------
extends Exception int ElectronicsTotal; -------------------------"); }
{ ZeroNumberException(Str }
ing msg) { public SYMarks(int comp, class StudentMain {
super(msg); }} int maths, int elec) {
class PrimeCheck { ComputerTotal = comp; public static void
static void checkPrime(int MathsTotal = maths; main(String args[]) {
n) throws ElectronicsTotal = elec; Scanner sc = new
ZeroNumberException { }} Scanner([Link]);
[Link]("Enter
if(n == 0) throw new #2 number of students: ");
ZeroNumberException("Num package TY;
ber is 0"); public class TYMarks { int n = [Link]();
boolean flag = true; int Theory;
for(int i=2; int Practicals; Student students[] =
i<=[Link](n); i++) { public TYMarks(int th, int new Student[n];
pr) {
if(n%i == 0) { Theory = th; for(int i=0;i<n;i++) {
Practicals = pr; } [Link]("Enter
flag = false; } Roll, Name, SY Marks
#3 (Computer Maths
break; import [Link].*; Electronics), TY Marks
} } import SY.*; (Theory Practicals):");
if(n == 1) flag = false; import TY.*;
class Student { int roll =
if(flag) int rollNumber; [Link]();
[Link](n + " is String name; String name =
Prime"); SYMarks sym; [Link]();
TYMarks tym; int syc =
else [Link](n [Link]();
+ " is Not Prime"); Student(int r, String n, int symaths =
SYMarks s, TYMarks t) { [Link]();
} rollNumber = r; int syele =
public static void name = n; [Link]();
main(String args[]) { sym = s; int tyth =
tym = t; } [Link]();
Scanner sc = new int typr =
Scanner([Link]); void displayResult() { [Link]();
int totalComputer = SYMarks sy = new
[Link]("Enter [Link] + SYMarks(syc, symaths,
number: "); [Link] + syele);
[Link];
int num = [Link](); [Link]("Roll: " TYMarks ty = new
+ rollNumber + " Name: " TYMarks(tyth, typr);
try { + name + " Computer
Total: " + totalComputer); students[i] = new
Student(roll, name, sy, ty);
checkPrime(num); } String grade; }
catch(ZeroNumberException if(totalComputer >= [Link]("\n-----
e) 70) grade = "A"; Student Results-----");
{ [Link](e.g else if(totalComputer for(int i=0;i<n;i++)
etMessage()); }}} >= 60) grade = "B"; students[i].displayResult();
else if(totalComputer
}} } AccountDetail(String
[Link](); name, int no, double bal,
[Link](); double min, double dep,
[Link]("File double with) {
copied successfully."); }}
Slip 15 super(name, no, bal,
Q2) Write a program to min);
Q1) Accept the names of
define a class Account depositamt = dep;
two files and copy the
having members withdrawalamt =
contents of the first to the
custname, accno. Define with;
second. First file having
default savingbal = savingbal
Book name and Author
+ depositamt -
name in file.
import [Link].*; withdrawalamt;
class Account {
import [Link].*;
String custname; }
import [Link].*;
int accno; void displayDetails() {
displaySaving();
class FileCopy {
Account() { [Link]("Deposi
public static void
custname = ""; t Amount: " + depositamt +
main(String args[]) throws
accno = 0; " Withdrawal Amount: " +
IOException {
} withdrawalamt);
Account(String name, [Link]("Update
Scanner sc = new
int no) { d Balance: " + savingbal);
Scanner([Link]);
custname = name; }
accno = no;
[Link]("Enter
public static void
source file name: ");
} main(String args[]) {
void displayAccount() {
String srcFile =
[Link]("Custo Scanner sc = new
[Link]();
mer Name: " + custname + Scanner([Link]);
" Account No: " + accno); [Link]("Enter
}} Name, Acc No, Balance,
[Link]("Enter
class SavingAccount Min Balance, Deposit,
destination file name: ");
extends Account { Withdrawal: ");
double savingbal;
String destFile = double minbal; String name =
[Link](); SavingAccount() { [Link]();
super();
File f1 = new savingbal = 0; int accno =
File(srcFile); minbal = 0; [Link]();
}
if(![Link]()) { SavingAccount(String double bal =
[Link]("Source name, int no, double bal, [Link]();
file does not exist."); double min) {
double min =
return; } super(name, no); [Link]();
savingbal = bal;
BufferedReader br = minbal = min; } double dep =
new BufferedReader(new void displaySaving() { [Link]();
FileReader(f1)); displayAccount(); double with =
[Link]("Saving [Link]();
BufferedWriter bw = Balance: " + savingbal + "
new BufferedWriter(new Minimum Balance: " + AccountDetail ad =
FileWriter(destFile)); minbal); }} new AccountDetail(name,
String line; class AccountDetail accno, bal, min, dep, with);
extends SavingAccount {
while((line =
[Link]();
[Link]()) != null) { double depositamt;
double withdrawalamt; }
[Link](line);
[Link]();
}
}
[Link](new
} ActionListener() {
Slip 16
Q2) Write a program to public void
Q1) Write a program to design a screen using Awt actionPerformed(ActionEv
find the Square of given that ent e) {
number using function
interface. String name =
[Link]();
// Import the functional import [Link].*;
interface package
import [Link].*; [Link]("Hello,
import " + name + "!");
[Link];
}
import [Link]; public class
SimpleAWTScreen { });

public static void


public class main(String[] args) {
SquareUsingFunctionInterf // Add components to
ace { // Create a Frame frame

public static void Frame f = new [Link](l);


main(String[] args) { Frame("AWT Example");
[Link](tf);
Scanner sc = new
Scanner([Link]); [Link](b);
// Create Label

Label l = new
Label("Enter your name:"); // Set frame properties
[Link]("Enter a
number: "); [Link](50, 50, [Link](400, 200);
120, 30);
int number = [Link](null);
[Link]();
[Link](true);
// Create TextField

// Using Function TextField tf = new


interface to define square TextField(); // Close window on
operation clicking close button
[Link](180, 50,
Function<Integer, 150, 30);
Integer> square = n -> n * [Link](new
n; WindowAdapter() {

// Create Button public void


windowClosing(WindowE
// Call the function Button b = new vent we) {
Button("Submit");
int result = [Link]();
[Link](number); [Link](100, 100,
80, 30); }

});

[Link]("Square // Add action to the }


of " + number + " is: " + button
result); }
balance = Borrower[] customers
Slip 17 [Link](); = new Borrower[n];
}
Q1) Design a Super class // Read details
Customer (name, phone- void displayDepositor() { for (int i = 0; i < n; i+
number). Derive a class displayCustomer(); +) {
Depositor(accno , balance)
from Customer. Again, [Link]("Accoun [Link]("Enter
derive a class Borrower t Number: " + accNo); details for Customer " + (i +
(loan-no, loan-amt) from 1));
Depositor. Write [Link]("Balance customers[i] = new
necessary member functions : " + balance); Borrower();
to read and display the }
details of ‘n’customers. } customers[i].readBorrower()
;
import [Link]; // Derived class from }
Depositor
// Superclass class Borrower extends // Display details
class Customer { Depositor { [Link]("\
String name; int loanNo; nCustomer Details:");
String phoneNumber; double loanAmount; for (int i = 0; i < n; i+
+) {
void readCustomer() { void readBorrower() {
Scanner sc = new readDepositor(); // customers[i].displayBorrow
Scanner([Link]); Read Depositor (and er();
Customer) details }
[Link]("Enter Scanner sc = new }
Customer Name: "); Scanner([Link]); }
name = [Link]();
[Link]("Enter
[Link]("Enter Loan Number: ");
Phone Number: "); loanNo = [Link]();
phoneNumber =
[Link](); [Link]("Enter
} Loan Amount: ");
loanAmount =
void displayCustomer() { [Link]();
}
[Link]("Name: "
+ name); void displayBorrower() {
displayDepositor();
[Link]("Phone
Number: " + [Link]("Loan
phoneNumber); Number: " + loanNo);
}
} [Link]("Loan
Amount: " + loanAmount);
// Derived class
class Depositor extends [Link]("----------
Customer { ------------------");
int accNo; }
double balance; }
void readDepositor() { // Main class
readCustomer(); // public class
Read Customer details CustomerDetails {
Scanner sc = new public static void
Scanner([Link]); main(String[] args) {
Scanner sc = new
[Link]("Enter Scanner([Link]);
Account Number: ");
accNo = [Link](); [Link]("Enter
number of customers: ");
[Link]("Enter int n = [Link]();
Balance: "); Slip 17 Q2
JButton concatButton });
Q2) Write Java program to = new
design three text boxes and JButton("Concatenate");
two buttons using swing.
Enter different JButton reverseButton // Add components to
strings in first and second = new JButton("Reverse"); frame
textbox. On clicking the
First command button, [Link](new
concatenation of JLabel("String 1:"));
two strings should be
// Add action listeners
displayed in third text box
[Link](tf1);
and on clicking second
command button,
[Link] [Link](new
tener(new ActionListener() JLabel("String 2:"));
import [Link].*;
{
import [Link].*; [Link](tf2);
public void
actionPerformed(ActionEv [Link](new
import [Link].*;
ent e) { JLabel("Output:"));

String str1 = [Link](tf3);


[Link]();
public class
StringOperationsSwing {
String str2 = [Link](concatButton);
[Link]();
public static void
main(String[] args) {
[Link](str1 + [Link](reverseButton);
str2);
// Create frame
}
JFrame frame = new
JFrame("String // Frame settings
});
Operations");

[Link](400, [Link]
200); ation(JFrame.EXIT_ON_C
LOSE);
[Link]
[Link](new
stener(new
FlowLayout());
ActionListener() { [Link](true);

public void }
actionPerformed(ActionEv
// Create text fields
ent e) { }
JTextField tf1 = new
String str1 =
JTextField(10);
[Link]();
JTextField tf2 = new
String str2 =
JTextField(10);
[Link]();
JTextField tf3 = new
String combined
JTextField(15);
= str1 + str2;

String reversed =
[Link](false); //
new
Output field should not be
StringBuilder(combined).r
editable
everse().toString();

[Link](reversed);
// Create buttons
}
double bat_avg;
Slip 18 // Constructor [Link]("--------
Q1) Border Layout CricketPlayer(String --------------------"); }}pu
Manager. name, int innings, int blic class CricketStats {
import [Link].*; notOut, int runs) { public static void
import [Link].*; [Link] = name; main(String[] args) {
public class this.no_of_innings =
BorderLayoutExample { innings; Scanner sc = new
public static void Scanner([Link]);
main(String[] args) { this.no_of_times_notout = [Link]("Enter
// Create frame notOut; number of players: ");
JFrame frame = new [Link] = runs; int n = [Link]();
JFrame("Border Layout this.bat_avg = 0.0; [Link](); // Consume
Example"); } newline
[Link](400, // Static method to CricketPlayer[] players =
300); calculate batting average new CricketPlayer[n];
[Link](new static void // Read player details
BorderLayout()); avg(CricketPlayer player)
// Create buttons for { for (int i = 0; i < n; i+
each region int outs = +)
JButton north = new player.no_of_innings - { [Link]
JButton("North"); player.no_of_times_notout ("Enter details for player "
JButton south = new ; + (i + 1));
JButton("South"); if (outs != 0) { [Link]("Name:
JButton east = new player.bat_avg = ");
JButton("East"); (double) [Link] / String name =
JButton west = new outs; [Link]();
JButton("West"); } else { [Link]("Number
JButton center = new player.bat_avg = of Innings: ");
JButton("Center"); [Link]; // If int innings =
never out, average = total [Link]();
// Add buttons to runs [Link]("Number
frame } } // Static method of times Not Out: ");
[Link](north, to sort array by battin int notOut =
[Link]); g average (descending) [Link]();
[Link](south, static void
[Link]); sort(CricketPlayer[] [Link]("Total
[Link](east, players) { Runs: ");
[Link]); for (int i = 0; i < int runs =
[Link](west, [Link] - 1; i++) { [Link]();
[Link]); [Link](); // Consume
[Link](center, for (int j = i + 1; j < newline
[Link]); [Link]; j++) { players[i] = new
// Frame settings if (players[i].bat_avg < CricketPlayer(name,
[Link] players[j].bat_avg) { innings, notOut, runs);
ation(JFrame.EXIT_ON_C CricketPlayer temp = [Link](players[i
LOSE); players[i]; ]); // Calculate batting
players[i] = players[j]; average } // Sort
[Link](true); }} players[j] = players by batting average
temp; } } }} [Link](players)
Q2) Define a class void display() ; // Display sorted
CricketPlayer { [Link]("N details
(name,no_of_innings,no_ ame: " + name); [Link]("\
of_times_notout, [Link]("Inning nPlayer Details in Sorted
totatruns, bat_avg). s: " + no_of_innings); Order (by batting
[Link]("Not average):");
import [Link]; Out: " +
class CricketPlayer { no_of_times_notout); for (CricketPlayer
String name; [Link]("Total player : players) {
int no_of_innings; Runs: " + totalRuns);
int no_of_times_notout; [Link]("Battin [Link]();} }}
int totalRuns; g Average: " + bat_avg);
"Software
int sum = 0; Testing" };
for (int i = 0; i < n; i+
+) { // Create ComboBox
sum += arr[i][i]; //
Slip 19 main diagonal elements JComboBox<String>
} comboBox = new
Q1) Write a program to [Link]("\ JComboBox<>(subjects);
accept the two dimensional nSum of diagonal elements
array from user and display = " + sum);
// Create TextField
sum of its diagonal }
elements. }
import [Link];
JTextField textField =
Q2) Write a program new JTextField(20);
public class DiagonalSum { which shows the combo
public static void box which includes list of
main(String[] args) { [Link].(Comp. Sci) [Link](false)
Scanner sc = new ;
Scanner([Link]); subjects. Display the
selected subject in a text // Add ActionListener
[Link]("Enter the field. to ComboBox
number of rows (n): ");
int n = [Link](); import [Link].*;
[Link]
[Link]("Enter the import [Link].*; ner(new ActionListener() {
number of columns (m): ");
int m = [Link](); import [Link].*; public void
actionPerformed(ActionEv
if (n != m) { ent e) {
public class
TYBScSubjects {
[Link]("Matrix String selected =
is not square! Diagonal sum (String)
can be calculated only for public static void
main(String[] args) { [Link]
square matrix.");
m();
return;
} // Create Frame

int[][] arr = new int[n] JFrame frame = new [Link](selected);


[m]; JFrame("[Link]. (Comp. } });
Sci) Subjects");
[Link]("Enter // Add components to
elements of the matrix:"); [Link](400, frame
for (int i = 0; i < n; i+ 200);
+) { [Link](new
for (int j = 0; j < m; [Link](new JLabel("Select Subject:"));
j++) { FlowLayout());
[Link]("Element // Create subject list [Link](comboBox);
[" + i + "][" + j + "]: ");
arr[i][j] = String[] subjects = { [Link](new
[Link](); JLabel("Selected
} Subject:"));
"Operating
}
Systems",
[Link]("\ [Link](textField);
nMatrix:");
for (int i = 0; i < n; i+ "Data Science",
// Frame settings
+) {
"Computer [Link]
for (int j = 0; j < m;
j++) { Networks", ation(JFrame.EXIT_ON_C
LOSE);
[Link](arr[i][j] + "Web [Link](true);
"\t"); Technologies",
} }}
[Link](); "Artificial
} Intelligence",
nce of floats = " + (x - y));
Slip 20 [Link]("State: " }}
+ stateName);
Q1) Write a Program to displayCountry(); package Operation;
illustrate multilevel displayContinent();
Inheritance such that } public class Maximum {
country is inherited from }
continent. State is inherited // Main class
from country. Display the public void max(int a,
public class int b) {
place, state, country and MultilevelInheritanceDemo
continent. {
if (a > b)
public static void
import [Link]; main(String[] args) {
[Link]("Maxim
Scanner sc = new um = " + a);
// Base class Scanner([Link]); else
class Continent { [Link]("Maxim
String continentName; State obj = new State(); um = " + b);
}}
void getContinent(String [Link]("Enter import [Link];
name) { Continent: ");
continentName = import
name; [Link]([Link] [Link];
} e());
void displayContinent() { import [Link];
[Link]("Enter public class MainProgram
[Link]("Contine Country: "); {
nt: " + continentName);
} [Link]([Link]( public static void
} )); main(String[] args) {
// Derived class [Link]("Enter
class Country extends Scanner sc = new
State: "); Scanner([Link]);
Continent {
String countryName; [Link]([Link]());
Addition addObj =
void getCountry(String new Addition();
[Link]("Enter
name) { Place: ");
countryName = name; Maximum maxObj =
} [Link]([Link]()); new Maximum();
[Link]("Enter
void displayCountry() { [Link]("\ two integers: ");
n--- Location Details ---");
[Link]("Country [Link](); int a = [Link]();
: " + countryName); }
} } int b = [Link]();
} Q2) Write a package for
// Derived class from Operation, which has two [Link](a, b);
Country classes, Addition and
class State extends Country Maximum. Addition has [Link](a, b);
{
String stateName; package Operation; [Link]("Enter
String placeName; public class Addition { two float numbers: ");
void getState(String
public void add(int a, int float x =
sname) {
b) { [Link]();
stateName = sname;
}
void getPlace(String float y =
pname) { [Link]("Sum [Link]();
placeName = pname; of integers = " + (a + b));
} } [Link](x, y);
void displayAll() { public void
subtract(float x, float y) { }
[Link]("Place: "
+ placeName); [Link]("Differe }
throw new public static void
Slip 21 InvalidDateException("Inv main(String[] args) {
alid Date! Month " + m + "
Q1) Define a class has only 30 days."); Scanner sc = new
MyDate(Day, Month, year) Scanner([Link]);
with methods to accept and
display a MyDateobject. MyDate date = new
// February check MyDate();
import [Link]; (leap year logic)

if (m == 2) {
try {
// User-defined Exception boolean leap = (y
% 4 == 0 && y % 100 !=
class InvalidDateException 0) || (y % 400 == 0); [Link]("Enter
extends Exception { date (dd mm yyyy): ");
if (leap && d > 29)
public int d = [Link]();
InvalidDateException(Stri throw new
ng message) { InvalidDateException("Inv int m = [Link]();
alid Date! February has 29
super(message); days in leap year."); int y = [Link]();
} if (!leap && d >
28)
} [Link](d,
throw new m, y);
InvalidDateException("Inv
alid Date! February has 28 [Link]();
// Class to store date days.");
} catch
class MyDate { } (InvalidDateException e) {
int day, month, year;
[Link]("Except
day = d; ion: " + [Link]());

// Method to accept date month = m; }


and validate
year = y; }
void acceptDate(int d,
int m, int y) throws } } [10 marks]
InvalidDateException {

if (y < 1 || m < 1 || m >


12 || d < 1 || d > 31) void displayDate() {
throw new
InvalidDateException("Inv [Link]("Valid
alid Date! Check Date: " + day + "/" +
day/month/year."); month + "/" + year);

}
// Months with 30 }
days

if ((m == 4 || m == 6 ||
m == 9 || m == 11) && d > // Main class
30)
public class
DateValidationDemo {
Slip 21 Q2 // Static method to display
count
}

Q2) Create an employee static void displayCount()


class(id,name,deptname,sal {
ary). Define a default and
parameterized [Link]("Numb
er of Employee objects
created: " + count);

}
class Employee {
void displayEmployee() {
int id;
[Link]("Emplo
String name; yee ID: " + id);

String deptname; [Link]("Name:


" + name);
double salary;
[Link]("Depart
static int count = 0; // static ment: " + deptname);
variable for object count
[Link]("Salary:
// Default constructor " + salary);

Employee() { [Link]("--------
------------------");
[Link] = 0;
}
[Link] = "Not
Assigned"; }

[Link] = "Not // Main class


Assigned";
public class
[Link] = 0.0; EmployeeDemo {

count++; public static void


main(String[] args) {
}
// Create employee objects
// Parameterized
constructor Employee e1 = new
Employee(1, "Alice", "IT",
Employee(int id, String 50000);
name, String deptname,
double salary) { [Link]();

[Link] = id; Employee e2 = new


Employee(2, "Bob", "HR",
[Link] = name; 45000);

[Link] = deptname; [Link]();

[Link] = salary; Employee e3 = new


Employee(3, "Charlie",
count++; "Finance", 55000);

displayCount(); [Link]();

} }
}
[Link]("Enter
length and breadth of
Slip 22 Rectangle: ");
// Triangle class
Q1) Write a program to int l = [Link]();
create an abstract class class Triangle extends
named Shape that contains Shape { int b = [Link]();
two integers and an
Triangle(int a, int b) { Shape rect = new
import [Link]; Rectangle(l, b);
super(a, b);
[Link]();
}
// Abstract class
void printArea() {
abstract class Shape {
[Link]("Enter
[Link]("Area base and height of
int dim1, dim2;
of Triangle: " + (0.5 * Triangle: ");
dim1 * dim2));
int base = [Link]();
Shape(int a, int b) { }
int height =
} [Link]();
dim1 = a;
// Circle class Shape tri = new
dim2 = b;
Triangle(base, height);
} class Circle extends Shape
{ [Link]();

Circle(int r) {
abstract void
printArea(); // abstract super(r, 0); // only one
dimension needed [Link]("Enter
method
radius of Circle: ");
} }
int r = [Link]();

Shape cir = new


void printArea() { Circle(r);
// Rectangle class
[Link]();
class Rectangle extends
[Link]("Area
Shape {
of Circle: " + (3.1416 * }
dim1 * dim1));
Rectangle(int a, int b) {
}
}
super(a, b);
[10 marks]
}
}
// Main class

public class ShapeDemo {


void printArea() {
public static void
[Link]("Area main(String[] args) {
of Rectangle: " + (dim1 *
dim2)); Scanner sc = new
Scanner([Link]);
}
Slip 22 Q2 } msg = "Mouse
}); Entered";
Q2) Write a program that
} repaint();
handles all mouse events
}
and shows the event name
public void
at the center of the
paint(Graphics g) { public void
mouseExited(MouseEvent
Window, red in color when
me) {
a mouse event is fired.
[Link]([Link]);
(Use adapter classes).
msg = "Mouse
[Link](new Exited";
import [Link].*;
Font("Arial", [Link], repaint();
20));
import [Link].*;
} }
[Link](msg,
public class
120, 150); // Inner class for
MouseEventDemo extends
MouseMotionAdapter
Frame {
}
class
String msg = "";
// Inner class for MyMouseMotionAdapter
MouseAdapter extends
public
MouseMotionAdapter {
MouseEventDemo() {
class MyMouseAdapter
extends MouseAdapter { public void
// Register listeners
mouseMoved(MouseEvent
using adapter classes
public void me) {
mouseClicked(MouseEven
t me) { msg = "Mouse
addMouseListener(new
Moved";
MyMouseAdapter());
msg = "Mouse
Clicked"; repaint();
addMouseMotionListener(
repaint(); }
new
MyMouseMotionAdapter()
} public void
);
mouseDragged(MouseEve
public void nt me) {
mousePressed(MouseEven
t me) { msg = "Mouse
setSize(400, 300);
Dragged";
msg = "Mouse
setTitle("Mouse
Pressed"; repaint();
Event Demo");
repaint(); }
setVisible(true);
} }

public void
// Close the window
mouseReleased(MouseEve
properly
nt me) { public static void
main(String[] args) {
addWindowListener(new msg = "Mouse
WindowAdapter() { Released"; new
MouseEventDemo();
public void repaint();
windowClosing(WindowE }
vent we) { }
}
dispose(); public void
mouseEntered(MouseEven
t me) {
JTextField(); } }
eurField = new private void
Slip 23 JTextField(); convertFromUSD() {
// Add listeners try {
isUpdating = true;
Q2) Write a simple
[Link] double usd =
currency converter, as
r(new ActionListener() { [Link](usdFi
shown in the figure. User
can enter the amount of [Link]());
public void double sgd = usd *
import [Link].*; actionPerformed(ActionEv 1.41;
import [Link].*; ent e) { double eur = usd *
import [Link].*; if (!isUpdating) 0.92;
import convertFromSGD(); [Link]([Link]
[Link]; } (sgd));
});
public class [Link] [Link]([Link](
CurrencyConverter extends r(new ActionListener() { eur));
JFrame { public void } catch
actionPerformed(ActionEv (NumberFormatException
ent e) { ex) {
private JTextField
if (!isUpdating) clearFields();
sgdField, usdField,
convertFromUSD(); } finally {
eurField;
} }); isUpdating = false;
[Link] } }
private boolean
(new ActionListener() {
isUpdating = false; //
public void private void
Prevents recursive updates
actionPerformed(ActionEv convertFromEUR() {
ent e) { try {
private DecimalFormat
if (!isUpdating) isUpdating = true;
df = new
convertFromEUR(); double eur =
DecimalFormat("#.00");
} }); [Link](eurFi
// Add to frame [Link]());
public
add(sgdLabel);
CurrencyConverter() {
add(sgdField); // reverse calculate
add(usdLabel); USD using EUR = USD *
setTitle("Currency
add(usdField); 0.92 → USD = EUR / 0.92
Converter");
add(eurLabel); double usd = eur /
add(eurField); 0.92;
setSize(350, 200);
setVisible(true); } double sgd = usd *
private void 1.41;
setLayout(new
convertFromSGD() { [Link]([Link]
GridLayout(3, 2, 5, 5));
try { (sgd));
isUpdating = true; [Link]([Link]
setDefaultCloseOperation(
double sgd = (usd));
JFrame.EXIT_ON_CLOS
[Link](sgdFi } catch
E); // Labels
[Link]()); (NumberFormatException
ex) {
JLabel sgdLabel =
double usd = sgd / clearFields();
new JLabel("Singapore
1.41; } finally {
Dollars",
isUpdating = false;
[Link]);
double eur = sgd * } }
0.65; private void
JLabel usdLabel =
[Link]([Link] clearFields() {
new JLabel("US Dollars",
(usd)); [Link]("");
[Link]);
[Link]([Link]( [Link]("");
eur)); [Link]("");
JLabel eurLabel =
} catch }
new JLabel("Euros",
(NumberFormatException public static void
[Link]);
ex) { main(String[] args) {
// Text Fields
clearFields(); new
sgdField = new
} finally { CurrencyConverter();}}
JTextField();
isUpdating = false;
usdField = new
// Method to check if }
Slip 23 Q1 number is zero
Q1) Define a class boolean isZero() {
MyNumber having one
// Parse command line
private int data member.
Write a default constructor to return num == 0; argument
initialize it to 0 and another
constructor to initialize it to a } int value =
value (Use this). Write [Link](args[0]);
methods

class MyNumber { // Method to check if


number is odd // Create object using
private int num; // parameterized constructor
private data member boolean isOdd() {
MyNumber n1 = new
return num % 2 != 0; MyNumber(value);

// Default constructor - }
initializes num to 0
// Display number
MyNumber() {
// Method to check if [Link]();
[Link] = 0; number is even

} boolean isEven() {
// Check properties
return num % 2 == 0;
[Link]("Is
// Parameterized } Positive? " +
constructor - initializes [Link]());
num using 'this'
[Link]("Is
MyNumber(int num) { // Display number Negative? " +
[Link]());
[Link] = num; void display() {
[Link]("Is
} Zero? " + [Link]());
[Link]("Numb
er: " + num); [Link]("Is
Odd? " + [Link]());
// Method to check if }
number is negative [Link]("Is
} Even? " + [Link]());
boolean isNegative() {
}
return num < 0;
public class }
} MyNumberDemo {

public static void


main(String[] args) {
// Method to check if
number is positive if ([Link] == 0) {

boolean isPositive() {
[Link]("Please
return num > 0; provide a number as
command line argument.");
}
return;
Slip 24 void getBalance() { public void
mouseClicked(MouseEven
[Link]("Balanc t me) {
Q1) Create an abstract e in Bank C: Rs." +
class 'Bank' with an balance); // Get click coordinates
abstract method
'getBalance'. Rs.100, }} x = [Link]();
Rs.150 and
// Main class y = [Link]();
// Abstract base class
public class BankDemo { repaint(); // redraw circles
abstract class Bank { at new position }
public static void
abstract void main(String[] args) { });
getBalance(); // abstract
method } Bank a = new // Add window listener to
BankA(100); close program
// Subclass BankA
Bank b = new addWindowListener(new
class BankA extends Bank BankB(150); WindowAdapter() {
{
Bank c = new BankC(200); public void
private int balance; windowClosing(WindowE
[Link](); vent we) {
BankA(int amount) {
[Link](); dispose(); // close window
[Link] = amount; }
[Link](); } });
void getBalance() {
}} }
[Link]("Balanc
e in Bank A: Rs." + Q2) Program that public void paint(Graphics
balance); } } displays three concentric g) {
circles where ever the
// Subclass BankB user clicks the mouse on // Draw 3 concentric
a frame. circles centered at (x, y)
class BankB extends Bank
{ import [Link].*; [Link](Color.LIGHT_
GRAY);
private int balance; import [Link].*;
[Link](x - 50, y - 50,
BankB(int amount) { public class 100, 100); // outer circle
ConcentricCircles extends
[Link] = amount; } Frame { [Link]([Link]);

void getBalance() { int x = -100, y = -100; // [Link](x - 35, y - 35,


initial position (off-screen) 70, 70); // middle circle
[Link]("Balanc
e in Bank B: Rs." + public ConcentricCircles() [Link](Color.DARK_
balance); } } { GRAY);

// Subclass BankC setTitle("Concentric [Link](x - 20, y - 20,


Circles"); 40, 40); // inner circle
class BankC extends Bank
{ setSize(400, 400); }

private int balance; setVisible(true); public static void


main(String[] args) {
BankC(int amount) { // Add mouse listener
new ConcentricCircles(); }
[Link] = amount; } addMouseListener(new
MouseAdapter() { }
[Link](); // Hobbies
Slip 25 [Link](); add(new
} JLabel("Your Hobbies:"));
Q1) Create a class } music = new
Student(rollno, name ,class, Q2) Create the following
per), to read student JCheckBox("Music");
GUI screen using dance = new
information from the appropriate layout JCheckBox("Dance");
manager. Accept the sports = new
name, class, JCheckBox("Sports");
import [Link].*;
class Student { add(music);
import [Link].*; add(dance);
int rollno;
import [Link].*; add(sports);
String name;
String cls;
import [Link].*; // Submit button
float per; submit = new
public class StudentForm JButton("Submit");
// Method to read data extends JFrame add(submit);
using BufferedReader implements ActionListener [Link](t
void readData() throws { his);
IOException { JTextField nameField; // Result area
BufferedReader br = JRadioButton fy, sy, ty; result = new
new BufferedReader(new JCheckBox music, JTextArea(3, 30);
InputStreamReader(System. dance, sports; add(result);
in)); JButton submit; // Frame settings
JTextArea result; setDefaultCloseOperation(
public StudentForm() { JFrame.EXIT_ON_CLOS
[Link]("Enter Roll setTitle("Student E);
No: "); Form"); setVisible(true); }
rollno = setSize(400, 300);
[Link]([Link] setLayout(new
()); public void
FlowLayout()); actionPerformed(ActionEv
[Link]("Enter add(new
Name: "); ent e) {
JLabel("Your Name:")); String name =
name = [Link](); nameField = new
[Link]("Enter [Link]();
JTextField(20); String cls = "";
Class: ");
add(nameField); if ([Link]()) cls
cls = [Link]();
[Link]("Enter = "FY";
Percentage: "); add(new else if
per = JLabel("Your Class:")); ([Link]()) cls =
[Link]([Link] "SY";
()); fy = new else if
} JRadioButton("FY"); ([Link]()) cls =
"TY";
// Method to display data sy = new String hobbies = "";
void displayData() { JRadioButton("SY"); if ([Link]())
[Link]("\ hobbies += "Music ";
n--- Student Details ---"); ty = new
JRadioButton("TY"); if ([Link]())
[Link]("Roll hobbies += "Dance ";
No: " + rollno); ButtonGroup
[Link]("Name: " classGroup = new if ([Link]())
+ name); ButtonGroup(); hobbies += "Sports ";
[Link]("Class: "
+ cls); [Link]("Name:
[Link](fy); " + name + "\nClass: " +
[Link]("Percent [Link](sy);
age: " + per); cls + "\nHobbies: " +
[Link](ty); hobbies); }
}
add(fy); public static void
}
add(sy); main(String[] args) {
public class StudentDemo {
add(ty); new StudentForm();
public static void
main(String[] args) throws
IOException { }}
Student s = new
Student();
[Link]();
Slip 26 [Link]("-------- LocalDate date =
-------------------"); } [Link](dateStr);
Q2) Define a class
‘Donor’ to store the below }public class [Link](new
mentioned details of a DonorFileDemo { Donor(name, age, addr,
blood donor. name, age, contact, bg, date)); }
public static void
address, contactnumber, main(String[] args) throws // Write donors to file
bloodgroup, date of last Exception {
donation. Create ‘n’ ObjectOutputStream
Scanner sc = new oos = new
import [Link].*; Scanner([Link]); ObjectOutputStream(new
import [Link].*; FileOutputStream("donors.
import [Link].*; dat"));
[Link]("Enter
class Donor implements number of donors: ");
Serializable { [Link](donorList)
int n = [Link](); ;
String name; [Link]();
[Link](); [Link]("\
int age; nDonor data saved to file.\
ArrayList<Donor> n");
String address; donorList = new
String contactNumber; ArrayList<>(); // Read donors from
String bloodGroup; file
LocalDate lastDonation; for (int i = 0; i < n; i+
+) ObjectInputStream ois
Donor(String name, int { [Link]( = new
age, String address, String "Enter details for Donor " ObjectInputStream(new
contactNumber, String + (i + 1)); FileInputStream("donors.d
bloodGroup, LocalDate [Link]("Name: at"));
lastDonation) { "); String name =
[Link](); ArrayList<Donor>
[Link] = name; [Link]("Age: "); list = (ArrayList<Donor>)
[Link] = age; [Link]();
[Link] = address; int age =
[Link] = [Link](); [Link]();
contactNumber;
[Link] = [Link](); [Link]("Donor
bloodGroup; s with Blood Group A+ve
[Link] = [Link]("Address: and not donated in last 6
lastDonation; "); months:\n");
String addr =
} [Link](); LocalDate today =
[Link]();
void display() { [Link]("Contact for (Donor d : list) {
Number: "); Period p =
[Link]([Link]
[Link]("Name: String contact = tion, today);
" + name); [Link]();
[Link]("Age: " if
+ age); ([Link]
[Link]("Addres [Link]("Blood eCase("A+ve") &&
s: " + address); Group: "); [Link]() +
[Link]("Contac ([Link]() * 12) >= 6) {
t: " + contactNumber); String bg =
[Link]("Blood [Link](); [Link]();
Group: " + bloodGroup); [Link]("Last
[Link]("Last Donation Date (yyyy-mm- } }}}
Donation: " + dd): ");
lastDonation); String dateStr =
Slip 27 if([Link]("y [Link]("Invalid
")) { path");
Q2) Write a program to
accept a string as for(File file : }
command line argument files) {
and check whether it is a [Link]();
file or
if([Link]()) count++; }
directory. Also perform
operations as follows: } }

import [Link].*;
[Link](count +
import [Link]; " files deleted.");

} else {

public class
FileDirectoryCheck { [Link]("No
files deleted.");
public static void
main(String[] args) { }

if([Link] < 1) { } else {

[Link]("Please [Link]("No
provide a path as command text files found in
line argument."); directory.");

return; }

} } else if([Link]()) {

File f = new
File(args[0]); [Link]("File
Name: " + [Link]());
Scanner sc = new
Scanner([Link]);
[Link]("Absolu
te Path: " +
[Link]());
if([Link]()) {

File[] files = [Link]("Size: "


[Link]((dir, name) -> + [Link]() + " bytes");
[Link](".txt"));

if(files != null && [Link]("Reada


[Link] > 0) { ble: " + [Link]());

[Link]("Do [Link]("Writab
you want to delete " + le: " + [Link]());
[Link] + " text files?
(y/n)");
[Link]("Execut
String ans = able: " + [Link]());
[Link]();
} else {
int count = 0;
} [Link](cField);

Q2) Write a program [Link](fLabel);


Slip 28 called
SwingTemperatureConver [Link](fField);
Q1) Write a program ter to convert temperature
that reads on file name values [Link](toF);
from the user, then between Celsius and
displays information about Fahrenheit. User can enter [Link](toC);
either the Celsius or the
import [Link].*; Fahrenheit value, [Link](e ->
{
import [Link]; in floating-point number.
Hints:
try {
import [Link].*;
double c =
public class FileInfo { [Link](cFiel
import [Link].*;
[Link]());
public static void
main(String[] args) { import [Link].*;
double f = (c * 9/5) + 32;
Scanner sc = new public class
[Link]([Link]
Scanner([Link]); SwingTemperatureConvert
t("%.1f", f));
er {
} catch(Exception ex) {
[Link]("Enter public static void
file name: "); main(String[] args) {
[Link]
Dialog(frame, "Invalid
String fileName = JFrame frame = new
Celsius value"); }
[Link](); JFrame("Temperature
Converter");
});
File f = new
File(fileName); [Link](300, 200);
[Link](e -
>{
[Link]("File [Link]
exists: " + [Link]()); ation(JFrame.EXIT_ON_C
try {
LOSE);
if([Link]()) { double f =
[Link](new
[Link](fField
[Link]("Reada GridLayout(4, 2));
.getText());
ble: " + [Link]());
JLabel cLabel = new
double c = (f - 32) * 5/9;
JLabel("Celsius:");
[Link]("Writab
[Link]([Link]
le: " + [Link]()); JTextField cField = new
at("%.1f", c));
JTextField();
} catch(Exception ex) {
[Link]("Type: JLabel fLabel = new
" + ([Link]() ? "File" : JLabel("Fahrenheit:");
[Link]
[Link]() ?
Dialog(frame, "Invalid
"Directory" : "Other")); JTextField fField = new
Fahrenheit value");
JTextField();
}
[Link]("Length JButton toF = new
: " + [Link]() + " bytes"); JButton("Convert to
});
Fahrenheit");
}
[Link](true); }
JButton toC = new
[Link](); JButton("Convert to
}
Celsius");
}
[Link](cLabel);
class HeavyMotorVehicle
Slip 29 extends Vehicle { [Link]("Compan
y: ");
Q2) Write a program to double capacityInTons;
create a super class String company =
Vehicle having members [Link]();
Company and price.

import [Link]; HeavyMotorVehicle(String [Link]("Price: ");


company, double price,
class Vehicle { double capacityInTons) { double price =
[Link]();
String company; super(company,
price); if(type == 1) {
double price;
[Link] =
Vehicle(String capacityInTons; [Link]("Mileage:
company, double price) { ");
}
[Link] = double mileage =
company; void display() { [Link]();

[Link] = price; [Link](); vehicles[i] = new


LightMotorVehicle(compa
} ny, price, mileage);
[Link]("Capaci
void display() { ty (tons): " + } else {
capacityInTons);

[Link]("Compa }} [Link]("Capacity
ny: " + company); in tons: ");
public class VehicleInfo {
double capacity
[Link]("Price: public static void = [Link]();
" + price); main(String[] args) {
vehicles[i] = new
}} Scanner sc = new HeavyMotorVehicle(comp
Scanner([Link]); any, price, capacity);
class LightMotorVehicle [Link]("Enter
extends Vehicle { number of vehicles: "); }

double mileage; int n = [Link](); [Link]();


LightMotorVehicle(String
company, double price, Vehicle[] vehicles = }
double mileage) { new Vehicle[n]; [Link]("\
nVehicle Details:");
super(company, for(int i=0; i<n; i++) {
price); for(Vehicle v :
vehicles) {
[Link] = [Link]("Vehicl
mileage; } e " + (i+1)); [Link]();
[Link]("Enter
void display() { type (1-Light, 2-Heavy):
"); [Link]();
[Link]();
int type = }
[Link]();
[Link]("Mileag [Link](); }
e: " + mileage); [Link]();
}
}}
JButton divideButton =
new JButton("Divide");

Slip 30 [Link](n1Label);

Q2) Write a program that [Link](n1Field);


creates a user interface to
perform integer divisions. [Link](n2Label);
The user enters two
[Link](n2Field);
numbers in the text fields,
Number1 and Number2. [Link](resultLabel);
The division of Number1
and Number2 is [Link](resultField);

import [Link].*; [Link](divideButton);

import [Link].*; [Link]


tener(e -> {
import [Link].*;
try {
public class
IntegerDivision { int num1 =
[Link]([Link]
public static void tText());
main(String[] args) {
int num2 =
JFrame frame = new [Link]([Link]
JFrame("Integer tText());
Division");
int result = num1 / num2;
[Link](300, 200);
[Link](String.v
[Link] alueOf(result));
ation(JFrame.EXIT_ON_C
LOSE); } catch
(NumberFormatException
[Link](new ex) {
GridLayout(4, 2));
[Link]
JLabel n1Label = new Dialog(frame, "Please
JLabel("Number1:"); enter valid integers.");

JTextField n1Field = new } catch


JTextField(); (ArithmeticException ex) {

JLabel n2Label = new [Link]


JLabel("Number2:"); Dialog(frame, "Division by
zero is not allowed.");
JTextField n2Field = new
JTextField(); }

JLabel resultLabel = new });


JLabel("Result:");
[Link](true);
JTextField resultField =
new JTextField(); }

[Link](fals }
e);

You might also like