Solved[June 2023] 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) Explain the basic features of object oriented programming language. [5 marks]

Answer :

The basic features of object-oriented programming (OOP) languages are:

1. Classes and Objects: Classes are blueprints for creating objects, which are instances of classes. They encapsulate data for the object and methods to manipulate that data. Objects are instances of classes created at runtime.

2. Encapsulation: This principle involves bundling data and methods that operate on that data within a single unit (class). It includes the concept of data hiding, where an object's internal details are hidden from the outside world, and access is restricted through well-defined interfaces.

3. Inheritance: This feature allows a class (subclass or derived class) to inherit properties and methods from another class (superclass or base class). It promotes code reusability and establishes a relationship between parent and child classes.

4. Polymorphism: This allows objects to take on multiple forms. It's often achieved through method overriding (runtime polymorphism) or method overloading (compile-time polymorphism). Polymorphism enables a single interface to be used for a general class of actions.

5. Abstraction: This involves hiding complex implementation details and showing only essential features of an object. It's achieved through abstract classes and interfaces, allowing developers to focus on what an object does rather than how it does it.

1. (b) Why is Java called machine independent language? Explain the functionality of JVM. [5 marks]

Answer :

Java is called a machine-independent language because Java code can run on any platform without recompilation, following the "Write Once, Run Anywhere" principle. This is achieved through the use of bytecode and the Java Virtual Machine (JVM).

The Java Virtual Machine (JVM) enables this machine independence through the following process:

1. Compilation: Java source code (.java files) is compiled into bytecode (.class files) by the Java compiler. This bytecode is platform-independent.

2. Bytecode: This is an intermediate code that's closer to machine code but not specific to any computer architecture. It's a set of instructions that the JVM can understand.

3. JVM: The JVM acts as an interpreter, translating bytecode to machine-specific code at runtime. Each operating system has its own JVM implementation.

4. Execution: The JVM executes the translated code on the host machine. It provides a runtime environment that includes memory management, garbage collection, and security features.

5. Platform Adaptation: The JVM handles platform-specific operations, allowing the same bytecode to run on different systems. It abstracts the underlying hardware and OS, providing a consistent environment for Java programs.

This process allows Java programs to run on any device with a JVM, regardless of the underlying hardware or operating system. The developer writes and compiles the code once, and it can then be distributed and run on various platforms without modification → true "Write Once, Run Anywhere" capability.

1. (c) Differentiate between constructor and method, give example for both. [5 marks]

Answer :

Constructors and methods are both important components in object-oriented programming, but they serve different purposes and have distinct characteristics:

1. Purpose:
Constructor: Initializes object state when created. It sets up the initial values for object attributes.
Method: Performs operations or computations on an object or its data.

2. Naming:
Constructor: Must have the same name as the class. It's a special method.
Method: Can have any valid identifier as a name, following the language's naming conventions.

3. Return Type:
Constructor: No return type, not even void. It implicitly returns an instance of the class.
Method: Must have a return type (void if no value is returned).

4. Invocation:
Constructor: Automatically called when an object is created using the 'new' keyword.
Method: Explicitly called on an object or, if static, on the class itself.

5. Inheritance:
Constructor: Not inherited by subclasses, but can be called using 'super()'.
Method: Inherited by subclasses (unless private or the class is final).

Examples:

Constructor:

    public class Car {
        private String model;
        private int year;
        
        public Car(String model, int year) {
            this.model = model;
            this.year = year;
            System.out.println("A new " + year + " " + model + " car is created.");
        }
    }

    // Usage
    Car myCar = new Car("Tesla Model 3", 2023);
     

Method:

    public class Car {
        private int speed;
        
        public void accelerate(int increment) {
            speed += increment;
            System.out.println("The car accelerated. Current speed: " + speed + " km/h");
        }

        public int getCurrentSpeed() {
            return speed;
        }
    }

    // Usage
    Car myCar = new Car();
    myCar.accelerate(20);
    int currentSpeed = myCar.getCurrentSpeed();
     

1. (d) What is an abstract class? Explain the use of abstract class with an example. [5 marks]

Answer :

An abstract class is a class that cannot be instantiated and may contain abstract methods (methods without a body) as well as concrete methods (with implementation). It serves as a base for subclasses to inherit from and implement the abstract methods.

Uses of abstract classes:

1. Define a common interface for a group of related subclasses
2. Provide default implementations for some methods
3. Declare fields that are common to all subclasses
4. Enforce certain methods to be implemented by subclasses
5. Achieve a level of abstraction by hiding certain details and only showing the object's essential features

