Java 8 Features
1. Lambda Expressions:
Before Java 8, we often used anonymous inner classes to implement functional interfaces.
Before Java 8:-
Runnable r = new Runnable(){
@Override
public void run(){
System.out.println("Hello");
}
};
Java 8:-
Runnable r = () -> System.out.println("Hello");
Lambda expressions allow us to write concise implementations of functional interfaces.
2. Stream API:
Stream API helps process collections of data using operations like filter(), map(), sorted(), and collect().
List<Integer> numbers = List.of(10, 20, 30, 40, 50);
List<Integer> result = numbers.stream()
.filter(n -> n > 20)
.toList();
System.out.println(result);
Output :- [30, 40, 50]
3. Functional Interfaces:
-
Predicate<T>-> Tests a condition and returns a boolean. -
Function<T, R>-> Accepts input and produces output. -
Consumer<T>-> Accepts input and consumes it. -
Supplier<T>-> Supplies a value.
4. Optional Class:
Helps represent potentially missing values and reduces direct null handling.
Optional<String> name = Optional.ofNullable(null);
System.out.println(name.orElse("Guest"));
Output -> Guest
5. Default and Static Methods in Interfaces:
Before Java 8, interfaces could not contain implemented instance methods.
interface Payment{
void pay();
default void paymentStatus(){
System.out.println("Payment Successful");
}
static void info(){
System.out.println("Payment Service");
}
}
6. Date and Time API:
Introduced the modern java.time package.
LocalDate date = LocalDate.now();
LocalTime time = LocalTime.now();
LocalDateTime dateTime = LocalDateTime.now();
Other Improvements Include:
-> Method references.
-> CompletableFuture.
-> Base64 API.
-> Parallel Streams.
Java 17 Features
1. Records:
Records simplify the creation of classes that primarily store data.
Before Java 17:-
public class Student{
private final String name;
private final int age;
public Student(String name, int age){
this.name = name;
this.age = age;
}
public String getName(){
return name;
}
public int getAge(){
return age;
}
}
Java 17:-
public record Student(String name, int age){}
Java automatically generates:
-> Constructor.
-> Getters (accessor methods named name() and age()).
-> equals().
-> hashCode().
-> toString().
2. Sealed Classes:
Sealed classes allow you to control which classes can extend a particular class.
public sealed class Payment permits UpiPayment, CardPayment{}
final class UpiPayment extends Payment{}
final class CardPayment extends Payment{}
Note :- Only permitted classes can directly extend Payment.
3. Pattern Matching for instanceof:
Before:-
if(obj instanceof String){
String str = (String)obj;
System.out.println(str.length());
}
Java 17:-
if(obj instanceof String str){
System.out.println(str.length());
}
4. Text Blocks:
Useful for writing multiline strings, especially SQL and JSON.
String json = """
{
"name" : "Joe",
"age" : 22
}
""";
5. Switch Expressions:
Before:-
String result;
switch(day){
case 1:
result = "Monday";
break;
case 2:
result = "Tuesday";
break;
default:
result = "Invalid";
}
Java 17:-
String result = switch(day){
case 1 -> "Monday";
case 2 -> "Tuesday";
default -> "Invalid";
};
Other Improvements:
-> Strong encapsulation of JDK internals.
-> Improved garbage collectors.
-> Foreign Function and Memory API (included in Java 17 as an incubator feature).
-> Enhanced pseudorandom number generators.
Java 21 Features
1. Virtual Threads:
Traditional Java threads are generally backed by operating system threads. Creating and managing a very large number of platform threads can be expensive.
Virtual threads are lightweight threads managed by the JVM.
public class Main {
public static void main(String[] args) throws InterruptedException {
Thread thread = Thread.startVirtualThread(() -> {
System.out.println("Running the virtual thread");
});
}
}
-> You can also create virtual threads using an executor.
import java.util.concurrent.Executors;
public class Main {
public static void main(String[] args) {
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 1000; i++) {
executor.submit(() -> {
System.out.println("Task running");
return null;
});
}
}
}
}
2. Record Patterns:
Java 21 allows you to extract values directly from records using patterns.
record Student(String name, int age){}
public class Main{
public static void main(String[] args){
Object obj = new Student("Ayush", 22);
if(obj instanceof Student(String name, int age)){
System.out.println(name);
System.out.println(age);
}
}
}
-> This avoids manually accessing record components after checking their type.
3. Pattern Matching for switch:
Java 21 made pattern matching for switch a permanent feature.
static String check(Object obj){
return switch(obj){
case Integer i -> "Integer: " + i;
case String s -> "String: " + s;
case Double d -> "Double: " + d;
case null -> "Null Value";
default -> "Unknown Type";
};
}
-> Now, switch can work with different object types, not just traditional primitive values and enums.
4. Sequenced Collections:
Java 21 introduced interfaces for collections with a defined encounter order.
Examples:-
SequencedCollectionSequencedSetSequencedMap
We can easily access the first and last elements.
SequencedCollection<String> names = new ArrayList<>();
names.add("Ayush");
names.add("Rahul");
names.add("Amit");
System.out.println(names.getFirst());
System.out.println(names.getLast());
System.out.println(names.reversed());
Top comments (0)