Lab Assignments


Name : Hitarth Singh Rajput
Roll No. : LCS2023040


Lab 3-4 April 2024


Q1

1)     Do all the programs that is explained in the class related with OOPS concepts.

Bubble Sort

package com.hitarth.IIITL2024;

import java.util.Arrays;

// Bubble Sort
public class temp {

    /* ------------------------------------------------------ */
    static void swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

    /* ------------------------------------------------------ */
    static void bubbleSort(int[] arr) {
        int n = arr.length;

        int flag = 0;

        for (int i = 0; i < arr.length - 1; i++) {
            flag = 0;
            for (int j = 0; j < arr.length - i - 1; j++) {
                if (arr[j + 1] < arr[j]) {
                    swap(arr, j, j + 1);
                    flag = 1;
                }
            }
            if (flag == 0)
                break;
        }
    }

    /* ------------------------------------------------------ */
    public static void main(String[] args) {

        int[] arr = {11, 13, 7, 12, 16, 9, 24, 5, 10, 3};

        bubbleSort(arr);

        System.out.println(Arrays.toString(arr));
    }
}

Insertion Sort

package com.hitarth.IIITL2024;

import java.util.Arrays;

// Insertion Sort
public class temp {

    /* ------------------------------------------------------ */
    static void insertionSort(int[] arr) {
        int n = arr.length;

        for (int i = 1; i < arr.length; i++) {
            int j = i-1;
            int x = arr[i];
            while(j>=0 && x < arr[j])
            {
                arr[j+1] = arr[j];
                j--;
            }
            arr[j+1] = x;
        }
    }

    /* ------------------------------------------------------ */
    public static void main(String[] args) {

        int[] arr = {11, 13, 7, 12, 16, 9, 24, 5, 10, 3};

        insertionSort(arr);

        System.out.println(Arrays.toString(arr));
    }
}

Selection Sort

package com.hitarth.IIITL2024;

import java.util.Arrays;

// Selection Sort
public class temp {

    /* ------------------------------------------------------ */
    static void swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

    /* ------------------------------------------------------ */
    static void selectionSort(int[] arr) {
        int n = arr.length;

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

            for (int j = i; j < n; j++) {
                if(arr[j]<arr[k])
                    k=j;
            }
            swap(arr, i, k);
        }
    }

    /* ------------------------------------------------------ */
    public static void main(String[] args) {

        int[] arr = {11, 13, 7, 12, 16, 9, 24, 5, 10, 3};

        selectionSort(arr);

        System.out.println(Arrays.toString(arr));
    }
}

Merge Sort

package com.hitarth.IIITL2024;

import java.util.Arrays;

// Merge Sort
public class temp {

    /* ------------------------------------------------------ */
    static void merge(int[] arr, int l, int mid, int h) {
        int[] b = new int[100];
        int i = l, j = mid + 1, k = l;

        while (i <= mid && j <= h) {
            if (arr[i] < arr[j])
                b[k++] = arr[i++];
            else
                b[k++] = arr[j++];
        }
        for (; i <= mid; i++)
            b[k++] = arr[i];
        for (; j <= h; j++)
            b[k++] = arr[j];
        for (i = l; i <= h; i++)
            arr[i] = b[i];
    }

    /* ------------------------------------------------------ */
    static void mergeSort(int[] arr, int l, int h) {

        if (l < h) {

            int mid = (l + h) / 2;

            mergeSort(arr, l, mid);
            mergeSort(arr, mid + 1, h);
            merge(arr, l, mid, h);

        }
    }

    /* ------------------------------------------------------ */
    public static void main(String[] args) {

        int[] arr = {11, 13, 7, 12, 16, 9, 24, 5, 10, 3};

        mergeSort(arr, 0, arr.length - 1);

        System.out.println(Arrays.toString(arr));
    }
}

Q2

2)     Implement the following case study using OOP concepts in Java. E-Book stall: Every book has properties which includes : Book _Name, Book_Author, Book_Count; Every Customer is having properties as: Customer_Id, Customer_Name, Customer_Address and he can buy books from E-Book stall. Write a Program which will display the text book name and the remaining count of text books when a customer buys a text book.

package com.hitarth.assignments.AfterMidSem.P1;

import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

class Customer {
    private Integer Customer_Id;
    private String Customer_Name;
    private String Customer_Address;

    public Integer getCustomer_Id() {
        return Customer_Id;
    }

    public void setCustomer_Id(Integer customer_Id) {
        Customer_Id = customer_Id;
    }

    public String getCustomer_Name() {
        return Customer_Name;
    }

    public void setCustomer_Name(String customer_Name) {
        Customer_Name = customer_Name;
    }

    public String getCustomer_Address() {
        return Customer_Address;
    }

    public void setCustomer_Address(String customer_Address) {
        Customer_Address = customer_Address;
    }

    public Customer(Integer customer_Id, String customer_Name, String customer_Address) {
        Customer_Id = customer_Id;
        Customer_Name = customer_Name;
        Customer_Address = customer_Address;
    }
}

class Book {
    private String Book_Name;
    private String Book_Author;