Example:

    abstract class Shape {
        protected String color;

        public Shape(String color) {
            this.color = color;
        }

        // Abstract method - must be implemented by subclasses
        public abstract double calculateArea();

        // Concrete method - provides implementation
        public void displayColor() {
            System.out.println("Color: " + color);
        }

        // Another abstract method
        public abstract void draw();
    }

    class Circle extends Shape {
        private double radius;

        public Circle(String color, double radius) {
            super(color);
            this.radius = radius;
        }

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

        @Override
        public void draw() {
            System.out.println("Drawing a circle");
        }
    }

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

        public Rectangle(String color, double width, double height) {
            super(color);
            this.width = width;
            this.height = height;
        }

        @Override
        public double calculateArea() {
            return width * height;
        }

        @Override
        public void draw() {
            System.out.println("Drawing a rectangle");
        }
    }

    // Usage
    public class Main {
        public static void main(String[] args) {
            Shape circle = new Circle("Red", 5);
            Shape rectangle = new Rectangle("Blue", 4, 6);

            circle.displayColor();
            System.out.println("Circle area: " + circle.calculateArea());
            circle.draw();

            rectangle.displayColor();
            System.out.println("Rectangle area: " + rectangle.calculateArea());
            rectangle.draw();
        }
    }
     

In this example, Shape is an abstract class with abstract methods calculateArea() and draw(). It also provides a concrete method displayColor(). Circle and Rectangle are concrete subclasses that extend Shape and implement the abstract methods.

The abstract class provides a common structure for all shapes, enforcing the implementation of area calculation and drawing for each specific shape. It also allows for shared functionality (like displaying color) and common attributes (color) across all shapes.

This demonstrates how abstract classes can be used to create a hierarchy of related classes, providing a mix of implemented and to-be-implemented functionality, which is particularly useful in designing frameworks and large-scale applications.

1. (e) What are cookies and session variables? Briefly discuss the utility of both. [5 marks]

Answer :

Cookies:

Cookies are small pieces of data stored on the client-side (user's browser) by websites. They are sent back to the server with subsequent requests, allowing the server to remember information about the user or their preferences.

Session Variables:

Session variables are server-side storage mechanisms that maintain user-specific information for the duration of a user's interaction with a web application (a session).

Utility of Cookies:

  • Remembering user preferences (e.g., language settings, theme choices)
  • Tracking user behavior for analytics
  • Maintaining login state across pages
  • Storing shopping cart information in e-commerce sites

Utility of Session Variables:

  • Storing user authentication information
  • Maintaining user-specific data during a browsing session
  • Implementing features like multi-page forms
  • Managing user state without modifying the client-side

Both cookies and session variables are crucial for creating personalized and stateful web experiences, but they differ in where data is stored (client vs. server) and how long it persists.

1. (f) Explain the different steps in the life cycle of an applet. [5 marks]

Answer :

The life cycle of a Java applet consists of the following steps:

1. Initialization (init()): This method is called when the applet is first loaded. It's used to initialize variables, load images or fonts, and set up the initial state of the applet.

2. Starting (start()): Called after init() and each time the applet is revisited in a web page. It starts the applet's execution, often used to begin animations or start threads.

3. Painting (paint()): Invoked to draw the applet's output on the screen. It's called 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. It's used to suspend threads or stop ongoing processes to conserve resources.

5. Destruction (destroy()): The final method called before the applet is unloaded. It's used for cleanup operations like closing files or network connections.

This lifecycle allows for efficient resource management and ensures the applet behaves correctly in a web environment. The browser or applet viewer manages these transitions automatically.

1. (g) Discuss the relationship between data abstraction and encapsulation. [5 marks]

Answer :

Data abstraction and encapsulation are closely related concepts in object-oriented programming:

Data Abstraction:

Data abstraction is the process of hiding complex implementation details and showing only the essential features of an object. It focuses on what an object does rather than how it does it.

Encapsulation:

Encapsulation is the bundling of data and the methods that operate on that data within a single unit (class). It includes the concept of data hiding, where an object's internal details are hidden from the outside world.

Relationship:

  • Encapsulation is a mechanism that enables data abstraction.
  • Data abstraction focuses on the observable behavior of an object, while encapsulation focuses on the implementation that gives rise to this behavior.
  • Encapsulation provides a way to achieve data abstraction by bundling the data and methods together and controlling access through access modifiers.
  • Data abstraction often relies on encapsulation to hide the internal details and expose only what's necessary.

In essence, data abstraction is the what (the abstract view of the data) and encapsulation is the how (the technique used to achieve and maintain this abstraction). Together, they help in creating more maintainable and modular code.

1. (h) Explain the usage of container in Java Applet and Servlet. [5 marks]

Answer :

Containers in Java play crucial roles in both Applets and Servlets, though their usage differs:

Containers in Applets:

  • In Applets, containers are GUI components that can hold other GUI components.
  • Common containers include Panel, Frame, and Applet itself.
  • They manage the layout and display of child components within the applet's visual interface.
  • Containers help in organizing and structuring the user interface of the applet.

Containers in Servlets:

  • For Servlets, the container (often called Servlet Container or Web Container) is a part of the web server that manages the servlet's lifecycle.
  • Examples include Apache Tomcat, Jetty, and WebSphere.
  • The container handles communication between the servlet and the web server.
  • It manages servlet initialization, execution, and destruction.
  • Provides services like session management, security, and concurrency handling.

Key Differences:

While both are called containers, they serve different purposes. Applet containers are UI-focused, managing visual components, while Servlet containers are server-side runtime environments managing the lifecycle and execution of servlets.

Understanding these container concepts is crucial for developing effective Java-based web applications, whether client-side (Applets) or server-side (Servlets).

2. (a) Explain how exception handling is performed in Java. Briefly discuss the concept of checked exception and unchecked exception, with an example of each. [10 marks]

Answer :

Exception Handling in Java:

Exception handling in Java is performed using try-catch blocks and throw statements. The process involves:

  1. Try block: Contains code that might throw an exception
  2. Catch block: Handles the exception if it occurs
  3. Finally block: (Optional) Executes regardless of whether an exception occurred
  4. Throw statement: Used to explicitly throw an exception

Checked Exceptions:

Checked exceptions are exceptions that must be either caught or declared in the method signature. They are checked at compile-time.

Example:


    import java.io.FileReader;
    import java.io.IOException;

    public class CheckedExceptionExample {
        public static void main(String[] args) {
            try {
                FileReader file = new FileReader("nonexistent.txt");
            } catch (IOException e) {
                System.out.println("File not found: " + e.getMessage());
            }
        }
    }
    

Unchecked Exceptions:

Unchecked exceptions are exceptions that don't need to be explicitly caught or declared. They usually indicate programming errors and are subclasses of RuntimeException.

Example:


    public class UncheckedExceptionExample {
        public static void main(String[] args) {
            int[] numbers = {1, 2, 3};
            try {
                System.out.println(numbers[5]); // Accessing out of bounds index
            } catch (ArrayIndexOutOfBoundsException e) {
                System.out.println("Array index out of bounds: " + e.getMessage());
            }
        }
    }
    

The key difference is that checked exceptions force the programmer to handle potential errors, while unchecked exceptions represent runtime errors that are often due to programming mistakes.

2. (b) Briefly discuss the concept of listener in Java. Write a program in Java to implement mouse motion listener, support your program with suitable comments. [10 marks]

Answer :

Concept of Listener in Java:

In Java, a listener is an interface that allows an object to receive notifications when a specific event occurs. It's a key part of event handling in Java, especially in GUI programming. Listeners are used to create interactive applications that respond to user actions or system events.

Here's a program implementing a MouseMotionListener:


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

    public class MouseMotionListenerExample extends JFrame implements MouseMotionListener {
        private JLabel statusBar;

        public MouseMotionListenerExample() {
            // Set up the frame
            setTitle("Mouse Motion Listener Example");
            setSize(300, 200);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            // Create a status bar to display mouse coordinates
            statusBar = new JLabel("Move the mouse inside the window");
            add(statusBar);

            // Add mouse motion listener to the frame
            addMouseMotionListener(this);
        }

        // Implement MouseMotionListener methods

        @Override
        public void mouseMoved(MouseEvent e) {
            // Update status bar with current mouse coordinates
            statusBar.setText("Mouse moved to: (" + e.getX() + ", " + e.getY() + ")");
        }

        @Override
        public void mouseDragged(MouseEvent e) {
            // Update status bar when mouse is dragged
            statusBar.setText("Mouse dragged to: (" + e.getX() + ", " + e.getY() + ")");
        }

        public static void main(String[] args) {
            // Create and display the frame on the Event Dispatch Thread
            SwingUtilities.invokeLater(() -> {
                new MouseMotionListenerExample().setVisible(true);
            });
        }
    }
    

Explanation:

  • The class extends JFrame and implements MouseMotionListener interface.
  • In the constructor, we set up a basic window and add a JLabel as a status bar.
  • We add the MouseMotionListener to the frame using addMouseMotionListener(this).
  • The mouseMoved() method is called when the mouse is moved within the frame.
  • The mouseDragged() method is called when the mouse is dragged within the frame.
  • Both methods update the status bar with the current mouse coordinates.
  • The main method creates an instance of the class and makes it visible.

This program demonstrates how listeners can be used to respond to user interactions in a GUI application. When run, it will display a window where the status bar updates with the mouse's coordinates as it moves or is dragged within the window.

3. (a) What is string class? How is it different from String Buffer class? Write a Java program to find the length of a given string. [7 marks]

Answer :

String Class:

The String class in Java is an immutable class that represents a sequence of characters. Once a String object is created, its value cannot be changed.

StringBuffer Class:

StringBuffer is a mutable class that also represents a sequence of characters. Unlike String, StringBuffer objects can be modified after creation.

Key Differences:

  • Mutability: String is immutable, StringBuffer is mutable.
  • Performance: StringBuffer is more efficient for frequent modifications.
  • Thread Safety: StringBuffer is synchronized and thread-safe, while String is not.
  • Memory: String can be more memory-efficient for unchanging text.

Java Program to Find String Length:


    public class StringLengthExample {
        public static void main(String[] args) {
            // Create a string
            String sampleString = "Hello, World!";

            // Get the length of the string
            int length = sampleString.length();

            // Print the result
            System.out.println("The length of the string "" + sampleString + "" is: " + length);
        }
    }
    

This program demonstrates how to use the length() method of the String class to find the number of characters in a string. When run, it will output:

The length of the string "Hello, World!" is: 13

3. (b) What is servlet? Explain how session handling is performed in servlet programming. [7 marks]

Answer :

Servlet:

A servlet is a Java programming language class used to extend the capabilities of servers that host applications accessed by means of a request-response programming model. Servlets are primarily used to process or store data submitted by an HTML form, provide dynamic content, and manage state information that doesn't exist in the stateless HTTP protocol.

Session Handling in Servlet Programming:

Session handling in servlets allows the server to maintain state information about a series of requests from the same client. Here's how it's typically performed:

  1. Session Creation: When a client makes the first request, the server creates a new HttpSession object.
  2. Session ID: A unique session ID is generated and typically stored as a cookie in the client's browser.
  3. Retrieving Session: In subsequent requests, the server retrieves the existing session using the session ID.
  4. Storing Data: Servlets can store data in the session using setAttribute() method.
  5. Retrieving Data: Data can be retrieved from the session using getAttribute() method.
  6. Session Timeout: Sessions typically have a timeout period after which they are invalidated.

Example Code Snippet:


    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        // Get the session object
        HttpSession session = request.getSession();

        // Store data in the session
        session.setAttribute("username", "JohnDoe");

        // Retrieve data from the session
        String username = (String) session.getAttribute("username");

        // Set or get session timeout (in seconds)
        session.setMaxInactiveInterval(1800); // 30 minutes

        // Invalidate the session
        // session.invalidate();
    }
    

