0% found this document useful (0 votes)
12 views8 pages

AnswerkeyProg QP Template CAT3(Updated)

The document outlines a Continuous Assessment Test for a programming subject, including various questions related to Java programming, RMI, TCP/UDP protocols, and Swing GUI components. It contains multiple-choice questions, coding tasks, and explanations of concepts such as connection-oriented vs connectionless protocols and the MVC architecture in Swing. The test is structured into two parts, with specific marks allocated for each section.

Uploaded by

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

AnswerkeyProg QP Template CAT3(Updated)

The document outlines a Continuous Assessment Test for a programming subject, including various questions related to Java programming, RMI, TCP/UDP protocols, and Swing GUI components. It contains multiple-choice questions, coding tasks, and explanations of concepts such as connection-oriented vs connectionless protocols and the MVC architecture in Swing. The test is structured into two parts, with specific marks allocated for each section.

Uploaded by

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

Reg. No.

Continuous Assessment Test- III [CAT - III]

Year & Section :

Semester :

Branch :

Sub. Code :

Subject Name : Programming Subjects

QP Code :

[Regulations ]

Date: Time: 90 Min Marks: 50


Answer ALL Questions

Part A [6 x 2 = 12 Marks]

Q.NO QUESTION BT LEVEL CO

4.1 Write the output for the below code. B2 CO4


InetAddress obj1 = InetAddress.getByName("rit.edu.in");
Answer
rit.edu.in

4.2 Write the output for the following B2 CO4


Statement stmt = con.createStatement(); int result = stmt.executeUpdate("UPDATE employees SET salary = 50000 WHERE id = 1");
Answer
It updates a record in the database and returns the number of rows affected.

4.3 Troubleshoot, write the cause of error B2 CO4


java.rmi.ConnectException: Connection refused to host: 116.203.202.217; nested exception is:
Answer correct IP address to clients.

4.4 In Java TCP networking, write classes are used for setting up client and server communication A2 CO4
Answer
TCP through classes like Socket and ServerSocket.

4.5 Compare and cons between connection oriented and connectionless protocol A2 CO4
Answer

Feature Connection-Oriented (e.g., TCP) Connectionless (e.g., UDP)

Reliability High, with guaranteed delivery Lower, no guarantee of delivery

Overhead Higher (handshakes, sequencing, checks) Lower (minimal setup, no handshakes)

Speed Generally slower Faster due to no connection setup

Use Cases File transfers, web pages, emails Streaming, VoIP, gaming

Error Handling Built-in error checking and recovery No error checking, managed at application level

4.6 Any two Advantages Remote Method Registry A2 CO4


Answer
1.Centralized Object Lookup and Access:
The RMI registry acts as a centralized directory where remote objects can be registered and looked up by clients.
2. Loose Coupling Between Client and Server:
With RMI Registry, clients don’t need to know the exact location of remote objects.

Part B [1x13=13 Marks]

4.7 a i) Explain about RMI (Remote Method Invocation). Illustrate the process. A2 CO4
Answer B2
 Define the Remote Interface: Declare the methods to be invoked remotely.
 Implement the Remote Interface: Create the server-side object that implements the remote interface.
 Start the RMI Registry: Use rmiregistry to allow clients to look up remote objects.
 Bind the Remote Object: Register the remote object in the registry.
 Client Lookup: The client retrieves the remote object using the name it was bound to.
 Method Invocation: The client invokes methods on the remote object as if it were local.

ii) Demonstrate rmi code that addition and it includes a remote interface, implementation, server, and client.
Answer
1. Remote Interface (Adder.java)
import java.rmi.Remote;
import java.rmi.RemoteException;

public interface Adder extends Remote {


int add(int a, int b) throws RemoteException;
}
2. Remote Implementation (AdderImpl.java)
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

public class AdderImpl extends UnicastRemoteObject implements Adder {


public AdderImpl() throws RemoteException {
super();
}

@Override
public int add(int a, int b) throws RemoteException {
return a + b;
}
}
3. RMI Server (AdderServer.java)
import java.rmi.Naming;
import java.rmi.registry.LocateRegistry;

