0% found this document useful (0 votes)
7 views

JPR Assignments 4-5-6

The document outlines a Java programming assignment focused on event handling using AWT and Swing components, covering topics such as creating frames and panels, layout managers, and various types of listeners. It includes detailed explanations, code examples, and key methods related to GUI components. Additionally, it defines concepts like events, event sources, and listeners, along with the relevant packages for AWT and Swing.

Uploaded by

Chinmay Aher
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

JPR Assignments 4-5-6

The document outlines a Java programming assignment focused on event handling using AWT and Swing components, covering topics such as creating frames and panels, layout managers, and various types of listeners. It includes detailed explanations, code examples, and key methods related to GUI components. Additionally, it defines concepts like events, event sources, and listeners, along with the relevant packages for AWT and Swing.

Uploaded by

Chinmay Aher
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 86

Subject: Java Programming [314317]

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 1 of 86


Assignments
Chapter
Name of chapter Marks
No.
Event Handling Using Abstract Window Toolkit (Awt) & Swings
4 16
Components
5 Basics of Network Programming 10

6 Interacting with Database 08

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 2 of 86


Q.
IV. Event handling using Abstract Window Toolkit (AWT) & Swings Components
No.
1 What is frame in swing? How to create frame.
Ans. In Swing (Java's GUI toolkit), a frame is a top-level window with a title and a border. It is
represented by the JFrame class in javax.swing. A frame is typically used as the main window of a
GUI application.

Creating a JFrame (Frame) in Swing

To create a frame, follow these steps:

1. Create an instance of JFrame.


2. Set properties like title, size, and default close operation.
3. Add components to the frame (like buttons, labels, etc.).
4. Make the frame visible.

import javax.swing.*;

public class MyFrame {


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

// Set frame properties


frame.setSize(400, 300); // Width: 400, Height: 300
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Close on exit
frame.setLayout(null); // No layout manager (absolute positioning)

// Make the frame visible


frame.setVisible(true);
}
}

Key Methods of JFrame

 setTitle(String title): Sets the frame title.


 setSize(int width, int height): Sets the frame size.
 setDefaultCloseOperation(int operation): Defines what happens when the close button is clicked
(JFrame.EXIT_ON_CLOSE to close the application).
 setVisible(boolean visible): Shows or hides the frame.
 setLayout(LayoutManager mgr): Sets the layout manager (or null for absolute positioning).
 add(Component comp): Adds a component to the frame.

2 What is panel? How to create with example.


Ans. In Swing, a panel (JPanel) is a container that holds and organizes GUI components like buttons, text

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 3 of 86


fields, and labels. It helps in managing the layout of components inside a JFrame.

A JPanel is not a window like JFrame; it is just a section within a window where components are
grouped.

How to Create a JPanel

1. Create an instance of JPanel.


2. Set properties like size, layout, and background color.
3. Add components (buttons, labels, etc.) to the panel.
4. Add the panel to a JFrame.

import javax.swing.*;

public class MyPanelExample {


public static void main(String[] args) {
// Create a frame
JFrame frame = new JFrame("JPanel Example");
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Create a panel
JPanel panel = new JPanel();

// Create components
JButton button = new JButton("Click Me");
JLabel label = new JLabel("Hello, Swing!");

// Add components to panel


panel.add(label);
panel.add(button);

// Add panel to frame


frame.add(panel);

// Make the frame visible


frame.setVisible(true);
}
}

Key Features of JPanel


 Container: It groups components together inside a JFrame.
 Supports Layouts: By default, it uses FlowLayout, but you can set others like GridLayout,
BorderLayout, etc..
 Customizable: You can set the background color, border, or even make custom drawings.

3 Name Different Layout manager.

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 4 of 86


Ans. Different Layout Managers in Java Swing

Swing provides several layout managers to control how components are arranged within containers
like JPanel and JFrame. Below are the commonly used layout managers:

1. FlowLayout (Default for JPanel)

 Arranges components in a row, one after another.


 If the row is full, it moves to the next row.
 Default alignment is center.

Example:

JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT));

2. BorderLayout (Default for JFrame)

 Divides the container into five regions: NORTH, SOUTH, EAST, WEST, CENTER.
 Useful for positioning major sections of a UI.

Example:

JFrame frame = new JFrame();


frame.setLayout(new BorderLayout());
frame.add(new JButton("North"), BorderLayout.NORTH);
frame.add(new JButton("Center"), BorderLayout.CENTER);

3. GridLayout

 Arranges components in a grid of rows and columns.


 All cells have equal size.

Example:

JPanel panel = new JPanel(new GridLayout(2, 2)); // 2 rows, 2 columns

4. BoxLayout

 Arranges components vertically (Y_AXIS) or horizontally (X_AXIS).

Example:

JPanel panel = new JPanel();


panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 5 of 86


5. CardLayout

 Stacks multiple components (like cards) and allows switching between them.
 Used for multi-page forms or wizards.

Example:

CardLayout cardLayout = new CardLayout();


JPanel panel = new JPanel(cardLayout);

6. GridBagLayout (Advanced, Flexible)

 Allows components to span multiple rows/columns.


 Supports precise control over alignment and resizing.

Example:

JPanel panel = new JPanel(new GridBagLayout());

4 Define Container list any 4 type of container


Ans. In Java's Abstract Window Toolkit (AWT), a container is a component that can hold and manage
other components, such as buttons, text fields, and other containers. Containers are essential for
creating complex graphical user interfaces (GUIs) by organizing and controlling the layout of their
child components.

Here are four primary types of containers in AWT:

1. Frame: A Frame is a top-level window with a title and border, capable of hosting other GUI
components. It serves as the main window for standalone applications. Frames can include
elements like menus, buttons, and text fields.
2. Panel: A Panel is a generic container used to group a collection of components within a
window. Panels are often employed to organize related components and can be nested within
other containers. They don't have a title bar or menu but are useful for structuring the GUI.

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 6 of 86


3. Window: A Window is a top-level container that lacks a title bar and border. It's typically used
as a base for creating other top-level windows or dialogs that don't require standard window
decorations. Windows are often utilized for creating custom pop-up windows or splash
screens.
4. Dialog: A Dialog is a pop-up window designed to capture user input or provide information.
Dialogs can be modal (blocking input to other windows until closed) or non-modal. They're
commonly used for tasks like displaying messages, confirming actions, or gathering user data.

Understanding and effectively utilizing these AWT containers is fundamental to building organized
and responsive Java GUI applications.
5 Name the package which is used to design AWT control.
Ans. In Java, the Abstract Window Toolkit (AWT) is utilized for creating graphical user interfaces (GUIs). The
classes and interfaces necessary for designing AWT controls are contained within the java.awt package. This
package includes components such as buttons, text fields, and labels, as well as supporting classes for event
handling, layouts, and graphics.
6 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 java.awt.event 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.
10. AdjustmentListener: Handles adjustment events, typically associated with adjustable
components like scrollbars.

7 List method of KeyListener with syntax.


Ans. In Java's Abstract Window Toolkit (AWT), the KeyListener interface is used to receive and handle
keyboard events. It resides in the java.awt.event package and defines the following three methods:

1. keyPressed(KeyEvent e):
o Purpose: Invoked when a key is pressed down.

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 7 of 86


o Syntax:

void keyPressed(KeyEvent e);

2. keyReleased(KeyEvent e):
o Purpose: Invoked when a key is released after being pressed.
o Syntax:

void keyReleased(KeyEvent e);

3. keyTyped(KeyEvent e):
o Purpose: Invoked when a key is typed. This event occurs when a key press is followed
by a key release for keys that correspond to characters.
o Syntax:

void keyTyped(KeyEvent e);

o Parameter: e - an instance of KeyEvent containing details about the key event.

8 Name method of MouseListener with syntax


Ans. In Java's Abstract Window Toolkit (AWT), the MouseListener interface, located in the java.awt.event
package, is designed to handle mouse events such as clicks, presses, releases, and cursor movements
over components. This interface defines five methods that must be implemented to respond to these
events:

1. mouseClicked(MouseEvent e):
o Purpose: Invoked when the mouse button has been clicked (pressed and released) on a
component.
o Syntax:

void mouseClicked(MouseEvent e);

2. mousePressed(MouseEvent e):
o Purpose: Invoked when a mouse button has been pressed on a component.
o Syntax:

void mousePressed(MouseEvent e);

3. mouseReleased(MouseEvent e):
o Purpose: Invoked when a mouse button has been released on a component.
o Syntax:

void mouseReleased(MouseEvent e);

4. mouseEntered(MouseEvent e):
o Purpose: Invoked when the mouse enters a component.
o Syntax:

void mouseEntered(MouseEvent e);

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 8 of 86


5. mouseExited(MouseEvent e):
o Purpose: Invoked when the mouse exits a component.
o Syntax:

void mouseExited(MouseEvent e);

o Parameter: e - an instance of MouseEvent containing details about the mouse event.

9 Name method of MouseMotionListener with syntax


Ans. In Java's Abstract Window Toolkit (AWT), the MouseMotionListener interface, part of the java.awt.event
package, is designed to handle mouse motion events, specifically when the mouse is moved or
dragged within a component. This interface defines two methods:

1. mouseDragged(MouseEvent e):
o Purpose: Invoked when a mouse button is pressed on a component and then dragged.
This event is continually triggered as the mouse is moved while the button remains
pressed.
o Syntax:

void mouseDragged(MouseEvent e);

o Parameter: e - an instance of MouseEvent containing details about the drag event.


2. mouseMoved(MouseEvent e):
o Purpose: Invoked when the mouse is moved within a component without any mouse
buttons being pressed.
o Syntax:

void mouseMoved(MouseEvent e);

o Parameter: e - an instance of MouseEvent containing details about the movement event.

10 Name method of ItemListener , ActionListener with syntax


Ans. In Java's Abstract Window Toolkit (AWT), the ItemListener and ActionListener interfaces are used to
handle specific types of events. Each interface defines a single method that must be implemented to
respond to the corresponding events.

1. ItemListener Interface:
o Method: itemStateChanged(ItemEvent e)
 Purpose: Invoked when the state of an item changes, such as when a checkbox
is selected or deselected.
 Syntax:

void itemStateChanged(ItemEvent e);

 Parameter: e - an instance of ItemEvent containing details about the item event.


2. ActionListener Interface:
o Method: actionPerformed(ActionEvent e)

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 9 of 86


 Purpose: Invoked when an action occurs, such as when a button is clicked.
 Syntax:

void actionPerformed(ActionEvent e);

 Parameter: e - an instance of ActionEvent containing details about the action


event.

11 Name method of TextListener with syntax


Ans. In Java's Abstract Window Toolkit (AWT), the TextListener interface, located in the java.awt.event
package, is designed to handle text events generated by components like TextField and TextArea. This
interface defines a single method:

1. textValueChanged(TextEvent e):
o Purpose: Invoked when the text within a text component changes, such as when the
user types or deletes characters.
o Syntax:

void textValueChanged(TextEvent e);

o Parameter: e - an instance of TextEvent containing details about the text change event.

12 Name the package which is used to design AWT control and swing.
Ans. In Java, the packages used for designing graphical user interfaces (GUIs) are:

1. Abstract Window Toolkit (AWT):


o Package: java.awt
o Description: The java.awt package contains classes for creating user interfaces and for
painting graphics and images. It includes components like buttons, text fields, and
menus, as well as classes for event handling, layouts, and more.
2. Swing:
o Package: javax.swing
o Description: The javax.swing package provides a set of "lightweight" (all-Java
language) components that work consistently across all platforms. Swing offers a
richer set of GUI components than AWT, including tables, trees, and tabbed panes, and
allows for a pluggable look and feel.

13 Define Event, source and Listener


Ans. Event: An event in Java represents a specific occurrence within a program, typically resulting from
user actions such as mouse clicks, key presses, or other interactions with GUI components. Each
event is encapsulated in an event object that contains information about the event, including its type
and the source component that generated it. For example, clicking a button generates an ActionEvent,
while pressing a key produces a KeyEvent.

Event Source: An event source is an object that generates events. This is usually a GUI component
like a button, text field, or menu item that the user interacts with. When an event occurs, the event
source creates an event object containing details about the event and notifies all registered listeners

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 10 of 86


about this occurrence. For instance, a Button component can generate an ActionEvent when clicked.

Event Listener: An event listener is an object that is notified when an event occurs. It must
implement a specific listener interface corresponding to the event type it intends to handle, such as
ActionListener for action events or KeyListener for key events. The listener object registers itself with an
event source to receive notifications. Upon the occurrence of an event, the event source invokes the
appropriate method on the listener object, allowing it to respond accordingly.
14 Design an application to create from using Textfield, Textarea, Button and Lable.
Ans. import java.awt.*;
import java.awt.event.*;

