Solved[December 2022] MCS024 - OOP And Java Programming

Hey there! Welcome to KnowledgeKnot! Don't forget to share this with your friends and revisit often. Your support motivates us to create more content in the future. Thanks for being awesome!

1. (a) What is method overloading? Explain with suitable example. [5 marks]

Answer :

Method overloading is a feature in Java that allows a class to have multiple methods with the same name but different parameters. It's a form of compile-time polymorphism.

Key points:

  • Methods must have the same name but different parameter lists.
  • Return type alone is not sufficient for overloading.
  • It improves code readability and reusability.

Example:


    public class Calculator {
        // Method with two int parameters
        public int add(int a, int b) {
            return a + b;
        }

        // Method with three int parameters
        public int add(int a, int b, int c) {
            return a + b + c;
        }

        // Method with two double parameters
        public double add(double a, double b) {
            return a + b;
        }

        public static void main(String[] args) {
            Calculator calc = new Calculator();
            System.out.println(calc.add(5, 10));          // Calls first method
            System.out.println(calc.add(5, 10, 15));      // Calls second method
            System.out.println(calc.add(5.5, 10.5));      // Calls third method
        }
    }
    

In this example, the add method is overloaded three times with different parameter lists. The appropriate method is called based on the number and types of arguments passed.

1. (b) Explain the relationship between inheritance and polymorphism through an example. [5 marks]

Answer :

Inheritance and polymorphism are closely related concepts in object-oriented programming:

  • Inheritance allows a class to inherit properties and methods from another class.
  • Polymorphism allows objects of different classes to be treated as objects of a common superclass.

Their relationship is that inheritance provides a structure for polymorphism to work with, especially in the case of method overriding.

Example:


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

    // Subclass
    class Dog extends Animal {
        @Override
        public void makeSound() {
            System.out.println("The dog barks");
        }
    }

    // Subclass
    class Cat extends Animal {
        @Override
        public void makeSound() {
            System.out.println("The cat meows");
        }
    }

    public class Main {
        public static void main(String[] args) {
            Animal myAnimal = new Animal();
            Animal myDog = new Dog();
            Animal myCat = new Cat();

            myAnimal.makeSound();  // Output: The animal makes a sound
            myDog.makeSound();     // Output: The dog barks
            myCat.makeSound();     // Output: The cat meows
        }
    }
    

In this example:

  • Dog and Cat inherit from Animal (inheritance).
  • Each subclass overrides the makeSound() method.
  • We can treat Dog and Cat objects as Animal objects (polymorphism).
  • The appropriate makeSound() method is called based on the actual object type, demonstrating polymorphic behavior.

This relationship allows for flexible and extensible code, where new animal types can be easily added without changing existing code that works with Animal objects.

1. (c) Distinguish between 'Final', 'Finally' and 'Finalize' keywords. Give example for each. [6 marks]

Answer :

1. Final:

  • Used to declare constants, prevent inheritance, or prevent method overriding.
  • Can be applied to variables, methods, and classes.

Example:


    public class FinalExample {
        final int MAX_VALUE = 100;  // constant
        
        final void display() {  // cannot be overridden
            System.out.println("This is a final method");
        }
    }

    final class FinalClass {  // cannot be inherited
        // Class implementation
    }
    

2. Finally:

  • Used in exception handling to specify a block of code that will be executed regardless of whether an exception occurs or not.

Example:


    public class FinallyExample {
        public static void main(String[] args) {
            try {
                int result = 10 / 0;  // This will throw an exception
            } catch (ArithmeticException e) {
                System.out.println("Exception caught: " + e.getMessage());
            } finally {
                System.out.println("This will always be executed");
            }
        }
    }
    

3. Finalize:

  • A method called by the garbage collector before object destruction.
  • Used to perform cleanup operations before an object is garbage collected.

Example:


    public class FinalizeExample {
        protected void finalize() throws Throwable {
            try {
                System.out.println("Finalize method called");
                // Cleanup operations
            } finally {
                super.finalize();
            }
        }

        public static void main(String[] args) {
            FinalizeExample obj = new FinalizeExample();
            obj = null;  // Making the object eligible for garbage collection
            System.gc();  // Requesting garbage collection
        }
    }
    

