Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

FAADIL_JAVA_LAB

Download as pdf or txt
Download as pdf or txt
You are on page 1of 70

B.M.S.

COLLEGE OF ENGINEERING
(Autonomous college under VTU)
Bull Temple Rd, Basavanagudi, Bengaluru, Karnataka 560019
2023-2025
Department of Computer Applications

Report is submitted for fulfillment of Lab Task in the subject

“JAVA PROGRAMMING”
(22MCA1PCJP)
By

Faadil Khaleel
(1BM23MC032)

Under the Guidance

Prof. R.V. Raghavendra Rao


(Assistant Professor)
B. M. S. COLLEGE OF ENGINEERING, BANGALORE – 19
(Autonomous Institute, Affiliated to VTU)
Department of Computer Applications
(Accredited by NBA for 5 years 2019-2024)

LABORATORY CERTIFICATE

This is to certify that Faadil Khaleel (1BM23MC032) has satisfactorily Completed the
course of practical in “Java Programming - 22MCA2PCJP” Laboratory prescribed
by BMS College of Engineering (Autonomous college under VTU) 2nd Semester MCA
Course in this college during the year 2023-2024.

Signature of Batch Incharge Signature of HoD


Dr. K. Vijayakumar Dr. Ch. Ram Mohan Reddy

Examiner:
CONTENTS

SL. Programs Page No.


No.

1. a). Write a JAVA program to display default value of all primitive data type 5
of JAVA
b). Write a java program that display the roots of a quadratic equation
ax2+bx=0. Calculate the discriminate D and basing on value of D, describe
the nature of root.
c). Five Bikers Compete in a race such that they drive at a constant speed
which may or may not be the same as the other. To qualify the race, the speed
of a racer must be more than the average speed of all 5 racers. Take as input
the speed of each racer and print back the speed of qualifying racers.
d) Write a case study on public static void main (250 words)

2. a). Write a program to create a class named shape. In this class we have three 11
sub classes circle, triangle and square each class has two-member function
named draw () and erase (). Create these using polymorphism concepts.
b). Write a program to create a room class, the attributes of this class is room
no, room type, room area and AC machine. In this class the member functions
are set data and display data.

3. a). Write a program to create interface A in this interface we have two method 15
meth1 and meth2. Implements this interface in another class named My Class.
b). Write a program to create interface named test. In this interface the
member function is square. Implement this interface in arithmetic class.
Create one new class called ToTestInt in this class use the object of arithmetic
class.
c). Create an outer class with a function display, again create another class
inside the outer class named inner with a function called display and call the
two functions in the main class.

4. a). Write a JAVA program that creates threads by extending Thread class. 20
First thread display “Good Morning” every 1 sec, the second thread displays
“Hello” every 2 seconds and the third display “Welcome” every 3 seconds
(Repeat the same by implementing Runnable)
b). Write a program illustrating isAlive and join ()

5. a). Write a Java program to perform employee payroll processing using 26


packages. In the java file, Emp.java creates a package employee and creates a
class Emp. Declare the variables name,empid, category, bpay, hra, da, npay,
pf, grosspay, incometax, and allowance. Calculate the values in methods.
Create another java file Emppay.java. Create an object e to call the methods to
perform and print values.
b). Write a Package MCA which has one class Student. Accept student detail
through parameterized constructor. Write display () method to display details.
Create a main class which will use package and calculate total marks and
percentage.
6. a). Write a complex program to illustrate how the thread priorities? Imagine 32
that the first thread has just begun to run, even before it has a chance to do
anything. Now comes the higher priority thread that wants to run as well.
Now the higher priority thread has to do its work before the first thread starts.
b). Write a Java program that implements producer consumer problem using
the concept of inter thread communication.

7. a). Write a program to create a text file in the path c:\java\abc.txt and check 39
whether that file is exists. Using the command exists(), isDirectory(), isFile(),
getName() and getAbsolutePath().
b) Write a program to rename the given file, after renaming the file delete the
renamed file. (Accept the file name using command line arguments.)
c) Write a program to create a directory and check whether the directory is
created.

8. a). Write a program that can read a host name and convert it to an IP address 44
b). Write a Socket base java server program that responds to client messages
as follows: When it receives a message from client, it simply converts the
message into all uppercase letters and sends back to the client. Write both
client and server programs demonstrating this.

9. a). Create the classes required to store data regarding different types of 48
courses that employees in a company can enroll for. All courses have name
and course fee. Courses are also either classroom delivered or delivered
online. Courses could also be full time or part time. The program must enable
the course coordinator to register employees for courses and list out
employees registered for specific courses.
b). Write a java program in to create a class Worker. Write classes Daily
Worker and SalariedWorker that inherit from Worker. Every worker has a
name and a salaryrate. Write method Pay (int hours) to compute the week pay
of every worker. A Daily worker is paid on the basis of the number of days
she/he works. The salaried worker gets paid the wage for 40 hours a week no
matter what the actual hours are. Test this program to calculate the pay of
workers.

10. a).Write a JAVA program to paint like paint brush in applet. 58


b) Write a JAVA program to display analog clock using Applet.
c). Write a JAVA program to create different shapes and fill colors using
Applet.

11. a).Write a JAVA program to build a Calculator in Swings 65


b). Write a JAVA program to display the digital watch using swings.
22MCA2PCJP: Java Programming

1.a)Write a JAVA program to display default value of all primitive data type of JAVA

public class primDataType{


static boolean a;
static int b;
static long c;
static byte d;
static short e;
static char f;
static float g;
static double h;

public static void main(String[] args){


System.out.println("Default value of boolean is"+ a);
System.out.println("Default value of int is"+ b);
System.out.println("Default value of long is"+ c);
System.out.println("Default value of byte is"+ d);
System.out.println("Default value of short is"+ e);
System.out.println("Default value of char is"+ f);
System.out.println("Default value of float is"+ g);
System.out.println("Default value of double is"+ h);
}
}

OutPut:

Department of Computer Applications, BMSCE 5


22MCA2PCJP: Java Programming

b.)Write a java program that display the roots of a quadratic equation ax2+bx=0. Calculate the discriminate D
and basing on value of D, describe the nature of root.

