Java Programming Lab-Sheet-5 Solutions

1 month ago

Java Programming Lab-Sheet-5 Solutions

17. Power calculation without Math class

java

Copy

Download

import java.util.Scanner;

class PowerCalculator {
    private int x;
    private int n;
    
    public PowerCalculator(int x, int n) {
        this.x = x;
        this.n = n;
    }
    
    public long calculate() {
        long result = 1;
        for(int i = 0; i < n; i++) {
            result *= x;
        }
        return result;
    }
}

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter base (x): ");
        int x = sc.nextInt();
        System.out.print("Enter exponent (n): ");
        int n = sc.nextInt();
        
        PowerCalculator pc = new PowerCalculator(x, n);
        System.out.println(x + "^" + n + " = " + pc.calculate());
    }
}

Output:

Copy

Download

Enter base (x): 5
Enter exponent (n): 3
5^3 = 125

18. Generate prime numbers from 1 to 100

java

Copy

Download

class PrimeGenerator {
    public void generatePrimes() {
        System.out.println("Prime numbers between 1 and 100:");
        for(int i = 2; i <= 100; i++) {
            if(isPrime(i)) {
                System.out.print(i + " ");
            }
        }
    }
    
    private boolean isPrime(int num) {
        if(num <= 1) return false;
        for(int i = 2; i <= Math.sqrt(num); i++) {
            if(num % i == 0) return false;
        }
        return true;
    }
}

public class Main {
    public static void main(String[] args) {
        PrimeGenerator pg = new PrimeGenerator();
        pg.generatePrimes();
    }
}

Output:

Copy

Download

Prime numbers between 1 and 100:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 

19. Function overloading illustration

java

Copy

Download

class Calculator {
    // Method to add two integers
    public int add(int a, int b) {
        return a + b;
    }
    
    // Overloaded method to add three integers
    public int add(int a, int b, int c) {
        return a + b + c;
    }
    
    // Overloaded method to add two doubles
    public double add(double a, double b) {
        return a + b;
    }
    
    // Overloaded method to concatenate two strings
    public String add(String a, String b) {
        return a + b;
    }
}

public class Main {
    public static void main(String[] args) {
        Calculator calc = new Calculator();
        
        System.out.println("Sum of 5 and 10: " + calc.add(5, 10));
        System.out.println("Sum of 5, 10 and 15: " + calc.add(5, 10, 15));
        System.out.println("Sum of 5.5 and 10.5: " + calc.add(5.5, 10.5));
        System.out.println("Concatenation of 'Hello' and 'World': " + calc.add("Hello", "World"));
    }
}

Output:

Copy

Download

Sum of 5 and 10: 15
Sum of 5, 10 and 15: 30
Sum of 5.5 and 10.5: 16.0
Concatenation of 'Hello' and 'World': HelloWorld

20. Abstract class illustration

java

Copy

Download

abstract class Shape {
    protected String color;
    
    public Shape(String color) {
        this.color = color;
    }
    
    // Abstract method (must be implemented by subclasses)
    public abstract double area();
    
    // Concrete method
    public String getColor() {
        return color;
    }
}

class Circle extends Shape {
    private double radius;
    
    public Circle(String color, double radius) {
        super(color);
        this.radius = radius;
    }
    
    @Override
    public double area() {
        return Math.PI * radius * radius;
    }
}

class Rectangle extends Shape {
    private double length;
    private double width;
    
    public Rectangle(String color, double length, double width) {
        super(color);
        this.length = length;
        this.width = width;
    }
    
    @Override
    public double area() {
        return length * width;
    }
}

public class Main {
    public static void main(String[] args) {
        Shape circle = new Circle("Red", 5.0);
        Shape rectangle = new Rectangle("Blue", 4.0, 6.0);
        
        System.out.println("Circle color: " + circle.getColor() + ", Area: " + circle.area());
        System.out.println("Rectangle color: " + rectangle.getColor() + ", Area: " + rectangle.area());
    }
}