    public String getBook_Name() {
        return Book_Name;
    }

    public void setBook_Name(String book_Name) {
        Book_Name = book_Name;
    }

    public String getBook_Author() {
        return Book_Author;
    }

    public void setBook_Author(String book_Author) {
        Book_Author = book_Author;
    }

    public Book(String book_Name, String book_Author) {
        Book_Name = book_Name;
        Book_Author = book_Author;
    }
}

class EbookStall {
    public Map<Integer, Book> shelf = new TreeMap<>();
    private Integer Book_Count = 0;

    public Map<Integer, Book> getShelf() {
        return shelf;
    }

    public void setShelf(Map<Integer, Book> shelf) {
        this.shelf = shelf;
    }

    public Integer getBook_Count() {
        return Book_Count;
    }

    public void buy(String book_name) {
        boolean found = false;
        Integer idToRemove = -1;
        for (Map.Entry<Integer, Book> entry : shelf.entrySet()) {
            if (entry.getValue().getBook_Name().equals(book_name)) {
                found = true;
                idToRemove = entry.getKey();
                break;
            }
        }
        if (found) {
            shelf.remove(idToRemove);
            Book_Count--;
            System.out.println("Book Bought: " + book_name);
            System.out.println("Remaining Count of Books: " + Book_Count);
        } else {
            System.out.println("Book not found!");
        }
    }

    public void add(Integer id, Book book) {
        shelf.put(id, book);
        Book_Count++;
        System.out.println("Book Added Successfully!");
    }

    public void showShelf() {
        for (Map.Entry<Integer, Book> entry : shelf.entrySet()) {
            System.out.println("ID: " + entry.getKey() + ", Book: " + entry.getValue().getBook_Name() + ", Author: " + entry.getValue().getBook_Author());
        }
    }
}

public class Q2 {
    public static void main(String[] args) {
        EbookStall ebookStall = new EbookStall();
        ebookStall.add(1, new Book("Book1", "Author1"));
        ebookStall.add(2, new Book("Book2", "Author2"));
        ebookStall.add(3, new Book("Book3", "Author3"));

        ebookStall.showShelf();

        ebookStall.buy("Book1");
    }
}

Pasted image 20240509191624.png

Q3

3)     Write a Java program to find Area and Circle of different shapes using polymorphism concept.

package com.hitarth.assignments.AfterMidSem.P1;

// 3) Write a Java program to find Area and Circle of different shapes using polymorphism concept.
// (Don't know what Circle of different shapes means here so I'm assuming it's a typo and I'm going to find the area of different shapes)

class CompileTimeP_Area {
    // circle
    public void area(int r) {
        System.out.println("Area of Circle: " + 3.14 * r * r);
    }

    // rectangle
    public void area(int l, int b) {
        System.out.println("Area of Rectangle: " + l * b);
    }
}

class RunTimeP_Area {
    // square
    public void area(int s) {
        System.out.println("Area of Square: " + s * s);
    }
}

class RunTimeP_Area2 extends RunTimeP_Area {
    // circle
    @Override
    public void area(int r) {
        System.out.println("Area of Circle: " + 3.14 * r * r);
    }
}


public class Q3 {
    public static void main(String[] args) {

        CompileTimeP_Area c = new CompileTimeP_Area();
        c.area(5);
        c.area(5, 10);

        RunTimeP_Area r = new RunTimeP_Area();
        r.area(5);

        RunTimeP_Area2 r2 = new RunTimeP_Area2();
        r2.area(5);
    }
}

Pasted image 20240509192433.png

Q4

  1. Write an application to create a super class Employee with information first name & last name and methods getFirstName(), getLastName(). Derive the sub-classes ContractEmployee and RegularEmployee with the information about department, designation & method displayFullName() , getDepartment(), getDesig() to print the salary and to set department name & designation of the corresponding sub-class objects respectively.
package com.hitarth.assignments.AfterMidSem.P1;


class Employee {
    private String first_name;
    private String last_name;

    public String getFirst_name() {
        return first_name;
    }

    public void setFirst_name(String first_name) {
        this.first_name = first_name;
    }

    public String getLast_name() {
        return last_name;
    }

    public void setLast_name(String last_name) {
        this.last_name = last_name;
    }

    public Employee() {
    }

    public Employee(String first_name, String last_name) {
        this.first_name = first_name;
        this.last_name = last_name;
    }
}

class ContractEmployee extends Employee {
    private String department = "Contract Dept.";
    private Integer salary = 16030020;
    private String degignation = "Contract Employee";

    public String getDepartment() {
        return department;
    }

    public void setDepartment(String department) {
        this.department = department;
    }

    public Integer getSalary() {
        return salary;
    }

    public void setSalary(Integer salary) {
        this.salary = salary;
    }

    public String getDegignation() {
        return degignation;
    }

    public void setDegignation(String degignation) {
        this.degignation = degignation;
    }

    public void printSalary() {
        System.out.println("Salary: " + salary);
    }
}

class RegularEmployee extends Employee {
    private String department = "Regular Dept.";
    private Integer salary = 6030020;
    private String degignation = "Regular Employee";