Note: The use of finalize() is discouraged in modern Java programming due to its unpredictable nature. It's better to use try-with-resources or explicit cleanup methods.

1. (d) Explain container class, and discuss its significance in Java GUI programming. [4 marks]

Answer :

A container class in Java GUI programming is a component that can hold and organize other GUI components. It provides a way to group related components together and manage their layout.

Significance in Java GUI programming:

  • Organization: Containers help in structuring the GUI by grouping related components.
  • Layout Management: They handle the positioning and sizing of child components through layout managers.
  • Hierarchy: Containers create a hierarchy of components, allowing for nested structures in complex GUIs.
  • Event Handling: They can propagate events to child components and handle events at a higher level.

Common container classes in Java Swing:

  • JFrame: Top-level container for creating windows.
  • JPanel: General-purpose container for grouping components.
  • JScrollPane: Container that provides scrolling capabilities to its contents.

Example:


    import javax.swing.*;
    import java.awt.*;

    public class ContainerExample extends JFrame {
        public ContainerExample() {
            setTitle("Container Example");
            setSize(300, 200);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            JPanel panel = new JPanel();
            panel.setLayout(new FlowLayout());
            
            panel.add(new JButton("Button 1"));
            panel.add(new JButton("Button 2"));
            
            add(panel);
        }

        public static void main(String[] args) {
            SwingUtilities.invokeLater(() -> {
                new ContainerExample().setVisible(true);
            });
        }
    }
    

In this example, JFrame is the top-level container, and JPanel is used as a container to group two buttons together.

1. (e) Explain each component of the statement 'public static void main (string args[ ])'. [5 marks]

Answer :

The statement 'public static void main (String args[])' is the entry point of a Java program. Let's break down each component:

  • public: Access modifier that makes the main method accessible from outside the class.
  • static: Keyword that allows the method to be called without creating an instance of the class.
  • void: Return type indicating that the method doesn't return any value.
  • main: The name of the method. The Java runtime looks specifically for a method named "main" to start execution.
  • (String args[]): The parameter of the main method. It's an array of String objects that can hold command-line arguments.

This method signature is crucial because:

  • It must be public for the JVM to access it.
  • It must be static so it can be called without creating an object.
  • The void return type is mandatory.
  • The name "main" is required for the JVM to recognize it as the starting point.
  • The String array parameter allows passing command-line arguments to the program.

1. (f) What is Java applet? How is it different from Java application program? [5 marks]

Answer :

Java Applet:

A Java applet is a special type of program that is designed to be transmitted over the Internet and executed by a Java-compatible web browser. Applets are used to provide interactive features to web applications that cannot be provided by HTML alone.

Differences between Java Applets and Java Applications:

  1. Execution Environment:
    • Applet: Runs within a web browser or applet viewer.
    • Application: Runs standalone in the Java Runtime Environment (JRE).
  2. Main Method:
    • Applet: Doesn't require a main method. Uses methods like init(), start(), stop(), and destroy().
    • Application: Requires a main method as the entry point.
  3. Security:
    • Applet: Runs under strict security constraints (sandbox).
    • Application: Has full access to system resources.
  4. User Interface:
    • Applet: Typically has a GUI and is designed for user interaction within a web page.
    • Application: Can be GUI-based or console-based.
  5. Distribution:
    • Applet: Distributed over the web and loaded dynamically.
    • Application: Typically installed and run locally.

Note: Java applets are now considered obsolete technology, with modern web technologies like JavaScript and HTML5 taking their place for interactive web content.

1. (g) Explain the Java RMI architecture with the help of a diagram. [5 marks]

Answer :

Java RMI (Remote Method Invocation) is an API that allows an object to invoke a method on an object running in another JVM. The RMI architecture consists of three layers:

  1. Stub and Skeleton Layer
  2. Remote Reference Layer
  3. Transport Layer

Diagram of RMI Architecture:

RMI architecture