Output:

Copy

Download

Circle color: Red, Area: 78.53981633974483
Rectangle color: Blue, Area: 24.0

21. Constructor implementation

java

Copy

Download

class Student {
    private String name;
    private int rollNo;
    private int age;
    
    // Default constructor
    public Student() {
        this.name = "Unknown";
        this.rollNo = 0;
        this.age = 0;
    }
    
    // Parameterized constructor
    public Student(String name, int rollNo) {
        this.name = name;
        this.rollNo = rollNo;
        this.age = 18; // Default age
    }
    
    // Parameterized constructor with all fields
    public Student(String name, int rollNo, int age) {
        this.name = name;
        this.rollNo = rollNo;
        this.age = age;
    }
    
    // Copy constructor
    public Student(Student other) {
        this.name = other.name;
        this.rollNo = other.rollNo;
        this.age = other.age;
    }
    
    public void display() {
        System.out.println("Name: " + name + ", Roll No: " + rollNo + ", Age: " + age);
    }
}

public class Main {
    public static void main(String[] args) {
        Student s1 = new Student();
        Student s2 = new Student("Alice", 101);
        Student s3 = new Student("Bob", 102, 20);
        Student s4 = new Student(s3);
        
        s1.display();
        s2.display();
        s3.display();
        s4.display();
    }
}

Output:

Copy

Download

Name: Unknown, Roll No: 0, Age: 0
Name: Alice, Roll No: 101, Age: 18
Name: Bob, Roll No: 102, Age: 20
Name: Bob, Roll No: 102, Age: 20

22. Polymorphism (static and dynamic binding)

java

Copy

Download

class Animal {
    // Static binding (method is private, final or static)
    private void eatPrivate() {
        System.out.println("Animal is eating (private)");
    }
    
    public final void eatFinal() {
        System.out.println("Animal is eating (final)");
    }
    
    public static void eatStatic() {
        System.out.println("Animal is eating (static)");
    }
    
    // Dynamic binding (method can be overridden)
    public void eat() {
        System.out.println("Animal is eating");
    }
    
    public void sound() {
        System.out.println("Animal makes a sound");
    }
}

class Dog extends Animal {
    // Cannot override private method
    // Cannot override final method
    
    // This is method hiding, not overriding
    public static void eatStatic() {
        System.out.println("Dog is eating (static)");
    }
    
    @Override
    public void eat() {
        System.out.println("Dog is eating");
    }
    
    @Override
    public void sound() {
        System.out.println("Dog barks");
    }
}

public class Main {
    public static void main(String[] args) {
        // Static binding examples
        Animal.eatStatic(); // Calls Animal's static method
        Dog.eatStatic();    // Calls Dog's static method
        
        Animal animal = new Animal();
        animal.eatFinal(); // Calls Animal's final method
        
        // Dynamic binding examples
        Animal myAnimal = new Dog(); // Upcasting
        myAnimal.eat();    // Calls Dog's eat() at runtime
        myAnimal.sound();  // Calls Dog's sound() at runtime
        
        // Compile-time error (private method not visible)
        // myAnimal.eatPrivate();
    }
}

Output:

Copy

Download

Animal is eating (static)
Dog is eating (static)
Animal is eating (final)
Dog is eating
Dog barks

23. Static method implementation

java

Copy

Download

class MathOperations {
    // Static method to calculate factorial
    public static int factorial(int n) {
        if(n == 0 || n == 1) return 1;
        return n * factorial(n - 1);
    }
    
    // Static method to check if number is even
    public static boolean isEven(int num) {
        return num % 2 == 0;
    }
    
    // Instance method
    public void displayMessage() {
        System.out.println("This is an instance method");
    }
}

public class Main {
    public static void main(String[] args) {
        // Calling static methods without creating an instance
        System.out.println("Factorial of 5: " + MathOperations.factorial(5));
        System.out.println("Is 10 even? " + MathOperations.isEven(10));
        
        // Creating instance to call instance method
        MathOperations math = new MathOperations();
        math.displayMessage();
        
        // Note: Calling instance method without instance is not possible
        // MathOperations.displayMessage(); // Error
    }
}