public class AWTFormExample extends Frame implements ActionListener {


private TextField textField;
private TextArea textArea;
private Button button;
private Label label;

public AWTFormExample() {
// Set the title of the window
setTitle("AWT Form Example");

// Set the layout manager


setLayout(new FlowLayout());

// Initialize components
label = new Label("Enter your name:");
textField = new TextField(20);
textArea = new TextArea(5, 20);
button = new Button("Submit");

// Add components to the frame


add(label);
add(textField);
add(textArea);
add(button);

// Configure frame settings


setSize(300, 250);
setVisible(true);

// Add window closing event to close the application


addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
dispose();
}
});
}

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 11 of 86


public static void main(String[] args) {
// Run the application
new AWTFormExample();
}
}
15 WAP to create three Button with Caption, OK, RESET and Cancel.
Ans. import java.awt.*;
import java.awt.event.*;

public class ButtonExample extends Frame {


private Button okButton;
private Button resetButton;
private Button cancelButton;

public ButtonExample() {
// Set the title of the window
setTitle("Button Example");

// Set the layout manager


setLayout(new FlowLayout());

// Initialize buttons
okButton = new Button("OK");
resetButton = new Button("RESET");
cancelButton = new Button("CANCEL");

// Add buttons to the frame


add(okButton);
add(resetButton);
add(cancelButton);

// Configure frame settings


setSize(300, 100);
setVisible(true);

// Add window listener to handle window closing event


addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
dispose();
}
});
}

public static void main(String[] args) {


// Run the application
new ButtonExample();
}
}

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 12 of 86


16 Explain feature of swing.
Ans. Java Swing is a part of the Java Foundation Classes (JFC) that provides a comprehensive set of GUI
components for building desktop applications in Java. It serves as an extension to the Abstract
Window Toolkit (AWT), offering enhanced functionality and a richer set of user interface elements.

Key Features of Java Swing:

1. Platform Independence: Swing components are written entirely in Java, enabling


applications to run consistently across all platforms without relying on native operating system
capabilities. This ensures a uniform appearance and behavior regardless of the underlying
system.
2. Lightweight Components: Unlike AWT components that depend on native system resources,
Swing components are lightweight as they are rendered using pure Java code. This reduces the
overhead and enhances the performance of GUI applications.
3. Rich Set of Controls: Swing provides a wide array of advanced controls such as trees, tabbed
panes, sliders, color pickers, and tables, allowing developers to create sophisticated and
feature-rich user interfaces.
4. Pluggable Look-and-Feel: Swing supports a pluggable look-and-feel architecture, enabling
applications to adopt different appearances, whether emulating native platform styles or
custom themes defined by developers. This flexibility allows for a tailored user experience.
5. MVC Architecture: Swing follows the Model-View-Controller (MVC) design pattern,
separating data (Model), user interface (View), and user input handling (Controller). This
separation enhances the maintainability and scalability of applications.
6. Event Handling: Swing offers a robust event-handling mechanism, allowing developers to
manage user interactions effectively. This includes support for drag-and-drop operations and
complex event chaining.
7. Customizable Components: Swing controls are highly customizable and configurable,
enabling developers to modify their behavior and appearance to meet specific application
requirements.

17 Write a program to demonstrate the use of keyEvent when key is pressed and display
“keypressed” message
Ans. import java.awt.*;
import java.awt.event.*;
public class KeyPressDemo extends Frame implements KeyListener {

private Label label;

public KeyPressDemo() {
// Set up the frame
setTitle("Key Press Demo");
setSize(400, 200);
setLayout(new FlowLayout());
setVisible(true);

// Initialize the label


label = new Label("Press any key...");
add(label);

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 13 of 86


// Add the KeyListener to the frame
addKeyListener(this);

// Add a window listener for the close button


addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
dispose();
}
});
}
// Implement the keyPressed method
public void keyPressed(KeyEvent e) {
label.setText("Key Pressed");
}

// Implement the keyReleased method


public void keyReleased(KeyEvent e) {
label.setText("Press any key...");
}

// Implement the keyTyped method


public void keyTyped(KeyEvent e) {
// Not used in this example
}

public static void main(String[] args) {


new KeyPressDemo();
}
}
18 Write a program to display The Number on Button from 0 to 9 using FlowLayout.
Ans. import java.awt.*;

public class NumberButtons extends Frame {

public NumberButtons() {
setTitle("Number Buttons");
setSize(300, 200);
setLayout(new FlowLayout());

// Manually create and add buttons labeled "0" to "9"


Button button0 = new Button("0");
add(button0);

Button button1 = new Button("1");


add(button1);

Button button2 = new Button("2");

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 14 of 86


add(button2);

Button button3 = new Button("3");


add(button3);

Button button4 = new Button("4");


add(button4);

Button button5 = new Button("5");


add(button5);

Button button6 = new Button("6");


add(button6);

Button button7 = new Button("7");


add(button7);

Button button8 = new Button("8");


add(button8);

Button button9 = new Button("9");


add(button9);

// Display the frame


setVisible(true);
}
public static void main(String[] args) {
new NumberButtons();
}
}
19 Write a program to generate following output.

Ans. import javax.swing.*;


import java.awt.*;

public class GridLayoutDemo {


public static void main(String[] args) {
// Create a JFrame

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 15 of 86


JFrame frame = new JFrame("GridLayout Demo");
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Set GridLayout with 3 rows and 2 columns


frame.setLayout(new GridLayout(3, 2, 10, 10)); // 10px gap between components

// Create buttons
JButton button1 = new JButton("Button 1");
JButton button2 = new JButton("Button 2");
JButton button3 = new JButton("Button 3");
JButton button4 = new JButton("Button 4");
JButton button5 = new JButton("Button 5");

// Add buttons to the frame


frame.add(button1);
frame.add(button2);
frame.add(button3);
frame.add(button4);
frame.add(button5);

// Set the frame visibility


frame.setVisible(true);
}
}
20 Explain Delegation Event Model
Ans. In Java, the Delegation Event Model is a robust and flexible mechanism for handling events,
particularly within graphical user interfaces (GUIs). This model streamlines event processing by
delegating the responsibility of handling events from the event source to designated listener objects.

Key Components of the Delegation Event Model:

1. Event Source: This is the object that generates an event. Common examples include GUI
components like buttons, text fields, and windows. When a user interacts with these
components (e.g., clicking a button), the component generates an event.
2. Event Listener: An event listener is an object that is notified when an event occurs. It must
implement specific interfaces corresponding to the event type it intends to handle. By
implementing these interfaces, the listener defines methods that dictate the actions to be
performed in response to particular events.
3. Event Object: This object encapsulates information about the event, such as its type and the
source that generated it. The event object is passed as an argument to the listener's event-
handling methods, providing context about the event.

How the Delegation Event Model Works:

 Registration: The event listener registers itself with the event source. This is typically done
using methods provided by the event source, such as addActionListener() for buttons. By
registering, the listener expresses its interest in being notified when specific events occur.

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 16 of 86


 Event Occurrence: When the user interacts with the event source (e.g., clicking a button), the
source generates an event object containing details about the interaction.
 Notification: The event source delegates the event to the registered listener by invoking the
appropriate method defined in the listener interface, passing the event object as an argument.
The listener then processes the event accordingly.

Advantages of the Delegation Event Model:

 Separation of Concerns: By delegating event handling to separate listener objects, the model
promotes a clear separation between the application's logic and its user interface components.
This enhances code maintainability and readability.
 Flexibility: Multiple listeners can register with a single event source, allowing different
components to respond to the same event in various ways. This facilitates the development of
complex, interactive applications.
 Reusability: Listeners can be reused across different components and applications, promoting
code reuse and reducing redundancy.

Implementing the Delegation Event Model:

To implement this model in Java, follow these steps:

1. Implement the Listener Interface: Create a class that implements the appropriate listener
interface for the event you want to handle. For example, to handle action events from a button,
implement the ActionListener interface.
2. Register the Listener: Instantiate the listener class and register it with the event source using
the source's registration method (e.g., addActionListener() for buttons).
3. Define Event-Handling Methods: Override the methods specified in the listener interface to
define the actions that should occur when the event is triggered.

21 WAP which create a menubar with different colour.


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

public class CustomMenuBarExample {

public static void main(String[] args) {


// Create the frame
JFrame frame = new JFrame("Custom MenuBar Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);

// Create the menu bar


JMenuBar menuBar = new JMenuBar();
menuBar.setBackground(Color.CYAN); // Set background color of menu bar

// Create menus with different background colors


JMenu fileMenu = new JMenu("File");
fileMenu.setBackground(Color.LIGHT_GRAY); // Set background color of File menu

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 17 of 86


JMenu editMenu = new JMenu("Edit");
editMenu.setBackground(Color.PINK); // Set background color of Edit menu
JMenu viewMenu = new JMenu("View");
viewMenu.setBackground(Color.ORANGE); // Set background color of View menu

// Create menu items for the File menu


JMenuItem newItem = new JMenuItem("New");
JMenuItem openItem = new JMenuItem("Open");
JMenuItem exitItem = new JMenuItem("Exit");

// Add menu items to the File menu


fileMenu.add(newItem);
fileMenu.add(openItem);
fileMenu.addSeparator(); // Adds a separator line
fileMenu.add(exitItem);

// Add menus to the menu bar


menuBar.add(fileMenu);
menuBar.add(editMenu);
menuBar.add(viewMenu);

// Set the menu bar for the frame


frame.setJMenuBar(menuBar);

// Set the frame's visibility


frame.setVisible(true);
}
}
22 Write a program to demonstrate ActionListener Interface.
Ans. import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

class ActionEventExample extends JFrame implements ActionListener


{
JButton button;
JLabel label;

ActionEventExample()
{
setTitle("Action Event Example");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());

button = new JButton("Click Me");


label = new JLabel("Press the button");

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 18 of 86


button.addActionListener(this);

add(button);
add(label);

setVisible(true);
}

public void actionPerformed(ActionEvent e)


{
label.setText("Button Clicked!");
}

public static void main(String[] args)


{
new ActionEventExample();
}
}
23 Write a program using JTextField to perform the addition of two numbers
Ans. import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class AdditionApp extends JFrame implements ActionListener {


private JTextField firstNumberField;
private JTextField secondNumberField;
private JButton addButton;
private JLabel resultLabel;

public AdditionApp() {
// Set up the frame
setTitle("Addition Application");
setSize(300, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());

// Initialize components
firstNumberField = new JTextField(10);
secondNumberField = new JTextField(10);
addButton = new JButton("Add");
resultLabel = new JLabel("Result: ");

// Add action listener to the button


addButton.addActionListener(this);

// Add components to the frame

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 19 of 86


add(new JLabel("Enter first number:"));
add(firstNumberField);
add(new JLabel("Enter second number:"));
add(secondNumberField);
add(addButton);
add(resultLabel);

// Make the frame visible


setVisible(true);
}

public void actionPerformed(ActionEvent e) {


// Parse numbers from text fields
double num1 = Double.parseDouble(firstNumberField.getText());
double num2 = Double.parseDouble(secondNumberField.getText());

// Perform addition
double sum = num1 + num2;

// Display result
resultLabel.setText("Result: " + sum);

public static void main(String[] args) {


new AdditionApp();
}
}
24 Write a program to demonstrate the use of mouseDragged and mouseMoved method of
MouseMotionListener
Ans. import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class MouseMotionExample extends JFrame implements MouseMotionListener {

private JLabel statusLabel;

public MouseMotionExample() {
setTitle("Mouse Motion Listener Example");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());

statusLabel = new JLabel("Move or drag the mouse within the window.");


statusLabel.setHorizontalAlignment(SwingConstants.CENTER);
add(statusLabel, BorderLayout.SOUTH);

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 20 of 86


addMouseMotionListener(this);
setVisible(true);
}

public void mouseMoved(MouseEvent e) {


statusLabel.setText("Mouse moved to X: " + e.getX() + ", Y: " + e.getY());
}

public void mouseDragged(MouseEvent e) {


statusLabel.setText("Mouse dragged to X: " + e.getX() + ", Y: " + e.getY());
}

public static void main(String[] args) {


new MouseMotionExample();
}
}
25 Write a java program to create a table of name of Student ,Percentage and Grade of 5 Student
using JTable.
Ans. import javax.swing.*;
import java.awt.*;

public class StudentTableExample extends JFrame {

public StudentTableExample() {
// Sample data for 5 students
Object[][] studentData = {
{"Alice Johnson", 85, "B"},
{"Bob Smith", 92, "A"},
{"Charlie Brown", 78, "C"},
{"Diana Prince", 88, "B"},
{"Ethan Hunt", 95, "A"}
};

// Column names
String[] columnNames = {"Name", "Percentage", "Grade"};

// Create JTable with data


JTable studentTable = new JTable(studentData, columnNames);

// Add the table to a scroll pane


JScrollPane scrollPane = new JScrollPane(studentTable);
studentTable.setFillsViewportHeight(true);

// Set layout manager and add components


setLayout(new BorderLayout());
add(scrollPane, BorderLayout.CENTER);

// Frame properties

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 21 of 86


setTitle("Student Grades Table");
setSize(400, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null); // Center the frame
setVisible(true);
}

public static void main(String[] args)


{
new StudentTableExample());
}
}
26 Develop an application using List components to add names of 10 different cities.
Ans. import java.awt.*;
import java.awt.event.*;