Explanation:

  • Stub: Client-side proxy for the remote object. It initiates the call, marshals the parameters, and unmarshals the return value.
  • Skeleton: Server-side entity that communicates with the stub, unmarshals incoming parameters, calls the actual method, and marshals the return value.
  • Remote Reference Layer: Manages references to remote objects.
  • Transport Layer: Handles the actual communication between client and server JVMs.

The client interacts with the stub as if it were the actual remote object. The stub communicates with the skeleton on the server side, which then interacts with the actual object implementation.

1. (h) What is Java Bean? Give advantages of Java beans in programming. [5 marks]

Answer :

Java Bean:

A Java Bean is a reusable software component that follows certain conventions:

  • It must have a no-argument constructor.
  • It should be serializable (implement java.io.Serializable).
  • It should provide getter and setter methods for accessing its properties.

Advantages of Java Beans in Programming:

  1. Reusability: Java Beans can be easily reused in different applications, reducing development time and effort.
  2. Encapsulation: They provide a clean way to encapsulate data and behavior, promoting good object-oriented design.
  3. Tool Support: Many development tools and frameworks provide special support for Java Beans, making them easier to use and integrate.
  4. Customization: Java Beans can be easily customized at design time or runtime, allowing for flexible application development.
  5. Event Handling: They support a standard mechanism for event handling, making it easier to create interactive applications.
  6. Persistence: Being serializable, Java Beans can be easily stored and retrieved, which is useful for saving application state.
  7. Introspection: Java Beans support introspection, allowing development tools to analyze how the bean works and customize it visually.

Example of a simple Java Bean:


    public class PersonBean implements java.io.Serializable {
        private String name;
        private int age;

        // No-argument constructor
        public PersonBean() {}

        // Getter and Setter methods
        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }
    }
    

This PersonBean follows Java Bean conventions and can be easily used in various Java applications and frameworks that support Java Beans.

2. (a) Explain the usage of Grid Layout and Grid Bag Layout in a Java Applet. [5 marks]

Answer :

Grid Layout:

  • Arranges components in a rectangular grid.
  • All components are given the same size.
  • Components are added to the grid from left to right, top to bottom.

Example usage in an applet:


    import java.applet.Applet;
    import java.awt.*;

    public class GridLayoutApplet extends Applet {
        public void init() {
            setLayout(new GridLayout(3, 2)); // 3 rows, 2 columns
            add(new Button("1"));
            add(new Button("2"));
            add(new Button("3"));
            add(new Button("4"));
            add(new Button("5"));
            add(new Button("6"));
        }
    }
    

Grid Bag Layout:

  • More flexible than GridLayout.
  • Allows components of different sizes.
  • Components can span multiple rows or columns.
  • Uses constraints to specify component placement and size.

Example usage in an applet:


    import java.applet.Applet;
    import java.awt.*;

    public class GridBagLayoutApplet extends Applet {
        public void init() {
            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();

            gbc.fill = GridBagConstraints.HORIZONTAL;
            gbc.gridx = 0;
            gbc.gridy = 0;
            add(new Button("Button 1"), gbc);

            gbc.gridx = 1;
            gbc.gridy = 0;
            add(new Button("Button 2"), gbc);

            gbc.gridx = 0;
            gbc.gridy = 1;
            gbc.gridwidth = 2;
            add(new Button("Button 3"), gbc);
        }
    }
    

GridBagLayout offers more control but is more complex to use compared to GridLayout.

2. (b) How String Class differs from String Buffer Class? Explain with suitable example. [5 marks]

Answer :

The main differences between String and StringBuffer classes are:

  1. Mutability:
    • String: Immutable (cannot be changed after creation)
    • StringBuffer: Mutable (can be modified after creation)
  2. Performance:
    • String: Less efficient for multiple modifications
    • StringBuffer: More efficient for multiple modifications
  3. Thread Safety:
    • String: Inherently thread-safe due to immutability
    • StringBuffer: Thread-safe (synchronized)