import java.util.Scanner;
class quadraticEquation{
public static void solve(double a, double b, double c) { double d = b * b - 4 * a * c;
if (d > 0) {
double root1 = (-b + Math.sqrt(d)) / (2 * a);
double root2 = (-b - Math.sqrt(d)) / (2 * a);
System.out.println("The roots are real and distinct."); System.out.println("Root 1 = " + root1);
System.out.println("Root 2 = " + root2);
} else if (d == 0) {
double root = -b / (2 * a);
System.out.println("The root is real (equal roots).");
System.out.println("Root = " + root);
} else {
System.out.println("The roots are complex .");
double realPart = -b / (2 * a);
double imaginaryPart = Math.sqrt(-d) / (2 * a);
System.out.println("Root 1 = " + realPart + " + " + imaginaryPart + "i"); System.out.println("Root 2 = " +
realPart + " - " + imaginaryPart + "i"); }
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the value of coefficient a:");
double a = scanner.nextDouble();
System.out.println("Enter the value of coefficient b:");
double b = scanner.nextDouble();
System.out.println("Enter the value of coefficient c:");
double c = scanner.nextDouble();
solve(a, b, c);
}
}

outPut:

Department of Computer Applications, BMSCE 6


22MCA2PCJP: Java Programming

Department of Computer Applications, BMSCE 7


22MCA2PCJP: Java Programming

1.c)Five Bikers Compete in a race such that they drive at a constant speed which may or may not be the same
as the other. To qualify the race, the speed of a racer must be more than the average speed of all 5 racers. Take
as input the speed of each racer and print back the speed of qualifying racers.

import java.util.Scanner;
class Bikers
{
public static void main(String args[ ])
{
float S1,S2,S3,S4,S5;
float AvgSpeed;
Scanner sc = new Scanner(System.in);
System.out.println(" Enter Speed of five Bike Racer");
S1 = sc.nextInt();
S2 = sc.nextInt();
S3 = sc.nextInt();
S4 = sc.nextInt();
S5 = sc.nextInt();
AvgSpeed=(S1+S2+S2+S3+S4+S5)/5;
if( S1>AvgSpeed)
System.out.println("The Speed of Qualifying Racer is"+S1);
if( S2>AvgSpeed)
System.out.println(" The Speed of Qualifying Racer is"+S2);
if( S3>AvgSpeed)
System.out.println(" The Speed of Qualifying Racer is"+S3);
if( S4>AvgSpeed)
System.out.println(" The Speed of Qualifying Racer is"+S4);
if( S5>AvgSpeed)
System.out.println(" The Speed of Qualifying Racer is"+S5);
}
}

Department of Computer Applications, BMSCE 8


22MCA2PCJP: Java Programming

OutPut:

Department of Computer Applications, BMSCE 9


22MCA2PCJP: Java Programming

d) Write a case study on public static void main(250 words)

In Java, the public static void main method is the entry point of a Java program. It is the starting point
where the program begins execution. In this case study, we will explore the significance of public
static void main and its role in Java programming.

What is public static void main?


public static void main is a special method in Java that is used to define the entry point of a Java
program. It is declared as public to make it accessible from outside the class, static to allow it to be
called without creating an instance of the class, and void to indicate that it does not return any value.

Why is public static void main necessary?


public static void main is necessary because it provides a single entry point for the Java Virtual
Machine (JVM) to start executing the program. Without it, the JVM would not know where to begin
executing the program.

How does public static void main work?


When a Java program is executed, the JVM searches for the public static void main method in the
main class. Once found, the JVM calls this method, passing in an array of strings as arguments. The
main method then executes the code inside it, which typically includes creating objects, calling
methods, and performing other operations.

Best Practices
When writing a public static void main method, it is essential to follow best practices to ensure that
the program is executed correctly. These include:
• Declaring the method as public and static to make it accessible from outside the class.
• Using the void return type to indicate that the method does not return any value.
• Providing a clear and concise name for the method, such as main.
• Keeping the method short and focused on initializing the program.

Conclusion
In conclusion, public static void main is a critical component of Java programming, providing a single
entry point for the JVM to start executing the program. By following best practices and understanding
the role of public static void main, developers can write efficient and effective Java programs.

Department of Computer Applications, BMSCE 10


22MCA2PCJP: Java Programming

2.a)Write a program to create a class named shape. In this class we have three sub classes circle, triangle and
square each class has two member function named draw () and erase (). Create these using polymorphism
concepts.

class shape{
void draw(){
System.out.println("Drawing Shape");
}

void erase(){
System.out.println("erasing Shape");
}
}

class Circle extends shape{


void draw(){
System.out.println("Drawing Circle");
}

void erase(){
System.out.println("erasing Circle");
}
}

class Triangle extends shape{


void draw(){
System.out.println("Drawing Triangle");
}

void erase(){
System.out.println("erasing Triangle");
}
}
class Square extends shape{

Department of Computer Applications, BMSCE 11


22MCA2PCJP: Java Programming

void draw(){
System.out.println("Drawing Square");
}

void erase(){
System.out.println("erasing Square");
}
}

class shapemain{
public static void main(String args[]){
shape c=new Circle();
shape t=new Triangle();
shape s=new Square();
c.draw();
c.erase();
t.draw();
t.erase();
s.draw();
s.erase();
}
}

Output:

Department of Computer Applications, BMSCE 12


22MCA2PCJP: Java Programming

2.b)Write a program to create a room class, the attributes of this class is roomno, roomtype, roomarea and AC
machine. In this class the member functions are setdata and displaydata.

class Room {
int roomno;
String roomtype;
double roomarea;
boolean hasAC;

public void setdata(int roomno, String roomtype, double roomarea, boolean hasAC) {
this.roomno = roomno;
this.roomtype = roomtype;
this.roomarea = roomarea;
this.hasAC = hasAC;
}

public void displaydata() {


System.out.println("Room Number: " + roomno);
System.out.println("Room Type: " + roomtype);
System.out.println("Room Area: " + roomarea + " sq.ft");
System.out.println("Has AC: " + (hasAC ? "Yes" : "No"));
}
}

public class roomDetails {


public static void main(String[] args) {

Room room1 = new Room();


room1.setdata(101, "Regular", 300, false);
System.out.println("Details of Room 1:");
room1.displaydata();
room1.setdata(102, "Premium Deluxe", 400, true);
System.out.println("\nUpdated Details of Room 1:");
Department of Computer Applications, BMSCE 13
22MCA2PCJP: Java Programming

room1.displaydata();
}
}

