0% found this document useful (0 votes)
63 views59 pages

AJP End Sem Official Paper Solution

The document provides an overview of Java GUI programming, focusing on container classes in Swing, AWT components, and hashing techniques. It explains the differences between ArrayList and Vector, demonstrates creating a simple GUI application, and details database connectivity using JDBC. Additionally, it covers the use of PreparedStatement for executing parameterized SQL queries to enhance security and performance.
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)
63 views59 pages

AJP End Sem Official Paper Solution

The document provides an overview of Java GUI programming, focusing on container classes in Swing, AWT components, and hashing techniques. It explains the differences between ArrayList and Vector, demonstrates creating a simple GUI application, and details database connectivity using JDBC. Additionally, it covers the use of PreparedStatement for executing parameterized SQL queries to enhance security and performance.
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

Q.

-› a) Container Class:

- In Java GUI programming, components and containers are essential elements


used to create user interfaces.
- Components are the graphical elements like buttons, text fields, labels, and
checkboxes that allow user interaction.
- Containers are the components that hold and manage other components,
ensuring their proper arrangement on the screen.

Container Class in Java:


- A container is a special type of component in Java Swing that can hold and
organize other components.
- Containers help in defining the structure of a GUI by grouping elements
logically.
- There are two types of containers: Top-Level Containers and Lightweight
Containers.

Types of Java Swing Containers:

1. Top-Level Containers:
- These containers are the root of a Java Swing application and are required
to create a GUI.
- Examples:
- JFrame: Used to create a main application window.
- JDialog: Used to create popup dialogs.
- JApplet: Special container used in applets.
- JWindow: A borderless top-level container.

2. Lightweight Containers:
Q.1
- These are containers placed inside top-level containers to manage
components more effectively.
- Examples:
- JPanel: Groups multiple components together.
- JScrollPane: Adds scroll functionality to components.
- JTabbedPane: Allows switching between different panels using tabs.
- JSplitPane: Splits the display area into two resizable parts.

Diagram :

AWT Components:

- Abstract Window Toolkit (AWT) is the original GUI toolkit in Java.


- It provides platform-dependent components that rely on the native OS
interface.
- AWT components are less flexible than Swing but are still used in legacy
applications.

Commonly Used AWT Components:

1. JButton: Creates a clickable button for user interaction.


2. JLabel: Displays a simple text or an image.
Q.1
3. JTextField: Allows single-line text input.
4. JTextArea: Allows multi-line text input.
5. JCheckBox: Provides a checkable option.
6. JRadioButton: Used in a group where only one option can be selected.
7. JComboBox: Creates a dropdown list of selectable options.
8. JSlider: Enables users to select a value from a range.
9. JList: Displays a list of items.
10. JScrollPane: Adds scrolling ability to components.

Example Program - Creating a Simple Swing GUI:

import [Link].*;
import [Link].*;

public class SimpleGUI {


public static void main(String[] args) {
JFrame frame = new JFrame("Swing Example");
[Link](400, 300);
[Link](JFrame.EXIT_ON_CLOSE);

JPanel panel = new JPanel();


[Link](panel);
placeComponents(panel);

[Link](true);
}

private static void placeComponents(JPanel panel) {


[Link](null);

JLabel label = new JLabel("Enter Name:");


Q.1
[Link](10, 20, 100, 25);
[Link](label);

JTextField userText = new JTextField(20);


[Link](120, 20, 165, 25);
[Link](userText);

JButton button = new JButton("Submit");


[Link](120, 50, 80, 25);
[Link](button);
}
}

Points from the Example:


- A ‘JFrame’ is created as the main window.
- A ‘JPanel’ is used to manage components.
- ‘JLabel’, ‘JTextField’, and ‘JButton’ components are placed in the panel.
- The ‘setBounds()’ method positions the components on the screen.
- ‘setVisible(true)’ makes the window visible to the user.

-› b) i) Hashing in Java:

Definition:
- Hashing is a technique used to store and retrieve data efficiently using a hash
function.
- It converts input data into a fixed-size hash code for quick access.

Features of Hashing:
Q.1
1. Fast Data Retrieval:
- Hashing allows searching and inserting data in constant time complexity O(1)
in ideal cases.

2. Use of Hash Function:


- A hash function maps keys to specific indices in a data structure.

3. Collision Handling:
- When two different keys produce the same hash value, techniques like
chaining and open addressing are used to resolve conflicts.

4. Commonly Used Hashing Classes in Java:


- ‘HashMap’: Stores key-value pairs using hashing.
- ‘HashSet’: Implements a set using hashing with no duplicate elements.
- ‘Hashtable’: A synchronized version of ‘HashMap’.

Example Program - Using HashMap for Hashing:

import [Link];

public class HashingExample {


public static void main(String[] args) {
HashMap<Integer, String> map = new HashMap<>();
[Link](1, "Alice");
[Link](2, "Bob");
[Link](3, "Charlie");

[Link]("Value for 2: " + [Link](2));


}
}
Q.1
Points from the Example:
- A ‘HashMap’ is used to store key-value pairs.
- The ‘put()’ method adds elements, and ‘get()’ retrieves values using a key.
- Hashing ensures quick data access.

ii) Java Utilities ([Link] Package)

- The ‘[Link]’ package is one of the most important utility packages in Java.
- It provides various utility classes and interfaces that help in performing
common programming tasks efficiently.
- This package contains collections framework, date and time handling, random
number generation, internationalization, and event handling classes.