public class CityListApp extends Frame {

public CityListApp() {
// Set the title of the frame
setTitle("City List");

// Define an array of city names


String[] cities = {
"New York", "Los Angeles", "Chicago", "Houston", "Phoenix",
"Philadelphia", "San Antonio", "San Diego", "Dallas", "San Jose"
};

// Create a List component


List cityList = new List(10); // 10 rows visible
for (String city : cities) {
cityList.add(city);
}

// Add the List to the frame


add(cityList);

// Set the size of the frame


setSize(300, 200);

// Use FlowLayout for the frame


setLayout(new FlowLayout());

// Add a window listener to handle the close operation


addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
dispose();
}

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 22 of 86


});

// Make the frame visible


setVisible(true);
}

public static void main(String[] args) {


new CityListApp();
}
}
27 Design an application to demonstrate the use of Radio Button and Checkbox using swing
Ans. import javax.swing.*;
import java.awt.*;

public class RadioButtonCheckboxDemo extends JFrame {

public RadioButtonCheckboxDemo() {
setTitle("RadioButton and Checkbox Demo");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());

// Create RadioButtons
JRadioButton option1 = new JRadioButton("Option 1");
JRadioButton option2 = new JRadioButton("Option 2");
JRadioButton option3 = new JRadioButton("Option 3");

// Group the RadioButtons


ButtonGroup group = new ButtonGroup();
group.add(option1);
group.add(option2);
group.add(option3);

// Create CheckBoxes
JCheckBox checkBox1 = new JCheckBox("CheckBox 1");
JCheckBox checkBox2 = new JCheckBox("CheckBox 2");
JCheckBox checkBox3 = new JCheckBox("CheckBox 3");

// Add components to the frame


add(new JLabel("Select one option:"));
add(option1);
add(option2);
add(option3);

add(new JLabel("Select multiple options:"));


add(checkBox1);
add(checkBox2);
add(checkBox3);

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 23 of 86


setVisible(true);
}

public static void main(String[] args) {


new RadioButtonCheckboxDemo();
}
}
28 Write a program to generate following output using Border Layout.

Ans. import javax.swing.*;


import java.awt.*;

public class BorderLayoutDemo {


public BorderLayoutDemo() {
JFrame frame = new JFrame("BorderLayout Example");
frame.setSize(400, 300);
frame.setLayout(new BorderLayout());

// Creating buttons
JButton topButton = new JButton("North");
JButton bottomButton = new JButton("South");
JButton leftButton = new JButton("West");
JButton rightButton = new JButton("East");
JButton centerButton = new JButton("Center");

// Adding buttons to the frame with BorderLayout


frame.add(topButton, BorderLayout.NORTH);
frame.add(bottomButton, BorderLayout.SOUTH);
frame.add(leftButton, BorderLayout.WEST);
frame.add(rightButton, BorderLayout.EAST);
frame.add(centerButton, BorderLayout.CENTER);

// Window close operation


frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}

public static void main(String[] args) {


new BorderLayoutDemo();

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 24 of 86


}
}
29 Write JTree program to show following output.

Ans. import javax.swing.*;


import javax.swing.tree.DefaultMutableTreeNode;

