Stay Ahead of the Curve: Get Access to the Latest Software Engineering Leadership and Technology Trends with Our Blog and Article Collection!


Select Desired Category


Java 17 Feature Examples


Some detailed examples that demonstrate the use of the Java 17 features:

  1. Sealed Classes
public sealed class Animal permits Cat, Dog {
    private String name;
    private int age;

    public Animal(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public void makeSound() {
        System.out.println("Animal is making a sound");
    }
}

final class Cat extends Animal {
    public Cat(String name, int age) {
        super(name, age);
    }

    @Override
    public void makeSound() {
        System.out.println("Meow!");
    }
}

non-sealed class Dog extends Animal {
    public Dog(String name, int age) {
        super(name, age);
    }

    @Override
    public void makeSound() {
        System.out.println("Woof!");
    }
}

public class SealedClassesExample {
    public static void main(String[] args) {
        Animal cat = new Cat("Fluffy", 2);
        Animal dog = new Dog("Buddy", 3);

        cat.makeSound();
        dog.makeSound();
    }
}

In this example, we have a sealed Animal class that is extended by two classes Cat and Dog. The Cat and Dog classes override the makeSound() method to make animal-specific sounds. We create instances of Cat and Dog and call their makeSound() methods to demonstrate polymorphism.

  1. Pattern Matching for instanceof
public class PatternMatchingExample {
    public static void main(String[] args) {
        Object obj = "Hello, World!";

        if (obj instanceof String s && s.length() > 0) {
            System.out.println(s.toUpperCase());
        } else {
            System.out.println("Object is not a non-empty string");
        }
    }
}

In this example, we have an Object variable obj that we check if it is an instance of a non-empty String. If the check succeeds, we cast obj to String and call the toUpperCase() method. If the check fails, we print a message indicating that the object is not a non-empty string.

  1. switch Expressions with yield
public class SwitchExpressionExample {
    public static void main(String[] args) {
        DayOfWeek day = DayOfWeek.WEDNESDAY;

        int result = switch (day) {
            case MONDAY, TUESDAY -> {
                int a = 5;
                int b = 10;
                yield a + b;
            }
            case WEDNESDAY -> 20;
            default -> throw new IllegalStateException("Unexpected value: " + day);
        };

        System.out.println(result);
    }
}

In this example, we have a DayOfWeek variable day that we use in a switch expression. We have three cases – for MONDAY and TUESDAY, we calculate the sum of two numbers using the yield keyword, for WEDNESDAY, we return a fixed value of 20, and for all other days, we throw an exception. We store the result of the switch expression in a variable result and print it to the console.

  1. Stream Improvements
public class StreamImprovementsExample {
    public static void main(String[] args) {
        List<String> list = List.of("foo", "bar", "baz", "hello", "world");

        Stream<String> stream1 = list.stream().takeWhile(s -> s.length() < 4);
        stream1.forEach(System.out::println); // Output: foo, bar

        Stream<String> stream2 = list.stream().dropWhile(s -> s.length() < 4);
        stream2.forEach(System.out::println); // Output: hello, world

        Map<Integer, List<String>> map = list.stream().collect(Collectors.groupingBy(String::length));
        System.out.println(map); // Output: {3=[foo, bar, baz], 5=[hello, world]
   }
}

In this example, we have a List of strings list containing five strings. We use the takeWhile() method to create a new Stream that contains the elements of list until a condition is met, in this case, the length of the string is less than 4. We print the elements of the new Stream using the forEach() method. Similarly, we use the dropWhile() method to create a new Stream that drops elements from list until a condition is met, in this case, the length of the string is less than 4. We print the elements of the new Stream using the forEach() method.

Finally, we use the groupingBy() method to group the elements of list based on their length and store the result in a Map. We print the Map to the console to verify that the grouping was done correctly.

  1. Enhanced NullPointerException Messages
public class NullPointerExceptionExample {
    public static void main(String[] args) {
        String str = null;
        Objects.requireNonNullElseThrow(str, () -> new IllegalArgumentException("Invalid input: " + str));
    }
}

In this example, we have a String variable str that is null. We use the requireNonNullElseThrow() method to check if str is null. If it is null, we throw an IllegalArgumentException with a custom message that includes the value of str. If the check passes, nothing happens. The output of this code will be an Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.length()" because "str" is null, which is a more informative message than the default NullPointerException message.

Please do not forget to subscribe to our posts at www.AToZOfSoftwareeEgineering.blog.

Listen & follow our podcasts available on Spotify and other popular platforms.

Have a great reading and listening experience!


Discover more from A to Z of Software Engineering

Subscribe to get the latest posts sent to your email.

Featured:

Podcasts Available on:

Amazon Music Logo
Apple Podcasts Logo
Castbox Logo
Google Podcasts Logo
iHeartRadio Logo
RadioPublic Logo
Spotify Logo

Posted

in

Comments

Leave a comment

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

Discover more from A to Z of Software Engineering

Subscribe now to keep reading and get access to the full archive.

Continue reading