Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 30

Java Programming and Dynamic Webpage (BCA-508)

BCA-Vth Sem (Session-2023-24)

PRACTICAL LIST
1 WAP to find the average and sum of the N numbers Using Command line argument.
import java.util.Arrays;
import java.util.InputMismatchException;

public class SumAndAverage {

public static void main(String[] args) {


if (args.length < 2) {
System.err.println("Usage: java SumAndAverage <number_of_values> <value1> <value2> ...
<valueN>");
System.exit(1);
}

try {
int n = Integer.parseInt(args[0]);
if (n <= 0) {
throw new IllegalArgumentException("Number of values must be positive");
}

if (args.length != n + 1) {
System.err.println("Incorrect number of arguments. Usage:");
System.err.println("java SumAndAverage <number_of_values> <value1> <value2> ...
<valueN>");
System.exit(1);
}

double[] values = new double[n];


for (int i = 1; i <= n; i++) {
try {
values[i - 1] = Double.parseDouble(args[i]);
} catch (NumberFormatException e) {
System.err.println("Invalid number format at argument " + i);
System.exit(1);
}
}

double sum = Arrays.stream(values).sum();


double average = sum / n;

System.out.println("Sum of " + n + " numbers: " + sum);


System.out.println("Average: " + average);
} catch (IllegalArgumentException | InputMismatchException e) {
System.err.println("Invalid input: " + e.getMessage());
System.exit(1);
}
}}
2 WAP to Demonstrate Type Casting.
public class TypeCastingDemo {

public static void main(String[] args) {

// Widening casting (implicit)


int numInt = 123;
long numLong = numInt; // No explicit casting needed, automatically widens to long
System.out.println("Widening: int 123 to long: " + numLong);

// Narrowing casting (explicit)


double numDouble = 3.14159;
int numIntNarrow = (int) numDouble; // Explicit casting using (int) to narrow to int
System.out.println("Narrowing: double 3.14159 to int (loss of precision): " + numIntNarrow);

// Narrowing with potential data loss


char letter = 'A';
byte byteChar = (byte) letter; // Explicit casting to byte might truncate higher values
System.out.println("Narrowing (potential data loss): char 'A' to byte: " + byteChar);

// Example of potential error with narrowing


double largeNumber = 1234567.891011;
int intLarge = (int) largeNumber; // Potential data loss if value exceeds int range
System.out.println("Narrowing (potential error): double 1234567.891011 to int: " + intLarge);

// Narrowing with rounding


float piFloat = 3.14159f; // float representation of pi
int piIntRounded = Math.round(piFloat); // Rounding using Math.round to nearest int
System.out.println("Narrowing with rounding: float pi (3.14159) to int: " + piIntRounded);
}
}

3 WAP to Demonstrate of Derive class Constructor.


class BaseClass {
int baseValue;

// Base class constructor with one parameter


public BaseClass(int value) {
baseValue = value;
System.out.println("Base class constructor called with value: " + value);
}

// Method to print base value


public void printBaseValue() {
System.out.println("Base value: " + baseValue);
}
}

class DerivedClass extends BaseClass {


int derivedValue;

// Derived class constructor with one parameter


public DerivedClass(int value) {
// Call base class constructor using super keyword
super(value); // This must be the first line in derived class constructor
derivedValue = value * 2;
System.out.println("Derived class constructor called with additional value: " + value);
}

// Method to print derived value


public void printDerivedValue() {
System.out.println("Derived value: " + derivedValue);
}
}

public class ConstructorDemo {


public static void main(String[] args) {
// Create an object of DerivedClass
DerivedClass obj = new DerivedClass(10);

// Print base and derived values


obj.printBaseValue();
obj.printDerivedValue();
}
}

4 WAP to Test the Prime number.


import java.util.Scanner;

public class PrimeTester {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.print("Enter a positive integer: ");


int num;
do {
try {
num = scanner.nextInt();
if (num <= 0) {
System.out.println("Error: Please enter a positive integer.");
} else {
break;
}
} catch (InputMismatchException e) {
System.out.println("Error: Please enter a valid integer.");
scanner.nextLine(); // clear invalid input
}
} while (true);

// Efficient prime checking: Optimized implementation

if (num <= 1) {
System.out.println(num + " is not a prime number.");
} else if (num <= 3) {
System.out.println(num + " is a prime number.");
} else if (num % 2 == 0 || num % 3 == 0) {
System.out.println(num + " is not a prime number.");
} else {
boolean isPrime = true;
for (int i = 5; i * i <= num; i += 6) {
if (num % i == 0 || num % (i + 2) == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
System.out.println(num + " is a prime number.");
} else {
System.out.println(num + " is not a prime number.");
}
}
}
}
5 WAP to calculate the Simple Interest and Input by the user.
import java.util.Scanner;

public class SimpleInterestCalculator {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Get user input for principal, rate, and time


System.out.print("Enter the principal amount: ");
double principal = getValidDouble(scanner, "Please enter a valid principal amount (positive number):
");

System.out.print("Enter the rate of interest (in percentage): ");


double rate = getValidDouble(scanner, "Please enter a valid rate of interest (positive number): ");

System.out.print("Enter the time period (in years): ");


double time = getValidDouble(scanner, "Please enter a valid time period (positive number): ");

// Calculate and display simple interest


double simpleInterest = (principal * rate * time) / 100;
System.out.printf("Simple Interest: %.2f\n", simpleInterest);
}

// Function to get valid double input with error handling


private static double getValidDouble(Scanner scanner, String errorMessage) {
double value;
do {
try {
value = scanner.nextDouble();
if (value <= 0) {
System.out.println(errorMessage);
} else {
break;
}
} catch (InputMismatchException e) {
System.out.println("Invalid input. Please enter a number:");
scanner.nextLine(); // Clear invalid input
}
} while (true);
return value;
}
}
6 WAP to create a Simple class to find out the Area and perimeter of rectangle and box using super and
this keyword.
class Shape {
double length;
double breadth;

// Constructor for Shape


Shape(double length, double breadth) {
this.length = length;
this.breadth = breadth;
}

// Method to calculate area


double getArea() {
return length * breadth;
}

// Method to calculate perimeter


double getPerimeter() {
return 2 * (length + breadth);
}
}

class Rectangle extends Shape {

// Constructor for Rectangle


Rectangle(double length, double breadth) {
super(length, breadth); // Call superclass constructor
}

// Override getArea() for specific functionality


@Override
double getArea() {
return super.getArea(); // Use superclass area calculation
}

// Override getPerimeter() for specific functionality


@Override
double getPerimeter() {
return super.getPerimeter(); // Use superclass perimeter calculation
}
}

class Box extends Shape {


double height;

// Constructor for Box


Box(double length, double breadth, double height) {
super(length, breadth); // Call superclass constructor
this.height = height;
}

// Override getArea() for box


@Override
double getArea() {
// Calculate total surface area of the box
return 2 * (length * breadth + length * height + breadth * height);
}

// Override getPerimeter() for box


@Override
double getPerimeter() {
// Calculate total perimeter of the box
return 4 * (length + breadth + height);
}
}

public class AreaPerimeterDemo {

public static void main(String[] args) {


// Create a Rectangle object
Rectangle rectangle = new Rectangle(5, 4);

// Calculate and print area and perimeter of rectangle


System.out.println("Rectangle area: " + rectangle.getArea());
System.out.println("Rectangle perimeter: " + rectangle.getPerimeter());

// Create a Box object


Box box = new Box(3, 2, 1);

// Calculate and print area and perimeter of box


System.out.println("Box area: " + box.getArea());
System.out.println("Box perimeter: " + box.getPerimeter());
}
}
7 WAP to find G.C.D of the number.
public class GCDCalculator {

public static void main(String[] args) {


if (args.length != 2) {
System.err.println("Usage: java GCDCalculator <number1> <number2>");
System.exit(1);
}

try {
int num1 = Integer.parseInt(args[0]);
int num2 = Integer.parseInt(args[1]);
int gcd = euclideanGCD(num1, num2);
System.out.println("GCD of " + num1 + " and " + num2 + " is: " + gcd);
} catch (NumberFormatException e) {
System.err.println("Invalid input: both arguments must be integers.");
System.exit(1);
}
}

public static int euclideanGCD(int num1, int num2) {


while (num2 != 0) {
int remainder = num1 % num2;
num1 = num2;
num2 = remainder;
}
return num1;
}
}
8 WAP to design a class account using the inheritance and static that show all function of bank (withdrawal,
deposit).
public class Bank {

// Static variable to store total number of accounts


private static int totalAccounts = 0;

public static int getTotalAccounts() {


return totalAccounts;
}

public static void main(String[] args) {


// Create accounts
SavingsAccount savings1 = new SavingsAccount(1000, 5); // Initial balance 1000, interest rate 5%
CurrentAccount current1 = new CurrentAccount(500); // Initial balance 500

// Deposit and withdraw money


savings1.deposit(200);
current1.withdraw(100);

// Print account details


System.out.println(savings1);
System.out.println(current1);

// Show total accounts


System.out.println("Total accounts: " + Bank.getTotalAccounts());
}
}

class Account {
protected int accountNumber;
protected double balance;

public Account(int accountNumber, double balance) {


this.accountNumber = accountNumber;
this.balance = balance;
Bank.totalAccounts++;
}

public void deposit(double amount) {


if (amount > 0) {
balance += amount;
System.out.println("Deposited " + amount + ". New balance: " + balance);
} else {
System.out.println("Invalid deposit amount. Please enter a positive value.");
}
}

public void withdraw(double amount) {


if (amount > 0 && amount <= balance) {
balance -= amount;
System.out.println("Withdrew " + amount + ". New balance: " + balance);
} else {
System.out.println("Invalid withdrawal amount. Please enter a positive amount less than or equal to
your balance.");
}
}

@Override
public String toString() {
return "Account Number: " + accountNumber + ", Balance: " + balance;
}
}

class SavingsAccount extends Account {


private double interestRate;

public SavingsAccount(int accountNumber, double balance, double interestRate) {


super(accountNumber, balance);
this.interestRate = interestRate;
}

public SavingsAccount(int accountNumber, double balance) {


this(accountNumber, balance, 0.0); // Default interest rate 0%
}

public void calculateInterest() {


double interest = balance * interestRate / 100;
balance += interest;
System.out.println("Interest earned: " + interest + ". New balance: " + balance);
}
}

class CurrentAccount extends Account {

public CurrentAccount(int accountNumber, double balance) {


super(accountNumber, balance);
}
public CurrentAccount(int accountNumber) {
this(accountNumber, 0.0); // Default balance 0
}
}
9 WAP to find the factorial of a given number using Recursion.
public class Factorial {

public static int calculateFactorial(int number) {


if (number == 0) {
return 1; // Base case: factorial of 0 is 1
} else {
return number * calculateFactorial(number - 1); // Recursive call
}
}

public static void main(String[] args) {


if (args.length != 1) {
System.err.println("Usage: java Factorial <number>");
System.exit(1);
}

try {
int number = Integer.parseInt(args[0]);
if (number < 0) {
throw new IllegalArgumentException("Number must be non-negative");
}

int factorial = calculateFactorial(number);


System.out.println("Factorial of " + number + " is: " + factorial);
} catch (NumberFormatException e) {
System.err.println("Invalid input: Please enter a valid integer.");
} catch (IllegalArgumentException e) {
System.err.println(e.getMessage());
}
}
}
10 WAP to design a class using abstract Methods and Classes.
import java.util.Random;

public interface Shape {


double getArea(); // Abstract method, common to all shapes

default void printDetails() {


System.out.println("This shape has an area of: " + getArea());
}
}

abstract class Polygon implements Shape {


protected int numSides;

public Polygon(int numSides) {


this.numSides = numSides;
}

public abstract double getPerimeter(); // Abstract method specific to polygons

public void printPolygonDetails() {


System.out.println("This is a " + numSides + "-sided polygon.");
}
}

class Triangle extends Polygon {

private double side1, side2, side3;

public Triangle(double side1, double side2, double side3) {


super(3);
this.side1 = side1;
this.side2 = side2;
this.side3 = side3;
}

@Override
public double getArea() {
double s = (side1 + side2 + side3) / 2;
return Math.sqrt(s * (s - side1) * (s - side2) * (s - side3));
}

@Override
public double getPerimeter() {
return side1 + side2 + side3;
}

@Override
public void printPolygonDetails() {
super.printPolygonDetails();
System.out.println("Side lengths: " + side1 + ", " + side2 + ", " + side3);
}
}

class Rectangle extends Polygon {

private double length, width;

public Rectangle(double length, double width) {


super(4);
this.length = length;
this.width = width;
}

@Override
public double getArea() {
return length * width;
}
@Override
public double getPerimeter() {
return 2 * (length + width);
}

@Override
public void printPolygonDetails() {
super.printPolygonDetails();
System.out.println("Length: " + length + ", Width: " + width);
}
}

class Circle implements Shape {

private double radius;

public Circle(double radius) {


this.radius = radius;
}

@Override
public double getArea() {
return Math.PI * radius * radius;
}

public void printCircleDetails() {


System.out.println("This is a circle with radius: " + radius);
}
}

public class ShapeDemo {

public static void main(String[] args) {


Random random = new Random();

// Create random shapes


Triangle triangle = new Triangle(random.nextDouble() * 5, random.nextDouble() * 5,
random.nextDouble() * 5);
Rectangle rectangle = new Rectangle(random.nextDouble() * 10, random.nextDouble() * 10);
Circle circle = new Circle(random.nextDouble() * 8);

// Display details of each shape


triangle.printPolygonDetails();
triangle.printDetails();
rectangle.printPolygonDetails();
rectangle.printDetails();
circle.printCircleDetails();
circle.printDetails();
}
}
11 WAP to design a String class that perform String Method (Equal Reverse the string change case).
public class MyString {
private char[] chars;
public MyString(String str) {
this.chars = str.toCharArray();
}

// Checks if two MyString objects have the same content


public boolean equals(MyString other) {
if (this.chars.length != other.chars.length) {
return false;
}
for (int i = 0; i < chars.length; i++) {
if (this.chars[i] != other.chars[i]) {
return false;
}
}
return true;
}

// Reverses the characters in the MyString object


public void reverse() {
for (int i = 0; i < chars.length / 2; i++) {
char temp = chars[i];
chars[i] = chars[chars.length - 1 - i];
chars[chars.length - 1 - i] = temp;
}
}

// Converts all characters to uppercase or lowercase


public void changeCase(boolean toUpperCase) {
for (int i = 0; i < chars.length; i++) {
if (toUpperCase) {
chars[i] = Character.toUpperCase(chars[i]);
} else {
chars[i] = Character.toLowerCase(chars[i]);
}
}
}

// Returns the String representation of the MyString object


@Override
public String toString() {
return new String(chars);
}

// Example usage
public static void main(String[] args) {
MyString str1 = new MyString("Hello, world!");
MyString str2 = new MyString("hello, World!");
MyString str3 = new MyString("dlrow ,olleH");

System.out.println(str1.equals(str2)); // False (different cases)


System.out.println(str1.equals(str3)); // True (same content)
System.out.println("Original string: " + str1);
str1.reverse();
System.out.println("Reversed string: " + str1);

System.out.println("Original string: " + str2);


str2.changeCase(true);
System.out.println("Uppercase string: " + str2);

System.out.println("Original string: " + str3);


str3.changeCase(false);
System.out.println("Lowercase string: " + str3);
}
}
12 WAP to handle the Exception using try and multiple catch block.
public class ExceptionHandlingDemo {

public static void main(String[] args) {


// Example 1: Simple division by zero
try {
int result = 10 / 0;
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero!");
}

// Example 2: NumberFormatException with specific handling


String input = "abc";
try {
int number = Integer.parseInt(input);
System.out.println("Parsed number: " + number);
} catch (NumberFormatException e) {
if (input.isBlank()) {
System.out.println("Input string is empty.");
} else {
System.out.println("Input string is not a valid number.");
}
}

// Example 3: Catching multiple exceptions with more specific first


try {
String str = null;
str.length(); // NullPointerException
} catch (NullPointerException e) {
System.out.println("Object reference is null.");
} catch (Exception e) { // This won't be reached due to more specific catch earlier
System.out.println("General exception!");
}

// Example 4: Using finally block for guaranteed execution


int[] arr = {1, 2, 3};
try {
System.out.println(arr[10]); // ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Index out of bounds.");
} finally {
System.out.println("This code will always execute, even if there's an exception.");
}

// Example 5: Custom exception with appropriate message


try {
throw new MyCustomException("This is a custom exception!");
} catch (MyCustomException e) {
System.out.println(e.getMessage()); // Prints "This is a custom exception!"
}
}

static class MyCustomException extends Exception {


public MyCustomException(String message) {
super(message);
}
}
}
13 WAP that Implement the Nested try Statements.
public class NestedTryDemo {

public static void main(String[] args) {


// Example 1: Accessing array element within a loop
try {
int[] myArray = {1, 2, 3};
for (int i = 0; i <= myArray.length; i++) { // Intentionally create potential exception
try {
System.out.println(myArray[i]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Index out of bounds: " + i);
}
}
} catch (Exception e) { // This won't be reached because exceptions are handled in the inner catch
block
System.out.println("General exception in outer try block!");
}

// Example 2: Closing resources (file or database connections)


try (AutoCloseableResource resource1 = new AutoCloseableResource("resource1");
AutoCloseableResource resource2 = new AutoCloseableResource("resource2")) {
// Use resources here
try {
throw new MyCustomException("This is a custom exception in inner try block!");
} catch (MyCustomException e) {
System.out.println(e.getMessage());
}
} catch (Exception e) { // This catches exceptions from both inner try and resource closing
System.out.println("General exception in outer try block!");
} finally {
System.out.println("Resources closed."); // Guaranteed execution, even with exceptions
}
}
static class AutoCloseableResource implements AutoCloseable {
private final String name;

public AutoCloseableResource(String name) {


this.name = name;
System.out.println("Opening resource: " + name);
}

@Override
public void close() throws Exception {
System.out.println("Closing resource: " + name);
}
}

static class MyCustomException extends Exception {


public MyCustomException(String message) {
super(message);
}
}
}
14 WAP to Create a package that access the member of external class as well as same package.
// Create a package named com.example.mypackage
package com.example.mypackage;

// Create a class named ExternalClass in a different package


package com.example.externalpackage;

public class ExternalClass {


public int publicMember = 10;
private int privateMember = 20;

public void publicMethod() {


System.out.println("This is a public method in ExternalClass.");
}

private void privateMethod() {


System.out.println("This is a private method in ExternalClass.");
}
}

// Create a class named MyClass in the same package as ExternalClass


package com.example.mypackage;

public class MyClass {

public static void main(String[] args) {


// Access public member of ExternalClass
System.out.println("Public member of ExternalClass: " + ExternalClass.publicMember);

// Create an instance of ExternalClass


OuterClass instance = new ExternalClass();
// Call public method of ExternalClass
instance.publicMethod();

// Cannot access private member of ExternalClass directly (compile-time error)


// System.out.println(instance.privateMember);

// Cannot call private method of ExternalClass directly (compile-time error)


// instance.privateMethod();
}
}
15 WAP that import the user define package and access the Member variable of classes that Contained by
Package.
// Create a package named com.example.mypackage
package com.example.mypackage;

// Create a class named Shape in the mypackage package


public class Shape {
protected double area; // Protected member, accessible by subclasses within and outside the package

public Shape(double area) {


this.area = area;
}

public void printArea() {


System.out.println("Shape area: " + area);
}
}

// Create a subclass named Triangle in the mypackage package


class Triangle extends Shape {
private double base, height;

public Triangle(double base, double height) {


super(base * height / 2); // Calculate and pass calculated area to Shape constructor
this.base = base;
this.height = height;
}

public void printDetails() {


System.out.println("Triangle base: " + base);
System.out.println("Triangle height: " + height);
super.printArea(); // Call Shape's printArea() to print calculated area
}
}

// Create a class named Circle in the mypackage package


class Circle extends Shape {
private double radius;

public Circle(double radius) {


super(Math.PI * radius * radius); // Calculate and pass calculated area to Shape constructor
this.radius = radius;
}
public void printDetails() {
System.out.println("Circle radius: " + radius);
super.printArea(); // Call Shape's printArea() to print calculated area
}
}

// Import the mypackage package in a separate class


public class Main {

public static void main(String[] args) {


// Create instances of Triangle and Circle
Triangle triangle = new Triangle(5, 4);
Circle circle = new Circle(3);

// Print details of shapes using their own methods


triangle.printDetails();
circle.printDetails();
}
}
16 WAP that show the partial implementation of Interface.

 Interface:

Java
public interface Drawable {
void draw(); // Abstract method, common to all drawable objects
}

 Abstract Class:

Java
public abstract class Shape implements Drawable {
protected String name;

public Shape(String name) {


this.name = name;
}

public abstract void draw(); // Abstract method specific to shapes

@Override
public String toString() {
return "Shape: " + name;
}
}

 Concrete Implementations:

Java
class Rectangle extends Shape {

private double width, height;

public Rectangle(String name, double width, double height) {


super(name);
this.width = width;
this.height = height;
}

@Override
public void draw() {
System.out.println("Drawing a rectangle named " + name + " with dimensions " +
width + "x" + height);
}
}

class Circle extends Shape {

private double radius;

public Circle(String name, double radius) {


super(name);
this.radius = radius;
}

@Override
public void draw() {
System.out.println("Drawing a circle named " + name + " with radius " +
radius);
}
}

 Main Class:

Java
public class Main {

public static void main(String[] args) {


Shape rectangle = new Rectangle("Rect", 5, 3);
Shape circle = new Circle("Circle", 2);

rectangle.draw(); // Calls Rectangle's specific draw()


circle.draw(); // Calls Circle's specific draw()

// Note: These shapes partially implement Drawable by providing their own


draw() methods,
// while inheriting other functionality from Shape.
}
}

17 WAP to Handle the user defined Exception using throw keyword.


// Create user-defined exception
public class MyCustomException extends Exception {
public MyCustomException(String message) {
super(message);
}
}

public class CustomExceptionHandling {

public static void validateAge(int age) throws MyCustomException {


if (age < 18) {
throw new MyCustomException("Age must be 18 or older.");
}
}
public static void main(String[] args) {
try {
validateAge(20); // Valid age, no exception
System.out.println("Age is valid.");
} catch (MyCustomException e) {
System.err.println(e.getMessage()); // Custom error message
}

try {
validateAge(15); // Invalid age, exception thrown
System.out.println("This will not be printed.");
} catch (MyCustomException e) {
System.err.println(e.getMessage()); // Custom error message
}
}
}
18 WAP to create a thread that Implement the Run able interface.
public class MyThread implements Runnable {

private String name;


private int delay;

public MyThread(String name, int delay) {


this.name = name;
this.delay = delay;
}

@Override
public void run() {
try {
System.out.println("Thread " + name + " started.");
Thread.sleep(delay); // Simulate some work by sleeping
System.out.println("Thread " + name + " finished.");
} catch (InterruptedException e) {
System.err.println("Thread " + name + " interrupted.");
}
}

public static void main(String[] args) {


// Create multiple threads with different names and delays
Thread thread1 = new Thread(new MyThread("Thread 1", 1000));
Thread thread2 = new Thread(new MyThread("Thread 2", 2000));
Thread thread3 = new Thread(new MyThread("Thread 3", 3000));

// Start the threads


thread1.start();
thread2.start();
thread3.start();

// Wait for all threads to finish (optional)


try {
thread1.join();
thread2.join();
thread3.join();
} catch (InterruptedException e) {
System.err.println("Main thread interrupted.");
}

System.out.println("All threads finished.");


}
}
19 WAP to Implement Interthread communication.
public class InterThreadCommunication {

private static boolean flag = false;


private static Object lock = new Object();

public static void main(String[] args) throws InterruptedException {


Thread producer = new Thread(() -> {
synchronized (lock) {
while (!flag) {
try {
// Produce data here (e.g., generate a random number)
int data = (int) (Math.random() * 100);
System.out.println("Producer produced: " + data);
// Signal consumer
flag = true;
lock.notify(); // wake up waiting consumer
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});

Thread consumer = new Thread(() -> {


synchronized (lock) {
while (!flag) {
try {
// Wait for producer to signal
lock.wait();
// Consume data here (e.g., process the produced number)
System.out.println("Consumer consumed: " + flag); // use the previously produced data
flag = false;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});

producer.start();
consumer.start();

// Optionally wait for threads to finish (e.g., for testing)


// producer.join();
// consumer.join();
}
}
20 WAP to create a class component that show controls and event handling on that controls.(math calc).

import java.awt.*;
import java.awt.event.*;

public class MyComponent extends Panel implements ActionListener {

private Button button;


private Label label;

public MyComponent() {
setLayout(new FlowLayout());

// Create a button
button = new Button("Click Me");
add(button);

// Create a label
label = new Label("...");
add(label);

// Register event listener for button click


button.addActionListener(this);
}

@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button) {
label.setText("Button clicked!");
}
}

public static void main(String[] args) {


Frame frame = new Frame("My Component");
MyComponent component = new MyComponent();
frame.add(component);
frame.pack();
frame.setVisible(true);
}
}
21 WAP to Draw the line, Rectangle, eval,text using the graphics method.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class DrawPanel extends JPanel implements MouseListener {

private Point startPoint, endPoint;


private String textToDraw = "Hello, World!";
public DrawPanel() {
super();
addMouseListener(this);
}

@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);

// Draw line if start and end points are set


if (startPoint != null && endPoint != null) {
g.setColor(Color.RED);
g.drawLine(startPoint.x, startPoint.y, endPoint.x, endPoint.y);
}

// Draw rectangle if end point is set


if (endPoint != null) {
g.setColor(Color.BLUE);
g.drawRect(startPoint.x, startPoint.y, endPoint.x - startPoint.x, endPoint.y - startPoint.y);
}

// Draw text at the specified location


g.setColor(Color.BLACK);
g.setFont(new Font("Arial", Font.BOLD, 20));
g.drawString(textToDraw, 10, 30);
}

@Override
public void mouseClicked(MouseEvent e) {
if (startPoint == null) {
startPoint = e.getPoint();
} else {
endPoint = e.getPoint();
repaint(); // Trigger redrawing with updated data
startPoint = null;
endPoint = null; // Reset for next line/rectangle
}
}

@Override
public void mousePressed(MouseEvent e) {}

@Override
public void mouseReleased(MouseEvent e) {}

@Override
public void mouseEntered(MouseEvent e) {}

@Override
public void mouseExited(MouseEvent e) {}

public static void main(String[] args) {


JFrame frame = new JFrame("Draw App");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new DrawPanel());
frame.pack();
frame.setVisible(true);
}
}
22 WAP to create a Menu using the frame.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class MenuExample implements ActionListener {

private JMenuBar menuBar;


private JMenu fileMenu, editMenu;
private JMenuItem newMenuItem, openMenuItem, saveMenuItem, exitMenuItem;
private JMenuItem copyMenuItem, pasteMenuItem, cutMenuItem;
private JFrame frame;

public MenuExample() {
// Create menus and menu items
menuBar = new JMenuBar();

fileMenu = new JMenu("File");


editMenu = new JMenu("Edit");

newMenuItem = new JMenuItem("New");


openMenuItem = new JMenuItem("Open");
saveMenuItem = new JMenuItem("Save");
exitMenuItem = new JMenuItem("Exit");

copyMenuItem = new JMenuItem("Copy");


pasteMenuItem = new JMenuItem("Paste");
cutMenuItem = new JMenuItem("Cut");

// Add menu items to menus


fileMenu.add(newMenuItem);
fileMenu.add(openMenuItem);
fileMenu.add(saveMenuItem);
fileMenu.addSeparator();
fileMenu.add(exitMenuItem);

editMenu.add(copyMenuItem);
editMenu.add(pasteMenuItem);
editMenu.add(cutMenuItem);

// Add menus to menu bar


menuBar.add(fileMenu);
menuBar.add(editMenu);

// Add action listeners to menu items


newMenuItem.addActionListener(this);
openMenuItem.addActionListener(this);
saveMenuItem.addActionListener(this);
exitMenuItem.addActionListener(this);
copyMenuItem.addActionListener(this);
pasteMenuItem.addActionListener(this);
cutMenuItem.addActionListener(this);

// Create frame with menu bar


frame = new JFrame("Menu Example");
frame.setJMenuBar(menuBar);
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}

@Override
public void actionPerformed(ActionEvent e) {
JMenuItem source = (JMenuItem) e.getSource();

if (source == newMenuItem) {
// Handle "New" action
System.out.println("Clicked New!");
} else if (source == openMenuItem) {
// Handle "Open" action
System.out.println("Clicked Open!");
} else if (source == saveMenuItem) {
// Handle "Save" action
System.out.println("Clicked Save!");
} else if (source == exitMenuItem) {
// Handle "Exit" action
System.out.println("Clicked Exit!");
frame.dispose();
} else if (source == copyMenuItem) {
// Handle "Copy" action
System.out.println("Clicked Copy!");
} else if (source == pasteMenuItem) {
// Handle "Paste" action
System.out.println("Clicked Paste!");
} else if (source == cutMenuItem) {
// Handle "Cut" action
System.out.println("Clicked Cut!");
}
}

public static void main(String[] args) {


new MenuExample();
}
}
23 WAP to create a Dialog box.
import javax.swing.*;

public class DialogExample {

public static void main(String[] args) {


String name = JOptionPane.showInputDialog(null, "Enter your name:");
JOptionPane.showMessageDialog(null, "Hello, " + name + "!");
}
}
24 WAP to Implement the flow layout And Border Layout.
import java.awt.*;

public class LayoutExample {

public static void main(String[] args) {


// Create a frame
JFrame frame = new JFrame("Layout Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Create panels with different layouts


JPanel flowPanel = new JPanel(new FlowLayout());
JPanel borderPanel = new JPanel(new BorderLayout());

// Add components to FlowLayout panel


flowPanel.add(new JLabel("Label 1"));
flowPanel.add(new JButton("Button 1"));
flowPanel.add(new JTextField(10));

// Add components to BorderLayout panel


borderPanel.add(new JLabel("North"), BorderLayout.NORTH);
borderPanel.add(new JLabel("South"), BorderLayout.SOUTH);
borderPanel.add(new JLabel("East"), BorderLayout.EAST);
borderPanel.add(new JLabel("West"), BorderLayout.WEST);
borderPanel.add(new JLabel("Center"), BorderLayout.CENTER);

// Add panels to the frame


frame.add(flowPanel, BorderLayout.NORTH);
frame.add(borderPanel, BorderLayout.CENTER);

// Set frame size and visibility


frame.setSize(400, 300);
frame.setVisible(true);
}
}
25 WAP to implement the Grid layout, Card Layout.
import java.awt.*;
import javax.swing.*;

public class LayoutExample {

public static void main(String[] args) {


// Create a frame
JFrame frame = new JFrame("Layout Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Create panels with different layouts


JPanel gridPanel = new JPanel(new GridLayout(2, 3));
JPanel cardPanel = new CardLayout();
// Add buttons to GridLayout panel
for (int i = 1; i <= 6; i++) {
gridPanel.add(new JButton("Button " + i));
}

// Add panels to CardLayout panel


cardPanel.add("Grid", gridPanel);
JPanel textPanel = new JPanel();
textPanel.add(new JLabel("This is the card layout panel."));
cardPanel.add("Text", textPanel);

// Add CardLayout panel to the frame


frame.add(cardPanel);

// Create button to switch cards


JButton switchButton = new JButton("Switch");
switchButton.addActionListener(e -> {
CardLayout layout = (CardLayout) cardPanel.getLayout();
layout.next(cardPanel);
});
frame.add(switchButton, BorderLayout.SOUTH);

// Set frame size and visibility


frame.setSize(400, 300);
frame.setVisible(true);
}
}
26 WAP to Create Indian Flag using Applet.
import java.applet.*;
import java.awt.*;

public class IndianFlagApplet extends Applet {

@Override
public void paint(Graphics g) {
int width = getWidth();
int height = getHeight();

// Calculate aspect ratio to maintain correct proportions


double aspectRatio = 2.0 / 3.0;
int flagWidth = Math.min(width, (int) (height * aspectRatio));
int flagHeight = (int) (flagWidth / aspectRatio);

// Calculate component widths and heights based on proportions


int saffronBandHeight = flagHeight / 3;
int whiteBandHeight = saffronBandHeight;
int greenBandHeight = flagHeight - saffronBandHeight - whiteBandHeight;
int chakraWidth = flagWidth / 5;
int chakraHeight = (int) (chakraWidth * 0.8);

// Draw saffron band


g.setColor(Color.ORANGE);
g.fillRect(0, 0, flagWidth, saffronBandHeight);

// Draw white band


g.setColor(Color.WHITE);
g.fillRect(0, saffronBandHeight, flagWidth, whiteBandHeight);

// Draw green band


g.setColor(Color.GREEN);
g.fillRect(0, saffronBandHeight + whiteBandHeight, flagWidth, greenBandHeight);

// Draw chakra (blue wheel with 24 spokes)


int chakraX = (flagWidth - chakraWidth) / 2;
int chakraY = (saffronBandHeight + whiteBandHeight - chakraHeight) / 2;

// Draw blue circle


g.setColor(Color.BLUE);
g.fillOval(chakraX, chakraY, chakraWidth, chakraHeight);

// Draw spokes (using polar coordinates)


for (int i = 0; i < 24; i++) {
double angle = (i * Math.PI) / 12; // 360 degrees / 24 spokes
int spokeX = (int) ((chakraWidth / 2) * Math.cos(angle) + chakraX + chakraWidth / 2);
int spokeY = (int) ((chakraHeight / 2) * Math.sin(angle) + chakraY + chakraHeight / 2);
g.drawLine(chakraX + chakraWidth / 2, chakraY + chakraHeight / 2, spokeX, spokeY);
}
}
}
27 WAP to demonstrate System clock
import java.awt.*;
import java.awt.event.*;
import java.time.*;
import javax.swing.*;

public class SystemClock extends JPanel implements ActionListener {

private JLabel timeLabel;


private JButton formatButton;
private boolean is12HourFormat = true;

public SystemClock() {
setLayout(new FlowLayout());

timeLabel = new JLabel("00:00:00");


timeLabel.setFont(new Font("Arial", Font.BOLD, 36));
add(timeLabel);

formatButton = new JButton("Change Format");


formatButton.addActionListener(this);
add(formatButton);

startTimer(); // Start updating time immediately


}
public void startTimer() {
Timer timer = new Timer(1000, this); // Update every second
timer.start();
}

@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == formatButton) {
toggleFormat();
} else { // Timer event
updateClock();
}
}

private void toggleFormat() {


is12HourFormat = !is12HourFormat;
formatButton.setText(is12HourFormat ? "24-Hour Format" : "12-Hour Format");
}

private void updateClock() {


LocalDateTime now = LocalDateTime.now();
int hour = now.getHour();
int minute = now.getMinute();
int second = now.getSecond();

String strHour = String.format("%02d", is12HourFormat ? (hour % 12) : hour);


String strMinute = String.format("%02d", minute);
String strSecond = String.format("%02d", second);

String timeString = is12HourFormat ? String.format("%s:%s:%s %s", strHour, strMinute, strSecond,


(hour >= 12) ? "PM" : "AM") : String.format("%s:%s:%s", strHour, strMinute, strSecond);
timeLabel.setText(timeString);
}

public static void main(String[] args) {


JFrame frame = new JFrame("System Clock");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new SystemClock());
frame.pack();
frame.setVisible(true);
}
}
28 WAP to create Frame that display the student information.
import java.awt.*;
import javax.swing.*;

public class StudentInformationFrame extends JFrame {

public StudentInformationFrame(String title, Student student) {


super(title);

// Create labels and text fields for displaying information


JLabel nameLabel = new JLabel("Name: ");
JTextField nameField = new JTextField(student.getName(), 20);
nameField.setEditable(false); // Make name uneditable

JLabel rollNoLabel = new JLabel("Roll No: ");


JTextField rollNoField = new JTextField(student.getRollNo(), 10);
rollNoField.setEditable(false); // Make roll no uneditable

JLabel programLabel = new JLabel("Program: ");


JTextField programField = new JTextField(student.getProgram(), 20);
programField.setEditable(false); // Make program uneditable

// Create and add layout for components


JPanel contentPanel = new JPanel(new GridLayout(4, 2));
contentPanel.add(nameLabel);
contentPanel.add(nameField);
contentPanel.add(rollNoLabel);
contentPanel.add(rollNoField);
contentPanel.add(programLabel);
contentPanel.add(programField);

// Add panel to frame and set attributes


add(contentPanel);
pack();
setVisible(true);
}

public static void main(String[] args) {


// Replace with actual student data
Student student = new Student("John Doe", "CS123", "Computer Science");
new StudentInformationFrame("Student Information", student);
}
}

class Student {
private String name;
private String rollNo;
private String program;

public Student(String name, String rollNo, String program) {


this.name = name;
this.rollNo = rollNo;
this.program = program;
}

public String getName() {


return name;
}

public String getRollNo() {


return rollNo;
}

public String getProgram() {


return program;
}
}

Class Coordinator
Mr.Sanjeev Giri
BCA-Vth Sem(Section-B)
Director Prof. (Dr.)Rakesh Kumar (BBA/BCA Department

You might also like