Subject: Java Programming
[314317]
Assignments
Ch. No.
Name of chapter Marks
4 Event handling using Abstract Window Toolkit (AWT) & Swings 16
Components
5 Basics of Network Programming 10
6 Interacting with Database 08
Q.
No. IV. Event handling using Abstract Window Toolkit (AWT) & Swings
Components
1 Define AWT components and give any two examples. 2marks
Ans. AWT components are basic GUI elements used to create user interfaces in Java. AWT stands
for Abstract Window Toolkit. It is part of the [Link] package. AWT components are
platformdependent. They use native operating system resources (heavyweight components).
Examples: Label, Button, TextField, Checkbox.
2 What is an Event Listener in Java? 2marks
Ans. An Event Listener is an interface used to handle events in Java. It is part of the delegation
event model. It listens for events generated by event sources. When an event occurs, its
method is executed automatically. It helps in making GUI interactive.
Examples: ActionListener, MouseListener, KeyListener.
3 Explain the difference between AWT and Swing. 4marks
Ans.
No. AWT Swing
1. Platform-dependent Platform-independent
2. Uses heavyweight components Uses lightweight components
3. Depends on native OS Written completely in Java
4. Limited number of components Rich set of components
5.
Native look and feel Customizable look and feel
6. Less flexible More flexible
7. Slower performance (OS dependent) Faster performance (pure Java)
8. Package: [Link] Package: [Link]
Provides advanced components (JTable,
9. No advanced components like JTable
JTree, etc.)
10. Less suitable for modern GUI More suitable for modern GUI
4
Write a Java program using AWT to create a button and display a message when it is
clicked. 4marks
Ans.
import [Link].*;
import [Link].*;
class AWTButtonDemo
{
public static void main(String[] args)
{
Frame f = new Frame("AWT Button Example");
Button b = new Button("Click Me");
[Link](100, 100, 100, 40);
[Link](new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
[Link]("Button Clicked");
}
});
[Link](b);
[Link](300, 300);
[Link](null);
[Link](true);
}
}
5 Write a Java program using Swing to create a TextField and display entered text on
button click. 4marks
Ans. import [Link].*;
import [Link].*;
class SwingTextDemo
{
public static void main(String[] args)
{
JFrame f = new JFrame("Swing Example");
JTextField tf = new JTextField();
[Link](50, 50, 150, 30);
JButton b = new JButton("Show");
[Link](50, 100, 100, 30);
[Link](new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
[Link]("Entered Text: " + [Link]());
}
});
[Link](tf);
[Link](b);
[Link](300, 200);
[Link](null);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}
}
6. Name Different Layout manager. 2marks
Ans.
7. List the different types of Listeners.
Ans. In Java's Abstract Window Toolkit (AWT), event listeners are interfaces that handle various
types of user interactions and system-generated events. These listeners are part of the
[Link] package and enable developers to define responses to specific events. Here are
some commonly used AWT event listeners:
1. ActionListener: Handles action events, such as when a user clicks a button or selects a
menu item.
2. KeyListener: Manages keyboard events, including key presses, releases, and typing
actions.
3. MouseListener: Handles mouse events like clicks, presses, releases, entry, and exit
over components.
4. MouseMotionListener: Deals with mouse motion events, specifically mouse
movements and drags.
5. ItemListener: Handles item events, which occur when the state of an item (like a
checkbox or radio button) changes.
6. WindowListener: Manages window events, such as opening, closing, activating,
deactivating, iconifying, deiconifying, and closing a window.
7. FocusListener: Handles focus events, which occur when a component gains or loses
keyboard focus.
8. ComponentListener: Deals with component events, such as when a component is
hidden, shown, moved, or resized.
9. ContainerListener: Manages container events, which occur when a component is
added to or removed from a container.
AdjustmentListener: Handles adjustment events, typically associated with adjustable
components like scrollbars.
Q.
V. Basics of Network Programming
No.
1 Define a socket in network programming.
Ans A socket is an endpoint of communication between two devices. It enables data exchange
over a network. It uses an IP address and port number. Sockets are used in client-server
communication. It works with protocols like TCP and UDP. In Java, sockets are
implemented using classes like Socket and ServerSocket.
2 What is a proxy server? 2marks
Ans A proxy server acts as an intermediary between client and server. It forwards client requests
to the actual server. It helps in security and privacy protection. It can cache data to improve
performance. It hides the client’s IP address. It is used for filtering and monitoring network
traffic.
3 Difference between TCP Sockets and Datagram Sockets. 4marks
Ans. No. TCP Sockets Datagram Sockets (UDP)
1 Connection-oriented Connectionless
Requires connection setup (3-way
2 handshake) No connection setup required
3 Reliable data transfer Unreliable data transfer
4 Ensures data delivery No guarantee of delivery
5 Maintains data order Data order not maintained
6 Error checking and correction available Limited error checking
7 Slower due to reliability features Faster due to less overhead
8 Uses Socket and ServerSocket classes Uses DatagramSocket class
9 Used in web, email, file transfer Used in video streaming, gaming
10 Larger overhead Smaller overhead
4.
Explain InetAddress class with methods Program. 4marks
Ans. Explanation :
InetAddress class is used to represent an IP address in Java. It belongs to the [Link]
package. It is used to identify a host name or IP address. Factory methods are used to create
objects instead of constructors. Instance methods are used to get details of the IP address. It
supports both IPv4 and IPv6.
Factory Methods
• getByName(String host) → Returns IP of given host
• getLocalHost() → Returns local system IP
• getAllByName(String host) → Returns all IPs of host Instance Methods
• getHostName() → Returns host name
• getHostAddress() → Returns IP address
• toString() → Returns host + IP import [Link].*; class InetDemo
{
public static void main(String[] args) throws Exception {
// Factory Methods
InetAddress ip1 = [Link]("[Link]");
InetAddress ip2 = [Link]();
// Display Information using Instance Methods
[Link]("Google Host Name: " + [Link]());
[Link]("Google IP Address: " + [Link]());
[Link]("Local Host Name: " + [Link]());
[Link]("Local IP Address: " + [Link]());
}
}
5 Write a Java program for TCP client-server communication.
Ans Server Code:
import [Link].*;
import [Link].*;
class Server {
public static void main(String[] args) throws Exception {
ServerSocket ss = new ServerSocket(5000);
Socket s = [Link]();
PrintWriter out = new PrintWriter([Link](), true);
[Link]("Hello Client");
}
}
Client Code:
import [Link].*;
import [Link].*;
class Client {
public static void main(String[] args) throws Exception {
Socket s = new Socket("localhost", 5000);
BufferedReader in = new
BufferedReader( new
InputStreamReader([Link]()));
[Link]([Link]());
}
}
6. Write a program using URL class to retrieve the host, protocol, port and file of URL
[Link] 2marks
Ans. import [Link].*;
public class URLDetails {
public static void main(String[] args) {
try {
// Create a URL object
URL url = new URL("[Link]
// Retrieve and display URL components
[Link]("Protocol: " + [Link]());
[Link]("Host: " + [Link]());
[Link]("Port: " + [Link]()); // Returns -1 if no port is specified
[Link]("File: " + [Link]()); // Returns empty if no file is specified
[Link]("Default Port: " + [Link]()); // Default HTTP port (80)
}
catch (MalformedURLException e)
{
[Link]("Invalid URL: " + [Link]());
}
}
}
Q.
No. VI. Interacting with Database
1 Define JDBC and ODBC 2marks
Ans. 1. JDBC (Java Database Connectivity):
JDBC is an API used in Java programs to connect and interact with databases. It is
developed by Oracle Corporation (originally Sun Microsystems). JDBC provides
a standard way for Java applications to: full form pan lihi doghancha
• Connect to a database
• Execute SQL queries
• Retrieve and update data
It uses JDBC drivers to communicate with different types of databases like MySQL,
Oracle, or PostgreSQL.
Example: A Java program using JDBC to fetch records from a student database.
2. ODBC (Open Database Connectivity):
ODBC is a standard API that allows applications written in different programming
languages to access databases. It is developed by Microsoft.
ODBC acts as a bridge between an application and a database by using ODBC
drivers. It allows programs written in languages like C, C++, or Python to:
• Connect to databases
• Execute SQL queries
• Manage data
Example: A Python application using ODBC to connect to SQL Server.
2 Difference between Two-tier and Three-tier JDBC 4marks
Ans Featur Two-Tier Architecture
e Three-Tier Architecture
3 (Client + Application Server +
Layers 2 (Client + Database) Database)
Conne Direct connection to
ction database Indirect (through middle layer)
Middle
Layer Not present Present (Application server)
Securit Low (client accesses
y DB directly) High (DB hidden behind server)
Scalabi
lity Limited High
Perfor
mance Faster for small apps Better for large applications
Compl
exity Simple More complex
Mainte Difficult for large
nance systems Easier due to separation of logic
Use Small/desktop
Case applications Web/enterprise applications
3
Java Program to connect database using DriverManager 4marks
Ans import [Link].*; class DBConnect
{ public static void main(String[]
args) { try {
// Load Driver
[Link]("[Link]");
// Establish Connection
Connection con = [Link](
"jdbc:mysql://localhost:3306/test",
"root",
"password"
);
[Link]("Connected Successfully");
// Close Connection
[Link]();
} catch (Exception e) {
[Link](e);
}
}
}
4 Java Program using PreparedStatement to insert data.
Ans. import [Link].*;
class InsertData {
public static void main(String[] args) {
try {
// Load Driver
[Link]("[Link]");
// Connect Database
Connection con = [Link](
"jdbc:mysql://localhost:3306/test",
"root",
"password"
);
// Prepare Statement
String query = "INSERT INTO student VALUES (?, ?)";
PreparedStatement pst = [Link](query);
// Set Values
[Link](1, 101);
[Link](2, "Rahul");
// Execute
[Link]();
[Link]("Record Inserted");
[Link]();
} catch (Exception e) {
[Link](e);
}
}
}
5. Explain with neat diagram of JDBC architecture. 2marks
Ans. JDBC Architecture Diagram
Components of JDBC Architecture
1. Java Application
• The Java application sends SQL queries to the database using JDBC API.
• It processes the results returned by the database.
2. JDBC API
• The JDBC API provides methods for:
o Establishing
connections o Executing
SQL statements
o Retrieving results o
Handling transactions
• Key JDBC interfaces include:
o DriverManager o
Connection o Statement
o ResultSet o
PreparedStatement
3. JDBC Driver Manager
• The DriverManager class is responsible for:
o Loading the appropriate JDBC driver.
o Managing connections between Java applications and databases.
• It maintains a list of all registered JDBC drivers.
Example:
Connection conn = [Link]("jdbc:mysql://localhost:3306/mydb",
"root", "password");
4. JDBC Driver
• The JDBC driver acts as a translator between the Java application and the database.
• It converts JDBC method calls into database-specific calls.
• Types of JDBC Drivers:
1. JDBC-ODBC Bridge Driver (Type 1) – Deprecated
2. Native API Driver (Type 2) – Platform dependent
3. Network Protocol Driver (Type 3) – Uses middleware server
4. Thin Driver (Pure Java Driver) (Type 4) – Most commonly used (e.g.,
MySQL JDBC Driver)
5. Database Server
• The actual database where data is stored.
• Processes SQL queries sent by the JDBC driver.
• Sends results back to the Java application.