Output:

Department of Computer Applications, BMSCE 14


22MCA2PCJP: Java Programming

3.a)Write a program to create interface A in this interface we have two method meth1 and meth2. Implements
this interface in another class named MyClass.

interface interfaceA{
void meth1();
void meth2();
}

class MyClass implements interfaceA{

public void meth1(){


System.out.println("Implement meth1()");
}
public void meth2(){
System.out.println("Implement meth2()");
}

public class InterfaceMain{


public static void main(String args[]){
MyClass cl = new MyClass();
cl.meth1();
cl.meth2();
}
}

OutPut:

Department of Computer Applications, BMSCE 15


22MCA2PCJP: Java Programming

Department of Computer Applications, BMSCE 16


22MCA2PCJP: Java Programming

3 b)Write a program to create interface named test. In this interface the member function is square. Implement
this interface in arithmetic class. Create one new class called ToTestInt in this class use the object of arithmetic
class.c). Create an outer class with a function display, again create another class inside the outer class named
inner with a function called display and call the two functions in the main class.

import java.util.Scanner;
interface Test {
int square(int num);
}

class Arithmetic implements Test {


public int square(int num) {
return num * num;
}
}

class ToTestInt {
Arithmetic arithmetic = new Arithmetic();

public void testSquare(int num) {


int result = arithmetic.square(num);
System.out.println("Square of " + num + " is: " + result);
}
}

class Outer {
void display() {
System.out.println("Outer display method");
class Inner {
void display() {
System.out.println("Inner display method");
}
}
Inner inner = new Inner();
Department of Computer Applications, BMSCE 17
22MCA2PCJP: Java Programming

inner.display();
}
}

public class testCase {


public static void main(String[] args) {
int n;
ToTestInt test = new ToTestInt();
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number to be squared");
n = sc.nextInt();
test.testSquare(n);
System.out.println();
Outer outer = new Outer();
outer.display();
}
}

OutPut:

Department of Computer Applications, BMSCE 18


22MCA2PCJP: Java Programming

3.c). Create an outer class with a function display, again create another class inside the outer class
named inner with a function called display and call the two functions in the main class.

class Outer {
void display() {
System.out.println("Outer class display method");
}
class Inner {
void display() {
System.out.println("Inner class display method");
}
}
}
public class innerouter {
public static void main(String[] args) {
Outer outer = new Outer();
outer.display();
Outer.Inner inner = outer.new Inner();
inner.display();
}
}

Department of Computer Applications, BMSCE 19


22MCA2PCJP: Java Programming

4.a)Write a JAVA program that creates threads by extending Thread class .First thread display “Good Morning
“every 1 sec, the second thread displays “Hello “every 2 seconds and the third display “Welcome” every 3
seconds ,(Repeat the same by implementing Runnable)

class GoodMorningThread extends Thread {


public void run() {
try {
while (true) {
System.out.println("Good Morning");
Thread.sleep(1000); // Sleep for 1 second
}
} catch (InterruptedException e) {
System.out.println(e);
}
}
}

class HelloThread extends Thread {


public void run() {
try {
while (true) {
System.out.println("Hello");
Thread.sleep(2000); // Sleep for 2 seconds
}
} catch (InterruptedException e) {
System.out.println(e);
}
}
}

class WelcomeThread extends Thread {


public void run() {
try {
while (true) {

Department of Computer Applications, BMSCE 20


22MCA2PCJP: Java Programming

System.out.println("Welcome");
Thread.sleep(3000); // Sleep for 3 seconds
}
} catch (InterruptedException e) {
System.out.println(e);
}
}
}

public class ThreadsDemo {


public static void main(String[] args) {
GoodMorningThread t1 = new GoodMorningThread();
HelloThread t2 = new HelloThread();
WelcomeThread t3 = new WelcomeThread();

t1.start();
t2.start();
t3.start();
}
}

Using Runnable Interface:

class GoodMorningRunnable implements Runnable {


public void run() {
try {
while (true) {
System.out.println("Good Morning");
Thread.sleep(1000); // Sleep for 1 second
}
} catch (InterruptedException e) {
System.out.println(e);
}

Department of Computer Applications, BMSCE 21


22MCA2PCJP: Java Programming

}
}

class HelloRunnable implements Runnable {


public void run() {
try {
while (true) {
System.out.println("Hello");
Thread.sleep(2000); // Sleep for 2 seconds
}
} catch (InterruptedException e) {
System.out.println(e);
}
}
}

class WelcomeRunnable implements Runnable {


public void run() {
try {
while (true) {
System.out.println("Welcome");
Thread.sleep(3000); // Sleep for 3 seconds
}
} catch (InterruptedException e) {
System.out.println(e);
}
}
}

public class threadsRunnable {


public static void main(String[] args) {
Thread t1 = new Thread(new GoodMorningRunnable());
Thread t2 = new Thread(new HelloRunnable());
Thread t3 = new Thread(new WelcomeRunnable());

Department of Computer Applications, BMSCE 22


22MCA2PCJP: Java Programming

t1.start();
t2.start();
t3.start();
}
}

OutPut:

Department of Computer Applications, BMSCE 23


22MCA2PCJP: Java Programming

4.b). Write a program illustrating isAlive and join ()

class PrintNumbers extends Thread {


public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(i);
try {
Thread.sleep(500); // Sleep for 0.5 seconds
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}

public class threadMain {


public static void main(String[] args) {
PrintNumbers t1 = new PrintNumbers();
PrintNumbers t2 = new PrintNumbers();

t1.start();
t2.start();

System.out.println("Thread 1 is alive: " + t1.isAlive());


System.out.println("Thread 2 is alive: " + t2.isAlive());

try {
t1.join(); // Main thread waits for t1 to finish
t2.join(); // Main thread waits for t2 to finish
} catch (InterruptedException e) {
System.out.println(e);
}

Department of Computer Applications, BMSCE 24


22MCA2PCJP: Java Programming

System.out.println("Thread 1 is alive: " + t1.isAlive());


System.out.println("Thread 2 is alive: " + t2.isAlive());
}
}

OutPut:

Department of Computer Applications, BMSCE 25


22MCA2PCJP: Java Programming

5.a)Write a Java program to perform employee payroll processing using packages. In the java file, Emp.java
creates a package employee and creates a class Emp. Declare the variables name,empid, category, bpay, hra,da,
npay, pf, grosspay, incometax, and allowance. Calculate the values in methods. Create another java file
Emppay.java. Create an object e to call the methods to perform and print values.