Output:

Copy

Download

Factorial of 5: 120
Is 10 even? true
This is an instance method

24. Nested class implementation

java

Copy

Download

class OuterClass {
    private int outerVar = 10;
    public static int staticOuterVar = 20;
    
    // Instance nested class (inner class)
    class InnerClass {
        public void display() {
            System.out.println("Inner class: outerVar = " + outerVar);
        }
    }
    
    // Static nested class
    static class StaticNestedClass {
        public void display() {
            System.out.println("Static nested class: staticOuterVar = " + staticOuterVar);
            // Cannot access non-static outerVar here
            // System.out.println(outerVar); // Error
        }
    }
    
    // Method with local inner class
    public void methodWithLocalClass() {
        int localVar = 30;
        
        class LocalClass {
            public void display() {
                System.out.println("Local class: outerVar = " + outerVar + 
                                 ", localVar = " + localVar);
            }
        }
        
        LocalClass lc = new LocalClass();
        lc.display();
    }
    
    // Anonymous inner class example
    public void anonymousClassExample() {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                System.out.println("Anonymous class: outerVar = " + outerVar);
            }
        };
        
        new Thread(r).start();
    }
}

public class Main {
    public static void main(String[] args) {
        OuterClass outer = new OuterClass();
        
        // Inner class example
        OuterClass.InnerClass inner = outer.new InnerClass();
        inner.display();
        
        // Static nested class example
        OuterClass.StaticNestedClass staticNested = new OuterClass.StaticNestedClass();
        staticNested.display();
        
        // Method with local class
        outer.methodWithLocalClass();
        
        // Anonymous inner class
        outer.anonymousClassExample();
    }
}

Output:

Copy

Download

Inner class: outerVar = 10
Static nested class: staticOuterVar = 20
Local class: outerVar = 10, localVar = 30
Anonymous class: outerVar = 10

25. Package creation and usage

Step 1: Create package (mypackage/MyUtility.java)

java

Copy

Download

package mypackage;

public class MyUtility {
    public static int add(int a, int b) {
        return a + b;
    }
    
    public static int multiply(int a, int b) {
        return a * b;
    }
}

Step 2: Main program using the package (Main.java)

java

Copy

Download

import mypackage.MyUtility;

public class Main {
    public static void main(String[] args) {
        int sum = MyUtility.add(5, 7);
        int product = MyUtility.multiply(5, 7);
        
        System.out.println("Sum: " + sum);
        System.out.println("Product: " + product);
    }
}

Output:

Copy

Download

Sum: 12
Product: 35

26. Interface illustration

java

Copy

Download

interface Vehicle {
    // Constant
    String TYPE = "Transportation";
    
    // Abstract methods
    void start();
    void stop();
    
    // Default method (Java 8+)
    default void honk() {
        System.out.println("Vehicle is honking!");
    }
    
    // Static method (Java 8+)
    static void displayType() {
        System.out.println("Type: " + TYPE);
    }
}

class Car implements Vehicle {
    @Override
    public void start() {
        System.out.println("Car is starting");
    }
    
    @Override
    public void stop() {
        System.out.println("Car is stopping");
    }
    
    // Overriding default method is optional
    @Override
    public void honk() {
        System.out.println("Car is honking loudly!");
    }
}

class Bike implements Vehicle {
    @Override
    public void start() {
        System.out.println("Bike is starting");
    }
    
    @Override
    public void stop() {
        System.out.println("Bike is stopping");
    }
}

public class Main {
    public static void main(String[] args) {
        Vehicle.displayType(); // Calling static method
        
        Vehicle car = new Car();
        car.start();
        car.honk();
        car.stop();
        
        Vehicle bike = new Bike();
        bike.start();
        bike.honk(); // Uses default implementation
        bike.stop();
    }
}

