Java.Java8.What are the new features in Java 8 and JDK 8?

🔹 1. Lambda Expressions

Lambda expressions enable you to treat functionality as a method argument or pass code as data. They simplify the development of APIs that rely on passing behavior.

List<String> list = Arrays.asList("a", "b", "c");
list.forEach(s -> System.out.println(s));

🔹 2. Functional Interfaces

An interface with a single abstract method (SAM) is called a functional interface. Java 8 introduces the @FunctionalInterface annotation to denote them.

Example:

@FunctionalInterface
interface MyFunction {
    void apply();
}

Java 8 includes many built-in functional interfaces in the java.util.function package, such as:

  • Predicate<T>
  • Function<T, R>
  • Consumer<T>
  • Supplier<T>

🔹 3. Streams API

Introduced in java.util.stream, it allows for functional-style operations on streams of elements, such as filter, map, and reduce.

Example:

List<String> list = Arrays.asList("a", "bb", "ccc");
list.stream().filter(s -> s.length() > 1).forEach(System.out::println);

🔹 4. Default Methods

Interfaces can now have method implementations using the default keyword.

Example:

interface MyInterface {
    default void print() {
        System.out.println("Hello");
    }
}

🔹 5. Method References and Constructor References

A shorthand for calling methods or constructors via ::.

Examples:

list.forEach(System.out::println);              // Method reference
Supplier<List<String>> listSupplier = ArrayList::new; // Constructor reference

🔹 6. New Date and Time API

The old java.util.Date and Calendar were replaced with a modern, immutable API in the java.time package (inspired by Joda-Time).

Classes:

  • LocalDate, LocalTime, LocalDateTime
  • ZonedDateTime, Period, Duration
  • DateTimeFormatter

Example:

LocalDate today = LocalDate.now();
LocalDate birthday = LocalDate.of(1990, Month.JANUARY, 1);

🔹 7. Optional

A container object that may or may not contain a non-null value. Helps avoid NullPointerException.

Example:

Optional<String> name = Optional.of("Stanley");
name.ifPresent(System.out::println);

🔹 8. Nashorn JavaScript Engine

A new JavaScript engine integrated into JDK 8 to replace Rhino, allowing you to run JS code from Java.

Example:

ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
engine.eval("print('Hello from JS')");

🔹 9. Repeating Annotations

Allows the same annotation to be used multiple times on the same declaration.

Example:

@Hint("hint1")
@Hint("hint2")
class Person {}

🔹 10. Type Annotations

Java 8 allows annotations to be used in more places, such as type uses.

Example:

@NonNull String name;
This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.