Java Programming: A Deep Dive into Collections, AWT, JDBC, RMI, and Networking
ArrayList vs. Vector
| ArrayList | Vector |
|---|---|
| Not synchronized by default | Synchronized by default |
| Performance: More efficient in single-threaded scenarios | Performance: Potentially lower performance due to synchronization |
| Increment: Grows array by 50% when expanding | Increment: Doubles array size when expanding |
| Introduced in Java 1.2 | Introduced in Java 1.0 |
| Use Cases: Suitable for single-threaded scenarios for better performance | Use Cases: Suitable when thread safety is required |
AWT (Abstract Window Toolkit)
AWT is a set of classes in Java that provides the foundation for building graphical user interfaces (GUIs). AWT components are the building blocks of GUI applications. AWT occupies more space. The components are part of the java.awt.* package.
- AbstractButton
- ButtonGroup
- JApplet
- JButton
- JCheckBox
- JComboBox
- JLabel
- JRadioButton
- JTextArea
- JTextField
- JSlider
Collection Framework
AbstractCollection, AbstractList, AbstractQueue, LinkedList, HashSet, TreeSet, PriorityQueue, ArrayList, EnumSet, Stack, Vector, Hashable
Hashing in Java
Hashing is a technique used in Java (and other programming languages) to efficiently store and retrieve data from data structures like hash tables or hash maps. It involves mapping data to a fixed-size value, called a hash code or hash value, using a hash function.
- Hash Function: A hash function takes input (data) and produces a unique hash code of a fixed length. The hash function should generate the same hash code for the same input consistently.
- Hash Code: The hash code is an integer value that represents the input data after applying the hash function. It serves as an index or key to store and retrieve data in hash-based data structures.
- Hash-based Data Structures: Hashing is commonly used in data structures like hash tables, hash maps, or hash sets. These data structures store data based on their hash codes, enabling fast access and retrieval of values.
Containers in Java
In Java, a Container class is a component that can contain and organize other components, including other containers. It’s part of the Abstract Window Toolkit (AWT), which is used for building graphical user interfaces in Java.
Types of Containers
Top-Level Containers
These are the main building blocks for any Java GUI application. They serve as the base window or frame in which other GUI components are added. Examples include:
JFrame: Used to create a window.JDialog: Creates a pop-up dialog window.JApplet: Used for creating applets (though applets are largely obsolete now).JWindow: Creates a window without the window decorations (like borders and title bar).
Low-Level Containers
These are used within top-level containers to organize the layout and manage a group of components. Examples include:
JPanel: A generic container used to group other components.ScrollPane: Allows you to add a scrollable view to components.JComponent: The base class for all Swing components, which itself extends Container.
JDBC Process
- Establish a Connection
- The Java application invokes classes and interfaces from the JDBC Driver for sending queries to the data source.
- Results are based on SQL statements, which are then returned to the Java application.
- The Java application then uses the retrieved information for further processing.
Execution of Commands
- Load JDBC Driver:
Class.forName("com.mysql.cj.jdbc.Driver"); - Establish Connection:
Connection conn = DriverManager.getConnection(); - Create Statement or Prepared Statement:
Statement stmt = conn.createStatement(); - Execute SQL Queries:
ResultSet rs = stmt.executeQuery("SELECT * FROM students"); - Close the ‘ResultSet’, ‘Statement’, and ‘Connection’:
rs.close(); stmt.close(); conn.close();
Steps to Connect a Java Application with a Database
- Import the Packages
- Load the drivers using the
forName()method. - Register the drivers using
DriverManager. - Establish a connection using the
Connectionclass object. - Create a statement.
- Execute the query.
- Close the connections.
SUN-MICROSYSTEM – JDBC APPLICATION
MICROSOFT – ODBC
Types of JDBC Drivers
- JDBC-ODBC Driver: This driver translates all JDBC calls into ODBC (Open Database Connectivity) calls and sends them to the ODBC driver. Thus, JDBC access is via the ODBC driver. ODBC is a generic API. In this scenario, the client database code must be present on the client machine.
- Native-API/Partly Java Driver: This driver translates all JDBC calls into database-specific calls. This driver works specifically for a particular database. For example, MySQL will have a native MySQL API. This type of driver directly communicates with the database server. Hence, some binary code must be present on the client machine.
- Net Protocol Driver – Middleware Server: In this type of driver, all JDBC calls are passed through the network to the middleware server. The middleware server then translates the request to the database-specific native-connectivity interface, and then the request is sent to the database server. This driver is a server-based driver. This is also known as a pure Java driver.
- Native/Protocol Pure Driver: This type of driver converts the JDBC calls to the network protocol used by the database directory so that the client application can directly communicate with the database server. This driver is also completely implemented in Java and hence is referred to as a Pure Java driver. As this driver is completely written in Java, it is platform-independent and can be used on the internet. There is no need to install specific software on the client machine. These drivers can be downloaded dynamically.
RMI (Remote Method Invocation)
RMI stands for Remote Method Invocation. It is a mechanism that allows an object residing in one system (JVM) to access/invoke an object running on another JVM. RMI is used to build distributed applications; it provides remote communication between Java programs. It is provided in the package java.rmi.
Architecture of an RMI Application
In an RMI application, we write two programs: a server program (resides on the server) and a client program (resides on the client). Inside the server program, a remote object is created, and a reference to that object is made available for the client (using the registry). The client program requests the remote objects on the server and tries to invoke its methods.
- Transport Layer: This layer connects the client and the server. It manages the existing connection and also sets up new connections.
- Stub: A stub is a representation (proxy) of the remote object at the client. It resides in the client system; it acts as a gateway for the client program.
- Skeleton: This is the object that resides on the server side. The stub communicates with this skeleton to pass requests to the remote object.
- RRL (Remote Reference Layer): It is the layer that manages the references made by the client to the remote object.
Working of an RMI Application
- When the client makes a call to the remote object, it is received by the stub, which eventually passes this request to the RRL.
- When the client-side RRL receives the request, it invokes a method called
invoke()of the objectremoteRef. It passes the request to the RRL on the server side. - The RRL on the server side passes the request to the Skeleton, which finally invokes the required object on the server.
- The result is passed all the way back to the client.
RMI Registry
- The RMI registry is a namespace on which all server objects are placed. Each time the server creates an object, it registers this object with the RMI registry (using
bind()orreBind()methods). These are registered using a unique name known as the bind name. - To invoke a remote object, the client needs a reference to that object. At that time, the client fetches the object from the registry using its bind name (using the
lookup()method).
Steps to Create an RMI Application
- Define the remote interface.
- Develop the implementation class (remote object).
- Develop the server program.
- Develop the client program.
- Compile the application.
- Execute the application.
Networking Classes and Interfaces in Java
Classes
SocketServerSocketDatagramSocketDatagramPacketInetAddressURLURLConnectionHttpURLConnectionMulticastSocketSocketAddressInetSocketAddressProxyProxySelectorAuthenticatorCookieHandlerCookieManagerCookiePolicyCookieStoreHttpCookie
Interfaces
SocketImplFactoryDatagramSocketImplFactoryContentHandlerFactoryFileNameMapProtocolFamilySocketOption<T>SocketOptions
TCP/IP Client Socket in Java
A TCP/IP client socket in Java is an endpoint of a two-way communication link between a client program and a server program over a TCP/IP network. The client socket is responsible for initiating the connection to the server and sending data to and receiving data from the server.
Methods of the TCP/IP Client Socket Class
- Socket Initialization:
import java.net.Socket; String serverHost = "example.com"; int serverPort = 8080; Socket socket = new Socket(serverHost, serverPort); - Data Communication:
import java.io.*; InputStream inputStream = socket.getInputStream(); OutputStream outputStream = socket.getOutputStream(); - Reading and Writing Data:
BufferedReader a = new BufferedReader(new InputStreamReader(inputStream)); String serverResponse = a.readLine(); - Closing the Socket:
socket.close();
Specific Methods
- Constructor:
Socket(String host, int port): Creates a new socket and connects it to the specified remote host and port number.Socket socket = new Socket("example.com", 8080); - Input and Output Streams:
getInputStream(): Returns an input stream that can be used to read data from the socket.InputStream inputStream = socket.getInputStream(); - Closing the Socket:
close(): Closes the socket and releases any resources associated with it.socket.close();
Java InetAddress Class
- The Java
InetAddressclass represents an IP address. - The
java.net.InetAddressclass provides methods to get the IP of any host name. - An IP address is represented by a 32-bit or 128-bit unsigned number.
- An instance of
InetAddressrepresents the IP address with its corresponding host name. - There are two types of addresses: Unicast and Multicast. Unicast is an identifier for a single interface, whereas Multicast is an identifier for a set of interfaces.
IP Address
- An IP address helps to identify a specific resource on the network using a numerical representation.
- Most networks combine IP with TCP (Transmission Control Protocol). It builds a virtual bridge between the destination and the source.
Types of IP Addresses
- IPv4: IPv4 is the primary Internet protocol. It is the first version of IP deployed for production in the ARPANET in 1983. It is a widely used IP version to differentiate devices on a network using an addressing scheme. A 32-bit addressing scheme is used to store 232 addresses, which is more than 4 million addresses.
- IPv6: IPv6 is the latest version of the Internet protocol. It aims at fulfilling the need for more internet addresses. It provides solutions for the problems present in IPv4. It provides a 128-bit address space that can be used to form a network of 340 undecillion unique IP addresses. IPv6 is also identified with the name IPng (Internet Protocol next generation).
Factory Methods
InetAddress has no visible constructor. Hence, to make use of the InetAddress object, we need to use Factory Methods. It is simply a conversion whereby static methods in a class return an instance of the class.
getLocalHost()getByName()
Datagrams in Java
- Datagrams are collections of information sent from one device to another device via the established network. When the datagram is sent to the targeted device, there is no assurance that it will reach the target device safely and completely. It may get damaged or lost in between. Likewise, the receiving device also never knows if the datagram received is damaged or not. The UDP protocol is used to implement datagrams in Java.
- Java DatagramSocket Class: The Java
DatagramSocketclass represents a connectionless socket for sending and receiving datagram packets. It is a mechanism used for transmitting datagram packets over a network. A datagram is basically information, but there is no guarantee of its content, arrival, or arrival time.
Commonly Used Constructors of the DatagramSocket Class
DatagramSocket() throws SocketException: It creates a datagram socket and binds it with the available port number on the localhost machine.DatagramSocket(int port) throws SocketException: It creates a datagram socket and binds it with the given port number.DatagramSocket(int port, InetAddress address) throws SocketException: It creates a datagram socket and binds it with the specified port number and host address.
- Java DatagramPacket Class:
DatagramPacketis a message that can be sent or received. It is a data container. If you send multiple packets, they may arrive in any order. Additionally, packet delivery is not guaranteed.
Commonly Used Constructors of the DatagramPacket Class
DatagramPacket(byte[] barr, int length): It creates a datagram packet. This constructor is used to receive the packets.DatagramPacket(byte[] barr, int length, InetAddress address, int port): It creates a datagram packet. This constructor is used to send the packet.
Cookies in Java
Cookies in Java are small pieces of data sent from a web server and stored on the client’s machine. They are used to remember information about the client, such as user preferences, session information, or tracking data. Cookies are an essential part of web development for managing user sessions and providing a personalized user experience.
Purpose of Cookies
- Session Management: Maintain session state, like keeping users logged in.
- Personalization: Store user settings and preferences.
- Tracking: Monitor user behavior and activity on a website.
Types of Cookies
- Session Cookies: Temporary, deleted when the browser closes.
- Persistent Cookies: Stored for a specified duration, even after the browser is closed.
Example Code for Accessing Cookies
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if ("username".equals(cookie.getName())) {
String username = cookie.getValue();
// Use the username
}
}
}