Example:


    public class StringVsStringBuffer {
        public static void main(String[] args) {
            // String example
            String str = "Hello";
            str = str + " World"; // Creates a new String object

            // StringBuffer example
            StringBuffer sb = new StringBuffer("Hello");
            sb.append(" World"); // Modifies the existing StringBuffer object

            System.out.println("String: " + str);
            System.out.println("StringBuffer: " + sb.toString());

            // Performance comparison
            long startTime = System.nanoTime();
            String s = "";
            for (int i = 0; i < 10000; i++) {
                s += "a";
            }
            long endTime = System.nanoTime();
            System.out.println("String concatenation time: " + (endTime - startTime) + " ns");

            startTime = System.nanoTime();
            StringBuffer sbf = new StringBuffer();
            for (int i = 0; i < 10000; i++) {
                sbf.append("a");
            }
            endTime = System.nanoTime();
            System.out.println("StringBuffer append time: " + (endTime - startTime) + " ns");
        }
    }
    

This example demonstrates the immutability of String vs. the mutability of StringBuffer, and shows the performance difference when doing multiple concatenations/appends.

2. (c) What is an applet? Discuss all the phases of applet life cycle. [5 marks]

Answer :

Applet: An applet is a Java program that runs in a web browser or an applet viewer. It's designed to be embedded within an HTML page and executed on the client side.

Applet Life Cycle Phases:

  1. Initialization (init()):
    • Called when the applet is first loaded.
    • Used to initialize variables and perform one-time setup tasks.
  2. Starting (start()):
    • Called after init() and each time the applet is revisited in a web page.
    • Used to start any threads or begin animations.
  3. Painting (paint()):
    • Called to draw the applet's output on the screen.
    • Invoked after init() and start(), and whenever the applet needs to redraw its contents.
  4. Stopping (stop()):
    • Called when the user navigates away from the applet's page.
    • Used to suspend threads or stop animations to conserve resources.
  5. Destruction (destroy()):
    • Called when the applet is about to be unloaded.
    • Used for final cleanup operations like closing files or network connections.

Example Applet demonstrating life cycle methods:


    import java.applet.Applet;
    import java.awt.Graphics;

    public class LifeCycleApplet extends Applet {
        String msg = "";

        public void init() {
            msg += "init() called. ";
        }

        public void start() {
            msg += "start() called. ";
        }

        public void paint(Graphics g) {
            msg += "paint() called. ";
            g.drawString(msg, 10, 30);
        }

        public void stop() {
            msg += "stop() called. ";
        }

        public void destroy() {
            msg += "destroy() called. ";
        }
    }
    

This applet demonstrates all life cycle methods, adding messages to indicate when each method is called.

2. (d) Explain GET and POST methods of servlet programming, with the help of suitable code. [5 marks]

Answer :

GET and POST are two HTTP methods used in servlet programming to send data from a client to a server:

GET Method:

  • Data is appended to the URL as query string.
  • Limited amount of data can be sent (usually up to 2048 characters).
  • Data is visible in the URL, so it's not secure for sensitive information.
  • Typically used for retrieving data.

POST Method:

  • Data is sent in the body of the HTTP request.
  • Can send large amounts of data.
  • Data is not visible in the URL, making it more secure.
  • Typically used for submitting data to be processed.

Example Servlet handling both GET and POST requests:


    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;

    public class GetPostServlet extends HttpServlet {
        protected void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            
            String name = request.getParameter("name");
            out.println("<html><body>");
            out.println("<h2>GET Request Received</h2>");
            out.println("<p>Name: " + name + "</p>");
            out.println("</body></html>");
        }

        protected void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            
            String name = request.getParameter("name");
            String email = request.getParameter("email");
            out.println("<html><body>");
            out.println("<h2>POST Request Received</h2>");
            out.println("<p>Name: " + name + "</p>");
            out.println("<p>Email: " + email + "</p>");
            out.println("</body></html>");
        }
    }
    

This servlet handles both GET and POST requests. For a GET request, it expects a 'name' parameter, while for a POST request, it expects both 'name' and 'email' parameters. The servlet demonstrates how to retrieve parameters and generate responses for both types of requests.

3. (a) Write a Java program to create a file named 'ignou.txt' and write 'Hello IGNOU' in it. [6 marks]

Answer :

