Assignment on Generics, Lambda Expressions, and NIO Classes in Java
1. Introduction
Java is a widely-used object-oriented programming language that offers powerful features to simplify
code development and make applications more flexible and robust. Among its many features,
Generics, Lambda Expressions, and the New Input/Output (NIO) package play an essential role in
writing scalable and efficient code.
This assignment explores the concepts, syntax, and applications of Generics, Lambda Expressions,
and NIO classes in Java, along with examples to clarify their use in real-world programming.
2. Generics in Java
2.1 What Are Generics?
Generics were introduced in Java 5 as a way to enable type-safe programming. They allow you to
write a single class, interface, or method that can work with different types of data, while ensuring
type safety during compile time.
2.2 Why Use Generics?
- Code Reusability: One generic class or method can handle different data types.
- Type Safety: Prevents ClassCastException at runtime.
- Compile-Time Checking: Detects type errors early.
2.3 Syntax of Generics
class Box<T> {
private T value;
public void set(T value) { this.value = value; }
public T get() { return value; }
}
2.4 Generic Methods
public <T> void printArray(T[] array) {
for (T element : array) {
System.out.println(element);
2.5 Bounded Type Parameters
class NumberBox<T extends Number> {
private T number;
public void setNumber(T number) { this.number = number; }
public double doubleValue() { return number.doubleValue(); }
3. Lambda Expressions in Java
3.1 What Is a Lambda Expression?
Lambda expressions were introduced in Java 8 to provide functional programming capabilities. They
enable you to write concise and readable implementations of functional interfaces.
3.2 Syntax of Lambda Expression
(parameters) -> expression
Example:
(int a, int b) -> a + b;
3.3 Lambda with Functional Interfaces
@FunctionalInterface
interface MathOperation {
int operation(int a, int b);
public class LambdaExample {
public static void main(String[] args) {
MathOperation addition = (a, b) -> a + b;
System.out.println("Sum: " + addition.operation(5, 3));
3.4 Benefits of Lambda Expressions
- Concise and readable code
- Supports functional programming
- Useful for iterating over collections (e.g., with streams)
3.5 Lambda with Collections
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
names.forEach(name -> System.out.println(name));
4. Java NIO (New Input/Output)
4.1 Introduction to NIO
Java NIO (New Input/Output), introduced in Java 1.4 and enhanced in Java 7 (NIO.2), provides a
more efficient and scalable way to perform I/O operations.
4.2 Key Components of NIO
- Buffers: Containers for data.
- Channels: Connections to entities (files, sockets).
- Selectors: Allow a single thread to monitor multiple channels.
4.3 Working with Buffers
ByteBuffer buffer = ByteBuffer.allocate(1024);
buffer.put("Hello NIO".getBytes());
buffer.flip();
while (buffer.hasRemaining()) {
System.out.print((char) buffer.get());
4.4 Working with Channels
RandomAccessFile file = new RandomAccessFile("example.txt", "rw");
FileChannel channel = file.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(48);
int bytesRead = channel.read(buffer);
while (bytesRead != -1) {
buffer.flip();
while (buffer.hasRemaining()) {
System.out.print((char) buffer.get());
buffer.clear();
bytesRead = channel.read(buffer);
file.close();
4.5 NIO.2 (Path, Files, and DirectoryStream)
Reading a File:
Path path = Paths.get("example.txt");
List<String> lines = Files.readAllLines(path);
lines.forEach(System.out::println);
Writing to a File:
Path path = Paths.get("output.txt");
Files.write(path, Arrays.asList("Line 1", "Line 2"), StandardCharsets.UTF_8);
5. Comparison and Use Cases
Feature | Generics | Lambda Expressions | NIO
-----------------|------------------|-------------------------|-----------------
Purpose | Type safety & reusability | Functional programming | Efficient I/O
Introduced In | Java 5 | Java 8 | Java 1.4 / 7
Common Use | Collections | Streams, events | File I/O, sockets
Syntax Example | class Box<T> | (a, b) -> a + b | Files.readAllLines()
6. Conclusion
Generics, Lambda Expressions, and the NIO classes are integral components of modern Java
programming. Generics ensure type safety and code reusability, Lambda Expressions make the
code more expressive and readable, and NIO provides high-performance I/O capabilities.