Output:

Copy

Download

Type: Transportation
Car is starting
Car is honking loudly!
Car is stopping
Bike is starting
Vehicle is honking!
Bike is stopping

27. Extending interface into another interface

java

Copy

Download

interface Animal {
    void eat();
    void sleep();
}

interface Pet extends Animal {
    void play();
    void beFriendly();
}

class Dog implements Pet {
    @Override
    public void eat() {
        System.out.println("Dog is eating");
    }
    
    @Override
    public void sleep() {
        System.out.println("Dog is sleeping");
    }
    
    @Override
    public void play() {
        System.out.println("Dog is playing fetch");
    }
    
    @Override
    public void beFriendly() {
        System.out.println("Dog is wagging its tail");
    }
}

public class Main {
    public static void main(String[] args) {
        Pet myPet = new Dog();
        myPet.eat();
        myPet.sleep();
        myPet.play();
        myPet.beFriendly();
    }
}

Output:

Copy

Download

Dog is eating
Dog is sleeping
Dog is playing fetch
Dog is wagging its tail

28. Multiple inheritance using interface

java

Copy

Download

interface Flyable {
    void fly();
}

interface Swimmable {
    void swim();
}

// Multiple inheritance through interfaces
class Duck implements Flyable, Swimmable {
    @Override
    public void fly() {
        System.out.println("Duck is flying");
    }
    
    @Override
    public void swim() {
        System.out.println("Duck is swimming");
    }
    
    public void quack() {
        System.out.println("Duck is quacking");
    }
}

public class Main {
    public static void main(String[] args) {
        Duck duck = new Duck();
        duck.fly();
        duck.swim();
        duck.quack();
        
        // Polymorphism examples
        Flyable flyingObject = duck;
        flyingObject.fly();
        
        Swimmable swimmingObject = duck;
        swimmingObject.swim();
    }
}

Output:

Copy

Download

Duck is flying
Duck is swimming
Duck is quacking
Duck is flying
Duck is swimming

29. Dynamic dispatch implementation

class Shape {
    public void draw() {
        System.out.println("Drawing a shape");
    }
    
    public void calculateArea() {
        System.out.println("Calculating shape area");
    }
}

class Circle extends Shape {
    @Override
    public void draw() {
        System.out.println("Drawing a circle");
    }
    
    @Override
    public void calculateArea() {
        System.out.println("Calculating circle area: πr²");
    }
}

class Square extends Shape {
    @Override
    public void draw() {
        System.out.println("Drawing a square");
    }
    
    @Override
    public void calculateArea() {
        System.out.println("Calculating square area: side²");
    }
}

public class Main {
    public static void main(String[] args) {
        Shape shape1 = new Circle(); // Upcasting
        Shape shape2 = new Square(); // Upcasting
        
        // Dynamic dispatch - method called depends on actual object type
        shape1.draw();
        shape1.calculateArea();
        
        shape2.draw();
        shape2.calculateArea();
        
        // Array of shapes demonstrating polymorphism
        Shape[] shapes = {new Shape(), new Circle(), new Square()};
        for(Shape shape : shapes) {
            shape.draw(); // Dynamic method dispatch
            System.out.println("---");
        }
    }
}

Output:

Drawing a circle
Calculating circle area: πr²
Drawing a square
Calculating square area: side²
Drawing a shape
---
Drawing a circle
---
Drawing a square
---

30. Illustration of super and this keywords

java

class Parent {
    protected String name;
    
    public Parent(String name) {
        this.name = name;
    }
    
    public void display() {
        System.out.println("Parent name: " + name);
    }
}

class Child extends Parent {
    private String name;
    
    public Child(String parentName, String childName) {
        super(parentName); // Using super to call parent constructor
        this.name = childName; // Using this to refer to current instance
    }
    
    @Override
    public void display() {
        super.display(); // Using super to call parent method
        System.out.println("Child name: " + this.name);
    }
    