    public String getDepartment() {
        return department;
    }

    public void setDepartment(String department) {
        this.department = department;
    }

    public Integer getSalary() {
        return salary;
    }

    public void setSalary(Integer salary) {
        this.salary = salary;
    }

    public String getDegignation() {
        return degignation;
    }

    public void setDegignation(String degignation) {
        this.degignation = degignation;
    }

    public void printSalary() {
        System.out.println("Salary: " + salary);
    }
}

public class Q4 {
    public static void main(String[] args) {
        ContractEmployee c = new ContractEmployee();
        c.setFirst_name("Hitarth");
        c.setLast_name("Rajput");
        System.out.println("First Name: " + c.getFirst_name());
        System.out.println("Last Name: " + c.getLast_name());
        System.out.println("Department: " + c.getDepartment());
        System.out.println("Degignation: " + c.getDegignation());
        c.printSalary();

        RegularEmployee r = new RegularEmployee();
        r.setFirst_name("Dev");
        r.setLast_name("Darshan");
        System.out.println("First Name: " + r.getFirst_name());
        System.out.println("Last Name: " + r.getLast_name());
        System.out.println("Department: " + r.getDepartment());
        System.out.println("Degignation: " + r.getDegignation());
        r.printSalary();
    }
}

Pasted image 20240509202308.png

Q5

  1. Create an abstract class Shape which calculate the area and volume of 2-d and 3-d shapes with methods getArea() and getVolume(). Reuse this class to calculate the area and volume of square, circle, cube and sphere.
package com.hitarth.assignments.AfterMidSem.P1;

abstract class Shape {
    public abstract Integer area();
    public abstract Integer Volume();
}

class Shape2D extends Shape {
    private Integer area = -1;
    private Integer volume = -1;

    public void square(Integer l) {
        area = l * l;
        volume = 0;
    }

    public void circle(Integer r) {
        area = (int) (3.14 * r * r);
        volume = 0;
    }

    @Override
    public Integer area() {
        return area;
    }

    @Override
    public Integer Volume() {
        return volume;
    }
}

class Shape3D extends Shape {
    private Integer area = -1;
    private Integer volume = -1;

    public void Cube(Integer l) {
        area = 6 * l * l;
        volume = l * l * l;
    }

    @Override
    public Integer area() {
        return area;
    }

    @Override
    public Integer Volume() {
        return volume;
    }
}

public class Q5 {
    public static void main(String[] args) {
        Shape2D s2d = new Shape2D();
        s2d.square(5);
        System.out.println("Area of Square: " + s2d.area());
        s2d.circle(5);
        System.out.println("Area of Circle: " + s2d.area());

        Shape3D s3d = new Shape3D();
        s3d.Cube(5);
        System.out.println("Area of Cube: " + s3d.area());
        System.out.println("Volume of Cube: " + s3d.Volume());
    }
}

Pasted image 20240509204519.png

Q6

  1. Write a program to create a class CIRCLE with one field as radius, used to calculate the area of a Circle. Create another class RECTANGLE used to calculate the area of the rectangle which is a subclass of CIRCLE class. Use the concept of single inheritance such that the radius of circle class can be re-used as length in rectangle class. Take necessary data members and member functions for both the classes to solve this problem. All the data members are initialized through the constructors. Show the result by accessing the area method of both the classes through the objects of the rectangle class.
package com.hitarth.assignments.AfterMidSem.P1;

class Circle {
    private Integer radius;

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

    public Integer getRadius() {
        return radius;
    }

    public Integer area() {
        return (int) (3.14 * radius * radius);
    }
}

class Rectangle extends Circle {
    private Integer length;

    public Rectangle(Integer radius, Integer length) {
        super(radius);
        this.length = length;
    }

    public Integer area() {
        return length * super.getRadius();
    }
}

public class Q6 {

    public static void main(String[] args) {
        Circle c = new Circle(5);
        System.out.println("Area of Circle: " + c.area());

        Rectangle r = new Rectangle(5, 10);
        System.out.println("Area of Rectangle: " + r.area());
    }
}

Pasted image 20240509210552.png

Q7

  1. Derive a class named as BOX from RECTANGLE class. Take necessary data & member functions for this box class to calculate the volume of the box. All the data members are initialized through the constructors. Show the result by accessing the area method of circle and rectangle and the volume method of box class through the objects of box class.
package com.hitarth.assignments.AfterMidSem.P1;
class Rectangle {
    private Integer length;
    private Integer breadth;

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

    public Integer area() {
        return length * breadth;
    }
}

class Box extends Rectangle {
    private Integer height;

    public Box(Integer length, Integer breadth, Integer height) {
        super(length, breadth);
        this.height = height;
    }

    public Integer volume() {
        return super.area()*height;
    }
}
public class Q7 {
    public static void main(String[] args) {
        Rectangle r = new Rectangle(5, 10);
        System.out.println("Area of Rectangle: " + r.area());

        Box b = new Box(5, 10, 15);
        System.out.println("Volume of Box: " + b.volume());
    }
}

Pasted image 20240509214438.png

