Java Practicals
Java Practicals
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]()) {
}
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
});
[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
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]());
}
// 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
}
}
class Employee {
void displayEmployee() {
int id;
[Link]("Emplo
String name; yee ID: " + id);
Employee() { [Link]("--------
------------------");
[Link] = 0;
}
[Link] = "Not
Assigned"; }
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]();
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
// 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 {
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]);
import [Link].*;
[Link](count +
import [Link]; " files deleted.");
} else {
public class
FileDirectoryCheck { [Link]("No
files deleted.");
public static void
main(String[] args) { }
[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]()) {
[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);
[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: "); }
Slip 30 [Link](n1Label);
[Link](fals }
e);