To create a file and write to it in Java, we use classes from the `java.io` package. Below is a Java program that creates a file named 'ignou.txt' and writes the text 'Hello IGNOU' into it. The program handles possible IOExceptions that might occur during file operations.


import java.io.FileWriter;
import java.io.IOException;

public class CreateFile {
    public static void main(String[] args) {
        try {
            FileWriter myWriter = new FileWriter("ignou.txt");
            myWriter.write("Hello IGNOU");
            myWriter.close();
            System.out.println("Successfully wrote to the file.");
        } catch (IOException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }
    }
}
        

3. (b) Write a Java program for 'writing output on console' using PrintWriter() method. Give suitable comments for readability of your program. [6 marks]

Answer :

Using `PrintWriter` in Java, we can write formatted data to an output stream. Here is a simple Java program that demonstrates how to use `PrintWriter` to print a message to the console. The program includes comments for better readability.


import java.io.PrintWriter;

public class PrintWriterExample {
    public static void main(String[] args) {
        // Create a PrintWriter object to write to the console
        PrintWriter writer = new PrintWriter(System.out, true);
        
        // Write a message to the console
        writer.println("Hello, this is a message printed using PrintWriter.");
        
        // Close the PrintWriter
        writer.close();
    }
}
        

3. (c) What is exception in Java? What are the basic causes of occurrence of an exception? Write a program in Java, to show the concept of exception handling. Support your program with suitable comments. [8 marks]

Answer :

An exception in Java is an event that disrupts the normal flow of the program's instructions. It is a problem that arises during the execution of a program. Common causes include invalid user input, file not found, network connection loss, and arithmetic errors such as division by zero.

Below is a Java program that demonstrates the concept of exception handling using try-catch-finally blocks. The program includes comments for better understanding.


public class ExceptionHandlingExample {
    public static void main(String[] args) {
        try {
            // Attempt to divide by zero
            int result = 10 / 0;
            System.out.println("Result: " + result);
        } catch (ArithmeticException e) {
            // Handle the ArithmeticException
            System.out.println("An error occurred: Division by zero is not allowed.");
        } finally {
            // This block will always execute
            System.out.println("This is the finally block.");
        }
    }
}
        

4. (a) What is inheritance? How is inheritance related to interface? Explain, how multiple inheritance can be implemented using interface in Java. Give suitable example. [10 marks]

Answer :

Inheritance in Java is a mechanism where a new class (subclass) inherits the properties and behavior (fields and methods) of an existing class (superclass). This allows for code reusability and method overriding.

In Java, inheritance is related to interfaces because interfaces can be used to define methods that a class must implement. While Java does not support multiple inheritance with classes, multiple inheritance can be achieved using interfaces. A class can implement multiple interfaces, thereby inheriting the abstract methods of all the interfaces.

Here is an example demonstrating multiple inheritance using interfaces in Java:


interface Animal {
    void eat();
}

interface Bird {
    void fly();
}

// Multiple inheritance using interfaces
class Bat implements Animal, Bird {
    @Override
    public void eat() {
        System.out.println("Bat is eating.");
    }

    @Override
    public void fly() {
        System.out.println("Bat is flying.");
    }
}

public class MultipleInheritanceExample {
    public static void main(String[] args) {
        Bat bat = new Bat();
        bat.eat();
        bat.fly();
    }
}
        

4. (b) Explain the steps of JDBC in establishing a connection for creating a dynamic website for INSERT/UPDATE the attendance record for employees of an organization. [10 marks]

Answer :

Java Database Connectivity (JDBC) is an API for connecting and executing queries on a database. Here are the steps to establish a connection and perform INSERT/UPDATE operations:

  1. **Load the JDBC Driver:** Load the database-specific driver using `Class.forName()` method.
  2. **Establish the Connection:** Use `DriverManager.getConnection()` to create a connection to the database.
  3. **Create a Statement:** Use the `Connection.createStatement()` or `Connection.prepareStatement()` to create a statement object to execute SQL queries.
  4. **Execute the Query:** Execute the SQL INSERT/UPDATE query using the `Statement.executeUpdate()` method.
  5. **Close the Connection:** Close the statement and connection objects to free up resources.