// File: Emp.java
package employee;

public class Emp {


// Variables
private String name;
private int empid;
private String category;
private double bpay; // Basic Pay
private double hra; // House Rent Allowance
private double da; // Dearness Allowance
private double npay; // Net Pay
private double pf; // Provident Fund
private double grosspay; // Gross Pay
private double incometax; // Income Tax
private double allowance; // Additional Allowance

// Constructor
public Emp(String name, int empid, String category, double bpay) {
this.name = name;
this.empid = empid;
this.category = category;
this.bpay = bpay;
}

// Methods to calculate pay details


public void calculateAllowances() {
hra = 0.10 * bpay; // 10% of basic pay
da = 0.05 * bpay; // 5% of basic pay
Department of Computer Applications, BMSCE 26
22MCA2PCJP: Java Programming

allowance = 0.07 * bpay; // 7% of basic pay


pf = 0.12 * bpay; // 12% of basic pay
grosspay = bpay + hra + da + allowance;
npay = grosspay - pf;
incometax = 0.05 * npay; // 5% of net pay for simplicity
npay -= incometax;
}

// Method to display employee details


public void displayPaySlip() {
System.out.println("Employee Name: " + name);
System.out.println("Employee ID: " + empid);
System.out.println("Category: " + category);
System.out.println("Basic Pay: $" + bpay);
System.out.println("HRA: $" + hra);
System.out.println("DA: $" + da);
System.out.println("Allowance: $" + allowance);
System.out.println("Gross Pay: $" + grosspay);
System.out.println("Provident Fund: $" + pf);
System.out.println("Income Tax: $" + incometax);
System.out.println("Net Pay: $" + npay);
}
}

// File: Emppay.java
import employee.Emp;

public class Emppay {


public static void main(String[] args) {
// Create an object of Emp
Emp e = new Emp("John Doe", 1234, "Manager", 5000.00);

// Calculate the allowances, gross pay, and net pay

Department of Computer Applications, BMSCE 27


22MCA2PCJP: Java Programming

e.calculateAllowances();

// Print the pay slip


e.displayPaySlip();
}
}

Department of Computer Applications, BMSCE 28


22MCA2PCJP: Java Programming

5.b)Write a Package MCA which has one class Student. Accept student detail through parameterized
constructor. Write display () method to display details. Create a main class which will use package and
calculate total marks and percentage.

// File: MCA/Student.java
package MCA;

public class Student {


// Student details
private String name;
private int rollNo;
private int[] marks; // Array to hold marks in different subjects

// Parameterized constructor
public Student(String name, int rollNo, int[] marks) {
this.name = name;
this.rollNo = rollNo;
this.marks = marks;
}

// Method to display student details


public void display() {
System.out.println("Student Name: " + name);
System.out.println("Roll Number: " + rollNo);
System.out.print("Marks: ");
int totalMarks = 0;
for (int mark : marks) {
System.out.print(mark + " ");
totalMarks += mark;
}
System.out.println();
System.out.println("Total Marks: " + totalMarks);
System.out.println("Percentage: " + calculatePercentage(totalMarks) + "%");
}
Department of Computer Applications, BMSCE 29
22MCA2PCJP: Java Programming

// Method to calculate percentage


private double calculatePercentage(int totalMarks) {
int numberOfSubjects = marks.length;
if (numberOfSubjects == 0) return 0;
return (totalMarks / (double) (numberOfSubjects * 100)) * 100;
}
}

// File: MainClass.java
import MCA.Student;

public class MainClass {


public static void main(String[] args) {
// Example student details
String name = "Alice Smith";
int rollNo = 101;
int[] marks = {85, 90, 78, 92, 88}; // Example marks in 5 subjects

// Create an instance of Student


Student student = new Student(name, rollNo, marks);

// Display student details and calculate total marks and percentage


student.display();
}
}

Department of Computer Applications, BMSCE 30


22MCA2PCJP: Java Programming

OUTPUT:

Department of Computer Applications, BMSCE 31


22MCA2PCJP: Java Programming

6)a)Write a complex program to illustrate how the thread priorities? Imagine that the first thread has just begun
to run, even before it has a chance to do anything. Now comes the higher priority thread that wants to run as
well. Now the higher priority thread has to do its work before the first thread starts.

class PriorityThreadExample {
public static void main(String[] args) {
// Creating the first thread (lower priority)
Thread thread1 = new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("Thread 1 is running...");
try {
Thread.sleep(1000); // Simulating work by sleeping for 1 second
} catch (InterruptedException e) {
System.out.println("Thread 1 was interrupted.");
}
}
System.out.println("Thread 1 has finished.");
}
});

// Creating the second thread (higher priority)


Thread thread2 = new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("Thread 2 is running (HIGH PRIORITY)...");
try {
Thread.sleep(500); // Simulating work by sleeping for 0.5 second
} catch (InterruptedException e) {
System.out.println("Thread 2 was interrupted.");
}
}
System.out.println("Thread 2 has finished.");
}

Department of Computer Applications, BMSCE 32


22MCA2PCJP: Java Programming

});

// Setting thread priorities


thread1.setPriority(Thread.MIN_PRIORITY); // Lowest priority
thread2.setPriority(Thread.MAX_PRIORITY); // Highest priority

// Starting both threads


thread1.start(); // Start thread1 first
try {
Thread.sleep(100); // Small delay before starting the higher priority thread
} catch (InterruptedException e) {
System.out.println("Main thread was interrupted.");
}
thread2.start(); // Start the higher-priority thread

// Joining threads to wait for their completion


try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
System.out.println("Thread joining was interrupted.");
}

System.out.println("Both threads have completed.");


}
}

Department of Computer Applications, BMSCE 33


22MCA2PCJP: Java Programming

Department of Computer Applications, BMSCE 34


22MCA2PCJP: Java Programming

b)Write a Java program that implements producer consumer problem using the concept of inter thread
communication.

import java.util.LinkedList;
import java.util.Queue;

