Java Assignment MSC
Java Assignment MSC
Assignment
Subject: Object Oriented Programming
Course Code: CMSPCOR06T
Submitted to:
Dr. Krishnendu Basuli
Department of Computer Science
West Bengal State University
Contents
1 Shipping database using multilevel inheritance 7
1.1 Java Implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.2 Program Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
6 Stack 39
6.1 Java implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
6.2 Program output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
7 Queue 45
7.1 Java implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
7.2 Program output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
1
10 Package and interface with inheritance 63
10.1 File directory structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
10.2 Java implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
10.2.1 [Link] . . . . . . . . . . . . . . . . . . . . . . . . . 63
10.2.2 animalKingdom/[Link] . . . . . . . . . . . . . . . . . . . . . . . . 64
10.2.3 animalKingdom/[Link] . . . . . . . . . . . . . . . . . . . . . . . . . 65
10.2.4 animalKingdom/[Link] . . . . . . . . . . . . . . . . . . . . . . . . 66
10.2.5 animalKingdom/[Link] . . . . . . . . . . . . . . . . . . . . . . . 67
10.2.6 animalKingdom/[Link] . . . . . . . . . . . . . . . . . . . . . 67
10.3 Program output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
12 Nested try-catch 72
12.1 Java implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
12.2 Program output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
16 Banker’s algorithm 79
16.1 Java implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
16.2 Program input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
16.3 Program output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
2
19 Applet program 1 86
19.1 Java implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
19.2 HTML implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
19.3 Program output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
20 Native Method 88
20.1 File directory structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
20.2 Java implementaion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
20.2.1 NativeMethod/[Link] . . . . . . . . . . . . . . . . . . . . 88
20.3 C implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
20.3.1 NativeMethod/NativeExample.c . . . . . . . . . . . . . . . . . . . . . . 88
20.4 Native Method Execution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
20.5 Program output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
22 Demonstrate InetAddress 93
22.1 Java implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
22.2 Program output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
23 Demonstrate getPort() 95
23.1 File directory structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
23.2 Java implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
23.2.1 portDemo/networking/[Link] . . . . . . . . . . . . . . . . . . . . . 95
23.2.2 portDemo/networking/[Link] . . . . . . . . . . . . . . . . . . . . . 95
23.3 Socket Communication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
23.3.1 Server Terminal Output (Before Client Connects) . . . . . . . . . . . . . . 96
23.3.2 Client Terminal Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
23.3.3 Updated Server Terminal Output (After Client Connects) . . . . . . . . . . 96
24 Demonstrate URL 97
24.1 Java implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
24.2 Program input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
24.3 Program output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
25 Demonstrate Datagram 98
25.1 File directory structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
25.2 Java implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
25.2.1 Datagram/[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
25.2.2 Datagram/[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
25.3 UDP Socket Execution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
25.3.1 Server Terminal Output (Before Client Connects) . . . . . . . . . . . . . . 100
25.3.2 Client Terminal Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
25.3.3 Server Terminal Output (After Client Sends Message) . . . . . . . . . . . . 100
3
26 Keyboard event listener 101
26.1 Java implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
26.2 Program output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
4
37 Shapes 129
37.1 Java implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
37.2 Program output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
42 Checkbox 136
42.1 Java implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136
42.2 Program output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
44 List 140
44.1 Java implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
44.2 Program output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141
46 Calculator 144
46.1 Java implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144
46.2 Program output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146
5
49 Sound effect 152
49.1 Java implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152
49.2 Program output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
6
1 Shipping database using multilevel inheritance
Write a program in Java for a shipping database using multilevel inheritance with at least 3 classes.
All classes must have two member variables and two member methods.
class shipment {
protected String shipmentId ;
protected String destination ;
public double c a l c u l a t e S h i p p i n g C o s t () {
return cargoWeight * 2.5;
}
7
public void updateCargoType ( String newType ) {
this . cargoType = newType ;
}
public void d i s p l a y C o n t a i n e r D e t a i l s () {
System . out . println ( " Container : " + containerNumber + " ( " +
containerSize + " ) " ) ;
}
while ( running ) {
System . out . println ( " \ n ===== Shipping Database Menu ===== " ) ;
System . out . println ( " 1. Add New Shipment " ) ;
System . out . println ( " 2. View All Shipments " ) ;
System . out . println ( " 3. Update destination " ) ;
System . out . println ( " 4. Update cargo details " ) ;
8
System . out . println ( " 5. Update container details " ) ;
System . out . println ( " 6. Exit " ) ;
System . out . print ( " Enter your choice (1 -6) : " ) ;
switch ( choice ) {
case 1 -> addNewShipment () ;
case 2 -> viewAllShipments () ;
case 3 -> u p d a t e S h i p m e n t D e s t i n a t i o n () ;
case 4 -> up da teC ar go De ta il s () ;
case 5 -> u p d a t e C o n t a i n e r D e t a i l s () ;
case 6 -> running = confirmExit () ;
}
}
System . out . println ( " Program exited . Thank you ! " ) ;
sc . close () ;
}
String shipmentId ;
while ( true ) {
System . out . print ( " Shipment ID : " ) ;
shipmentId = sc . nextLine () . trim () ;
if ( shipmentId . isEmpty () ) {
System . out . println ( " Error : Shipment ID cannot be empty ! " ) ;
continue ;
}
if ( i sS hi pm en tI dE xi st s ( shipmentId ) ) {
System . out . println ( " Error : Shipment ID already exists ! " ) ;
} else {
break ;
}
}
System . out . print ( " Destination : " ) ;
String destination = sc . nextLine () ;
9
container newContainer = new container ( shipmentId , destination ,
cargoWeight ,
cargoType , containerNumber , containerSize ) ;
shipments . add ( newContainer ) ;
10
private static void up da te Ca rg oD et ai ls () {
if ( shipments . isEmpty () ) {
System . out . println ( " \ nNo shipments available to update ! " ) ;
return ;
}
System . out . println ( " \ n === Update Cargo Details === " ) ;
v i e w A l l S h i p m e n t s B r i e f () ;
System . out . print ( " Enter shipment number to update : " ) ;
int index = getIntInput ( shipments . size () ) - 1;
System . out . println ( " \ n === Update Container Details === " ) ;
v i e w A l l S h i p m e n t s B r i e f () ;
System . out . print ( " Enter shipment number to update : " ) ;
int index = getIntInput ( shipments . size () ) - 1;
11
try {
int input = Integer . parseInt ( sc . nextLine () ) ;
if ( input >= 1 && input <= max ) return input ;
System . out . printf ( " Please enter a number between % d and % d
: " , 1 , max ) ;
} catch ( N u m b e r F o r m a t E x c e p t i o n e ) {
System . out . print ( " Invalid input . Please enter a number : " )
;
}
}
}
12
Shipment added successfully!
===== Shipping Database Menu =====
1. Add New Shipment
2. View All Shipments
3. Update destination
4. Update cargo details
5. Update container details
6. Exit
Enter your choice (1-6): 2
=== All Shipments ===
Shipment #1
Tracking shipment ID: SHP-001 heading to New York
Cargo Type: Electronics, Weight: 1500.0 kg
Shipping Cost: \$3750.00
Container: CNTR-001 (40ft)
----------------------
===== Shipping Database Menu =====
1. Add New Shipment
2. View All Shipments
3. Update destination
4. Update cargo details
5. Update container details
6. Exit
Enter your choice (1-6): 3
=== Update Destination ===
Shipment #1 - ID: SHP-001 | Container: CNTR-001 (40ft)
Enter shipment number to update: 1
Enter new destination: Chicago
Destination updated for shipment SHP-001
Destination updated successfully!
===== Shipping Database Menu =====
1. Add New Shipment
2. View All Shipments
3. Update destination
4. Update cargo details
5. Update container details
6. Exit
Enter your choice (1-6): 6
Are you sure you want to exit? (yes/no): yes
Program exited. Thank you!
13
2 Shape Area Calculation: Polymorphism & Inheritance
Write a program in Java to calculate the area of different shapes using polymorphism and inheritance.
@Override
public double calculateArea () {
return Math . PI * radius * radius ;
}
}
class Rectangle extends Shape {
private final double length ;
private final double width ;
@Override
public double calculateArea () {
return length * width ;
}
}
class Triangle extends Shape {
private final double base ;
private final double height ;
@Override
public double calculateArea () {
return ( base * height ) / 2;
14
}
}
class Rhombus extends Shape {
private final double diagonal1 ;
private final double diagonal2 ;
@Override
public double calculateArea () {
return ( diagonal1 * diagonal2 ) / 2;
}
}
class Parallelogram extends Shape {
private final double base ;
private final double height ;
@Override
public double calculateArea () {
return base * height ;
}
}
class Trapezium extends Shape {
private final double base1 ;
private final double base2 ;
private final double height ;
@Override
public double calculateArea () {
return (( base1 + base2 ) / 2) * height ;
}
}
class E q u il a t er a l Tr i a ng l e extends Shape {
private final double side ;
@Override
15
public double calculateArea () {
return ( Math . sqrt (3) / 4) * side * side ;
}
}
class Sector extends Shape {
private final double radius ;
private final double angle ; // in degrees
@Override
public double calculateArea () {
return ( Math . PI * radius * radius ) * ( angle / 360) ;
}
}
public class S ha p e Ar e a Ca l c ul a t or {
public static void main ( String [] args ) {
Scanner scanner = new Scanner ( System . in ) ;
int choice ;
do {
System . out . println ( " \ nShape Area Calculator " ) ;
System . out . println ( " 1. Circle " ) ;
System . out . println ( " 2. Rectangle " ) ;
System . out . println ( " 3. Triangle " ) ;
System . out . println ( " 4. Rhombus " ) ;
System . out . println ( " 5. Parallelogram " ) ;
System . out . println ( " 6. Trapezium " ) ;
System . out . println ( " 7. Equilateral Triangle " ) ;
System . out . println ( " 8. Sector " ) ;
System . out . println ( " 9. Exit " ) ;
System . out . print ( " Enter your choice : " ) ;
switch ( choice ) {
case 1 -> {
System . out . print ( " Enter radius : " ) ;
shape = new Circle ( scanner . nextDouble () ) ;
}
case 2 -> {
System . out . print ( " Enter length : " ) ;
double length = scanner . nextDouble () ;
System . out . print ( " Enter width : " ) ;
shape = new Rectangle ( length , scanner . nextDouble () ) ;
}
case 3 -> {
System . out . print ( " Enter base : " ) ;
double base = scanner . nextDouble () ;
16
System . out . print ( " Enter height : " ) ;
shape = new Triangle ( base , scanner . nextDouble () ) ;
}
case 4 -> {
System . out . print ( " Enter first diagonal : " ) ;
double d1 = scanner . nextDouble () ;
System . out . print ( " Enter second diagonal : " ) ;
shape = new Rhombus ( d1 , scanner . nextDouble () ) ;
}
case 5 -> {
System . out . print ( " Enter base : " ) ;
double pBase = scanner . nextDouble () ;
System . out . print ( " Enter height : " ) ;
shape = new Parallelogram ( pBase , scanner . nextDouble () )
;
}
case 6 -> {
System . out . print ( " Enter first base : " ) ;
double b1 = scanner . nextDouble () ;
System . out . print ( " Enter second base : " ) ;
double b2 = scanner . nextDouble () ;
System . out . print ( " Enter height : " ) ;
shape = new Trapezium ( b1 , b2 , scanner . nextDouble () ) ;
}
case 7 -> {
System . out . print ( " Enter side length : " ) ;
shape = new E q u il a t er a l Tr i a n gl e ( scanner . nextDouble () ) ;
}
case 8 -> {
System . out . print ( " Enter radius : " ) ;
double radius = scanner . nextDouble () ;
System . out . print ( " Enter angle ( degrees ) : " ) ;
shape = new Sector ( radius , scanner . nextDouble () ) ;
}
case 9 -> System . out . println ( " Exiting program ... " ) ;
default -> System . out . println ( " Invalid choice ! Please try
again . " ) ;
}
if ( shape != null ) {
shape . displayArea () ;
}
} while ( choice != 9) ;
scanner . close () ;
}
}
17
2.2 Program Output
18
Enter second base: 7
Enter height: 4
Area: 24.00
Shape Area Calculator
1. Circle
2. Rectangle
3. Triangle
4. Rhombus
5. Parallelogram
6. Trapezium
7. Equilateral Triangle
8. Sector
9. Exit
Enter your choice: 7
Enter side length: 6
Area: 15.59
Shape Area Calculator
1. Circle
2. Rectangle
3. Triangle
4. Rhombus
5. Parallelogram
6. Trapezium
7. Equilateral Triangle
8. Sector
9. Exit
Enter your choice: 8
Enter radius: 10
Enter angle (degrees): 60
Area: 52.36
Shape Area Calculator
1. Circle
2. Rectangle
3. Triangle
4. Rhombus
5. Parallelogram
6. Trapezium
7. Equilateral Triangle
8. Sector
9. Exit
Enter your choice: 12
Invalid choice! Please try again.
Shape Area Calculator
1. Circle
2. Rectangle
3. Triangle
4. Rhombus
5. Parallelogram
6. Trapezium
7. Equilateral Triangle
8. Sector
9. Exit
Enter your choice: 9
Exiting program...
19
3 Hospital management using multilevel inheritance
Write a program in Java for Hospital management using Multilevel inheritance with at least 3
classes all classes must have two-member variable and two -member method.
class Person {
protected String name ;
protected int age ;
public void d i s p l a y M e d i c a l I n f o r m a t i o n () {
System . out . println ( " Diagnosis : " + diagnosis + " , Doctor : " +
attendingDoctor ) ;
}
}
20
public InPatient ( String name , int age , String diagnosis , String
attendingDoctor ,
String admissionDate , int roomNumber ) {
super ( name , age , diagnosis , attendingDoctor ) ;
this . admissionDate = admissionDate ;
this . roomNumber = roomNumber ;
}
public void d i s p l a y A d m i s s i o n D e t a i l s () {
System . out . println ( " Admission Date : " + admissionDate + " , Room : "
+ roomNumber ) ;
}
}
while ( running ) {
System . out . println ( " \ n ===== Hospital Management System ===== " )
;
System . out . println ( " 1. Admit New Patient " ) ;
System . out . println ( " 2. View All Patients " ) ;
System . out . println ( " 3. Update Diagnosis " ) ;
System . out . println ( " 4. Assign New Room " ) ;
System . out . println ( " 5. Discharge Patient " ) ;
System . out . println ( " 6. Exit " ) ;
System . out . print ( " Enter your choice (1 -6) : " ) ;
switch ( choice ) {
case 1 -> admitPatient () ;
case 2 -> viewAllPatients () ;
case 3 -> updateDiagnosis () ;
case 4 -> assignNewRoom () ;
case 5 -> dischargePatient () ;
case 6 -> running = confirmExit () ;
}
}
System . out . println ( " Program exited . Thank you ! " ) ;
sc . close () ;
}
21
private static void admitPatient () {
System . out . println ( " \ n === New Patient Admission === " ) ;
22
System . out . print ( " Enter new diagnosis : " ) ;
String newDiagnosis = sc . nextLine () ;
System . out . println ( " \ n === Assign New Room === " ) ;
viewBriefList () ;
System . out . print ( " Enter patient number to update : " ) ;
int index = getIntInput (1 , patients . size () ) - 1;
23
System . out . printf ( " Please enter between %d -% d : " , min , max
);
} catch ( N u m b e r F o r m a t E x c e p t i o n e ) {
System . out . print ( " Invalid input . Enter a number : " ) ;
}
}
}
private static void viewBriefList () {
for ( int i = 0; i < patients . size () ; i ++) {
System . out . println ( " Patient # " + ( i +1) + " : " + patients . get ( i
) . name ) ;
}
}
private static String getValidDate () {
Dat eTimeF ormatt er formatter = Da teTime Forma tter . ofPattern ( " dd / MM /
yyyy " ) ;
while ( true ) {
try {
String dateInput = sc . nextLine () ;
LocalDate . parse ( dateInput , formatter ) ;
return dateInput ;
} catch ( D a t e T i m e P a r s e E x c e p t i o n e ) {
System . out . println ( " Invalid date format ! Please use DD / MM /
YYYY format . " ) ;
}
}
}
}
24
5. Discharge Patient
6. Exit
Enter your choice (1-6): 1
=== New Patient Admission ===
Patient Name: Jane Smith
Age: 32
Diagnosis: Fractured Arm
Attending Doctor (Dr.): Johnson
Admission Date (DD/MM/YYYY): 16/05/2024
Room Number: 312
Patient admitted successfully!
===== Hospital Management System =====
1. Admit New Patient
2. View All Patients
3. Update Diagnosis
4. Assign New Room
5. Discharge Patient
6. Exit
Enter your choice (1-6): 2
=== Patient Records ===
Patient #1
Name: John Doe, Age: 45
Diagnosis: Pneumonia, Doctor: Smith
Admission Date: 15/05/2024, Room: 205
----------------------
Patient #2
Name: Jane Smith, Age: 32
Diagnosis: Fractured Arm, Doctor: Johnson
Admission Date: 16/05/2024, Room: 312
----------------------
===== Hospital Management System =====
1. Admit New Patient
2. View All Patients
3. Update Diagnosis
4. Assign New Room
5. Discharge Patient
6. Exit
Enter your choice (1-6): 3
=== Update Diagnosis ===
Patient #1: John Doe
Patient #2: Jane Smith
Enter patient number to update: 1
Enter new diagnosis: Severe Bronchitis
Diagnosis updated for John Doe
===== Hospital Management System =====
1. Admit New Patient
2. View All Patients
3. Update Diagnosis
4. Assign New Room
5. Discharge Patient
6. Exit
25
Enter your choice (1-6): 4
=== Assign New Room ===
Patient #1: John Doe
Patient #2: Jane Smith
Enter patient number to update: 2
Enter new room number: 410
Room assigned for Jane Smith
===== Hospital Management System =====
1. Admit New Patient
2. View All Patients
3. Update Diagnosis
4. Assign New Room
5. Discharge Patient
6. Exit
Enter your choice (1-6): 5
=== Discharge Patient ===
Patient #1: John Doe
Patient #2: Jane Smith
Enter patient number to discharge: 1
Patient John Doe discharged successfully!
Discharge Summary:
Name: John Doe, Age: 45
Diagnosis: Severe Bronchitis, Doctor: Smith
Admission Date: 15/05/2024, Room: 205
===== Hospital Management System =====
1. Admit New Patient
2. View All Patients
3. Update Diagnosis
4. Assign New Room
5. Discharge Patient
6. Exit
Enter your choice (1-6): 2
=== Patient Records ===
Patient #1
Name: Jane Smith, Age: 32
Diagnosis: Fractured Arm, Doctor: Johnson
Admission Date: 16/05/2024, Room: 410
----------------------
===== Hospital Management System =====
1. Admit New Patient
2. View All Patients
3. Update Diagnosis
4. Assign New Room
5. Discharge Patient
6. Exit
Enter your choice (1-6): 6
Are you sure you want to exit? (yes/no): yes
Program exited. Thank you!
26
4 Library management using multilevel inheritance
Write a program in Java for Library management using Multilevel inheritance with at least 3 classes
all classes must have two-member variable and two -member method.
class LibraryItem {
protected String title ;
protected boolean isAvailable ;
27
private final int edition ;
private final String isbn ;
public C om p u te r S ci e n ce B o ok ( String title , String author , String isbn ,
String specialization , int edition ) {
super ( title , author ) ;
this . specialization = specialization ;
this . edition = edition ;
this . isbn = isbn ;
}
@Override
public void displayInfo () {
super . displayInfo () ;
System . out . println ( " Specialization : " + specialization ) ;
System . out . println ( " Edition : " + edition ) ;
System . out . println ( " ISBN : " + isbn ) ;
}
}
public class L i b r a r y M a n a g e m e n t S y s t e m {
private static final ArrayList < LibraryItem > library = new ArrayList
< >() ;
private static final Scanner scanner = new Scanner ( System . in ) ;
28
" 8176560724 " ,
" Databases " ,
1
));
29
" Data Communication and Networking " ,
" Behrouz A . Forouzan " ,
" 0073376221 " ,
" Networking " ,
5
));
while ( true ) {
System . out . println ( " \ n ===== Computer Science Library ===== " ) ;
System . out . println ( " 1. Show All Books " ) ;
System . out . println ( " 2. Check Out Book " ) ;
System . out . println ( " 3. Return Book " ) ;
System . out . println ( " 4. Exit " ) ;
System . out . print ( " Enter choice (1 -4) : " ) ;
switch ( choice ) {
case 1 -> displayBooks () ;
case 2 -> checkOutBook () ;
case 3 -> returnBook () ;
case 4 -> {
System . out . println ( " Exiting Program .... " ) ;
scanner . close () ;
System . exit (0) ;
}
}
}
}
30
if ( item instanceof C om p u te r S ci e n c eB o o k csb ) {
csb . displayInfo () ;
System . out . println ( " Status : " + ( csb . isAvailable ? "
Available " : " Checked Out " ) ) ;
}
System . out . println ( " - - - - - - - - - - - - - - - - - - - - - - " ) ;
}
}
31
4.2 Program Output
32
Status: Available
Enter book number to check out: 1
Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow: Concepts,
Tools, and Techniques to Build Intelligent Systems, Third Edition checked out
successfully
===== Computer Science Library =====
1. Show All Books
2. Check Out Book
3. Return Book
4. Exit
Enter choice (1-4): 1
Available Computer Science Books:
1. Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow:
Concepts, Tools, and Techniques to Build Intelligent Systems, Third Edition
Author: Aurélien Géron
Specialization: Machine Learning
Edition: 3
ISBN: 1098125975
Status: Checked Out
----------------------
2. Data Science From Scratch
Author: Joel Grus
Specialization: Data Science
Edition: 2
ISBN: 1492041130
Status: Available
----------------------
... [Additional books displayed] ...
13. Java: The Complete Reference
Author: Herbert Schildt
Specialization: Programming
Edition: 11
ISBN: 1260440230
Status: Available
----------------------
===== Computer Science Library =====
1. Show All Books
2. Check Out Book
3. Return Book
4. Exit
Enter choice (1-4): 3
1. Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow:
Concepts, Tools, and Techniques to Build Intelligent Systems, Third Edition
Status: Checked Out
2. Data Science From Scratch
Status: Available
3. Python Data Science Handbook
Status: Available
... [Additional books listed] ...
13. Java: The Complete Reference
Status: Available
Enter book number to return: 1
33
Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow:
Concepts, Tools, and Techniques to Build Intelligent Systems, Third Edition
===== Computer Science Library =====
1. Show All Books
2. Check Out Book
3. Return Book
4. Exit
Enter choice (1-4): 2
1. Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow:
Concepts, Tools, and Techniques to Build Intelligent Systems, Third Edition
Status: Available
2. Data Science From Scratch
Status: Available
... [Additional books listed] ...
Enter book number to check out: 13
Java: The Complete Reference checked out successfully
===== Computer Science Library =====
1. Show All Books
2. Check Out Book
3. Return Book
4. Exit
Enter choice (1-4): 3
Enter book number to return: 2
Data Science From Scratch was not checked out
===== Computer Science Library =====
1. Show All Books
2. Check Out Book
3. Return Book
4. Exit
Enter choice (1-4): 4
Exiting Program....
34
5 Railway management using multilevel inheritance
Write a program in Java for Railway management using Multilevel inheritance with at least 3 classes
all classes must have two-member variable and two -member method.
class RailwayEntity {
protected String name ;
protected String code ;
public Train ( String name , String code , String route , int capacity ) {
super ( name , code ) ;
this . route = route ;
this . capacity = capacity ;
}
35
System . out . println ( " Ticket booked for " + name + " ( " + code + " ) "
);
}
public class R a i l w a y M a n a g e m e n t S y s t e m {
private static final ArrayList < PassengerTrain > trains = new ArrayList
< >() ;
private static final Scanner scanner = new Scanner ( System . in ) ;
trains . add ( new PassengerTrain ( " Superfast " , " SF -456 " ,
" Chennai - Kolkata " , 450 , 18 , " AC , Charging Points " ) ) ;
trains . add ( new PassengerTrain ( " Local Commuter " , " LC -789 " ,
" Bangalore Suburban " , 800 , 15 , " Standard Seating " ) ) ;
while ( true ) {
System . out . println ( " \ n ==== Railway Management System ==== " ) ;
System . out . println ( " 1. View All Trains " ) ;
System . out . println ( " 2. Book Ticket " ) ;
System . out . println ( " 3. Show Train Details " ) ;
System . out . println ( " 4. Exit " ) ;
System . out . print ( " Enter choice (1 -4) : " ) ;
switch ( choice ) {
case 1 -> viewAllTrains () ;
case 2 -> bookTicket () ;
case 3 -> showTrainDetails () ;
case 4 -> {
System . out . println ( " Exiting system . Thank you ! " ) ;
scanner . close () ;
System . exit (0) ;
}
}
}
}
36
for ( int i = 0; i < trains . size () ; i ++) {
System . out . println (( i +1) + " . " + trains . get ( i ) . name + " ( " +
trains . get ( i ) . code + " ) " ) ;
}
}
37
2. Superfast (SF-456)
3. Local Commuter (LC-789)
==== Railway Management System ====
1. View All Trains
2. Book Ticket
3. Show Train Details
4. Exit
Enter choice (1-4): 2
Available Trains:
1. Express 2023 (EXP-2023)
2. Superfast (SF-456)
3. Local Commuter (LC-789)
Select train to book: 1
Ticket booked for Express 2023 (EXP-2023)
==== Railway Management System ====
1. View All Trains
2. Book Ticket
3. Show Train Details
4. Exit
Enter choice (1-4): 3
Available Trains:
1. Express 2023 (EXP-2023)
2. Superfast (SF-456)
3. Local Commuter (LC-789)
Select train to view details: 1
===== Train Details =====
Entity: Express 2023 (Code: EXP-2023)
Capacity: 500 passengers
Amenities: AC, WiFi, Pantry
Route: Mumbai-Delhi
Coaches: 20
==== Railway Management System ====
1. View All Trains
2. Book Ticket
3. Show Train Details
4. Exit
Enter choice (1-4): 4
Exiting system. Thank you!
38
6 Stack
Write a program in Java to implement stack data structure.
39
public int size () {
return top + 1;
}
while ( true ) {
System . out . println ( " \ nStack Operations : " ) ;
System . out . println ( " 1. Push " ) ;
System . out . println ( " 2. Pop " ) ;
System . out . println ( " 3. Peek " ) ;
System . out . println ( " 4. Check if Empty " ) ;
System . out . println ( " 5. Check if Full " ) ;
System . out . println ( " 6. Get Size " ) ;
System . out . println ( " 7. Show all elements " ) ;
System . out . println ( " 8. Exit " ) ;
System . out . println ( " Enter Choice : " ) ;
try {
switch ( choice ) {
case 1 -> {
System . out . print ( " Enter a value to push : " ) ;
int value = sc . nextInt () ;
stack . push ( value ) ;
System . out . println ( " Pushed " + value ) ;
}
case 2 -> System . out . println ( " Popped : " + stack . pop () )
;
case 3 -> System . out . println ( " Top element : " + stack .
peek () ) ;
case 4 -> System . out . println ( " Is stack Empty ?: " +
stack . isEmpty () ) ;
case 5 -> System . out . println ( " Is stack full ?: " +
stack . isFull () ) ;
40
case 6 -> System . out . println ( " Current Size : " + stack .
size () + " \ nCapacity : " + capacity ) ;
case 7 -> stack . displayElements () ;
case 8 -> {
sc . close () ;
System . exit (0) ;
}
default -> System . out . println ( " Invalid Choice ! " ) ;
}
} catch ( E m p ty S t ac k E xc e p ti o n e ) {
System . out . println ( " Error : Stack is empty ! " ) ;
} catch ( S ta ckO ve rf lo wE rr or e ) {
System . out . println ( " Error : Stack is full ! " ) ;
}
}
}
}
41
3. Peek
4. Check if Empty
5. Check if Full
6. Get Size
7. Show all elements
8. Exit
Enter Choice:
1
Enter a value to push: 30
Pushed 30
Stack Operations:
1. Push
2. Pop
3. Peek
4. Check if Empty
5. Check if Full
6. Get Size
7. Show all elements
8. Exit
Enter Choice:
1
Enter a value to push: 40
Error: Stack is full!
Stack Operations:
1. Push
2. Pop
3. Peek
4. Check if Empty
5. Check if Full
6. Get Size
7. Show all elements
8. Exit
Enter Choice:
7
Stack elements (Top to bottom):
30
20
10
Stack Operations:
1. Push
2. Pop
3. Peek
4. Check if Empty
5. Check if Full
6. Get Size
7. Show all elements
8. Exit
Enter Choice:
3
Top element: 30
Stack Operations:
1. Push
2. Pop
3. Peek
42
4. Check if Empty
5. Check if Full
6. Get Size
7. Show all elements
8. Exit
Enter Choice:
2
Popped: 30
Stack Operations:
1. Push
2. Pop
3. Peek
4. Check if Empty
5. Check if Full
6. Get Size
7. Show all elements
8. Exit
Enter Choice:
6
Current Size: 2
Capacity: 3
Stack Operations:
1. Push
2. Pop
3. Peek
4. Check if Empty
5. Check if Full
6. Get Size
7. Show all elements
8. Exit
Enter Choice:
4
Is stack Empty?: false
Stack Operations:
1. Push
2. Pop
3. Peek
4. Check if Empty
5. Check if Full
6. Get Size
7. Show all elements
8. Exit
Enter Choice:
5
Is stack full?: false
Stack Operations:
1. Push
2. Pop
3. Peek
4. Check if Empty
5. Check if Full
6. Get Size
7. Show all elements
8. Exit
Enter Choice:
43
8
44
7 Queue
Write a program in Java to implement queue data structure.
45
public boolean isEmpty () {
return size == 0;
}
while ( true ) {
System . out . println ( " \ nQueue Operations : " ) ;
System . out . println ( " 1. Enqueue " ) ;
System . out . println ( " 2. Dequeue " ) ;
System . out . println ( " 3. Peek " ) ;
System . out . println ( " 4. Check if empty " ) ;
System . out . println ( " 5. Check if full " ) ;
System . out . println ( " 6. Display elements " ) ;
System . out . println ( " 7. Get size " ) ;
System . out . println ( " 8. Exit " ) ;
System . out . print ( " Enter choice : " ) ;
try {
switch ( choice ) {
case 1 -> {
System . out . print ( " Enter value to enqueue : " ) ;
int value = sc . nextInt () ;
queue . enqueue ( value ) ;
System . out . println ( " Enqueued " + value ) ;
}
case 2 -> System . out . println ( " Dequeued : " + queue .
dequeue () ) ;
case 3 -> System . out . println ( " Front element : " + queue
. peek () ) ;
46
case 4 -> System . out . println ( " Queue is empty : " +
queue . isEmpty () ) ;
case 5 -> System . out . println ( " Queue is full : " + queue
. isFull () ) ;
case 6 -> queue . display () ;
case 7 -> System . out . println ( " Current size : " + queue .
getSize () + " \ nCapacity : " + capacity ) ;
case 8 -> {
sc . close () ;
System . exit (0) ;
}
default -> System . out . println ( " Invalid choice ! " ) ;
}
} catch ( Exception e ) {
System . out . println ( " Error : " + e . getMessage () ) ;
}
}
}
47
3. Peek
4. Check if empty
5. Check if full
6. Display elements
7. Get size
8. Exit
Enter choice: 1
Enter value to enqueue: 30
Enqueued 30
Queue Operations:
1. Enqueue
2. Dequeue
3. Peek
4. Check if empty
5. Check if full
6. Display elements
7. Get size
8. Exit
Enter choice: 1
Enter value to enqueue: 40
Error: Queue is full!
Queue Operations:
1. Enqueue
2. Dequeue
3. Peek
4. Check if empty
5. Check if full
6. Display elements
7. Get size
8. Exit
Enter choice: 6
Queue elements:
10 20 30
Queue Operations:
1. Enqueue
2. Dequeue
3. Peek
4. Check if empty
5. Check if full
6. Display elements
7. Get size
8. Exit
Enter choice: 3
Front element: 10
Queue Operations:
1. Enqueue
2. Dequeue
3. Peek
4. Check if empty
5. Check if full
6. Display elements
7. Get size
8. Exit
Enter choice: 2
Dequeued: 10
48
Queue Operations:
1. Enqueue
2. Dequeue
3. Peek
4. Check if empty
5. Check if full
6. Display elements
7. Get size
8. Exit
Enter choice: 7
Current size: 2
Capacity: 3
Queue Operations:
1. Enqueue
2. Dequeue
3. Peek
4. Check if empty
5. Check if full
6. Display elements
7. Get size
8. Exit
Enter choice: 4
Queue is empty: false
Queue Operations:
1. Enqueue
2. Dequeue
3. Peek
4. Check if empty
5. Check if full
6. Display elements
7. Get size
8. Exit
Enter choice: 5
Queue is full: false
Queue Operations:
1. Enqueue
2. Dequeue
3. Peek
4. Check if empty
5. Check if full
6. Display elements
7. Get size
8. Exit
Enter choice: 8
49
8 University admission system using packages
Write a program in Java for University admission system using packages.
public class U n i v e r s i t y A d m i s s i o n S y s t e m {
private static final ArrayList < Course > courses = new ArrayList < >() ;
private static final ArrayList < Applicant > applicants = new ArrayList
< >() ;
private static final Scanner scanner = new Scanner ( System . in ) ;
50
System . out . print ( " Enter choice (1 -5) : " ) ;
switch ( choice ) {
case 1 -> viewCourses () ;
case 2 -> re gister Appli cant () ;
case 3 -> pr ocessA dmiss ions () ;
case 4 -> viewApplicants () ;
case 5 -> {
System . out . println ( " Exiting system ... " ) ;
scanner . close () ;
System . exit (0) ;
}
}
}
}
51
private static void proces sAdmis sions () {
if ( applicants . isEmpty () ) {
System . out . println ( " \ nNo applicants to process ! " ) ;
return ;
}
52
}
}
}
}
8.2.2 com/Unversity/admission/[Link]
package com . University . admission ;
8.2.3 com/Unversity/applicants/[Link]
package com . University . applicants ;
// Getters
public String getApplicantId () { return applicantId ; }
public String getName () { return name ; }
public double getGrade () { return grade ; }
public Course ge tSelec tedCo urse () { return selectedCourse ; }
53
this . selectedCourse = course ;
}
}
8.2.4 com/Unversity/courses/[Link]
package com . University . courses ;
public Course ( String code , String name , int cap , double minGrade ) {
this . courseCode = code ;
this . courseName = name ;
this . capacity = cap ;
this . minGrade = minGrade ;
this . enrolled = 0;
}
54
EE201 - Electrical Engineering (Capacity: 0/40, Minimum Grade: 60%)
MA301 - Mathematics (Capacity: 0/35, Minimum Grade: 60%)
PHY401 - Physics (Capacity: 0/30, Minimum Grade: 60%)
CHEM501 - Chemistry (Capacity: 0/25, Minimum Grade: 60%)
==== University Admission System ====
1. View All Courses
2. Register Applicant
3. Process Admissions
4. View Applicants
5. Exit
Enter choice (1-5): 2
Enter applicant ID: A001
Enter name: Alice
Enter grade: 72.5
Available Courses:
CS101 - Computer Science (Capacity: 0/50, Minimum Grade: 60%)
EE201 - Electrical Engineering (Capacity: 0/40, Minimum Grade: 60%)
MA301 - Mathematics (Capacity: 0/35, Minimum Grade: 60%)
PHY401 - Physics (Capacity: 0/30, Minimum Grade: 60%)
CHEM501 - Chemistry (Capacity: 0/25, Minimum Grade: 60%)
Select course (1-5): 1
Applicant registered!
==== University Admission System ====
1. View All Courses
2. Register Applicant
3. Process Admissions
4. View Applicants
5. Exit
Enter choice (1-5): 2
Enter applicant ID: A002
Enter name: Bob
Enter grade: 58.0
Applicant does not meet minimum grade requirement (60%)
==== University Admission System ====
1. View All Courses
2. Register Applicant
3. Process Admissions
4. View Applicants
5. Exit
Enter choice (1-5): 4
Registered Applicants:
A001 - Alice (Grade: 72.5%) - Applied to: Computer Science
==== University Admission System ====
1. View All Courses
2. Register Applicant
3. Process Admissions
4. View Applicants
5. Exit
Enter choice (1-5): 3
Processed 1 applications
Successful admissions: 1
55
==== University Admission System ====
1. View All Courses
2. Register Applicant
3. Process Admissions
4. View Applicants
5. Exit
Enter choice (1-5): 1
Available Courses:
CS101 - Computer Science (Capacity: 1/50, Minimum Grade: 60%)
EE201 - Electrical Engineering (Capacity: 0/40, Minimum Grade: 60%)
MA301 - Mathematics (Capacity: 0/35, Minimum Grade: 60%)
PHY401 - Physics (Capacity: 0/30, Minimum Grade: 60%)
CHEM501 - Chemistry (Capacity: 0/25, Minimum Grade: 60%)
==== University Admission System ====
1. View All Courses
2. Register Applicant
3. Process Admissions
4. View Applicants
5. Exit
Enter choice (1-5): 5
Exiting system...
56
9 Stack using a package and interface
Write a program in Java to implement stack data structure using package and interface.
while ( true ) {
System . out . println ( " \ nStack Operations : " ) ;
System . out . println ( " 1. Push " ) ;
System . out . println ( " 2. Pop " ) ;
System . out . println ( " 3. Peek " ) ;
System . out . println ( " 4. Check if empty " ) ;
System . out . println ( " 5. Check if full " ) ;
System . out . println ( " 6. Get Size " ) ;
System . out . println ( " 7. Show all elements " ) ;
System . out . println ( " 8. Exit " ) ;
System . out . println ( " Enter Choice : " ) ;
try {
switch ( choice ) {
case 1 -> {
System . out . println ( " Enter value to Push : " ) ;
int value = sc . nextInt () ;
stack . push ( value ) ;
System . out . println ( " Pushed " + value ) ;
}
case 2 -> System . out . println ( " Popped : " + stack . pop () )
;
57
case 3 -> System . out . println ( " Top element : " + stack .
peek () ) ;
case 4 -> System . out . println ( " Stack is empty : " +
stack . isEmpty () ) ;
case 5 -> System . out . println ( " Stack is full : " + stack
. isFull () ) ;
case 6 -> System . out . println ( " Current Size : " + stack .
size () + " \ nCapacity : " + capacity ) ;
case 7 -> stack . displayElements () ;
case 8 -> {
sc . close () ;
System . exit (0) ;
}
default -> System . out . println ( " Invalid choice ! " ) ;
}
} catch ( E m p ty S t ac k E xc e p ti o n | S ta ck Ov er fl ow Err or e ) {
System . out . println ( " Error : " + e . getMessage () ) ;
}
}
}
}
9.2.2 StackPackage/[Link]
package StackPackage ;
@Override
public void push ( int value ) {
if ( isFull () ) {
throw new S ta ckO ve rf lo wE rr or ( " Stack is Full " ) ;
}
stackArray [++ top ] = value ;
}
@Override
58
public int pop () {
if ( isEmpty () ) {
throw new E m p ty S t ac k E xc e p ti o n () ;
}
return stackArray [ top - -];
}
@Override
public int peek () {
if ( isEmpty () ) {
throw new E m p ty S t ac k E xc e p ti o n () ;
}
return stackArray [ top ];
}
@Override
public boolean isEmpty () {
return top == -1;
}
@Override
public boolean isFull () {
return capacity - 1 == top ;
}
@Override
public void displayElements () {
if ( isEmpty () ) {
throw new E m p ty S t ac k E xc e p ti o n () ;
}
System . out . println ( " Stack elements ( Top to bottom ) : " ) ;
for ( int i = top ; i >= 0; i - -) {
System . out . println ( stackArray [ i ] + " " ) ;
}
System . out . println () ;
}
@Override
public int size () {
return top + 1;
}
}
9.2.3 StackPackage/[Link]
package StackPackage ;
public interface StackInterface {
void push ( int value ) ;
int pop () ;
int peek () ;
boolean isEmpty () ;
boolean isFull () ;
59
void displayElements () ;
int size () ;
}
60
3. Peek
4. Check if empty
5. Check if full
6. Get Size
7. Show all elements
8. Exit
Enter Choice:
1
Enter value to Push:
40
Error: Stack is Full
Stack Operations:
1. Push
2. Pop
3. Peek
4. Check if empty
5. Check if full
6. Get Size
7. Show all elements
8. Exit
Enter Choice:
3
Top element: 30
Stack Operations:
1. Push
2. Pop
3. Peek
4. Check if empty
5. Check if full
6. Get Size
7. Show all elements
8. Exit
Enter Choice:
7
Stack elements (Top to bottom):
30
20
10
Stack Operations:
1. Push
2. Pop
3. Peek
4. Check if empty
5. Check if full
6. Get Size
7. Show all elements
8. Exit
Enter Choice:
2
Popped: 30
Stack Operations:
1. Push
2. Pop
3. Peek
4. Check if empty
61
5. Check if full
6. Get Size
7. Show all elements
8. Exit
Enter Choice:
4
Stack is empty: false
Stack Operations:
1. Push
2. Pop
3. Peek
4. Check if empty
5. Check if full
6. Get Size
7. Show all elements
8. Exit
Enter Choice:
8
62
10 Package and interface with inheritance
Write a program in Java to implement package and interface with inheritance.
while ( true ) {
System . out . println ( " \ nAnimal Category Selection : " ) ;
System . out . println ( " 1. Mammals " ) ;
System . out . println ( " 2. Birds " ) ;
System . out . println ( " 3. Reptiles " ) ;
System . out . println ( " 4. Exit " ) ;
System . out . print ( " Enter your choice : " ) ;
if ( choice == 4) {
System . out . println ( " Exiting program ... " ) ;
break ;
}
63
case 1 -> " Enter the mammal name ( e . g . , Tiger , Dog ) : " ;
case 2 -> " Enter the bird name ( e . g . , Peacock , Eagle ) : " ;
case 3 -> " Enter the reptile name ( e . g . , Snake , Lizard ) : "
;
default -> " " ;
};
scanner . close () ;
}
private static void displa yAnima lInfo ( Animal animal , String name ) {
System . out . println ( " \ n " + name + " Characteristics : " ) ;
System . out . println ( " Warm Blooded : " + animal . warmBlooded () ) ;
System . out . println ( " Feeds Milk : " + animal . feedMilk () ) ;
System . out . println ( " Has Fur / Feathers : " + animal . hasFur () ) ;
System . out . println ( " Has Lungs : " + animal . hasLungs () ) ;
System . out . println ( " Four Limb Body Plan : " + animal .
fourLimbBodyPlan () ) ;
System . out . print ( " Movement : " ) ;
animal . move () ;
System . out . print ( " Sound : " ) ;
animal . makeSound () ;
System . out . print ( " Eating : " ) ;
animal . eat () ;
System . out . print ( " Sleeping : " ) ;
animal . sleep () ;
}
}
10.2.2 animalKingdom/[Link]
package animalKingdom ;
64
void move () ;
void makeSound () ;
boolean warmBlooded () ;
boolean feedMilk () ;
boolean hasFur () ;
boolean hasLungs () ;
boolean fourLimbBodyPlan () ;
}
10.2.3 animalKingdom/[Link]
package animalKingdom ;
@Override
public void eat () {
System . out . println ( name + " is pecking food " ) ;
}
@Override
public void sleep () {
System . out . println ( name + " is roosting " ) ;
}
@Override
public void move () {
final Set < String > FLIGHTLESS_BIRDS = Set . of (
" ostriches " , " emus " , " cassowaries " , " rheas " , " kiwis "
);
if ( FLIGHTLESS_BIRDS . contains ( name . toLowerCase () ) ) {
System . out . println ( name + " is walking / running " ) ;
}
else if ( name . equalsIgnoreCase ( " penguin " ) ) {
System . out . println ( name + " is swimming / walking / running " ) ;
}
else {
System . out . println ( name + " is flying " ) ;
}
}
@Override public void makeSound () {
System . out . println ( name + " says : Chirp " ) ;
}
@Override public boolean warmBlooded () {
return true ;
}
@Override public boolean feedMilk () {
return false ;
}
65
@Override public boolean hasFur () {
return false ;
}
}
10.2.4 animalKingdom/[Link]
package animalKingdom ;
@Override
public void eat () {
System . out . println ( name + " is chewing food " ) ;
}
@Override
public void sleep () {
System . out . println ( name + " is sleeping " ) ;
}
@Override
public void move () {
System . out . println ( name + " is walking / running " ) ;
}
@Override
public void makeSound () {
final Set < String > CANINE = Set . of (
" dog " , " wolf " , " jackal " , " fox "
);
if ( CANINE . contains ( name . toLowerCase () ) ) {
System . out . println ( name + " says : Growl / Bark / Howl " ) ;
}
else {
System . out . println ( name + " says : Growl " ) ;
}
@Override
public boolean warmBlooded () {
return true ;
}
@Override
public boolean feedMilk () {
66
return ! name . equalsIgnoreCase ( " platypus " ) && ! name .
equalsIgnoreCase ( " anteater " ) ;
}
@Override
public boolean hasFur () {
return true ;
}
}
10.2.5 animalKingdom/[Link]
package animalKingdom ;
@Override
public void eat () {
System . out . println ( name + " is swallowing food " ) ;
}
@Override
public void sleep () {
System . out . println ( name + " is basking " ) ;
}
@Override
public void move () {
System . out . println ( name + " is crawling " ) ;
}
@Override
public void makeSound () {
System . out . println ( name + " hisses " ) ;
}
@Override
public boolean warmBlooded () {
return false ;
}
@Override
public boolean feedMilk () {
return false ;
}
@Override
public boolean hasFur () {
return false ;
}
}
10.2.6 animalKingdom/[Link]
67
package animalKingdom ;
@Override
public boolean hasLungs () {
return true ;
}
@Override
public boolean fourLimbBodyPlan () {
return true ;
}
}
68
Four Limb Body Plan: true
Movement: Penguin is swimming/walking/running
Sound: Penguin says: Chirp
Eating: Penguin is pecking food
Sleeping: Penguin is roosting
Animal Category Selection:
1. Mammals
2. Birds
3. Reptiles
4. Exit
Enter your choice: 3
Enter the reptile name (e.g., Snake, Lizard): Snake
Snake Characteristics:
Warm Blooded: false
Feeds Milk: false
Has Fur/Feathers: false
Has Lungs: true
Four Limb Body Plan: true
Movement: Snake is crawling
Sound: Snake hisses
Eating: Snake is swallowing food
Sleeping: Snake is basking
Animal Category Selection:
1. Mammals
2. Birds
3. Reptiles
4. Exit
Enter your choice: 4
Exiting program...
69
11 Create your own exception
Write a program in Java to create your own exception.
try {
int choice = sc . nextInt () ;
switch ( choice ) {
case 1:
try {
System . out . print ( " Enter your age : " ) ;
int age = sc . nextInt () ;
validateAge ( age ) ;
System . out . println ( " \ nVoting eligibility
confirmed ! " ) ;
} catch ( I n v al i d Ag e E xc e p ti o n e ) {
System . out . println ( " Error : " + e . getMessage () )
;
} catch ( I n p u t M i s m a t c h E x c e p t i o n e ) {
System . out . println ( " Invalid input ! Please
enter numbers only . " ) ;
sc . nextLine () ;
}
break ;
70
case 2:
sc . close () ;
System . out . println ( " Exiting program ... " ) ;
System . exit (0) ;
default :
System . out . println ( " Invalid choice ! Please enter 1
or 2. " ) ;
}
} catch ( I n p u t M i s m a t c h E x c e p t i o n e ) {
System . out . println ( " Invalid input ! Please enter numbers
only . " ) ;
sc . nextLine () ;
}
}
}
}
71
12 Nested try-catch
Write a program in Java for nested try catch.
while ( running ) {
System . out . println ( " \ n ===== Menu ===== " ) ;
System . out . println ( " 1. Access Array Element " ) ;
System . out . println ( " 2. Exit " ) ;
System . out . print ( " Enter your choice : " ) ;
try {
int choice = sc . nextInt () ;
try {
switch ( choice ) {
case 1 -> {
boolean validIndex = false ;
while (! validIndex ) {
try {
System . out . print ( " Enter array index
(0 -2) : " ) ;
int index = sc . nextInt () ;
try {
System . out . println ( " Value at index
" + index + " : " + marks [ index
]) ;
validIndex = true ;
} catch (
ArrayIndexOutOfBoundsException e) {
System . out . println ( " Level 3 Inner
Catch : Invalid index ! Maximum
index is 2 " ) ;
}
} catch ( I n p u t M i s m a t c h E x c e p t i o n e ) {
System . out . println ( " Level 2 Middle
Catch : Please enter numbers only
for index ! " ) ;
sc . nextLine () ;
}
}
}
case 2 -> {
running = false ;
72
System . out . println ( " Exiting program ... " ) ;
}
default -> System . out . println ( " Invalid menu choice
!");
}
} catch ( Exception e ) {
System . out . println ( " Level 1 Outer Catch : General error
in menu operation " ) ;
}
} catch ( I n p u t M i s m a t c h E x c e p t i o n e ) {
System . out . println ( " Top - level Catch : Invalid input ! Please
enter numbers only for menu choice . " ) ;
sc . nextLine () ; // Clear invalid input
}
}
sc . close () ;
}
}
73
13 Create multiple threads
Write a program in Java to create multiple threads.
Thread 1 is running
Thread 2 is running
Thread 3 is running
Thread 1 completed
Thread 2 completed
Thread 3 completed
74
14 Demonstrate priority assignment to multiple threads
Write a program in Java to demonstrate priority assigning to multiple threads.
@Override
public void run () {
for ( int i = 0; i < iterations ; i ++) {
System . out . println ( this . getName () ) ;
}
}
}
System . out . print ( " Enter number of iterations for all threads : " ) ;
int iterations = sc . nextInt () ;
t1 . start () ;
t2 . start () ;
t3 . start () ;
t4 . start () ;
t5 . start () ;
sc . close () ;
}
}
75
14.2 Program input
76
15 Producer–consumer via inter-thread communication
Write a program in Java to implement producer-consumer program using inter-thread communica-
tion.
@Override
public void run () {
try {
for ( int i = 1; i <= 10; i ++) {
System . out . println ( " Produced : " + i ) ;
sharedQueue . put ( i ) ;
Thread . sleep (100) ;
}
} catch ( I n t e r r u p t e d E x c e p t i o n e ) {
Thread . currentThread () . interrupt () ;
System . out . println ( " Producer Interrupted " ) ;
}
System . out . println ( " Producer finished " ) ;
}
}
@Override
public void run () {
try {
for ( int i = 1; i <= 10; i ++) {
Integer item = sharedQueue . take () ;
System . out . println ( " Consumed : " + item ) ;
Thread . sleep (100) ;
}
} catch ( I n t e r r u p t e d E x c e p t i o n e ) {
Thread . currentThread () . interrupt () ;
System . out . println ( " Consumer interrupted " ) ;
}
77
System . out . println ( " Consumer finished " ) ;
}
}
producerThread . start () ;
consumerThread . start () ;
Produced: 1
Consumed: 1
Produced: 2
Consumed: 2
Produced: 3
Consumed: 3
Produced: 4
Consumed: 4
Produced: 5
Consumed: 5
Produced: 6
Consumed: 6
Produced: 7
Consumed: 7
Produced: 8
Consumed: 8
Produced: 9
Consumed: 9
Produced: 10
Consumed: 10
Producer finished
Consumer finished
All tasks completed
78
16 Banker’s algorithm
Write a program in Java to implement banker-algorithm in order to prevent deadlock.
79
}
// Safety algorithm
int [] work = available . clone () ;
int [] safeSequence = new int [ numProcesses ];
int count = 0;
80
System . out . print ( " P " + safeSequence [ i ]) ;
if ( i != numProcesses -1) System . out . print ( " -> " ) ;
}
System . out . println () ;
}
81
17 Count vowels in a 2–3 line text
Write a program in Java to count the vowels of a 2-to-3-line text.
while ( true ) {
System . out . println ( " \ n ==== Text Analyzer ===== " ) ;
System . out . println ( " 1. Start New Analysis " ) ;
System . out . println ( " 2. Exit " ) ;
System . out . print ( " Enter choice : " ) ;
int lineCount = 0;
int vowelCount = 0;
int characterCount = 0;
while ( true ) {
String line = sc . nextLine () ;
82
for ( int i = 0; i < line . length () ; i ++) {
char c = Character . toLowerCase ( line . charAt ( i ) ) ;
if ( c == ’a ’ || c == ’e ’ || c == ’i ’ || c == ’o ’ || c == ’
u ’) {
vowelCount ++;
}
}
83
18 Copy contents of [Link] to [Link]
Create a file [Link] and copy the content of [Link] to [Link].
String line ;
while (( line = reader . readLine () ) != null ) {
writer . write ( line ) ;
writer . newLine () ; // maintain line breaks
}
System . out . println ( " Content copied to B . txt successfully ! " ) ;
} catch ( F i l e N o t F o u n d E x c e p t i o n e ) {
System . out . println ( " File A . txt not found : " + e . getMessage () ) ;
} catch ( IOException e ) {
System . out . println ( " Error creating B . txt : " + e . getMessage () ) ;
}
}
}
84
Contents of [Link]
Contents of [Link]
85
19 Applet program 1
Write a program in Java to create a banner using Applet.
86
19.2 HTML implementation
< html >
< body >
< applet code = " BannerApplet . class " width = " 400 " height = " 100 " >
</ applet >
</ body >
</ html >
87
20 Native Method
Write a Java Program to write a native method.
20.3 C implementation
20.3.1 NativeMethod/NativeExample.c
# include < stdio .h >
# include < jni .h >
# include " N a t i v e M e t h o d _ N a t i v e E x a m p l e . h " // Generated header
88
Step 1: Java Class Definition
[ NativeMethod / NativeExample . java
This generates the file NativeMethod_NativeExample.h, which defines the native function sig-
nature expected in C.
For Linux:
gcc -I " $JAVA_HOME / include " -I " $JAVA_HOME / include / linux " - fPIC - shared -o
libNativeExample . so NativeExample . c
This confirms the successful invocation of a native method from Java using JNI
89
21 Implement any five functions of String
21.1 Java implementation
import java . util . Scanner ;
90
}
case 5 -> {
System . out . print ( " Enter Original String : " ) ;
String originalString = sc . nextLine () ;
System . out . print ( " Enter characters to replace : " ) ;
String oldChar = sc . nextLine () ;
System . out . print ( " Enter replacement character : " ) ;
String newChar = sc . nextLine () ;
System . out . println ( " Modified String : " +
originalString . replace ( oldChar , newChar ) ) ;
}
case 6 -> System . out . println ( " Exiting Program ... " ) ;
default -> System . out . println ( " Invalid choice ! Please try
again . " ) ;
}
} while ( choice != 6) ;
sc . close () ;
}
}
91
Enter replacement character: @
Modified String: B@n@n@
===== String Operations Menu =====
Enter your choice (1-6): 6
Exiting Program...
92
22 Demonstrate InetAddress
Write a Java Program to demonstrate InetAddress.
93
22.2 Program output
Local Host:
Host Name: DESKTOP-P2NC49C
IP Address: [Link]
Canonical Name: DESKTOP-P2NC49C
Information for [Link]:
IP Address: [Link]
Canonical Name: [Link]
All IP addresses for [Link]:
IP: [Link]
Reverse lookup for [Link]:
Host Name: [Link]
Canonical Name: [Link]
94
23 Demonstrate getPort()
Write a Java Program to demonstrate getPort().
clientSocket . close () ;
serverSocket . close () ;
} catch ( Exception e ) {
e . printStackTrace () ;
}
}
}
23.2.2 portDemo/networking/[Link]
package portDemo . networking ;
95
Socket socket = new Socket ( " localHost " , 12345) ;
System . out . println ( " Connected to Server : " ) ;
System . out . println ( " Server Port : " + socket . getPort () ) ;
System . out . println ( " Client Port : " + socket . getLocalPort () ) ;
socket . close () ;
} catch ( Exception e ) {
e . printStackTrace () ;
}
}
}
C:\Users\Sayan Dutta\IdeaProjects\Java_Assignments_MSc\src\portDemo\
networking>java Server
Server started on port: 12345
C:\Users\Sayan Dutta\IdeaProjects\Java_Assignments_MSc\src\portDemo\
networking>java Client
Connected to Server:
Server Port: 12345
Client Port: 52352
96
24 Demonstrate URL
Write a Java Program to demonstrate URL.
97
25 Demonstrate Datagram
Write a Java Program to demonstrate datagram.
while ( true ) {
// Receive packet from client
DatagramPacket receivePacket = new DatagramPacket (
receiveBuffer , receiveBuffer . length ) ;
socket . receive ( receivePacket ) ;
// Prepare response
InetAddress clientAddress = receivePacket . getAddress () ;
98
}
} catch ( IOException e ) {
e . printStackTrace () ;
} finally {
if ( socket != null && ! socket . isClosed () ) {
socket . close () ;
}
}
}
}
25.2.2 Datagram/[Link]
package Datagram ;
99
receivePacket . getLength ()
);
System . out . println ( " Received from server : " + receivedResponse
);
} catch ( IOException e ) {
e . printStackTrace () ;
} finally {
if ( socket != null && ! socket . isClosed () ) {
socket . close () ;
}
}
}
}
C:\Users\Sayan Dutta\IdeaProjects\Java_Assignments_MSc\src\Datagram>
java [Link]
Server started on port 9876...
C:\Users\Sayan Dutta\IdeaProjects\Java_Assignments_MSc\src\Datagram>
java [Link]
Sent message to server: Hello Server!
Received from server: Message received!
C:\Users\Sayan Dutta\IdeaProjects\Java_Assignments_MSc\src\Datagram>
java [Link]
Server started on port 9876...
Received from Client: Hello Server!
Sent response to client
100
26 Keyboard event listener
Write a Java programme to implement the keyboard event listener.
public K e y b o a r d E v e n t L i s t e n e r () {
// Set up the frame
setTitle ( " Keyboard Event Listener " ) ;
setSize (400 , 300) ;
s e t D e f a u l t C l o s e O p e r a t i o n ( JFrame . EXIT_ON_CLOSE ) ;
setLayout ( new BorderLayout () ) ;
// Create components
label = new JLabel ( " Press any key ... " , JLabel . CENTER ) ;
label . setFont ( new Font ( " Arial " , Font . BOLD , 16) ) ;
101
@Override
public void keyReleased ( KeyEvent e ) {
String message = " Key Released : " + KeyEvent . getKeyText ( e .
getKeyCode () ) ;
label . setText ( message ) ;
textArea . append ( message + " \ n \ n " ) ;
}
@Override
public void keyTyped ( KeyEvent e ) {
String message = " Key Typed : ’" + e . getKeyChar () + " ’" ;
label . setText ( message ) ;
textArea . append ( message + " \ n " ) ;
textArea . append ( " Character : " + e . getKeyChar () + " \ n \ n " ) ;
}
102
27 Mouse event listener
Write a Java program to implement mouse event listener (click, enter, exited, pressed, release).
public Mou se Ev en tL is te ne r () {
setTitle ( " Mouse Event Listener " ) ;
setSize (500 , 400) ;
s e t D e f a u l t C l o s e O p e r a t i o n ( JFrame . EXIT_ON_CLOSE ) ;
setLayout ( new BorderLayout () ) ;
// Create components
statusLabel = new JLabel ( " Mouse status : Waiting for events ... " ,
JLabel . CENTER ) ;
statusLabel . setFont ( new Font ( " Arial " , Font . BOLD , 16) ) ;
statusLabel . setBorder ( BorderFactory . cr eateEm ptyBor der (10 , 10 , 10 ,
10) ) ;
statusLabel . setOpaque ( true ) ;
statusLabel . setBackground ( Color . LIGHT_GRAY ) ;
// Display instructions
eventLog . append ( " Mouse Event Listener Program \ n " ) ;
eventLog . append ( " - - - - - - - - - - - - - - - - - - - - - - - - - - - -\ n " ) ;
eventLog . append ( " Interact with mouse in this window to see events
.\ n " ) ;
eventLog . append ( " Supported events : click , enter , exit , press ,
release \ n \ n " ) ;
}
103
// Implement MouseListener methods
@Override
public void mouseClicked ( MouseEvent e ) {
clickCount ++;
String message = " Mouse Clicked at ( " + e . getX () + " , " + e . getY ()
+ ")";
statusLabel . setText ( message + " - Total clicks : " + clickCount ) ;
eventLog . append ( message + " \ n " ) ;
eventLog . append ( " Click count : " + e . getClickCount () + " \ n " ) ;
eventLog . append ( " Button : " + g et Mo us eB ut to nT ex t ( e . getButton () ) + "
\n");
eventLog . append ( " Modifiers : " + KeyEvent . g et K e yM o d if i e rs T e xt ( e .
getModifiersEx () ) + " \ n \ n " ) ;
}
@Override
public void mouseEntered ( MouseEvent e ) {
statusLabel . setText ( " Mouse Entered component " ) ;
statusLabel . setBackground ( Color . GREEN ) ;
eventLog . append ( " Mouse Entered component at ( " + e . getX () + " , " +
e . getY () + " ) \ n \ n " ) ;
}
@Override
public void mouseExited ( MouseEvent e ) {
statusLabel . setText ( " Mouse Exited component " ) ;
statusLabel . setBackground ( Color . RED ) ;
eventLog . append ( " Mouse Exited component at ( " + e . getX () + " , " +
e . getY () + " ) \ n \ n " ) ;
}
@Override
public void mousePressed ( MouseEvent e ) {
statusLabel . setText ( " Mouse Pressed at ( " + e . getX () + " , " + e .
getY () + " ) " ) ;
eventLog . append ( " Mouse Pressed at ( " + e . getX () + " , " + e . getY ()
+ ")\n");
eventLog . append ( " Button : " + g et Mo us eB ut to nT ex t ( e . getButton () ) + "
\n\n");
}
@Override
public void mouseReleased ( MouseEvent e ) {
statusLabel . setText ( " Mouse Released at ( " + e . getX () + " , " + e .
getY () + " ) " ) ;
eventLog . append ( " Mouse Released at ( " + e . getX () + " , " + e . getY ()
+ ")\n");
eventLog . append ( " Button : " + g et Mo us eB ut to nT ex t ( e . getButton () ) + "
\n\n");
}
104
switch ( button ) {
case MouseEvent . BUTTON1 : return " Left Button " ;
case MouseEvent . BUTTON2 : return " Middle Button " ;
case MouseEvent . BUTTON3 : return " Right Button " ;
default : return " Unknown Button " ;
}
}
105
28 Applet programme 2
Write a Java program to create a child frame window from within an applet.
106
28.3 Program output
107
29 Applet programme 3
Write a Java program to create a night view of the sky using applet.
108
29.3 Program output
109
30 Applet programme 4
Write a Java program to create a sand clock using applet.
@Override
public void init () {
setSize (300 , 500) ;
// initialize grains at random positions inside the upper triangle
for ( int i = 0; i < NUM_GRAINS ; i ++) {
spawnGrainAtTop ( i ) ;
hasFallen [ i ] = false ;
}
}
@Override
public void start () {
animator = new Thread ( this ) ;
animator . start () ;
}
@Override
public void stop () {
animator = null ;
}
@Override
110
public void run () {
while ( Thread . currentThread () == animator ) {
for ( int i = 0; i < NUM_GRAINS ; i ++) {
if (! hasFallen [ i ]) {
grainY [ i ]++;
if ( grainY [ i ] > 450) {
hasFallen [ i ] = true ;
fallenCount ++;
}
}
}
repaint () ;
// stop when all grains have fallen
if ( fallenCount >= NUM_GRAINS ) {
stop () ;
break ;
}
try {
Thread . sleep (50) ;
} catch ( I n t e r r u p t e d E x c e p t i o n e ) {
break ;
}
}
}
@Override
public void paint ( Graphics g ) {
// Clear background
g . setColor ( Color . WHITE ) ;
g . fillRect (0 , 0 , getWidth () , getHeight () ) ;
111
x = Math . max ( xLeft , Math . min (x , xRight ) ) ;
} else {
float frac = ( float ) (450 - y ) / 200;
int xLeft = 100 + ( int ) (50 * frac ) ;
int xRight = 200 - ( int ) (50 * frac ) ;
x = Math . max ( xLeft , Math . min (x , xRight ) ) ;
}
g . fillOval ( x - 3 , y - 3 , 6 , 6) ;
}
}
}
}
112
31 Bouncing balls
Write a Java program to bounce more than one ball.
public BouncingBalls () {
// Create 10 random balls
for ( int i = 0; i < 10; i ++) {
balls . add ( createRandomBall () ) ;
}
// Animation timer
Timer timer = new Timer (20 , new ActionListener () {
@Override
public void actionPerformed ( ActionEvent e ) {
updateBalls () ;
repaint () ;
}
}) ;
timer . start () ;
113
getRandomColor () ,
random . nextInt (10) - 5 ,
random . nextInt (10) - 5) ;
}
@Override
protected void paintComponent ( Graphics g ) {
super . paintComponent ( g ) ;
for ( Ball ball : balls ) {
ball . draw ( g ) ;
}
}
public Ball ( int x , int y , int size , Color color , int dx , int dy ) {
this . x = x ;
this . y = y ;
this . size = size ;
this . color = color ;
this . dx = dx ;
this . dy = dy ;
}
114
public void draw ( Graphics g ) {
g . setColor ( color ) ;
g . fillOval (x , y , size , size ) ;
g . setColor ( Color . BLACK ) ;
g . drawOval (x , y , size , size ) ;
}
}
115
32 Digital clock
Write a Java program to create a digital clock.
public DigitalClock () {
// Set up the frame
setTitle ( " Digital Clock " ) ;
setSize (400 , 200) ;
s e t D e f a u l t C l o s e O p e r a t i o n ( JFrame . EXIT_ON_CLOSE ) ;
setLayout ( new BorderLayout () ) ;
setResizable ( false ) ;
116
Timer timer = new Timer (1000 , e -> updateTime () ) ;
timer . start () ;
// Update date
String date = java . time . LocalDate . now () . format ( DateTi meForm atter .
ofPattern ( " EEEE , MMMM dd , yyyy " ) ) ;
dateLabel . setText ( date ) ;
}
117
33 Analog clock
Write a Java program to create a digital clock.
public AnalogClock () {
// Set up the panel
setPreferredSize ( new Dimension (400 , 450) ) ;
setBackground ( Color . WHITE ) ;
@Override
protected void paintComponent ( Graphics g ) {
super . paintComponent ( g ) ;
Graphics2D g2d = ( Graphics2D ) g ;
g2d . setRenderingHint ( RenderingHints . KEY_ANTIALIASING ,
RenderingHints . VA LUE _A NT IA LI AS _O N ) ;
118
clockRadius = Math . min ( centerX , centerY ) - 20;
119
private void drawClockHands ( Graphics2D g2d ) {
int hours = currentTime . getHour () % 12;
int minutes = currentTime . getMinute () ;
int seconds = currentTime . getSecond () ;
120
g2d . drawString ( time , centerX - timeWidth /2 , centerY + clockRadius
+ 40) ;
121
34 India’s Flag
Write a Java programme to create India’s flag.
public IndianFlag () {
setTitle ( " Indian National Flag " ) ;
setSize (600 , 400) ;
s e t D e f a u l t C l o s e O p e r a t i o n ( JFrame . EXIT_ON_CLOSE ) ;
s e t L o c a t i o n R e l a t i v e T o ( null ) ;
add ( new FlagPanel () ) ;
}
122
g2d . fillRect (90 , 350 , 30 , 20) ;
}
123
double angle = Math . toRadians ( i * angleIncrement - 90) ; //
-90 to start at top
124
35 Ashok Chakra
Write a Java programme to create Ashok Chakra.
public AshokChakra () {
setTitle ( " Ashok Chakra " ) ;
setSize (400 , 400) ;
s e t D e f a u l t C l o s e O p e r a t i o n ( JFrame . EXIT_ON_CLOSE ) ;
s e t L o c a t i o n R e l a t i v e T o ( null ) ;
add ( new ChakraPanel () ) ;
}
125
// Calculate endpoint on outer circle
int x = centerX + ( int ) ( radius * Math . cos ( angle ) ) ;
int y = centerY + ( int ) ( radius * Math . sin ( angle ) ) ;
// Add label
g2d . setColor ( Color . BLACK ) ;
g2d . setFont ( new Font ( " Arial " , Font . BOLD , 16) ) ;
String label = " Ashok Chakra (24 Spokes ) " ;
int labelWidth = g2d . getFontMetrics () . stringWidth ( label ) ;
g2d . drawString ( label , centerX - labelWidth /2 , centerY + radius
+ 30) ;
}
}
126
36 Concentric circles
Write a Java programme to create concentric circles in different colours.
@Override
protected void paintComponent ( Graphics g ) {
super . paintComponent ( g ) ;
Graphics2D g2d = ( Graphics2D ) g ;
g2d . setRenderingHint ( RenderingHints . KEY_ANTIALIASING ,
RenderingHints . VA LU E_A NT IA LI AS _O N ) ;
127
// Draw filled circle
g2d . fill ( new Ellipse2D . Double (
centerX - radius ,
centerY - radius ,
diameter ,
diameter ) ) ;
// Draw outline
g2d . setColor ( Color . BLACK ) ;
g2d . setStroke ( new BasicStroke (2) ) ;
g2d . draw ( new Ellipse2D . Double (
centerX - radius ,
centerY - radius ,
diameter ,
diameter ) ) ;
128
37 Shapes
Write a Java programme to create different shapes.
public ShapeDrawing () {
setTitle ( " Basic Shapes Drawing " ) ;
setSize (600 , 400) ;
s e t D e f a u l t C l o s e O p e r a t i o n ( JFrame . EXIT_ON_CLOSE ) ;
s e t L o c a t i o n R e l a t i v e T o ( null ) ;
add ( new ShapesPanel () ) ;
}
129
int centerX = 300;
int centerY = 250;
int radius = 70;
130
38 Text fonts
Write a Java program to display the fonts of a text.
131
39 Positioned Text
Write a Java program to display a text in a specific location on window.
132
40 Demonstrate labels
Write a Java program to demonstrate labels.
public LabelDemo ()
{
// Memory Allocated to frame
frame = new Frame ( " AWT Label " ) ;
// Register ActionListener
button . ad dActio nListe ner ( this ) ;
// Dimensions of Frame
frame . setSize (600 , 600) ;
frame . setVisible ( true ) ;
133
String str ;
if ( count % 2 == 0)
str = count + " is Even " ;
else
str = count + " is odd " ;
134
41 Demonstrate buttons
Write a Java program to demonstrate buttons.
JLabel label = new JLabel ( " Click the button below ! " ) ;
JButton button = new JButton ( " Click Me " ) ;
135
42 Checkbox
Write a Java programme to demonstrate checkbox.
136
42.2 Program output
137
43 Checkbox group
Write a Java program to demonstrate checkbox group.
// Create checkboxes
option1 = new JCheckBox ( " Option 1 " ) ;
option2 = new JCheckBox ( " Option 2 " ) ;
option3 = new JCheckBox ( " Option 3 " ) ;
// Submit button
submitButton = new JButton ( " Submit " ) ;
submitButton . a ddActi onList ener ( this ) ;
add ( submitButton ) ;
@Override
public void actionPerformed ( ActionEvent e ) {
StringBuilder selectedOptions = new StringBuilder ( " Selected : " ) ;
138
if ( option2 . isSelected () ) {
selectedOptions . append ( " Option 2 " ) ;
anySelected = true ;
}
if ( option3 . isSelected () ) {
selectedOptions . append ( " Option 3 " ) ;
anySelected = true ;
}
if (! anySelected ) {
selectedOptions . append ( " None " ) ;
}
139
44 List
Write a Java program to demonstrate list.
140
44.2 Program output
141
45 Scroll bar
Write a Java program to demonstrate handling a scroll bar.
142
45.2 Program output
143
46 Calculator
Write a Java program to create a calculator.
public SimpleCalculator () {
setTitle ( " Simple Calculator " ) ;
setSize (300 , 400) ;
s e t D e f a u l t C l o s e O p e r a t i o n ( EXIT_ON_CLOSE ) ;
s e t L o c a t i o n R e l a t i v e T o ( null ) ;
setLayout ( new BorderLayout () ) ;
@Override
public void actionPerformed ( ActionEvent e ) {
String cmd = e . getActionCommand () ;
144
if ( Character . isDigit ( cmd . charAt (0) ) ) {
if ( operation . isEmpty () ) {
// Entering first number
if ( startNewNumber ) {
display . setText ( " " ) ;
startNewNumber = false ;
}
display . setText ( display . getText () + cmd ) ;
} else {
// Entering second number
secondInput += cmd ;
display . setText ( firstNumber + " " + operation + " " +
secondInput ) ;
}
} else { // Operators : + - * /
if (! display . getText () . isEmpty () ) {
try {
firstNumber = Double . parseDouble ( display . getText () ) ;
operation = cmd ;
startNewNumber = false ;
} catch ( N u m b e r F o r m a t E x c e p t i o n ignored ) {
}
}
145
}
}
146
47 Menu bar
Write a Java program to demonstrate menu bar.
public MenuBarDemo () {
setTitle ( " Menu Bar Demonstration " ) ;
setSize (400 , 300) ;
s e t D e f a u l t C l o s e O p e r a t i o n ( JFrame . EXIT_ON_CLOSE ) ;
s e t L o c a t i o n R e l a t i v e T o ( null ) ;
147
// Create Help menu
JMenu helpMenu = new JMenu ( " Help " ) ;
JMenuItem aboutItem = new JMenuItem ( " About " ) ;
helpMenu . add ( aboutItem ) ;
148
47.2 Program output
⇒ ⇒
149
48 Image display
Write a Java program to display an image.
try {
// Load the original image
BufferedImage originalImage = ImageIO . read ( new File ( imagePath )
);
} catch ( IOException e ) {
JOptionPane . sho wMessa geDial og ( this , " Error loading image : " +
e . getMessage () ,
" Error " , JOptionPane . ERROR_MESSAGE ) ;
System . exit (1) ;
150
}
}
151
49 Sound effect
Write a Java program to demonstrate sound effect.
public SimpleBeepDemo () {
setTitle ( " Simple Beep Demo " ) ;
setSize (300 , 150) ;
s e t D e f a u l t C l o s e O p e r a t i o n ( EXIT_ON_CLOSE ) ;
setLayout ( new FlowLayout () ) ;
sdl . drain () ;
sdl . stop () ;
sdl . close () ;
} catch ( Exception e ) {
152
e . printStackTrace () ;
}
}
153
50 Multiple exception
Write a Java Program for multiple exception in a single code.
public class M u l t i p l e E x c e p t i o n D e m o {
try {
// Example 1: A ri t h me t i cE x c ep t i on ( division by zero )
System . out . print ( " Enter numerator : " ) ;
int numerator = scanner . nextInt () ;
System . out . print ( " Enter denominator : " ) ;
int denominator = scanner . nextInt () ;
// Example 2: A r r a y I n d e x O u t O f B o u n d s E x c e p t i o n
System . out . print ( " Enter array index to access (0 -4) : " ) ;
int index = scanner . nextInt () ;
int [] numbers = {10 , 20 , 30 , 40 , 50};
System . out . println ( " Value at index " + index + " : " + numbers [
index ]) ;
// Example 3: F i l e N o t F o u n d E x c e p t i o n
System . out . print ( " Enter file name to read : " ) ;
String fileName = scanner . next () ;
readFile ( fileName ) ;
// Example 4: N u m b e r F o r m a t E x c e p t i o n
System . out . print ( " Enter a number as string to parse : " ) ;
String numberStr = scanner . next () ;
int parsedNumber = Integer . parseInt ( numberStr ) ;
System . out . println ( " Parsed number : " + parsedNumber ) ;
} catch ( A r i th m e ti c E xc e p ti o n e ) {
System . out . println ( " Error : Cannot divide by zero ! " ) ;
} catch ( A r r a y I n d e x O u t O f B o u n d s E x c e p t i o n e ) {
System . out . println ( " Error : Array index out of bounds ! " ) ;
} catch ( F i l e N o t F o u n d E x c e p t i o n e ) {
System . out . println ( " Error : File not found ! " ) ;
} catch ( N u m b e r F o r m a t E x c e p t i o n e ) {
System . out . println ( " Error : Invalid number format ! " ) ;
} catch ( I n p u t M i s m a t c h E x c e p t i o n e ) {
154
System . out . println ( " Error : Invalid input type ! " ) ;
} finally {
System . out . println ( " \ nThis block always executes ( cleanup code
)");
scanner . close () ;
}
Enter numerator: 10
Enter denominator: 0
Error: Cannot divide by zero!
This block always executes (cleanup code)
Program continues after exception handling...
Enter numerator: 15
Enter denominator: 3
Division result: 5
Enter array index to access (0-4): 7
Error: Array index out of bounds!
This block always executes (cleanup code)
Program continues after exception handling...
155
50.2.3 Output 3: NumberFormatException
Enter numerator: 12
Enter denominator: 4
Division result: 3
Enter array index to access (0-4): 2
Value at index 2: 30
Enter a number as string to parse: hello
Error: Invalid number format!
This block always executes (cleanup code)
Program continues after exception handling...
156