0% found this document useful (0 votes)
75 views35 pages

PBLJ Chapter 5

Chapter 5 covers Wrapper Classes, I/O Streams, and Lambda Expressions in Java. It explains the purpose and methods of wrapper classes for primitive types, file handling operations, stream classes, and object serialization, including autoboxing and unboxing. Additionally, it introduces lambda expressions for cleaner code and functional programming concepts.

Uploaded by

singhmaanvi779
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)
75 views35 pages

PBLJ Chapter 5

Chapter 5 covers Wrapper Classes, I/O Streams, and Lambda Expressions in Java. It explains the purpose and methods of wrapper classes for primitive types, file handling operations, stream classes, and object serialization, including autoboxing and unboxing. Additionally, it introduces lambda expressions for cleaner code and functional programming concepts.

Uploaded by

singhmaanvi779
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/ 35

Chapter 5 (UNIT 2)

Wrapper Classes, I/O Streams and Lambda Expression

(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

What is a Wrapper Class?


A wrapper class in Java is used to convert primitive data types into objects. Java provides wrapper classes for all
eight primitive data types.
The package java.lang contains several classes that function as the wrappers for the primitives. These
are Byte, Short, Integer, Long, Float, Double, Character, and Boolean.

Why use wrapper classes?


• Allow primitive data types to be used as objects (e.g., in collections like ArrayList<Integer>).
• Provide utility methods for operations like parsing (Integer.parseInt()), conversions, and
comparisons.
• Support autoboxing and unboxing, which automatically converts primitives to objects and vice versa.
Inheritance Hierarchy of Wrapper Classes
Wrapper Classes for Primitive Data Types

Primitive Type Wrapper Class


byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean
Wrapper Classes Method

Method Wrapper Class Purpose Example

int value = Integer.parseInt("123");


Integer, Double,
parseXxx(String s) Converts String to primitive type double d = Double.parseDouble("3.14");
Boolean, etc.
boolean b = Boolean.parseBoolean("true");

Integer, Double, Integer obj1 = Integer.valueOf(50);


valueOf(Xxx) Converts primitive/String to Wrapper Object
etc. Integer obj2 = Integer.valueOf("100");

Integer obj = 42;


Integer, Double,
xxxValue() Converts Wrapper Object to primitive int primitive = obj.intValue();
etc.
float f = obj.floatValue();
Integer a = 10, b = 20;
Integer, Double,
compareTo(Xxx) Compares two Wrapper Objects System.out.println(a.compareTo(b)); //
etc.
Output: -1
Wrapper Classes Method

Method Wrapper Class Purpose Example


Integer x = 50, y = 50;
equals(Object obj) Integer, Double, etc. Checks equality of two Wrapper Objects
System.out.println(x.equals(y)); // true
Integer num = 123;
toString() Integer, Double, etc. Converts Wrapper Object to String
System.out.println(num.toString()); // "123"
Double d = Double.NaN;
isNaN() Float, Double Checks if value is NaN
System.out.println(d.isNaN()); // true
double d = 1.0 / 0;
isInfinite() Float, Double Checks if value is infinite System.out.println(Double.isInfinite(d)); //
true
Integer num = 100;
hashCode() Integer, Double, etc. Returns hash code of the object
System.out.println(num.hashCode());
byteValue(), shortValue(), Integer obj = 42;
longValue(), floatValue(), Integer, Double, etc. Converts Wrapper to different primitive types byte b = obj.byteValue();
doubleValue() long l = obj.longValue();
Character Wrapper Classes Method
Method Purpose Example
Checks if the character has a defined
isDefined(char ch) System.out.println(Character.isDefined('©')); // true
Unicode value
isDigit(char ch) Checks if the character is a digit (0-9) System.out.println(Character.isDigit('5')); // true
Checks if the character is a letter (A-Z,
isLetter(char ch) System.out.println(Character.isLetter('A')); // true
a-z)
isLetterOrDigit(char Checks if the character is a letter or a
System.out.println(Character.isLetterOrDigit('8')); // true
ch) digit
isLowerCase(char Checks if the character is lowercase (a-
System.out.println(Character.isLowerCase('b')); // true
ch) z)
isUpperCase(char Checks if the character is uppercase (A-
System.out.println(Character.isUpperCase('Z')); // true
ch) Z)
Checks if the character is a space
isSpaceChar(char
character (e.g., normal space, no-break System.out.println(Character.isSpaceChar(' ')); // true
ch)
space)
isWhitespace(char Checks if the character is a whitespace
System.out.println(Character.isWhitespace('\n')); // true
ch) character (space, tab, newline, etc.)
toLowerCase(char
Converts the character to lowercase System.out.println(Character.toLowerCase('A')); // a
ch)
toUpperCase(char
Converts the character to uppercase System.out.println(Character.toUpperCase('b')); // B
ch)
Autoboxing & Unboxing (Automatic Conversion)

Java automatically converts between primitives and wrapper objects, reducing manual
conversions.

1) Autoboxing (Primitive → Object)