class ProducerConsumerExample {

public static void main(String[] args) {


Buffer buffer = new Buffer(5); // Buffer size of 5

Thread producerThread = new Thread(new Producer(buffer));


Thread consumerThread = new Thread(new Consumer(buffer));

producerThread.start();
consumerThread.start();
}
}

class Buffer {
private Queue<Integer> queue;
private int capacity;

public Buffer(int capacity) {


this.queue = new LinkedList<>();
this.capacity = capacity;
}

// Method for the producer to add items


public synchronized void produce(int value) throws InterruptedException {
while (queue.size() == capacity) {
System.out.println("Buffer is full. Producer is waiting...");
Department of Computer Applications, BMSCE 35
22MCA2PCJP: Java Programming

wait(); // Wait until the consumer consumes some items


}

queue.add(value);
System.out.println("Produced: " + value);

notify(); // Notify the consumer that an item has been produced


}

// Method for the consumer to consume items


public synchronized int consume() throws InterruptedException {
while (queue.isEmpty()) {
System.out.println("Buffer is empty. Consumer is waiting...");
wait(); // Wait until the producer produces some items
}

int value = queue.remove();


System.out.println("Consumed: " + value);

notify(); // Notify the producer that an item has been consumed


return value;
}
}

// Producer class that will produce items and add them to the buffer
class Producer implements Runnable {
private Buffer buffer;

public Producer(Buffer buffer) {


this.buffer = buffer;
}

Department of Computer Applications, BMSCE 36


22MCA2PCJP: Java Programming

@Override
public void run() {
int value = 0;
try {
while (true) {
buffer.produce(++value); // Produce an item
Thread.sleep(500); // Simulate time to produce the item
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}

// Consumer class that will consume items from the buffer


class Consumer implements Runnable {
private Buffer buffer;

public Consumer(Buffer buffer) {


this.buffer = buffer;
}

@Override
public void run() {
try {
while (true) {
buffer.consume(); // Consume an item
Thread.sleep(1000); // Simulate time to consume the item
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
Department of Computer Applications, BMSCE 37
22MCA2PCJP: Java Programming

Department of Computer Applications, BMSCE 38


22MCA2PCJP: Java Programming

7)a)Write a program to create a text file in the path c:\java\abc.txt and check whether that file is exists. Using
the command exists(), isDirectory(), isFile(), getName() and getAbsolutePath().

import java.io.IOException;

public class FileExample {


public static void main(String[] args) {
String filePath = "C:/Users/student/Documents/Java/Week5/Emppay.class";
File file = new File(filePath);

try {
if (!file.exists()) {
file.createNewFile();
System.out.println("File created successfully!");
} else {
System.out.println("File already exists!");
}

if (file.exists()) {
System.out.println("File exists!");
} else {
System.out.println("File does not exist!");
}

if (file.isDirectory()) {
System.out.println("File is a directory!");
} else {
System.out.println("File is not a directory!");
}

if (file.isFile()) {
System.out.println("File is a file!");
} else {
System.out.println("File is not a file!");
}

Department of Computer Applications, BMSCE 39


22MCA2PCJP: Java Programming

System.out.println("File name: " + file.getName());

System.out.println("Absolute path: " + file.getAbsolutePath());


} catch (IOException e) {
System.out.println("Error creating file: " + e.getMessage());
}
}
}

Department of Computer Applications, BMSCE 40


22MCA2PCJP: Java Programming

b)Write a program to rename the given file, after renaming the file delete the renamed file. (Accept
the file name using command line arguments.)
import java.io.File;
public class RenameAndDeleteFile {
public static void main(String[] args) {
if (args.length != 1) {
System.out.println("Usage: java RenameAndDeleteFile <filename>");
System.exit(1);
}

String fileName = args[0];


File file = new File(fileName);

if (!file.exists()) {
System.out.println("File does not exist!");
System.exit(1);
}

String newFileName = "renamed_" + fileName;


File newFile = new File(newFileName);

if (file.renameTo(newFile)) {
System.out.println("File renamed successfully!");
} else {
System.out.println("Failed to rename file!");
System.exit(1);
}

if (newFile.delete()) {
System.out.println("Renamed file deleted successfully!");
} else {
System.out.println("Failed to delete renamed file!");
}
}
}

Department of Computer Applications, BMSCE 41


22MCA2PCJP: Java Programming

Department of Computer Applications, BMSCE 42


22MCA2PCJP: Java Programming

c)Write a program to create a directory and check whether the directory is created.

import java.io.File;
public class CreateDirectory {
public static void main(String[] args) {
String dirName = "MyNewDirectory";

File dir = new File(dirName);

if (dir.mkdir()) {
System.out.println("Directory created: " + dirName);
} else {
System.out.println("Failed to create directory: " + dirName);
}

if (dir.exists()) {
System.out.println("Directory exists: " + dirName);
} else {
System.out.println("Directory does not exist: " + dirName);
}
}
}

Department of Computer Applications, BMSCE 43


22MCA2PCJP: Java Programming

8)a)Write a program that can read a host name and convert it to an IP address
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Scanner;

public class HostnameToIPAddress {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Prompt the user to enter a hostname


System.out.print("Enter the hostname: ");
String hostname = scanner.nextLine();

try {
// Convert hostname to IP address
InetAddress ipAddress = InetAddress.getByName(hostname);
System.out.println("IP Address: " + ipAddress.getHostAddress());
} catch (UnknownHostException e) {
System.out.println("Could not resolve the hostname.");
}

scanner.close();
}
}

Department of Computer Applications, BMSCE 44


22MCA2PCJP: Java Programming