public class JTreeExample {


public static void main(String[] args) {
// Create the root node
DefaultMutableTreeNode root = new DefaultMutableTreeNode("Style");

// Create "color" node and add color options


DefaultMutableTreeNode colorNode = new DefaultMutableTreeNode("color");
colorNode.add(new DefaultMutableTreeNode("red"));
colorNode.add(new DefaultMutableTreeNode("blue"));
colorNode.add(new DefaultMutableTreeNode("black"));
colorNode.add(new DefaultMutableTreeNode("green"));

// Create "font" node


DefaultMutableTreeNode fontNode = new DefaultMutableTreeNode("font");

// Add child nodes to the root


root.add(colorNode);
root.add(fontNode);

// Create the JTree with the root node


JTree tree = new JTree(root);

// Create a JFrame and add the tree to it


JFrame frame = new JFrame("JTree Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new JScrollPane(tree)); // Add tree inside a scroll pane
frame.setSize(300, 200);
frame.setVisible(true);
}
}
30 Write a program which create Progress bar Vertically.
Ans. import javax.swing.*;
import java.awt.*;

public class VerticalProgressBarExample extends JFrame {


public VerticalProgressBarExample() {

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 25 of 86


setTitle("Vertical Progress Bar Example");
setSize(200, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());

// Create a vertical progress bar with minimum 0 and maximum 100


JProgressBar verticalProgressBar = new JProgressBar(JProgressBar.VERTICAL, 0, 100);
verticalProgressBar.setValue(0); // Set initial progress value
verticalProgressBar.setStringPainted(true); // Display progress percentage

add(verticalProgressBar, BorderLayout.CENTER);

// Simulate progress in a separate thread


new Thread(() -> {
for (int i = 0; i <= 100; i++) {
final int progress = i;
SwingUtilities.invokeLater(() -> verticalProgressBar.setValue(progress));
try {
Thread.sleep(100); // Simulate time-consuming task
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();

setVisible(true);
}

public static void main(String[] args) {


new VerticalProgressBarExample();
}
}
31 Differences between SWING and AWT.
Ans. Parameter AWT (Abstract Window Toolkit) Swing
Platform Relies on the underlying native
Dependency operating system's GUI Renders its own components using
components, making it platform- pure Java, ensuring platform
dependent. independence.
Component Weight Components are heavyweight as Components are lightweight
they depend on native resources because they are written entirely in
of the host operating system. Java and do not rely on native code.
Look and Feel Provides the look and feel of the Offers a pluggable look and feel,
native operating system, which allowing developers to customize
can vary across platforms. the appearance of applications to be
consistent across platforms.
Component Offers a limited set of GUI Provides a comprehensive set of

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 26 of 86


Richness components. advanced components, such as
tables, trees, and tabbed panes,
enhancing the functionality of
applications.
Performance May exhibit performance issues Generally offers better performance
due to reliance on system and flexibility, although it may
resources and native code. require more memory due to its
lightweight components.
Event Handling Uses an older event-handling Implements the newer and more
model which can be less efficient. efficient event delegation model,
improving event handling
capabilities.
Extensibility Limited in terms of extensibility Highly extensible, allowing
and customization of developers to create custom
components. components and modify existing
ones to suit specific needs.
Threading Model Follows the simple single- Utilizes a more sophisticated
threaded model, which can lead threading model with the
to potential issues in GUI updates. SwingWorker class, facilitating better
handling of long-running tasks.
Data Binding Does not support automatic data Supports automatic data binding
binding. with models like TableModel,
enhancing data management in
components like JTable.
Internationalization Limited support for Provides robust support for
internationalization. internationalization, making it easier
to develop applications for a global
audience.
32 Write a program to create Combo Box
Ans. import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class JComboBoxExample extends JFrame implements ActionListener {


JComboBox<String> comboBox;
JLabel label;

public JComboBoxExample() {
setTitle("JComboBox Example");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());

String[] items = {"Apple", "Banana", "Cherry", "Date", "Elderberry"};

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 27 of 86


comboBox = new JComboBox<>(items);
comboBox.addActionListener(this);

label = new JLabel("Select a fruit");

add(comboBox);
add(label);

setVisible(true);
}
public void actionPerformed(ActionEvent e) {
label.setText("Selected: " + comboBox.getSelectedItem());
}

public static void main(String[] args) {


new JComboBoxExample();
}
}

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 28 of 86


Q. V. Basics Of Network Programming
No.
1. What is networking? write its advantage and disadvantage .
Ans. What is Networking?

Networking refers to the practice of connecting computers and other devices to share resources,
exchange data, and communicate efficiently. It can be classified into different types, such as LAN
(Local Area Network), WAN (Wide Area Network), MAN (Metropolitan Area Network), and
PAN (Personal Area Network).

Advantages of Networking

1. Resource Sharing – Devices like printers, scanners, and storage can be shared among multiple
users, reducing costs.
2. Data Sharing – Users can easily share files and information without the need for external
storage devices.
3. Improved Communication – Emails, instant messaging, and video calls enable fast and
efficient communication.
4. Centralized Data Management – Data can be stored and accessed from a central location,
improving security and accessibility.
5. Scalability – Networks can be expanded as the organization grows.
6. Remote Access – Users can access the network from different locations, enabling remote work.
7. Cost Efficiency – Reduces the need for multiple standalone systems, leading to lower
operational costs.

Disadvantages of Networking

1. Security Risks – Networks are vulnerable to hacking, viruses, and data breaches.
2. High Initial Setup Cost – Installing networking infrastructure can be expensive.
3. Complex Maintenance – Requires skilled professionals to maintain and troubleshoot network
issues.
4. Data Loss Risk – If the central server crashes, critical data may be lost if proper backups are
not maintained.
5. Network Congestion – Too many devices on a network can slow down performance.
6. Unauthorized Access – Weak security settings can allow unauthorized users to access sensitive
information.
7. Dependency on Servers – If the main server fails, it can disrupt the entire network.

2. Define Socket and ServerSocket class.


Ans. Socket and ServerSocket Classes in Java

In Java, the Socket and ServerSocket classes are part of the java.net package and are used for network
communication using the TCP/IP protocol.

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 29 of 86


1. Socket Class

The Socket class is used to create a client-side socket that connects to a server. It facilitates
communication between the client and the server over a network.

Key Methods of Socket Class:

 Socket(String host, int port): Connects to a server using the specified hostname and port.
 getInputStream(): Returns an input stream to read data from the server.
 getOutputStream(): Returns an output stream to send data to the server.
 close(): Closes the socket connection.

Example of a Client using Socket Class

import java.io.*;
import java.net.*;

public class Client {


public static void main(String[] args) {
try {
// Connect to server at localhost on port 5000
Socket socket = new Socket("localhost", 5000);

// Send message to server


OutputStreamWriter writer = new OutputStreamWriter(socket.getOutputStream());
writer.write("Hello, Server!\n");
writer.flush();

// Read response from server


BufferedReader reader = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
System.out.println("Server says: " + reader.readLine());

// Close connection
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

2. ServerSocket Class

The ServerSocket class is used to create a server-side socket that listens for incoming client
connections. It acts as a communication endpoint for server applications.

Key Methods of ServerSocket Class:

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 30 of 86


 ServerSocket(int port): Creates a server socket bound to the specified port.
 accept(): Waits for and accepts an incoming client connection, returning a Socket object.
 close(): Closes the server socket.

Example of a Server using ServerSocket Class


import java.io.*;
import java.net.*;

public class Server {


public static void main(String[] args) {
try {
// Create server socket on port 5000
ServerSocket serverSocket = new ServerSocket(5000);
System.out.println("Server is waiting for client...");

// Accept client connection


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

// Read message from client


BufferedReader reader = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
System.out.println("Client says: " + reader.readLine());

// Send response to client


OutputStreamWriter writer = new OutputStreamWriter(socket.getOutputStream());
writer.write("Hello, Client!\n");
writer.flush();

// Close connections
socket.close();
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

How It Works?

1. The server starts first and listens on a specific port using ServerSocket.
2. A client connects to the server using Socket with the same port number.
3. Data is exchanged between the client and server using input and output streams.
4. Both close their connections after the communication is complete.

3 Write the use of getByName() and getAllByName() method.

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 31 of 86


Ans. Use of getByName() and getAllByName() Methods in Java

Both methods belong to the InetAddress class in the java.net package and are used to retrieve IP
addresses from a given hostname.

1. getByName(String host)

 This method returns a single InetAddress object containing the IP address of the given
hostname.
 If the hostname has multiple IP addresses, it returns only one (not necessarily the primary one).

Syntax:
public static InetAddress getByName(String host) throws UnknownHostException

Example:
import java.net.*;

public class GetByNameExample {


public static void main(String[] args) {
try {
InetAddress address = InetAddress.getByName("www.google.com");
System.out.println("IP Address: " + address.getHostAddress());
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
Output (Example):

IP Address: 142.250.190.36

2. getAllByName(String host)

 This method returns an array of InetAddress objects containing all IP addresses associated with
the given hostname.
 Useful when a domain has multiple IP addresses (e.g., load-balanced servers).

Syntax:
public static InetAddress[] getAllByName(String host) throws UnknownHostException

Example:
import java.net.*;

public class GetAllByNameExample {


public static void main(String[] args) {

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 32 of 86


try {
InetAddress[] addresses = InetAddress.getAllByName("www.google.com");
for (InetAddress address : addresses) {
System.out.println("IP Address: " + address.getHostAddress());
}
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
Output (Example):

IP Address: 142.250.190.36
IP Address: 142.250.190.37
IP Address: 142.250.190.38

4. Write the function of Connect(), Bind().


Ans. Functions of connect() and bind() in Java Networking

Both connect() and bind() methods are used in socket programming and belong to the Socket and
ServerSocket classes in the java.net package.

1. connect() Method

 The connect() method is used in client-side sockets (Socket class).


 It establishes a connection between a client socket and a server.

Syntax:

public void connect(SocketAddress endpoint) throws IOException


public void connect(SocketAddress endpoint, int timeout) throws IOException

 The endpoint is the address (IP and port) of the server.


 The optional timeout specifies how long to wait before failing the connection attempt.

Example: (Client using connect())

java
CopyEdit
import java.io.*;
import java.net.*;

public class ClientExample {


public static void main(String[] args) {
try {
// Create an unconnected socket
Socket socket = new Socket();

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 33 of 86


// Define the server address and port
InetSocketAddress serverAddress = new InetSocketAddress("localhost", 5000);

// Connect to the server with a timeout of 5 seconds


socket.connect(serverAddress, 5000);

System.out.println("Connected to server!");

// Close the socket


socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

2. bind() Method

 The bind() method is used in server-side sockets (ServerSocket and DatagramSocket classes).
 It binds a socket to a specific IP address and port so it can listen for incoming connections.

Syntax:

public void bind(SocketAddress endpoint) throws IOException

 endpoint is the IP address and port to which the server socket will be bound.

Example: (Server using bind())

import java.io.*;
import java.net.*;

public class ServerExample {


public static void main(String[] args) {
try {
// Create a server socket without binding
ServerSocket serverSocket = new ServerSocket();

// Define the IP and port to bind


InetSocketAddress address = new InetSocketAddress("localhost", 5000);

// Bind the socket to the specified address and port


serverSocket.bind(address);

System.out.println("Server is listening on port 5000...");

// Accept client connections

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 34 of 86


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

// Close the sockets


socket.close();
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
5. Name the package in which URL class is defined.
Ans. The URL class is defined in the java.net package.

Declaration:

package java.net;
public class URL { ... }

The URL class is used to represent a Uniform Resource Locator (URL) and provides methods to
access and manipulate URLs.
6. Write the use of openConnection() method of URLConnection class.
Ans. Use of openConnection() Method in URLConnection Class

The openConnection() method is used to establish a connection between a Java application and a
resource (such as a webpage, file, or API) specified by a URL.

Syntax:

public URLConnection openConnection() throws IOException

 This method returns a URLConnection object, which can be used to interact with the
resource.
 It does not establish a connection immediately; the connection is established only when you
read from or write to the connection.

Example: Fetching Data from a Website

import java.io.*;
import java.net.*;

public class URLConnectionExample {


public static void main(String[] args) {
try {
// Create a URL object
URL url = new URL("https://www.example.com");

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 35 of 86


// Open a connection to the URL
URLConnection connection = url.openConnection();

// Read data from the URL


BufferedReader reader = new BufferedReader(new
InputStreamReader(connection.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}

// Close the reader


reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Key Features of openConnection():


✔ Opens a connection to a specified URL.
✔ Supports both HTTP and non-HTTP URLs.
✔ Can be used to read from or write to a resource.
✔ Does not immediately establish a connection (it happens when reading/writing starts).
7. Write a program using URL class to retrieve the host, protocol, port and file of URL
http://www.msbte.org.in
Ans. import java.net.*;

public class URLDetails {


public static void main(String[] args) {
try {
// Create a URL object
URL url = new URL("http://www.msbte.org.in");

// Retrieve and display URL components


System.out.println("Protocol: " + url.getProtocol());
System.out.println("Host: " + url.getHost());
System.out.println("Port: " + url.getPort()); // Returns -1 if no port is specified
System.out.println("File: " + url.getFile()); // Returns empty if no file is specified
System.out.println("Default Port: " + url.getDefaultPort()); // Default HTTP port (80)
}
catch (MalformedURLException e)
{
System.out.println("Invalid URL: " + e.getMessage());
}
}
}

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 36 of 86


Expected Output:

Protocol: http
Host: www.msbte.org.in
Port: -1
File:
Default Port: 80

Explanation:

 getProtocol() → Returns http as the protocol.


 getHost() → Returns www.msbte.org.in as the host.
 getPort() → Returns -1 (since no port is specified in the URL).
 getFile() → Returns an empty string (no specific file is provided).
 getDefaultPort() → Returns 80 (default port for HTTP).

8. Develop a program using InetAddress class to retrieve IP address of computer


when hostname is entered by the user.
Ans. import java.net.*;
import java.util.Scanner;

public class IPAddressFinder {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Ask user for a hostname


System.out.print("Enter a hostname: ");
String hostname = scanner.nextLine();

try {
// Get InetAddress object for the given hostname
InetAddress address = InetAddress.getByName(hostname);

// Display the IP address


System.out.println("IP Address of " + hostname + ": " + address.getHostAddress());
} catch (UnknownHostException e) {
System.out.println("Host not found: " + e.getMessage());
} finally {
scanner.close();
}
}
}
Example Run:
Input:
Enter a hostname: www.google.com
Output:
IP Address of www.google.com: 142.250.190.78

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 37 of 86


Explanation:

✔ Scanner class is used to take hostname input from the user.


✔ InetAddress.getByName(hostname) retrieves the IP address of the entered hostname.
✔ getHostAddress() extracts and displays the IP address.
✔ Handles exceptions in case the hostname is invalid or unreachable.

9. Write the difference between SeverSocket and DatagramPacket.


Ans. Difference Between ServerSocket and DatagramPacket

Both ServerSocket and DatagramPacket classes are part of Java's java.net package and are used for
network communication, but they work differently.

Feature ServerSocket DatagramPacket


Communication
Connection-oriented (TCP) Connectionless (UDP)
Type
Used for server-side communication Used to send and receive datagram
Class Type
in TCP. packets in UDP.
Provides reliable communication
Unreliable, as data can be lost or arrive out
Reliability (ensures data delivery, order, and
of order.
integrity).
Data Transfer Stream-based (continuous flow of Packet-based (data sent in discrete
Mode data). chunks).
Ensures data is received using
No acknowledgments, leading to faster but
Acknowledgment acknowledgments and
unreliable communication.
retransmissions.
Higher latency due to connection Lower latency as there is no connection
Latency
establishment and error checking. setup.
Used in applications requiring Used in applications where speed matters
reliable data transmission, such as more than reliability, such as video
Usage
web servers, file transfers, and streaming, online gaming, and real-time
messaging apps. communication.

Example Usage:

1. ServerSocket Example (TCP Server)

import java.io.*;
import java.net.*;

public class TCPServer {


public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(5000);

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 38 of 86


System.out.println("TCP Server is listening on port 5000...");

Socket socket = serverSocket.accept();


System.out.println("Client connected!");

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


System.out.println("Received: " + reader.readLine());

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

2. DatagramPacket Example (UDP Server)

import java.net.*;

public class UDPServer {


public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket(5000);
byte[] buffer = new byte[1024];

DatagramPacket packet = new DatagramPacket(buffer, buffer.length);


System.out.println("UDP Server is waiting for packets...");

socket.receive(packet);
String receivedData = new String(packet.getData(), 0, packet.getLength());
System.out.println("Received: " + receivedData);

socket.close();
}
}

Conclusion:

 Use ServerSocket for reliable, connection-oriented communication (TCP).


 Use DatagramPacket for faster, connectionless communication (UDP).

10. Explain URL class with example.


Ans. URL Class in Java:

The URL (Uniform Resource Locator) class in Java is part of the java.net package and is used to
represent a web address (such as websites, files, and network resources). It allows Java programs to
access and manipulate URLs.

1. Declaration of URL Class

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 39 of 86


The URL class is declared as:

public final class URL extends Object implements Serializable


Since URL is a final class, it cannot be extended.

2. Creating a URL Object:

A URL object is created using its constructor:


URL url = new URL("https://www.example.com");
It throws a MalformedURLException if the URL is incorrect.

3. Important Methods in URL Class


Method Description
getProtocol() Returns the protocol used (e.g., http, https, ftp).
getHost() Returns the host name (e.g., www.example.com).
getPort() Returns the port number (-1 if no port is specified).
getFile() Returns the file name or resource after the domain.
getPath() Returns the path of the URL (excluding query parameters).
getQuery() Returns the query string in the URL.
openStream() Opens a connection and returns an InputStream to read from the URL.

4. Example Program: Extracting URL Components

import java.net.*;

public class URLExample {


public static void main(String[] args) {
try {
// Creating a URL object
URL url = new URL("https://www.example.com:8080/index.html?user=abc");

// Display URL details


System.out.println("Protocol: " + url.getProtocol()); // https
System.out.println("Host: " + url.getHost()); // www.example.com
System.out.println("Port: " + url.getPort()); // 8080
System.out.println("File: " + url.getFile()); // /index.html?user=abc
System.out.println("Path: " + url.getPath()); // /index.html
System.out.println("Query: " + url.getQuery()); // user=abc

} catch (MalformedURLException e) {
System.out.println("Invalid URL: " + e.getMessage());
}
}
}

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 40 of 86


5. Example Output:

Protocol: https
Host: www.example.com
Port: 8080
File: /index.html?user=abc
Path: /index.html
Query: user=abc

6. Example: Reading Data from a URL

This program fetches the HTML content of a webpage using the openStream() method.

import java.io.*;
import java.net.*;

public class URLReaderExample {


public static void main(String[] args) {
try {
// Create a URL object
URL url = new URL("https://www.example.com");

// Open a stream to read data from the URL


BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
String line;

while ((line = reader.readLine()) != null) {


System.out.println(line);
}

// Close the reader


reader.close();
} catch (IOException e) {
System.out.println("Error reading URL: " + e.getMessage());
}
}
}

7. Summary

 The URL class is used to represent web addresses.


 Provides methods to extract protocol, host, port, file, path, and query parameters.
 Can be used to fetch data from the web.

11. Explain URLConnection class method (any 4).

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 41 of 86


Ans. URLConnection Class in Java

The URLConnection class in Java is part of the java.net package and is used to establish a connection
between a Java application and a resource (such as a web page, file, or API) specified by a URL.

1. Declaration of URLConnection Class

public abstract class URLConnection extends Object

Since it is an abstract class, it cannot be instantiated directly. Instead, an instance is obtained using
the openConnection( ) method of the URL class.

2. How to Establish a URL Connection

Steps to Use URLConnection


1. Create a URL object.
2. Use openConnection() to get a URLConnection object.
3. Configure the connection if needed (e.g., set request properties).
4. Read or write data using the connection.

3. Important Methods of URLConnection Class


Method Description
connect() Establishes a connection to the URL.
getInputStream() Returns an input stream to read data from the URL.
getOutputStream() Returns an output stream to write data to the URL.
Returns the content type (e.g., text/html,
getContentType()
application/json).
getContentLength() Returns the length of the content in bytes.
getContentEncoding() Returns the encoding of the content (e.g., gzip).
setDoOutput(true/false) Enables or disables output (used for POST requests).
setRequestProperty(String key, String
Sets a request header (e.g., User-Agent).
value)
getHeaderField(String name) Retrieves a specific response header.
getDate() Returns the date when the resource was last modified.

4. Example: Reading Data from a URL using URLConnection

This program fetches and prints the HTML content of a webpage.

import java.io.*;
import java.net.*;

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 42 of 86


public class URLConnectionExample {
public static void main(String[] args) {
try {
// Create a URL object
URL url = new URL("https://www.example.com");

// Open a connection to the URL


URLConnection connection = url.openConnection();

// Get an input stream to read data


BufferedReader reader = new BufferedReader(new
InputStreamReader(connection.getInputStream()));

String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}

// Close the reader


reader.close();
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
}

Example Output (HTML Content of www.example.com)

<!DOCTYPE html>
<html>
<head><title>Example Domain</title></head>
<body><h1>Example Domain</h1></body>
</html>

5. Example: Sending Data using HttpURLConnection (POST Request)

To send data to a server, we use HttpURLConnection, a subclass of URLConnection.

import java.io.*;
import java.net.*;

public class HttpPostExample {


public static void main(String[] args) {
try {
// URL to send data
URL url = new URL("https://postman-echo.com/post");

// Open connection

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 43 of 86


HttpURLConnection connection = (HttpURLConnection) url.openConnection();

// Set request method to POST


connection.setRequestMethod("POST");

// Enable output to send data


connection.setDoOutput(true);

// Write data to request body


OutputStream os = connection.getOutputStream();
os.write("message=HelloServer".getBytes());
os.flush();
os.close();

// Read response
BufferedReader reader = new BufferedReader(new
InputStreamReader(connection.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}

reader.close();
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
}

Example Output (JSON Response)

{
"args": {},
"data": "",
"files": {},
"form": {
"message": "HelloServer"
}
}

6. Summary

 URLConnection is used for fetching data from the web or sending data to servers.
 Supports both GET and POST methods (for HTTP requests).
 Provides methods to set request headers and get response details.

12. Explain URL class Constructor (any 4).


Ans. URL Class Constructors in Java

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 44 of 86


The URL (Uniform Resource Locator) class in Java is used to represent web addresses and network
resources. It provides constructors to create a URL object in different ways.

1. Constructors of URL Class

Java provides four constructors to create a URL object.


Constructor Description
Creates a URL from a string representation (e.g.,
URL(String spec)
"https://www.example.com").
URL(String protocol, String host, int Creates a URL with a specified protocol, host, port, and file
port, String file) path.
URL(String protocol, String host, Similar to the above but uses the default port for the
String file) protocol.
URL(URL context, String spec) Creates a URL by resolving it relative to a base URL.

2. Example of Each Constructor

(1) URL(String spec) – Creating a URL from a String

import java.net.*;

public class URLExample1 {


public static void main(String[] args) {
try {
URL url = new URL("https://www.example.com/index.html");
System.out.println("URL: " + url);
} catch (MalformedURLException e) {
System.out.println("Invalid URL: " + e.getMessage());
}
}
}

✔ Output:

URL: https://www.example.com/index.html

(2) URL(String protocol, String host, int port, String file)

This constructor allows specifying the protocol, host, port, and file path.

import java.net.*;

public class URLExample2 {


public static void main(String[] args) {

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 45 of 86


try {
URL url = new URL("https", "www.example.com", 8080, "/index.html");
System.out.println("URL: " + url);
} catch (MalformedURLException e) {
System.out.println("Invalid URL: " + e.getMessage());
}
}
}

✔ Output:

URL: https://www.example.com:8080/index.html

(3) URL(String protocol, String host, String file)

This constructor is similar to the previous one but uses the default port for the specified protocol.

import java.net.*;

public class URLExample3 {


public static void main(String[] args) {
try {
URL url = new URL("https", "www.example.com", "/index.html");
System.out.println("URL: " + url);
} catch (MalformedURLException e) {
System.out.println("Invalid URL: " + e.getMessage());
}
}
}

✔ Output:
URL: https://www.example.com/index.html

👉 The default port for HTTPS is 443, so no port is shown.

(4) URL(URL context, String spec) – Resolving a Relative URL

This constructor creates a relative URL using a base URL.

import java.net.*;

public class URLExample4 {


public static void main(String[] args) {
try {

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 46 of 86


// Base URL
URL baseURL = new URL("https://www.example.com/docs/");

// Relative URL
URL relativeURL = new URL(baseURL, "tutorial.html");

System.out.println("Base URL: " + baseURL);


System.out.println("Resolved URL: " + relativeURL);
} catch (MalformedURLException e) {
System.out.println("Invalid URL: " + e.getMessage());
}
}
}

✔ Output:
Base URL: https://www.example.com/docs/
Resolved URL: https://www.example.com/docs/tutorial.html

3. Handling MalformedURLException

All constructors throw a MalformedURLException if the URL is incorrect.


For example:

URL url = new URL("invalid-url"); // Throws MalformedURLException

4. Summary
Constructor Use Case
URL(String spec) Create URL from a string.
URL(String protocol, String host, int port, String file) Create URL with a custom port.
URL(String protocol, String host, String file) Create URL with the default port.
URL(URL context, String spec) Create URL relative to a base URL.
13. Explain Factory method of InetAddress class.
Ans. Factory Methods of InetAddress Class in Java

The InetAddress class in Java (part of java.net package) is used to represent IP addresses (both IPv4
and IPv6). Since InetAddress does not have public constructors, it provides factory methods to
create instances.

1. What is a Factory Method?

A factory method is a static method that returns an instance of a class, instead of calling a constructor
directly.

2. Factory Methods in InetAddress Class

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 47 of 86


Factory Method Description
Returns an InetAddress object for a single IP address of the
getByName(String host)
given hostname.
Returns an array of InetAddress objects for all IP addresses of
getAllByName(String host)
the given hostname.
getLocalHost() Returns the InetAddress object for the local computer.
Returns an InetAddress object for the specified IP address (in
getByAddress(byte[] addr)
byte array form).
getByAddress(String host, byte[] Returns an InetAddress object for a given hostname and IP
addr) address.

3. Example Usage of Each Factory Method

(1) getByName(String host) – Get IP Address of a Hostname

This method returns a single IP address of a given hostname.

import java.net.*;

public class InetAddressExample1 {


public static void main(String[] args) {
try {
InetAddress address = InetAddress.getByName("www.google.com");
System.out.println("IP Address: " + address.getHostAddress());
} catch (UnknownHostException e) {
System.out.println("Host not found: " + e.getMessage());
}
}
}

✔ Example Output:
IP Address: 142.250.190.78

(2) getAllByName(String host) – Get All IP Addresses of a Hostname

This method returns all IP addresses associated with a hostname.

import java.net.*;

public class InetAddressExample2 {


public static void main(String[] args) {
try {
InetAddress[] addresses = InetAddress.getAllByName("www.google.com");

for (InetAddress address : addresses) {

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 48 of 86


System.out.println("IP Address: " + address.getHostAddress());
}
} catch (UnknownHostException e) {
System.out.println("Host not found: " + e.getMessage());
}
}
}

✔ Example Output:

IP Address: 142.250.190.78
IP Address: 142.250.190.79
IP Address: 142.250.190.80

(3) getLocalHost() – Get Local Machine's IP Address

This method returns the IP address of the computer running the program.

import java.net.*;

public class InetAddressExample3 {


public static void main(String[] args) {
try {
InetAddress localAddress = InetAddress.getLocalHost();
System.out.println("Local Hostname: " + localAddress.getHostName());
System.out.println("Local IP Address: " + localAddress.getHostAddress());
} catch (UnknownHostException e) {
System.out.println("Could not determine local host: " + e.getMessage());
}
}
}

✔ Example Output:
Local Hostname: MyComputer
Local IP Address: 192.168.1.5

(4) getByAddress(byte[] addr) – Get IP Address from Byte Array

This method creates an InetAddress object from a byte array representing an IP address.

import java.net.*;

public class InetAddressExample4 {


public static void main(String[] args) {
try {
byte[] ip = { 8, 8, 8, 8 }; // Google's public DNS (8.8.8.8)

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 49 of 86


InetAddress address = InetAddress.getByAddress(ip);
System.out.println("IP Address: " + address.getHostAddress());
} catch (UnknownHostException e) {
System.out.println("Invalid address: " + e.getMessage());
}
}
}

✔ Output:
IP Address: 8.8.8.8

(5) getByAddress(String host, byte[] addr) – Get IP Address with Hostname

This method associates a hostname with an IP address.

import java.net.*;

public class InetAddressExample5 {


public static void main(String[] args) {
try {
byte[] ip = { 8, 8, 8, 8 }; // Google's public DNS
InetAddress address = InetAddress.getByAddress("google-dns", ip);
System.out.println("Hostname: " + address.getHostName());
System.out.println("IP Address: " + address.getHostAddress());
} catch (UnknownHostException e) {
System.out.println("Invalid address: " + e.getMessage());
}
}
}

✔ Output:

Hostname: google-dns
IP Address: 8.8.8.8

4. Summary of Factory Methods


Method Returns Example Usage
Single InetAddress for a given
getByName(String host) Find IP address of www.google.com
hostname
Array of InetAddress for a Get multiple IP addresses of
getAllByName(String host)
hostname www.google.com
IP address of the local
getLocalHost() Find the IP of your machine
computer
getByAddress(byte[] addr) IP address from a byte array Convert {8,8,8,8} to 8.8.8.8
getByAddress(String host, byte[] IP with a custom hostname Assign "google-dns" to 8.8.8.8

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 50 of 86


addr)
14. Explain Instance Method s of InetAddress class.
Ans. Instance Methods of InetAddress Class in Java

The InetAddress class in Java provides several instance methods to retrieve information about an IP
address or hostname. These methods are used after an InetAddress object is created using a factory
method like getByName(), getAllByName(), or getLocalHost().

1. Important Instance Methods of InetAddress Class


Return
Method Description
Type
getHostName() String Returns the hostname of the IP address.
getHostAddress() String Returns the IP address as a string.
getCanonicalHostName() String Returns the fully qualified domain name (FQDN).
Checks if the IP address is reachable within a given timeout
isReachable(int timeout) boolean
(milliseconds).
equals(Object obj) boolean Compares two InetAddress objects.
hashCode() int Returns a hash code for the IP address.
toString() String Returns a string representation of the InetAddress object.

2. Example Usage of Each Method

(1) getHostName() – Get the Hostname

This method returns the hostname associated with an InetAddress object.

import java.net.*;

public class InetAddressExample1 {


public static void main(String[] args) {
try {
InetAddress address = InetAddress.getByName("8.8.8.8"); // Google's public DNS
System.out.println("Hostname: " + address.getHostName());
} catch (UnknownHostException e) {
System.out.println("Host not found: " + e.getMessage());
}
}
}

✔ Example Output:

Hostname: dns.google.

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 51 of 86


(2) getHostAddress() – Get the IP Address

This method returns the IP address in string format.

import java.net.*;

public class InetAddressExample2 {


public static void main(String[] args) {
try {
InetAddress address = InetAddress.getByName("www.google.com");
System.out.println("IP Address: " + address.getHostAddress());
} catch (UnknownHostException e) {
System.out.println("Host not found: " + e.getMessage());
}
}
}

✔ Example Output:

IP Address: 142.250.190.78

(3) getCanonicalHostName() – Get Fully Qualified Domain Name (FQDN)

This method returns the canonical (official) hostname.

import java.net.*;

public class InetAddressExample3 {


public static void main(String[] args) {
try {
InetAddress address = InetAddress.getByName("www.google.com");
System.out.println("Canonical Hostname: " + address.getCanonicalHostName());
} catch (UnknownHostException e) {
System.out.println("Host not found: " + e.getMessage());
}
}
}

✔ Example Output:

Canonical Hostname: bom12s07-in-f14.1e100.net

👉 This is useful for getting the official domain name mapped to an IP.

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 52 of 86


(4) isReachable(int timeout) – Check if IP is Reachable

This method checks whether an IP address is reachable within a timeout (in milliseconds).

import java.net.*;

public class InetAddressExample4 {


public static void main(String[] args) {
try {
InetAddress address = InetAddress.getByName("www.google.com");

if (address.isReachable(5000)) { // Timeout = 5000ms (5 seconds)


System.out.println(address.getHostName() + " is reachable.");
} else {
System.out.println(address.getHostName() + " is not reachable.");
}
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}

✔ Example Output:

www.google.com is reachable.

👉 The method sends a ping request to check if the host is active.

(5) equals(Object obj) – Compare Two InetAddress Objects

This method checks if two InetAddress objects represent.

The same IP address.import java.net.*;

public class InetAddressExample5 {


public static void main(String[] args) {
try {
InetAddress address1 = InetAddress.getByName("www.google.com");
InetAddress address2 = InetAddress.getByName("142.250.190.78"); // Google's IP

if (address1.equals(address2)) {
System.out.println("Both addresses are the same.");
} else {
System.out.println("Addresses are different.");

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 53 of 86


}
} catch (UnknownHostException e) {
System.out.println("Error: " + e.getMessage());
}
}
}

✔ Example Output:

Both addresses are the same.

👉 This method is useful for IP comparisons.

(6) hashCode() – Get a Unique Hash Code for an IP

This method returns a unique integer hash code for an IP address.

import java.net.*;

public class InetAddressExample6 {


public static void main(String[] args) {
try {
InetAddress address = InetAddress.getByName("www.google.com");
System.out.println("Hash Code: " + address.hashCode());
} catch (UnknownHostException e) {
System.out.println("Error: " + e.getMessage());
}
}
}

✔ Example Output:

Hash Code: 1349381091

👉 This is useful for storing IPs in hash-based data structures.

(7) toString() – Convert InetAddress to String

This method returns a string representation of the InetAddress object.

import java.net.*;

public class InetAddressExample7 {


public static void main(String[] args) {

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 54 of 86


try {
InetAddress address = InetAddress.getByName("www.google.com");
System.out.println("InetAddress toString(): " + address.toString());
} catch (UnknownHostException e) {
System.out.println("Error: " + e.getMessage());
}
}
}

✔ Example Output:

InetAddress toString(): www.google.com/142.250.190.78

👉 This method combines both the hostname and IP address.

3. Summary of Instance Methods


Method Description Example Output
getHostName() Returns hostname of IP dns.google
getHostAddress() Returns IP as a string 142.250.190.78
getCanonicalHostName() Returns FQDN bom12s07-in-f14.1e100.net
isReachable(int timeout) Checks if IP is reachable true
equals(Object obj) Compares two IPs true
hashCode() Returns hash code for IP 1349381091
toString() Returns IP & hostname www.google.com/142.250.190.78

Conclusion

 The instance methods of InetAddress help retrieve network information, resolve hostnames,
and check connectivity.
 These methods are useful for DNS lookups, network monitoring, and host verification.
 They work with both IPv4 and IPv6 addresses.

15. Write a program using Socket and ServerSocket to create Chat Application.
Ans. Here's a simple Chat Application using Java Sockets and ServerSocket. This program consists of
two parts:

1. Server (ChatServer.java) – Listens for incoming connections and communicates with the
client.
2. Client (ChatClient.java) – Connects to the server and enables chatting.

1. Server Code (ChatServer.java)

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 55 of 86


The server listens on a port (e.g., 5000) and waits for a client to connect. Once connected, both can
send and receive messages.

import java.io.*;
import java.net.*;

public class ChatServer {


public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(5000); // Create server socket on port 5000
System.out.println ("Server is running... Waiting for client connection...");

Socket socket = serverSocket.accept(); // Accept client connection


System.out.println ("Client connected!");

// Input and Output Streams


BufferedReader reader = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
BufferedReader consoleReader = new BufferedReader(new InputStreamReader(System.in));

// Chat loop
String message;
while (true) {
message = reader.readLine(); // Receive message from client
if (message.equalsIgnoreCase("exit")) break;
System.out.println("Client: " + message);

System.out.print("Server: ");
String reply = consoleReader.readLine(); // Read reply from server console
writer.println(reply); // Send reply to client
}

// Close resources
socket.close();
serverSocket.close();
System.out.println ("Chat closed.");
} catch (IOException e) {
e.printStackTrace();
}
}
}

2. Client Code (ChatClient.java)

The client connects to the server's IP address and port (5000) and enables two-way communication.

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 56 of 86


import java.io.*;
import java.net.*;

public class ChatClient {


public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 5000); // Connect to server on localhost and port 5000
System.out.println("Connected to server!");

// Input and Output Streams


BufferedReader reader = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
BufferedReader consoleReader = new BufferedReader(new InputStreamReader(System.in));

// Chat loop
String message;
while (true) {
System.out.print("Client: ");
String sendMessage = consoleReader.readLine(); // Read user input
writer.println(sendMessage); // Send message to server

if (sendMessage.equalsIgnoreCase("exit")) break;

message = reader.readLine(); // Receive message from server


System.out.println("Server: " + message);
}

// Close resources
socket.close();
System.out.println("Chat closed.");
} catch (IOException e) {
e.printStackTrace();
}
}
}

3. How to Run the Program

Step 1: Start the Server

 Compile and run ChatServer.java first.


 The server will wait for a client connection.

Step 2: Start the Client

 Compile and run ChatClient.java.

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 57 of 86


 The client will connect to the server.

Step 3: Chat!

 Type messages in either the server or client console, and press Enter.
 To exit, type "exit" in either console.

4. Example Output

Server Console
Server is running... Waiting for client connection...
Client connected!
Client: Hello Server!
Server: Hi Client!
Client: How are you?
Server: I am good. You?
Client: exit
Chat closed.

Client Console
Connected to server!
Client: Hello Server!
Server: Hi Client!
Client: How are you?
Server: I am good. You?
Client: exit
Chat closed.

5. Explanation of Code

Server (ChatServer.java)
 Creates a ServerSocket on port 5000.
 Waits for client connection (accept()).
 Reads messages from client and responds.

Client (ChatClient.java)
 Connects to localhost:5000 (new Socket()).
 Sends messages to the server.
 Receives and displays server replies.

6. Features & Enhancements

✅ Bi-directional chat (both server & client can send messages).


✅ Exit command (exit to close chat).
✅ Simple implementation using BufferedReader & PrintWriter.

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 58 of 86


Q. VI. Interacting with Database
No.
1. Name the Types of drivers for data base connectivity.
Ans. There are several types of database connectivity drivers, each designed to enable communication
between an application and a database. Here are the main types:

1. ODBC (Open Database Connectivity) Driver:


o A standard API for accessing database management systems (DBMS).
o Allows applications to connect to any DBMS that supports ODBC.
2. JDBC (Java Database Connectivity) Driver:
o Used for Java applications to connect to databases.
o JDBC drivers are available in four types:
 Type 1: JDBC-ODBC Bridge Driver (uses ODBC to connect to the database).
 Type 2: Native-API Driver (uses database-specific native libraries).
 Type 3: Network Protocol Driver (uses a middleware server to communicate
with the database).
 Type 4: Thin Driver (communicates directly with the database over TCP/IP).
3. OLE DB (Object Linking and Embedding, Database) Driver:
o A set of interfaces that allow applications to connect to different types of data sources
(not just relational databases).
o More flexible and feature-rich than ODBC.
4. ADO.NET (ActiveX Data Objects for .NET):
o A data access framework for .NET applications.
o Provides connectivity for a variety of databases, including SQL Server and Oracle.
5. Native Database Driver:
o These are database-specific drivers optimized for a particular DBMS (e.g., MySQL
Connector, Oracle Call Interface (OCI), or PostgreSQL JDBC Driver).
o Typically faster and more efficient for the specific database.

These drivers differ in terms of their architecture, ease of use, performance, and the level of abstraction
they provide between the application and the database.
2. Write the use of Class.forName()
Ans. The Class.forName() method in Java is used to dynamically load a class at runtime. This method is
typically used when you need to load a class by its name (as a string) rather than at compile time,
allowing for flexibility in applications like database connectivity or other situations where classes need
to be loaded dynamically.

Key Uses of Class.forName():

1. Loading JDBC Drivers: In database connectivity, Class.forName() is used to load the JDBC
driver class dynamically. This allows the Java application to establish a connection to the
database without explicitly importing the driver class.

For example:

try {
// Load the JDBC driver for MySQL database
Class.forName("com.mysql.cj.jdbc.Driver");

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 59 of 86


// Establish a connection (assuming you have a valid database URL, user, and password)
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase",
"username", "password");
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}

In this example, Class.forName("com.mysql.cj.jdbc.Driver") loads the MySQL JDBC driver at


runtime. Without this step, the application wouldn't know how to communicate with the
MySQL database.

2. Dynamic Class Loading:


o Class.forName() allows dynamic loading of classes based on conditions that may not be
known until runtime. For example, you may load a different class based on user input, a
configuration file, or the environment.
o It can be used for reflection, where you instantiate a class or invoke methods
dynamically using the Class object obtained from forName().
3. Reflection:
o The Class.forName() method returns a Class object that can be used to reflectively
inspect the class and invoke methods, access fields, and perform other reflection
operations.

For example:

try {
// Dynamically load a class using Class.forName
Class<?> cls = Class.forName("com.example.MyClass");

// Create an instance of the class


Object obj = cls.getDeclaredConstructor().newInstance();

// You can use reflection to call methods or access fields dynamically


} catch (Exception e) {
e.printStackTrace();
}

Key Points:

 Class.forName() is particularly useful for loading classes that are not known until runtime.
 It is often used in situations like database connections (e.g., JDBC drivers) where you might not
know the exact database or driver class until runtime.
 Class.forName() triggers the class loading mechanism in Java, causing the class to be loaded
and initialized.
3 List Advantages JDBC over ODBC.
Ans. DBC (Java Database Connectivity) and ODBC (Open Database Connectivity) are both technologies
used to connect applications to databases, but JDBC offers several advantages over ODBC, particularly

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 60 of 86


in the context of Java applications. Below are the key advantages of JDBC over ODBC:

1. Platform Independence:

 JDBC is designed specifically for Java applications, allowing it to work seamlessly across
different platforms. Java is a platform-independent language, and JDBC leverages this
characteristic to ensure that database connectivity is the same regardless of the underlying
operating system.
 ODBC, on the other hand, is not platform-independent. It works on specific platforms and
requires platform-specific drivers (like the ODBC driver for Windows), which can limit
portability.

2. Simpler Integration with Java:

 JDBC is part of the Java standard library, and it's built into the Java Development Kit (JDK). It
provides a native and integrated way to access databases from Java applications, making it
straightforward to implement.
 ODBC is a general database connectivity API and requires an additional ODBC driver
manager, making the integration with Java more complex. Java developers need to use the
JDBC-ODBC bridge (which is deprecated in modern Java versions) to use ODBC, adding an
extra layer of complexity.

3. Direct Database Access:

 JDBC provides a direct connection to databases, including a simple API for interacting with
SQL databases. With JDBC, developers can directly access and manipulate databases using
SQL commands from Java code.
 ODBC relies on a middleware layer (ODBC driver manager), which can introduce extra
overhead and complexity in terms of performance and configuration.

4. No Need for a Middleware Layer:

 JDBC does not require any middleware layer for database connectivity. It communicates
directly with the database driver, leading to better performance and more straightforward setup.
 ODBC often requires an additional ODBC driver manager, which can lead to additional setup,
configuration, and potential performance bottlenecks.

5. Better Integration with Java Features:

 JDBC is built to integrate well with other Java features, such as exception handling (using
SQLException), multithreading, and object-oriented concepts. It follows Java's conventions,
making it more cohesive and easier to work with.
 ODBC was designed before the rise of Java and does not integrate as smoothly with Java's
features or object-oriented model.

6. Type Safety:

 JDBC supports Java's type system, making it easier to manage database types and map them to

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 61 of 86


Java types. This allows for more robust and error-free code when working with database data.
 ODBC uses a more generic approach, which can result in mismatched data types and additional
data conversion steps.

7. Flexibility and Extensibility:

 JDBC is highly flexible and can be extended to support different types of databases through
custom drivers. It supports a wide range of database management systems (DBMS), including
relational databases like MySQL, Oracle, PostgreSQL, and others.
 ODBC also supports multiple databases but does not offer the same level of integration and
customization as JDBC, especially in the Java environment.

8. Built-in Support for Connection Pooling:

 JDBC provides support for connection pooling, either through Java EE containers (like
Tomcat, JBoss) or third-party libraries. Connection pooling helps optimize database
connections by reusing connections, improving performance and scalability.
 ODBC does not have native connection pooling support, and managing connection pools
usually requires additional tools or libraries.

9. Rich Ecosystem:

 JDBC has a rich ecosystem of third-party libraries, frameworks, and tools that help simplify
database operations, such as ORM frameworks like Hibernate, Spring JDBC, etc.
 ODBC does not have the same level of ecosystem support within Java, and using it with Java
often requires more manual setup and management.

10. Cross-Database Compatibility:

 JDBC is specifically designed to work well with many different types of relational databases,
providing better cross-database compatibility. Developers can easily switch between databases
without changing much of the Java code, as long as a JDBC driver for the target DB is
available.
 ODBC also works with multiple databases, but it may require additional configuration for
different DBMS systems.
4. Write Advantages and disadvantages of Statements And Prepared Statement
Ans. In Java, both Statement and PreparedStatement are used to execute SQL queries against a database.
However, they differ in their functionality, performance, and use cases. Below are the advantages and
disadvantages of each:

Statement

Advantages of Statement:

1. Simple to Use:
o The Statement object is easier to use and ideal for executing simple SQL queries that
don’t involve user input or variable data.
o It’s best suited for static queries that don't need to be parameterized.

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 62 of 86


2. Quick Setup:
o For a single, static query, Statement can be set up quickly without the need for
preparing or binding parameters.
3. No Need for Parameterization:
o When you don't need to pass parameters dynamically to your queries, a Statement can
be the easiest and most straightforward way to execute SQL statements.

Disadvantages of Statement:

1. Vulnerable to SQL Injection:


o One of the biggest drawbacks is the risk of SQL injection attacks. Since the SQL query
is created by concatenating strings, it’s vulnerable to malicious user input if not properly
validated or sanitized.
o Example:

String query = "SELECT * FROM users WHERE username = '" + username + "' AND
password = '" + password + "'";

This can allow an attacker to inject harmful SQL code into the query.

2. Performance:
o Statement does not benefit from query caching, as the SQL query is sent to the database
server every time it is executed. If the same query is executed repeatedly, performance
can suffer because it is parsed and compiled by the database each time.
o There is no optimization for repeated queries.
3. No Reusability:
o Each time a Statement is used, it is compiled and executed. This makes it less efficient
for repeated executions of the same query.

PreparedStatement

Advantages of PreparedStatement:

1. Precompilation:
o PreparedStatement allows the SQL query to be precompiled by the database when the
query is created, which can improve performance when the same query is executed
multiple times with different parameters.
o This precompilation reduces the overhead of SQL query parsing, leading to faster
execution for repeated queries.
2. Prevention of SQL Injection:
o PreparedStatement helps prevent SQL injection attacks by using parameterized
queries. Parameters are bound to the query at runtime, which means user input is never
directly concatenated into the SQL string.
o Example:

String query = "SELECT * FROM users WHERE username = ? AND password = ?";

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 63 of 86


PreparedStatement pstmt = con.prepareStatement(query);
pstmt.setString(1, username);
pstmt.setString(2, password);

The input is treated as data, not as part of the SQL query.

3. Improved Performance for Repeated Queries:


o PreparedStatement allows the same SQL query to be executed multiple times with
different parameters. The query is parsed and compiled once, and then reused, which
significantly improves performance when the same query is executed frequently.
4. Automatic Handling of Data Types:
o PreparedStatement automatically handles different data types (like strings, integers,
dates) when setting parameters, eliminating the need for manual type conversions.
5. Easier to Maintain:
o Code using PreparedStatement is often easier to maintain and less error-prone because
the query is cleaner and parameters are handled in a type-safe manner.

Disadvantages of PreparedStatement:

1. More Complex Setup:


o PreparedStatement can be more complex to set up compared to a simple Statement,
especially when dealing with dynamic queries that involve multiple parameters. You
need to bind each parameter to a placeholder using setXXX() methods.
2. Less Flexibility for Dynamic Queries:
o While PreparedStatement is great for queries with fixed SQL structure but dynamic
data, it may be less flexible for highly dynamic queries where the entire SQL query
changes based on conditions or user input. You would need to modify the query string
itself or use conditional logic, which can reduce the advantages of prepared statements.
3. Memory Usage:
o PreparedStatement objects may use more memory, as the database needs to keep the
precompiled query in memory. This overhead can be a concern if many different
prepared statements are used simultaneously in large-scale applications.

Comparison Summary:

Feature Statement PreparedStatement


SQL No precompilation; query is Precompiled, improving performance on
Precompilation compiled every time repeated use
Prevents SQL injection by using
Security Vulnerable to SQL injection
parameterized queries
Slower for repeated execution of Faster for repeated execution (due to
Performance
the same query precompilation)
More complex setup for parameterized
Ease of Use Simpler for static queries
queries

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 64 of 86


Highly reusable for repeated execution with
Reusability Not reusable for repeated queries
different parameters
Manual data handling and
Data Handling Automatic handling of data types
conversion required

When to Use:
 Statement: Best for one-off, simple queries that don’t require parameters or are executed only
once.
 PreparedStatement: Ideal for executing SQL queries multiple times with different parameters,
and for scenarios where security and performance are important.

5. List steps for database connectivity


Ans. Steps for Database Connectivity in Java (Using JDBC)

JDBC (Java Database Connectivity) allows Java applications to interact with databases. Below are the
steps to establish a database connection in Java:

1. Load the JDBC Driver

 Ensure that the JDBC driver for your database (e.g., MySQL, PostgreSQL, Oracle) is available
in your project.
 Example for MySQL:

Class.forName("com.mysql.cj.jdbc.Driver");

 This step is optional for JDBC 4.0+ as DriverManager automatically loads the driver.

2. Establish a Connection

 Use DriverManager.getConnection() to connect to the database.


 Example:

Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase",


"root", "password");

3. Create a Statement or PreparedStatement

 Use a Statement for simple queries:

Statement stmt = conn.createStatement();

 Use a PreparedStatement for parameterized queries:


PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM users WHERE id = ?");
pstmt.setInt(1, 1);

4. Execute SQL Queries

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 65 of 86


 For SELECT queries:

ResultSet rs = stmt.executeQuery("SELECT * FROM users");


while (rs.next()) {
System.out.println("User ID: " + rs.getInt("id") + ", Name: " + rs.getString("name"));
}

 For INSERT, UPDATE, DELETE:

int rowsAffected = stmt.executeUpdate("INSERT INTO users (name, email) VALUES ('John


Doe', '[email protected]')");

5. Handle Exceptions

 Use try-catch to handle SQL exceptions:

try {
Connection conn= DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase",
"root", "password");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM users");
} catch (SQLException e) {
e.printStackTrace();
}

6. Close Resources

 Always close the ResultSet, Statement, and Connection to free resources:


rs.close();
stmt.close();
conn.close();

Complete Example

import java.sql.*;

public class DatabaseConnection {


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

try {
// Load MySQL JDBC Driver
Class.forName("com.mysql.cj.jdbc.Driver");

// Establish connection
Connection conn = DriverManager.getConnection(url, user, password);

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 66 of 86


// Create statement
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM users");

// Process results
while (rs.next()) {
System.out.println("User ID: " + rs.getInt("id") + ", Name: " + rs.getString("name"));
}

// Close resources
rs.close();
stmt.close();
conn.close();

} catch (Exception e) {
e.printStackTrace();
}
}
}
6. Differentiate between Statement and Prepared Statement Interface
Ans. Difference Between Statement and PreparedStatement in Java (JDBC)

Feature Statement PreparedStatement


Used for executing parameterized SQL
Definition Used for executing static SQL queries
queries
Query Query is compiled and executed every Query is compiled once and executed
Execution time multiple times efficiently
Faster for repeated queries due to pre-
Performance Slower for repeated queries
compilation
SQL Injection High (since queries are concatenated as
Low (parameters are set using placeholders)
Risk strings)
Statement stmt =
PreparedStatement pstmt =
conn.createStatement();
Usage Example conn.prepareStatement("SELECT * FROM
stmt.executeQuery("SELECT * FROM
users WHERE id = ?"); pstmt.setInt(1, 1);
users WHERE id = 1");
Recommended Repeated execution of similar queries,
Single-use queries, DDL commands
For secure transactions
7. Write program to Create a student table in database and insert a record in student table.
Ans. Java Program to Create a student Table and Insert a Record Using JDBC

This program connects to a MySQL database, creates a student table if it doesn’t exist, and inserts a
record into the table.

Steps:

1. Load the JDBC Driver

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 67 of 86


2. Establish a Connection to the MySQL database
3. Create the student Table (if not exists)
4. Insert a Record into the student Table
5. Close the Connection

Java Program

import java.sql.*;

public class StudentDatabase {


public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydatabase"; // Replace 'mydatabase' with your actual
database name
String user = "root"; // Replace with your MySQL username
String password = "password"; // Replace with your MySQL password

Connection conn = null;


Statement stmt = null;
PreparedStatement pstmt = null;

try {
// Load MySQL JDBC Driver
Class.forName("com.mysql.cj.jdbc.Driver");

// Establish connection
conn = DriverManager.getConnection(url, user, password);
stmt = conn.createStatement();

// SQL query to create table if not exists


String createTableSQL = "CREATE TABLE IF NOT EXISTS student ("
+ "id INT AUTO_INCREMENT PRIMARY KEY, "
+ "name VARCHAR(50), "
+ "age INT, "
+ "grade VARCHAR(10))";
stmt.executeUpdate(createTableSQL);
System.out.println("Student table created successfully!");

// SQL query to insert data


String insertSQL = "INSERT INTO student (name, age, grade) VALUES (?, ?, ?)";
pstmt = conn.prepareStatement(insertSQL);
pstmt.setString(1, "John Doe");
pstmt.setInt(2, 20);
pstmt.setString(3, "A");
int rowsInserted = pstmt.executeUpdate();

if (rowsInserted > 0) {
System.out.println("Record inserted successfully!");
}

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 68 of 86


} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (pstmt != null) pstmt.close();
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}

Explanation

1. Load JDBC Driver → Class.forName("com.mysql.cj.jdbc.Driver");


2. Establish Connection → DriverManager.getConnection(url, user, password);
3. Create Table → CREATE TABLE IF NOT EXISTS student
4. Insert Record → Using PreparedStatement to prevent SQL injection.
5. Close Resources → Ensuring all connections are closed.
8. Write program to update record in database.
Ans. Java Program to Update a Record in a Database Using JDBC

This program connects to a MySQL database and updates a record in the student table.

Steps to Update a Record:

1. Load the JDBC Driver


2. Establish a Connection to the MySQL database
3. Write an SQL UPDATE Query
4. Execute the Query Using PreparedStatement
5. Close the Connection

Java Program

import java.sql.*;

public class UpdateStudentRecord {


public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydatabase"; // Replace 'mydatabase' with your actual
database name
String user = "root"; // Replace with your MySQL username
String password = "password"; // Replace with your MySQL password

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 69 of 86


Connection conn = null;
PreparedStatement pstmt = null;

try {
// Load MySQL JDBC Driver
Class.forName("com.mysql.cj.jdbc.Driver");

// Establish connection
conn = DriverManager.getConnection(url, user, password);

// SQL query to update a record


String updateSQL = "UPDATE student SET age = ?, grade = ? WHERE id = ?";
pstmt = conn.prepareStatement(updateSQL);

// Set new values


pstmt.setInt(1, 22); // Update age to 22
pstmt.setString(2, "A+"); // Update grade to A+
pstmt.setInt(3, 1); // Update record where id = 1

// Execute update
int rowsUpdated = pstmt.executeUpdate();

if (rowsUpdated > 0) {
System.out.println("Record updated successfully!");
} else {
System.out.println("No record found with the given ID.");
}

} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (pstmt != null) pstmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}

Explanation

1. Load JDBC Driver → Class.forName("com.mysql.cj.jdbc.Driver");


2. Establish Connection → DriverManager.getConnection(url, user, password);
3. Prepare Update Query → UPDATE student SET age = ?, grade = ? WHERE id = ?
4. Set Values in PreparedStatement:
o pstmt.setInt(1, 22); (New age)

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 70 of 86


o pstmt.setString(2, "A+"); (New grade)
o pstmt.setInt(3, 1); (Target student ID)
5. Execute Update Query → pstmt.executeUpdate();
6. Close Resources → Ensures all database connections are closed properly.
9. Write program to implement delete statement.
Ans. Java Program to Delete a Record from the Database Using JDBC

This program connects to a MySQL database and deletes a record from the student table based on the
id.

Steps to Delete a Record:

1. Load the JDBC Driver


2. Establish a Connection to the database
3. Write an SQL DELETE Query
4. Execute the Query Using PreparedStatement
5. Close the Connection

Java Program

import java.sql.*;

public class DeleteStudentRecord {


public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydatabase"; // Replace 'mydatabase' with your actual
database name
String user = "root"; // Replace with your MySQL username
String password = "password"; // Replace with your MySQL password

Connection conn = null;


PreparedStatement pstmt = null;

try {
// Load MySQL JDBC Driver
Class.forName("com.mysql.cj.jdbc.Driver");

// Establish connection
conn = DriverManager.getConnection(url, user, password);

// SQL query to delete a record


String deleteSQL = "DELETE FROM student WHERE id = ?";
pstmt = conn.prepareStatement(deleteSQL);

// Set the id of the record to delete


pstmt.setInt(1, 1); // Change 1 to the ID of the record you want to delete

// Execute delete query


int rowsDeleted = pstmt.executeUpdate();

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 71 of 86


if (rowsDeleted > 0) {
System.out.println("Record deleted successfully!");
} else {
System.out.println("No record found with the given ID.");
}

} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (pstmt != null) pstmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}

Explanation

Load JDBC Driver → Class.forName("com.mysql.cj.jdbc.Driver");


1.
Establish Connection → DriverManager.getConnection(url, user, password);
2.
Prepare Delete Query → DELETE FROM student WHERE id = ?
3.
4.
Set Values in PreparedStatement:
o pstmt.setInt(1, 1); (Deletes record where id = 1)
5. Execute Delete Query → pstmt.executeUpdate();
6. Close Resources → Ensures all database connections are closed properly.
10. Develop JDBC program to Retrieve Data from table using resultset interface.
Ans. JDBC Program to Retrieve Data from a Table Using ResultSet Interface

This Java program connects to a MySQL database and retrieves data from the student table using the
ResultSet interface.

Steps to Retrieve Data:

1. Load the JDBC Driver


2. Establish a Connection to the database
3. Execute a SELECT Query Using Statement or PreparedStatement
4. Retrieve and Process the Data Using ResultSet
5. Close the Connection

Java Program

import java.sql.*;

public class RetrieveStudentRecords {

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 72 of 86


public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydatabase"; // Replace 'mydatabase' with your actual
database name
String user = "root"; // Replace with your MySQL username
String password = "password"; // Replace with your MySQL password

Connection conn = null;


Statement stmt = null;
ResultSet rs = null;

try {
// Load MySQL JDBC Driver
Class.forName("com.mysql.cj.jdbc.Driver");

// Establish connection
conn = DriverManager.getConnection(url, user, password);

// Create a statement object


stmt = conn.createStatement();

// SQL query to retrieve data


String selectSQL = "SELECT * FROM student";

// Execute query and get result set


rs = stmt.executeQuery(selectSQL);

// Process the result set


System.out.println("Student Records:");
System.out.println("ID | Name | Age | Grade");
System.out.println("----------------------------------");

while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
String grade = rs.getString("grade");

System.out.printf("%-3d | %-10s | %-3d | %-5s%n", id, name, age, grade);


}

} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 73 of 86


e.printStackTrace();
}
}
}
}

Explanation

Load JDBC Driver → Class.forName("com.mysql.cj.jdbc.Driver");


1.
Establish Connection → DriverManager.getConnection(url, user, password);
2.
Create SQL Query → SELECT * FROM student
3.
4.
Execute Query & Retrieve Data Using ResultSet:
o rs.next() moves the cursor to the next row.
o Retrieve data using rs.getInt(), rs.getString(), etc.
5. Display the Data in a Table Format
6. Close Resources → Ensures all database connections are properly closed.
11. Explain Types of ResultSet.
Ans. Types of ResultSet in JDBC

In JDBC, the ResultSet interface provides different types of result sets based on scrollability and
updatability. These types allow flexibility when fetching data from a database.

1. Based on Scrollability

(i) ResultSet.TYPE_FORWARD_ONLY (Default)

 The cursor moves only forward.


 Once a row is processed, you cannot go back.
 Fastest performance.

✅ Example:

Statement stmt=conn.createStatement(ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY);
ResultSet rs = stmt.executeQuery("SELECT * FROM student");
while (rs.next()) {
System.out.println(rs.getString("name"));
}

✅ Best for: Simple retrieval operations where backtracking is not needed.

(ii) ResultSet.TYPE_SCROLL_INSENSITIVE

 Cursor can move both forward and backward.


 Does not reflect database changes made after execution.
 Slightly slower than TYPE_FORWARD_ONLY.

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 74 of 86


✅ Example:

Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,


ResultSet.CONCUR_READ_ONLY);
ResultSet rs = stmt.executeQuery("SELECT * FROM student");

rs.last(); // Move to last row


System.out.println("Last Student: " + rs.getString("name"));

rs.first(); // Move to first row


System.out.println("First Student: " + rs.getString("name"));

✅ Best for: Navigating records when real-time updates are not required.

(iii) ResultSet.TYPE_SCROLL_SENSITIVE

 Cursor can move both forward and backward.


 Reflects changes made to the database after execution.
 Slightly slower than TYPE_SCROLL_INSENSITIVE.

✅ Example:

Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,


ResultSet.CONCUR_READ_ONLY);
ResultSet rs = stmt.executeQuery("SELECT * FROM student");

rs.absolute(2); // Move to the second row


System.out.println("Second Student: " + rs.getString("name"));

✅ Best for: Scenarios where live updates to data should be reflected in the ResultSet.

2. Based on Updatability

(i) ResultSet.CONCUR_READ_ONLY (Default)

 Cannot update records.


 Highest performance.

✅ Example:

Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,


ResultSet.CONCUR_READ_ONLY);
ResultSet rs = stmt.executeQuery("SELECT * FROM student");

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 75 of 86


✅ Best for: Read-only operations.

(ii) ResultSet.CONCUR_UPDATABLE

 Allows modifications to database records.


 Requires a scrollable ResultSet.

✅ Example:

Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,


ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery("SELECT * FROM student");

rs.absolute(1); // Move to first row


rs.updateString("name", "Updated Name");
rs.updateRow(); // Apply changes

✅ Best for: Applications needing real-time updates without executing separate UPDATE queries.

Summary Table
Reflects DB Allows
ResultSet Type Description Navigation
Changes? Updates?
TYPE_FORWARD_ONLY Moves forward only ❌ ❌ ❌
Moves in any direction,
TYPE_SCROLL_INSENSITIVE does not reflect ✅ ❌ ❌
changes
Moves in any direction,
TYPE_SCROLL_SENSITIVE
reflects changes ✅ ✅ ❌

✅ (depends ✅ (depends
CONCUR_READ_ONLY Read-only ResultSet ❌
on type) on type)
Allows updates to ✅ (depends ✅ (depends
CONCUR_UPDATABLE
records ✅
on type) on type)

Which Type to Use?

 For best performance → Use TYPE_FORWARD_ONLY, CONCUR_READ_ONLY.


 For navigation within results → Use TYPE_SCROLL_INSENSITIVE.
 For real-time updates reflection → Use TYPE_SCROLL_SENSITIVE.
 For modifying records directly → Use CONCUR_UPDATABLE.
12. Explain the methods of ResultSet Interface.
Ans.
Methods of ResultSet Interface in JDBC

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 76 of 86


The ResultSet interface provides methods to navigate through query results, retrieve data, and
modify records. Below is a categorized explanation of its important methods.

1. Navigational Methods (Move Cursor)

These methods help move the cursor to different rows.

Method Description
boolean next() Moves to the next row (returns false if no more rows).
boolean previous() Moves to the previous row (only for scrollable ResultSet).
boolean first() Moves to the first row.
boolean last() Moves to the last row.
boolean absolute(int row) Moves cursor to the specified row number.
boolean relative(int rows) Moves forward or backward by the given number of rows.
boolean isBeforeFirst() Returns true if cursor is before the first row.
boolean isAfterLast() Returns true if cursor is after the last row.

✅ Example:
ResultSet rs = stmt.executeQuery("SELECT * FROM student");
rs.last(); // Moves to the last row
System.out.println("Last Student: " + rs.getString("name"));

2. Data Retrieval Methods

These methods fetch values from columns in the ResultSet.

Method Description
int getInt(String columnLabel) Retrieves an integer value.
String getString(String columnLabel) Retrieves a String value.
double getDouble(String columnLabel) Retrieves a double value.
Date getDate(String columnLabel) Retrieves a date value.
boolean getBoolean(String columnLabel) Retrieves a boolean value.
Object getObject(String columnLabel) Retrieves a generic object.

✅ Example:
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
System.out.println("ID: " + id + ", Name: " + name + ", Age: " + age);
}

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 77 of 86


3. Update Methods (Modify Data in ResultSet)

These methods modify data directly in the ResultSet.


Method Description
void updateString(String columnLabel, String value) Updates a String column.
void updateInt(String columnLabel, int value) Updates an int column.
void updateDouble(String columnLabel, double value) Updates a double column.
void updateRow() Saves the updated row into the database.
void deleteRow() Deletes the current row from the database.
void insertRow() Inserts a new row into the database.

✅ Example:

if (rs.next()) {
rs.updateString("name", "Updated Name");
rs.updateInt("age", 25);
rs.updateRow(); // Apply changes to database
}

4. Metadata Methods

These methods provide information about the ResultSet.

Method Description
Returns metadata about the ResultSet (column names, types,
ResultSetMetaData getMetaData()
etc.).
int getRow() Returns the current row number.
int getType() Returns the ResultSet type (TYPE_FORWARD_ONLY, etc.).
boolean wasNull() Checks if the last retrieved column value was NULL.

✅ Example:
ResultSetMetaData metaData = rs.getMetaData();
int columnCount = metaData.getColumnCount();
System.out.println("Number of Columns: " + columnCount);

5. Closing Methods

These methods help release resources.

Method Description
void close() Closes the ResultSet and releases resources.

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 78 of 86


✅ Example:

rs.close(); // Close ResultSet

Summary Table
Category Important Methods
Navigation next(), previous(), first(), last(), absolute(n), relative(n), isBeforeFirst(), isAfterLast()
Retrieval getInt(), getString(), getDouble(), getDate(), getBoolean(), getObject()
Updating updateString(), updateInt(), updateRow(), deleteRow(), insertRow()
Metadata getMetaData(), getRow(), getType(), wasNull()
Closing close()

Which Methods Should You Use?

 For basic retrieval → next(), getString(), getInt()


 For moving between records → first(), last(), absolute(n)
 For updating records → updateString(), updateRow()
 For metadata → getMetaData()
13. Explain with neat diagram of JDBC architecture.
Ans. JDBC Architecture Diagram

Below is a neat representation of the JDBC architecture:

Components of JDBC Architecture

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 79 of 86


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 = DriverManager.getConnection("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)

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 80 of 86


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.

How JDBC Works? (Step-by-Step)

1. Java Application makes a request using the JDBC API (SELECT * FROM students).
2. The JDBC Driver Manager selects the appropriate JDBC driver.
3. The JDBC Driver translates the request into database-specific commands.
4. The Database Server executes the query and returns results.
5. The JDBC Driver converts the results into a Java-readable format.
6. The Java Application processes and displays the results.

Example JDBC Code


import java.sql.*;

public class JDBCExample {


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

try {
// Load JDBC Driver
Class.forName("com.mysql.cj.jdbc.Driver");

// Establish Connection
Connection conn = DriverManager.getConnection(url, user, password);

// Create and Execute SQL Query


Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM student");

// Process the ResultSet


while (rs.next()) {
System.out.println(rs.getInt("id") + " - " + rs.getString("name"));
}

// Close Resources
rs.close();
stmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 81 of 86


}
}

Conclusion


JDBC bridges the gap between Java applications and databases.

The JDBC API, Driver Manager, JDBC Driver, and Database work together to handle
database operations efficiently.
 JDBC is essential for database-driven applications like web apps, enterprise systems, and
reporting tools.
14. Explain Two tier Model of JDBC Architecture.
Ans.
Two-Tier Model of JDBC Architecture

What is the Two-Tier Model?

The Two-Tier Architecture (also known as Client-Server Architecture) is a model where the Java
application directly communicates with the database without any intermediate layer.

This model is simpler and commonly used in small-scale applications, such as desktop applications,
stand-alone applications, or local database interactions.

Diagram of Two-Tier JDBC Architecture

How the Two-Tier Model Works?

1. The Java Application sends SQL queries using JDBC.


2. The JDBC Driver Manager selects and loads the appropriate JDBC Driver.
3. The JDBC Driver converts JDBC method calls into database-specific commands.
4. The Database Server processes the query and sends back results.
5. The JDBC Driver receives the results and sends them back to the Java Application.
6. The Java application processes and displays the results.

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 82 of 86


Key Features of Two-Tier JDBC Model

✅ Direct communication between the Java application and the database.


✅ Faster performance due to the absence of an intermediate layer.
✅ Suitable for small applications with a single user or a few users.
✅ Works well for local databases or when the database is on the same network.
❌ Not scalable for large applications (since multiple clients directly access the database).
15. Explain JDBC drivers.
Ans.
JDBC Drivers in Java

A JDBC Driver is a software component that enables a Java application to communicate with a
database. It translates JDBC API calls into database-specific operations so that Java programs can
interact with different databases seamlessly.

Types of JDBC Drivers

JDBC drivers are categorized into four types, based on how they interact with the database.

Platform
JDBC Driver Type Description Speed
Dependency
Type 1: JDBC-ODBC Uses ODBC (Open Database
Slow Yes
Bridge Driver Connectivity)
Uses database-specific native
Type 2: Native API Driver Moderate Yes
libraries
Type 3: Network Protocol Uses middleware for database Moderate to
No
Driver communication Fast
Type 4: Thin Driver (Pure Directly communicates with the
Fastest No
Java) database

1. Type 1: JDBC-ODBC Bridge Driver

✅ How it Works?

 Uses the ODBC driver to interact with the database.


 Requires ODBC Driver installed on the system.

✅ Diagram:
Java Application → JDBC-ODBC Bridge → ODBC Driver → Database

✅ Advantages:
✔Allows Java to communicate with any database that supports ODBC.

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 83 of 86


✔ Good for testing purposes.

❌Disadvantages:
❌Slow performance due to multiple translations.
❌Platform-dependent (requires ODBC setup on each system).
❌ Deprecated (not recommended for new applications).

2. Type 2: Native API Driver

✅ How it Works?

 Uses database-specific native libraries (e.g., Oracle OCI, MySQL C API).


 Converts JDBC calls into native API calls.

✅ Diagram:

Java Application → JDBC API → Native API Driver → Database

✅Advantages:
✔Better performance than Type 1.
✔ Supports advanced database features.

❌Disadvantages:
❌Platform-dependent (requires native libraries).
❌ Cannot be used for web-based applications.

3. Type 3: Network Protocol Driver (Middleware Driver)

✅ How it Works?

 Uses a middleware server to communicate with the database.


 Converts JDBC calls into a network protocol and sends them to the middleware.
 Middleware translates and forwards them to the database.

✅ Diagram:

Java Application → JDBC API → Type 3 Driver → Middleware Server → Database

✅Advantages:
✔Platform-independent (works across different operating systems).
✔ Good for web-based applications.
✔ No need to install database-specific libraries on the client machine.

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 84 of 86


❌Disadvantages:
❌Requires a middleware server, increasing complexity.
❌ Slower than Type 4 due to the extra network layer.

4. Type 4: Thin Driver (Pure Java Driver)

✅ How it Works?

 Directly communicates with the database using database-specific protocols.


 No intermediate layers or native code involved.

✅ Diagram:

Java Application → JDBC API → Type 4 Driver → Database

✅Advantages:
✔ Fastest and most efficient JDBC driver.
✔ Platform-independent (100% Java-based).
✔ Most widely used driver in modern applications.

❌ Disadvantages:
❌ Database-specific (each database needs its own Type 4 driver).

✅ Common Type 4 Drivers:

 MySQL: com.mysql.cj.jdbc.Driver
 Oracle: oracle.jdbc.OracleDriver
 PostgreSQL: org.postgresql.Driver
 SQL Server: com.microsoft.sqlserver.jdbc.SQLServerDriver

✅ Example (Using MySQL Type 4 Driver):

import java.sql.*;

public class Type4JDBCExample {


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

try {
// Load Type 4 JDBC Driver
Class.forName("com.mysql.cj.jdbc.Driver");

// Establish Connection
Connection conn = DriverManager.getConnection(url, user, password);

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 85 of 86


System.out.println("Connected successfully!");

conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

Which JDBC Driver Should You Use?


Use Case Recommended JDBC Driver
Small testing projects Type 1 (JDBC-ODBC Bridge) (Deprecated)
Platform-dependent applications Type 2 (Native API)
Enterprise & web applications Type 3 (Middleware)
Modern applications (Best choice) Type 4 (Thin Driver)

Best Choice?

✅ Type 4 JDBC Driver is the most widely used because of high performance and platform
independence.

Conclusion

 JDBC Drivers act as a bridge between Java applications and databases.


 Type 4 (Thin Driver) is the best choice for modern applications.
 Type 3 (Middleware Driver) is useful for distributed applications.
 Type 1 and Type 2 are rarely used today due to performance and compatibility issues.

Prepared By: Prof.G.N.Handge(Computer Technology Dept.) Page 86 of 86

You might also like