Integer obj = 10; // Automatically converts int to Integer (Autoboxing)

2) Unboxing (Object → Primitive)

int num = obj; // Automatically converts Integer to int (Unboxing)


Example public class AutoboxingUnboxing {
public static void main(String[] args) {
// Autoboxing: Converting primitive to Wrapper class
int num = 10;
Integer obj = num; // Autoboxing (int → Integer)
System.out.println("Autoboxing: " + obj);
// Unboxing: Converting Wrapper class to primitive
Output:
Integer obj2 = Integer.valueOf(20);
Autoboxing: 10
int num2 = obj2; // Unboxing (Integer → int) Unboxing: 20
System.out.println("Unboxing: " + num2); Sum using Unboxing: 16.0
// Autoboxing with collections
java.util.ArrayList<Double> list = new java.util.ArrayList<>();
list.add(10.5); // Autoboxing (double → Double)
list.add(5.5);
// Unboxing while retrieving from collection
double sum = list.get(0) + list.get(1); // Unboxing (Double → double)
System.out.println("Sum using Unboxing: " + sum);
}
}
File Handling

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.

File Handling Operations:


• Creating a File: Use the File class and its createNewFile() method.
• Writing to a File: Utilize FileWriter or BufferedWriter to write data efficiently.
• Reading from a File: Use Scanner or BufferedReader for reading file contents.
• Deleting a File: Apply the delete() method of the File class to remove a file.
Stream Classes (File Handling)
What is a Stream in Java?
Java uses a concept of Stream for such tasks related to file

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.

• Character Streams (for text data, e.g., files, keyboard input)


• Character streams handle text-based data using Reader and Writer
classes.
Byte Stream

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:

Processes raw binary data (images, audio, video, etc.).


Works with 8-bit bytes for efficiency.
Commonly uses FileInputStream & FileOutputStream for file
handling.
InputStream (Reading Data) Method
InputStream is an abstract class that defines Java’s model of streaming byte input.
Method Description
Reads one byte of data. Returns -1 if end of stream is
int read()
reached.
Reads data into a byte array. Returns number of bytes
int read(byte[] b)
read.

int read(byte[] b, int off, int len) Reads up to len bytes into b starting from off.

void close() Closes the stream and releases resources.

int available() Returns the number of available bytes in the stream.

void mark(int readlimit) Marks a position in the stream for reset.

void reset() Resets the stream to the marked position.

boolean markSupported() Checks if mark/reset is supported.


long skip(long n) Skips n bytes in the stream.
OutputStream (Writing Data) Method
OutputStream is an abstract class that defines streaming byte output.

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);

ByteArrayOutputStream (Writing to Byte Array)


• Writes data to a byte array instead of a file.
• Useful for modifying, compressing, or buffering data in memory before writing to disk or network.
Syntax
ByteArrayOutputStream baos = new ByteArrayOutputStream();
BufferedInputStream & BufferedOutputStream
Buffered Streams improve performance by reducing the number of I/O operations. Instead of
reading/writing one byte at a time, they use a buffer (default: 8192 bytes)

BufferedInputStream (Reading Data)


BufferedInputStream bis = new BufferedInputStream(new FileInputStream("filename.txt"));

BufferedOutputStream (Writing Data)


BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("filename.txt"));
Character Stream

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.

Key Classes for Character Streams:


• Input: FileReader, BufferedReader
• Output: FileWriter, BufferedWriter
Reader Class (Reading Data) Method
Reader is an abstract class that defines Java’s model of streaming character input. It implements the
Closeable and Readable interfaces.

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);

CharacterArrayWriter (Writing to a Character Array)


FileWriter (Writing to a File) • Stores character data in memory, similar to
• Writes character-by-character into a file. StringWriter.
• The contents can be converted into a char[] or String.
• Can overwrite or append data.
Syntax
Syntax CharArrayWriter caw = new CharArrayWriter();
FileWriter fw = new FileWriter("filename.txt");
Object Serialization

Serialization is the process of converting an object into a byte stream so it can be


