PBLJ Chapter 5
PBLJ Chapter 5
(Use of Wrapper Class, Integer, Character, Long, Boolean, Autoboxing, Unboxing, Byte stream, character
stream, Object serialization, cloning, Introduce lambda syntax, functional interfaces, method
references, stream operations, sorting, filtering, mapping, reducing.)
Wrapper Classes
Java automatically converts between primitives and wrapper objects, reducing manual
conversions.
File handling in Java involves managing and manipulating file contents, including
reading and writing data. The java.io package provides essential classes for
handling various file formats, where a File object is used to specify the
destination for input and output operations.
A Stream in Java is used for reading from or writing to a source, such as files, network
connections, or memory buffers. It is part of Java's I/O system (java.io package).
• Input Stream: Reads data from a source using a sequence of objects and pipelines.
• Output Stream: Writes data to a destination through a structured flow of objects.
Streams Class Hierarchy
Types of Stream Classes in Java
Java provides two types of streams for handling input and output (I/O):
• Byte Streams (for binary data, e.g., images, audio, video)
• Byte streams handle raw binary data using InputStream and
OutputStream.
A Byte Stream is used to read and write binary data (e.g., images, audio,
video, and files) one byte at a time in Java.
Key Points:
int read(byte[] b, int off, int len) Reads up to len bytes into b starting from off.
Method Description
void write(int b) Writes a single byte to the stream.
void write(byte[] b) Writes an entire byte array to the stream.
void write(byte[] b, int off, int len) Writes len bytes from array b starting at off.
void flush() Forces any buffered data to be written out.
void close() Closes the stream and releases resources.
FileInputStream & FileOutputStream
import java.io.*;
public class ByteStreamExample {
public static void main(String[] args) throws IOException {
FileInputStream is a byte stream class
// Writing to a file
used to read/write binary data (text,
FileOutputStream fos = new FileOutputStream("test.txt");
images, audio, etc.) from a file byte by
fos.write("Hello, Byte Stream!".getBytes());
byte.
fos.close();
// Reading from a file
FileInputStream fis = new FileInputStream("test.txt"); Output:
int i; Hello, Byte Stream!
while ((i = fis.read()) != -1) {
System.out.print((char) i);
}
fis.close();
}
}
ByteArrayInputStream & ByteArrayOutputStream
The ByteArrayInputStream and ByteArrayOutputStream classes in Java are used for handling byte
arrays as input and output streams instead of files. These classes work in memory (RAM), making them
faster than file-based streams.
ByteArrayInputStream (Reading from Byte Array)
• Reads data from a byte array as an input stream.
• Used for processing data in memory without accessing files.
Syntax
ByteArrayInputStream bais = new ByteArrayInputStream(byteArray);
Character Streams in Java are used to read and write text data (i.e., character-
based data). Unlike Byte Streams, which handle data in 8-bit bytes, Character
Streams work with 16-bit Unicode characters, making them suitable for
reading and writing text files.
Method Description
Reads a single character (returns -1 if EOF
int read()
reached).
int read(char[] cbuf) Reads characters into an array.
boolean ready() Returns true if stream is ready to be read.
Marks the current position for a future
void mark(int readAheadLimit)
reset.
void reset() Resets stream to the marked position.
void close() Closes the stream.
Writer Class (Reading Data) Method
Writer is an abstract class that defines streaming character output. It implements the Closeable, Flushable, and
Appendable interfaces.
Method Description
void write(int c) Writes a single character.
void write(char[] cbuf) Writes an array of characters.
void write(String str) Writes a string.
Forces writing buffered data to the
void flush()
output.
void close() Closes the stream.
FileReader & FileWriter CharacterArrayReader &
CharacterArrayWriter
FileReader (Reading from a File) CharacterArrayReader (Reading from a Character Array)
• Reads character-by-character from a file. •Reads character data from an in-memory character
• Best for text-based files. array.
•Works similarly to StringReader but for arrays.
Syntax Syntax
FileReader fr = new FileReader("filename.txt"); CharArrayReader car = new CharArrayReader(charArray);
// Step 1: Implement Serializable public static void main(String[] args) throws Exception {
• The transient keyword is used in serialization to indicate that a field should not be saved
when an object is serialized.
• When an object is deserialized, transient fields are set to their default values (e.g., null
for objects, 0 for numbers).
Why Use transient?
To protect sensitive data (e.g., passwords, security keys).
To avoid serializing non-essential fields (e.g., calculated fields, cache data).
To prevent serialization of objects that don’t support Serializable (e.g., Thread,
Socket).
The password field is transient, so it’s lost after serialization (set to null).
Clone Student s1 = new Student("Alice");
Student s2 = (Student) s1.clone(); // Cloning
System.out.println(s1.name); // Alice
System.out.println(s2.name); // Alice
• Cloning creates an exact copy of an object.
• Java provides shallow cloning using the clone() method of the Object class.
• To enable cloning, a class must implement Cloneable and override clone().
Types of Cloning
interface MyFunction {
void showMessage(String message);
}
A functional interface is an interface in Java that contains only one abstract method but can have
multiple default and static methods. It is mainly used for lambda expressions and method
references.
Introduced in Java 8, functional interfaces enable functional programming in Java.
Declaring a Functional Interface
A functional interface can be declared using the @FunctionalInterface annotation (optional but
recommended).
@FunctionalInterface
interface MyFunction {
void displayMessage(String message);
}
The @FunctionalInterface annotation ensures the interface contains only one abstract method.
Annotation
An annotation in Java is a metadata tag that provides additional information about the code but does not
change its behavior. Annotations are used for compilation checks, runtime processing, and code
documentation.
Java provides some predefined annotations, categorized as Marker, Single-Value, and Multi-Value
annotations.
Annotation Description
@Override Ensures that a method overrides a superclass method
@Deprecated Marks a method/class as obsolete
@SuppressWarnings Hides compiler warnings
@FunctionalInterface Ensures an interface is functional (one abstract method)
@SafeVarargs Prevents warnings for varargs methods
Method References
class Printer {
static void printMessage(String message) {
System.out.println("Message: " + message);
}
}