Network Basics in Java Programming
🔹 What is Networking in Java?
Networking in Java allows programs to communicate with other programs over a network — typically over the Internet or a local network (LAN).
- Java provides a rich set of APIs in the
java.netpackage to support network communication. - You can build client-server applications, send/receive data, and handle protocols like TCP/IP and UDP.
🔹 Key Concepts of Networking in Java
1. IP Address and Port
- IP Address: Unique address of a computer on the network.
- Port: A numeric identifier for a specific process or service on the computer.
2. Protocols
- TCP (Transmission Control Protocol): Reliable, connection-oriented communication.
- UDP (User Datagram Protocol): Connectionless, faster but less reliable.
🔹 Java Networking Classes
| Class | Purpose |
|---|---|
InetAddress |
Represents IP addresses |
Socket |
Client-side TCP socket |
ServerSocket |
Server-side TCP socket |
DatagramSocket |
UDP socket |
DatagramPacket |
Packet of data for UDP |
URL |
Represents a URL |
URLConnection |
Represents a communication link to a URL |
🔹 Basic Networking Operations in Java
1. Using InetAddress
- Represents an IP address.
- Can get IP address from hostname or vice versa.
Example:
InetAddress address = InetAddress.getByName("www.google.com");
System.out.println("IP Address: " + address.getHostAddress());
System.out.println("Host Name: " + address.getHostName());
2. Creating a TCP Client (Using Socket)
- Connects to a server at a given IP address and port.
Socket socket = new Socket("localhost", 5000);
// Use socket.getInputStream() and socket.getOutputStream() to communicate
3. Creating a TCP Server (Using ServerSocket)
- Listens for client connections on a port.
ServerSocket server = new ServerSocket(5000);
Socket clientSocket = server.accept(); // wait for client connection
// Communicate using clientSocket.getInputStream() and getOutputStream()
4. UDP Communication (DatagramSocket and DatagramPacket)
- UDP is connectionless and sends packets of data.
Example sending UDP packet:
DatagramSocket socket = new DatagramSocket();
byte[] buffer = "Hello UDP".getBytes();
InetAddress address = InetAddress.getByName("localhost");
DatagramPacket packet = new DatagramPacket(buffer, buffer.length, address, 5000);
socket.send(packet);
socket.close();
🔹 Example: Simple TCP Client-Server Communication
Server.java
ServerSocket server = new ServerSocket(5000);
Socket client = server.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
PrintWriter out = new PrintWriter(client.getOutputStream(), true);
String msg = in.readLine();
System.out.println("Received: " + msg);
out.println("Message received");
Client.java
Socket socket = new Socket("localhost", 5000);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out.println("Hello Server");
String response = in.readLine();
System.out.println("Server says: " + response);
🔹 Summary Table
| Topic | Details |
|---|---|
| Package | java.net |
| IP Address | Unique network address |
| Port | Endpoint number for communication |
| Protocols | TCP (connection-oriented), UDP (connectionless) |
| Main Classes | InetAddress, Socket, ServerSocket, DatagramSocket |
| TCP Communication | Reliable, socket-based |
| UDP Communication | Fast, packet-based |
Overview of TCP/IP
🔹 What is TCP/IP?
TCP/IP stands for Transmission Control Protocol / Internet Protocol. It is a set of communication protocols used to interconnect network devices on the internet or private networks.
- It defines how data should be packetized, addressed, transmitted, routed, and received.
- TCP/IP is the foundation for the internet and most modern networks.
🔹 TCP/IP Model Layers
TCP/IP protocols are organized into four abstraction layers:
| Layer | Function | Examples of Protocols |
|---|---|---|
| Application | High-level protocols for apps and services | HTTP, FTP, SMTP, DNS, SSH |
| Transport | Reliable or unreliable data transfer | TCP (reliable), UDP (unreliable) |
| Internet | Addressing and routing packets | IP (IPv4, IPv6), ICMP, ARP |
| Network Interface | Physical transmission of data | Ethernet, Wi-Fi, ARP |
🔹 Key Protocols
1. IP (Internet Protocol)
- Handles addressing and routing of packets across networks.
- Responsible for delivering packets from source to destination based on IP addresses.
- Versions: IPv4 (most common), IPv6 (newer, larger address space).
2. TCP (Transmission Control Protocol)
- Provides reliable, connection-oriented communication.
- Ensures data packets arrive in order and without errors.
- Establishes a connection before sending data (3-way handshake).
- Handles retransmission of lost packets.
3. UDP (User Datagram Protocol)
- Connectionless and unreliable protocol.
- Sends packets called datagrams without establishing a connection.
- Used for applications needing speed over reliability (e.g., video streaming, gaming).
🔹 How TCP/IP Works
- Data from an application is divided into smaller units called packets.
- TCP ensures packets are numbered and checks for errors.
- IP handles addressing and routing the packets to their destination.
- At the destination, TCP reassembles packets into the original data.
- If packets are lost or damaged, TCP retransmits them.
🔹 TCP/IP in Java
- Java's
java.netpackage provides classes likeSocket,ServerSocket(for TCP), andDatagramSocket,DatagramPacket(for UDP). - Java developers use TCP/IP protocols to create client-server applications, web services, and network tools.
🔹 Summary Table
| Protocol | Purpose | Connection | Reliability | Use Cases |
|---|---|---|---|---|
| TCP | Reliable data transfer | Connection-oriented | Reliable | Web browsing, email, file transfer |
| UDP | Fast, low-overhead transmission | Connectionless | Unreliable | Streaming, gaming, VoIP |
| IP | Routing and addressing packets | N/A | N/A | Underpins all internet communication |
Socket Programming in Java:
🔹 What is Socket Programming?
Socket programming is a way to enable communication between two programs (usually client and server) over a network.
- A socket is an endpoint for sending or receiving data across a network.
- It provides a bidirectional communication channel between two processes, possibly on different machines.
🔹 How Socket Programming Works
- The server creates a
ServerSocketthat listens on a specific port. - The client creates a
Socketand connects to the server’s IP address and port. - Once connected, both client and server can send and receive data through input and output streams attached to the socket.
- After communication, the sockets are closed.
🔹 Key Java Classes for Socket Programming
| Class | Description |
|---|---|
ServerSocket |
Listens for incoming client connections on a port |
Socket |
Represents a client-side or accepted server-side socket connection |
InputStream / OutputStream |
Streams to read from/write to the socket |
BufferedReader / PrintWriter |
Convenient wrappers for reading/writing text |
🔹 Basic Workflow for TCP Socket Programming
On the Server Side:
- Create a
ServerSocketbound to a port. - Wait for a client to connect by calling
accept(). - Use the returned
Socketto communicate with the client. - Read and write data via input/output streams.
- Close the socket after communication ends.
On the Client Side:
- Create a
Socketspecifying server IP and port. - Use input/output streams to send/receive data.
- Close the socket after communication ends.
🔹 Simple Java Example: TCP Server and Client
Server Code (Server.java)
import java.net.*;
import java.io.*;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(1234);
System.out.println("Server listening on port 1234...");
Socket clientSocket = serverSocket.accept(); // Wait for client
System.out.println("Client connected.");
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
String message = in.readLine();
System.out.println("Received from client: " + message);
out.println("Hello from server!");
clientSocket.close();
serverSocket.close();
}
}
Client Code (Client.java)
import java.net.*;
import java.io.*;
public class Client {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("localhost", 1234);
System.out.println("Connected to server.");
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out.println("Hello Server!");
String response = in.readLine();
System.out.println("Server says: " + response);
socket.close();
}
}
🔹 Key Points to Remember
- Sockets use ports to identify communication endpoints.
- TCP sockets are connection-oriented, ensuring reliable communication.
- Use input/output streams to read/write data over sockets.
- Always close sockets to free resources.
- Exception handling (
try-catch) is essential for robust networking code.
🔹 When to Use Socket Programming?
- Building client-server applications like chat servers, multiplayer games.
- Communicating between distributed systems.
- Creating custom protocols over TCP/UDP.
- Implementing network tools and utilities.
Proxy Servers
🔹 What is a Proxy Server?
A proxy server acts as an intermediary between a client (like your computer or browser) and the internet (or another network service). When you send a request (e.g., visit a website), it first goes to the proxy server, which then forwards the request to the destination server on your behalf. The response returns back through the proxy to you.
🔹 How Does a Proxy Server Work?
- Client sends a request to the proxy server instead of directly to the destination.
- Proxy evaluates the request (e.g., for caching, filtering, or logging).
- Proxy forwards the request to the destination server.
- Destination server sends response back to the proxy.
- Proxy sends the response back to the client.
🔹 Types of Proxy Servers
| Type | Purpose/Use Case |
|---|---|
| Forward Proxy | Sits between client and internet; controls or filters client requests (e.g., for web filtering, security) |
| Reverse Proxy | Sits between internet and one or more web servers; distributes incoming traffic, provides load balancing, SSL termination |
| Transparent Proxy | Does not modify requests or responses; often used for caching or monitoring |
| Anonymous Proxy | Hides client’s IP address to provide privacy |
| Caching Proxy | Saves copies of frequently accessed resources to speed up responses |
| Open Proxy | Publicly accessible proxy servers (often unsafe) |
🔹 Why Use a Proxy Server?
- Privacy: Hide your IP address and location.
- Security: Block malicious sites, filter content, prevent direct access.
- Caching: Reduce bandwidth by serving cached content.
- Load Balancing: Distribute requests among multiple servers (reverse proxy).
- Access Control: Restrict access to certain websites or services.
- Logging and Monitoring: Track user activity.
🔹 Proxy Servers in Java
Java programs can use proxy servers by configuring:
- System properties for HTTP, HTTPS proxies:
System.setProperty("http.proxyHost", "proxy.example.com");
System.setProperty("http.proxyPort", "8080");
- Use
Proxyclass injava.netpackage to programmatically use proxies forSocketorHttpURLConnection.
Example:
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy.example.com", 8080));
HttpURLConnection connection = (HttpURLConnection) new URL("http://example.com").openConnection(proxy);
🔹 Summary Table
| Aspect | Details |
|---|---|
| What is Proxy? | Intermediary between client and server |
| Types | Forward, Reverse, Transparent, Anonymous |
| Benefits | Privacy, Security, Caching, Load balancing |
| Java Support | System properties, Proxy class |
TCP/IP Sockets
🔹 What Are TCP/IP Sockets?
- A socket is one endpoint of a two-way communication link between two programs running on a network.
- TCP/IP sockets use the TCP/IP protocol suite to establish reliable, ordered, and error-checked communication between client and server applications.
- TCP (Transmission Control Protocol) ensures a connection-oriented, reliable data transfer, while IP (Internet Protocol) handles addressing and routing.
🔹 Key Concepts of TCP/IP Sockets
| Term | Explanation |
|---|---|
| Socket | Combination of IP address and port number identifying an endpoint |
| Port | Logical communication endpoint for a process on a machine |
| IP Address | Unique address for a device on the network |
| TCP | Provides reliable, connection-oriented communication |
🔹 How TCP/IP Sockets Work
-
Server Side:
-
Creates a ServerSocket listening on a specific port.
- Waits (blocks) for incoming client connection requests.
- When a client connects, the server accepts the connection, creating a new Socket for communication.
-
Communicates with the client through input/output streams attached to the socket.
-
Client Side:
-
Creates a Socket and connects to the server's IP address and port.
-
Uses input/output streams to send and receive data.
-
Data Transmission:
-
Data is broken down into packets by TCP/IP and sent over the network.
- TCP guarantees packets arrive in order, retransmitting lost packets if necessary.
🔹 TCP/IP Socket Communication Steps
| Step | Description |
|---|---|
| 1. Socket creation | Server creates ServerSocket; client creates Socket |
| 2. Connection | Client connects; server accepts connection |
| 3. Data Exchange | Both sides send/receive data via streams |
| 4. Termination | Either side closes socket to end communication |
🔹 Java Classes for TCP/IP Sockets
| Class | Purpose |
|---|---|
ServerSocket |
Listens for and accepts incoming connections |
Socket |
Represents client connection to server |
InputStream |
To read data from socket |
OutputStream |
To write data to socket |
BufferedReader/PrintWriter |
Easier handling of text data |
🔹 Simple Example (Summary)
- Server creates
ServerSocketon port 5000. - Client creates
Socketto connect to server on port 5000. - Both communicate via streams.
🔹 Why Use TCP/IP Sockets?
- To build networked applications like chat apps, games, file transfer tools.
- Enables reliable, ordered communication over the internet.
- Works across different devices and platforms as TCP/IP is universal.
Network Address (Net Address)
🔹 What is a Network Address (Net Address)?
A network address is an identifier used to uniquely locate a device (host) or network on a larger network, such as the Internet.
- It tells where a device is located in the network hierarchy.
- It enables routing of data packets from one device to another.
🔹 Types of Network Addresses
| Type | Description | Examples |
|---|---|---|
| IP Address | Numeric label assigned to each device on a network | IPv4 (e.g., 192.168.1.1), IPv6 (e.g., 2001:0db8::1) |
| MAC Address | Unique hardware address of a network interface card | 00:1A:2B:3C:4D:5E |
| Subnet Address | Represents a segment of a larger network | Derived from IP & subnet mask |
🔹 Network Address in TCP/IP
- IP Address is the primary network address in TCP/IP.
-
It consists of two parts:
-
Network portion: Identifies the specific network.
- Host portion: Identifies the specific device on that network.
- The division depends on the subnet mask.
🔹 Network Address in Java (InetAddress)
Java provides the class java.net.InetAddress to represent IP addresses.
- Can represent both IPv4 and IPv6 addresses.
- Used for hostname resolution and IP manipulation.
Key Methods:
InetAddress.getByName(String host): Resolves hostname to IP address.InetAddress.getHostAddress(): Returns the IP address as a string.InetAddress.getHostName(): Returns the hostname.
Example:
import java.net.*;
public class NetworkAddressExample {
public static void main(String[] args) throws Exception {
InetAddress address = InetAddress.getByName("www.google.com");
System.out.println("Host Name: " + address.getHostName());
System.out.println("IP Address: " + address.getHostAddress());
}
}
🔹 Summary
| Term | Meaning |
|---|---|
| Network Address | Identifier for locating devices or networks |
| IP Address | Main network address in TCP/IP |
InetAddress |
Java class representing network addresses |
URL in Java and networking:
🔹 What is a URL?
URL stands for Uniform Resource Locator.
- It is the address used to locate resources on the internet, such as web pages, images, files, etc.
- A URL tells the browser or program where to find the resource and how to access it.
🔹 Structure of a URL
A typical URL looks like this:
protocol://hostname:port/path?query#fragment
| Part | Description | Example |
|---|---|---|
| Protocol | The method used to access the resource | http, https, ftp |
| Hostname | The domain name or IP address of the server | www.example.com |
| Port | (Optional) Port number where the server listens | 80 (default for HTTP) |
| Path | The specific resource on the server | /index.html |
| Query | (Optional) Parameters passed to the resource | ?id=123&sort=asc |
| Fragment | (Optional) Section within the resource | #section2 |
🔹 URL Example
https://www.example.com:443/products/item1.html?color=red#details
- Protocol: https
- Hostname: www.example.com
- Port: 443 (default for HTTPS)
- Path: /products/item1.html
- Query: color=red
- Fragment: details
🔹 URL in Java (java.net.URL)
Java provides the URL class to work with URLs programmatically.
Key Features:
- Parse URL strings into components (protocol, host, port, path, etc.).
- Open streams to read data from the URL.
- Access URL components via getter methods.
Example:
import java.net.*;
public class URLExample {
public static void main(String[] args) throws Exception {
URL url = new URL("https://www.example.com:443/products/item1.html?color=red#details");
System.out.println("Protocol: " + url.getProtocol());
System.out.println("Host: " + url.getHost());
System.out.println("Port: " + url.getPort()); // Returns -1 if default port
System.out.println("Path: " + url.getPath());
System.out.println("Query: " + url.getQuery());
System.out.println("Ref: " + url.getRef());
}
}
🔹 Summary
| Term | Meaning |
|---|---|
| URL | Uniform Resource Locator, address of resource |
| Protocol | Access method (HTTP, HTTPS, FTP, etc.) |
| Hostname | Server address |
| Port | Network port |
| Path | Resource location on server |
| Query | Parameters passed to resource |
| Fragment | Specific section within resource |
Datagrams
🔹 What Are Datagrams?
- A datagram is a basic transfer unit associated with connectionless packet-switched networks.
- It is a self-contained, independent packet of data that carries enough information for routing from source to destination without relying on earlier exchanges.
- Unlike TCP (connection-oriented), datagrams use UDP (User Datagram Protocol), which is connectionless and unreliable (no guaranteed delivery or order).
🔹 Characteristics of Datagrams
| Feature | Description |
|---|---|
| Connectionless | No formal connection established before sending data |
| Unreliable | Packets may be lost, duplicated, or arrive out of order |
| Small Size | Each datagram fits within a single packet (usually up to 65,535 bytes) |
| Independent | Each datagram is handled independently by the network |
🔹 Datagram in Java (java.net.DatagramPacket and DatagramSocket)
Java provides classes to handle UDP datagram communication:
DatagramPacket: Represents a datagram packet (data + destination/source address).DatagramSocket: Socket for sending and receiving datagram packets.
🔹 How Datagram Communication Works in Java
Sending Side
- Create a
DatagramPacketwith data and destination IP & port. - Send the packet through a
DatagramSocket.
Receiving Side
- Create an empty
DatagramPacketwith a buffer. - Use
DatagramSocketto receive incoming packets. - Extract data and sender information from the packet.
🔹 Simple Java Example: UDP Datagram Sender and Receiver
Datagram Sender (UDPClient.java)
import java.net.*;
public class UDPClient {
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket();
String message = "Hello UDP Server";
byte[] buffer = message.getBytes();
InetAddress address = InetAddress.getByName("localhost");
DatagramPacket packet = new DatagramPacket(buffer, buffer.length, address, 9876);
socket.send(packet);
socket.close();
}
}
Datagram Receiver (UDPServer.java)
import java.net.*;
public class UDPServer {
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket(9876);
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
socket.receive(packet);
String received = new String(packet.getData(), 0, packet.getLength());
System.out.println("Received: " + received);
socket.close();
}
}
🔹 When to Use Datagrams?
- Applications where speed is critical, and some data loss is acceptable.
- Examples: Video streaming, VoIP, online gaming, DNS queries.
- Situations where the overhead of establishing a connection is too high.
🔹 Summary Table
| Aspect | Datagram (UDP) | TCP (Socket) |
|---|---|---|
| Connection | Connectionless | Connection-oriented |
| Reliability | Unreliable (no guarantee of delivery/order) | Reliable (guaranteed delivery/order) |
| Use Cases | Real-time apps (streaming, games) | File transfer, web browsing |
Working with Windows using AWT Classes
🔹 What is AWT?
AWT (Abstract Window Toolkit) is Java’s original platform-independent windowing, graphics, and user-interface widget toolkit. It provides classes to create GUI components like windows, buttons, text fields, menus, etc.
🔹 Working with Windows in AWT
In AWT, a window is a top-level container that can hold GUI components. The main classes related to windows are:
| Class | Description |
|---|---|
Frame |
A top-level window with a title bar and border |
Window |
A basic window with no borders or title bar |
Dialog |
A popup window for user interaction |
🔹 Creating a Window Using AWT
Key Steps:
- Create a Frame object: The main window.
- Set size and layout: Define dimensions and layout manager.
- Add components: Buttons, labels, text fields, etc.
- Make the window visible.
- Handle window events (like closing).
🔹 Example: Creating a Simple Window with AWT
import java.awt.*;
import java.awt.event.*;
public class SimpleAWTWindow {
public static void main(String[] args) {
// Step 1: Create a Frame
Frame frame = new Frame("My AWT Window");
// Step 2: Set size
frame.setSize(400, 300);
// Step 3: Add a simple component
Label label = new Label("Welcome to AWT Window");
frame.add(label);
// Step 4: Set layout (optional)
frame.setLayout(new FlowLayout());
// Step 5: Make window visible
frame.setVisible(true);
// Step 6: Handle window closing event
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.out.println("Window is closing");
frame.dispose(); // Close window
System.exit(0); // Exit program
}
});
}
}
🔹 Important Window-Related Classes in AWT
| Class | Purpose |
|---|---|
Frame |
Main application window with borders/title |
Window |
Basic window without decorations |
Dialog |
Popup dialog window |
Canvas |
Area to draw graphics |
Panel |
Container to group components |
🔹 Handling Window Events
- Use
WindowListenerinterface orWindowAdapterclass to handle window events like minimize, maximize, close. - Commonly handled event: windowClosing to exit the app gracefully.
🔹 Summary
| Step | Description |
|---|---|
Create Frame |
Window with title and border |
| Set size/layout | Define appearance |
| Add components | Add buttons, labels, etc. |
| Make visible | Show the window |
| Handle events | Manage user interactions (close) |
AWT Controls
🔹 What are AWT Controls?
AWT Controls are the basic GUI components provided by the Abstract Window Toolkit (AWT) that allow user interaction in Java applications.
They include things like buttons, text fields, checkboxes, lists, and more.
🔹 Common AWT Controls
| Control | Description |
|---|---|
| Button | A clickable button to trigger actions |
| Label | Displays a text string or image (non-editable) |
| TextField | Single-line text input field |
| TextArea | Multi-line text input area |
| Checkbox | A box that can be checked or unchecked (true/false) |
| CheckboxGroup | Group of checkboxes allowing only one selection (radio buttons) |
| Choice | Drop-down list allowing user to select one option |
| List | List box allowing single or multiple selection |
| ScrollBar | Scroll bar component for scrolling |
| Panel | Container to group multiple controls |
🔹 Description of Some Key Controls
1. Button
- Used to perform an action when clicked.
- Example:
Button btn = new Button("Click Me");
2. Label
- Used to display a text or image.
- Not editable.
- Example:
Label lbl = new Label("Username:");
3. TextField
- Used for single-line input.
- Can set maximum length.
- Example:
TextField tf = new TextField(20); // 20 columns wide
4. Checkbox
- Represents a boolean option.
- Example:
Checkbox cb = new Checkbox("Subscribe to newsletter");
5. Choice
- Drop-down list for selecting one option.
- Example:
Choice choice = new Choice();
choice.add("Option 1");
choice.add("Option 2");
6. List
- Displays a list of items for selection.
- Can allow single or multiple selections.
- Example:
List list = new List(4, true); // 4 visible rows, multiple select enabled
list.add("Java");
list.add("Python");
🔹 Example: Using AWT Controls in a Frame
import java.awt.*;
import java.awt.event.*;
public class AWTControlsExample {
public static void main(String[] args) {
Frame frame = new Frame("AWT Controls Demo");
frame.setLayout(new FlowLayout());
Label lbl = new Label("Enter Name:");
TextField tf = new TextField(20);
Button btn = new Button("Submit");
Checkbox cb = new Checkbox("Subscribe");
frame.add(lbl);
frame.add(tf);
frame.add(cb);
frame.add(btn);
frame.setSize(300, 150);
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
frame.dispose();
System.exit(0);
}
});
}
}
🔹 Summary
| Control | Use Case |
|---|---|
| Button | Trigger actions on click |
| Label | Display text/images |
| TextField | Single-line user input |
| Checkbox | Boolean choice |
| Choice | Drop-down selection |
| List | Multiple/single selection list |
Layout Managers and Menus in Java AWT:
🔹 Layout Managers in Java AWT
What are Layout Managers?
- Layout managers control how components are arranged inside a container (like a Frame or Panel).
- They help organize GUI components automatically, managing their size and position based on rules.
- Using layout managers avoids manual positioning and resizing.
Common AWT Layout Managers
| Layout Manager | Description | Usage Example |
|---|---|---|
| FlowLayout | Places components in a row, left to right, wraps to next line | Default for Panel |
| BorderLayout | Divides container into 5 regions: North, South, East, West, Center | Default for Frame |
| GridLayout | Arranges components in a grid of rows and columns, all equal size | Buttons in calculator-like layout |
| CardLayout | Stacks components like cards; only one visible at a time | Wizard steps UI |
1. FlowLayout
- Components flow left to right.
- When no space, wraps to next line.
Frame f = new Frame();
f.setLayout(new FlowLayout());
2. BorderLayout
- Divides space into five areas.
- Add components to specific areas:
Frame f = new Frame();
f.setLayout(new BorderLayout());
f.add(new Button("North"), BorderLayout.NORTH);
f.add(new Button("Center"), BorderLayout.CENTER);
3. GridLayout
- Components arranged in rows and columns.
- Each cell same size.
Frame f = new Frame();
f.setLayout(new GridLayout(2, 3)); // 2 rows, 3 columns
4. CardLayout
- Used to swap between different "cards" or panels.
- Useful for wizard dialogs.
🔹 Menus in Java AWT
What is a Menu?
- A menu provides a list of options or commands the user can select.
- In AWT, menus appear typically on the top of a window (like File, Edit).
Menu Classes in AWT
| Class | Description |
|---|---|
| MenuBar | The bar that holds menus (usually at the top) |
| Menu | A pull-down menu (e.g., File menu) |
| MenuItem | An individual item in a menu |
| CheckboxMenuItem | A menu item with a checkbox |
Example: Creating a Simple Menu
import java.awt.*;
import java.awt.event.*;
public class MenuExample {
public static void main(String[] args) {
Frame f = new Frame("Menu Demo");
// Create MenuBar
MenuBar menuBar = new MenuBar();
// Create Menus
Menu fileMenu = new Menu("File");
Menu editMenu = new Menu("Edit");
// Create MenuItems
MenuItem newItem = new MenuItem("New");
MenuItem openItem = new MenuItem("Open");
MenuItem exitItem = new MenuItem("Exit");
// Add MenuItems to File menu
fileMenu.add(newItem);
fileMenu.add(openItem);
fileMenu.addSeparator();
fileMenu.add(exitItem);
// Add menus to MenuBar
menuBar.add(fileMenu);
menuBar.add(editMenu);
// Set MenuBar to Frame
f.setMenuBar(menuBar);
// Handle Exit menu item action
exitItem.addActionListener(e -> {
f.dispose();
System.exit(0);
});
f.setSize(400, 300);
f.setVisible(true);
}
}
🔹 Summary
| Topic | Purpose |
|---|---|
| Layout Managers | Control positioning and resizing of GUI components |
| FlowLayout | Simple left-to-right flow layout |
| BorderLayout | 5-region layout (North, South, East, West, Center) |
| GridLayout | Grid of equal-sized cells |
| Menus | Provide user options like File, Edit menus |
| MenuBar/Menu/MenuItem | Components to create menus and items |
JDBC Connectivity
🔹 What is JDBC?
- JDBC stands for Java Database Connectivity.
- It is an API (Application Programming Interface) in Java that allows Java programs to connect and interact with databases.
- JDBC provides methods to query and update data in a database.
🔹 Why Use JDBC?
- To connect Java applications with databases (like MySQL, Oracle, PostgreSQL).
- To perform database operations like SELECT, INSERT, UPDATE, DELETE.
- To execute SQL statements from Java.
🔹 JDBC Architecture Overview
- JDBC API: Java interface that application programs use.
- JDBC Driver Manager: Manages different database drivers.
- JDBC Drivers: Implement specific database protocols.
🔹 Steps for JDBC Connectivity
- Load the JDBC Driver
- Establish a Connection to the database
- Create a Statement or PreparedStatement
- Execute SQL queries or updates
- Process the ResultSet (if any)
- Close the connection
🔹 Key Interfaces and Classes
| Interface/Class | Purpose |
|---|---|
DriverManager |
Manages JDBC drivers |
Connection |
Represents a connection to the database |
Statement |
Used to execute static SQL statements |
PreparedStatement |
Used to execute precompiled SQL statements with parameters |
ResultSet |
Represents the result set from a query |
🔹 Example: Simple JDBC Program
import java.sql.*;
public class JDBCExample {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydatabase"; // database URL
String user = "root"; // database username
String password = "password"; // database password
try {
// Step 1: Load JDBC driver (optional for newer JDBC versions)
Class.forName("com.mysql.cj.jdbc.Driver");
// Step 2: Establish connection
Connection conn = DriverManager.getConnection(url, user, password);
// Step 3: Create statement
Statement stmt = conn.createStatement();
// Step 4: Execute query
ResultSet rs = stmt.executeQuery("SELECT * FROM employees");
// Step 5: Process results
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
System.out.println("ID: " + id + ", Name: " + name);
}
// Step 6: Close connections
rs.close();
stmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
🔹 Important Points
- Loading Driver: Since JDBC 4.0, drivers are auto-registered if in classpath, so
Class.forNamemay be optional. - Connection URL: Format depends on the database (MySQL, Oracle, etc.)
- SQL Injection: Always prefer
PreparedStatementto avoid SQL injection. - Exception Handling: Handle
SQLException.
🔹 Summary
| Step | Description |
|---|---|
| Load Driver | Register JDBC driver |
| Connect to Database | Get connection using URL and credentials |
| Create Statement | Prepare SQL commands |
| Execute Query/Update | Run SQL against DB |
| Process ResultSet | Read returned data |
| Close Resources | Release DB resources |