Programming Pandit

c/c++/c#/Javav/Python


Latest Update

Monday, February 24, 2025

February 24, 2025

Java program that implements inheritance and method overriding

Objective: Write a Java Program to create an abstract class named Shape that contains two integers and an empty method named print Area(). Provide three classes named Rectangle, Triangle and Circle such that each one of the classes extends the class Shape. Each one of the classes contains only the method print Area () that prints the area of the given shape.


Code: 

import java.util.Scanner;

// Base class
abstract class Shape {
    abstract void printArea();  // Abstract method (empty method)
}

// Derived class for Rectangle
class Rectangle extends Shape {
    private double length, breadth;

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

    @Override
    void printArea() {
        double area = length * breadth;
        System.out.println("Area of Rectangle: " + area);
    }
}

// Derived class for Triangle
class Triangle extends Shape {
    private double base, height;

    Triangle(double base, double height) {
        this.base = base;
        this.height = height;
    }

    @Override
    void printArea() {
        double area = 0.5 * base * height;
        System.out.println("Area of Triangle: " + area);
    }
}

// Derived class for Circle
class Circle extends Shape {
    private double radius;

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

    @Override
    void printArea() {
        double area = Math.PI * radius * radius;
        System.out.println("Area of Circle: " + area);
    }
}

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

        // Input for Rectangle
        System.out.print("Enter length of the rectangle: ");
        double length = scanner.nextDouble();
        System.out.print("Enter breadth of the rectangle: ");
        double breadth = scanner.nextDouble();
        Shape rectangle = new Rectangle(length, breadth);

        // Input for Triangle
        System.out.print("Enter base of the triangle: ");
        double base = scanner.nextDouble();
        System.out.print("Enter height of the triangle: ");
        double height = scanner.nextDouble();
        Shape triangle = new Triangle(base, height);

        // Input for Circle
        System.out.print("Enter radius of the circle: ");
        double radius = scanner.nextDouble();
        Shape circle = new Circle(radius);

        System.out.println("\nCalculating Areas:");
        rectangle.printArea();
        triangle.printArea();
        circle.printArea();

        scanner.close();
    }
}



Output:



February 24, 2025

Java program that performs string operations using ArrayList.

 Objective: Write a program to perform string operations using Array List. Write functions for the following a. Append - add at end b. Insert add at particular index c. Search d. List all string starts with given letter. 

Code:

import java.util.ArrayList;

import java.util.Scanner;


public class StringOperations {

    private ArrayList<String> stringList;


    // Constructor to initialize the ArrayList

    public StringOperations() {

        stringList = new ArrayList<>();

    }


    // a. Append - Add at the end

    public void appendString(String str) {

        stringList.add(str);

        System.out.println("\"" + str + "\" added at the end.");

    }


    // b. Insert - Add at a particular index

    public void insertString(int index, String str) {

        if (index >= 0 && index <= stringList.size()) {

            stringList.add(index, str);

            System.out.println("\"" + str + "\" inserted at index " + index);

        } else {

            System.out.println("Invalid index! Index should be between 0 and " + stringList.size());

        }

    }


    // c. Search - Find a string

    public void searchString(String str) {

        if (stringList.contains(str)) {

            int index = stringList.indexOf(str);

            System.out.println("\"" + str + "\" found at index " + index);

        } else {

            System.out.println("\"" + str + "\" not found in the list.");

        }

    }


    // d. List all strings that start with a given letter

    public void listStringsByLetter(char letter) {

        boolean found = false;

        System.out.println("Strings starting with '" + letter + "':");

        for (String str : stringList) {

            if (str.toLowerCase().charAt(0) == Character.toLowerCase(letter)) {

                System.out.println(str);

                found = true;

            }

        }

        if (!found) {

            System.out.println("No strings found starting with '" + letter + "'.");

        }

    }


    // Display all strings in the list

    public void displayList() {

        System.out.println("Current String List: " + stringList);

    }


    public static void main(String[] args) {

        StringOperations obj = new StringOperations();

        Scanner scanner = new Scanner(System.in);


        while (true) {

            System.out.println("\nChoose an operation:");

            System.out.println("1. Append String");

            System.out.println("2. Insert String at Index");

            System.out.println("3. Search String");

            System.out.println("4. List Strings Starting with a Letter");

            System.out.println("5. Display All Strings");

            System.out.println("6. Exit");

            System.out.print("Enter your choice: ");


            int choice = scanner.nextInt();

            scanner.nextLine(); // Consume newline


            switch (choice) {

                case 1:

                    System.out.print("Enter string to append: ");

                    String appendStr = scanner.nextLine();

                    obj.appendString(appendStr);

                    break;


                case 2:

                    System.out.print("Enter index: ");

                    int index = scanner.nextInt();

                    scanner.nextLine(); // Consume newline

                    System.out.print("Enter string to insert: ");

                    String insertStr = scanner.nextLine();

                    obj.insertString(index, insertStr);

                    break;


                case 3:

                    System.out.print("Enter string to search: ");

                    String searchStr = scanner.nextLine();

                    obj.searchString(searchStr);

                    break;


                case 4:

                    System.out.print("Enter starting letter: ");

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

                    obj.listStringsByLetter(letter);

                    break;


                case 5:

                    obj.displayList();

                    break;


                case 6:

                    System.out.println("Exiting...");

                    scanner.close();

                    System.exit(0);

                    break;


                default:

                    System.out.println("Invalid choice! Please enter a number between 1 and 6.");

            }

        }

    }

}