    public void showNames() {
        System.out.println("Parent's name: " + super.name); // Access parent field
        System.out.println("Child's name: " + this.name); // Access current field
    }
}

public class Main {
    public static void main(String[] args) {
        Child child = new Child("John", "Alice");
        child.display();
        System.out.println("---");
        child.showNames();
    }
}

Output:

Parent name: John
Child name: Alice
---
Parent's name: John
Child's name: Alice

31. Student Class with Computer Science and Mathematics Subclasses

java

Copy

Download

class Student {
    String name;
    int rollNumber;
    int[] marks;

    public Student(String name, int rollNumber, int[] marks) {
        this.name = name;
        this.rollNumber = rollNumber;
        this.marks = marks;
    }

    public double calculateAverage() {
        int sum = 0;
        for (int mark : marks) {
            sum += mark;
        }
        return (double) sum / marks.length;
    }

    public void displayDetails() {
        System.out.println("Name: " + name);
        System.out.println("Roll Number: " + rollNumber);
        System.out.println("Average Marks: " + calculateAverage());
    }
}

class ComputerScienceStudent extends Student {
    String programmingLanguage;
    String database;

    public ComputerScienceStudent(String name, int rollNumber, int[] marks, 
                                 String programmingLanguage, String database) {
        super(name, rollNumber, marks);
        this.programmingLanguage = programmingLanguage;
        this.database = database;
    }

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

class MathematicsStudent extends Student {
    String algebra;
    String calculus;

    public MathematicsStudent(String name, int rollNumber, int[] marks, 
                             String algebra, String calculus) {
        super(name, rollNumber, marks);
        this.algebra = algebra;
        this.calculus = calculus;
    }

    @Override
    public void displayDetails() {
        super.displayDetails();
        System.out.println("Algebra: " + algebra);
        System.out.println("Calculus: " + calculus);
    }
}

public class StudentDemo {
    public static void main(String[] args) {
        int[] csMarks = {85, 90, 78, 92, 88};
        ComputerScienceStudent csStudent = new ComputerScienceStudent("John Doe", 101, csMarks, 
                                                                     "Java", "MySQL");
        
        int[] mathMarks = {92, 88, 95, 90, 87};
        MathematicsStudent mathStudent = new MathematicsStudent("Jane Smith", 102, mathMarks, 
                                                               "Linear Algebra", "Differential Calculus");
        
        System.out.println("Computer Science Student Details:");
        csStudent.displayDetails();
        
        System.out.println("\nMathematics Student Details:");
        mathStudent.displayDetails();
    }
}

Output:

Copy

Download

Computer Science Student Details:
Name: John Doe
Roll Number: 101
Average Marks: 86.6
Programming Language: Java
Database: MySQL

Mathematics Student Details:
Name: Jane Smith
Roll Number: 102
Average Marks: 90.4
Algebra: Linear Algebra
Calculus: Differential Calculus

32. Employee, Manager, and Executive Classes

java

Copy

Download

class Employee {
    String name;
    double salary;

    public Employee(String name, double salary) {
        this.name = name;
        this.salary = salary;
    }

    @Override
    public String toString() {
        return "Name: " + name + ", Salary: $" + salary;
    }
}

class Manager extends Employee {
    String department;

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

    @Override
    public String toString() {
        return super.toString() + ", Department: " + department;
    }
}

class Executive extends Manager {
    public Executive(String name, double salary, String department) {
        super(name, salary, department);
    }

    @Override
    public String toString() {
        return "Executive - " + super.toString();
    }
}

public class EmployeeDemo {
    public static void main(String[] args) {
        Manager manager = new Manager("Sarah Johnson", 85000, "Marketing");
        Executive executive = new Executive("Michael Brown", 120000, "Operations");
        
        System.out.println(manager);
        System.out.println(executive);
    }
}

Output:

Copy

Download

Name: Sarah Johnson, Salary: $85000.0, Department: Marketing
Executive - Name: Michael Brown, Salary: $120000.0, Department: Operations

33. Bank Account Inheritance

java

Copy

Download

class BankAccount {
    String accountNumber;
    double totalBalance;