Q8

  1. Derive a class named as CYLINDER from CIRCLE class. Take necessary data & member functions for this class to calculate the volume of the cylinder. Show the result by accessing the area method of circle and rectangle through object of rectangle class and the area of circle and volume method of cylinder class through the objects of cylinder class.
// Circle class
class Circle {
    public double radius;
    public Circle(double radius) {
        this.radius = radius;
    }

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

class Cylinder extends Circle {
    private double height;

    public Cylinder(double radius, double height) {
        super(radius);
        this.height = height;
    }

    public double volume() {
        return area() * height;
    }
}

class Rectangle {
    public double length;
    public double width;

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

    public double area() {
        return length * width;
    }
}

public class Q8 {
    public static void main(String[] args) {
        Rectangle myRectangle = new Rectangle(5, 4);

        double rectangleArea = myRectangle.area();
        System.out.println("Area of the rectangle: " + rectangleArea);

        Cylinder myCylinder = new Cylinder(3, 5);

        double circleArea = myCylinder.area();
        System.out.println("Area of the circle (base of cylinder): " + circleArea);

        double cylinderVolume = myCylinder.volume();
        System.out.println("Volume of the cylinder: " + cylinderVolume);
    }
}

Pasted image 20240509215148.png

Q9

  1. Design a base class called Student with two fields :- (i) Name (ii) roll number. Derive two classes called Sports and Exam from the Student base class. Class Sports has a field called s_grade and class Exam has a field called e_grade which are integer fields. Derive a class called Results which inherit from Sports and Exam. This class has a character array or string field to represent the final result. Also it has a member function called display which can be used to display the final result. Illustrate the usage of these classes in main.

Solution : Java does not support multiple inheritance directly (i.e., a class cannot inherit from more than one class). Hence, this question cannot be answered.

Q10

  1. Create an abstract class Employee with methods getAmount() which displays the amount paid to employee. Reuse this class to calculate the amount to be paid to WeeklyEmployeed and HourlyEmployee according to no. of hours and total hours for HourlyEmployee and no. of weeks and total weeks for WeeklyEmployee.

Pasted image 20240517165018.png

package com.hitarth.assignments.AfterMidSem.P1;

abstract class Employee {
    abstract void getAmount();
}

class WeeklyEmployee extends Employee {
    int weeks;
    int totalWeeks;

    WeeklyEmployee(int weeks, int totalWeeks) {
        this.weeks = weeks;
        this.totalWeeks = totalWeeks;
    }

    void getAmount() {
        System.out.println("Amount Paid to Weekly Employee: " + weeks * totalWeeks);
    }
}

class HourlyEmployee extends Employee {
    int hours;
    int totalHours;

    HourlyEmployee(int hours, int totalHours) {
        this.hours = hours;
        this.totalHours = totalHours;
    }

    void getAmount() {
        System.out.println("Amount Paid to Hourly Employee: " + hours * totalHours);
    }
}

public class Q10 {
    public static void main(String[] args) {
        WeeklyEmployee w = new WeeklyEmployee(10, 120);
        HourlyEmployee h = new HourlyEmployee(10, 13);

        w.getAmount();
        h.getAmount();
    }
}

Q11

  1. Create an Interface payable with method getAmount (). Calculate the amount to be paid to Invoice and Employee by implementing Interface.

Pasted image 20240517165122.png

package com.hitarth.assignments.AfterMidSem.P1;

interface Payable {
    void getAmount();
}

class Invoice implements Payable {
    int quantity;
    int price;

    Invoice(int quantity, int price) {
        this.quantity = quantity;
        this.price = price;
    }

    public void getAmount() {
        System.out.println("Amount to be paid to Invoice: " + quantity * price);
    }
}

class Employee implements Payable {
    int hours;
    int rate;

    Employee(int hours, int rate) {
        this.hours = hours;
        this.rate = rate;
    }

    public void getAmount() {
        System.out.println("Amount to be paid to Employee: " + hours * rate);
    }
}



public class Q11 {
    public static void main(String[] args) {
        Invoice i = new Invoice(10, 120);
        Employee e = new Employee(10, 13);

        i.getAmount();
        e.getAmount();
    }
}

Q12

  1. Create an Interface Vehicle with method getColor(), getNumber(), getConsumption() calculate the fuel consumed, name and color for TwoWheeler and Four Wheeler By implementing interface Vehicle.

Pasted image 20240517165351.png

package com.hitarth.assignments.AfterMidSem.P1;

interface Vehicle {
    void getColor();
    void getNumber();
    void getConsumption();
}

class TwoWheeler implements Vehicle {
    String name;
    String color;
    int fuelConsumed;

    TwoWheeler(String name, String color, int fuelConsumed) {
        this.name = name;
        this.color = color;
        this.fuelConsumed = fuelConsumed;
    }

    public void getColor() {
        System.out.println("Color of Two Wheeler: " + color);
    }

    public void getNumber() {
        System.out.println("Name of Two Wheeler: " + name);
    }