This approach allows servlets to maintain user-specific information across multiple requests, enabling the development of stateful web applications.

3. (c) What is an Interface? Write a Java program to show how a class implements two interfaces. [6 marks]

Answer :

Interface:

An interface in Java is an abstract type that is used to specify a behavior that classes must implement. It contains abstract methods (methods without a body) and can also include constants, default methods, and static methods.

Key Characteristics of Interfaces:

  • All methods in an interface are implicitly public and abstract.
  • Interfaces can extend multiple interfaces.
  • A class can implement multiple interfaces.

Java Program Implementing Two Interfaces:


    // First interface
    interface Printable {
        void print();
    }

    // Second interface
    interface Displayable {
        void display();
    }

    // Class implementing both interfaces
    class Document implements Printable, Displayable {
        private String content;

        public Document(String content) {
            this.content = content;
        }

        // Implementing print() from Printable
        @Override
        public void print() {
            System.out.println("Printing: " + content);
        }

        // Implementing display() from Displayable
        @Override
        public void display() {
            System.out.println("Displaying: " + content);
        }
    }

    // Main class to demonstrate
    public class InterfaceExample {
        public static void main(String[] args) {
            Document doc = new Document("Hello, World!");
            doc.print();   // Calls print() method
            doc.display(); // Calls display() method
        }
    }
    