    public BankAccount(String accountNumber, double totalBalance) {
        this.accountNumber = accountNumber;
        this.totalBalance = totalBalance;
    }

    public void deposit(double amount) {
        totalBalance += amount;
    }

    public void withdraw(double amount) {
        if (amount <= totalBalance) {
            totalBalance -= amount;
        } else {
            System.out.println("Insufficient balance");
        }
    }

    public double getBalance() {
        return totalBalance;
    }
}

class SavingAccount extends BankAccount {
    double interestRate;

    public SavingAccount(String accountNumber, double totalBalance, double interestRate) {
        super(accountNumber, totalBalance);
        this.interestRate = interestRate;
    }

    public void addInterest() {
        double interest = totalBalance * interestRate / 100;
        deposit(interest);
    }
}

public class BankDemo {
    public static void main(String[] args) {
        SavingAccount sa = new SavingAccount("SA12345", 5000, 3.5);
        
        System.out.println("Initial Balance: $" + sa.getBalance());
        sa.deposit(1000);
        System.out.println("After deposit: $" + sa.getBalance());
        sa.withdraw(500);
        System.out.println("After withdrawal: $" + sa.getBalance());
        sa.addInterest();
        System.out.println("After adding interest: $" + sa.getBalance());
    }
}

Output:

Copy

Download

Initial Balance: $5000.0
After deposit: $6000.0
After withdrawal: $5500.0
After adding interest: $5692.5

34. Member, Employee, and Manager Classes

java

Copy

Download

class Member {
    String name;
    int age;
    String phone;
    String address;
    double salary;

    public void setMemberDetails(String name, int age, String phone, 
                               String address, double salary) {
        this.name = name;
        this.age = age;
        this.phone = phone;
        this.address = address;
        this.salary = salary;
    }

    public void printMemberDetails() {
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
        System.out.println("Phone: " + phone);
        System.out.println("Address: " + address);
        System.out.println("Salary: $" + salary);
    }
}

class Employee extends Member {
    String specialization;

    public void printSpecialization() {
        System.out.println("Specialization: " + specialization);
    }
}

class Manager extends Member {
    String department;

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

    public void printDepartment() {
        System.out.println("Department: " + department);
    }
}

public class MemberDemo {
    public static void main(String[] args) {
        Employee emp = new Employee();
        emp.setMemberDetails("Alice Johnson", 28, "555-1234", "123 Main St", 60000);
        emp.specialization = "Software Development";
        
        Manager mgr = new Manager();
        mgr.setMemberDetails("Bob Smith", 45, "555-5678", "456 Oak Ave", 90000);
        mgr.setDepartment("IT");
        
        System.out.println("Employee Details:");
        emp.printMemberDetails();
        emp.printSpecialization();
        
        System.out.println("\nManager Details:");
        mgr.printMemberDetails();
        mgr.printDepartment();
    }
}

Output:

Copy

Download

Employee Details:
Name: Alice Johnson
Age: 28
Phone: 555-1234
Address: 123 Main St
Salary: $60000.0
Specialization: Software Development

Manager Details:
Name: Bob Smith
Age: 45
Phone: 555-5678
Address: 456 Oak Ave
Salary: $90000.0
Department: IT

35. Abstract Fmachine and Airplane Classes

java

Copy

Download

abstract class Fmachine {
    abstract void getdata();
    abstract void putdata();
}

class Airplane extends Fmachine {
    String code;
    String name;
    int capacity;

    @Override
    void getdata() {
        code = "A123";
        name = "Boeing 747";
        capacity = 416;
    }