    public void getConsumption() {
        System.out.println("Fuel Consumed by Two Wheeler: " + fuelConsumed);
    }
}

class FourWheeler implements Vehicle {
    String name;
    String color;
    int fuelConsumed;

    FourWheeler(String name, String color, int fuelConsumed) {
        this.name = name;
        this.color = color;
        this.fuelConsumed = fuelConsumed;
    }

    public void getColor() {
        System.out.println("Color of Four Wheeler: " + color);
    }

    public void getNumber() {
        System.out.println("Name of Four Wheeler: " + name);
    }

    public void getConsumption() {
        System.out.println("Fuel Consumed by Four Wheeler: " + fuelConsumed);
    }
}

public class Q12 {
    public static void main(String[] args) {
        TwoWheeler t = new TwoWheeler("Activa", "Black", 10);
        FourWheeler f = new FourWheeler("Innova", "White", 20);

        t.getColor();
        t.getNumber();
        t.getConsumption();

        f.getColor();
        f.getNumber();
        f.getConsumption();
    }
}

Q13

  1. Create an Interface Fare with method getAmount() to get the amount paid for fare of travelling. Calculate the fare paid by bus and train implementing interface Fare.

Pasted image 20240517210556.png

package com.hitarth.assignments.AfterMidSem.P1;

interface Fare {
    void getAmount();
}

class Bus implements Fare {
    int amount;

    Bus(int amount) {
        this.amount = amount;
    }

    public void getAmount() {
        System.out.println("Amount paid for Bus Fare: " + amount);
    }
}

class Train implements Fare {
    int amount;

    Train(int amount) {
        this.amount = amount;
    }

    public void getAmount() {
        System.out.println("Amount paid for Train Fare: " + amount);
    }
}

public class Q13 {
    public static void main(String[] args) {
        Bus bus = new Bus(100);
        Train train = new Train(200);

        bus.getAmount();
        train.getAmount();
    }
}

Q14

  1. Create an Interface StudentFee with method getAmount(), getFirstName(),getLastName(), getAddress(), getContact(). Calculate the amount paid by the Hostler and NonHostler student by implementing interface Student Fee.

Pasted image 20240517210831.png

package com.hitarth.assignments.AfterMidSem.P1;

interface StudentFee {
    void getAmount();
    void getFirstName();
    void getLastName();
    void getAddress();
    void getContact();
}

class Hostler implements StudentFee {
    int amount;
    String firstName;
    String lastName;
    String address;
    String contact;

    Hostler(int amount, String firstName, String lastName, String address, String contact) {
        this.amount = amount;
        this.firstName = firstName;
        this.lastName = lastName;
        this.address = address;
        this.contact = contact;
    }

    public void getAmount() {
        System.out.println("Amount paid by Hostler: " + amount);
    }

    public void getFirstName() {
        System.out.println("First Name of Hostler: " + firstName);
    }

    public void getLastName() {
        System.out.println("Last Name of Hostler: " + lastName);
    }

    public void getAddress() {
        System.out.println("Address of Hostler: " + address);
    }

    public void getContact() {
        System.out.println("Contact of Hostler: " + contact);
    }
}

class NonHostler implements StudentFee {
    int amount;
    String firstName;
    String lastName;
    String address;
    String contact;

    NonHostler(int amount, String firstName, String lastName, String address, String contact) {
        this.amount = amount;
        this.firstName = firstName;
        this.lastName = lastName;
        this.address = address;
        this.contact = contact;
    }

    public void getAmount() {
        System.out.println("Amount paid by Non Hostler: " + amount);
    }

    public void getFirstName() {
        System.out.println("First Name of Non Hostler: " + firstName);
    }

    public void getLastName() {
        System.out.println("Last Name of Non Hostler: " + lastName);
    }

    public void getAddress() {
        System.out.println("Address of Non Hostler: " + address);
    }

    public void getContact() {
        System.out.println("Contact of Non Hostler: " + contact);
    }
}

public class Q14 {
    public static void main(String[] args) {
        Hostler hostler = new Hostler(1000, "Akshat", "Singh", "Ghaziabad", "1234567890");
        NonHostler nonHostler = new NonHostler(2000, "Hitarth", "Rajput", "Lucknow", "1234567890");

        hostler.getAmount();
        hostler.getFirstName();
        hostler.getLastName();
        hostler.getAddress();
        hostler.getContact();

        nonHostler.getAmount();
        nonHostler.getFirstName();
        nonHostler.getLastName();
        nonHostler.getAddress();
        nonHostler.getContact();
    }
}

Lab 10 April 2024


Q1

  1. Java Program to Access Super Class Method and Instance Variable Using Super Keyword
    Pasted image 20240517211315.png
package com.hitarth.assignments.AfterMidSem.P1;

class SuperClass {
    int num = 100;
    public void display() {
        System.out.println("This is the display method of superclass");
    }
}

class SubClass extends SuperClass {
    int num = 110;
    public void display() {
        System.out.println("This is the display method of subclass");
    }

