0% found this document useful (0 votes)
13 views43 pages

4 Oops

The document provides an overview of Java streams, including input and output streams, and their subclasses for handling byte and character data. It explains client-server architecture, socket programming, and multithreaded servers, highlighting the importance of handling multiple client requests simultaneously. Additionally, it covers JDBC for database connectivity, serialization, and the Java Collections framework for managing groups of objects.

Uploaded by

notboy0003
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views43 pages

4 Oops

The document provides an overview of Java streams, including input and output streams, and their subclasses for handling byte and character data. It explains client-server architecture, socket programming, and multithreaded servers, highlighting the importance of handling multiple client requests simultaneously. Additionally, it covers JDBC for database connectivity, serialization, and the Java Collections framework for managing groups of objects.

Uploaded by

notboy0003
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

Unit-4

In Java, streams are the sequence of data that are read from the source and written to
the destination.
An input stream is used to read data from the source. And, an output stream is used to
write data to the destination.

Types of Streams
Depending upon the data a stream holds, it can be classified into:
Byte Stream
Byte stream is used to read and write a single byte (8 bits) of data.
All byte stream classes are derived from base abstract classes called input stream and
output stream .
Character Stream
Character stream is used to read and write a single character of data.
All the character stream classes are derived from base abstract classes Reader and
Writer.
Input Stream class is an abstract class. It is the root class for reading binary I/O data.
It is the superclass of all classes representing an input stream of bytes. Since
InputStream class is an abstract class, we cannot create an object of this class. We
must use subclasses of this class to create an object.

The several subclasses of Java InputStream class can be used for performing several
input functions
All these methods are present in java.io.InputStream package. InputStream methods are as
follows:
1. int Read(): The read() method reads the next byte of data from the input stream. It returns
input byte read as an int value in the range 0 to 255.
If no byte is present because the end of the stream is reached, the value –1 is returned. If this
method encounters an I/O error, it will throw an IOException.
The read() method returns an int value -1 instead of a byte because it indicates the end of
stream.
2. int read(byte[ ] b): This method reads the number of bytes from the input stream and stores
them into the array of bytes b.
It returns the total number of bytes read as an int. If the end of stream is reached, returns -1.
3. int read(byte[ ] b, int n, int m): It reads up to m bytes of data from the input stream starting
from nth byte into an array b.
It returns the total number of bytes read as an int. Returns -1 at the end of stream because of
no more data.
4. int available(): The available method returns an estimate of the number of bytes that can be
read (or skipped over) from the input stream.
5. void close(): The close() method closes the input stream and releases any system resources
associated with it.
6. long skip(long n): This method skips over n bytes of data from this input stream. It returns
the actual number of bytes skipped.
7. void reset(): The reset() method is used to go back to the beginning of the stream.
8. boolean markSupported(): This method tests this input stream supports the mark and reset
methods. It returns true if the input stream supports mark and reset methods.
OutputStream class is an abstract class. It is the root class for writing
binary data. It is a superclass of all classes that represents an output
stream of bytes.
Since like InputStream, OutputStream is an abstract class, therefore, we
cannot create object of it.
The several subclasses of OutputStream class in Java can be used for
performing several output functions.
The OutputStream class defines the following method in
java.io.OutputStream package that are used to perform output tasks such
as writing bytes, closing streams, and flushing streams.
The OutputStream methods with a brief description are as follows:

1. void write(int b): The write() method writes the specified byte to the
output stream. It accepts an int value as an input parameter. It throws an
IOException if an I/O error occurs (e.g. output stream has been closed).
2. void write(byte[ ] b): This method writes all the specified bytes in the
array b to the output stream.
3. void write(byte[ ] b, int n, int m): It writes m bytes from array b starting
from nth byte to the output stream.
4. void close(): It closes the output stream and releases any system
resources associated with this stream.
5. void flush(): It flushes the output stream and forces any buffered output
bytes to be written out.
The Java Reader is the base class of all Reader's in the Java IO API. Subclasses include
a BufferedReader, PushbackReader, InputStreamReader, StringReader and several
others.
The Java Writer class is the base class of all Writers in the Java IO API. Subclasses
include BufferedWriter and PrintWriter among others.
Every language has some predefined streams for its users and Java
is one of these languages. Three Java Predefined streams or
standard streams are available in the java.lang.System class.
In Java, an IOException occurs when an input/output
operation fails or is interrupted. This can happen during
scenarios like reading from or writing to a file, network
communications, or when interacting with a file system.

