Java Unit 3,4 copy
Java Unit 3,4 copy
UNIT - 3
Threads
Threads are a fundamental concept in Java that allow concurrent execution of
code. They are lightweight units of execution within a program, enabling multiple
tasks to run concurrently. Here are the key aspects of threads:
By default, Java programs have at least one thread, known as the main
thread, which is created automatically when the program starts.
Creating Threads:
In Java, there are two main ways to create threads:
You can create a thread by extending the Thread class and overriding its
run() method, which contains the code to be executed by the thread.
Here's an example:
To start the thread, create an instance of the MyThread class and call its
start() method.
JAVA 55
Alternatively, you can create a thread by implementing the Runnable
Here's an example:
Thread Priority:
Threads in Java can have different priorities, ranging from 1 (lowest) to 10
(highest). The default priority is 5. Here are some points to know about thread
priority:
Thread priorities are used by the thread scheduler to determine the order of
execution when multiple threads are ready to run.
You can set the priority of a thread using the setPriority() method, passing
the desired priority as an argument.
Thread priority should be used with caution and should not be solely relied
upon for critical operations.
Blocked States:
Threads can enter into blocked states in certain situations. Here are two
common scenarios:
method, which causes the thread to pause execution for a specified period
of time.
Waiting: Threads can wait for a specific condition to be met using the wait()
JAVA 56
Extending the Thread Class:
As mentioned earlier, one way to create threads is by extending the Thread
When extending the Thread class, you override the run() method to define
the behavior of the thread.
By extending the Thread class, your class becomes a thread itself and can
be instantiated and started like any other thread.
However, this approach limits the flexibility of your class, as it does not allow
for extending other classes.
If you've created a thread by extending the Thread class, you can simply
create an instance of your class and call the start() method on it.
Example:
javaCopy code
MyThread myThread = new MyThread(); // Assuming MyThread extends Thread
myThread.start();
It's important to note that concurrent programming and managing threads can be
complex, as it involves synchronization, thread safety, and coordination between
threads. It's recommended to study these topics further to write robust and
efficient multi-threaded programs.
Runnable Interface
The Runnable interface in Java provides an alternative way to create threads by
encapsulating the code to be executed within a separate object. Here's an
overview of the Runnable interface:
JAVA 57
Create a class that implements the Runnable interface.
Implement the run() method within the class, which contains the code to be
executed by the thread.
Call the start() method on the Thread object to start the execution of the
thread.
class directly:
JAVA 58
Enhanced Thread Pooling: When utilizing thread pooling techniques, such
as the Executor framework, using Runnable objects allows for more efficient
utilization of thread resources.
By utilizing the Runnable interface, you can design your code to be more flexible,
modular, and scalable when dealing with multi-threaded scenarios.
Thread Synchronization:
In multi-threaded programming, thread synchronization is important to ensure
proper coordination and order of execution between threads. It helps prevent
data inconsistency and race conditions. Java provides synchronization
mechanisms to achieve thread synchronization:
1. Synchronized Methods:
Example:
2. Synchronized Blocks:
You can also synchronize specific blocks of code using the synchronized
The lock ensures that only one thread can execute the synchronized
block at a time.
Example:
synchronized (lockObject) {
// Synchronized block code
}
JAVA 59
Synchronize Threads:
To synchronize threads and ensure proper coordination, you can use methods
like wait() , notify() , and notifyAll() . These methods must be called from
within a synchronized context (synchronized method or synchronized block).
Here's an overview:
wait() : Causes the current thread to release the lock and enter a waiting
state until another thread calls notify() or notifyAll() on the same object. It
should be used within a loop to check the condition that caused the thread to
wait.
: Wakes up one of the threads that are waiting on the same object.
notify()
The awakened thread can then compete for the lock and continue execution.
notifyAll() : Wakes up all the threads that are waiting on the same object.
By using synchronization and the methods mentioned above, you can control the
execution order and synchronization between threads, ensuring proper
concurrency and data consistency.
1. Syntax:
synchronized (object) {
// Synchronized code block
}
2. Object Lock:
The lock can be any object, but it is commonly a shared object that the
threads need to synchronize on.
JAVA 60
Only one thread can hold the lock at a time, and other threads will wait
until the lock is released.
3. Benefits:
Sync code blocks allow you to synchronize only the critical section of
code that needs synchronization, rather than the entire method.
thread1.start();
thread2.start();
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
JAVA 61
to ensure that only one thread can modify the count variable at a time.
Overriding Synchronized Methods:
When dealing with inheritance and overriding methods in Java, there are a few
things to consider when it comes to synchronized methods:
Example:
class SuperClass {
public synchronized void synchronizedMethod() {
// Superclass synchronized method
}
}
In the example above, the SuperClass has a synchronized method. The SubClass
Thread Communication
Thread Communication using wait(), notify(), and notifyAll():
In Java, threads can communicate with each other using the methods wait() ,
notify() , and notifyAll() . These methods are part of the Object class and can
JAVA 62
be used to coordinate the execution of threads. Here's an explanation of how
these methods work:
1. wait():
The wait() method causes the current thread to release the lock on the
object and enter a waiting state until another thread calls notify() or
notifyAll() on the same object.
When a thread calls wait() , it relinquishes the lock and allows other
threads to continue execution. The thread remains in a waiting state until
it receives a notification to resume.
Example:
synchronized (sharedObject) {
while (condition) {
sharedObject.wait(); // Waits until notified
}
// Continue execution after receiving notification
}
2. notify():
The notify() method wakes up one thread that is waiting on the same
object. It allows that thread to continue execution after it regains the
lock.
If multiple threads are waiting, the thread that gets the notification is
arbitrary and depends on the thread scheduler.
Example:
synchronized (sharedObject) {
// Update shared data or perform some task
sharedObject.notify(); // Notifies one waiting thread
}
3. notifyAll():
The notifyAll() method wakes up all threads that are waiting on the
same object. It allows all the waiting threads to continue execution after
they regain the lock.
JAVA 63
Example:
synchronized (sharedObject) {
// Update shared data or perform some task
sharedObject.notifyAll(); // Notifies all waiting threads
}
Call wait() , notify() , and notifyAll() only from within synchronized blocks
or synchronized methods.
Use a loop with wait() to check the condition that caused the thread to wait.
This helps prevent spurious wake-ups.
Make sure the threads involved are accessing the same shared object for
synchronization.
AWT Components
AWT (Abstract Window Toolkit) is a set of classes and components in Java used
for creating graphical user interfaces (GUIs) for desktop applications. AWT
provides a collection of UI components that allow developers to create windows,
buttons, labels, text fields, and other elements to build interactive user
interfaces. Here are some commonly used AWT components:
1. Frame:
The Frame class represents a top-level window with a title bar and
borders.
JAVA 64
Example:
2. Panel:
The Panel class represents a container that can hold other components.
Example:
3. Button:
Example:
4. Label:
Example:
5. TextField:
The TextField class represents a single-line input field where users can
enter text.
JAVA 65
It is used for accepting user input or displaying dynamic text.
Example:
6. TextArea:
The TextArea class represents a multi-line text area where users can
enter or view large amounts of text.
Example:
7. Checkbox:
Example:
These are just a few examples of AWT components. AWT provides many more
components such as List, Choice, Scrollbar, Menu, etc., which you can use to
create rich and interactive GUIs in Java.
To use AWT components, you need to import the relevant classes from the
java.awt package.
class are fundamental classes that form the building blocks of graphical user
interfaces. These classes provide the foundation for creating and managing GUI
components within a window. Let's take a closer look at each class:
JAVA 66
1. Component Class:
The Component class is an abstract class that serves as the base class
for all AWT components.
2. Container Class:
JAVA 67
setLayout(LayoutManager manager) : Sets the layout manager for the
container to define how components are arranged.
The Component class and the Container class provide the basic functionality for
creating and managing GUI components in AWT. By subclassing these classes
and utilizing their methods and properties, you can build complex and interactive
user interfaces in Java.
The LayoutManager interface is the base interface for all layout managers
in AWT.
JAVA 68
Dimension minimumLayoutSize(Container parent) : Returns the minimum
size of the layout.
2. Default Layouts:
AWT provides several default layout managers that implement the
LayoutManager interface. These layouts handle the positioning and sizing of
FlowLayout:
Example:
BorderLayout:
Example:
GridLayout:
JAVA 69
Example:
GridBagLayout:
Example:
These are just a few examples of default layouts available in AWT. Each
layout manager has its own set of properties and behavior, allowing you to
choose the most appropriate one for your GUI design.
By utilizing the Layout Manager interface and selecting the appropriate layout
manager, you can create well-structured and responsive user interfaces in Java.
1. Insets:
JAVA 70
int top : Represents the top inset (distance from the top edge of the
container).
int left : Represents the left inset (distance from the left edge of
the container).
int bottom : Represents the bottom inset (distance from the bottom
edge of the container).
int right : Represents the right inset (distance from the right edge of
the container).
2. Dimensions:
It's worth noting that both Insets and Dimension are immutable classes,
meaning their values cannot be changed once set. To modify their values,
you would typically create new instances with the desired values.
These classes are often used in conjunction with layout managers to control the
size, spacing, and positioning of components within containers. They provide a
convenient way to manage the visual aspects of GUI design.
JAVA 71
Border Layout:
The BorderLayout is a default layout manager provided by AWT.
It divides the container into five regions: North, South, East, West, and
Center.
Example usage:
Flow Layout:
The FlowLayout is a default layout manager provided by AWT.
Example usage:
Grid Layout:
Example usage:
JAVA 72
Container container = new Container();
container.setLayout(new GridLayout(rows, columns));
container.add(component1);
container.add(component2);
These layout managers are commonly used in Java GUI applications to organize
components within containers. By selecting the appropriate layout manager and
adding components to the specified regions or grid cells, you can create visually
appealing and responsive user interfaces.
Card Layout:
The CardLayout is a default layout manager provided by AWT.
Components are added to the CardLayout using unique names, and you can
switch between components using methods like next() , previous() , or
show() .
Example usage:
Example usage:
JAVA 73
Container container = new Container();
container.setLayout(new GridBagLayout());
GridBagConstraints constraints = new GridBagConstraints();
constraints.gridx = 0;
constraints.gridy = 0;
container.add(component1, constraints);
constraints.gridx = 1;
constraints.gridy = 0;
container.add(component2, constraints);
AWT Events:
AWT provides a set of event classes and interfaces to handle user
interactions with GUI components.
To handle AWT events, you need to implement event listener interfaces and
register them with the appropriate components using methods like
addActionListener() , addMouseListener() , or addKeyListener() .
Example usage:
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Handle button click event
}
});
These layout managers and event handling mechanisms in AWT allow you to
create dynamic and interactive user interfaces in your Java applications.
Event Models:
In Java, there are different event models that define how events are generated,
dispatched, and handled in graphical user interfaces (GUIs). The two main event
JAVA 74
models used in Java are the AWT event model and the Swing event model. Let's
explore each of them:
The AWT (Abstract Window Toolkit) event model is the original event
model in Java.
In the AWT event model, events are generated by the operating system
and delivered to the appropriate components.
The event handling process involves three main steps: event generation,
event dispatching, and event handling.
The Swing event model is an enhanced version of the AWT event model
and is built on top of it.
The Swing event model introduces the concept of "pluggable look and
feel" (PLAF) and "lightweight" components.
JAVA 75
EventListenerList: A container class to manage Swing event
listeners.
Both event models provide a similar set of event classes and interfaces, but the
Swing event model offers more features and flexibility for GUI development.
To handle events in Java, you need to implement event listener interfaces and
register them with the appropriate components. Common event listener
interfaces include ActionListener, MouseListener, KeyListener, etc. The actual
event handling code is written within the implemented listener methods.
Example usage:
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Handle button click event
}
});
textField.addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
// Handle key press event
}
By understanding the event models and utilizing event listeners, you can create
interactive and responsive GUI applications in Java.
Listeners:
In Java, listeners are interfaces that define callback methods to handle specific
events. They are used in event-driven programming to capture and respond to
user actions or system events. Here are the key points about listeners:
JAVA 76
Listeners are implemented as interfaces in Java. Each listener interface
defines one or more methods that need to be implemented to handle
specific events.
Listeners follow the Observer design pattern, where the listener objects
register themselves with the event source to receive notifications when the
corresponding events occur.
When an event occurs, the event source invokes the appropriate methods
on the registered listeners, passing relevant information about the event.
Listeners decouple the event source from event handling logic, allowing for
flexible and modular design of event-driven systems.
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Handle button click event
}
});
Class Listener:
JAVA 77
The term "Class Listener" refers to a design pattern where a separate class is
created to implement a listener interface. This approach provides better
modularity and separation of concerns. Instead of using anonymous inner
classes or implementing the listener interface in the same class, you create a
separate class dedicated to handling events.
Here's an example of implementing a class listener:
1. Define a listener class that implements the desired listener interface and
overrides the corresponding event handling methods.
1. Instantiate the listener class and register it with the event source.
Using class listeners allows for cleaner code organization, improved reusability,
and easier maintenance, especially when multiple components need to share
the same event handling logic.
Adapters:
In Java, adapters are classes that provide default implementations for listener
interfaces. They allow you to implement only the methods you need, rather than
having to provide empty implementations for all methods in the interface.
Adapters are useful when you want to listen to specific events and avoid writing
unnecessary code. Here are the key points about adapters:
Adapters are classes that implement a listener interface and provide default
implementations for all the methods in the interface.
The adapter class acts as a bridge between the event source and the
listener, allowing you to override only the methods you are interested in.
JAVA 78
By using adapters, you can avoid implementing all methods of the listener
interface, which can save time and reduce code clutter.
1. Define an adapter class that extends the appropriate adapter class for the
listener interface you want to use. For example, if you want to handle mouse
events, you can extend the MouseAdapter class, which provides empty
implementations for all methods in the MouseListener interface.
1. Instantiate the adapter class and register it with the event source.
Using adapters simplifies event handling code, especially when you are
interested in handling a specific subset of events provided by a listener interface.
It allows you to focus on the events that matter to you without having to
implement unnecessary methods.
1. getSource(): Returns the object that generated the event. Useful when
multiple components share the same ActionListener.
JAVA 79
Object source = event.getSource();
1. getModifiers(): Returns the modifiers associated with the event, such as Ctrl,
Shift, or Alt keys.
1. getKeyCode(): Returns the unique code for the key that triggered the event.
JAVA 80
int keyCode = event.getKeyCode();
Mouse Events:
Mouse events in Java are triggered by user interactions with the mouse, such as
clicking, moving, or scrolling. There are several types of mouse events available
in Java, including:
JAVA 81
mouseExited(MouseEvent e): Invoked when the mouse exits a
component.
JAVA 82
Window Events:
Window events are related to the state and behavior of windows, such as
opening, closing, resizing, or moving windows. In Java, you can handle window
events using the WindowListener interface. Some commonly used methods in
the WindowListener interface include:
JAVA 83
}
You can then attach the window listener to a window object using the add
WindowListener() method.
frame.addWindowListener(new MyWindowListener());
By implementing the appropriate listener interfaces and their methods, you can
respond to user interactions with the mouse and handle various window-related
events in your Java programs.
UNIT - 4
Input/Output Streams:
In Java, input and output streams are used to handle the flow of data between a
program and an external source or destination, such as files, network
connections, or standard input/output. Streams provide a convenient way to read
data from and write data to these sources or destinations. Here are the key
points about input and output streams:
Input Streams: Input streams are used to read data from a source. They
provide methods to read different types of data, such as bytes, characters, or
objects, from the source. Some commonly used input stream classes include:
JAVA 84
Example of reading from a file using FileInputStream:
Output Streams: Output streams are used to write data to a destination. They
provide methods to write different types of data to the destination. Some
commonly used output stream classes include:
Byte Streams vs. Character Streams: Byte streams are used for reading and
writing binary data, while character streams are used for reading and writing
textual data. Character streams automatically handle character encoding and
decoding, making them suitable for working with text files.
Example of using character streams:
JAVA 85
e.printStackTrace();
}
These are some of the basic concepts and classes related to input and output
streams in Java. They provide a flexible and efficient way to handle data input
and output in various scenarios.
Stream Filters:
Stream filters in Java provide a way to transform data as it passes through an
input or output stream. They are used to perform operations such as
compression, encryption, or data manipulation on the data being read from or
written to a stream. Stream filters are implemented using the decorator design
pattern, where a filter class wraps around an existing stream and modifies its
behavior.
The java.io package provides several classes for stream filters, including:
JAVA 86
Data Input and Output Stream:
DataInputStream and DataOutputStream classes are used for reading and
writing primitive data types from/to a stream. They provide methods to read and
write data in a machine-independent format. These classes are particularly
useful when you need to exchange data between different platforms or systems.
Example of using DataOutputStream:
Print Stream:
PrintStream is a class in Java that provides methods for printing formatted
representations of data to an output stream. It is commonly used to write text
data to the console or to a file. PrintStream extends the OutputStream class and
provides additional print and println methods for convenient printing.
JAVA 87
Example of using PrintStream to write to console:
import java.io.PrintStream;
import java.io.IOException;
import java.io.RandomAccessFile;
// Reading data
int intValue = file.readInt();
double doubleValue = file.readDouble();
JAVA 88
} catch (IOException e) {
e.printStackTrace();
}
}
}
In this example, we create a RandomAccessFile object file with the file name
"data.txt" and mode "rw" (read-write). We write an integer value and a double
value to the file using the writeInt and writeDouble methods. Then, we seek to
the beginning of the file using the seek method. Finally, we read the values back
from the file using the readInt and readDouble methods.
RandomAccessFile provides flexibility in accessing specific parts of a file,
making it useful for scenarios where you need to read or modify data at arbitrary
positions within a file.
1. JDBC Architecture:
JAVA 89
database vendor provides its own JDBC driver that you need to include
in your project.
Process the results: If executing a query, retrieve the results using the
ResultSet object and process the data as needed.
import java.sql.*;
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
System.out.println("ID: " + id + ", Name: " + name);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
1. Database-specific Drivers:
JAVA 90
MS-Access: To connect to an MS-Access database, you need to use the
JDBC-ODBC Bridge driver. This driver acts as a bridge between the
JDBC API and the ODBC API. You'll need to set up the ODBC data
source for your MS-Access database and use it in the JDBC URL.
Note: The specific details of connecting to each database may vary, so refer to
the documentation and JDBC driver documentation provided by the respective
database vendor for the exact configurations and usage.
These are some of the concepts and steps involved in using JDBC for database
connectivity in Java, including connecting to different databases such as MS-
Access, Oracle, and MS-SQL Server.
Object Serialization
Object serialization in Java refers to the process of converting an object into a
stream of bytes, which can be written to a file or transmitted over a network.
Serialization allows objects to be saved or transmitted and later deserialized
back into objects. This is useful for scenarios such as persisting object state,
sending objects over a network, or storing objects in a database.
To make a class serializable, it needs to implement the Serializable interface,
which is a marker interface with no methods. By default, all of the class's non-
transient instance variables are serialized. Here's an example:
import java.io.*;
JAVA 91
try (FileOutputStream fileOut = new FileOutputStream("person.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut)) {
out.writeObject(person);
System.out.println("Object serialized successfully.");
} catch (IOException e) {
e.printStackTrace();
}
@Override
public String toString() {
return "Person{name='" + name + "', age=" + age + "}";
}
}
In this example, the Person class implements the Serializable interface, which
allows instances of the class to be serialized and deserialized. The Person object
is serialized by writing it to a file using ObjectOutputStream , and then it is
deserialized by reading from the file using ObjectInputStream . The deserialized
object is cast back to the Person type.
Sockets
Sockets in Java provide a way to establish communication channels between
two different programs running on the same machine or over a network. They
facilitate client-server communication by allowing data to be sent and received
JAVA 92
across network connections. Java provides the Socket and ServerSocket classes
to handle network communication using sockets.
Client Socket: The Socket class represents a client-side socket that initiates
a connection to a server. It provides methods to establish a connection, send
data to the server, and receive data from the server.
object.
// Server code
import java.io.*;
import java.net.*;
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println("Server: Received from client: " + inputLine);
out.println
// Client code
import java.io.*;
import java.net.*;
JAVA 93
try (Socket socket = new Socket("localhost", 1234);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.g
etInputStream()));
BufferedReader stdIn = new BufferedReader(new InputStreamReader(Syste
m.in))) {
String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("Client: Sent to server: " + userInput);
String response = in.readLine();
System.out.println("Client: Received from server: " + response);
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
In this example, the server listens on port 1234 using a ServerSocket . When a
client connects, it accepts the connection and creates input and output streams
to communicate with the client. The server receives messages from the client,
prints them, and sends a response back.
The client creates a Socket object to connect to the server's IP address and port.
It also creates input and output streams to communicate with the server. The
client reads input from the user, sends it to the server, and displays the response
received from the server.
Use the ServerSocket class from the java.net package to listen for
incoming client connections.
JAVA 94
Accept client connections by calling the accept() method of the
ServerSocket class, which returns a Socket object representing the client
connection.
Spawn a new thread or use a thread pool to handle each client request
separately, allowing multiple clients to connect concurrently.
Receive and parse requests from clients by reading from the input
stream of the Socket object.
Send requests to the server by writing to the output stream of the Socket
object.
Wait for the server's response by reading from the input stream of the
Socket object.
Process the response received from the server and take appropriate
action based on the application logic.
Run both the server-side and client-side applications and verify that they
can communicate properly.
Debug any issues or errors that arise during testing, such as incorrect
data transmission or unexpected behavior.
JAVA 95
Add additional functionality to the client and server applications as
needed.
Use the ServerSocket class from the java.net package to create a server
socket that listens for incoming client connections on a specific port.
JAVA 96
Choose an appropriate port number for your server.
For each client connection, create a new thread or use a thread pool to
handle the client's requests separately.
For each client connection, create a new thread or task to handle the
client's requests.
Inside the thread or task, use the Socket object representing the client
connection to communicate with the client.
Read data from the input stream of the Socket to receive client requests.
Send responses back to the client by writing data to the output stream of
the Socket .
Provide a way to gracefully stop the server, which includes stopping new
client connections and waiting for existing client threads to finish their
JAVA 97
work before exiting.
JAVA 98
1. Define Remote Interface:
Register the remote object with the RMI registry using the rebind()
Obtain a reference to the remote object from the RMI registry using the
lookup() method of the java.rmi.Naming class.
JAVA 99
7. Handle Exceptions:
Both the remote interface and the remote object implementation should
throw java.rmi.RemoteException to handle communication-related
exceptions that may occur during remote method invocation.
8. Security Considerations:
Note: RMI has been part of the Java platform for many years, but there are
alternative technologies available today for distributed computing in Java, such
as Java Remote Method Invocation over Internet Inter-ORB Protocol (RMI-IIOP),
Java Message Service (JMS), and web services.
Java classes can define native methods, which are declared using the
native keyword and implemented in native code.
The Java Native Interface allows for passing data and invoking native
functions from Java code and vice versa.
JAVA 100
2. Write Native Code:
The native code should match the function signatures declared in the
native methods of the corresponding Java classes.
Include the necessary header files, such as jni.h , which provide the
JNI function prototypes and macros.
Create a Java class that serves as a wrapper for the native code. This
class will contain the native method declarations.
Load the native library that contains the native code using the
System.loadLibrary() method.
Use the Java javac command with the h option to generate the C/C++
header file for the Java class that contains native method declarations.
Implement the native methods in the native code file (.c or .cpp) using
the function signatures defined in the generated header file.
Use the JNI function calls to interact with Java objects, invoke Java
methods, get/set field values, and handle exceptions.
Compile the native code file (.c or .cpp) using a C/C++ compiler and
generate a shared library file (e.g., a DLL on Windows or a shared
object on Unix-like systems).
JAVA 101
Ensure that the necessary JNI library files are included during
compilation and linking.
Load the native library using the System.loadLibrary() method in the Java
code before invoking the native methods.
The JVM will load the shared library and make the native methods
available for invocation.
Run the Java application and test the functionality of the JNI-based
code.
Debug any issues that arise during execution, such as incorrect data
handling or compatibility problems between Java and native code.
JNI allows you to leverage existing native code libraries or access platform-
specific functionality from your Java applications. It provides a bridge between
Java and native code, enabling you to combine the portability of Java with the
power and
flexibility of native languages.
JAVA 102
Note: When working with JNI, it's important to exercise caution as it involves
direct interaction with native code, which can introduce potential security risks
and compatibility issues.
2. List Interface:
3. Set Interface:
4. Queue Interface:
5. Map Interface:
Synchronized (thread-safe).
2. Stack Class:
JAVA 103
Methods for stack operations like push, pop, and peek.
3. Hashtable Class:
Synchronized (thread-safe).
4. Enumerations:
5. Set Interface:
6. List Interface:
7. Map Interface:
8. Iterators:
These concepts and classes form the foundation for working with collections in
Java, allowing you to store, manipulate, and iterate over groups of elements
efficiently.
JAVA 104