    public void myMethod() {
        SubClass sub = new SubClass();
        sub.display();
        System.out.println("Value of the variable named num in subclass: " + sub.num);
        System.out.println("Value of the variable named num in superclass: " + super.num);
        super.display();
    }
}

public class Q1 {
    public static void main(String[] args) {
        SubClass obj = new SubClass();
        obj.myMethod();
    }
}

Q2

  1. Java Program to Access Super Class Method and Instance Variable without Super Keyword.

Pasted image 20240517224838.png

package com.hitarth.assignments.AfterMidSem.P1;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

class SuperClass {
    public int superValue = 10;

    public void superMethod() {
        System.out.println("SuperClass method");
    }
}

class SubClass extends SuperClass {
    public int subValue = 20;

    public void subMethod() {
        System.out.println("SubClass method");
    }

    public void accessSuperMembers() {
        try {
            Method superMethod = SuperClass.class.getMethod("superMethod");
            superMethod.invoke(this);

            Field superField = SuperClass.class.getField("superValue");
            int value = superField.getInt(this);
            System.out.println("Value of superValue: " + value);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        SubClass subClass = new SubClass();
        subClass.accessSuperMembers();
    }
}

Q3

  1. Write Java program for the following:
    a. Example for this operator and the use of this keyword.
    b. Example for super keyword.
    c. Example for static variables and methods.

Pasted image 20240517225307.png

package com.hitarth.assignments.AfterMidSem.P1;

// a. Example for this operator and the use of this keyword.
class ThisExample {
    private Integer a;
    private Integer b;

    public ThisExample(Integer a, Integer b) {
        this.a = a;
        this.b = b;
    }

    public void display() {
        System.out.println("a: " + this.a);
        System.out.println("b: " + this.b);
    }
}

// b. Example for super keyword.
class SuperExample extends ThisExample {
    private Integer c;

    public SuperExample(Integer a, Integer b, Integer c) {
        super(a, b);
        this.c = c;
    }

    public void display() {
        super.display();
        System.out.println("c: " + this.c);
    }
}

// c. Example for static variables and methods.
class StaticExample {
    private static Integer count = 0;

    public StaticExample() {
        count++;
    }

    public static void display() {
        System.out.println("Count: " + count);
    }
}

public class Q3 {
    public static void main(String[] args) {
        // a. Example for this operator and the use of this keyword.
        ThisExample t = new ThisExample(5, 10);
        t.display();

        // b. Example for super keyword.
        SuperExample s = new SuperExample(5, 10, 15);
        s.display();

        // c. Example for static variables and methods.
        StaticExample.display();
        StaticExample s1 = new StaticExample();
        StaticExample s2 = new StaticExample();
        StaticExample s3 = new StaticExample();
        StaticExample.display();
    }
}

Q4

  1. Write a Java program to print the sum of two numbers by using this keyword.

Pasted image 20240517225331.png

package com.hitarth.assignments.AfterMidSem.P1;
// 4.	Write a Java program to print the sum of two numbers by using this keyword.
public class Q4 {
    private Integer a;
    private Integer b;

    public Q4(Integer a, Integer b) {
        this.a = a;
        this.b = b;
    }

    public void display() {
        System.out.println("Sum: " + (this.a + this.b));
    }

    public static void main(String[] args) {
        Q4 q = new Q4(5, 10);
        q.display();
    }
}

Q5

  1. Derive sub-classes of ContractEmployee namely HourlyEmployee & WeeklyEmployee with information number of hours & wages per hour, number of weeks & wages per week respectively & method calculateWages() to calculate their monthly salary. Also override getDesig() method depending on the type of contract employee.

Pasted image 20240517230156.png

package com.hitarth.assignments.AfterMidSem.P1;

abstract class Employee {
    abstract void getDesig();
}

abstract class ContractEmployee extends Employee {
    abstract void calculateWages();
    abstract void getDesig();
}

class HourlyEmployee extends ContractEmployee {
    int hours;
    int wagesPerHour;

    HourlyEmployee(int hours, int wagesPerHour) {
        this.hours = hours;
        this.wagesPerHour = wagesPerHour;
    }

    void calculateWages() {
        System.out.println("Amount Paid to Hourly Employee: " + hours * wagesPerHour);
    }

    void getDesig() {
        System.out.println("Designation: Hourly Employee");
    }
}

class WeeklyEmployee extends ContractEmployee {
    int weeks;
    int wagesPerWeek;

    WeeklyEmployee(int weeks, int wagesPerWeek) {
        this.weeks = weeks;
        this.wagesPerWeek = wagesPerWeek;
    }

    void calculateWages() {
        System.out.println("Amount Paid to Weekly Employee: " + weeks * wagesPerWeek);
    }

    void getDesig() {
        System.out.println("Designation: Weekly Employee");
    }
}

public class Q5 {
    public static void main(String[] args) {
        HourlyEmployee h = new HourlyEmployee(10, 13);
        WeeklyEmployee w = new WeeklyEmployee(10, 120);

        h.calculateWages();
        h.getDesig();

        w.calculateWages();
        w.getDesig();
    }
}

Q6