b)Write a Socket base java server program that responds to client messages as follows:
When it receives a message from client, it simply converts the message into all uppercase letters and
sends back to the client. Write both client and server programs demonstrating this.

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class UppercaseServer {


public static void main(String[] args) {
final int PORT = 12345; // Port number to listen on

try (ServerSocket serverSocket = new ServerSocket(PORT)) {


System.out.println("Server is listening on port " + PORT);

// Infinite loop to accept and handle multiple clients


while (true) {
try (Socket clientSocket = serverSocket.accept();
BufferedReader in = new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(new
OutputStreamWriter(clientSocket.getOutputStream()), true)) {

System.out.println("Client connected: " + clientSocket.getInetAddress());

// Read message from client


String message = in.readLine();
System.out.println("Received from client: " + message);

// Convert message to uppercase and send back


String response = message.toUpperCase();
out.println(response);

Department of Computer Applications, BMSCE 45


22MCA2PCJP: Java Programming

System.out.println("Sent to client: " + response);


} catch (Exception e) {
System.err.println("Error handling client: " + e.getMessage());
}
}
} catch (Exception e) {
System.err.println("Error starting server: " + e.getMessage());
}
}
}

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class UppercaseClient {


public static void main(String[] args) {
final String SERVER_ADDRESS = "localhost"; // Server address
final int PORT = 12345; // Port number used by the server

try (Socket socket = new Socket(SERVER_ADDRESS, PORT);


Scanner scanner = new Scanner(System.in);
PrintWriter out = new PrintWriter(new
OutputStreamWriter(socket.getOutputStream()), true);
BufferedReader in = new BufferedReader(new
InputStreamReader(socket.getInputStream()))) {

System.out.println("Connected to server at " + SERVER_ADDRESS + ":" + PORT);

// Read input from user


System.out.print("Enter message to send to server: ");
String message = scanner.nextLine();

Department of Computer Applications, BMSCE 46


22MCA2PCJP: Java Programming

// Send message to server


out.println(message);

// Receive and display response from server


String response = in.readLine();
System.out.println("Received from server: " + response);
} catch (Exception e) {
System.err.println("Error communicating with server: " + e.getMessage());
}
}
}

Department of Computer Applications, BMSCE 47


22MCA2PCJP: Java Programming

9.
a). Create the classes required to store data regarding different types of courses that employees in a
company can enroll for. All courses have name and course fee. Courses are also either classroom
delivered or delivered online. Courses could also be full time or part time. The program must enable
the course coordinator to register employees for courses and list out employees registered for specific
courses.

import java.util.Scanner;

abstract class Course {


private String name;
private double fee;
private Employee[] employeesRegistered;
private int numEmployees;
private boolean isOnline;
private boolean isFullTime;

public Course(String name, double fee, int maxEmployees, boolean isOnline, boolean
isFullTime) {
this.name = name;
this.fee = fee;
this.employeesRegistered = new Employee[maxEmployees];
this.numEmployees = 0;
this.isOnline = isOnline;
this.isFullTime = isFullTime;
}

public String getName() {


return name;
}

public double getFee() {


return fee;
}

Department of Computer Applications, BMSCE 48


22MCA2PCJP: Java Programming

public boolean isOnline() {


return isOnline;
}

public boolean isFullTime() {


return isFullTime;
}

public void registerEmployee(Employee employee) {


if (numEmployees < employeesRegistered.length) {
employeesRegistered[numEmployees++] = employee;
} else {
System.out.println("Cannot register more employees. Course is full.");
}
}

public Employee[] getEmployeesRegistered() {


Employee[] registeredEmployees = new Employee[numEmployees];
System.arraycopy(employeesRegistered, 0, registeredEmployees, 0, numEmployees);
return registeredEmployees;
}

public String[] listEmployees() {


String[] employeeNames = new String[numEmployees];
for (int i = 0; i < numEmployees; i++) {
employeeNames[i] = employeesRegistered[i].getName();
}
return employeeNames;
}

@Override
public String toString() {
return "Course{name='" + name + "', fee=" + fee + ", online=" + isOnline + ", fullTime="
+ isFullTime + "}";
}
}

Department of Computer Applications, BMSCE 49


22MCA2PCJP: Java Programming

class ConcreteCourse extends Course {


public ConcreteCourse(String name, double fee, int maxEmployees, boolean isOnline,
boolean isFullTime) {
super(name, fee, maxEmployees, isOnline, isFullTime);
}
}

class Employee {
private String name;

public Employee(String name) {


this.name = name;
}

public String getName() {


return name;
}
}

class CourseCoordinator {
private Course[] courses;
private int numCourses;

public CourseCoordinator(int maxCourses) {


this.courses = new Course[maxCourses];
this.numCourses = 0;
}

public void addCourse(Course course) {


if (numCourses < courses.length) {
courses[numCourses++] = course;
} else {
System.out.println("Cannot add more courses. Coordinator is full.");
}
}

Department of Computer Applications, BMSCE 50


22MCA2PCJP: Java Programming

public void registerEmployee(String courseName, Employee employee) {


Course course = findCourseByName(courseName);
if (course != null) {
course.registerEmployee(employee);
} else {
System.out.println("Course " + courseName + " not found.");
}
}

public String[] listEmployeesForCourse(String courseName) {


Course course = findCourseByName(courseName);
if (course != null) {
return course.listEmployees();
} else {
System.out.println("Course " + courseName + " not found.");
return new String[0];
}
}

private Course findCourseByName(String courseName) {


for (int i = 0; i < numCourses; i++) {
if (courses[i].getName().equalsIgnoreCase(courseName)) {
return courses[i];
}
}
return null;
}
}

public class coursemanageMain {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
CourseCoordinator coordinator = new CourseCoordinator(10);

while (true) {
try {
System.out.println("\n1. Add Course");

Department of Computer Applications, BMSCE 51


22MCA2PCJP: Java Programming

System.out.println("2. Register Employee");


System.out.println("3. List Employees for Course");
System.out.println("4. Exit");
System.out.print("Enter your choice: ");

int choice = Integer.parseInt(scanner.nextLine().trim());

switch (choice) {
case 1:
System.out.print("Enter course name: ");
String courseName = scanner.nextLine();
System.out.print("Enter course fee: ");
double fee = Double.parseDouble(scanner.nextLine().trim());
System.out.print("Enter maximum number of employees: ");
int maxEmployees = Integer.parseInt(scanner.nextLine().trim());
System.out.print("Is the course online? (true/false): ");
boolean isOnline = Boolean.parseBoolean(scanner.nextLine().trim());
System.out.print("Is the course full-time? (true/false): ");
boolean isFullTime = Boolean.parseBoolean(scanner.nextLine().trim());

Course course = new ConcreteCourse(courseName, fee, maxEmployees,


isOnline, isFullTime);
coordinator.addCourse(course);
System.out.println("Course added successfully!");
break;

case 2:
System.out.print("Enter course name to register: ");
String regCourseName = scanner.nextLine();
System.out.print("Enter employee name: ");
String employeeName = scanner.nextLine();

Employee employee = new Employee(employeeName);


coordinator.registerEmployee(regCourseName, employee);
System.out.println("Employee registered successfully!");
break;

Department of Computer Applications, BMSCE 52


22MCA2PCJP: Java Programming

case 3:
System.out.print("Enter course name to list employees: ");
String listCourseName = scanner.nextLine();

String[] employees = coordinator.listEmployeesForCourse(listCourseName);


System.out.println("Employees registered for " + listCourseName + ":");
if (employees.length == 0) {
System.out.println("No employees registered.");
} else {
for (String emp : employees) {
System.out.println(emp);
}
}
break;

case 4:
System.out.println("Exiting...");
scanner.close();
return;

default:
System.out.println("Invalid choice. Please try again.");
}
} catch (NumberFormatException e) {
System.out.println("Invalid input. Please enter numeric values where required.");
} catch (Exception e) {
System.out.println("An error occurred: " + e.getMessage());
}
}
}
}

