0% found this document useful (0 votes)
51 views41 pages

MCS-206 2024-25 Em@

The document is a solved assignment for the MCS-206 course for the academic year 2024-25, consisting of eight questions worth 80 marks, with an additional 20 marks for viva voce. It covers various topics in Java programming, including data types, object-oriented programming features, classes, inheritance, abstract classes, polymorphism, and exception handling. Each section provides explanations, examples, and code snippets to illustrate the concepts discussed.

Uploaded by

jicof22068
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
51 views41 pages

MCS-206 2024-25 Em@

The document is a solved assignment for the MCS-206 course for the academic year 2024-25, consisting of eight questions worth 80 marks, with an additional 20 marks for viva voce. It covers various topics in Java programming, including data types, object-oriented programming features, classes, inheritance, abstract classes, polymorphism, and exception handling. Each section provides explanations, examples, and code snippets to illustrate the concepts discussed.

Uploaded by

jicof22068
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

MCS-206

SOLVED ASSIGNMENT
2024-25
Note: This assignment has eight questions of 80 Marks. Answer all questions. Rest 20
marks are for viva voce. You may use illustrations and diagrams to enhance the
explanations. Please go through the guidelines regarding assignments given in the
Programme Guide for the format of presentation
Question1: (a) Explain different data types available in java. (5 Marks)
Ans. In Java, data types are categorized into primitive and non-primitive (reference) data
types. Each type defines the nature and size of data that can be stored in variables.

1. Primitive Data Types:


Primitive data types are the most basic types that store simple values.

- byte: 8-bit signed integer. Range: -128 to 127.


- Example: `byte b = 100;`

- short: 16-bit signed integer. Range: -32,768 to 32,767.


- Example: `short s = 1000;`

- int: 32-bit signed integer. Range: -2^31 to 2^31-1.


- Example: `int i = 100000;`

- long: 64-bit signed integer. Range: -2^63 to 2^63-1.


- Example: `long l = 10000000000L;`

- float: 32-bit floating point for decimal values.


- Example: `float f = 10.5f;`

- double: 64-bit floating point, more precision than float.


- Example: `double d = 20.99;`

- char: 16-bit Unicode character. Used to store a single character.


- Example: `char c = 'A';`

Page 1 of 40
- boolean: Represents two possible values: `true` or `false`.
- Example: `boolean flag = true;`

2. Non-Primitive Data Types:


Non-primitive data types store references to objects.

- String: A sequence of characters.


- Example: `String str = "Hello";`

- Arrays: A collection of elements of the same type.


- Example: `int[] arr = {1, 2, 3};`

- Classes, Interfaces, and Enums: User-defined data types to model complex data.

Java is statically typed, meaning variables must be declared with a type before use, ensuring
type safety and preventing errors.

(b) Explain features of object oriented programming. Explain role of JVM in java
programming. (5 Marks)
Ans. Features of Object-Oriented Programming (OOP)

Object-Oriented Programming (OOP) is a programming paradigm based on the concept of


"objects," which are instances of classes. Key features of OOP include:

1. Encapsulation:
- Definition: Encapsulation is the bundling of data (attributes) and methods (functions) that
operate on the data into a single unit or class.
- Benefit: It hides the internal state of an object from the outside world and only exposes a
controlled interface, enhancing security and modularity.

2. Inheritance:

Page 2 of 40
- Definition: Inheritance allows a new class (subclass or derived class) to inherit properties
and behaviors (methods) from an existing class (superclass or base class).
- Benefit: It promotes code reusability and establishes a natural hierarchy between classes,
reducing redundancy and facilitating easier maintenance.

3. Polymorphism:
- Definition: Polymorphism enables objects to be treated as instances of their parent class
rather than their actual class. It allows methods to do different things based on the object it is
acting upon.
- Benefit: It simplifies code and enhances flexibility by allowing one interface to be used
for a general class of actions.

4. Abstraction:
- Definition: Abstraction is the concept of hiding the complex implementation details and
showing only the essential features of an object.
- Benefit: It simplifies the interaction with complex systems and focuses on what an object
does rather than how it achieves it.

Role of JVM in Java Programming

The Java Virtual Machine (JVM) is a crucial component of Java's architecture. Its role
includes:

1. Bytecode Execution:
- Function: The JVM executes Java bytecode, which is an intermediate representation of
Java programs compiled by the Java compiler. This allows Java applications to be platform-
independent.