    @Override
    void putdata() {
        System.out.println("Airplane Code: " + code);
        System.out.println("Airplane Name: " + name);
        System.out.println("Passenger Capacity: " + capacity);
    }
}

public class AirplaneDemo {
    public static void main(String[] args) {
        Airplane plane1 = new Airplane();
        plane1.getdata();
        plane1.putdata();
        
        Airplane plane2 = new Airplane();
        plane2.code = "B456";
        plane2.name = "Airbus A380";
        plane2.capacity = 853;
        plane2.putdata();
    }
}

Output:

Copy

Download

Airplane Code: A123
Airplane Name: Boeing 747
Passenger Capacity: 416
Airplane Code: B456
Airplane Name: Airbus A380
Passenger Capacity: 853

36. Rectangle Class with Area Calculation

java

Copy

Download

class Rectangle {
    double length;
    double breadth;

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

    public double computeArea() {
        return length * breadth;
    }

    public void displayArea() {
        System.out.println("Rectangle Area: " + computeArea());
    }
}

public class RectangleDemo {
    public static void main(String[] args) {
        Rectangle rect1 = new Rectangle(5, 10);
        Rectangle rect2 = new Rectangle(7, 3);
        
        rect1.displayArea();
        rect2.displayArea();
        
        if (rect1.computeArea() > rect2.computeArea()) {
            System.out.println("First rectangle has larger area");
        } else if (rect2.computeArea() > rect1.computeArea()) {
            System.out.println("Second rectangle has larger area");
        } else {
            System.out.println("Both rectangles have equal area");
        }
    }
}

Output:

Copy

Download

Rectangle Area: 50.0
Rectangle Area: 21.0
First rectangle has larger area

37. Interface num with Implementation

java

Copy

Download

interface Num {
    int add(int x, int y);
    int diff(int x, int y);
}

class Calculator implements Num {
    @Override
    public int add(int x, int y) {
        return x + y;
    }

    @Override
    public int diff(int x, int y) {
        return x - y;
    }
}

public class NumDemo {
    public static void main(String[] args) {
        Calculator calc = new Calculator();
        System.out.println("Addition: " + calc.add(10, 5));
        System.out.println("Difference: " + calc.diff(10, 5));
    }
}

Output:

Copy

Download

Addition: 15
Difference: 5

38. Interface calculate with Implementation

java

Copy

Download

interface Calculate {
    int add(int x, int y);
    int subtract(int x, int y);
}

class Arithmetic implements Calculate {
    @Override
    public int add(int x, int y) {
        return x + y;
    }

    @Override
    public int subtract(int x, int y) {
        return x - y;
    }
}

public class CalculateDemo {
    public static void main(String[] args) {
        Arithmetic arith = new Arithmetic();
        System.out.println("10 + 5 = " + arith.add(10, 5));
        System.out.println("10 - 5 = " + arith.subtract(10, 5));
    }
}

Output:

Copy

Download

10 + 5 = 15
10 - 5 = 5

39. Student, Test, and Result Classes

java

Copy

Download

class Student {
    int rollNo;

    public void readRollNo(int rollNo) {
        this.rollNo = rollNo;
    }

    public void displayRollNo() {
        System.out.println("Roll No: " + rollNo);
    }
}

class Test extends Student {
    int marks1;
    int marks2;

    public void readMarks(int m1, int m2) {
        marks1 = m1;
        marks2 = m2;
    }

    public void displayMarks() {
        System.out.println("Marks in Subject 1: " + marks1);
        System.out.println("Marks in Subject 2: " + marks2);
    }
}

class Result extends Test {
    int total;

    public void calculateTotal() {
        total = marks1 + marks2;
    }

    public void displayTotal() {
        System.out.println("Total Marks: " + total);
    }
}

public class ResultDemo {
    public static void main(String[] args) {
        Result student1 = new Result();
        student1.readRollNo(101);
        student1.readMarks(85, 90);
        student1.calculateTotal();
        
        student1.displayRollNo();
        student1.displayMarks();
        student1.displayTotal();
    }
}

Output:

Copy

Download

Roll No: 101
Marks in Subject 1: 85
Marks in Subject 2: 90
Total Marks: 175

40. Shape Interface with Rectangle and Square

java

Copy

Download

interface Shape {
    void getData();
    void displayArea();
}

class Rectangle implements Shape {
    double length;
    double width;