Department of Computer Applications, BMSCE 53


22MCA2PCJP: Java Programming

Department of Computer Applications, BMSCE 54


22MCA2PCJP: Java Programming

b). Write a java program in to create a class Worker. Write classes DailyWorker and SalariedWorker that
inherit from Worker. Every worker has a name and a salaryrate. Write method Pay (int hours) to compute the
week pay of every worker. A Daily worker ia paid on the basis of the number of days she/he works. The
salaried worker gets paid the wage for 40 hours a week no matter what the actual hours are. Test this program
to calculate the pay of workers.

// Abstract base class Worker


abstract class Worker {
private String name;
private double salaryRate;

public Worker(String name, double salaryRate) {


this.name = name;
this.salaryRate = salaryRate;
}

public String getName() {


return name;
}

public double getSalaryRate() {


return salaryRate;
}

// Abstract method to calculate pay


public abstract double pay(int hours);
}

// Class for DailyWorker inheriting from Worker


class DailyWorker extends Worker {
public DailyWorker(String name, double salaryRate) {
super(name, salaryRate);
}

Department of Computer Applications, BMSCE 55


22MCA2PCJP: Java Programming

// Pay is calculated based on the number of hours worked


@Override
public double pay(int hours) {
// Assuming an 8-hour workday
return getSalaryRate() * (hours / 8.0);
}
}

// Class for SalariedWorker inheriting from Worker


class SalariedWorker extends Worker {
public SalariedWorker(String name, double salaryRate) {
super(name, salaryRate);
}

// Salaried worker is paid for 40 hours per week regardless of the hours worked
@Override
public double pay(int hours) {
// Fixed weekly pay for 40 hours
return getSalaryRate() * 40;
}
}

// Main class to test the program


public class SalaryMain {
public static void main(String[] args) {
// Creating workers
Worker dailyWorker = new DailyWorker("Faadil", 100.0); // 100 per day
Worker salariedWorker = new SalariedWorker("Khaleel", 20.0); // 20 per hour

// Calculating pay for the workers


int hoursWorked = 40; // Weekly hours
System.out.println(dailyWorker.getName() + " earned: $" + dailyWorker.pay(hoursWorked) + " this

Department of Computer Applications, BMSCE 56


22MCA2PCJP: Java Programming

week.");
System.out.println(salariedWorker.getName() + " earned: $" + salariedWorker.pay(hoursWorked) + " this
week.");
}
}

Department of Computer Applications, BMSCE 57


22MCA2PCJP: Java Programming

10.
a).Write a JAVA program to paint like paint brush in applet.

import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseListener;

/*
<applet code="PaintBrushApplet" width=400 height=400>
</applet>
*/

public class PaintBrushApplet extends Applet implements MouseMotionListener, MouseListener {


int x = 0, y = 0; // Store the coordinates for drawing

public void init() {


setBackground(Color.white); // Set the background to white
addMouseMotionListener(this); // Add mouse motion listener to capture dragging
addMouseListener(this); // Add mouse listener to capture clicking
}

// Implement the method to draw when the mouse is dragged


public void mouseDragged(MouseEvent e) {
x = e.getX();
y = e.getY();
Graphics g = getGraphics();
g.setColor(Color.black); // Set brush color to black
g.fillOval(x, y, 5, 5); // Draw a small oval to simulate brush strokes
}

Department of Computer Applications, BMSCE 58


22MCA2PCJP: Java Programming

// Empty implementation of mouseMoved, required by MouseMotionListener


public void mouseMoved(MouseEvent e) {
}

// Capture the initial point of the brush when the mouse is pressed
public void mousePressed(MouseEvent e) {
x = e.getX();
y = e.getY();
}

// Empty implementations for the remaining mouse events


public void mouseReleased(MouseEvent e) {
}

public void mouseClicked(MouseEvent e) {


}

public void mouseEntered(MouseEvent e) {


}

public void mouseExited(MouseEvent e) {


}

// Optional: paint method can be used to draw the initial UI or repaint the applet
public void paint(Graphics g) {
g.setColor(Color.black);
g.drawString("Draw with your mouse!", 20, 20);
}
}

Department of Computer Applications, BMSCE 59


22MCA2PCJP: Java Programming

Department of Computer Applications, BMSCE 60


22MCA2PCJP: Java Programming

b) Write a JAVA program to display analog clock using Applet.

import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;

public class AnalogClockApplet extends Applet {

private Timer timer;

public void init() {


setSize(400, 400);
timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
repaint();
}
}, 0, 1000); // Schedule the task to run every second
}