2. Memory Management:
- Function: The JVM handles memory allocation and garbage collection, managing
resources automatically and preventing memory leaks and other issues.

3. Platform Independence:

Page 3 of 40
- Function: By interpreting bytecode rather than source code, the JVM allows Java
applications to run on any platform that has a compatible JVM implementation, adhering to
the "write once, run anywhere" principle.

4. Security:
- Function: The JVM provides a secure execution environment through its bytecode verifier
and runtime checks, preventing potentially harmful operations and protecting against security
threats.

Overall, the JVM abstracts away platform-specific details, allowing Java programs to be
portable, secure, and efficient across different operating systems and hardware.

Question2: (a) What is a class? How a class is defined in Java? Explain use different
access specifiers in java. (5 Marks)
Ans. What is a Class in Java?

A class in Java is a blueprint or template that defines the structure and behavior (data
members and methods) of objects. It encapsulates data (fields) and functionalities (methods)
and serves as the foundation for object-oriented programming in Java. Each object is an
instance of a class.

Defining a Class in Java

A class is defined using the `class` keyword followed by the class name. The structure of a
class includes fields (variables) and methods (functions) that define the properties and
behavior of the objects created from the class.

Syntax of Class Definition:

Page 4 of 40
Example:

In this example, `Car` is a class with fields `model` and `year`, and the method
`displayDetails()` prints the car's details.

Access Specifiers in Java

Access specifiers (or access modifiers) define the visibility or accessibility of classes,
methods, and variables.

1. public:
- Accessible from any other class.
- Example:

Page 5 of 40
2. private:
- Accessible only within the class in which it is declared.
- Example:

3. protected:
- Accessible within the same package and by subclasses in other packages.
- Example:

4. default (no modifier):


- Accessible only within the same package.
- Example:

Page 6 of 40
Each specifier controls the level of access, promoting encapsulation and security in Java.

(b) Explain use of this, final and static keywords in Java. (3 Marks)
Ans. In Java, the `this`, `final`, and `static` keywords each have distinct roles and purposes.

1. `this` Keyword:
The `this` keyword in Java refers to the current instance of the class. It is commonly used to
differentiate between class fields and parameters with the same name. For example, in a
constructor or a method, `this.field` refers to the class-level field, while `field` refers to the
method or constructor parameter. Additionally, `this` can be used to call other constructors in
the same class (constructor chaining) and to pass the current instance as a parameter to other
methods or constructors. Here's an example:

2. `final` Keyword:
The `final` keyword in Java is used to define constants, prevent method overriding, and
inheritance. When applied to a variable, `final` makes it a constant; its value cannot be
changed once assigned. For methods, `final` prevents subclasses from overriding the method,
ensuring that the method’s implementation remains constant across inheritance hierarchies.
When applied to classes, `final` prevents the class from being subclassed, thus ensuring that
its functionality cannot be extended. Examples:

Page 7 of 40
3. `static` Keyword:
The `static` keyword denotes that a member belongs to the class rather than instances of the
class. Static variables are shared among all instances of a class, making them suitable for
constants or shared data. Static methods can be called without creating an instance of the
class and can only directly access other static members. Static blocks are used for static
initializations. Example:

In summary, `this` refers to the current instance, `final` ensures immutability and prevents
overriding/inheritance, and `static` defines class-level members shared across instances.

(c) What is Character class? Explain use of compareTo and toString methods of
Character class. (2 Marks)
Ans. Character Class in Java

The Character class in Java is a wrapper class for the primitive data type `char`. It provides
methods to manipulate characters (such as checking if a character is a digit, letter, uppercase,
lowercase, etc.) and converting characters to different formats.
Example of Creating a Character Object:

This wraps the primitive `char` value `'A'` into an object of the `Character` class.

`compareTo()` Method of the Character Class

The `compareTo()` method compares two `Character` objects numerically. It returns:


- `0` if both characters are equal,
- A negative integer if the first character is less than the second,
- A positive integer if the first character is greater than the second.

Syntax:

Example:

`toString()` Method of the Character Class

The `toString()` method converts the `Character` object to its corresponding `String`
representation.

Syntax:
Example:

Both methods are essential for comparing characters and converting them into strings when
needed, facilitating easier handling and manipulation of character data.

Question 3: (a) Write a java program to find sum of two matrices. Define proper class
and methods in your program. (4 Marks)
Ans. Here's a simple Java program to find the sum of two matrices. It defines a class called
`Matrix` with methods to input and add two matrices.

Java Program to Find the Sum of Two Matrices:


Explanation:
- Matrix Class: This class has fields for rows, columns, and the matrix itself. It contains
methods to input matrix elements, add two matrices, and display the matrix.
- addMatrices(): This method takes another `Matrix` object as input, adds the corresponding
elements of both matrices, and returns a new `Matrix` object containing the sum.
- Main Method: The program creates two matrices, inputs their elements, computes their sum,
and displays the result.

Example Output:
(b) Explain use of java File class and its methods with the help of examples (6 Marks)
Ans.
Question 4: (a) What is inheritance? What are different types of inheritance supported
by java? Explain how inheritance is implemented in java with the help of an example. (6
Marks)
Ans. Inheritance is a fundamental concept in object-oriented programming (OOP) that allows
a new class to inherit properties and behaviors (methods) from an existing class. This
promotes code reusability and establishes a natural hierarchy between classes. In Java,
inheritance helps in creating a new class (subclass or derived class) based on an existing class
(superclass or base class).

Types of Inheritance in Java

1. Single Inheritance: A class inherits from only one superclass.


2. Multiple Inheritance (through interfaces): Java does not support multiple inheritance
directly with classes to avoid complexity and ambiguity. However, it is achievable through
interfaces.

3. Multilevel Inheritance: A class inherits from another class, which in turn inherits from
another class.
4. Hierarchical Inheritance: Multiple classes inherit from a single superclass.
```java
```

5. Hybrid Inheritance: Combines multiple and hierarchical inheritance. This is complex and
not directly supported in Java with classes due to ambiguity issues.

Implementation Example

Here’s an example of single inheritance:


In this example, `Car` inherits the `start` method from `Vehicle` and adds its own method,
`honk`. The `Car` object can call both the inherited and its own methods, demonstrating how
inheritance facilitates code reuse and extension.
(b) What is abstract class? Explain its advantages. How is it different from Interface? (4
Marks)
Ans. An abstract class in Java is a class that cannot be instantiated on its own and is intended
to be subclassed. It serves as a blueprint for other classes and can include both abstract
methods (methods without a body) and concrete methods (methods with a body). Abstract
classes are defined using the `abstract` keyword.

Advantages of Abstract Classes

1. Code Reusability: Abstract classes allow you to define common behavior in a single place,
which can be inherited by multiple subclasses. This avoids code duplication and promotes
code reuse.
2. Partial Implementation: They enable you to provide a partial implementation that can be
shared among multiple subclasses while leaving some methods abstract for subclasses to
implement. This is useful for defining common templates or partial behavior.

3. Encapsulation: Abstract classes allow you to encapsulate fields and methods that are shared
among all subclasses, which can help in organizing and managing code better.

4. Enhanced Design: By using abstract classes, you can design a robust class hierarchy with a
clear separation of common and specific functionalities. This makes the design more
maintainable and understandable.

Difference from Interface

1. Abstract Methods:
- Abstract Class: Can have both abstract methods (without implementation) and concrete
methods (with implementation). Subclasses can inherit concrete methods.
- Interface: Prior to Java 8, interfaces could only have abstract methods. From Java 8
onwards, interfaces can also have default methods with implementation.

2. Fields:
- Abstract Class: Can have instance variables (fields) with any access modifiers (private,
protected, public).
- Interface: Can only have `public static final` fields (constants), and they are implicitly
`public` and `static`.

3. Constructor:
- Abstract Class: Can have constructors, which can be used by subclasses to initialize the
state.
- Interface: Cannot have constructors.

4. Multiple Inheritance:
- Abstract Class: A class can only inherit from one abstract class (single inheritance).
- Interface: A class can implement multiple interfaces (multiple inheritance), allowing
greater flexibility in combining functionalities.
5. Inheritance:
- Abstract Class: A class can extend only one abstract class but can implement multiple
interfaces.
- Interface: An interface can extend multiple other interfaces, providing a form of multiple
inheritance.

Example
In this example, `Animal` is an abstract class with an abstract method `makeSound` and a
concrete method `sleep`. `Dog` extends `Animal` and provides an implementation for
`makeSound`. `Drawable` is an interface with an abstract method `draw` and a default
method `resize`. `Circle` implements `Drawable` and provides an implementation for `draw`,
while inheriting the default implementation of `resize`.
Question 5: (a) What is polymorphism? Explain its advantages with examples. (4
Marks)
Ans. Polymorphism is a core concept in object-oriented programming (OOP) that allows
objects of different classes to be treated as objects of a common superclass. It is derived from
the Greek words "poly" (many) and "morph" (form), meaning "many forms." Polymorphism
enables a single interface to be used for different underlying data types, allowing for
flexibility and the ability to handle objects in a more generic way.