Output:








February 24, 2025

Java Interface for ADT Stack and its Array Implementation with Exception Handling

 Objective: Design a Java interface for ADT Stack. Implement this interface using array. Provide necessary exception handling in both the implementations.


Code: 

// Custom Exception for Stack Overflow

class StackOverflowException extends Exception {

    public StackOverflowException(String message) {

        super(message);

    }

}


// Custom Exception for Stack Underflow

class StackUnderflowException extends Exception {

    public StackUnderflowException(String message) {

        super(message);

    }

}


// Stack Interface

interface StackADT {

    void push(int item) throws StackOverflowException;

    int pop() throws StackUnderflowException;

    int peek() throws StackUnderflowException;

    boolean isEmpty();

    boolean isFull();

    int size();

}


// Stack Implementation using Array

class ArrayStack implements StackADT {

    private int[] stack;

    private int top;

    private int capacity;


    // Constructor to initialize stack

    public ArrayStack(int capacity) {

        this.capacity = capacity;

        stack = new int[capacity];

        top = -1; // Stack is empty initially

    }


    // Push an element onto the stack

    @Override

    public void push(int item) throws StackOverflowException {

        if (isFull()) {

            throw new StackOverflowException("Stack Overflow! Cannot push " + item);

        }

        stack[++top] = item;

        System.out.println("Pushed: " + item);

    }


    // Pop an element from the stack

    @Override

    public int pop() throws StackUnderflowException {

        if (isEmpty()) {

            throw new StackUnderflowException("Stack Underflow! Cannot pop from an empty stack.");

        }

        int poppedItem = stack[top--];

        System.out.println("Popped: " + poppedItem);

        return poppedItem;

    }


    // Peek at the top element of the stack

    @Override

    public int peek() throws StackUnderflowException {

        if (isEmpty()) {

            throw new StackUnderflowException("Stack is empty! No element to peek.");

        }

        return stack[top];

    }


    // Check if stack is empty

    @Override

    public boolean isEmpty() {

        return top == -1;

    }


    // Check if stack is full

    @Override

    public boolean isFull() {

        return top == capacity - 1;

    }


    // Get the size of the stack

    @Override

    public int size() {

        return top + 1;

    }

}


// Main class to test the stack implementation

public class StackDemo {

    public static void main(String[] args) {

        ArrayStack stack = new ArrayStack(5); // Create stack of size 5


        try {

            stack.push(10);

            stack.push(20);

            stack.push(30);

            stack.push(40);

            stack.push(50);


            // Uncomment to test Stack Overflow

            // stack.push(60);


            System.out.println("Top element is: " + stack.peek());

            System.out.println("Stack size: " + stack.size());


            stack.pop();

            stack.pop();


            System.out.println("Top element after pop: " + stack.peek());

            System.out.println("Stack size after pop: " + stack.size());


            // Uncomment to test Stack Underflow

            // stack.pop(); stack.pop(); stack.pop(); stack.pop();


        } catch (StackOverflowException | StackUnderflowException e) {

            System.out.println("Error: " + e.getMessage());

        }

    }

}


Output:




February 24, 2025

JAVA Program for Salary slip


Objective: Develop a java application with Employee class with Emp_name, Emp_id, Address, Mail_id, Mobile_no as members. Inherit the classes, Programmer, Assistant Professor, Associate Professor and Professor from employee class. Add Basic Pay (BP) as the member of all the inherited classes with 97% of BP as DA, 10 % of BP as HRA, 12% of BP as PF, 0.1% of BP for staff club fund. Generate pay slips for the employees with their gross and net salary.


Code: 

import java.util.Scanner;


// Base class Employee

class Employee {

    String empName, empId, address, mailId;

    long mobileNo;


    public Employee(String empName, String empId, String address, String mailId, long mobileNo) {

        this.empName = empName;

        this.empId = empId;

        this.address = address;

        this.mailId = mailId;

        this.mobileNo = mobileNo;

    }


    // Display common details

    public void displayEmployeeDetails() {

        System.out.println("Employee Name: " + empName);

        System.out.println("Employee ID: " + empId);

        System.out.println("Address: " + address);

        System.out.println("Mail ID: " + mailId);

        System.out.println("Mobile No: " + mobileNo);

    }

}


