Java 8 Features-1
Java 8 Features-1
Lambda Expressions
Lambda expression is one of the biggest feature introduced in Java. A lambda expression
facilitates functional programming in Java. A lambda expression works on the principle of
functional interface. A Functional interface is an interface with only one method to
implement. A lambda expression provides an implementation of the functional interface
method.
Lambda expression simplifies functional programming a lot and makes code readable
without any boilerplate code. A lambda expression can infer the type of parameter used
and can return a value without a return keyword. In the case of the simple one-
statement method, even curly braces can be eliminated.
Open Compiler
package com.tutorialspoint;
return a + b;
}
};
int result = sum.operate(2,3);
System.out.println(result);
interface Calculator {
int operate(int a, int b);
}
}
Let us compile and run the above program, this will produce the following result −
5
5
Method References
Method reference is a short and concise way to call methods, static methods and even
constructors without any lengthy syntax. Method references help to point to methods by
their names even without specifying the arguments. Arguments are passed by the
lambda expression. A method reference is described using "::" symbol.
<<class-name>>::methodName
<<object-name>>::methodName
<<class-name>>::new
In this example, we've used a static method compare and an instance method
compareTo to sort two arraylist of integers. We've used method references to represent
both static and instance methods.
Open Compiler
package com.tutorialspoint;
import java.util.Arrays;
import java.util.List;
numbers = Arrays.asList(1,2,4,9,8,7,3);
System.out.println("Sorted using instance method reference" );
// Use instance method compareTo
numbers = numbers.stream().sorted(Integer::compareTo).toList();
System.out.println(numbers);
}
}
Let us compile and run the above program, this will produce the following result −
Learn Java in-depth with real-world projects through our Java certification course.
Enroll and become a certified expert to boost your career.
Default Methods
Before Java 8, an interface could have only abstract methods. With Java 8, lambda
expression were introduced. Now for backward compatability, default method capability
was added so that old interfaces can leverage lambda expression without modifying their
implementations.
For example, List or Collection interfaces do not have 'forEach' method declaration. Thus,
adding such method will simply break the collection framework implementations. Java 8
introduces default method so that List/Collection interface can have a default
implementation of forEach method, and the class implementing these interfaces need not
implement the same.
Syntax
Open Compiler
package com.tutorialspoint;
interface vehicle {
// default method must have an implementation
default void message() {
System.out.println("I am a vehicle!");
}
}
// of an interface.
public class Tester implements vehicle {
public static void main(String args[]) {
Tester tester = new Tester();
// implementing class can access the default method as its own
method
tester.message();
}
}
Let us compile and run the above program, this will produce the following result −
I am a vehicle!
Stream API
Stream API is a new abstract layer introduced in Java 8 to process data in a declarative
way. A stream represents a sequence of elements. A stream provides a set of elements
of specific type in a sequential manner. A stream gets/computes elements on demand. It
never stores the elements.
Stream supports aggregate operations like filter, map, limit, reduce, find, match, and so
on and can do the iterations internally over the source elements provided, in contrast to
Collections where explicit iteration is required.
Syntax
<<collection-instance>>.stream().<<non-terminal-operation()>>.<<non-
terminal-operation()>>.<<terminal-operation()>>
In this example, we've created a list of strings where few entries are empty. Now using
stream API, we're filtering the empty strings and counting them.
Open Compiler
Page 6 of 10
package com.tutorialspoint;
import java.util.Arrays;
import java.util.List;
Let us compile and run the above program, this will produce the following result −
Empty Strings: 2
Optional Class
Optional class feature was introduced in java 8 to handle Null Pointer Exception scenarios
programmatically, to make programs more concise, less error prone. A Null Pointer
Exception occurs whenever a null object reference is used to get value from it or to
invoke its method. As program size increases, it is very tedious to handle all cases where
Null Pointer Exception can happens.
Optional Class instance provides a wrapper over the object with many utility methods like
to get the alternate value if underlying value is null, to check if object reference is null
and so.
Open Compiler
package com.tutorialspoint;
import java.util.Optional;
System.out.println(value);
System.out.println(value1);
}
}
Let us compile and run the above program, this will produce the following result −
-1
10
Java 8 introduces a new date-time API under the package java.time. Following are some
of the important classes introduced in java.time package.
Page 8 of 10
Open Compiler
package com.tutorialspoint;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Month;
import java.time.ZonedDateTime;
Let us compile and run the above program, this will produce the following result −
Example
C:\JAVA>jjs
jjs> print("Hello, World!")
Hello, World!
jjs> quit()
>>
C:\JAVA>
package com.tutorialspoint;
Page 10 of 10
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
try {
// call the javascript function, pass a java variable
nashorn.eval("print('" + message + "')");
// call the javascript function and get the result back in
java
result = (Integer) nashorn.eval(expression);
} catch(ScriptException e) {
System.out.println("Error executing script: "+
e.getMessage());
}
System.out.println(result.toString());
}
}
Let us compile and run the above program, this will produce the following result −
This is a message
12
Nashorn engine was deprecated in java 11 and removed in java 15 and is replaced by
GraalVM javascript engine.