Definition:
- The ‘[Link]’ package is a core Java package that contains a set of utility
classes for handling data structures, algorithms, and common functionalities.
- It provides essential tools that enhance the efficiency of Java applications.

Significance of [Link] Package:

1. Collections Framework:
- Provides a set of classes and interfaces for working with data structures
like lists, sets, and maps.
- Common classes include ‘ArrayList’, ‘HashSet’, ‘HashMap’, and ‘LinkedList’.

2. Date and Time Handling:


- Includes classes like ‘Date’, ‘Calendar’, and ‘TimeZone’ for managing dates
and time zones.
- Helps in formatting and manipulating date-related data.
Q.1
3. Random Number Generation:
- The ‘Random’ class helps in generating random numbers for applications such
as gaming and simulations.

4. Event Handling:
- Contains event listener interfaces that help in GUI event-driven
programming.
- Examples include ‘EventListener’, ‘Observer’, and ‘TimerTask’.

5. Internationalization Support:
- Provides classes like ‘Locale’, ‘ResourceBundle’, and ‘Currency’ for adapting
applications to different languages and regions.

Importing the [Link] Package:

- The ‘import’ keyword is used to include classes from the ‘[Link]’ package in
a Java program.
- Example of importing a single class:

import [Link];
- Example of importing the entire package:

import [Link].*;

-› c) Differences between ArrayList & Vector


- Both ArrayList and Vector are dynamic arrays that allow elements to be stored
in an ordered sequence.
- They belong to the List interface and provide indexed access to elements.
Q.1
- ArrayList is not synchronized, while Vector is synchronized, making it thread-
safe.

Differences Between ArrayList and Vector :


Q.2

-› a) Swings Component :

- Swing is a part of Java Foundation Classes (JFC) and provides GUI components
for creating interactive applications.
- It is an extension of AWT and is more flexible and powerful.
- The JTextField component is used to take input, and JButton is used to trigger
the addition process.
- The JLabel component is used to display the result.

Program to Add Two Numbers Using Swing :

import [Link].*;
import [Link].*;
import [Link].*;

public class AddTwoNumbers extends JFrame implements ActionListener {


JTextField num1Field, num2Field, resultField;
JButton addButton;

public AddTwoNumbers() {
// Setting up the frame
setTitle("Addition of Two Numbers");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(4, 2));

// Creating components
JLabel num1Label = new JLabel("Enter First Number: ");
num1Field = new JTextField();
Q.2
JLabel num2Label = new JLabel("Enter Second Number: ");
num2Field = new JTextField();

addButton = new JButton("Add");


[Link](this);

JLabel resultLabel = new JLabel("Result: ");


resultField = new JTextField();
[Link](false);

// Adding components to frame


add(num1Label); add(num1Field);
add(num2Label); add(num2Field);
add(addButton);
add(resultLabel); add(resultField);

setVisible(true);
}

public void actionPerformed(ActionEvent e) {


try {
// Retrieving values from text fields
int num1 = [Link]([Link]());
int num2 = [Link]([Link]());
int sum = num1 + num2;

// Displaying the result


[Link]([Link](sum));
} catch (NumberFormatException ex) {
[Link]("Invalid Input!");
}
Q.2
}

public static void main(String[] args) {


new AddTwoNumbers();
}
}

Explanation of Program :
- JFrame: Creates the main window of the application.
- JTextField: Used to take input for two numbers and display the result.
- JLabel: Displays labels for input fields and results.
- JButton: Adds an event listener to perform the addition when clicked.
- GridLayout: Arranges the components in a 4-row, 2-column layout.
- ActionListener: Listens for button clicks and performs the addition operation.

Expected Output :
- User enters two numbers.
- Clicks on the "Add" button.
- The result is displayed in the text field below.

-› b) AWT Components :

- Abstract Window Toolkit (AWT) is Java's original GUI toolkit.


- It provides a set of platform-dependent components for building graphical
applications.
- AWT components rely on the native OS for rendering, making them less
flexible compared to Swing.
Q.2
Definition:
- AWT components are pre-defined graphical elements that allow user
interaction in a Java application.
- These components include buttons, labels, text fields, checkboxes, radio
buttons, and more.

Commonly Used AWT Components:

1. Button:
- Creates a clickable button that performs an action when pressed.
- Used to trigger events in the application.

2. Label:
- Displays static text or an image on the screen.
- Does not allow user interaction.

3. TextField:
- Allows the user to enter a single line of text input.
- Commonly used in forms and login screens.

4. TextArea:
- Supports multi-line text input.
- Useful for comments, descriptions, and notes.

5. Checkbox:
- Represents an option that can be selected or deselected.
- Used for multiple-choice selections.

6. RadioButton:
- Allows the selection of one option from a group of choices.
- Used in mutually exclusive selections.
Q.2

7. List:
- Displays a list of selectable items.
- Allows single or multiple selections.

8. Choice:
- A drop-down menu allowing users to select one option.

9. Scrollbar:
- Provides vertical and horizontal scrolling functionality.
- Used in areas where content exceeds visible space.

10. Canvas:
- A drawing surface for custom graphics.
- Used for game development and animations.

Diagram :

Example Program - Demonstrating AWT Components:

import [Link].*;
import [Link].*;
Q.2

public class AWTExample {


public static void main(String[] args) {
Frame frame = new Frame("AWT Example");
[Link](400, 300);
[Link](null);
Label label = new Label("Enter Name:");
[Link](50, 50, 100, 20);
[Link](label);
TextField textField = new TextField();
[Link](160, 50, 150, 20);
[Link](textField);
Button button = new Button("Submit");
[Link](160, 80, 80, 30);
[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
[Link]("Name: " + [Link]());
}
});
[Link](button);
[Link](true);
}
}

