Java is a popular programming language that is widely used in enterprise software development. The language has evolved over the years, with new features and improvements being added in each release. Two of the most significant releases in recent years are Java 8 and Java 11. In this article, we’ll explore the key differences between these two versions of Java with code examples.
Java 8
Java 8 was released in 2014 and introduced several significant new features to the language, including:
Lambdas
One of the most significant new features in Java 8 is support for lambdas. Lambdas are anonymous functions that can be passed around like any other object. They provide a concise way to represent a piece of functionality that can be executed later. Lambdas can be used to implement functional interfaces, which are interfaces that have only one abstract method.
Here’s an example of using lambdas to sort a list of strings:
List<String> names = Arrays.asList("John", "Paul", "George", "Ringo"); Collections.sort(names, (a, b) -> a.compareTo(b)); System.out.println(names);
In this example, we’re using the Collections.sort
method to sort a list of strings. We’re passing in a lambda expression as the second argument, which tells Java how to compare the strings. The lambda expression is (a, b) -> a.compareTo(b)
, which compares two strings and returns an integer value that represents their order.
Stream API
Another significant new feature in Java 8 is the Stream API. The Stream API provides a fluent, functional way to work with collections of data. It allows you to perform operations like filtering, mapping, and reducing on a collection of data using a series of fluent method calls.
Here’s an example of using the Stream API to filter a list of strings:
List<String> names = Arrays.asList("John", "Paul", "George", "Ringo"); List<String> filteredNames = names.stream() .filter(name -> name.length() < 5) .collect(Collectors.toList()); System.out.println(filteredNames);
In this example, we’re using the stream
method to create a stream of strings from a list of names. We’re then using the filter
method to remove any strings that are longer than 4 characters. Finally, we’re using the collect
method to convert the stream back into a list.
Optional
Java 8 also introduced the Optional class, which is a container object that may or may not contain a non-null value. The Optional class is used to reduce the occurrence of null pointer exceptions in Java code.
Here’s an example of using the Optional class:
String name = null; Optional<String> optionalName = Optional.ofNullable(name); if (optionalName.isPresent()) { System.out.println("Name: " + optionalName.get()); } else { System.out.println("Name not present"); }
In this example, we’re using the ofNullable
method to create an Optional object from a potentially null string. We’re then checking if the object is present using the isPresent
method. If the object is present, we’re retrieving its value using the get
method. If the object is not present, we’re printing a message.
Date and Time API
Java 8 also introduced a new Date and Time API that is designed to be easier to use and more powerful than the previous Date and Calendar classes. The new API includes classes for representing dates, times, time zones, durations, and periods.
Here’s an example of using the new Date and Time API:
LocalDateTime now = LocalDateTime.now(); System.out.println("Current date and time: " + now); LocalDateTime christmas = LocalDateTime.of(2023, Month.DECEMBER, 25, 0, 0); System.out.println("Christmas day: " + christmas); Duration timeUntilChristmas = Duration.between(now, christmas); System.out.println("Time until Christmas: " + timeUntilChristmas);
In this example, we’re using the LocalDateTime
class to get the current date and time. We’re then creating a LocalDateTime
object that represents Christmas day in 2023. We’re using the Duration
class to calculate the time between the current date and time and Christmas day.
Java 11
Java 11 was released in 2018 and introduced several new features and improvements to the language. Here are some of the key differences between Java 8 and Java 11:
Var keyword
Java 11 introduced a new var
keyword that allows you to declare variables without specifying their type. The type of the variable is inferred from the value assigned to it.
Here’s an example of using the var
keyword:
var names = List.of("John", "Paul", "George", "Ringo"); var filteredNames = names.stream() .filter(name -> name.length() < 5) .collect(Collectors.toList()); System.out.println(filteredNames);
In this example, we’re using the var
keyword to declare variables names
and filteredNames
. The type of these variables is inferred from the value assigned to them.
HTTP Client
Java 11 introduced a new HTTP Client API that provides a more modern way to make HTTP requests. The new API is designed to be more flexible and easier to use than the previous HttpURLConnection
and HttpClient
classes.
Here’s an example of using the new HTTP Client API:
HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://jsonplaceholder.typicode.com/posts/1")) .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.body());
In this example, we’re using the HttpClient
class to create an HTTP client. We’re then using the HttpRequest
class to create an HTTP request for a REST API. We’re using the HttpResponse
class to handle the response from the API.
String API
Java 11 introduced several improvements to the String API, including new methods for working with whitespace and Unicode code points.
Here’s an example of using the new String API:
String str = " Hello World! "; System.out.println("Original string: " + str); System.out.println("Trimmed string: " + str.strip()); System.out.println("Uppercase string: " + str.toUpperCase());
In this example, we’re using the strip
method to remove leading and trailing whitespace from a string. We’re using the toUpperCase
method to convert the string to uppercase.
Conclusion
Java 8 and Java 11 are both significant releases of the Java programming language. Java 8 introduced lambdas, the Stream API, Optional, and a new Date and Time API, while Java 11 introduced the var
keyword, a new HTTP Client API, and improvements to the String API. As a developer, it’s essential to be familiar with the differences between these two versions of Java and to understand how to use their new features to write better code.