What are the new features introduced in Java 8?
Java 8 introduced significant features to enhance the language's capabilities, improve performance, and make development more efficient.
- Lambda Expressions
- Concise syntax for writing anonymous methods. It allows you to treat functionality as a method argument or treat a code as data like defining a small function inline without needing a separate method.
java
Runnable runnable = () -> System.out.println("Hello, world!");
3. Streams API
4. Process sequences of elements with filter/map/reduce operations. It allows performing filter/map/reduce-like operations with ease like a production line where items are filtered and processed in sequence.
java
List<String> names = Arrays.asList("John", "Jane", "Jack");
names.stream().filter(name -> name.startsWith("J")).forEach(System.out::println);
5. Functional Interfaces
6. Interfaces with a single abstract method. It facilitates the use of lambda expressions and method references like a contract that defines a single task to be performed.
java
@FunctionalInterface
interface MyFuncInterface {
void execute();
}
MyFuncInterface func = () -> System.out.println("Executing");
func.execute();
7. Default Methods
8. Methods with default implementations in interfaces. It allows interfaces to have methods with bodies like having a fallback implementation if the class doesn't provide one.
java
interface MyInterface {
default void myDefaultMethod() {
System.out.println("Default method");
}
}
9. Method References
10. Shorthand for calling methods.
java
List<String> names = Arrays.asList("John", "Jane", "Jack");
names.forEach(System.out::println);
11. Optional Class
12. Container for optional values. It helps to avoid null pointer exceptions by providing methods to deal with non-existent values like a box that might contain something or be empty, and you have methods to check and handle it.
java
Optional<String> optional = Optional.ofNullable("Hello");
optional.ifPresent(System.out::println);
13. New Date and Time API
14. Modern API for date and time.
java
LocalDate today = LocalDate.now();
15. Nashorn JavaScript Engine
16. A new engine to run JavaScript code.
17. CompletableFuture
18. A class for asynchronous programming.
java
CompletableFuture.runAsync(() -> System.out.println("Async task"));
19. New Collection APIs
* New methods in collections.
java List<String> list = Arrays.asList("a", "b", "c"); list.replaceAll(String::toUpperCase);