Types of Polymorphism

1. Compile-Time Polymorphism (Method Overloading):


- Method Overloading: Allows multiple methods with the same name but different
parameters in the same class. The method that gets invoked is determined at compile-time
based on the method signature.
2. Runtime Polymorphism (Method Overriding):
- Method Overriding: Allows a subclass to provide a specific implementation of a method
that is already defined in its superclass. The method to be executed is determined at runtime
based on the object's actual class type.
Advantages of Polymorphism

1. Code Reusability: Allows for writing more generic and reusable code. By using
polymorphism, the same interface or method name can be used for different data types,
reducing redundancy and improving code maintenance.
2. Flexibility and Extensibility: Makes it easier to extend and modify the system. New classes
can be introduced without altering the existing code that relies on the polymorphic behavior.
For instance, adding a new subclass does not require changes to the methods that operate on
the superclass.

3. Improved Maintenance: Simplifies code management. By relying on polymorphic


behavior, you can modify or enhance functionalities with minimal changes to existing code.
This leads to cleaner and more manageable code.

4. Enhanced Abstraction: Allows for a more abstract design. By programming to an interface


or superclass rather than concrete implementations, you achieve a higher level of abstraction,
making your system more modular and adaptable.

In summary, polymorphism enhances flexibility, reusability, and maintainability of code,


making it a powerful feature in object-oriented programming.
(b) What is an exception? Explain various causes of exceptions. How exceptions are
handled in java? Explain how user defined exceptions are created in Java.
Ans. An exception in Java is an event that disrupts the normal flow of a program's execution.
It is a signal that an unusual or exceptional condition has occurred, which can potentially
cause the program to terminate or behave unexpectedly if not handled properly. Exceptions
are objects that represent these unexpected conditions and can be caught and managed to
ensure that the program continues to run or terminates gracefully.

Causes of Exceptions

Exceptions can be caused by a variety of issues, including:

1. Input/Output Errors:
- File Not Found: Trying to access a file that does not exist (e.g.,
`FileNotFoundException`).
- Read/Write Errors: Issues while reading from or writing to a file (e.g., `IOException`).

2. Arithmetic Errors:
- Division by Zero: Attempting to divide a number by zero (e.g., `ArithmeticException`).
3. Null Pointer Errors:
- Dereferencing Null: Trying to use an object reference that is `null` (e.g.,
`NullPointerException`).

4. Array Errors:
- Array Index Out of Bounds: Accessing an invalid index in an array (e.g.,
`ArrayIndexOutOfBoundsException`).

5. Class Loading Errors:


- Class Not Found: Attempting to load a class that cannot be found (e.g.,
`ClassNotFoundException`).

6. Type Errors:
- Invalid Type Casting: Trying to cast an object to a type that it is not (e.g.,
`ClassCastException`).

7. Illegal Argument Errors:


- Invalid Method Arguments: Passing illegal or inappropriate arguments to a method (e.g.,
`IllegalArgumentException`).

Exception Handling in Java

Java provides a robust mechanism for handling exceptions through the use of `try`, `catch`,
`finally`, and `throw` statements:

1. `try` Block: Contains code that might throw an exception. It is used to encapsulate the code
that might cause an exception.
2. `catch` Block: Catches and handles the exception thrown by the `try` block. You can have
multiple `catch` blocks to handle different types of exceptions.

3. `finally` Block: Contains code that is always executed, regardless of whether an exception
was thrown or not. It is typically used for resource cleanup (e.g., closing files or database
connections).

4. `throw` Statement: Used to explicitly throw an exception from a method or block of code.

5. `throws` Keyword: Indicates that a method may throw one or more exceptions and must be
handled by the caller of the method.

User-Defined Exceptions
In Java, you can create custom exceptions by extending the `Exception` class or one of its
subclasses. This is useful when you need to handle specific error conditions that are not
covered by standard Java exceptions.

Steps to Create a User-Defined Exception:

1. Define the Exception Class: Extend the `Exception` class or `RuntimeException` class.
Provide constructors to pass messages or causes.

2. Throw the Exception: Use the `throw` keyword to throw the custom exception from a
method.