    @Override
    public void getData() {
        length = 5;
        width = 3;
    }

    @Override
    public void displayArea() {
        System.out.println("Rectangle Area: " + (length * width));
    }
}

class Square implements Shape {
    double side;

    @Override
    public void getData() {
        side = 4;
    }

    @Override
    public void displayArea() {
        System.out.println("Square Area: " + (side * side));
    }
}

public class ShapeDemo {
    public static void main(String[] args) {
        Rectangle rect = new Rectangle();
        Square sq = new Square();
        
        rect.getData();
        sq.getData();
        
        rect.displayArea();
        sq.displayArea();
    }
}

Output:

Copy

Download

Rectangle Area: 15.0
Square Area: 16.0

41. Number Class with getMax() Method

java

Copy

Download

class Number {
    int x, y, z;

    public Number(int x, int y, int z) {
        this.x = x;
        this.y = y;
        this.z = z;
    }

    public int getMax() {
        return Math.max(Math.max(x, y), z);
    }
}

public class NumberDemo {
    public static void main(String[] args) {
        Number num = new Number(10, 25, 15);
        System.out.println("The largest number is: " + num.getMax());
    }
}

Output:

Copy

Download

The largest number is: 25

42. Box and BoxWeight Classes

java

Copy

Download

class Box {
    double length;
    double breadth;
    double height;

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

    public double getVolume() {
        return length * breadth * height;
    }
}

class BoxWeight extends Box {
    double weight;

    public BoxWeight(double length, double breadth, double height, double weight) {
        super(length, breadth, height);
        this.weight = weight;
    }

    public void setWeight(double weight) {
        this.weight = weight;
    }

    public double getWeight() {
        return weight;
    }
}

public class BoxDemo {
    public static void main(String[] args) {
        BoxWeight box1 = new BoxWeight(2, 3, 4, 5);
        BoxWeight box2 = new BoxWeight(1, 2, 3, 4);
        
        System.out.println("Box 1 Volume: " + box1.getVolume() + ", Weight: " + box1.getWeight());
        System.out.println("Box 2 Volume: " + box2.getVolume() + ", Weight: " + box2.getWeight());
    }
}

Output:

Copy

Download

Box 1 Volume: 24.0, Weight: 5.0
Box 2 Volume: 6.0, Weight: 4.0

43. Zoo Animal Class Hierarchy

java

Copy

Download

class Animal {
    String name;
    int age;

    public Animal(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public void makeSound() {
        System.out.println("The animal makes a sound");
    }
}

class Lion extends Animal {
    public Lion(String name, int age) {
        super(name, age);
    }

    @Override
    public void makeSound() {
        System.out.println("Roar!");
    }
}

class Tiger extends Animal {
    public Tiger(String name, int age) {
        super(name, age);
    }

    @Override
    public void makeSound() {
        System.out.println("Growl!");
    }
}

class Giraffe extends Animal {
    public Giraffe(String name, int age) {
        super(name, age);
    }

    @Override
    public void makeSound() {
        System.out.println("Bleat!");
    }
}

class Zebra extends Animal {
    public Zebra(String name, int age) {
        super(name, age);
    }

    @Override
    public void makeSound() {
        System.out.println("Whinny!");
    }
}

public class ZooDemo {
    public static void main(String[] args) {
        Animal[] animals = {
            new Lion("Simba", 5),
            new Tiger("Rajah", 4),
            new Giraffe("Melman", 7),
            new Zebra("Marty", 3)
        };
        
        for (Animal animal : animals) {
            System.out.print(animal.name + " the " + animal.getClass().getSimpleName() + " says: ");
            animal.makeSound();
        }
    }
}

Output:

Copy

Download

Simba the Lion says: Roar!
Rajah the Tiger says: Growl!
Melman the Giraffe says: Bleat!
Marty the Zebra says: Whinny!