public void paint(Graphics g) {


super.paint(g);
Graphics2D g2d = (Graphics2D) g;

// Draw clock face


g2d.setColor(Color.WHITE);
g2d.fillOval(50, 50, 300, 300);
g2d.setColor(Color.BLACK);
g2d.drawOval(50, 50, 300, 300);

Department of Computer Applications, BMSCE 61


22MCA2PCJP: Java Programming

// Draw clock ticks


for (int i = 0; i < 12; i++) {
double angle = Math.toRadians(i * 30);
int x1 = (int) (200 + 140 * Math.cos(angle - Math.PI / 2));
int y1 = (int) (200 + 140 * Math.sin(angle - Math.PI / 2));
int x2 = (int) (200 + 150 * Math.cos(angle - Math.PI / 2));
int y2 = (int) (200 + 150 * Math.sin(angle - Math.PI / 2));
g2d.drawLine(x1, y1, x2, y2);
}

// Get current time


Calendar now = Calendar.getInstance();
int hour = now.get(Calendar.HOUR) == 0 ? 12 : now.get(Calendar.HOUR);
int minute = now.get(Calendar.MINUTE);
int second = now.get(Calendar.SECOND);

// Draw hour hand


double hourAngle = Math.toRadians((hour % 12 + minute / 60.0) * 30 - 90);
g2d.setColor(Color.BLACK);
drawHand(g2d, hourAngle, 70);

// Draw minute hand


double minuteAngle = Math.toRadians(minute * 6 - 90);
g2d.setColor(Color.BLACK);
drawHand(g2d, minuteAngle, 100);

// Draw second hand


double secondAngle = Math.toRadians(second * 6 - 90);
g2d.setColor(Color.RED);
drawHand(g2d, secondAngle, 120);
}

private void drawHand(Graphics2D g2d, double angle, int length) {


AffineTransform oldTransform = g2d.getTransform();
g2d.translate(200, 200);
Department of Computer Applications, BMSCE 62
22MCA2PCJP: Java Programming

g2d.rotate(angle);
g2d.drawLine(0, 0, 0, -length);
g2d.setTransform(oldTransform);
}

public void stop() {


timer.cancel();
}
}

Department of Computer Applications, BMSCE 63


22MCA2PCJP: Java Programming

c). Write a JAVA program to create different shapes and fill colors using Applet.

import java.applet.Applet;
import java.awt.*;

public class ShapesApplet extends Applet {

public void paint(Graphics g) {

g.setColor(Color.red);
g.fillRect(50, 50, 100, 50);

g.setColor(Color.green);
g.fillOval(200, 50, 100, 50);

g.setColor(Color.blue);
g.fillRoundRect(50, 150, 100, 50, 20, 20);

int[] x = {200, 250, 300};


int[] y = {150, 100, 150};
g.setColor(Color.yellow);
g.fillPolygon(x, y, 3);
}
}

Department of Computer Applications, BMSCE 64


22MCA2PCJP: Java Programming

11.
a). Write a JAVA program to build a Calculator in Swings

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

public class SimpleCalculator extends JFrame implements ActionListener {

// Create a text field to display the input and results


private JTextField display;

// Store the current input and operation


private StringBuilder input = new StringBuilder();
private String operator = "";
private double firstNumber = 0;

public SimpleCalculator() {
// Create the frame
setTitle("Simple Calculator");
setSize(400, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());

// Create the display panel


display = new JTextField();
display.setEditable(false);
display.setFont(new Font("Arial", Font.BOLD, 24));
add(display, BorderLayout.NORTH);

// Create the button panel


JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(4, 4, 10, 10));

// Define button labels


String[] labels = {
Department of Computer Applications, BMSCE 65
22MCA2PCJP: Java Programming

"7", "8", "9", "/",


"4", "5", "6", "*",
"1", "2", "3", "-",
"0", ".", "=", "+"
};

// Create and add buttons to the panel


for (String label : labels) {
JButton button = new JButton(label);
button.addActionListener(this);
buttonPanel.add(button);
}

add(buttonPanel, BorderLayout.CENTER);
}

@Override
public void actionPerformed(ActionEvent e) {
JButton source = (JButton) e.getSource();
String command = source.getText();

switch (command) {
case "=":
calculate();
break;
case "+":
case "-":
case "*":
case "/":
handleOperator(command);
break;
default:
appendToInput(command);
break;
}
}

Department of Computer Applications, BMSCE 66


22MCA2PCJP: Java Programming

private void appendToInput(String text) {


if (input.length() == 0 && text.equals(".")) {
// Prevent leading decimal point
return;
}
input.append(text);
display.setText(input.toString());
}

private void handleOperator(String op) {


if (input.length() > 0) {
firstNumber = Double.parseDouble(input.toString());
input.setLength(0); // Clear input for the next number
operator = op;
}
}

private void calculate() {


if (operator.isEmpty() || input.length() == 0) {
return; // No calculation needed
}

double secondNumber = Double.parseDouble(input.toString());


double result = 0;

switch (operator) {
case "+":
result = firstNumber + secondNumber;
break;
case "-":
result = firstNumber - secondNumber;
break;
case "*":
result = firstNumber * secondNumber;
break;
case "/":
if (secondNumber != 0) {

Department of Computer Applications, BMSCE 67


22MCA2PCJP: Java Programming

result = firstNumber / secondNumber;


} else {
JOptionPane.showMessageDialog(this, "Cannot divide by zero");
result = 0;
}
break;
}

input.setLength(0); // Clear input


input.append(result);
display.setText(input.toString());
operator = ""; // Clear operator
}

public static void main(String[] args) {


// Create and display the calculator
SwingUtilities.invokeLater(() -> {
SimpleCalculator calculator = new SimpleCalculator();
calculator.setVisible(true);
});
}
}

Department of Computer Applications, BMSCE 68


22MCA2PCJP: Java Programming

b). Write a JAVA program to display the digital watch using swings.

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.Date;
// Use JApplet for Swing-based applets
public class DigitalWatchApplet extends JApplet {
private JLabel timeLabel;
private SimpleDateFormat timeFormat;
@Override
public void init() {
// Set up the GUI
setSize(300, 100);
setLayout(new BorderLayout());

// Create a label to display the time


timeLabel = new JLabel();
timeLabel.setFont(new Font("Arial", Font.BOLD, 40));
timeLabel.setHorizontalAlignment(SwingConstants.CENTER)
// Add the label to the applet
add(timeLabel, BorderLayout.CENTER);

// Set up the time format


timeFormat = new SimpleDateFormat("HH:mm:ss");

// Create and start a timer to update the time every second


Timer timer = new Timer(1000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
updateTime();
}
});
timer.start();

Department of Computer Applications, BMSCE 69


22MCA2PCJP: Java Programming

// Initial update
updateTime();
}

// Method to update the time display


private void updateTime() {
Date now = new Date();
timeLabel.setText(timeFormat.format(now));
}

Department of Computer Applications, BMSCE 70

You might also like