Java is a robust and versatile programming language, and as you advance in your Java journey, you’ll encounter powerful features that make the language even more powerful and efficient. In this blog, we’ll explore some of the advanced Java features, including
- Generics
- Collections Framework
- Lambda Expressions
- Streams API
- Multi-threading
1. Generics in Java
Generics allow you to write more flexible and reusable code by enabling classes, interfaces, and methods to operate on objects of various types while providing compile-time type safety. Instead of using Object
and performing casting, Generics ensure that type-related errors are caught at compile time.
Example:
// Generic class
class Box<T> {
private T value;
public T getValue() {
return value;
}
public void setValue(T value) {
this.value = value;
}
}
// Usage
Box<Integer> intBox = new Box<>();
intBox.setValue(10);
System.out.println(intBox.getValue()); // Output: 10
Box<String> strBox = new Box<>();
strBox.setValue("Hello");
System.out.println(strBox.getValue()); // Output: Hello