1. Features of Java 8
- Functional Interfaces
- Lambda Expressions
- Stream API
- Default Methods
- Method References
- Optional Class
- Date and Time API
- Nashorn JavaScript Engine
- Concurrency Enhancements
forEach()
Method- Parallel Array Sorting
- Improved Annotations
2. Functional Interfaces
Java 8 introduced several built-in functional interfaces in the java.util.function
package to facilitate functional programming:
Supplier<T>
Consumer<T>
Predicate<T>
Function<T, R>
UnaryOperator<T>
BinaryOperator<T>
3. Lambda Expressions
Lambda expressions in Java provide a way to write shorter and more concise code for defining small, single-use functions, often referred to as anonymous functions.
They allow you to:
- Eliminate the need for anonymous inner classes.
- Write code that’s more expressive and readable.
- Simplify functional-style operations.
4. Lambda Expressions – Examples
Traditional approach using an anonymous inner class:
javaCopyEditRunnable runnable = new Runnable() {
@Override
public void run() {
System.out.println("Hello, World!");
}
};
Using a lambda expression:
javaCopyEditRunnable runnable = () -> {
System.out.println("Hello, World!");
};
5. Stream API
The Stream API facilitates functional-style operations on sequences of elements. It allows:
- Operations like
map
,reduce
,filter
, andforEach
on collections. - Support for parallel execution, improving performance on multi-core systems.
6. Stream API – Examples
javaCopyEditList<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David", "Eve");
// Filter names starting with 'A'
List<String> filteredNames = names.stream()
.filter(name -> name.startsWith("A"))
.collect(Collectors.toList());
// Convert names to uppercase
List<String> uppercaseNames = names.stream()
.map(String::toUpperCase)
.collect(Collectors.toList());
// Sum of all numbers
int sum = numbers.stream()
.reduce(0, Integer::sum);
// Sort names alphabetically
List<String> sortedNames = names.stream()
.sorted()
.collect(Collectors.toList());
7. Default Methods
Before Java 8, interfaces could only contain method declarations with no implementations. Java 8 introduced default methods to interfaces, enabling:
- Providing method implementations in interfaces.
- Backward compatibility with older versions.
- Extension of interfaces without affecting existing implementations.
8. Date and Time API
Java 8 introduced a new Date and Time API in the java.time
package to overcome the limitations of java.util.Date
and java.util.Calendar
.
Key Features:
- Immutability
- Thread safety
- Clear and fluent API
- Better handling of time zones and durations
Default Methods in Interfaces (Java 8)
Definition:
A default method in an interface is a method with a body (implementation). It allows interfaces to have methods with default behavior without affecting implementing classes.
Example:
javaCopyEditinterface Vehicle {
// Regular method (abstract)
void start();
// Default method with implementation
default void honk() {
System.out.println("Honk honk!");
}
}
class Car implements Vehicle {
// Implementing abstract method
public void start() {
System.out.println("Car started.");
}
}
Method Reference (Java 8)
Definition:
A method reference is a shorthand notation of a lambda expression to call a method directly.
Types of Method References:
- Static Method —
ClassName::staticMethodName
- Instance Method of a Particular Object —
instance::methodName
- Instance Method of an Arbitrary Object of a Particular Type —
ClassName::methodName
- Constructor Reference —
ClassName::new
Example:
javaCopyEdit// Instance method to print string in lowercase
public void printLowerCase(String str) {
System.out.println(str.toLowerCase());
}
// Reference to an instance method of a particular object
MethodReferenceExample converter = new MethodReferenceExample();
names.forEach(converter::printLowerCase);
Optional Class (Java 8)
Purpose:
To handle values that might be null
and avoid NullPointerException
.
Key Points:
- Introduced in Java 8.
- Container for optional (nullable) values.
- Provides utility methods for safe access and manipulation.
Example:
javaCopyEditString str = "Hello";
Optional<String> optionalStr = Optional.ofNullable(str);
// Check presence
if (optionalStr.isPresent()) {
System.out.println("Value is present: " + optionalStr.get());
} else {
System.out.println("Value is absent");
}
// Using ifPresent
optionalStr.ifPresent(value ->
System.out.println("Value is present: " + value)
);
// Using orElse
String defaultValue = optionalStr.orElse("Default Value");
System.out.println("Value or default: " + defaultValue);
forEach() Method (Java 8)
Definition:
Used to perform an action for each element of a collection.
Available In:
Iterable
interfaceStream
interface
Usage Example:
javaCopyEditList<String> names = Arrays.asList("Alice", "Bob", "Charlie");
names.forEach(name -> System.out.println(name));
Nashorn JavaScript Engine (Java 8)
Overview:
- Replaces the old Rhino engine.
- Executes JavaScript code on the JVM.
- Supports ECMAScript 5.1.
- Faster execution via JVM optimizations.
Parallel Array Sorting (Java 8)
Method: Arrays.parallelSort()
Key Benefits:
- Sorts large arrays more efficiently by utilizing multiple CPU cores.
- Introduced in Java 8.
Example:
javaCopyEditint[] numbers = {5, 3, 8, 1, 2};
Arrays.parallelSort(numbers);