Category : Java | Sub Category : Java8 Features | By Prasad Bonam Last updated: 2023-11-13 04:06:03 Viewed : 679
Introduction to the key features introduced in Java 8:
Java 8, released in March 2014, introduced several major features and enhancements to the Java programming language. Here is an overview of the key features introduced in Java 8:
Lambda Expressions:
(parameters) -> expression
or (parameters) -> { statements }
.java// Old way using anonymous inner class
Runnable oldRunnable = new Runnable() {
@Override
public void run() {
System.out.println("Old way");
}
};
// Using lambda expression
Runnable newRunnable = () -> System.out.println("Lambda way");
Functional Interfaces:
java@FunctionalInterface
interface MyFunctionalInterface {
void myMethod();
}
Stream API:
javaList<String> myList = Arrays.asList("a1", "a2", "b1", "c2", "c1");
myList
.stream()
.filter(s -> s.startsWith("c"))
.map(String::toUpperCase)
.sorted()
.forEach(System.out::println);
Default Methods:
javainterface MyInterface {
void myMethod();
default void myDefaultMethod() {
System.out.println("Default implementation");
}
}
Method References:
java// Using lambda expression
list.forEach(s -> System.out.println(s));
// Using method reference
list.forEach(System.out::println);
Optional:
Optional
class is introduced to provide a more robust way of dealing with potentially null values, reducing the chances of NullPointerException
.javaOptional<String> optional = Optional.ofNullable(getValue());
System.out.println(optional.orElse("Default Value"));
New Date and Time API:
java.time
package provides a comprehensive set of classes for date and time manipulation, addressing the limitations of the older java.util.Date
and java.util.Calendar
.javaLocalDate today = LocalDate.now();
CompletableFuture:
CompletableFuture
is introduced for asynchronous programming. It represents a promise that can be completed with a value or exception in the future.javaCompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
// Asynchronous task
});
Nashorn JavaScript Engine:
javaScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("nashorn");
engine.eval("print(`Hello, Nashorn!`)");
These features collectively brought significant improvements to the Java language, making it more expressive, concise, and capable of handling modern programming paradigms. Java 8`s features laid the foundation for subsequent releases, influencing the direction of Java`s evolution.