Points from the Example:


- ‘Frame’ acts as the main window.
- ‘Label’ is used to display a message.
- ‘TextField’ allows user input.
- ‘Button’ triggers an action when clicked.
- ‘ActionListener’ handles button click events.
Q.3

-› a) Database Connection:

- A database connection is a link established between a Java application and a


database, allowing the application to send queries and retrieve results.

Connecting a Java Application to a Database Using JDBC:

- Java Database Connectivity (JDBC) is an API that enables Java applications


to interact with databases.

- To connect a Java application to a MySQL database using JDBC, follow these


steps:

- Ensure Prerequisites:
- MySQL should be installed, and the required database should be created.
- Java Development Kit (JDK) should be installed.
- Download the MySQL JDBC driver (e.g., ‘[Link]-
[Link]’) and place it in the appropriate directory (e.g.,
‘C:\your_tomcat_directory\common\lib’).

- Ensure Apache Tomcat or another server is running if deploying a web


application.

- Load the JDBC Driver:


- Use the ‘[Link]()’ method to load the MySQL JDBC driver:
- ‘[Link]("[Link]");’

- Establish a Connection:

Define the connection URL:


Q.3
‘jdbc:mysql://localhost:3306/my_database’

- ‘jdbc’: Indicates the API.


- ‘mysql’: Specifies the database.
- ‘localhost’: Server hosting the database (use IP address if remote).
- ‘3306’: Port number.
- ‘my_database’: Name of the database.

Obtain the connection using ‘[Link]()’:

- ‘Connection conn =
[Link]("jdbc:mysql://localhost:3306/my_database",
"username", "password");’

Create a Statement:

- Use the ‘Connection’ object to create a ‘Statement’:


- ‘Statement stmt = [Link]();’

Execute Queries:
- Execute SQL queries using the ‘Statement’ object:
‘ResultSet rs = [Link]("SELECT * FROM table_name");’

Process Results:

- Iterate through the ‘ResultSet’ to access data:


‘while ([Link]()) { /* process data */ }’

Close Resources:
- Close the ‘ResultSet’, ‘Statement’, and ‘Connection’ to free resources:
- ‘[Link]();’
Q.3
- ‘[Link]();’
- ‘[Link]();’

Diagram:

Explanation of Diagram:

- Java Application:
- Initiates the process by loading the JDBC driver and establishing a
connection to the database.

- JDBC Driver:
- Acts as an intermediary, translating Java calls into database-specific calls.

- Database:
- Receives and processes SQL queries from the application via the JDBC driver
and returns results.
Q.3

-› b) PreparedStatement
- PreparedStatement is a subinterface of ‘Statement’ in JDBC, used to execute
parameterized SQL queries.
- It helps in preventing SQL injection and improves performance for repeated
executions.
- This program inserts Student Name and Branch Name into the ‘Student’
table.

- Prerequisites:
- Install and configure a relational database (e.g., MySQL).
- Ensure the ‘Student’ table exists with columns student_name and
branch_name.
- Add the MySQL JDBC Driver (‘[Link]’) to the project.

- Steps to Insert Data Using JDBC PreparedStatement:


1. Load and Register JDBC Driver:
- Use ‘[Link]("[Link]");’.

2. Establish a Database Connection:


- Use ‘[Link](url, username, password);’.

3. Create a PreparedStatement Object:


- Use ‘prepareStatement()’ with a SQL ‘INSERT’ statement containing
placeholders (‘?’).

4. Set Parameters for the PreparedStatement:


- Use ‘setString(index, value)’ to set values dynamically.

5. Execute the Query:


- Use ‘executeUpdate()’ to insert records into the table.
Q.3

6. Close the Connection:


- Use ‘close()’ to release database resources.

Java Program to Insert Student Name and Branch Name:

import [Link];
import [Link];
import [Link];
import [Link];

public class InsertStudent {


public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/your_database";
String username = "root";
String password = "password";

String insertQuery = "INSERT INTO Student (student_name,


branch_name) VALUES (?, ?)";
try (Connection conn = [Link](url, username,
password);
PreparedStatement pstmt = [Link](insertQuery);
Scanner scanner = new Scanner([Link])) {

// Accept user input


[Link]("Enter Student Name: ");
String studentName = [Link]();
[Link]("Enter Branch Name: ");
String branchName = [Link]();
Q.3
// Set parameters
[Link](1, studentName);
[Link](2, branchName);

// Execute update
int rowsAffected = [Link]();
[Link](rowsAffected + " row(s) inserted successfully.");
} catch (Exception e) {
[Link]();
}
}
}

Explanation of the Program:


- The JDBC driver is loaded and a database connection is established.
- The ‘PreparedStatement’ is created with an SQL ‘INSERT’ statement.
- The user inputs Student Name and Branch Name, which are dynamically
assigned to the query.
- The ‘executeUpdate()’ method inserts the data into the ‘Student’ table.
- The connection and statement objects are closed automatically using ‘try-
with-resources’.

Features:
- Uses PreparedStatement to prevent SQL injection.
- Takes user input dynamically for insertion.
- Follows best practices for JDBC connection handling.

This program successfully inserts Student Name and Branch Name into the
Student table using JDBC ‘PreparedStatement’.
Q.4

-› a) Java Database Connectivity (JDBC)