3. Catch and Handle the Exception: Catch the custom exception in a `try-catch` block and
handle it accordingly.
In summary, exceptions are a crucial part of error handling in Java, allowing programs to
manage and recover from unexpected conditions gracefully. By using built-in and user-
defined exceptions, Java provides a structured way to address and manage errors effectively,
ensuring robust and reliable applications.

Question 6: (a) What is multithreading? Explain how multiple child threads are
created? Write a java program to demonstrate interthread communication. (7 Marks)
Ans. (a) What is Multithreading?

Multithreading in Java refers to the concurrent execution of two or more threads, where each
thread represents a separate path of execution within a program. This allows multiple tasks to
be executed in parallel, improving the efficiency of the program by utilizing CPU resources
more effectively. Threads in Java can either be created by extending the `Thread` class or
implementing the `Runnable` interface.

Creating Multiple Child Threads

Multiple child threads can be created by either extending the `Thread` class or implementing
the `Runnable` interface. When a thread is created and started, it goes through a lifecycle:
new, runnable, running, and terminated. A thread can be created by:

1. Extending the `Thread` class and overriding the `run()` method.


2. Implementing the `Runnable` interface and passing an instance of the implementing class
to the `Thread` constructor.
Once the thread is started using the `start()` method, the JVM creates a new child thread
which runs concurrently with the main thread and other child threads.

Java Program for Inter-thread Communication

Inter-thread communication in Java is achieved using methods like `wait()`, `notify()`, and
`notifyAll()` that belong to the `Object` class. Here's an example demonstrating inter-thread
communication:
This program demonstrates how a producer thread and a consumer thread communicate using
`wait()` and `notify()` to avoid race conditions. The producer generates data and notifies the
consumer when it is ready, while the consumer consumes the data and notifies the producer
when it is done.

(b) Explain use of List interface and Vector class in Java. (3 Marks)
Ans. (b) Use of List Interface and Vector Class in Java

List Interface:

The `List` interface in Java is part of the Java Collections Framework and represents an
ordered collection (also known as a sequence). It allows duplicate elements and maintains the
insertion order. Lists can be used when we need to store, retrieve, and manipulate elements in
a specific sequence.

Key features of the `List` interface include:


- Index-based access: Elements in a list can be accessed by their index (position in the list).
- Allows duplicates: The same element can appear multiple times.
- Sublist feature: A portion of the list can be extracted using the `subList()` method.
- Common implementations: `ArrayList`, `LinkedList`, and `Vector`.

Methods in the `List` interface:


- `add(E e)`: Adds an element to the list.
- `get(int index)`: Retrieves an element at a specific position.
- `remove(int index)`: Removes the element at a specific index.
- `size()`: Returns the number of elements in the list.

Vector Class:

`Vector` is a legacy class in Java, but it also implements the `List` interface. It is similar to
`ArrayList`, but there are some differences, particularly with respect to synchronization.

Key features of the `Vector` class:


- Thread-safe: All methods in `Vector` are synchronized, meaning it is safe to use in multi-
threaded environments. However, this synchronization can make it slower compared to non-
synchronized alternatives like `ArrayList`.
- Dynamic array: Like `ArrayList`, `Vector` can grow and shrink in size dynamically.
- Capacity increment: When the size of the `Vector` exceeds its capacity, it expands by a
specified amount, known as the capacity increment.

Example usage of `Vector`:

While `Vector` is synchronized and safe for concurrent use, in modern applications,
developers often prefer `ArrayList` or `CopyOnWriteArrayList` for better performance unless
synchronization is specifically needed.

Question 7: (a) Explain Swing package/class hierarchy. What is difference between


AWT and Swing ? (6 Marks)
Ans. (a) Swing Package/Class Hierarchy

Swing is a part of Java’s Foundation Classes (JFC) and provides a rich set of lightweight
components for building graphical user interfaces (GUIs). Swing components are written in
pure Java and do not depend on platform-specific code. It provides a more flexible and
powerful interface than the Abstract Window Toolkit (AWT), which was Java's original GUI
framework.

Swing Class Hierarchy:


At the top of the Swing hierarchy is `javax.swing.JComponent`, from which most of the
Swing components are derived. Below is a simplified hierarchy of Swing classes:

1. `java.lang.Object`: Root of the class hierarchy.


2. `java.awt.Component`: The base class for all AWT and Swing components.
3. `java.awt.Container`: A subclass of `Component` that can hold other components.
4. `javax.swing.JComponent`: The root class for all Swing components that can be added to
containers (buttons, panels, etc.).

Common components derived from `JComponent`:


- JButton: A button component.
- JLabel: A component for displaying text.
- JTextField: A single-line text input.
- JCheckBox: A checkbox component.
- JRadioButton: A radio button component.
- JComboBox: A drop-down list.
- JPanel: A container that can hold other components.
- JFrame: A top-level window.

Swing components are typically prefixed with "J" to distinguish them from their AWT
counterparts.

Difference between AWT and Swing


In conclusion, while AWT is simple and platform-dependent, Swing offers more components,
better performance, and a uniform, customizable look and feel across platforms. Swing is
generally preferred for building modern Java GUIs.

(b) What is FXML? Explain event handling in JavaFX. (4 Marks)


Ans. (b) What is FXML?

FXML is an XML-based language used to define the structure of a JavaFX user interface (UI)
separately from the application logic. It allows developers to design the user interface using a
declarative approach, much like HTML for web development, while keeping the business
logic in Java code. FXML files can be loaded and used to create the JavaFX scene graph,
which forms the GUI for JavaFX applications.

Key benefits of using FXML:


- Separation of concerns: UI design is separated from the application logic, making the code
cleaner and easier to maintain.
- Visual editing: FXML files can be edited using visual tools like Scene Builder, allowing
designers to work on the UI while developers focus on the functionality.
- Ease of use: It simplifies the creation of complex UIs by providing a more readable and
structured way to define the GUI.

Here's a basic structure of an FXML file:

In this example, a `Button` is placed inside a `VBox` layout, and the button's action is linked
to a method called `handleButtonAction` in the controller class.

Event Handling in JavaFX

In JavaFX, event handling refers to the process of responding to user actions such as clicks,
key presses, or mouse movements. JavaFX provides a flexible and efficient mechanism for
event handling through event listeners and event handlers.

Steps for Event Handling:

1. Event Source: The component that generates an event, such as a button.


2. Event Listener/Handler: The method that listens for and handles the event.

In JavaFX, event handling is typically done using lambda expressions or by linking event
handlers directly in FXML.

Example of Event Handling in JavaFX:


1. Handling Events in Java Code:

2. Handling Events via FXML:


In FXML, event handlers can be specified in the XML file using the `onAction` attribute. The
corresponding method is then defined in the controller class.

FXML Example:
Controller Class:

In JavaFX, event handling is seamless and allows for clean and modular code, either through
inline Java code using lambda expressions or declaratively using FXML.

Question 8: (a) Write a Java program using JDBC to manage saving accounts of a bank.
Make necessary assumptions. Make provisions of exception handling in your program.
(8 Marks)
Ans. (a) Java Program Using JDBC to Manage Saving Accounts of a Bank

Here’s a Java program that demonstrates how to manage saving accounts in a bank using
JDBC. The program connects to a database, allows account creation, and handles exceptions.

Assumptions:
- The database is named `BankDB` with a table `SavingAccount` having columns
`AccountNumber`, `AccountHolderName`, and `Balance`.
- JDBC Driver is properly configured, and the database connection details (URL, username,
password) are set.

Java Program with Exception Handling:


Key Points:
- Connection: Uses `DriverManager.getConnection()` to connect to the MySQL database.
- PreparedStatement: Safely executes SQL queries for account creation and retrieval.
- Exception Handling: Each JDBC operation is wrapped in a `try-catch` block to handle
`SQLException`.

(b) Explain use of commit () and rollback() in JDBC programming with the help of a
small program
Ans. (b) Use of `commit()` and `rollback()` in JDBC Programming

In JDBC, `commit()` and `rollback()` are used to manage transactions. A transaction is a


sequence of operations that are executed as a single unit, ensuring data integrity. By default,
JDBC is in auto-commit mode, meaning each individual SQL statement is treated as a
transaction. However, when working with multiple SQL operations that must either all
succeed or all fail (e.g., money transfer between accounts), manual transaction control using
`commit()` and `rollback()` is necessary.

`commit()`:
- Commits the current transaction, making all changes permanent.
- Use `commit()` after a series of operations if they all complete successfully.
`rollback()`:
- Rolls back the current transaction, undoing all changes since the last commit.
- Use `rollback()` to revert changes if any part of the transaction fails.

Example Program Using `commit()` and `rollback()`:


Explanation:
- `setAutoCommit(false)`: Turns off auto-commit to manually control the transaction.
- `conn.commit()`: If both operations (withdraw and deposit) succeed, changes are
committed.
- `conn.rollback()`: If an error occurs, the transaction is rolled back, undoing changes.

You might also like