// Derived class for different designations

class Programmer extends Employee {

    double basicPay;


    public Programmer(String empName, String empId, String address, String mailId, long mobileNo, double basicPay) {

        super(empName, empId, address, mailId, mobileNo);

        this.basicPay = basicPay;

    }


    public void generatePaySlip() {

        System.out.println("\n====== PAY SLIP: PROGRAMMER ======");

        displayEmployeeDetails();

        calculateSalary();

    }


    public void calculateSalary() {

        double da = 0.97 * basicPay;

        double hra = 0.10 * basicPay;

        double pf = 0.12 * basicPay;

        double staffClubFund = 0.001 * basicPay;

        double grossSalary = basicPay + da + hra;

        double netSalary = grossSalary - (pf + staffClubFund);


        System.out.println("Basic Pay: " + basicPay);

        System.out.println("DA (97% of BP): " + da);

        System.out.println("HRA (10% of BP): " + hra);

        System.out.println("PF (12% of BP): " + pf);

        System.out.println("Staff Club Fund (0.1% of BP): " + staffClubFund);

        System.out.println("Gross Salary: " + grossSalary);

        System.out.println("Net Salary: " + netSalary);

    }

}


// Assistant Professor class

class AssistantProfessor extends Programmer {

    public AssistantProfessor(String empName, String empId, String address, String mailId, long mobileNo, double basicPay) {

        super(empName, empId, address, mailId, mobileNo, basicPay);

    }


    public void generatePaySlip() {

        System.out.println("\n====== PAY SLIP: ASSISTANT PROFESSOR ======");

        displayEmployeeDetails();

        calculateSalary();

    }

}


// Associate Professor class

class AssociateProfessor extends Programmer {

    public AssociateProfessor(String empName, String empId, String address, String mailId, long mobileNo, double basicPay) {

        super(empName, empId, address, mailId, mobileNo, basicPay);

    }


    public void generatePaySlip() {

        System.out.println("\n====== PAY SLIP: ASSOCIATE PROFESSOR ======");

        displayEmployeeDetails();

        calculateSalary();

    }

}


// Professor class

class Professor extends Programmer {

    public Professor(String empName, String empId, String address, String mailId, long mobileNo, double basicPay) {

        super(empName, empId, address, mailId, mobileNo, basicPay);

    }


    public void generatePaySlip() {

        System.out.println("\n====== PAY SLIP: PROFESSOR ======");

        displayEmployeeDetails();

        calculateSalary();

    }

}


// Main Class to run the program

public class EmployeePayroll {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);


        System.out.println("Enter Employee Name: ");

        String name = sc.nextLine();

        

        System.out.println("Enter Employee ID: ");

        String empId = sc.nextLine();

        

        System.out.println("Enter Employee Address: ");

        String address = sc.nextLine();

        

        System.out.println("Enter Employee Mail ID: ");

        String mailId = sc.nextLine();

        

        System.out.println("Enter Mobile No: ");

        long mobileNo = sc.nextLong();

        

        System.out.println("Enter Basic Pay: ");

        double basicPay = sc.nextDouble();

        

        System.out.println("Choose Employee Role:");

        System.out.println("1. Programmer\n2. Assistant Professor\n3. Associate Professor\n4. Professor");

        int choice = sc.nextInt();

     

        switch (choice) {

            case 1:

                Programmer prog = new Programmer(name, empId, address, mailId, mobileNo, basicPay);

                prog.generatePaySlip();

                break;

            case 2:

                AssistantProfessor asstProf = new AssistantProfessor(name, empId, address, mailId, mobileNo, basicPay);

                asstProf.generatePaySlip();

                break;

            case 3:

                AssociateProfessor assocProf = new AssociateProfessor(name, empId, address, mailId, mobileNo, basicPay);

                assocProf.generatePaySlip();

                break;

            case 4:

                Professor prof = new Professor(name, empId, address, mailId, mobileNo, basicPay);

                prof.generatePaySlip();

                break;

            default:

                System.out.println("Invalid choice!");

        }

        sc.close();

    }

}


Output:





Wednesday, February 12, 2025

February 12, 2025

Converter Application in java using package

 Objective :  Develop a java program to implement currency converter (Dollar to INR, EURO to INR, Yen to INR and vice versa), distance converter (meter to KM, miles to KM and vice versa), time converter (hours to minutes, seconds and vice versa) using packages.


Code: 

// Package for currency conversion

package converters.currency;

public class CurrencyConverter {

    public static double dollarToINR(double dollar) { return dollar * 83.0; }

    public static double inrToDollar(double inr) { return inr / 83.0; }

    public static double euroToINR(double euro) { return euro * 90.0; }

    public static double inrToEuro(double inr) { return inr / 90.0; }