- Java Database Connectivity (JDBC) is an API that enables Java applications
to interact with relational databases.
- JDBC drivers serve as a bridge between Java applications and databases,
translating Java calls into database-specific operations.

Types of JDBC Drivers:

1. Type 1: JDBC-ODBC Bridge Driver:

- Translates JDBC calls into ODBC (Open Database Connectivity) calls, which
are then processed by the ODBC driver to interact with the database.

Diagram :

Explanation of Diagram:

- Java Application: Initiates JDBC calls.


- JDBC-ODBC Bridge: Converts JDBC calls to ODBC calls.
- ODBC Driver: Processes ODBC calls to communicate with the database.
- Database: Stores and manages data.
Q.4
Advantages:
- Allows access to databases with existing ODBC drivers.

Disadvantages:
- Performance overhead due to double translation (JDBC to ODBC to
database).
- Requires ODBC driver installation on the client machine.
- Not suitable for large-scale applications.

2. Type 2: Native-API Driver (Partially Java Driver):

- Converts JDBC calls into database-specific native calls using client-side


libraries.

Diagram :

Explanation of Diagram:

- Java Application: Initiates JDBC calls.


- Native-API Driver: Translates JDBC calls into native database API calls.
- Database: Processes native API calls to manage data.
Q.4
Advantages:
- Better performance than Type 1 drivers due to direct native API calls.

Disadvantages:
- Requires native database libraries on the client machine.
- Not portable across different databases.
- Unsuitable for internet-based applications.

3. Type 3: Network Protocol Driver (All-Java Driver):

- Uses a middleware server to convert JDBC calls into database-specific


calls, enabling communication over the network.

Diagram :

Explanation:

- Java Application: Initiates JDBC calls.


- Network Protocol Driver: Forwards JDBC calls over the network.
- Middleware Server: Translates network protocol calls into database-
specific calls.
- Database: Handles database-specific calls to manage data.
Q.4

Advantages:
- No need for client-side database libraries.
- Suitable for internet-based applications.
- Allows centralized management of database connections.

Disadvantages:
- Requires middleware server setup and maintenance.
- Potential performance overhead due to network communication.

4. Type 4: Native-Protocol Driver (Pure Java Driver):


- Directly converts JDBC calls into database-specific protocol calls using
Java, allowing direct communication with the database.

Diagram :

Explanation of Diagram:

- Java Application: Initiates JDBC calls.


- Native-Protocol Driver: Directly translates JDBC calls into database
protocol calls.
- Database: Processes protocol calls to manage data.
Q.4
Advantages:
- Platform-independent and fully implemented in Java.
- No need for additional client-side software or middleware.
- Offers better performance due to direct communication.

Disadvantages:
- Requires a separate driver for each database.

-› b) Executing SQL Commands

- Java Database Connectivity (JDBC) is an API that enables Java applications


to interact with relational databases by executing SQL commands.

- Establishing a Connection:
- To begin, load the JDBC driver and establish a connection to the database
using ‘[Link]()’.

- Creating Statement Objects:


- Once connected, create a ‘Statement’, ‘PreparedStatement’, or
‘CallableStatement’ object to send SQL commands to the database.

- Executing SQL Commands:


- Using Statement:
- For general SQL commands without parameters, use the ‘Statement’ object.
- Example:

Statement stmt = [Link]();


ResultSet rs = [Link]("SELECT * FROM Students");
- Using PreparedStatement:
Q.4
- For SQL commands with parameters, ‘PreparedStatement’ is preferred for
efficiency and security.
- Example:
PreparedStatement pstmt = [Link]("INSERT INTO
Students (rollNumber, studentName) VALUES (?, ?)");
[Link](1, 101);
[Link](2, "John Doe");
[Link]();
- Using CallableStatement:
- To execute stored procedures, use ‘CallableStatement’.
- Example:
CallableStatement cstmt = [Link]("{call getStudentName(?)}");
[Link](1, 101);
ResultSet rs = [Link]();

- Handling Results:
- For queries returning data, process the ‘ResultSet’ to retrieve the results.
- Example:
while ([Link]()) {
int rollNumber = [Link]("rollNumber");
String studentName = [Link]("studentName");
}

- Closing Resources:
- Always close ‘ResultSet’, ‘Statement’, and ‘Connection’ objects to free
resources.
- Example:

[Link]();
[Link]();
[Link]();
Q.5

-› a) Remote Method Invocation (RMI) : Architecture

- Definition:
- RMI stands for Remote Method Invocation.
- It enables an object running on one Java Virtual Machine (JVM) to invoke
methods on an object running on another JVM, possibly on a different physical
machine.

- Purpose:
- Facilitates the development of distributed applications in Java.
- Allows seamless communication between objects across different JVMs.

RMI Architecture:
- Stub:
- Acts as a proxy for the remote object on the client side.
- Implements the same interfaces as the remote object.
- Transmits method calls from the client to the server via the skeleton.
- Skeleton:
- Resides on the server side.
- Receives method calls from the stub.
- Invokes the corresponding method on the actual remote object.
- Remote Reference Layer:
- Manages references to remote objects.
- Handles the semantics of invoking a method on a remote object.
- Transport Layer:
- Establishes and manages network connections between client and server
JVMs.
- Typically uses TCP/IP for communication.
Q.5
- Diagram:

- Explanation of Diagram:
- The client interacts with the stub as if it were the actual remote object.
- The stub forwards the method invocation to the skeleton on the server side.
- The skeleton then calls the appropriate method on the actual remote object.
- The result is sent back through the skeleton to the stub, and finally to the
client.