In this program:

  • We define two interfaces: Printable and Displayable.
  • The Document class implements both interfaces.
  • The class provides implementations for both print() and display() methods.
  • In the main method, we create a Document object and call both methods.

This example demonstrates how a single class can implement multiple interfaces, allowing for a form of multiple inheritance of behavior in Java.

4. (a) What is RMI in Java? Write the steps to create stub and skeleton. [7 marks]

Answer :

RMI (Remote Method Invocation):

RMI in Java is a mechanism that allows an object residing in one Java Virtual Machine (JVM) to invoke methods on an object in another JVM. RMI provides a way to create distributed Java applications where methods of remote Java objects can be invoked from other Java virtual machines, possibly on different hosts.

Key Components of RMI:

  • Remote Interface: Defines the methods that can be invoked remotely.
  • Remote Object: The implementation of the remote interface.
  • Stub: Client-side proxy for the remote object.
  • Skeleton: Server-side entity that communicates with the stub.

Steps to Create Stub and Skeleton:

  1. Define the Remote Interface:
    
        import java.rmi.Remote;
        import java.rmi.RemoteException;
    
        public interface RemoteService extends Remote {
            String sayHello() throws RemoteException;
        }
                
  2. Implement the Remote Interface:
    
        import java.rmi.RemoteException;
        import java.rmi.server.UnicastRemoteObject;
    
        public class RemoteServiceImpl extends UnicastRemoteObject implements RemoteService {
            public RemoteServiceImpl() throws RemoteException {
                super();
            }
    
            @Override
            public String sayHello() throws RemoteException {
                return "Hello, World!";
            }
        }
                
  3. Compile the Interface and Implementation:

    Use javac to compile both files.

  4. Generate Stub and Skeleton:

    Use the rmic tool to generate stub and skeleton classes:

    rmic RemoteServiceImpl

  5. Start the RMI Registry:

    Run the RMI registry:

    start rmiregistry

  6. Create and Run the Server:
    
        import java.rmi.registry.LocateRegistry;
        import java.rmi.registry.Registry;
    
        public class Server {
            public static void main(String[] args) {
                try {
                    RemoteService service = new RemoteServiceImpl();
                    Registry registry = LocateRegistry.createRegistry(1099);
                    registry.rebind("RemoteService", service);
                    System.out.println("Server is running...");
                } catch (Exception e) {
                    System.err.println("Server exception: " + e.toString());
                    e.printStackTrace();
                }
            }
        }
                

Note: In modern versions of Java (since Java 5), the creation of stub classes using rmic is not necessary as they are generated dynamically at runtime. However, understanding the concept of stubs and skeletons is still important for grasping RMI architecture.

4. (b) Write a Java program to create a volume class. Derive cube and sphere classes from it. Define constructor for these three classes. [7 marks]

Answer :

Here's a Java program that creates a Volume class and derives Cube and Sphere classes from it, with constructors for all three classes:


    // Abstract base class for volume
    abstract class Volume {
        protected double volume;

        // Constructor
        public Volume() {
            this.volume = 0;
        }

        // Abstract method to calculate volume
        public abstract void calculateVolume();

        // Method to get volume
        public double getVolume() {
            return volume;
        }
    }

    // Cube class derived from Volume
    class Cube extends Volume {
        private double side;

        // Constructor
        public Cube(double side) {
            super();
            this.side = side;
            calculateVolume();
        }

        @Override
        public void calculateVolume() {
            this.volume = Math.pow(side, 3);
        }
    }

    // Sphere class derived from Volume
    class Sphere extends Volume {
        private double radius;

        // Constructor
        public Sphere(double radius) {
            super();
            this.radius = radius;
            calculateVolume();
        }

        @Override
        public void calculateVolume() {
            this.volume = (4.0 / 3.0) * Math.PI * Math.pow(radius, 3);
        }
    }

    // Main class to demonstrate
    public class VolumeDemo {
        public static void main(String[] args) {
            Cube cube = new Cube(5);
            System.out.println("Volume of Cube: " + cube.getVolume());

            Sphere sphere = new Sphere(3);
            System.out.println("Volume of Sphere: " + sphere.getVolume());
        }
    }
    