  1. Create an Interface Vehicle with method getColor(), getNumber(), getConsumption() calculate the fuel consumed, name and color for Two Wheeler and Four Wheeler By implementing interface Vehicle.
    Pasted image 20240517230303.png
package com.hitarth.assignments.AfterMidSem.P1;

interface Vehicle {
    void getColor();
    void getNumber();
    void getConsumption();
}

class TwoWheeler implements Vehicle {
    String name;
    String color;
    int fuelConsumed;

    TwoWheeler(String name, String color, int fuelConsumed) {
        this.name = name;
        this.color = color;
        this.fuelConsumed = fuelConsumed;
    }

    public void getColor() {
        System.out.println("Color of Two Wheeler: " + color);
    }

    public void getNumber() {
        System.out.println("Name of Two Wheeler: " + name);
    }

    public void getConsumption() {
        System.out.println("Fuel Consumed by Two Wheeler: " + fuelConsumed);
    }
}

class FourWheeler implements Vehicle {
    String name;
    String color;
    int fuelConsumed;

    FourWheeler(String name, String color, int fuelConsumed) {
        this.name = name;
        this.color = color;
        this.fuelConsumed = fuelConsumed;
    }

    public void getColor() {
        System.out.println("Color of Four Wheeler: " + color);
    }

    public void getNumber() {
        System.out.println("Name of Four Wheeler: " + name);
    }

    public void getConsumption() {
        System.out.println("Fuel Consumed by Four Wheeler: " + fuelConsumed);
    }
}

public class Q6 {
    public static void main(String[] args) {
        TwoWheeler twoWheeler = new TwoWheeler("Scooter", "Red", 10);
        twoWheeler.getColor();
        twoWheeler.getNumber();
        twoWheeler.getConsumption();

        FourWheeler fourWheeler = new FourWheeler("Car", "Black", 20);
        fourWheeler.getColor();
        fourWheeler.getNumber();
        fourWheeler.getConsumption();
    }
}

Q7

  1. Create an Interface Fare with method getAmount() to get the amount paid for fare of travelling. Calculate the fare paid by bus and train implementing interface Fare.

Pasted image 20240517230428.png

package com.hitarth.assignments.AfterMidSem.P1;

interface Fare {
    void getAmount();
}

class Bus implements Fare {
    int amount;

    Bus(int amount) {
        this.amount = amount;
    }

    public void getAmount() {
        System.out.println("Amount paid for Bus Fare: " + amount);
    }
}

class Train implements Fare {
    int amount;

    Train(int amount) {
        this.amount = amount;
    }

    public void getAmount() {
        System.out.println("Amount paid for Train Fare: " + amount);
    }
}

public class Q7 {
    public static void main(String[] args) {
        Bus bus = new Bus(100);
        Train train = new Train(200);

        bus.getAmount();
        train.getAmount();
    }
}

Q8

  1. Create an Interface Student Fee with method getAmount(), getFirstName(), getLastName(), getAddress(), getContact(). Calculate the amount paid by the Hostler and Non Hostler student by implementing interface Student Fee.

Pasted image 20240517232747.png

package com.hitarth.assignments.AfterMidSem.P1;

interface StudentFee {
    void getAmount();
    void getFirstName();
    void getLastName();
    void getAddress();
    void getContact();
}

class Hostler implements StudentFee {
    int amount;
    String firstName;
    String lastName;
    String address;
    String contact;

    Hostler(int amount, String firstName, String lastName, String address, String contact) {
        this.amount = amount;
        this.firstName = firstName;
        this.lastName = lastName;
        this.address = address;
        this.contact = contact;
    }

    public void getAmount() {
        System.out.println("Amount paid by Hostler: " + amount);
    }

    public void getFirstName() {
        System.out.println("First Name of Hostler: " + firstName);
    }

    public void getLastName() {
        System.out.println("Last Name of Hostler: " + lastName);
    }

    public void getAddress() {
        System.out.println("Address of Hostler: " + address);
    }

    public void getContact() {
        System.out.println("Contact of Hostler: " + contact);
    }
}

class NonHostler implements StudentFee {
    int amount;
    String firstName;
    String lastName;
    String address;
    String contact;

    NonHostler(int amount, String firstName, String lastName, String address, String contact) {
        this.amount = amount;
        this.firstName = firstName;
        this.lastName = lastName;
        this.address = address;
        this.contact = contact;
    }

    public void getAmount() {
        System.out.println("Amount paid by Non Hostler: " + amount);
    }

    public void getFirstName() {
        System.out.println("First Name of Non Hostler: " + firstName);
    }

    public void getLastName() {
        System.out.println("Last Name of Non Hostler: " + lastName);
    }

    public void getAddress() {
        System.out.println("Address of Non Hostler: " + address);
    }

    public void getContact() {
        System.out.println("Contact of Non Hostler: " + contact);
    }
}

public class Q8 {
    public static void main(String[] args) {
        Hostler hostler = new Hostler(100, "Askhat", "Singh", "Ghaziabad", "1234567890");
        NonHostler nonHostler = new NonHostler(200, "Hitarth", "Rajput", "Lucknow", "1234567890");

        hostler.getAmount();
        hostler.getFirstName();
        hostler.getLastName();
        hostler.getAddress();
        hostler.getContact();

        nonHostler.getAmount();
        nonHostler.getFirstName();
        nonHostler.getLastName();
        nonHostler.getAddress();
        nonHostler.getContact();
    }
}

Q9