Comparison Between Stub and Skeleton:


Q.5

-› b) Developing an RMI Application to Check for Palindromes:

- Remote Method Invocation (RMI) enables a Java program to invoke methods


on an object located remotely, facilitating distributed computing.

- A palindrome is a sequence (word, number, phrase) that reads the same


forward and backward, such as "madam" or "12321".

Steps to Develop an RMI Application for Palindrome Checking:

1. Define the Remote Interface:

- Create an interface that extends ‘[Link]’.

- Declare the remote method ‘isPalindrome’ that throws ‘RemoteException’.

- This method will check if a given string or number is a palindrome.

2. Implement the Remote Interface:

- Develop a class that implements the remote interface.

- Provide the logic for the ‘isPalindrome’ method to determine if the input is
a palindrome.

3. Create the Server Program:

- Instantiate the implementation class.

- Bind the remote object to the RMI registry using a unique name.
Q.5

- This allows clients to look up and invoke the remote method.

4. Develop the Client Program:

- Obtain a reference to the remote object from the RMI registry.

- Invoke the ‘isPalindrome’ method with the desired input.

- Display the result indicating whether the input is a palindrome.

5. Compile and Run:

- Compile all Java files.

- Start the RMI registry service.

- Run the server program to bind the remote object.

- Execute the client program to test the palindrome functionality.

Example Implementation:

1. Remote Interface ([Link]):

import [Link];
import [Link];

public interface Palindrome extends Remote {


boolean isPalindrome(String input) throws RemoteException;
Q.5
}

2. Remote Object Implementation ([Link]):

import [Link];
import [Link];

public class PalindromeImpl extends UnicastRemoteObject implements


Palindrome {
protected PalindromeImpl() throws RemoteException {
super();
}

@Override
public boolean isPalindrome(String input) throws RemoteException {
String cleanInput = [Link]("\\s+", "").toLowerCase();
String reverse = new StringBuilder(cleanInput).reverse().toString();
return [Link](reverse);
}
}

3. Server Program ([Link]):

import [Link];
import [Link];

public class PalindromeServer {


public static void main(String[] args) {
try {
Q.5
PalindromeImpl palindrome = new PalindromeImpl();
Registry registry = [Link](1099);
[Link]("PalindromeService", palindrome);
[Link]("Palindrome Service is running...");
} catch (Exception e) {
[Link]();
}
}
}

4. Client Program ([Link]):

import [Link];
import [Link];
import [Link];

public class PalindromeClient {


public static void main(String[] args) {
try {
Registry registry = [Link]("localhost", 1099);
Palindrome stub = (Palindrome) [Link]("PalindromeService");
Scanner scanner = new Scanner([Link]);
[Link]("Enter a string or number to check for
palindrome:");
String input = [Link]();
boolean result = [Link](input);
if (result) {
[Link](input + " is a palindrome.");
} else {
[Link](input + " is not a palindrome.");
Q.5
}
[Link]();
} catch (Exception e) {
[Link]();
}
}
}

Explanation of Code:

- Remote Interface: Defines the ‘isPalindrome’ method that throws


‘RemoteException’.

- Implementation Class: Provides the logic to check if the input is a palindrome


by cleaning the input (removing spaces and converting to lowercase) and
comparing it to its reverse.

- Server Program: Registers the ‘PalindromeImpl’ object with the RMI registry
under the name "PalindromeService".

- Client Program: Looks up the "PalindromeService" in the RMI registry, takes


user input, and calls the ‘isPalindrome’ method to determine if the input is a
palindrome.
Q.6

-› a) Writing Distributed Applications with RMI:

Introduction to RMI:
- Remote Method Invocation (RMI): A Java API that allows an object to invoke
methods on an object running in another Java Virtual Machine (JVM),
facilitating distributed computing.

Steps to Write a Distributed Application Using RMI:

1. Define the Remote Interface:


- Create an interface that extends ‘[Link]’.
- Declare each method that can be invoked remotely, ensuring they throw
‘[Link]’.

2. Implement the Remote Interface:


- Develop a class that implements the remote interface.
- Extend ‘[Link]’ or use the ‘exportObject()’
method to make the object available for remote invocation.

3. Compile the Implementation Class:


- Compile the implementation class to generate the necessary bytecode.

4. Start the RMI Registry:


- Initiate the RMI registry using the ‘rmiregistry’ command, which listens for
client requests.

5. Create and Start the Server Application:


- Instantiate the implementation class.
- Bind the remote object to a name in the RMI registry using ‘[Link]()’.
Q.6
6. Create and Start the Client Application:
- Lookup the remote object in the RMI registry using ‘[Link]()’.
- Invoke remote methods as if they were local.

Example: Addition of Two Numbers Using RMI

1. Define the Remote Interface:

import [Link].*;

public interface Adder extends Remote {


int add(int x, int y) throws RemoteException;
}

2. Implement the Remote Interface:

import [Link].*;
import [Link].*;

public class AdderRemote extends UnicastRemoteObject implements Adder {


AdderRemote() throws RemoteException {
super();
}

public int add(int x, int y) {


return x + y;
}
}

3. Create and Start the Server Application:


Q.6

import [Link].*;
import [Link].*;

public class MyServer {


public static void main(String args[]) {
try {
Adder stub = new AdderRemote();
[Link]("rmi://localhost:5000/sonoo", stub);
} catch (Exception e) {
[Link](e);
}
}
}

4. Create and Start the Client Application:

import [Link].*;

