Top features of Java 8

Saurav Kumar
4 min readMay 12, 2023

--

Java 8 is an important release in the Java programming language. It introduced several new features and improvements that have made development faster, more efficient, and more enjoyable. Here are some of the key reasons why Java 8 is important:

  1. Lambda expressions:

Lambda expressions are a new feature in Java 8 that allows you to write concise anonymous functions. A lambda expression consists of a list of parameters, a lambda operator (“->”), and a function body. Here is an example:

List<String> names = Arrays.asList("Alice", "Bob", "Charlie");

names.stream()
.filter(name -> name.startsWith("A"))
.forEach(System.out::println);

In this example, we create a list of names and use the Stream API to filter out any names that do not start with the letter “A”. The lambda expression name -> name.startsWith("A") is used to define the filter criteria.

2. Stream API:

The Stream API is a powerful new feature in Java 8 that provides a functional programming approach to processing collections. It allows you to perform complex operations such as filtering, mapping, and reducing collections in a concise and readable way. Here is an example:

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int sum = numbers.stream()
.filter(n -> n % 2 == 0)
.mapToInt(Integer::intValue)
.sum();

System.out.println(sum);

In this example, we create a list of numbers and use the Stream API to filter out any odd numbers, convert the remaining even numbers to int values, and then compute the sum of the resulting values.

3. Default methods:

Default methods allow you to add new methods to an interface without breaking existing code that implements that interface. Here is an example:

interface MyInterface {
void doSomething();

default void doSomethingElse() {
System.out.println("Doing something else!");
}
}
class MyClass implements MyInterface {
public void doSomething() {
System.out.println("Doing something!");
}
}
MyClass myObject = new MyClass();
myObject.doSomething();
myObject.doSomethingElse();

In this example, we define an interface MyInterface with a default method doSomethingElse(). We then implement this interface in the MyClass class, which only needs to provide an implementation for the doSomething() method. We can then create an instance of MyClass and call both methods on it.

4. Optional:

The Optional class is a new class in Java 8 that represents a value that may or may not be present. It can be used to avoid null pointer exceptions and make your code more robust. Here is an example:

Optional<String> name = Optional.ofNullable(getName());
if (name.isPresent()) {
System.out.println("Hello, " + name.get() + "!");
} else {
System.out.println("Hello, world!");
}

In this example, we use the Optional.ofNullable() method to create an Optional the object that may or may not contain a value. We then use the isPresent() method to check whether the value is present, and the get() method to retrieve the value if it is present.

5. Date and Time API:

The Date and Time API is a new API in Java 8 that provides a more comprehensive and flexible way to handle dates and times. Here is an example:

LocalDateTime now = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formattedDate = now.format(formatter);
System.out.println(formattedDate);

In this example, we create LocalDateTime an object representing the current date and time and then use a DateTimeFormatter

6. Nashorn JavaScript engine:

The Nashorn JavaScript engine is a new JavaScript engine that was introduced in Java 8. It is faster than the previous JavaScript engine, and it allows you to embed JavaScript code in your Java applications. Here is an example:

ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
try {
engine.eval("print('Hello, world!')");
} catch (ScriptException e) {
e.printStackTrace();
}

In this example, we create ScriptEngineManager object and use it to obtain a reference to the Nashorn JavaScript engine. We then use the eval() method to execute a simple JavaScript program that prints "Hello, world!" to the console.

7. Parallel array sorting:

Parallel array sorting is a new feature in Java 8 that allows you to sort arrays in parallel, which can significantly improve performance for large arrays. Here is an example:

int[] numbers = {5, 2, 7, 1, 8, 4};
Arrays.parallelSort(numbers);
System.out.println(Arrays.toString(numbers));

In this example, we create an array of integers and use the Arrays.parallelSort() method to sort the array in parallel. We then print out the sorted array using the Arrays.toString() method.

8. PermGen removed:

PermGen was a memory space used in previous versions of Java to store metadata about classes. In Java 8, PermGen has been removed and replaced with a new memory space called Metaspace. This change can help to reduce memory usage and improve performance, especially in applications that use a lot of dynamic class loading. Here is an example:

class MyObject {
// some code here
}
for (int i = 0; i < 100000; i++) {
String className = "MyObject" + i;
byte[] classBytes = generateClassBytes(className);
Class<?> clazz = defineClass(className, classBytes, 0, classBytes.length);
}
System.out.println("Classes loaded: " + ClassLoader.getSystemClassLoader().getLoadedClassCount());

In this example, we dynamically generate and load a large number of classes using the defineClass() method. In previous versions of Java, this could cause problems with PermGen space, but in Java 8 it should work without issue because the Metaspace automatically handles the loading and unloading of classes. We then print out the number of classes that have been loaded using the getLoadedClassCount() method.

--

--

Saurav Kumar
Saurav Kumar

Written by Saurav Kumar

Experienced Software Engineer adept in Java, Spring Boot, Microservices, Kafka & Azure.

No responses yet