DEV Community

Ayush Verma
Ayush Verma

Posted on Edited on

Java 8, 17 & 21 Features

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");
     }
};
Enter fullscreen mode Exit fullscreen mode

Java 8:-

Runnable r = () -> System.out.println("Hello");
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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"));
Enter fullscreen mode Exit fullscreen mode

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");
      }
}
Enter fullscreen mode Exit fullscreen mode

6. Date and Time API:

Introduced the modern java.time package.

LocalDate date = LocalDate.now();
LocalTime time = LocalTime.now();
LocalDateTime dateTime = LocalDateTime.now();
Enter fullscreen mode Exit fullscreen mode

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;
      }
}
Enter fullscreen mode Exit fullscreen mode

Java 17:-

public record Student(String name, int age){}
Enter fullscreen mode Exit fullscreen mode

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{}
Enter fullscreen mode Exit fullscreen mode

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());
}
Enter fullscreen mode Exit fullscreen mode

Java 17:-

if(obj instanceof String str){
       System.out.println(str.length());
}
Enter fullscreen mode Exit fullscreen mode

4. Text Blocks:

Useful for writing multiline strings, especially SQL and JSON.

String json = """
             {
                 "name" : "Joe",
                 "age" : 22
             }
         """;
Enter fullscreen mode Exit fullscreen mode

5. Switch Expressions:

Before:-

String result;

switch(day){
     case 1:
         result = "Monday";
         break;
     case 2:
         result = "Tuesday";
         break;
     default:
         result = "Invalid";
}
Enter fullscreen mode Exit fullscreen mode

Java 17:-

String result = switch(day){
       case 1 -> "Monday";
       case 2 -> "Tuesday";
       default -> "Invalid";
};
Enter fullscreen mode Exit fullscreen mode

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");
        });
    }
}
Enter fullscreen mode Exit fullscreen mode

-> 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;
                });
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

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);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

-> 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";
      };
}
Enter fullscreen mode Exit fullscreen mode

-> 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:-

  • SequencedCollection
  • SequencedSet
  • SequencedMap

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());
Enter fullscreen mode Exit fullscreen mode

Top comments (0)