public class MyClient {


public static void main(String args[]) {
try {
Adder stub = (Adder) [Link]("rmi://localhost:5000/sonoo");
[Link]([Link](34, 4));
} catch (Exception e) {
[Link](e);
}
}
}

Explanation:
Q.6
- Remote Interface (‘Adder’): Declares the ‘add’ method that can be invoked
remotely.
- Remote Implementation (‘AdderRemote’): Provides the actual implementation
of the ‘add’ method.
- Server (‘MyServer’): Binds the remote object to the RMI registry for clients
to access.
- Client (‘MyClient’): Looks up the remote object in the RMI registry and invokes
the ‘add’ method.

Note: Ensure that the RMI registry is running, and the server is bound correctly
before running the client application.

-› b) Remote Method Invocation (RMI) : Architecture


- Definition:
- RMI stands for Remote Method Invocation.
- It enables an object running on one Java Virtual Machine (JVM) to invoke
methods on an object running on another JVM, possibly on a different physical
machine.

- Purpose:
- Facilitates the development of distributed applications in Java.
- Allows seamless communication between objects across different JVMs.

RMI Architecture:
- Stub:
- Acts as a proxy for the remote object on the client side.
- Implements the same interfaces as the remote object.
- Transmits method calls from the client to the server via the skeleton.
- Skeleton:
Q.6
- Resides on the server side.
- Receives method calls from the stub.
- Invokes the corresponding method on the actual remote object.
- Remote Reference Layer:
- Manages references to remote objects.
- Handles the semantics of invoking a method on a remote object.
- Transport Layer:
- Establishes and manages network connections between client and server
JVMs.
- Typically uses TCP/IP for communication.

- Diagram:

- Explanation of Diagram:
- The client interacts with the stub as if it were the actual remote object.
- The stub forwards the method invocation to the skeleton on the server side.
- The skeleton then calls the appropriate method on the actual remote object.
- The result is sent back through the skeleton to the stub, and finally to the
client.
Q.6

Goals of RMI:

- Transparency:
- Allow remote method invocations to appear similar to local method calls.

- Simplicity:
- Provide a straightforward API for developers to implement distributed
applications.

- Flexibility:
- Support various transport protocols and enable future enhancements without
significant changes to existing code.

- Integration:
- Seamlessly integrate with Java's object-oriented features, ensuring that
remote objects can be used just like local ones.
Q.7

-› a) TCP/IP Communication

- TCP/IP (Transmission Control Protocol/Internet Protocol) is the fundamental


suite of communication protocols used to interconnect network devices on the
internet.

- TCP/IP ensures reliable, ordered, and error-checked delivery of data between


applications running on hosts connected via an IP network.

TCP/IP Client Sockets:

- A client socket in Java is an endpoint for communication between two


machines.

- The ‘Socket’ class in Java represents the client-side socket and provides the
necessary methods to establish a connection to a server.

Creating a TCP/IP Client Socket:

- To create a client socket, instantiate the ‘Socket’ class by specifying the


server's hostname and port number.

- For example: ‘Socket socket = new Socket("serverAddress", portNumber);’

Common Methods of the ‘Socket’ Class:

- ‘getInputStream()’:

- Retrieves the input stream of the socket, allowing the client to read data
sent by the server.
Q.7

- ‘getOutputStream()’:

- Retrieves the output stream of the socket, enabling the client to send data
to the server.

- ‘close()’:

- Closes the socket and releases any associated resources.

TCP/IP Server Sockets:

- A server socket waits for requests to come in over the network. It performs
operations based on the request and then possibly returns a result to the
requester.

- The ‘ServerSocket’ class in Java provides mechanisms for the server program
to listen for clients and establish connections.

Creating a TCP/IP Server Socket:

- To create a server socket, instantiate the ‘ServerSocket’ class by specifying


the port number on which the server will listen.

- For example: ‘ServerSocket serverSocket = new ServerSocket(portNumber);’

Common Methods of the ‘ServerSocket’ Class:

- ‘accept()’:
Q.7
- Listens for a connection to be made to this socket and accepts it. The method
blocks until a connection is made.

- ‘close()’:

- Closes the server socket and releases any associated resources.

Java Example: TCP/IP Client-Server Communication

Server Program:

import [Link].*;
import [Link].*;

public class TCPServer {


public static void main(String[] args) {
int port = 1234; // Server port number
try (ServerSocket serverSocket = new ServerSocket(port)) {
[Link]("Server is listening on port " + port);
while (true) {
Socket socket = [Link]();
[Link]("New client connected");
new ServerThread(socket).start();
}
} catch (IOException ex) {
[Link]("Server exception: " + [Link]());
[Link]();
}
}
}
Q.7
class ServerThread extends Thread {
private Socket socket;

public ServerThread(Socket socket) {


[Link] = socket;
}

public void run() {


try (InputStream input = [Link]();
BufferedReader reader = new BufferedReader(new
InputStreamReader(input));
OutputStream output = [Link]();
PrintWriter writer = new PrintWriter(output, true)) {

String text;
while ((text = [Link]()) != null) {
[Link]("Received: " + text);
[Link]("Message received");
}
} catch (IOException ex) {
[Link]("Server exception: " + [Link]());
[Link]();
}
}
}

Client Program:

import [Link].*;
import [Link].*;
Q.7
public class TCPClient {
public static void main(String[] args) {
String hostname = "localhost";
int port = 1234;
try (Socket socket = new Socket(hostname, port)) {
OutputStream output = [Link]();
PrintWriter writer = new PrintWriter(output, true);
[Link]("Hello, Server!");

InputStream input = [Link]();


BufferedReader reader = new BufferedReader(new
InputStreamReader(input));
String response = [Link]();
[Link]("Server response: " + response);
} catch (UnknownHostException ex) {
[Link]("Server not found: " + [Link]());
} catch (IOException ex) {
[Link]("I/O error: " + [Link]());
}
}
}

Explanation of Code:

- Server Program:

- The server listens on a specified port number for incoming client connections.

- Upon accepting a connection, it spawns a new thread (‘ServerThread’) to


handle communication with the connected client.
Q.7
- The server reads messages sent by the client and responds with a
confirmation message.

- Client Program:

- The client attempts to connect to the server using the server's hostname
and port number.

- Upon establishing the connection, the client sends a message to the server
and waits for a response.

- The client then prints the server's response to the console.

-› b) Socket Programming in Java:

- Definition of Socket: A socket is an endpoint for communication between two


machines. It enables programs to exchange data over a network.

- Types of Sockets:
- Stream Sockets (TCP): Provide reliable, connection-oriented communication.
- Datagram Sockets (UDP): Offer connectionless, unreliable communication.

Steps in Socket Programming:

1. Server Side:
- Create ServerSocket: Initialize with a specific port to listen for client
requests.
- Listen and Accept: Wait for client connections and establish communication
upon request.
Q.7
- Open I/O Streams: Set up input and output streams to receive and send
data.
- Process Requests: Handle client data as per application logic.
- Close Connections: Terminate streams and sockets after communication
ends.

2. Client Side:
- Create Socket: Connect to the server using its hostname and port number.
- Open I/O Streams: Establish input and output streams for data exchange.
- Send Requests: Transmit data or requests to the server.
- Receive Responses: Obtain and process data sent by the server.
- Close Connections: Shut down streams and sockets after tasks are complete.

Simple Java Socket Programming Example:

- Server Program:

import [Link].*;
import [Link].*;

public class SimpleServer {


public static void main(String[] args) {
try (ServerSocket serverSocket = new ServerSocket(12345)) {
[Link]("Server is listening on port 12345");
while (true) {
Socket socket = [Link]();
new ServerThread(socket).start();
}
} catch (IOException e) {
[Link]();
}
Q.7
}
}

class ServerThread extends Thread {


private Socket socket;

public ServerThread(Socket socket) {


[Link] = socket;
}

public void run() {


try (BufferedReader in = new BufferedReader(new
InputStreamReader(sock
[Link]()));
PrintWriter out = new PrintWriter([Link](), true))
{
String message = [Link]();
[Link]("Received: " + message);
[Link]("Echo: " + message);
} catch (IOException e) {
[Link]();
}
}
}

- Client Program:

import [Link].*;
import [Link].*;
Q.7
public class SimpleClient {
public static void main(String[] args) {
try (Socket socket = new Socket("localhost", 12345);
PrintWriter out = new PrintWriter([Link](), true);
BufferedReader in = new BufferedReader(new
InputStreamReader(socket .getInputStream()))) {
[Link]("Hello, Server!");
String response = [Link]();
[Link]("Server response: " + response);
} catch (IOException e) {
[Link]();
}
}
}

Explanation of Code:

- Server Program:
- Creates a ‘ServerSocket’ listening on port 12345.
- Waits for client connections and starts a new thread for each connection.
- Reads a message from the client and sends an acknowledgment.

- Client Program:
- Connects to the server at ‘localhost’ on port 12345.
- Sends a message to the server.
- Receives and prints the server's response.
Q.8

-› a) Datagram Communication (Connectionless Transmission)

- In network communication, datagram communication refers to the


transmission of data packets without establishing a dedicated connection
between the sender and receiver.
- This method is connectionless, meaning each packet, known as a datagram, is
sent independently and may take different paths to reach the destination.
- The User Datagram Protocol (UDP) is commonly used for this type of
communication, offering faster data transmission but without guaranteed
delivery or order.

Datagram:
- A datagram is a self-contained, independent packet of data carrying enough
information to be routed from the source to the destination without relying on
earlier exchanges.
- Each datagram contains:
- Header Information:
- Source and destination addresses.
- Port numbers.
- Length and checksum.
- Payload:
- The actual data being transmitted.
- Datagrams are used in scenarios where speed is crucial, and occasional data
loss is acceptable, such as live video streaming or online gaming.

‘DatagramSocket’:

- In Java, the ‘DatagramSocket’ class provides mechanisms for sending and


receiving datagram packets over UDP.
- features include:
Q.8
- Binding to a Port:
- Associates the socket with a specific port on the local machine, enabling
it to send or receive data.
- Sending Data:
- Uses the ‘send()’ method to transmit datagram packets to the destination.
- Receiving Data:
- Uses the ‘receive()’ method to listen for incoming datagram packets.
- The ‘DatagramSocket’ class is essential for applications requiring low-latency
communication without the overhead of establishing a connection.

‘DatagramPacket’:

- The ‘DatagramPacket’ class represents the data packet sent or received via
a ‘DatagramSocket’.
- components include:
- Data Buffer:
- Holds the data to be sent or the data received.
- Length:
- Specifies the size of the data in bytes.
- Address and Port:
- Indicates the destination or source address and port number.
- When sending data, a ‘DatagramPacket’ is constructed with the data,
destination address, and port. When receiving data, it's constructed with a
buffer to store incoming data.

- A Datagram Example:
- Below is an example demonstrating the use of ‘DatagramSocket’ and
‘DatagramPacket’ for sending and receiving data over UDP:

Server (Receiver):
Q.8
import [Link];
import [Link];

public class UDPServer {


public static void main(String[] args) {
try {
// Create a socket to listen on port 9876
DatagramSocket serverSocket = new DatagramSocket(9876);
byte[] receiveData = new byte[1024];

while (true) {
// Create a packet to receive data
DatagramPacket receivePacket = new
DatagramPacket(receiveData, [Link]);
// Receive data from client
[Link](receivePacket);
// Extract data from packet
String sentence = new String([Link](), 0,
[Link]());
[Link]("RECEIVED: " + sentence);
}
} catch (Exception e) {
[Link]();
}
}
}

Client (Sender):

import [Link];
import [Link];
Q.8
import [Link];

public class UDPClient {


public static void main(String[] args) {
try {
// Create a socket to send data
DatagramSocket clientSocket = new DatagramSocket();
InetAddress IPAddress = [Link]("localhost");
byte[] sendData;
String sentence = "Hello, UDP Server!";
sendData = [Link]();
// Create a packet to send data
DatagramPacket sendPacket = new DatagramPacket(sendData,
[Link], IPAddress, 9876);
// Send data to server
[Link](sendPacket);
[Link]();
} catch (Exception e) {
[Link]();
}
}
}

Explanation of the Example:

- Server Side:
- A ‘DatagramSocket’ is created and bound to port 9876 to listen for
incoming datagram packets.
- A buffer (‘receiveData’) is defined to store incoming data.
- The server enters an infinite loop, continuously waiting for data:
Q.8
- A ‘DatagramPacket’ (‘receivePacket’) is created to receive data into the
buffer.
- The ‘receive()’ method waits for an incoming packet and stores it in
‘receivePacket’.
- The data is extracted from the packet and converted into a string
(‘sentence’).
- The received message is printed to the console.
- Client Side:
- A ‘DatagramSocket’ is created to send data.
- The server's IP address (‘localhost’) and port number (9876) are specified.
- The message to be sent (‘sentence’) is converted into bytes and stored in
‘sendData’.
- A ‘DatagramPacket’ (‘sendPacket’) is created with the data, server
address, and port number.
- The ‘send()’ method is used to transmit the packet to the server.
- The socket is closed after sending the data.

Advantages of Datagram Communication :


- Faster transmission since it doesn’t require a connection setup.
- Lower overhead due to the absence of error checking and retransmission.
- Useful for real-time applications like video conferencing and gaming.

Disadvantages of Datagram Communication :


- No guarantee of delivery, packets may be lost.
- Packets may arrive out of order, requiring additional logic in the application to
reassemble data.
- Less secure compared to TCP, as it lacks built-in reliability mechanisms.
Q.8

-› b) The Life Cycle of a Servlet:

- The servlet lifecycle is managed by the servlet container and consists of the
following stages:
- Loading and Instantiation:
- The servlet class is loaded into memory by the servlet container.
- An instance of the servlet is created.
- Initialization (‘init’ method):
- The servlet container calls the ‘init(ServletConfig config)’ method to
initialize the servlet.
- This method is called only once during the servlet's lifecycle.
- Request Handling (‘service’ method):
- For each client request, the servlet container invokes the
‘service(ServletRequest req, ServletResponse res)’ method.
- This method determines the type of request (e.g., GET, POST) and
dispatches it to the appropriate handler method (‘doGet’, ‘doPost’, etc.).
- Termination (‘destroy’ method):
- When the servlet is to be removed from service, the servlet container
calls the ‘destroy()’ method.
- This allows the servlet to release resources before being garbage
collected.

Diagram:
Q.8
Explanation of Diagram:

- Step 1: The servlet is loaded and an instance is created by the servlet


container.
- Step 2: The ‘init()’ method initializes the servlet.
- Step 3: The ‘service()’ method handles multiple client requests.
- Step 4: The ‘destroy()’ method is called before the servlet is removed from
memory.

Your First Servlet:

- To create a basic servlet, extend the ‘HttpServlet’ class and override the
‘doGet()’ or ‘doPost()’ method.
- A servlet is deployed inside a Java web container such as Apache Tomcat.

Example: A Simple Calculator Servlet:

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

@WebServlet("/CalculatorServlet")
public class CalculatorServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
[Link]("text/html");
Q.8
PrintWriter out = [Link]();

int num1 = [Link]([Link]("num1"));


int num2 = [Link]([Link]("num2"));
String operation = [Link]("operation");
int result = 0;

switch (operation) {
case "add":
result = num1 + num2;
break;
case "subtract":
result = num1 - num2;
break;
case "multiply":
result = num1 * num2;
break;
case "divide":
result = num2 != 0 ? num1 / num2 : 0;
break;
}

[Link]("<h2>Result: " + result + "</h2>");


}
}

Explanation of Code:
- Annotations (‘@WebServlet’): Specifies the URL pattern for accessing the
servlet.
- ‘doPost()’ method: Handles POST requests from an HTML form.
- Extracting parameters: Reads user input (‘num1’, ‘num2’, and ‘operation’).
Q.8
- Performing operations: Executes addition, subtraction, multiplication, or
division based on the selected operation.
- Displaying result: Sends an HTML response with the calculated result.

Deploying and Running the Servlet:


1. Create an HTML Form to collect user inputs.
2. Compile and Deploy the Servlet inside a web server (e.g., Apache Tomcat).
3. Access the Servlet by entering its URL (‘[Link]
rvlet’).

You might also like