FileNotFoundException
InterruptedIOException
CharConversionException
Closedconnectionexception
SocketException
ClassNotFoundException
What is a Client?
A client is a device or software that requests services or resources from
another program or computer (usually a server).
Examples: A mobile app asking for weather info is a client.
In Java, a program using Socket to connect to a server is a client.
What is a Server?
A server is a device or program that provides services or data to clients
upon request. It listens for incoming connections and responds.
Examples: A mail server delivers emails to clients.
In Java, a program using ServerSocket to listen on a port is a server.
The client-server architecture refers to a system that hosts, delivers,
and manages most of the resources and services that the client
requests. In this model, all requests and services are delivered over a
network, and it is also referred to as the networking computing model
or client server network.
1. First, the client sends their request via a
network-enabled device
2. Then, the network server accepts and
processes the user request
3. Finally, the server delivers the reply to
the client
A socket is one end-point of a two-way communication link between two
programs running on the network.
Server socket
A "server socket" is a type of socket used in network communication for server
applications, specifically designed to listen for incoming client connections and
establish communication channels.
1. Server:
Creates a server socket.
Binds the socket to a specific port (e.g., 8080).
Listens for incoming connections.
When a client connects, the server accepts the connection and
creates a new socket for that client.
The server communicates with the client through this new
socket.
2. Client:
Creates a socket.
Connects to the server's address and port.
Communicates with the server through the socket.
Closes the connection when done.
On the Server Side:
1) Create a Server Socket
The server opens a socket and binds it to a specific port to
listen for incoming client requests.
2) Wait for a Connection
The server remains in a waiting state, blocking until a client
tries to connect.
3) Accept the Connection
Once a client connects, the server accepts the connection and
establishes a communication link.
4) Establish Input and Output Streams
These streams allow the server to send and receive data to
and from the connected client.
5) Process the Request
The server reads the client’s message, performs necessary
processing, and sends a response back.
6) Close the Connection
Once communication is complete, the server closes the
connection (or keeps it open for further use).

soc.close(); // Socket (client or accepted socket on server)


On the Client Side:
1. Request a Connection
The client attempts to connect to the server by
specifying the server’s IP address and port number.
2.Establish Communication Streams
The client sets up input and output streams to
exchange data with the server.
3.Send a Request
The client sends a request or message to the server.
4.Receive a Response
The client waits and receives the server’s reply through
the input stream.
5.Close the Connection
After the interaction, the client closes the connection
properly.
Serialization in Java is the process of converting an object into a byte
stream so that the object can be easily saved to a file, transferred
over a network, or stored in memory. It allows the object's state to be
preserved and later reconstructed through deserialization.

To serialize an object in Java:


• The class must implement the java.io.Serializable interface.
• ObjectOutputStream is used to perform serialization.
• ObjectInputStream is used for deserialization.
Multithreaded Server: A server having more than one thread is
known as Multithreaded Server. When a client sends the request, a
thread is generated through which a user can communicate with the
server. We need to generate multiple threads to accept multiple
requests from multiple clients at the same time.
Think of it like this:
The server is a restaurant.
A socket is like a telephone line between the customer and the restaurant.
A thread is like a waiter who handles one customer's order.
So when many customers (clients) call the restaurant (server):
The restaurant needs many waiters (threads) to talk to them at the same time.
Each telephone line (socket) connects the customer and the waiter.
1. To Handle Multiple Clients Simultaneously
Imagine a server that gets requests from many users at the same time:
If you use a single-threaded server, only one client can be served at a time. Others have
to wait, which is inefficient and leads to timeouts.
A multithreaded server spawns a new thread for each client, so many clients can be
served at the same time . No client is blocked waiting for others
🔹 2. Parallel Processing of Requests
Each thread can handle a separate task like:
1. Receiving client data
2. Processing a request
3. Sending a response
While one thread waits for user input, others can keep working!
🔹 3. Better Resource Utilization
Java's thread management + modern multi-core CPUs
Multiple threads can run in parallel on different cores.
Java handles thread scheduling efficiently, using low-level OS features.
🔹 4. Scalability
As your application grows:
More users = more requests
A multithreaded server can scale much better than a single-threaded one
JDBC (Java Database Connectivity) is an
API in Java that enables applications to
interact with databases. It allows a Java
program to connect to a
database, execute queries, and retrieve
and manipulate data. By providing a
standard interface, JDBC ensures that
Java applications can work with
different relational databases like
MySQL, Oracle, PostgreSQL, and more.
Purpose:
Database Connectivity: JDBC provides the necessary tools
and classes for Java applications to establish connections
with various database systems.
SQL Execution: It allows Java applications to execute SQL
queries and commands to interact with the database, such
as retrieving data, inserting records, updating data, and
deleting records.
Result Handling: JDBC enables Java applications to process
the results received from the database in response to
queries.
1. JDBC-ODBC Bridge Driver
A JDBC driver that uses ODBC (Open Database Connectivity) to
connect Java applications to databases. It acts as a bridge
between the JDBC API and the ODBC driver. Easy to set up for
quick prototyping. Good for accessing older databases that only
support ODBC.