public class AdderServer {


public static void main(String[] args) {
try {
// Create an instance of the Adder implementation
AdderImpl adder = new AdderImpl();
// Start the RMI registry
LocateRegistry.createRegistry(1099); // Default RMI port
// Bind the remote object in the registry
Naming.rebind("AdderService", adder);
System.out.println("Adder Service is running...");
} catch (Exception e) {
e.printStackTrace();
}
}
}
4. RMI Client (AdderClient.java)
import java.rmi.Naming;

public class AdderClient {


public static void main(String[] args) {
try {
// Look up the remote object from the registry
Adder adder = (Adder) Naming.lookup("rmi://localhost/AdderService");
// Call the remote add method
int result = adder.add(10, 20);
System.out.println("Result of addition: " + result);
} catch (Exception e) {
e.printStackTrace();
}
}
}

[OR]

b i)Explain in detail about TCP , UDP and its characteristics with its diagram. A2 CO4
Answer B2
Comparison Between TCP and UDP:

Feature TCP UDP

Connection Connection-oriented Connectionless

Reliability Reliable, with error recovery Unreliable, no error recovery

Data Ordering Guaranteed, in sequence No ordering

Flow Control Yes No

Congestion Control Yes No

Low (minimal header)


Overhead High (due to reliability)

1. TCP is best suited for applications where reliability, data integrity, and ordered delivery are critical, even at the cost of
speed.
2. UDP is ideal for real-time or time-sensitive applications where speed is more important than reliability.
ii) Create a program for client-server application using TCP sockets.The client/server application should send a message.
Answer
TCP Server Code
import java.io.*;
import java.net.*;

public class TCPServer {


public static void main(String[] args) {
try {
// Server listens on port 65432
int port = 65432;
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("Server started, waiting for a connection...");

// Wait for a connection


Socket socket = serverSocket.accept();
System.out.println("Client connected!");

// Set up input and output streams


InputStream input = socket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));

OutputStream output = socket.getOutputStream();


PrintWriter writer = new PrintWriter(output, true);

// Read message from client


String message = reader.readLine();
System.out.println("Received from client: " + message);
// Respond to the client
String response = "Message received!";
writer.println(response);

// Close the connection


socket.close();
serverSocket.close();

} catch (IOException ex) {


System.out.println("Server error: " + ex.getMessage());
ex.printStackTrace();
}
}
}
TCP Client Code (TCPClient.java)
import java.io.*;
import java.net.*;

public class TCPClient {


public static void main(String[] args) {
String hostname = "127.0.0.1"; // Localhost
int port = 65432;

try {
// Connect to the server
Socket socket = new Socket(hostname, port);
System.out.println("Connected to the server!");

// Set up output and input streams


OutputStream output = socket.getOutputStream();
PrintWriter writer = new PrintWriter(output, true);

InputStream input = socket.getInputStream();


BufferedReader reader = new BufferedReader(new InputStreamReader(input));

// Send message to the server


String message = "Hello, Server!";
writer.println(message);
System.out.println("Sent to server: " + message);

// Receive response from the server


String response = reader.readLine();
System.out.println("Server response: " + response);

// Close the connection


socket.close();

} catch (UnknownHostException ex) {


System.out.println("Server not found: " + ex.getMessage());
} catch (IOException ex) {
System.out.println("I/O error: " + ex.getMessage());
}
}
}

Part A [6 x 2 = 12 Marks]

Q.NO QUESTION BT LEVEL CO

5.1 Explain the four attributes needed to draw line in the below code B2 CO5
public abstract void drawLine(int x1, int y1, int x2, int y2)
Answer
 The x1, y1 pair is the (X, Y) coordinate of the starting point.
 The x2, y2 pair is the (X, Y) coordinate of the ending point.
The line is drawn from the point (x1, y1) to the point (x2, y2) on a 2D coordinate plane, where x is the horizontal axis and y is the vertical
axis.

5.2 Draw the output for the following code. B2 CO5


frame.setVisible(frame);
System.out.println("Frame shown.");
Answer
The method setVisible() is expected to take a boolean parameter indicating whether the frame should be visible or not, rather than a
reference to the frame itself. Therefore, it should look like this:

5.3 Write the output for the below code. B2 CO5


JButton button = null; button.setText("Click Me");
setText on a null object
Answer
// Error: Cannot invoke setText on a null object
Error Explanation: Attempting to call a method on a null object reference results in a NullPointerException.

5.4 Write about the regions in BorderLayout,with diagram. A2 CO5


