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

2.

Write a Java Program to Find ASCII Value of a character


import java.util.Scanner;

public class ASCIIValue {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a character: ");
char ch = scanner.next().charAt(0);
// Finding ASCII value of the character
int asciiValue = (int) ch;
// Print ASCII value
System.out.println("ASCII value of " + ch + " is: " + asciiValue);
scanner.close();
}
}

5. Write a Java Program to Check Whether an Alphabet is Vowel or Consonant


import java.util.Scanner;

public class VowelOrConsonant {


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

System.out.print("Enter a character: ");


char ch = scanner.next().charAt(0);

// Convert input character to lowercase to handle both cases (upper and lower)
ch = Character.toLowerCase(ch);

// Check if the character is an alphabet


if ((ch >= 'a' && ch <= 'z')) {
// Check if the character is a vowel
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
System.out.println(ch + " is a Vowel");
} else {
System.out.println(ch + " is a Consonant");
}
} else {
System.out.println(ch + " is not an Alphabet");
}

scanner.close();
}
}

6. Write a Java Program to Find all Roots of a Quadratic Equation


import java.util.Scanner;

public class QuadraticEquation {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.println("Enter coefficients of the quadratic equation (a, b, c):");

System.out.print("a = ");

double a = scanner.nextDouble();

System.out.print("b = ");

double b = scanner.nextDouble();

System.out.print("c = ");

double c = scanner.nextDouble();

// Calculate discriminant

double discriminant = b * b - 4 * a * c;

if (discriminant > 0) {

// Calculate two distinct real roots

double root1 = (-b + Math.sqrt(discriminant)) / (2 * a);

double root2 = (-b - Math.sqrt(discriminant)) / (2 * a);

System.out.println("Roots are real and distinct:");

System.out.println("Root 1 = " + root1);

System.out.println("Root 2 = " + root2);

} else if (discriminant == 0) {

// Calculate one real root (roots are equal)

double root = -b / (2 * a);

System.out.println("Roots are real and equal:");


System.out.println("Root = " + root);

} else {

// No real roots (discriminant < 0)

System.out.println("No real roots exist (complex roots)");

scanner.close();

8. Write a Java Program to Check Leap Year


9. Write a Java Program to Check Whether a Character is Alphabet or Not
10. Write a Java Program to Calculate the Sum of Natural Numbers
11. Write a Java Program to Find Factorial of a Number
13. Write a Java Program to Display Fibonacci Series
14. Write a Java Program to Find GCD of two Numbers
15. Write a Java Program to Find LCM of two Numbers
16. Write a Java Program to Display Alphabets (A to Z) using loop
17. Write a Java Program to Count Number of Digits in an Integer
18. Write a Java Program to Reverse a Number
19. Write a Java Program to Calculate the Power of a Number
import java.util.Scanner;

public class PowerOfNumber {


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

System.out.print("Enter the base number (x): ");


double base = scanner.nextDouble();

System.out.print("Enter the exponent (n): ");


int exponent = scanner.nextInt();

double result = power(base, exponent);

System.out.println(base + " raised to the power of " + exponent + " is: " + result);
scanner.close();
}

// Function to calculate power using a loop


public static double power(double base, int exponent) {
double result = 1;
for (int i = 1; i <= exponent; i++) {
result *= base;
}
return result;
}
}

20. Write a Java Program to Check Palindrome


21. Write a Java Program to Check Whether a Number is Prime or Not
22. Write a Java Program to Display Prime Numbers Between Two Intervals
23. Write a Java Program to Check Armstrong Number
24. Write a Java Program to Display Armstrong Number Between Two Intervals.
import java.util.Scanner;

public class ArmstrongNumbersBetweenIntervals {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter the lower limit of the interval: ");

int lower = scanner.nextInt();

System.out.print("Enter the upper limit of the interval: ");

int upper = scanner.nextInt();

System.out.println("Armstrong numbers between " + lower + " and " + upper + ":");

for (int num = lower; num <= upper; num++) {

if (isArmstrong(num)) {

System.out.print(num + " ");


}

scanner.close();

// Function to check if a number is Armstrong or not

public static boolean isArmstrong(int number) {

int originalNumber, remainder, result = 0;

int n = numberOfDigits(number);

originalNumber = number;

// Calculate sum of nth power of digits

while (originalNumber != 0) {

remainder = originalNumber % 10;

result += Math.pow(remainder, n);

originalNumber /= 10;

// Check if number is equal to the sum of nth power of digits

if (result == number) {

return true;

} else {

return false;

// Function to calculate number of digits in a number

public static int numberOfDigits(int number) {

int count = 0;

while (number != 0) {

number /= 10;

count++;

}
return count;

25. Write a Java Program to Display Prime Numbers Between Intervals Using Function
import java.util.Scanner;

public class PrimeNumbers {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter the lower limit of the interval: ");

int lower = scanner.nextInt();

System.out.print("Enter the upper limit of the interval: ");

int upper = scanner.nextInt();

System.out.println("Prime numbers between " + lower + " and " + upper + ":");

for (int num = lower; num <= upper; num++) {

if (isPrime(num)) {

System.out.print(num + " ");

scanner.close();

// Function to check if a number is prime or not

public static boolean isPrime(int number) {

if (number <= 1) {

return false; // 1 and below are not prime numbers

if (number == 2) {

return true; // 2 is a prime number


}

if (number % 2 == 0) {

return false; // Even numbers greater than 2 are not prime

// Check for odd divisors from 3 up to the square root of the number

for (int i = 3; i <= Math.sqrt(number); i += 2) {

if (number % i == 0) {

return false; // Number is divisible by 'i', hence not prime

return true; // Number is prime

26. Write a Java Program to Display Armstrong Numbers Between Intervals Using Function
import java.util.Scanner;

public class ArmstrongNumbers {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter the lower limit of the interval: ");

int lower = scanner.nextInt();

System.out.print("Enter the upper limit of the interval: ");

int upper = scanner.nextInt();

System.out.println("Armstrong numbers between " + lower + " and " + upper + ":");

for (int num = lower; num <= upper; num++) {

if (isArmstrong(num)) {

System.out.print(num + " ");

}
scanner.close();

// Function to check if a number is Armstrong or not

public static boolean isArmstrong(int number) {

int originalNumber, remainder, result = 0;

originalNumber = number;

// Calculate sum of nth power of digits

while (originalNumber != 0) {

remainder = originalNumber % 10;

result += Math.pow(remainder, String.valueOf(number).length());

originalNumber /= 10;

// Check if number is equal to the sum of nth power of digits

if (result == number) {

return true;

} else {

return false;

27. Write a Java Program to Display Factors of a Number

1. Write a Java program to find the sum of even numbers in an integer array
public class SumOfEvenNumbers {
public static void main(String[] args) {
// Sample array
int[] array = {2, 5, 8, 3, 10, 6, 7, 1};

// Initialize sum
int sum = 0;
// Iterate through the array
for (int i = 0; i < array.length; i++) {
// Check if the current element is even
if (array[i] % 2 == 0) {
sum += array[i]; // Add even number to sum
}
}

// Print the sum of even numbers


System.out.println("Sum of even numbers in the array: " + sum);
}
}

2. Write a Java program to find the sum of diagonal elements in a 2D array.


public class DiagonalSum {
public static void main(String[] args) {
// Sample 2D array (square matrix)
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

// Calculate sum of main diagonal elements


int sum = 0;
int n = matrix.length; // Assuming matrix is a square matrix

for (int i = 0; i < n; i++) {


sum += matrix[i][i]; // Sum of elements where row index equals column index
}

// Print the sum of diagonal elements


System.out.println("Sum of diagonal elements: " + sum);
}
}

3. Write a Java program to find duplicate elements in a 1D array and find their frequency of occurrence.
import java.util.HashMap;
import java.util.Map;

public class DuplicateElements {


public static void main(String[] args) {
// Sample array with duplicate elements
int[] array = { 4, 3, 7, 8, 7, 9, 3, 4, 2, 7, 7, 9, 5 };

// Create a HashMap to store element and its frequency


Map<Integer, Integer> elementCountMap = new HashMap<>();

// Iterate through the array to count occurrences of each element


for (int i = 0; i < array.length; i++) {
int key = array[i];
if (elementCountMap.containsKey(key)) {
// If element is already present in the map, increment its count
elementCountMap.put(key, elementCountMap.get(key) + 1);
} else {
// If element is encountered for the first time, add it to the map with count 1
elementCountMap.put(key, 1);
}
}

// Print duplicate elements along with their frequencies


System.out.println("Duplicate elements in the array with their frequencies:");
for (Map.Entry<Integer, Integer> entry : elementCountMap.entrySet()) {
if (entry.getValue() > 1) {
System.out.println(entry.getKey() + " - " + entry.getValue() + " times");
}
}
}
}
4. Create a class ThreeD . The class should have volume() and surfaceArea() to calculate volume and
surface area of sphere, cone and cylinder. Must apply the concept of overloading .

ThreeD Class
// ThreeD class

class ThreeD {
private static final double PI = 3.14159; // Constant PI value

// Method to calculate volume of a sphere


public double volume(double radius) {
return (4.0 / 3.0) * PI * radius * radius * radius;
}

// Method to calculate surface area of a sphere


public double surfaceArea(double radius) {
return 4 * PI * radius * radius;
}

// Method to calculate volume of a cone


public double volume(double radius, double height) {
return (1.0 / 3.0) * PI * radius * radius * height;
}

// Method to calculate surface area of a cone


public double surfaceArea(double radius, double slantHeight) {
double baseArea = PI * radius * radius;
double sideArea = PI * radius * slantHeight;
return baseArea + sideArea;
}

// Method to calculate volume of a cylinder


public double volume(double radius, double height, String type) {
if (type.equalsIgnoreCase("cylinder")) {
return PI * radius * radius * height;
} else {
return 0.0;
}
}

// Method to calculate surface area of a cylinder


public double surfaceArea(double radius, double height, String type) {
if (type.equalsIgnoreCase("cylinder")) {
double baseArea = PI * radius * radius;
double lateralArea = 2 * PI * radius * height;
return 2 * baseArea + lateralArea;
} else {
return 0.0;
}
}
}
// Main class to test the ThreeD classpublic class ThreeDTest {
public static void main(String[] args) {
ThreeD shape = new ThreeD();

// Calculate volume and surface area of a sphere with radius 5.0


double sphereRadius = 5.0;
double sphereVolume = shape.volume(sphereRadius);
double sphereSurfaceArea = shape.surfaceArea(sphereRadius);

System.out.println("Sphere:");
System.out.println("Radius: " + sphereRadius);
System.out.println("Volume: " + sphereVolume);
System.out.println("Surface Area: " + sphereSurfaceArea);
System.out.println();

// Calculate volume and surface area of a cone with radius 3.0 and slant height 4.0
double coneRadius = 3.0;
double coneHeight = 4.0;
double coneVolume = shape.volume(coneRadius, coneHeight);
double coneSurfaceArea = shape.surfaceArea(coneRadius, coneHeight);
System.out.println("Cone:");
System.out.println("Radius: " + coneRadius);
System.out.println("Height: " + coneHeight);
System.out.println("Volume: " + coneVolume);
System.out.println("Surface Area: " + coneSurfaceArea);
System.out.println();

// Calculate volume and surface area of a cylinder with radius 2.0 and height 6.0
double cylinderRadius = 2.0;
double cylinderHeight = 6.0;
String cylinderType = "cylinder";
double cylinderVolume = shape.volume(cylinderRadius, cylinderHeight, cylinderType);
double cylinderSurfaceArea = shape.surfaceArea(cylinderRadius, cylinderHeight,
cylinderType);

System.out.println("Cylinder:");
System.out.println("Radius: " + cylinderRadius);
System.out.println("Height: " + cylinderHeight);
System.out.println("Volume: " + cylinderVolume);
System.out.println("Surface Area: " + cylinderSurfaceArea);
}
}

5. Create a class Computer with properties model_no(auto generated),RAM_size, Processor_name,Price.


Create the class with three different types of constructor(parameterized, non parameterized, object as
parameter). Display() will display all properties.

Computer Class
// Computer class
class Computer {
private static int nextModelNo = 1; // Auto-generated model number
private int model_no;
private int RAM_size;
private String Processor_name;
private double Price;
// Parameterized constructor
public Computer(int RAM_size, String Processor_name, double Price) {
this.model_no = nextModelNo++;
this.RAM_size = RAM_size;
this.Processor_name = Processor_name;
this.Price = Price;
}

// Non-parameterized constructor
public Computer() {
this.model_no = nextModelNo++;
this.RAM_size = 0;
this.Processor_name = "Unknown";
this.Price = 0.0;
}

// Constructor with object as parameter


public Computer(Computer otherComputer) {
this.model_no = nextModelNo++;
this.RAM_size = otherComputer.RAM_size;
this.Processor_name = otherComputer.Processor_name;
this.Price = otherComputer.Price;
}

// Method to display all properties of the computer


public void display() {
System.out.println("Model Number: " + model_no);
System.out.println("RAM Size: " + RAM_size + " GB");
System.out.println("Processor Name: " + Processor_name);
System.out.println("Price: $" + Price);
}
}
// Main class to test the Computer classpublic class ComputerTest {
public static void main(String[] args) {
// Create computers using different constructors
Computer comp1 = new Computer(16, "Intel Core i7", 1200.0);
Computer comp2 = new Computer();
Computer comp3 = new Computer(comp1); // Using object as parameter

// Display details of each computer


System.out.println("Computer 1:");
comp1.display();
System.out.println();

System.out.println("Computer 2:");
comp2.display();
System.out.println();

System.out.println("Computer 3 (Copy of Computer 1):");


comp3.display();
}
}

6. Create a class Box . The class should have volume() and surfaceArea() to calculate volume and surface
area of a box. Must apply the concept of overloading .

Box Class

// Box class
class Box {
// Method to calculate volume of a cube
public double volume(double side) {
return side * side * side;
}

// Method to calculate surface area of a cube


public double surfaceArea(double side) {
return 6 * side * side;
}

// Method to calculate volume of a rectangular box


public double volume(double length, double width, double height) {
return length * width * height;
}

// Method to calculate surface area of a rectangular box


public double surfaceArea(double length, double width, double height) {
return 2 * ((length * width) + (width * height) + (height * length));
}
}
// Main class to test the Box classpublic class BoxTest {
public static void main(String[] args) {
// Create a Box object
Box box = new Box();

// Calculate volume and surface area of a cube with side 5.0


double cubeSide = 5.0;
double cubeVolume = box.volume(cubeSide);
double cubeSurfaceArea = box.surfaceArea(cubeSide);

System.out.println("Cube - Side: " + cubeSide);


System.out.println("Cube - Volume: " + cubeVolume);
System.out.println("Cube - Surface Area: " + cubeSurfaceArea);
System.out.println();

// Calculate volume and surface area of a rectangular box with dimensions 3.0 x 4.0 x
5.0
double length = 3.0;
double width = 4.0;
double height = 5.0;
double rectangularVolume = box.volume(length, width, height);
double rectangularSurfaceArea = box.surfaceArea(length, width, height);

System.out.println("Rectangular Box - Dimensions: " + length + " x " + width + " x " +
height);
System.out.println("Rectangular Box - Volume: " + rectangularVolume);
System.out.println("Rectangular Box - Surface Area: " + rectangularSurfaceArea);
}
}
7. Create a class Circle with properties radius. PI value should be declare as constant and shared mode.
The class should have method Area(), Perimeter() and display(). display() will show the value of
radius,area and perimeter. Only display() is accessible through object.

Circle Class

// Circle class
class Circle {
private double radius;
private static final double PI = 3.14159; // Constant PI value

// Constructor to initialize radius


public Circle(double radius) {
this.radius = radius;
}

// Method to calculate area of the circle


public double area() {
return PI * radius * radius;
}

// Method to calculate perimeter (circumference) of the circle


public double perimeter() {
return 2 * PI * radius;
}

// Method to display radius, area, and perimeter of the circle


public void display() {
System.out.println("Radius: " + radius);
System.out.println("Area: " + area());
System.out.println("Perimeter: " + perimeter());
}
}
// Main class to test the Circle classpublic class CircleTest {
public static void main(String[] args) {
// Create a Circle object with radius 5.0
Circle circle = new Circle(5.0);

// Display information about the circle


circle.display();
}
}

8. Write a class, Commission, which has an instance variable, sales; an appropriate constructor; and a
method, commission() that returns the commission. Now write a demo class to test the Commission
class by reading a sale from the user, using it to create a Commission object after validating that the
value is not negative. Finally, call the commission() method to get and print the commission. If the sales
are negative, your demo should print the message “Invalid Input”.

Commission Class

// Commission class
class Commission {
private double sales;

// Constructor
public Commission(double sales) {
this.sales = sales;
}

// Method to calculate commission


public double calculateCommission() {
if (sales < 0) {
return -1; // Indicates invalid input
} else if (sales >= 0 && sales <= 1000) {
return sales * 0.02; // 2% commission for sales <= $1000
} else if (sales > 1000 && sales <= 5000) {
return 20 + (sales - 1000) * 0.05; // $20 plus 5% commission for sales >
$1000 and <= $5000
} else {
return 270 + (sales - 5000) * 0.07; // $270 plus 7% commission for sales >
$5000
}
}
}

CommissionDemo Class

import java.util.Scanner;
// Demo class to test Commission classpublic class CommissionDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Prompt user to enter sales amount


System.out.print("Enter sales amount: ");
double sales = scanner.nextDouble();

// Validate input and create Commission object


if (sales < 0) {
System.out.println("Invalid Input");
} else {
Commission commissionObj = new Commission(sales);
double commission = commissionObj.calculateCommission();

if (commission == -1) {
System.out.println("Invalid Input");
} else {
System.out.println("Commission: $" + commission);
}
}

scanner.close();
}
}

1. Write a Java program to create a class called Vehicle with a method called drive(). Create a subclass
called Car that overrides the drive() method to print "Repairing a car".
// Base class Vehicle
class Vehicle {
// Method to drive (to be overridden)
public void drive() {
System.out.println("Driving a vehicle");
}
}

// Derived class Car


class Car extends Vehicle {
// Override the drive method to repair a car
@Override
public void drive() {
System.out.println("Repairing a car");
}
}

// Main class to test the implementation


public class VehicleTest {
public static void main(String[] args) {
// Create a Vehicle object
Vehicle vehicle = new Vehicle();

// Test drive method of Vehicle


vehicle.drive(); // Output: Driving a vehicle

// Create a Car object


Car car = new Car();

// Test drive method of Car


car.drive(); // Output: Repairing a car
}
}

2. Write a Java program to create a class called Shape with a method called getArea(). Create a subclass
called Rectangle that overrides the getArea() method to calculate the area of a rectangle.
// Base class Shape
class Shape {
// Method to calculate area (to be overridden)
public double getArea() {
return 0; // Default implementation returns 0
}
}

// Derived class Rectangle


class Rectangle extends Shape {
private double length;
private double width;

// Constructor to initialize length and width


public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}

// Override the getArea method to calculate area of rectangle


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

// Method to display information about the rectangle


public void displayInfo() {
System.out.println("Rectangle Length: " + length);
System.out.println("Rectangle Width: " + width);
System.out.println("Rectangle Area: " + getArea());
}
}

// Main class to test the implementation


public class ShapeTest {
public static void main(String[] args) {
// Create a Rectangle object with given dimensions
Rectangle rectangle = new Rectangle(5.0, 3.0);

// Display information about the rectangle


rectangle.displayInfo();
}
}
3. Write a Java program to create a class called Employee with methods called work() and getSalary().
Create a subclass called HRManager that overrides the work() method and adds a new method called
addEmployee().
// Base class Employee
class Employee {
protected double salary;

// Constructor
public Employee(double salary) {
this.salary = salary;
}

// Method to perform work


public void work() {
System.out.println("Employee is working.");
}

// Method to get salary


public double getSalary() {
return salary;
}
}

// Derived class HRManager


class HRManager extends Employee {
// Constructor
public HRManager(double salary) {
super(salary);
}

// Override work method


@Override
public void work() {
System.out.println("HR Manager is managing HR tasks.");
}

// Method specific to HRManager to add an employee


public void addEmployee() {
System.out.println("HR Manager is adding a new employee.");
}
}
// Main class to test the implementation
public class EmployeeTest {
public static void main(String[] args) {
// Create an Employee object
Employee emp = new Employee(50000);

// Test Employee methods


emp.work();
System.out.println("Employee Salary: " + emp.getSalary());

System.out.println();

// Create an HRManager object


HRManager hrManager = new HRManager(80000);

// Test HRManager methods


hrManager.work();
System.out.println("HR Manager Salary: " + hrManager.getSalary());
hrManager.addEmployee();
}
}

4. Write a Java program to create a class known as "BankAccount" with methods called deposit() and
withdraw(). Create a subclass called SavingsAccount that overrides the withdraw() method to prevent
withdrawals if the account balance falls below one hundred.
// Base class BankAccount
class BankAccount {
protected double balance;

// Constructor
public BankAccount() {
this.balance = 0;
}

// Method to deposit money


public void deposit(double amount) {
if (amount > 0) {
balance += amount;
System.out.println(amount + " deposited successfully.");
} else {
System.out.println("Invalid amount. Deposit failed.");
}
}

// Method to withdraw money


public void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
System.out.println(amount + " withdrawn successfully.");
} else {
System.out.println("Insufficient funds or invalid amount. Withdrawal failed.");
}
}

// Method to display balance


public void displayBalance() {
System.out.println("Current Balance: " + balance);
}
}

// Derived class SavingsAccount


class SavingsAccount extends BankAccount {
private static final double MIN_BALANCE = 100.0;

// Override withdraw method to check minimum balance


@Override
public void withdraw(double amount) {
if (amount > 0 && balance - amount >= MIN_BALANCE) {
balance -= amount;
System.out.println(amount + " withdrawn successfully.");
} else {
System.out.println("Withdrawal failed. Minimum balance of " + MIN_BALANCE + " required.");
}
}
}

// Main class to test the implementation


public class BankAccountTest {
public static void main(String[] args) {
// Create a SavingsAccount object
SavingsAccount savingsAccount = new SavingsAccount();

// Deposit and withdraw operations


savingsAccount.deposit(500);
savingsAccount.withdraw(200);
savingsAccount.displayBalance();

savingsAccount.withdraw(400); // Should fail due to minimum balance constraint


savingsAccount.displayBalance();

savingsAccount.withdraw(50); // Should succeed


savingsAccount.displayBalance();
}
}

5. Write a Java program to create a class called Shape with methods called getPerimeter() and getArea().
Create a subclass called Circle that overrides the getPerimeter() and getArea() methods to calculate the
area and perimeter of a circle.
// Base class Shape
class Shape {
// Method to get the perimeter (to be overridden)
public double getPerimeter() {
return 0;
}

// Method to get the area (to be overridden)


public double getArea() {
return 0;
}
}

// Derived class Circle


class Circle extends Shape {
private double radius;

// Constructor to initialize radius


public Circle(double radius) {
this.radius = radius;
}
// Override the getPerimeter method
@Override
public double getPerimeter() {
return 2 * Math.PI * radius;
}

// Override the getArea method


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

// Method to display information about the circle


public void displayInfo() {
System.out.println("Radius: " + radius);
System.out.println("Perimeter: " + getPerimeter());
System.out.println("Area: " + getArea());
}
}

// Main class to test the implementation


public class ShapeTest {
public static void main(String[] args) {
// Create a Circle object with a given radius
Circle circle = new Circle(5.0);

// Display information about the circle


circle.displayInfo();
}
}

6. Write a Java program that creates a class hierarchy for employees of a company. The base class
should be Employee, with subclasses Manager, Developer, and Programmer. Each subclass should have
properties such as name, address, salary, and job title. Implement methods for calculating bonuses,
generating performance reports, and managing projects.

// Base class Employee


class Employee {
protected String name;
protected String address;
protected double salary;
protected String jobTitle;

public Employee(String name, String address, double salary, String jobTitle) {


this.name = name;
this.address = address;
this.salary = salary;
this.jobTitle = jobTitle;
}

public double calculateBonus() {


return salary * 0.10; // Default bonus of 10% of salary
}

public String generatePerformanceReport() {


return "Performance report for " + jobTitle + " " + name + ": Satisfactory.";
}

public void displayInfo() {


System.out.println("Name: " + name);
System.out.println("Address: " + address);
System.out.println("Salary: " + salary);
System.out.println("Job Title: " + jobTitle);
}
}

// Derived class Manager


class Manager extends Employee {
private String department;

public Manager(String name, String address, double salary, String jobTitle, String department) {
super(name, address, salary, jobTitle);
this.department = department;
}

@Override
public double calculateBonus() {
return salary * 0.15; // Managers get a 15% bonus
}

@Override
public String generatePerformanceReport() {
return "Performance report for Manager " + name + " in " + department + ": Excellent leadership and
management skills.";
}

public void manageProject(String projectName) {


System.out.println("Manager " + name + " is managing the project: " + projectName);
}

@Override
public void displayInfo() {
super.displayInfo();
System.out.println("Department: " + department);
}
}

// Derived class Developer


class Developer extends Employee {
private String programmingLanguage;

public Developer(String name, String address, double salary, String jobTitle, String
programmingLanguage) {
super(name, address, salary, jobTitle);
this.programmingLanguage = programmingLanguage;
}

@Override
public double calculateBonus() {
return salary * 0.12; // Developers get a 12% bonus
}

@Override
public String generatePerformanceReport() {
return "Performance report for Developer " + name + ": Outstanding coding and development skills.";
}
public void developSoftware(String softwareName) {
System.out.println("Developer " + name + " is developing the software: " + softwareName + " using " +
programmingLanguage);
}

@Override
public void displayInfo() {
super.displayInfo();
System.out.println("Programming Language: " + programmingLanguage);
}
}

// Derived class Programmer


class Programmer extends Employee {
private String[] projects;

public Programmer(String name, String address, double salary, String jobTitle, String[] projects) {
super(name, address, salary, jobTitle);
this.projects = projects;
}

@Override
public double calculateBonus() {
return salary * 0.10; // Programmers get a 10% bonus
}

@Override
public String generatePerformanceReport() {
return "Performance report for Programmer " + name + ": Highly efficient in multiple projects.";
}

public void writeCode(String projectName) {


System.out.println("Programmer " + name + " is writing code for the project: " + projectName);
}

@Override
public void displayInfo() {
super.displayInfo();
System.out.println("Projects: " + String.join(", ", projects));
}
}

// Main class to test the implementation


public class EmployeeTest {
public static void main(String[] args) {
Employee manager = new Manager("Alice", "123 Main St", 90000, "Manager", "IT");
Employee developer = new Developer("Bob", "456 Elm St", 80000, "Developer", "Java");
Employee programmer = new Programmer("Charlie", "789 Oak St", 70000, "Programmer", new String[]
{"ProjectA", "ProjectB"});

System.out.println("Manager Info:");
manager.displayInfo();
System.out.println("Bonus: " + manager.calculateBonus());
System.out.println(manager.generatePerformanceReport());
((Manager) manager).manageProject("ProjectX");
System.out.println();

System.out.println("Developer Info:");
developer.displayInfo();
System.out.println("Bonus: " + developer.calculateBonus());
System.out.println(developer.generatePerformanceReport());
((Developer) developer).developSoftware("SoftwareY");
System.out.println();

System.out.println("Programmer Info:");
programmer.displayInfo();
System.out.println("Bonus: " + programmer.calculateBonus());
System.out.println(programmer.generatePerformanceReport());
((Programmer) programmer).writeCode("ProjectB");
}
}

7. Create a general class ThreeDObject and derive the classes Box, Cube, Cylinder and Cone from it. The
class ThreeDObject has methods wholeSurfaceArea ( ) and volume ( ). Override these two methods in
each of the derived classes to calculate the volume and whole surface area of each type of three-
dimensional objects. The dimensions of the objects are to be taken from the users and passed through
the respective constructors of each derived class. Write a main method to test these classes.
import java.util.Scanner;
// Base class ThreeDObject
abstract class ThreeDObject {
abstract double wholeSurfaceArea();
abstract double volume();
}

// Derived class Box


class Box extends ThreeDObject {
private double length, width, height;

public Box(double length, double width, double height) {


this.length = length;
this.width = width;
this.height = height;
}

@Override
double wholeSurfaceArea() {
return 2 * (length * width + width * height + height * length);
}

@Override
double volume() {
return length * width * height;
}
}

// Derived class Cube


class Cube extends ThreeDObject {
private double side;

public Cube(double side) {


this.side = side;
}

@Override
double wholeSurfaceArea() {
return 6 * side * side;
}

@Override
double volume() {
return side * side * side;
}
}

// Derived class Cylinder


class Cylinder extends ThreeDObject {
private double radius, height;

public Cylinder(double radius, double height) {


this.radius = radius;
this.height = height;
}

@Override
double wholeSurfaceArea() {
return 2 * Math.PI * radius * (radius + height);
}

@Override
double volume() {
return Math.PI * radius * radius * height;
}
}

// Derived class Cone


class Cone extends ThreeDObject {
private double radius, height;

public Cone(double radius, double height) {


this.radius = radius;
this.height = height;
}

@Override
double wholeSurfaceArea() {
double slantHeight = Math.sqrt(radius * radius + height * height);
return Math.PI * radius * (radius + slantHeight);
}

@Override
double volume() {
return (1.0 / 3) * Math.PI * radius * radius * height;
}
}
// Main class to test the implementation
public class ThreeDObjectTest {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.println("Enter the dimensions for the Box (length, width, height): ");
double length = scanner.nextDouble();
double width = scanner.nextDouble();
double height = scanner.nextDouble();
ThreeDObject box = new Box(length, width, height);
System.out.println("Box Surface Area: " + box.wholeSurfaceArea());
System.out.println("Box Volume: " + box.volume());

System.out.println("\nEnter the side length for the Cube: ");


double side = scanner.nextDouble();
ThreeDObject cube = new Cube(side);
System.out.println("Cube Surface Area: " + cube.wholeSurfaceArea());
System.out.println("Cube Volume: " + cube.volume());

System.out.println("\nEnter the dimensions for the Cylinder (radius, height): ");


double radius = scanner.nextDouble();
double cylHeight = scanner.nextDouble();
ThreeDObject cylinder = new Cylinder(radius, cylHeight);
System.out.println("Cylinder Surface Area: " + cylinder.wholeSurfaceArea());
System.out.println("Cylinder Volume: " + cylinder.volume());

System.out.println("\nEnter the dimensions for the Cone (radius, height): ");


double coneRadius = scanner.nextDouble();
double coneHeight = scanner.nextDouble();
ThreeDObject cone = new Cone(coneRadius, coneHeight);
System.out.println("Cone Surface Area: " + cone.wholeSurfaceArea());
System.out.println("Cone Volume: " + cone.volume());

scanner.close();
}

8. An educational institution maintains a database of its employees. The database is divided into a
number of classes whose hierarchical relationships are shown below. Write all the classes and define the
methods to create the database and retrieve individual information as and when needed. Write a driver
program to test the classes. Staff (code, name) Teacher (subject, publication) is a Staff Officer (grade) is a
Staff Typist (speed) is a Staff RegularTypist (remuneration) is a Typist CasualTypist (daily wages) is a
Typist.
// Base class Staff
class Staff {
private int code;
private String name;

public Staff(int code, String name) {


this.code = code;
this.name = name;
}

public int getCode() {


return code;
}

public String getName() {


return name;
}

public void displayInfo() {


System.out.println("Code: " + code + ", Name: " + name);
}
}

// Derived class Teacher


class Teacher extends Staff {
private String subject;
private String publication;

public Teacher(int code, String name, String subject, String publication) {


super(code, name);
this.subject = subject;
this.publication = publication;
}

public String getSubject() {


return subject;
}

public String getPublication() {


return publication;
}

@Override
public void displayInfo() {
super.displayInfo();
System.out.println("Subject: " + subject + ", Publication: " + publication);
}
}

// Derived class Officer


class Officer extends Staff {
private String grade;

public Officer(int code, String name, String grade) {


super(code, name);
this.grade = grade;
}

public String getGrade() {


return grade;
}

@Override
public void displayInfo() {
super.displayInfo();
System.out.println("Grade: " + grade);
}
}

// Derived class Typist


class Typist extends Staff {
private int speed;

public Typist(int code, String name, int speed) {


super(code, name);
this.speed = speed;
}

public int getSpeed() {


return speed;
}

@Override
public void displayInfo() {
super.displayInfo();
System.out.println("Speed: " + speed + " wpm");
}
}

// Derived class RegularTypist


class RegularTypist extends Typist {
private double remuneration;

public RegularTypist(int code, String name, int speed, double remuneration) {


super(code, name, speed);
this.remuneration = remuneration;
}

public double getRemuneration() {


return remuneration;
}

@Override
public void displayInfo() {
super.displayInfo();
System.out.println("Remuneration: " + remuneration);
}
}

// Derived class CasualTypist


class CasualTypist extends Typist {
private double dailyWages;

public CasualTypist(int code, String name, int speed, double dailyWages) {


super(code, name, speed);
this.dailyWages = dailyWages;
}

public double getDailyWages() {


return dailyWages;
}

@Override
public void displayInfo() {
super.displayInfo();
System.out.println("Daily Wages: " + dailyWages);
}
}
// Driver class to test the classes
public class EducationalInstitution {
public static void main(String[] args) {
Staff staff1 = new Teacher(101, "Alice", "Mathematics", "OUP");
Staff staff2 = new Officer(102, "Bob", "A");
Staff staff3 = new RegularTypist(103, "Charlie", 70, 3000.0);
Staff staff4 = new CasualTypist(104, "David", 60, 200.0);

staff1.displayInfo();
System.out.println();
staff2.displayInfo();
System.out.println();
staff3.displayInfo();
System.out.println();
staff4.displayInfo();
}
}

1. Write a Java program to create an interface Shape with the getArea(), getPerimeter() method. Create
three classes Rectangle, Circle, and Triangle that implement the Shape interface. Implement the
getArea() method for each of the three classes.
// Define the Shape interface

interface Shape {

double getArea();

double getPerimeter();

// Implement the Circle class

class Circle implements Shape {

private final double radius;

public Circle(double radius) {

this.radius = radius;

@Override

public double getArea() {

return Math.PI * radius * radius;

}
@Override

public double getPerimeter() {

return 2 * Math.PI * radius;

// Implement the Rectangle class

class Rectangle implements Shape {

private final double length;

private final double width;

public Rectangle(double length, double width) {

this.length = length;

this.width = width;

@Override

public double getArea() {

return length * width;

@Override

public double getPerimeter() {

return 2 * (length + width);

// Implement the Triangle class

class Triangle implements Shape {

private final double side1;

private final double side2;

private final double side3;

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


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;

// Main class to test the implementation

public class ShapeTest {

public static void main(String[] args) {

Shape circle = new Circle(5);

System.out.println("Circle Area: " + circle.getArea());

System.out.println("Circle Perimeter: " + circle.getPerimeter());

Shape rectangle = new Rectangle(4, 6);

System.out.println("Rectangle Area: " + rectangle.getArea());

System.out.println("Rectangle Perimeter: " + rectangle.getPerimeter());

Shape triangle = new Triangle(3, 4, 5);

System.out.println("Triangle Area: " + triangle.getArea());

System.out.println("Triangle Perimeter: " + triangle.getPerimeter());

}
2. Write a Java programming to create a banking system with interface Account and classes
SavingsAccount, and CurrentAccount. The bank should have a list of accounts and methods for adding
them. Accounts should be an interface with methods to deposit, withdraw, calculate interest, and view
balances. SavingsAccount and CurrentAccount should implement the Account interface and have their
own unique methods.
import java.util.ArrayList;

import java.util.List;

// Define the Account interface

interface Account {

void deposit(double amount);

void withdraw(double amount);

double calculateInterest();

double getBalance();

void viewBalance();

// Implement the SavingsAccount class

class SavingsAccount implements Account {

private double balance;

private double interestRate;

public SavingsAccount(double initialBalance, double interestRate) {

this.balance = initialBalance;

this.interestRate = interestRate;

@Override

public void deposit(double amount) {

if (amount > 0) {

balance += amount;

System.out.println("Deposited: " + amount);

@Override
public void withdraw(double amount) {

if (amount > 0 && balance >= amount) {

balance -= amount;

System.out.println("Withdrew: " + amount);

} else {

System.out.println("Insufficient funds.");

@Override

public double calculateInterest() {

return balance * interestRate / 100;

@Override

public double getBalance() {

return balance;

@Override

public void viewBalance() {

System.out.println("Savings Account Balance: " + balance);

// Implement the CurrentAccount class

class CurrentAccount implements Account {

private double balance;

private double overdraftLimit;

public CurrentAccount(double initialBalance, double overdraftLimit) {

this.balance = initialBalance;

this.overdraftLimit = overdraftLimit;

}
@Override

public void deposit(double amount) {

if (amount > 0) {

balance += amount;

System.out.println("Deposited: " + amount);

@Override

public void withdraw(double amount) {

if (amount > 0 && balance + overdraftLimit >= amount) {

balance -= amount;

System.out.println("Withdrew: " + amount);

} else {

System.out.println("Exceeded overdraft limit.");

@Override

public double calculateInterest() {

// Current accounts typically do not have interest, so return 0

return 0;

@Override

public double getBalance() {

return balance;

@Override

public void viewBalance() {

System.out.println("Current Account Balance: " + balance);

}
// Implement the Bank class

class Bank {

private List<Account> accounts;

public Bank() {

this.accounts = new ArrayList<>();

public void addAccount(Account account) {

accounts.add(account);

System.out.println("Account added.");

public void viewAllBalances() {

for (Account account : accounts) {

account.viewBalance();

// Main class to test the implementation

public class BankingSystem {

public static void main(String[] args) {

Bank bank = new Bank();

SavingsAccount savingsAccount = new SavingsAccount(1000, 5);

CurrentAccount currentAccount = new CurrentAccount(500, 1000);

bank.addAccount(savingsAccount);

bank.addAccount(currentAccount);

savingsAccount.deposit(500);

savingsAccount.withdraw(200);

System.out.println("Savings Account Interest: " + savingsAccount.calculateInterest());


currentAccount.deposit(300);

currentAccount.withdraw(700);

currentAccount.withdraw(200);

System.out.println("Current Account Interest: " + currentAccount.calculateInterest());

bank.viewAllBalances();

3. Write a Java program to create an interface Sortable with a method sort() that sorts an array of
integers in ascending order. Create two classes BubbleSort and SelectionSort that implement the
Sortable interface and provide their own implementations of the sort() method.
package Assinment4;

public interface Sortable {


int[] sort(int[] a);
}
package Assinment4;

public class BubbleSort implements Sortable{

@Override
public int[] sort(int[] a) {
// TODO Auto-generated method stub
int n = a.length;
for (int i = 0; i < n - 1; i++) {
for (int j = 1; j < n; j++) {
if (a[j-1] > a[j]) {
// swap arr[j] and arr[j+1]
int temp = a[j-1];
a[j-1] = a[j];
a[j] = temp;
}
}
}
return a;

}
package Assinment4;

public class SelectionSort implements Sortable{


@Override
public int[] sort(int[] a) {
// TODO Auto-generated method stub
for(int i=0;i<a.length-1;i++) {
int small=i;
for(int j=i+1;j<a.length;j++) {
if(a[j]<a[i]) {
small=j;
}
}
int temp=a[i];
a[i]=a[small];
a[small]=temp;
}
return a;
}

}
package Assinment4;

import java.util.Scanner;

public class SortableMain {

public static void main(String[] args) {


// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
int n;
System.out.println("enter the number of elements:");
n=sc.nextInt();
int a[]=new int[n];
System.out.println("enter the data:");
for(int i=0;i<a.length;i++) {
a[i]=sc.nextInt();
}
System.out.println("The Array:");
for(int i=0;i<a.length;i++)
System.out.print(a[i]+"\t");
System.out.println();

Sortable ob=new BubbleSort();


int b[]=ob.sort(a);
System.out.println("After Bubble sort:");
for(int i=0;i<b.length;i++)
System.out.print(b[i]+"\t");
System.out.println();

Sortable ob2=new SelectionSort();


int c[]=ob2.sort(a);
System.out.println("After Selection sort::");
for(int i=0;i<c.length;i++)
System.out.print(c[i]+"\t");
System.out.println();
}

4. Write a program to check if the letter 'e' is present in the word 'Umbrella'.
package Assinment4;

public class Ass4 {

public static void main(String[] args) {


// TODO Auto-generated method stub
String s="Umbrella";
for(int i=0;i<s.length();i++) {
if(s.charAt(i)=='e') {
System.out.println("The letter 'e' is present
in the word 'Umbrella'.");
}
}

}
5. Write a program that takes your full name as input and displays the abbreviations of the first and
middle names except the last name which is displayed as it is. For example, if your name is Robert Brett
Roser, then the output should be R.B.Roser.
package Assinment4;

import java.util.Scanner;

public class Ass5 {

public static void main(String[] args) {


// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
System.out.println("Enter your name:");
String name=sc.nextLine();
String []s=name.split(" ");
String s2="";
for(int i=0;i<s.length;i++) {
if(i==s.length-1) {
s2=s2.concat(s[i]);
}
else {
s2=s2.concat(s[i].charAt(0)+".");
}
}
System.out.println("Your name is "+s2);
}

6. Write a Java program to compare a given string to the specified character sequence
class HelloWorld {
public static void main(String[] args) {
String s1="today is good day";
String s2="days";
boolean f=false;
for(int i=0;i<s1.length()-s2.length();i++){
if(s1.substring(i,i+s2.length()).equals(s2)){
f=true;
break;
}
}
if(f){
System.out.println("found");
}
else{
System.out.println("not found");
}

}
}
7. Write a Java program to Swap Two Strings without Third String Variable.
package Assinment4;

import java.util.Scanner;

public class Ass7 {


public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc= new Scanner(System.in);

// Input two strings


System.out.print("Enter the first string: ");
String s1 = sc.nextLine();
System.out.print("Enter the second string: ");
String s2 = sc.nextLine();

// Display strings before swapping


System.out.println("Strings before swapping:");
System.out.println("First string s1: " + s1);
System.out.println("Second string s2: " + s2);

// Swap strings without third variable


s1 = s1 + s2; // Concatenate both strings
s2 = s1.substring(0, s1.length() - s2.length()); //
Extract first string from concatenated string
s1 = s1.substring(s2.length()); // Extract second
string from concatenated string

// Display strings after swapping


System.out.println("\nStrings after swapping:");
System.out.println("s1: " + s1);
System.out.println("s2: " + s2);

8. Write a Java program to Reverse Each Word of a String


package Assinment4;

import java.util.Scanner;

public class Ass8 {

public static void main(String[] args) {


// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
System.out.println("Enter String:");
String str=sc.nextLine();
String []s=str.split(" ");
String str2="";
for(int i=0;i<s.length;i++) {
char[]s2=s[i].toCharArray();
String c="";
for(int j=s[i].length()-1;j>=0;j--) {
c=c+s2[j];
}
str2=str2+c+" ";
}
System.out.println(str2.trim());

9. Write a Java program to find the longest Palindromic Substring within a


string.
import java.util.Scanner;

public class LongestPalindromicSubstring {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String input = scanner.nextLine();
scanner.close();

String longestPalindrome = findLongestPalindrome(input);


if (longestPalindrome.isEmpty()) {
System.out.println("No palindromic substring found.");
} else {
System.out.println("Longest palindromic substring: " + longestPalindrome);
}
}

public static String findLongestPalindrome(String s) {


if (s == null || s.length() < 1) {
return "";
}
int start = 0;
int end = 0;
int maxLength = 1;

for (int i = 0; i < s.length(); i++) {


int len1 = expandAroundCenter(s, i, i); // For odd length palindromes like "aba"
int len2 = expandAroundCenter(s, i, i + 1); // For even length palindromes like "abba"
int len = Math.max(len1, len2);

if (len > maxLength) {


maxLength = len;
start = i - (len - 1) / 2;
end = i + len / 2;
}
}

if (maxLength == 1) {
return ""; // No palindromic substring found
}

return s.substring(start, end + 1);


}

private static int expandAroundCenter(String s, int left, int right) {


while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
left--;
right++;
}
return right - left - 1; // Length of the palindromic substring found
}
}
10. Write a Java program to find the second most frequent character in a given
string.
import java.util.Scanner;

public class SecondMostFrequentCharacter {


public static char[] findAndPrintSecondMostFrequentChars(String input) {
int[] charCount = new int[256]; // Assuming ASCII characters

// Count the frequency of each character


for (char c : input.toCharArray()) {
charCount[c]++;
}

// Find the first and second highest frequency counts


int firstMax = 0, secondMax = 0;
for (int count : charCount) {
if (count > firstMax) {
secondMax = firstMax;
firstMax = count;
} else if (count > secondMax && count != firstMax) {
secondMax = count;
}
}
String s="";
// Collect all characters with the second highest frequency count
// boolean found = false;
// System.out.print("The second most frequent character(s): ");
for (int i = 0; i < charCount.length; i++) {
if (charCount[i] == secondMax) {
s+=(char)i;
}
}
return s.toCharArray();
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a string: ");
String input = scanner.nextLine();
char[] str=findAndPrintSecondMostFrequentChars(input);
if(str.length>0 && str[0]!='\0'){
System.out.println("second most freq char:"+new String(str));
}
else{
System.out.println("No second most frequent character found.");
}

Ass 5
1. Write a Java program to create a method that takes a string as input and throws an exception if the
string does not contain vowels.
public class MyException extends Exception{
String str1;
MyException(String str2){
str1=str2;
}
public String toString(){
return ("Exception occured: "+str1);
}
}
package College;

import java.util.Scanner;

public class Exception1 {


public static void check(String s) throws MyException{
int f=0;
char c[]=s.toLowerCase().toCharArray();
for(int i=0; i<c.length;i++) {
if(c[i]=='a'||c[i]=='e'||c[i]=='i'||c[i]=='o'||
c[i]=='u') {
System.out.println("The string contain
vowels");
break;
}
else {
f++;
}
}
if(f==c.length) {
throw new MyException("The string does not
contain vowels");
}
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter a string");
String s=sc.nextLine();
try{
check(s);
}catch(Exception e){
System.out.println("Exception: "+e);
}

2. Create an user defined exception for the Bank class.


Class member: acc_id(auto generate), c_name, balance=0
Class methods: withdraw(), deposit(), display_details()
Exception arises on following consequences:
i) Negative value input for withdraw or deposit
ii) Withdrawing amount excess of balance
iii) Minimum Balance must be 1000.
package College;

public class MyException extends Exception{


String str1;
MyException(String str2){
str1=str2;
}
public String toString(){
return ("Exception occured: "+str1);
}
}

package College;

public class Bank {


static int c;
int acc_id;
String C_name;
double balance=0;
public Bank(String s){
acc_id=++c;
C_name=s;
//balance=0.0;
}
public void deposit(double amount)throws MyException{
if(amount<0){
throw new MyException("Negative amount is not
valid");
}
else{
balance+=amount;
System.out.println(amount+" amount deposited!");
// System.out.println("Account ID "+acc_id);
// System.out.println("Customer name "+C_name);
// System.out.println("Current balance "+balance);

}
}
public void withdraw(double amount)throws MyException{
if(amount<0){
throw new MyException("Negative amount is not
valid");
}
else{
if(amount>balance){
throw new MyException("Not allowed!! amount
is greater than balance");
}
else if(balance<=1000){
throw new MyException("Not allowed!! Balance
should be minimum 1000 rs.");
}
else{
balance-=amount;
System.out.println(amount+" amount
withdrawn!");
// System.out.println("Account ID "+acc_id);
// System.out.println("Customer name "+C_name);
// System.out.println("Current balance
"+balance);

}
}
}
public void display_details() {
System.out.println("Customer ID: "+acc_id+" Customer
Name: "+C_name+" BanK Balance: "+balance);
}

package College;

import java.util.Scanner;

public class BankMain {


public static void main(String args[]){
try{
Scanner sc=new Scanner(System.in);
System.out.println("Enter customer name");
String n=sc.nextLine();
Bank ob=new Bank(n);
while(true){
System.out.println("Enter 1 for deposit \nEnter 2
for withdraw \nEnter 3 for Display Bank Details \nEnter 4 for
exit");
System.out.println("Enter your choice:");
int ch=sc.nextInt();

if(ch==1){
System.out.println("Enter amount for
deposit");
double amount=sc.nextDouble();
ob.deposit(amount);
}
else if(ch==2){
System.out.println("Enter amount for
withdraw:");
double amount=sc.nextDouble();
ob.withdraw(amount);
}
else if(ch==3){
ob.display_details();
}
else{
System.out.println("End of program....");
break;
}
}
}catch(Exception exp){
System.out.println(exp);
}

3. Write a program called Factorial.java that computes factorials and catches the result in an array of
type long for reuse.
The long type of variable has its own range. For example 20! Is as high as the range of long type. So check
the argument passes and “throw an exception”,
if it is too big or too small.
If x is less than 0 throw an IllegalArgumentException with a message “Value of x must be positive”.
If x is above the length of the array throw an IllegalArgumentException with a message “Result will
overflow”. Here x is the value for which we want to find the factorial.
import java.util.Scanner;
public class Main {
public static long factorials[]=new long[20+1];
public static long factorialcheck(int x){
if(x<0){
throw new IllegalArgumentException("Value of x must be positive");
}
if(x>20){
throw new IllegalArgumentException("Result will overflow");
}
if(x ==0 || x==1){
return factorials[x]=1;
}
else{
factorials[x]=x*factorialcheck(x-1);
}
return factorials[x];
}
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number of terms:");
int terms=sc.nextInt();
int arr[]=new int[terms];
for(int i=0;i<terms;i++){
arr[i]=sc.nextInt();
}
for( int i:arr){
try{
System.out.println("factorial:"+factorialcheck(i));
}catch(IllegalArgumentException e){
System.out.println("Error:"+e);
}
}
}
}
4. Write a Java program to get following informations of the current executing thread :
the thread's name, ID, priority, state, daemon status, liveness, and interruption status
public class CurrentThreadInfo
{
public static void main(String[] args)
{
// Get the current executing thread
Thread currentThread = Thread.currentThread();
// Print thread information
System.out.println("Thread Name : " + currentThread.getName());
System.out.println("Thread ID : " + currentThread.getId());
System.out.println("Thread Priority : " + currentThread.getPriority());
System.out.println("Thread State : " + currentThread.getState());
System.out.println("Thread is Daemon : " + currentThread.isDaemon());
System.out.println("Thread is Alive : " + currentThread.isAlive());
System.out.println("Thread is Interrupted : " +currentThread.isInterrupted());
}}
5. Write a Java program in which total 4 threads should run. Set different priorities to the thread.
public class ThreadDemo extends Thread {
public void run()
{
System.out.println("Inside run method");
}
public static void main(String[] args)
{
ThreadDemo t1 = new ThreadDemo();
ThreadDemo t2 = new ThreadDemo();
ThreadDemo t3 = new ThreadDemo();
System.out.println("t1 thread priority : "+ t1.getPriority());
System.out.println("t2 thread priority : "+ t2.getPriority());
System.out.println("t3 thread priority : "+ t3.getPriority());
t1.setPriority(2);
t2.setPriority(5);
t3.setPriority(8);
System.out.println("t1 thread priority : "+ t1.getPriority());
System.out.println("t2 thread priority : "+ t2.getPriority());
System.out.println("t3 thread priority : "+ t3.getPriority());
System.out.println("Currently Executing Thread : "+ Thread.currentThread().getName());
System.out.println("Main thread priority : "+ Thread.currentThread().getPriority());
Thread.currentThread().setPriority(10);
System.out.println("Main thread priority : "+ Thread.currentThread().getPriority());
}
}
6. Write a Java program to create and start multiple threads that increment a shared counter variable
concurrently.
class IncrementThread extends Thread {
private Counter counter;
private int incrementsPerThread;
public IncrementThread(Counter counter, int incrementsPerThread) {
this.counter = counter;
this.incrementsPerThread = incrementsPerThread;
}

public void run() {


for (int i = 0; i < incrementsPerThread; i++) {
counter.increment();
}
}

class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public int getCount() {
return count;
}
}

public class Main {


public static void main(String[] args) {
Counter counter = new Counter();
int numThreads = 6;
int incrementsPerThread = 10000;
IncrementThread[] threads = new IncrementThread[numThreads];

for (int i = 0; i < numThreads; i++) {


threads[i] = new IncrementThread(counter, incrementsPerThread);
threads[i].start();
}
try {
for (IncrementThread thread: threads) {
thread.join();
}
} catch (InterruptedException e) {
e.printStackTrace();
}

System.out.println("Final count: " + counter.getCount());


}
}

7. Write a Java Program to Solve Producer Consumer Problem Using Synchronization.


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

class Buffer {
private Queue<Integer> queue = new LinkedList<>();
private int capacity;

public Buffer(int capacity) {


this.capacity = capacity;
}

public synchronized void produce(int value) throws InterruptedException {


while (queue.size() == capacity) {
wait();
}

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

notifyAll();
}

public synchronized int consume() throws InterruptedException {


while (queue.isEmpty()) {
wait();
}

int value = queue.poll();


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

notifyAll();
return value;
}
}

class Producer implements Runnable {


private Buffer buffer;

public Producer(Buffer buffer) {


this.buffer = buffer;
}

@Override
public void run() {
int value = 0;
while (true) {
try {
buffer.produce(value++);
Thread.sleep((int) (Math.random() * 1000));
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
}
}
}

class Consumer implements Runnable {


private Buffer buffer;

public Consumer(Buffer buffer) {


this.buffer = buffer;
}

@Override
public void run() {
while (true) {
try {
buffer.consume();
Thread.sleep((int) (Math.random() * 1000));
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
}
}
}

public class ProducerConsumerProblem {


public static void main(String[] args) {
Buffer buffer = new Buffer(5);

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


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

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

8. Write a Java Program to Solve Deadlock Using Thread.


Occhurence:
public class TestDeadlock{
public static void main(String args[]){
final String r1="Printer";
final String r2="Speaker";
Thread t1=new Thread(){
public void run(){
synchronized(r1){
System.out.println("Thread1:locked resource1");
try{Thread.sleep(100);}catch(Exception e){}
synchronized(r2){
System.out.println("Thread1:locked resource2");
}
}
}
};
Thread t2=new Thread(){
public void run(){
synchronized(r2){
System.out.println("Thread2:locked resource2");
try{Thread.sleep(100);}catch(Exception e){}
synchronized(r1){
System.out.println("Thread2:locked resource1");
}
}
}
};
t1.start();
t2.start();
}
}

Prevention:
public class TestDeadlock{
public static void main(String args[]){
final String r1="Printer";
final String r2="Speaker";
//t1 tries to lock r1 then r2
Thread t1=new Thread(){
public void run(){
synchronized(r1){
System.out.println("Thread1:locked resource1");
try{Thread.sleep(100);}catch(Exception e){}
}
synchronized(r2){
System.out.println("Thread1:locked resource2");
try{Thread.sleep(100);}catch(Exception e){}
}
}
};
//t2 tries to lock r2 then r1
Thread t2=new Thread(){
public void run(){
synchronized(r2){
System.out.println("Thread2:locked resource2");
try{Thread.sleep(100);}catch(Exception e){}
}
synchronized(r1){
System.out.println("Thread2:locked resource1");
try{Thread.sleep(100);}catch(Exception e){}
}
}
};
t1.start();
t2.start();
}
}

9. Write a Java program to demonstrate Semaphore usage for thread synchronization.


//SemaphoreExercise.java
import java.util.concurrent.Semaphore;
public class SemaphoreExercise {
private static final int NUM_THREADS = 5;
private static final int NUM_PERMITS = 2;
public static void main(String[] args) {
Semaphore semaphore = new Semaphore(NUM_PERMITS);
Thread[] threads = new Thread[NUM_THREADS];
for (int i = 0; i < NUM_THREADS; i++) {
threads[i] = new Thread(new Worker(semaphore));
threads[i].start();
}
try {
for (Thread thread: threads) {
thread.join();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
static class Worker implements Runnable {
private Semaphore semaphore;
public Worker(Semaphore semaphore) {
this.semaphore = semaphore;
}

public void run() {


try {
semaphore.acquire();
// Perform work that requires the semaphore
System.out.println("Thread " + Thread.currentThread().getName() + "acquired the
semaphore.");
Thread.sleep(2000); // Simulating work
System.out.println("Thread " + Thread.currentThread().getName() + " released the
semaphore.");
semaphore.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

10. Write a Java Program to show inter thread communication.

Test.java

class Customer{
int amount=10000;

synchronized void withdraw(int amount){


System.out.println("going to withdraw...");
if(this.amount<amount){
System.out.println("Less balance; waiting for deposit...");
try{
wait();
}catch(Exception e){}
}
this.amount-=amount;
System.out.println("withdraw completed...");
}

synchronized void deposit(int amount){


System.out.println("going to deposit...");
this.amount+=amount;
System.out.println("deposit completed... ");
notify();
}
}

public class Test{


public static void main(String args[]){
Customer c=new Customer();
new Thread(){
public void run(){
c.withdraw(15000);
}
}.start();
new Thread(){
public void run(){
c.deposit(10000);
}
}.start();

}}

You might also like