In this program:

  • The Volume class is an abstract base class with an abstract method calculateVolume().
  • The Cube class extends Volume and implements calculateVolume() for a cube.
  • The Sphere class extends Volume and implements calculateVolume() for a sphere.
  • Each class has its own constructor that initializes its specific attributes and calls calculateVolume().
  • The main method demonstrates the creation and use of Cube and Sphere objects.

4. (c) What is Synchronization? Explain how methods are synchronized in Java, with the help of an example. [6 marks]

Answer :

Synchronization in Java is a mechanism to control access to shared resources in a multi-threaded environment. It ensures that only one thread can access the synchronized code at a time, preventing race conditions and ensuring thread safety.

How methods are synchronized in Java:

  1. Using the synchronized keyword before the method declaration.
  2. Using synchronized blocks within methods.

Example of synchronized methods:


    public class BankAccount {
        private int balance = 0;

        // Synchronized method for deposit
        public synchronized void deposit(int amount) {
            balance += amount;
            System.out.println("Deposited: " + amount + ", New Balance: " + balance);
        }

        // Synchronized method for withdrawal
        public synchronized void withdraw(int amount) {
            if (balance >= amount) {
                balance -= amount;
                System.out.println("Withdrawn: " + amount + ", New Balance: " + balance);
            } else {
                System.out.println("Insufficient funds");
            }
        }
    }

    class TransactionThread extends Thread {
        private BankAccount account;
        private boolean isDeposit;
        private int amount;

        public TransactionThread(BankAccount account, boolean isDeposit, int amount) {
            this.account = account;
            this.isDeposit = isDeposit;
            this.amount = amount;
        }

        public void run() {
            if (isDeposit) {
                account.deposit(amount);
            } else {
                account.withdraw(amount);
            }
        }
    }

    public class SynchronizationExample {
        public static void main(String[] args) {
            BankAccount account = new BankAccount();
            TransactionThread t1 = new TransactionThread(account, true, 1000);
            TransactionThread t2 = new TransactionThread(account, false, 500);

            t1.start();
            t2.start();
        }
    }
    

In this example:

  • The deposit() and withdraw() methods are synchronized, ensuring that only one thread can access them at a time.
  • This prevents race conditions where two threads might try to modify the balance simultaneously.
  • The TransactionThread class simulates concurrent transactions on the account.
  • The main method creates two threads that perform a deposit and a withdrawal concurrently.

Synchronization ensures that these operations are thread-safe and maintain the integrity of the account balance.

5. Write short notes on the following: [5×4=20 marks]
(a) Dynamic Binding
(b) Stream Tokenizer
(c) JDBC Drivers
(d) Function Overloading

Answer :

(a) Dynamic Binding:

  • Dynamic binding, also known as late binding, is a mechanism in Java where the method call is resolved at runtime rather than compile time.
  • It's associated with polymorphism and method overriding in inheritance.
  • The JVM determines which method to call based on the actual object type, not the reference type.
  • This allows for more flexible and extensible code, as subclasses can provide specific implementations of methods.
  • Example: When a method is called on a superclass reference to a subclass object, the subclass's overridden method is executed.

(b) Stream Tokenizer:

  • StreamTokenizer is a class in Java that breaks an input stream into tokens, making it easier to parse.
  • It's particularly useful for reading formatted input from files or strings.
  • Tokens can be numbers, words, or individual characters.
  • It provides methods like nextToken() to read the next token and various methods to check the token type.
  • Useful in scenarios like parsing configuration files, simple programming languages, or structured text data.

(c) JDBC Drivers:

  • JDBC (Java Database Connectivity) drivers are software components that enable Java applications to interact with databases.
  • They implement the JDBC API for a particular database management system.
  • Four types of JDBC drivers:
    1. Type 1: JDBC-ODBC Bridge driver
    2. Type 2: Native-API driver (partly Java driver)
    3. Type 3: Network-Protocol driver (fully Java driver)
    4. Type 4: Thin driver (pure Java driver)
  • Type 4 drivers are most commonly used as they are database-specific, entirely written in Java, and provide the best performance.

(d) Function Overloading:

  • Function 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 or static polymorphism.
  • Methods can be overloaded by changing:
    1. The number of parameters
    2. The data types of parameters
    3. The order of parameters
  • Return type alone is not sufficient for overloading; the parameter list must differ.
  • It enhances code readability and reusability by allowing related methods to have the same name.
  • Example: print(int i), print(double d), print(String s) are overloaded methods.