2. Native-API Driver
A JDBC driver that converts JDBC calls into native (C/C++) API
calls specific to the database. It uses a native library provided
by the database vendor. Better performance than Type 1 (JDBC-
ODBC), since it eliminates the ODBC layer. Supports advanced
database features through native calls.
3. Network Protocol Driver
A JDBC driver that sends JDBC calls to a middleware server,
which then communicates with the actual database. The driver
itself doesn’t interact directly with the database.
Pure Java – platform-independent.
Ideal for internet-based or distributed applications.
Can connect to multiple types of databases via the
middleware (DB independence).
Centralized configuration on the middleware simplifies client-
side setup.

4.Thin Driver
A pure Java JDBC driver that directly converts JDBC calls into
the database’s native protocol. Doesn’t require any native
libraries or middleware — it connects straight to the database.
100% Java – fully platform-independent.
High performance – no intermediate layer.
Easy to deploy – just include the driver .jar file.
Most modern databases provide these drivers.
Below are the steps that explains how to connect to Database in Java:
Step 1: Import the Packages
Step 2: Load the drivers using the forName() method
Step 3: Register the drivers using DriverManager
Step 4: Establish a connection using the Connection class object
Step 5: Create a statement
Step 6: Execute the query
Step 7: Close the connections
Use Byte-Oriented Streams when...
You are dealing with raw binary data, like:
•Images (e.g., .png, .jpg)
•Audio files (e.g., .mp3, .wav)
•Video files
•PDFs, Excel files, ZIP files, etc.
•Network data that isn’t text-based
•Basically: Anything that’s not plain text
Use Character-Oriented Streams when...
You are dealing with text data, like:
•.txt files
•.csv, .xml, .html files (that are human-readable)
•Text-based network protocols (e.g., HTTP, SMTP)
•Reading/writing from/to console (System.in, System.out)
•Internationalized text (Java handles encodings like UTF-8 for you)

1. What is a socket in networking?


2. What are the differences between a ServerSocket and a Socket in
Java?
3. Explain how a client sends a message to a server and waits for a
response using socket programming.
4. What is a BufferedReader and PrintWriter in the context of socket
programming?
BufferedReader:
Reads text data (characters) from an input stream.
Buffered: This means it reads large chunks of data at once, rather than reading one byte
at a time. This increases the efficiency of reading from the network (or any input stream).
Commonly Used for reading data received from the server (or client) over a socket
connection.
PrintWriter:
Writes text data (characters) to an output stream.
Buffered: Like BufferedReader, PrintWriter is buffered, meaning it writes large
chunks of data at once to increase efficiency. Commonly Used to send data
from the client to the server (or vice versa) in a text-based format.
Why We Use Events in Java
Events let different parts of a program talk to each other when
something happens, like:
•A button is clicked
•A key is pressed
•A window is closed

Listener vs Adapter - Simple Difference


Listener Interface:
Like a contract saying "you must handle all these events"
You have to write code for every single event, even if you don't
need it
Adapter Class:
Like a helper that says "you only need to handle the events you
care about"
It provides empty methods for all events, so you can just fill in
the ones you need
JNI (Java Native Interface) is a framework that allows Java code running in
the Java Virtual Machine (JVM) to interact with native applications and
libraries written in languages like C, C++, or assembly. It enables Java to
leverage the performance of native code or interact with platform-
specific features that Java alone cannot access.
How JNI Works:
1.Java Code Calls Native Code: Java code uses the native keyword to declare
methods that are implemented in native languages (like C or C++).
2.Native Code Calls Java Code: Native code can also call Java methods using the JNI
functions.
3.JNI Bridge: The interaction between Java and native code happens through the JNI
API, which provides a set of functions to access native code from Java and vice versa.

Java Collections are a framework in Java that provides


architecture to store and manipulate groups of objects. Think
of it like a toolkit that helps you work with data structures like
lists, sets, maps, and queues, without having to build them
from scratch.

You might also like