saved to a file, sent over a network, or stored in a database. The reverse process,
deserialization, converts the byte stream back into an object.
Why Use Serialization?
Save object state to a file or database
Send objects over a network (e.g., RMI, Web Services)
Store objects in a cache or transfer them between processes
How to Serialize an Object?
• The class must implement the Serializable interface (a marker interface with no
methods).
• Use ObjectOutputStream to write the object to a file.
• Use ObjectInputStream to read the object back.
Object Serialization
import java.io.*; public class SerializationExample {

// Step 1: Implement Serializable public static void main(String[] args) throws Exception {

class Person implements Serializable { Person p = new Person("Alice", 30);


// Serialization: Writing the object to a file
String name;
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("person.ser"));
int age;
out.writeObject(p);
out.close();
Person(String name, int age) {
// Deserialization: Reading the object from a file
this.name = name; ObjectInputStream in = new ObjectInputStream(new FileInputStream("person.ser"));
this.age = age; Person newPerson = (Person) in.readObject();
} in.close();
} System.out.println(newPerson.name + " - " + newPerson.age);
}
}
Tranisent Keyword

• 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).

transient String password; // Will NOT be serialized

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

Cloning Type Description


Copies only references for objects inside the class. Changes in
Shallow Copy
cloned object affect the original.
Creates new instances for each object, ensuring cloned object is
Deep Copy
independent.
Lambda Expression
A lambda expression is a short way to define anonymous functions in Java. It allows passing behavior
as a parameter, making code cleaner and more readable.
Syntax:
(parameters) -> expression or (parameters) -> { statements }

interface MyFunction {
void showMessage(String message);
}

public class LambdaExample {


public static void main(String[] args) {
MyFunction msg = (message) -> System.out.println("Message: " + message);
msg.showMessage("Hello, Lambda!");
}
} Message: Hello, Lambda! //Output
Functional Interfaces

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

Method references allow calling an existing method using :: operator.

class Printer {
static void printMessage(String message) {
System.out.println("Message: " + message);
}
}

public class MethodReferenceExample {


public static void main(String[] args) {
MyFunction ref = Printer::printMessage; // Method Reference
ref.showMessage("Hello, Method Reference!");
} Message: Hello, Method Reference!
}
Method References: Types

Type Syntax Example

Static Method ClassName::methodName Math::sqrt

Instance Method instance::methodName System.out::println

Constructor ClassName::new ArrayList::new


Stream Operation: Sorting, Filtering, Mapping, Reducing

Streams provide functional-style processing of collections.

Operation Description Example


Sorting Sort elements list.stream().sorted()
Keep elements matching a
Filtering list.stream().filter(x -> x > 10)
condition
Mapping Convert elements list.stream().map(x -> x * 2)
list.stream().reduce(0,
Reducing Aggregate results
Integer::sum)
Stream Operation: Sorting, Filtering, Mapping,
Reducing
import java.util.*; // Mapping (square each number)

import java.util.stream.*; List<Integer> mapped = numbers.stream().map(n -> n * n).collect(Collectors.toList());


public class StreamOperationsExample { System.out.println("Mapped: " + mapped);

public static void main(String[] args) {

List<Integer> numbers = Arrays.asList(10, 5, 20, 15, 25); // Reducing (sum of numbers)

// Sorting int sum = numbers.stream().reduce(0, Integer::sum);


List<Integer> sorted = numbers.stream().sorted().collect(Collectors.toList()); System.out.println("Reduced (Sum): " + sum);

System.out.println("Sorted: " + sorted); }


}
// Filtering (numbers > 10)

List<Integer> filtered = numbers.stream().filter(n -> n > 10).collect(Collectors.toList());

System.out.println("Filtered: " + filtered);

Sorted: [5, 10, 15, 20, 25]


Filtered: [15, 20, 25]
Mapped: [100, 25, 400, 225, 625]
Reduced (Sum): 75
Questions
• What is the purpose of wrapper classes in Java? Explain with an example.
• Differentiate between autoboxing and unboxing with an example.
• How do you convert a String to an int and vice versa using wrapper classes?
• Explain the concept of parseXXX() methods in wrapper classes. Give an example.
• What is the Stream API in Java, and how is it different from collections?
• How can you filter even numbers from a list using streams? Provide a code snippet.
• Write a Java program to find the maximum number from a list using streams.
• What is the difference between Byte Streams and Character Streams in Java?
• What is a functional interface? Name some built-in functional interfaces in Java.
• What is a lambda expression in Java? How does it improve code readability?

You might also like