  1. Create your own exception class using the extends keyword. Write a constructor for this class that takes a String argument and stores it inside the object with a String reference. Write a method that prints out the stored String. Create a try- catch clause to exercise your new exception.
    Pasted image 20240517233231.png
package com.hitarth.assignments.AfterMidSem.P1;

class MyException extends Exception {
    private String message;

    MyException(String message) {
        this.message = message;
    }

    public void printMessage() {
        System.out.println("Message: " + message);
    }
}

public class Q9 {
    public static void main(String[] args) {
        try {
            throw new MyException("This is a custom exception");
        } catch (MyException e) {
            e.printMessage();
        }
    }
}

Q10

  1. Write a Java program to create package called dept. Create four classes as CSE, ECE, ME and CE add methods in each class which can display subject names of your respect year. access this package classes from main class.

Pasted image 20240517233337.png

package com.hitarth.assignments.AfterMidSem.P1;

class CSE {
    public void display() {
        System.out.println("CSE Subjects");
    }
}

class ECE {
    public void display() {
        System.out.println("ECE Subjects");
    }
}

class ME {
    public void display() {
        System.out.println("ME Subjects");
    }
}

class CE {
    public void display() {
        System.out.println("CE Subjects");
    }
}

public class Q10 {
    public static void main(String[] args) {
        CSE c = new CSE();
        ECE e = new ECE();
        ME m = new ME();
        CE ce = new CE();

        c.display();
        e.display();
        m.display();
        ce.display();
    }
}


Other Questions

Q1

Implement, create, update, insert, delete and iterate the following data structures

  1. set- hash set, tree set
  2. map- hash table, hash map

Pasted image 20240517233624.png

package com.hitarth.assignments.AfterMidSem.P1;

import java.util.HashSet;
import java.util.TreeSet;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;

public class Q11 {
    public static void main(String[] args) {
        HashSet<Integer> hashSet = new HashSet<>();
        hashSet.add(1);
        hashSet.add(2);
        hashSet.add(3);
        hashSet.add(4);
        hashSet.add(5);
        System.out.println("HashSet: " + hashSet);

        TreeSet<Integer> treeSet = new TreeSet<>();
        treeSet.add(1);
        treeSet.add(2);
        treeSet.add(3);
        treeSet.add(4);
        treeSet.add(5);
        System.out.println("TreeSet: " + treeSet);

        HashMap<Integer, String> hashMap = new HashMap<>();
        hashMap.put(1, "One");
        hashMap.put(2, "Two");
        hashMap.put(3, "Three");
        hashMap.put(4, "Four");
        hashMap.put(5, "Five");
        System.out.println("HashMap: " + hashMap);

        Hashtable<Integer, String> hashTable = new Hashtable<>();
        hashTable.put(1, "One");
        hashTable.put(2, "Two");
        hashTable.put(3, "Three");
        hashTable.put(4, "Four");
        hashTable.put(5, "Five");
        System.out.println("HashTable: " + hashTable);
    }
}

Q2

  1. In the following collection framework perform these operation creation, insertion, updation, deletion, iteration. Array list, linked list, vector.

Pasted image 20240517233822.png

package com.hitarth.assignments.AfterMidSem.P1;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Vector;

public class Q12 {
    public static void main(String[] args) {
        // ArrayList
        ArrayList<Integer> arrayList = new ArrayList<>();
        arrayList.add(1);
        arrayList.add(2);
        arrayList.add(3);
        arrayList.add(4);
        arrayList.add(5);
        System.out.println("ArrayList: " + arrayList);
        arrayList.set(2, 10);
        System.out.println("ArrayList after updating: " + arrayList);
        arrayList.remove(2);
        System.out.println("ArrayList after deleting: " + arrayList);
        for (Integer i : arrayList) {
            System.out.println("ArrayList iteration: " + i);
        }

        // LinkedList
        LinkedList<Integer> linkedList = new LinkedList<>();
        linkedList.add(1);
        linkedList.add(2);
        linkedList.add(3);
        linkedList.add(4);
        linkedList.add(5);
        System.out.println("LinkedList: " + linkedList);
        linkedList.set(2, 10);
        System.out.println("LinkedList after updating: " + linkedList);
        linkedList.remove(2);
        System.out.println("LinkedList after deleting: " + linkedList);
        for (Integer i : linkedList) {
            System.out.println("LinkedList iteration: " + i);
        }

        // Vector
        Vector<Integer> vector = new Vector<>();
        vector.add(1);
        vector.add(2);
        vector.add(3);
        vector.add(4);
        vector.add(5);
        System.out.println("Vector: " + vector);
        vector.set(2, 10);
        System.out.println("Vector after updating: " + vector);
        vector.remove(2);
        System.out.println("Vector after deleting: " + vector);
        for (Integer i : vector) {
            System.out.println("Vector iteration: " + i);
        }
    }
}