Java 10 Features with Examples

In this article, I will share new Java 10 features with examples. These are; var keyword and some Collectors API changes. Let’s get started!

Var Keyword in Java 10

First, we will start with the var keyword. We can use the var keyword only in declarations. It is not allowed for null and cannot be used for parameters or return types. It is not a reserved keyword. We cannot use var for Lambda declarations. Let’s do sample examples. As you can see in the examples below, we declared several var variables as integer, list, map, and string. I also showed that we cannot use var in lambda expressions, and it cannot be null.

@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class Java10Features {

    /**
     * We can use var only in declarations. It is not allowed for null and cannot be used for parameters or return types.
     * It is not a reserved keyword.
     * We cannot use var for Lambda declarations.
     */
    @Test
    @Order(1)
    public void varTest() {
        var number = 20;
        var numberList = List.of(1, 2, 3, 4);
        var footballerMap = Map.of(1, "Ronaldo", 2, "Messi");
        var var = "SW Test Academy!"; //Var is not a reserved keyword.

        //var text = null; -> null is not allowed for var declaration.
        //var multiply = (number) -> number * number; //Var is not allowed for lambda declarations!

        System.out.println(number);
        System.out.println(numberList);
        System.out.println(footballerMap);
        System.out.println(var);
    }
}

Output

var keyword in java

Collectors API Changes in Java 10

In java 10, the Collectors class has toUnmodifiableList() method. It does not let us modify a list.  We can see this in the example below. By using the toUnmodifiableList() method, we made list2 as an unmodifiable list. After this, when we tried to modify the list2, we got an UnsupportedOperationException exception. For list3, we used the toList() method and which made list3 a modifiable list. After this, when we tried to add a new value to list3. We did not get any errors.

@Test
@Order(2)
public void collectorsAPITest() {
    var list1 = List.of(1,2,3);

    var list2 = list1.stream()
        .map(number -> number*number)
        .collect(Collectors.toUnmodifiableList());

    Assertions.assertThrows(UnsupportedOperationException.class, () -> list2.add(5)); //Throws exception.

    var list3 = list1.stream()
        .map(number -> number*number)
        .collect(Collectors.toList());
    list3.add(5);

    Assertions.assertTrue(list3.contains(5));
}

Output

java 10 collectors api changes

GitHub Project

Java10Features.java

In this article, I shared the new changed Java 10 features like var keyword and Collectors API method changes such as toUnmodifiableList() method.

Thanks for reading,
Onur Baskirt

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.