Here is a sample code for inserting an attendance record:


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class JDBCDemo {
    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/organization";
        String user = "root";
        String password = "password";
        Connection conn = null;

        try {
            // Load the JDBC driver
            Class.forName("com.mysql.cj.jdbc.Driver");
            
            // Establish the connection
            conn = DriverManager.getConnection(url, user, password);
            
            // Create the SQL INSERT statement
            String sql = "INSERT INTO attendance (employee_id, date, status) VALUES (?, ?, ?)";
            PreparedStatement pstmt = conn.prepareStatement(sql);
            
            // Set the values
            pstmt.setInt(1, 101);
            pstmt.setDate(2, java.sql.Date.valueOf("2024-06-26"));
            pstmt.setString(3, "Present");
            
            // Execute the query
            pstmt.executeUpdate();
            System.out.println("Record inserted successfully.");
            
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (conn != null) conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
        

5. (a) Write a Java program which takes two 3 × 3 matrices as input and find sum of the two matrices. Define constructor for initializing the matrix object. Give suitable comments for readability of your code. [10 marks]

Answer :

Below is a Java program that takes two 3 × 3 matrices as input and finds the sum of the two matrices. The program defines a constructor for initializing the matrix object and includes comments for readability.


import java.util.Scanner;

class Matrix {
    int[][] data;

    // Constructor to initialize the matrix
    public Matrix(int[][] data) {
        this.data = data;
    }

    // Method to add two matrices
    public Matrix add(Matrix other) {
        int[][] result = new int[3][3];
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                result[i][j] = this.data[i][j] + other.data[i][j];
            }
        }
        return new Matrix(result);
    }

    // Method to display the matrix
    public void display() {
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                System.out.print(data[i][j] + " ");
            }
            System.out.println();
        }
    }
}

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

        // Input first matrix
        int[][] data1 = new int[3][3];
        System.out.println("Enter the first 3x3 matrix:");
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                data1[i][j] = scanner.nextInt();
            }
        }

        // Input second matrix
        int[][] data2 = new int[3][3];
        System.out.println("Enter the second 3x3 matrix:");
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                data2[i][j] = scanner.nextInt();
            }
        }

        // Create matrix objects
        Matrix matrix1 = new Matrix(data1);
        Matrix matrix2 = new Matrix(data2);

        // Add the matrices
        Matrix sumMatrix = matrix1.add(matrix2);

        // Display the result
        System.out.println("Sum of the matrices:");
        sumMatrix.display();
    }
}
        

5. (b) Write a Java program to print factorial of a number entered by user. [5 marks]

Answer :

Below is a Java program that prompts the user to enter a number and then prints the factorial of that number. The program includes comments for better readability.


import java.util.Scanner;

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

        // Prompt the user to enter a number
        System.out.print("Enter a number: ");
        int number = scanner.nextInt();

        // Calculate the factorial
        int factorial = 1;
        for (int i = 1; i <= number; i++) {
            factorial *= i;
        }

        // Print the factorial
        System.out.println("Factorial of " + number + " is: " + factorial);
    }
}
        

5. (c) Compare object oriented programming and structured programming. Give advantages of object oriented programming over the structured programming. [5 marks]

Answer :

Object-Oriented Programming (OOP) and Structured Programming are two different programming paradigms.

  • **Structured Programming:**
    • Focuses on procedure (functions).
    • Uses top-down approach.
    • Data and functions are separate.
    • Examples: C, Pascal.
  • **Object-Oriented Programming (OOP):**
    • Focuses on objects that contain both data and methods.
    • Uses bottom-up approach.
    • Encapsulation, inheritance, and polymorphism are key concepts.
    • Examples: Java, C++, Python.

**Advantages of OOP over Structured Programming:**

  • **Encapsulation:** Combines data and methods, reducing complexity.
  • **Inheritance:** Allows reuse of existing code, enhancing productivity.
  • **Polymorphism:** Supports method overriding, providing flexibility.
  • **Modularity:** Divides the program into smaller, manageable objects.