Answer
Divided into five regions (N, S, E, W, C)

5.5 Identify key distinctions between GridLayout and GridBagLayout. A2 CO5


Answer

A layout manager that arranges components in a A more flexible layout manager that arranges components in a
Definition uniform grid of rows and columns. Each cell in the grid, allowing them to span multiple rows or columns. Each
grid has the same size. component can have different sizes and weights.

Fixed number of rows and columns is defined upon Uses a grid of cells where components can occupy multiple
Structure creation. Components fill the grid sequentially from left cells and can vary in size. Layout is determined by
to right and top to bottom. constraints specified for each component.

5.6 Outline any two advantages of NullLayout A2 CO5


Answer
1. Precise Control Over Component Placement
2. Useful for Dynamic Resizing

Part B [1x13=13 Marks]

5.7 a (i)Describe the component hierarchy in Swing.Explain the what are the classes used for different components. A2 CO5
Answer B2
 The Swing component hierarchy is designed to facilitate the creation and organization of GUI components in Java
applications.
 The base classes Component, Container, and JComponent allow for consistent behavior and properties among
components, while the various classes (like JButton, JLabel, JFrame, etc.) provide specialized functionality.
 Understanding this hierarchy is crucial for effectively using Swing to build robust and user-friendly applications
ii) Write a Swing program that creates a login page with two text fields (for username and password), two labels (for the username
and password), and a submit button.
Answer
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class LoginPage {


public static void main(String[] args) {
// Create the frame
JFrame frame = new JFrame("Login Page");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 150);
frame.setLayout(new GridLayout(3, 2));

// Create labels
JLabel usernameLabel = new JLabel("Username:");
JLabel passwordLabel = new JLabel("Password:");

// Create text fields


JTextField usernameField = new JTextField();
JPasswordField passwordField = new JPasswordField();

// Create submit button


JButton submitButton = new JButton("Submit");

// Add action listener to the submit button


submitButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String username = usernameField.getText();
String password = new String(passwordField.getPassword());
// Here you can add logic to handle the login (authentication)
JOptionPane.showMessageDialog(frame, "Username: " + username + "\nPassword: " + password);
}
});

// Add components to the frame


frame.add(usernameLabel);
frame.add(usernameField);
frame.add(passwordLabel);
frame.add(passwordField);
frame.add(submitButton);

// Set the frame to be visible


frame.setVisible(true);
}
}

[OR]

b (i)Describe the architecture of Swing which include details about the Model-View-Controller (MVC) design pattern. A2 CO5
Answer B2
 The Swing architecture leverages the MVC design pattern to create a flexible, maintainable, and extensible framework
for building GUI applications.
 By separating the data, presentation, and user input, developers can create responsive and interactive applications that
are easier to manage and evolve over time.

ii) Write a Swing program that simulates entering a student’s registration number (Register No) and name. Include two text boxes for
input and two labels to display the field names.
Answer
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class StudentRegistration {


public static void main(String[] args) {
// Create a new JFrame
JFrame frame = new JFrame("Student Registration");

// Create labels
JLabel registerNoLabel = new JLabel("Register No:");
registerNoLabel.setBounds(20, 20, 100, 30);
JLabel nameLabel = new JLabel("Name:");
nameLabel.setBounds(20, 60, 100, 30);

// Create text fields


JTextField registerNoField = new JTextField();
registerNoField.setBounds(120, 20, 150, 30);
JTextField nameField = new JTextField();
nameField.setBounds(120, 60, 150, 30);

// Create a submit button


JButton submitButton = new JButton("Submit");
submitButton.setBounds(120, 100, 100, 30);

// Add action listener to the button


submitButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String registerNo = registerNoField.getText(); // Get text from Register No field
String name = nameField.getText(); // Get text from Name field
// Display the entered information in a message dialog
JOptionPane.showMessageDialog(frame, "Register No: " + registerNo + "\nName: " + name);
}
});

// Add components to the frame


frame.add(registerNoLabel);
frame.add(registerNoField);
frame.add(nameLabel);
frame.add(nameField);
frame.add(submitButton);

// Set frame properties


frame.setSize(300, 200);
frame.setLayout(null); // Use no layout manager for absolute positioning
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

Course Faculty Course Coordinator Course Expert HoD

You might also like