    public static double yenToINR(double yen) { return yen * 0.56; }

    public static double inrToYen(double inr) { return inr / 0.56; }

}


// Package for distance conversion

package converters.distance;

public class DistanceConverter {

    public static double metersToKM(double meters) { return meters / 1000.0; }

    public static double kmToMeters(double km) { return km * 1000.0; }

    public static double milesToKM(double miles) { return miles * 1.609; }

    public static double kmToMiles(double km) { return km / 1.609; }

}


// Package for time conversion

package converters.time;

public class TimeConverter {

    public static double hoursToMinutes(double hours) { return hours * 60.0; }

    public static double minutesToHours(double minutes) { return minutes / 60.0; }

    public static double secondsToMinutes(double seconds) { return seconds / 60.0; }

    public static double minutesToSeconds(double minutes) { return minutes * 60.0; }

}


// Main class with user interaction

import java.util.Scanner;

import converters.currency.CurrencyConverter;

import converters.distance.DistanceConverter;

import converters.time.TimeConverter;


public class ConverterApp {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        while (true) {

            System.out.println("Select conversion type:");

            System.out.println("1. Currency Converter");

            System.out.println("2. Distance Converter");

            System.out.println("3. Time Converter");

            System.out.println("4. Exit");

            int choice = scanner.nextInt();


            if (choice == 4) break;

            double value, result;

            switch (choice) {

                case 1:

                    System.out.println("Select conversion: 1. Dollar to INR, 2. INR to Dollar, 3. Euro to INR, 4. INR to Euro, 5. Yen to INR, 6. INR to Yen");

                    int currencyChoice = scanner.nextInt();

                    System.out.println("Enter amount: ");

                    value = scanner.nextDouble();

                    result = switch (currencyChoice) {

                        case 1 -> CurrencyConverter.dollarToINR(value);

                        case 2 -> CurrencyConverter.inrToDollar(value);

                        case 3 -> CurrencyConverter.euroToINR(value);

                        case 4 -> CurrencyConverter.inrToEuro(value);

                        case 5 -> CurrencyConverter.yenToINR(value);

                        case 6 -> CurrencyConverter.inrToYen(value);

                        default -> 0;

                    };

                    System.out.println("Converted value: " + result);

                    break;

                case 2:

                    System.out.println("Select conversion: 1. Meters to KM, 2. KM to Meters, 3. Miles to KM, 4. KM to Miles");

                    int distanceChoice = scanner.nextInt();

                    System.out.println("Enter distance: ");

                    value = scanner.nextDouble();

                    result = switch (distanceChoice) {

                        case 1 -> DistanceConverter.metersToKM(value);

                        case 2 -> DistanceConverter.kmToMeters(value);

                        case 3 -> DistanceConverter.milesToKM(value);

                        case 4 -> DistanceConverter.kmToMiles(value);

                        default -> 0;

                    };

                    System.out.println("Converted value: " + result);

                    break;

                case 3:

                    System.out.println("Select conversion: 1. Hours to Minutes, 2. Minutes to Hours, 3. Seconds to Minutes, 4. Minutes to Seconds");

                    int timeChoice = scanner.nextInt();

                    System.out.println("Enter time value: ");

                    value = scanner.nextDouble();

                    result = switch (timeChoice) {

                        case 1 -> TimeConverter.hoursToMinutes(value);

                        case 2 -> TimeConverter.minutesToHours(value);

                        case 3 -> TimeConverter.secondsToMinutes(value);

                        case 4 -> TimeConverter.minutesToSeconds(value);

                        default -> 0;

                    };

                    System.out.println("Converted value: " + result);

                    break;

                default:

                    System.out.println("Invalid choice, try again.");

            }

        }

        scanner.close();

        System.out.println("Thank you for using the converter!");

    }

}



Package folder Hierarchey: 

│── ConverterApp.java

│── converters\

│   ├── currency\

│   │   ├── CurrencyConverter.java

│   ├── distance\

│   │   ├── DistanceConverter.java

│   ├── time\

│       ├── TimeConverter.java



Output:

Compilation of source codes for class file of packages:



Runing of the Main class :






Wednesday, February 5, 2025

February 05, 2025

User input for addition of two numbers JAVA

Java program that takes user input for two numbers and performs addition: 


import java.util.Scanner;  // Import the Scanner class


public class AdditionProgram 

{

    public static void main(String[] args) {

        // Create a Scanner object for user input

        Scanner scanner = new Scanner(System.in);

        

        // Prompt user for first number

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

        int num1 = scanner.nextInt();

        

        // Prompt user for second number

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

        int num2 = scanner.nextInt();

   

        // Perform addition

        int sum = num1 + num2;

        

        // Display result

        System.out.println("The sum is: " + sum);

        

        // Close scanner

        scanner.close();

    }

}




Output :