Java 8 New Features: Default Methods in Interfaces
Java 8 New Features: Default Methods in Interfaces
Java 8 New Features: Default Methods in Interfaces
D E FAU LT M E T H O D S I N I N T E R FAC E S
• When Java team decided to provided lot of features that supports lambda, functional
programming by updating the collections framework, they got a problem. If they add new
abstract methods inside the interfaces/abstract classes all the classes implementing them has
to updated as per the requirements and this will effect all the teams using Java.
• To overcome this and provide backward compatibility even after adding new features inside
Interfaces, Java team1 allowed concrete method implementations inside Interfaces which are
called as default methods.
• Default methods are also known as defender methods or virtual extension methods.
• Just like regular interface methods, default methods are also implicitly public.
• Unlike regular interface methods, default methods will be declared with default keyword at the
beginning of the method signature along with the implementation code.
1
JAVA 8 NEW FEATURES
D E FAU LT M E T H O D S I N I N T E R FAC E S
• Interface default methods are by-default available to all the implementation classes. Based on
requirement, implementation class can use these default methods with default behavior or can
override them.
• We can’t override the methods present inside the Object class as default methods inside a
interface. The compiler will throw errors if we do so.
• We can’t write default methods inside a class. Even in the scenarios where we are overriding
the default keyword should not be used inside the class methods.
2
JAVA 8 NEW FEATURES
D E FAU LT M E T H O D S I N I N T E R FAC E S
• The most typical use of default methods in interfaces is to incrementally provide additional
features/enhancements to a given type without breaking down the implementing classes.
• What happens when a class implements multiple Interfaces which has similar default methods
defined inside them?
public interface A { ✓ This will create ambiguity to the compiler and it will
default 3void m1() { // } throw an error. We also call it as Diamond problem.
Interfaces with default methods can’t have a Abstract classes can have a constructor, state and
constructor, state and behavior behavior
Static and instance blocks are not allowed Static and instance blocks are allowed
4
JAVA 8 NEW FEATURES
STAT I C M E T H O D S I N I N T E R FAC E S
• From Java 8, just like we can write default methods inside interfaces, we can also write static
methods inside them to define any utility functionality.
• Since static methods don't belong to a particular object, they are not available to the classes
implementing the interface, and they have to be called by using the interface name preceding
the method name.
5
• Defining a static method within an interface is similar to defining one in a class.
• Static methods in interfaces make possible to group related utility methods, without having
to create artificial utility classes that are simply placeholders for static methods.
• Since interface static methods by default not available to the implementation class,
overriding concept is not applicable.
• Based on our requirement we can define exactly same method in the implementation class,
it’s valid but not overriding. 5
JAVA 8 NEW FEATURES
STAT I C M E T H O D S I N I N T E R FAC E S
public interface A {
public static void sayHello() {
System.out.println("Hi, This is a static method inside Interfaces");
}
}
} 6
JAVA 8 NEW FEATURES
O P T I O N A L TO D E A L W I T H N U L L S
• If I ask a question to all the developers in the world to raise their hand if they have seen
NullPointerException in their code, there might be no one who will not raise their hand ☺
• We as developers spend good amount of time fixing or caring for the NullPointerException in
our code and it is a very painful or tedious process always. Below is one of the sample code
where we can see an null pointer exception,
7
• In the above code we may get null pointer exception at any instance like while accessing the
order from user/ item from order/name from item in case if they are null values. If we have to
handle them we will end up writing code like below,
7
JAVA 8 NEW FEATURES
O P T I O N A L TO D E A L W I T H N U L L S
• Sometimes we may know based on our business domain knowledge that particular objects
can never be null but every time you doubt that a variable could be null, you’re obliged to add
a
further nested if block
8
JAVA 8 NEW FEATURES
O P T I O N A L TO D E A L W I T H N U L L S
• You may wonder about the difference between a null reference and Optional.empty().
Semantically, they could be seen as the same thing, but in practice, the difference is huge.
Trying to access a null causes a NullPointerException, whereas Optional.empty() is a valid,
workable object of type Optional that can be invoked in useful ways.
• It’s important to note that the intention of the Optional class isn’t to replace every single null
reference. Instead, its purpose is to help you design more-comprehensible APIs so that by
reading the signature9 of a method, you can tell whether to expect an optional value.
• Java was designed in the 1990s as an object-oriented programming language, when object-
oriented programming was the principal paradigm for software development. Recently,
functional programming has risen in importance because it is well suited for concurrent and
event-driven (or “reactive”) programming. That doesn’t mean that objects are bad. Instead, the
winning strategy is to blend object-oriented and functional programming.
• A “lambda expression” is a block of code that you can pass around so it can be executed later,
once or multiple times. It is an anonymous (nameless) function. That means the function which
doesn’t have the name, return type and access modifiers.
• Lambda has been part of Java competitive languages like Python, Ruby already.
11
JAVA 8 NEW FEATURES
L A M B DA ( Λ ) E X P R E S S I O N
Note: When we have a single line of code inside your lambda method, we can remove the {}
surrounding it to make it more simple.
12
JAVA 8 NEW FEATURES
L A M B DA ( Λ ) E X P R E S S I O N
Note: When we have a single input parameter inside your lambda method, we can remove the ()
surrounding it to make it more simple.
13
JAVA 8 NEW FEATURES
L A M B DA ( Λ ) E X P R E S S I O N
Note: The compiler can detect the input parameters data type based on the abstract method. But
you can still mention them inside your lambda code and these are optional in nature.
14
JAVA 8 NEW FEATURES
L A M B DA ( Λ ) E X P R E S S I O N
Note: If we have a single line of code inside your lambda method then return keyword is optional.
We can remove it and compiler can interpret that the outcome of the statement should be return.
15
JAVA 8 NEW FEATURES
L A M B DA ( Λ ) E X P R E S S I O N
• Lambda expressions are used heavily inside the Collections, Streams libraries from Java 8. So it
is very important to understand them.
• We can provide Lambda expressions in the place of object and method arguments.
16
JAVA 8 NEW FEATURES
L A M B DA ( Λ ) E X P R E S S I O N
• Lambda expressions can use variables defined in an outer scope. They can capture static
variables, instance variables, and local variables, but only local variables must be final or
effectively final.
• A variable is final or effectively final when it's initialized once and is never mutated in its owner
class; we can't initialize it in loops or inner classes.
17 ✓ Inside lambda code or blocks, we can’t modify the local
variables present outside the lambda blocks.
It is a anonymous inner class with out name It is a anonymous method with out name
It can implement the interfaces with any number It can implement the interfaces which has only 1
18
of abstract methods inside them abstract method called Functional interfaces
They can be instantiated and can extend abstract They can’t be instantiated and can’t extend
and concrete classes. abstract and concrete classes.
Instance variables can be declared and “this” Only local variables can be declared and “this”
inside it always refer to the current inner class inside it always refer to the outer enclosing class
Memory inside heap will be allocated on demand Permanent memory (Method area) will be
whenever we create an object for it allocated for it
18
JAVA 8 NEW FEATURES
F U N C T I O N A L I N T E R FAC E
• Functional interfaces contains only one abstract method. Below are the thumb rules for
Functional interfaces,
✓ Only 1 abstract method is allowed (Also called as SAM – Single Abstract method)
✓ Any number of default methods are allowed
✓ Any number of static methods are allowed
✓ Any number
19 of private methods are allowed
• Since functional interfaces has only one abstract method, we can write lambda code/pass the
implementation behavior of it using lambda code. Since there is only one unimplemented
method inside interface compiler doesn’t complain for method name, parameters datatype,
return type of the method etc.
• Java already has some interfaces similar to functional Interfaces even before Java 8. Those are
like,
✓ Runnable – It contains only 1 abstract method run()
✓ Comparable : It contains only 1 abstract method compareTo()
@FunctionalInterface 20
public interface ArithmeticOperation{
public int performOperation (int a, int b); ======➔ Valid functional interface as it
contains
} SAM
@FunctionalInterface
public interface ArithmeticOperation{
public int performOperation (int a, int b); ======➔ Invalid functional interface as it
contains
public int performOperation (int c); 2 abstract methods 20
JAVA 8 NEW FEATURES
F U N C T I O N A L I N T E R FAC E
@FunctionalInterface
public interface ArithmeticOperation{
======➔ Invalid functional interface as it doesn’t
} have single abstract method
@FunctionalInterface
public interface ArithmeticOperation{
public int performOperation
21 (int a, int b);
}
@FunctionalInterface
public interface SimpleOperation extends ArithmeticOperation {
SimpleOperation interface is a valid functional interface though it doesn’t have any abstract method
because it extends another functional interface which has only 1 abstract method.
21
JAVA 8 NEW FEATURES
F U N C T I O N A L I N T E R FAC E
@FunctionalInterface
public interface SameOperation extends ArithmeticOperation {
public int performOperation (int a, int b);
}
SameOperation interface is a valid functional interface though it inherits 1 abstract method from its
parent and it also has 1. This is because the abstract method name and signature is same as parent
interface. 22
@FunctionalInterface
public interface InvalidOperation extends ArithmeticOperation {
public int performAnotherOperation (int a, int b);
}
InvalidOperation interface is not a valid functional interface because it inherits 1 abstract method
from its parent and it also has another abstract method which violates the rule of SAM.
22
JAVA 8 NEW FEATURES
F U N C T I O N A L I N T E R FAC E
Compiler will not have any problem with NormalOperation interface as it is not marked as a
Functional interface and it can have any number of abstract methods.
23
23
JAVA 8 NEW FEATURES
F U N C T I O N A L I N T E R FAC E
• To make developer life easy, Java 8 has provided some pre defined functional interfaces by
considering most common requirements during the development. All such interfaces are
present inside the ‘java.util.function’ package.
• Below are the most important functional interfaces provided by the Java team,
✓ java.util.function.Predicate
24 <T>
✓ java.util.function.Function<T, R>
✓ java.util.function.Consumer <T>
✓ java.util.function.Supplier<T>
✓ java.util.function.BiPredicate<T, U>
✓ java.util.function.BiFunction<T, U, R>
✓ java.util.function.BiConsumer<T, U>
✓ java.util.function.UnaryOperator<T>
✓ java.util.function.BinaryOperator<T>
✓ Primitive Functional Interfaces
24
JAVA 8 NEW FEATURES
P R E D I C AT E F U N C T IO N A L I N T E R FAC E
java.util.function.Predicate <T>
• Predicate Functional interface handles the scenarios where we accept a input parameter and
return the boolean after processing the input.
• @param <T> the type of the input to the function
✓ default Predicate<T> or(Predicate<? super T> other) === > Default method that can be used while
joining multiple predicate conditions. This acts like a logical OR condition
✓ default Predicate<T> negate() === > Default method that can be used while joining multiple predicate
conditions. This acts like a logical NOT condition
✓ default Predicate<T> and(Predicate<? super T> other) === > Default method that can be used
while joining multiple predicate conditions. This acts like a logical AND condition
25
JAVA 8 NEW FEATURES
F U N C T I O N F U N C T IO N A L I N T E R FAC E
java.util.function.Function<T, R>
• Function is similar to Predicate except with a change that instead of boolean it can return any
datatype as outcome. It represents a function that accepts one argument and produces a
result.
• @param <T> the type of the input to the function
• @param <R> the type of the result of the function
26
✓ R apply(T t); === > Single abstract method available
✓ static <T> Function<T, T> identity() === > Utility static method which will return the same input value
as output
✓ default compose(..)/andThen(..) === > Default method that can be used for chaining
• The difference between andThen() and compose() is that in the andThen first func will be
executed followed by second func whereas in compose it is vice versa.
26
JAVA 8 NEW FEATURES
P R E D I C AT E Vs F U N C T I O N
PREDICATE FUNCTION
Is used for checking the conditions on given input Is used for executing business logic for the input
and return boolean value and return any type of output.
It takes one type parameter which indicates input It takes 2 type parameters which indicates input
parameter and return parameter is always boolean parameter and return parameter
It has a static method called isEqual() which will It has a static method called identity() which will
check the equality of the 2 values/objects. return the same as input given.
It has 3 default methods for chaining namely It has 2 default methods for chaining namely
and(), or() & negate() andThen() & compose()
27
JAVA 8 NEW FEATURES
U N A RY O P E R ATO R F U N C T I O N A L I N T E R FAC E
java.util.function.UnaryOperator<T>
• If we have scenarios where both the input and output parameters data type is same, then
instead of using Function<T,R> we can use the UnaryOperator<T>
• @param <T> the type of the operand and result of the operator
• It is a child of Function<T,T>.
28 So all the methods apply(), compose(), andThen() are available
inside the UnaryOperator interface also.
• In other words we can say that UnaryOperator takes one argument, and returns a result of the
same type of its arguments.
28
JAVA 8 NEW FEATURES
C O N S U M E R F U N C T IO N A L I N T E R FAC E
java.util.function.Consumer<T>
• As the name indicates Consumer interface will always consumes/accept the given input for
processing but not return anything to the invocation method.
✓ default andThen(..) === > Default method that can be used for chaining
29
JAVA 8 NEW FEATURES
S U P P L I E R F U N C T I O N A L I N T E R FAC E
java.util.function.Supplier<T>
• As the name indicates Supplier interface will always return a value with out accepting any
input. Think of the scenarios like generating report or OTP where we don’t provide any input.
• There are no static and chaining methods available in Supplier functional interface. The reason
is that it will not accept any input so there is no meaning of chaining in it.
30
JAVA 8 NEW FEATURES
C O N S U M E R Vs S U P P L I E R
CONSUMER SUPPLIER
Is used in the scenarios where we send an input Is used in the scenarios where we don’t send any
but not expect any return value from it input but expecting return value from it
It takes one type parameter which indicates input It takes one type parameter which indicates output
parameter and return parameter is always void parameter and input parameter is not needed
It is like setter method inside our POJO classes It is like getter method inside our POJO classes
31
JAVA 8 NEW FEATURES
B I F U N C T I O N A L I N T E R FAC ES
• As of now we have see the functional interfaces which will accept only 1 parameter as input
but what if we have a need to send 2 input parameters. To address the same Java has Bi
Functional interfaces.
32
JAVA 8 NEW FEATURES
B I F U N C T I O N A L I N T E R FAC ES
• There is no BiSupplier for Supplier functional interface as it will not accept any input
33
parameters.
33
JAVA 8 NEW FEATURES
B I N A RY O P E R ATO R F U N C T I O N A L I N T E R FAC E
java.util.function.BinaryOperator<T>
• BinaryOperator<T> is a child of BiFunction<T,U,R> .We will use this in the scenarios where the
2 input parameters and 1 return parameter data types is same.
• @param <T> the type of the operands and result of the operator
• In other words we 34 can say that BinaryOperator takes two arguments of the same type and
returns a result of the same type of its arguments.
• In addition to the methods that it inherits from BiFunction<T,U,R>, it also has 2 utility static
methods inside it. They both will be used to identify the minimum or maximum of 2 elements
based on the comparator logic that we pass,
34
JAVA 8 NEW FEATURES
P R I M I T I VE T Y P E F U N C T I O N A L I N T E R FAC ES
• All the functional interfaces like Predicate, Function, Consumer that we discussed previously
accepts or returns only Object type values like Integer, Double, Float, Long etc.
• There is a performance problem with this. If we pass any primitive input values like int, long,
double, float Java will auto box them in order to convert them into corresponding wrapper
objects. Similarly once the logic is being executed Java has to convert them into primitive
types using unboxing.
35
• Since there is lot of auto boxing and unboxing happening it may impact performance for
larger values/inputs. To overcome such scenarios Java has primitive type functional interfaces
as well.
Auto Boxing
Auto Unboxing
35
JAVA 8 NEW FEATURES
P R I M I T I VE T Y P E F U N C T I O N A L I N T E R FAC ES
• Below are the most important primitive functional interfaces provided by the Java team,
✓ java.util.function.IntFunction<R> - Always accepts int as input and return any type as output
R apply(int value);
36
JAVA 8 NEW FEATURES
P R I M I T I VE T Y P E F U N C T I O N A L I N T E R FAC ES
• Below are the most important primitive functional interfaces provided by the Java team,
✓ java.util.function.DoubleFunction<R> - Always accepts double as input and return any type as output
R apply(double value);
✓ java.util.function.LongFunction<R> - Always accepts long as input and return any type as output
37
R apply(long value);
✓ java.util.function.ToIntFunction<T> - Always return int value but accepts any type as input
✓ java.util.function.ToDoubleFunction<T> - Always return double value but accepts any type as input
37
JAVA 8 NEW FEATURES
P R I M I T I VE T Y P E F U N C T I O N A L I N T E R FAC ES
• Below are the most important primitive functional interfaces provided by the Java team,
✓ java.util.function.ToLongFunction<T> - Always return long value but accepts any type as input
✓ java.util.function.IntToLongFunction - Always takes int type as input and return long as return type
38
long applyAsLong(int value);
✓ java.util.function.IntToDoubleFunction - Always takes int type as input and return double as return type
✓ java.util.function.LongToIntFunction - Always takes long type as input and return int as return type
38
JAVA 8 NEW FEATURES
P R I M I T I VE T Y P E F U N C T I O N A L I N T E R FAC ES
• Below are the most important primitive functional interfaces provided by the Java team,
✓ java.util.function.LongToDoubleFunction - Always takes long type as input and return double as return
type
double applyAsDouble(long value);
✓ java.util.function.DoubleToIntFunction - Always takes double as input and return int as return type
39
int applyAsInt(double value);
✓ java.util.function.DoubleToLongFunction - Always takes double type as input and return long as return
type
long applyAsLong(double value);
✓ java.util.function.ToIntBiFunction - Always takes 2 input parameters of any type and return int as
return type
• Below are the most important primitive functional interfaces provided by the Java team,
✓ java.util.function.ToLongBiFunction - Always takes 2 input parameters of any type and return long as
return type
long applyAsLong(T t, U u);
✓ java.util.function.ToDoubleBiFunction - Always takes 2 input parameters of any type and return double
as return type 40
double applyAsDouble(T t, U u);
40
JAVA 8 NEW FEATURES
P R I M I T I VE T Y P E F U N C T I O N A L I N T E R FAC ES
• Below are the most important primitive functional interfaces provided by the Java team,
✓ java.util.function.ObjIntConsumer<T> - Always accepts 2 inputs of type int and any data type
41
void accept(T t, int value);
✓ java.util.function.ObjLongConsumer<T> - Always accepts 2 inputs of type long and any data type
✓ java.util.function.ObjDoubleConsumer<T> - Always accepts 2 inputs of type double and any data type
41
JAVA 8 NEW FEATURES
P R I M I T I VE T Y P E F U N C T I O N A L I N T E R FAC ES
• Below are the most important primitive functional interfaces provided by the Java team,
int getAsInt();
double getAsDouble();
boolean getAsBoolean();
42
JAVA 8 NEW FEATURES
P R I M I T I VE T Y P E F U N C T I O N A L I N T E R FAC ES
• Below are the most important primitive functional interfaces provided by the Java team,
43
JAVA 8 NEW FEATURES
P R I M I T I VE T Y P E F U N C T I O N A L I N T E R FAC ES
• Below are the most important primitive functional interfaces provided by the Java team,
44
JAVA 8 NEW FEATURES
METHOD REFERENCES
• Sometimes, there is already a method that carries out exactly the action that you’d like to pass
on inside lambda code. In such cases it would be nicer to pass on the method instead of
duplicating the code again.
• This problem is solved using method references in Java 8. Method references are a special
type of lambda expressions which are often used to create simple lambda expressions by
referencing existing methods.
45
• There are 4 types of method references introduced in Java 8,
• As you might have observed, Java has introduced a new operator :: (double colon) called as
Method Reference Delimiter.. In general, one don’t have to pass arguments to method
references. 45
JAVA 8 NEW FEATURES
METHOD REFERENCES
46
JAVA 8 NEW FEATURES
METHOD REFERENCES
47
JAVA 8 NEW FEATURES
METHOD REFERENCES
48
JAVA 8 NEW FEATURES
C O N ST R UC TO R R E F E R E N C ES
• String::new;
• Integer::new;
• ArrayList::new;
• UserDetail::new;
49
JAVA 8 NEW FEATURES
ST R E A M S A P I
• Java 8 introduced java.util.stream API which has classes for processing sequence of objects
that we usually stored inside the collections. The central API class is the Stream<T>.
• Don’t get confused with the java.io streams which are meant for processing the binary data
to/from the files.
java.io streams != java.util streams
• In Streams the code is written in a declarative way: you specify what you want to achieve
like in query style as opposed to specifying how to implement an operation.
50
JAVA 8 NEW FEATURES
ST R E A M S A P I
51
JAVA 8 NEW FEATURES
ST R E A M S A P I
• Inside java.util.Arrays52
new static methods were added to convert an array into a stream,
• To make an empty stream with no elements, we can use empty() method inside Stream class.
• To generate an infinite stream of elements which is suitable for stream of random elements, Stream has
2 static methods called Stream.generate() & Stream.iterate()
52
JAVA 8 NEW FEATURES
ST R E A M S A P I
Eazy E a z E a z y E
y ✓ a
z
B y t e y
Bytes B y t e
s B
y
Stream<String> map s flatMap t forEach
e
Stream of Words Stream<String[]> Stream<String> s Print the char values
54
JAVA 8 NEW FEATURES
ST R E A M S A P I
55
JAVA 8 NEW FEATURES
ST R E A M S A P I
56
JAVA 8 NEW FEATURES
ST R E A M S A P I
57
JAVA 8 NEW FEATURES
ST R E A M S A P I
✓ You can get a new stream from the initial data source to
traverse it again as you would for an iterator assuming it’s a
repeatable source like a collection but not an I/O channel.
58
✓ For example like in the example, if we try to traverse the
stream again after consuming all the elements inside it, we
will get an runtime ‘java.lang.IllegalStateException’ with a
message ‘stream has already been operated upon or closed’
58
JAVA 8 NEW FEATURES
ST R E A M S A P I
59
JAVA 8 NEW FEATURES
ST R E A M S A P I
✓ collectingAndThen() will be used in the scenarios where the stream elements need to be collected and then the collected
object needs to be transformed using a given rule\function. Using the collectingAndThen collector both these tasks of
collection and transformation can be specified and executed together.
✓ It accepts 2 parameters,
• 1st input parameter is downstream which is an instance of a Collector<T,A,R> i.e. the standard definition of a collector. In
other words, any collector
61 can be used here.
• 2nd input parameter is finisher which needs to be an instance of a Function<R,RR> functional interface.
61
JAVA 8 NEW FEATURES
ST R E A M S A P I
✓ The groupingBy() method of Collectors class in Java are used for grouping objects by some property and storing results in a
Map instance. In order to use it, we always need to specify a property by which the grouping would be performed. This method
provides similar functionality to SQL’s GROUP BY clause.
✓ Below is the sample code where we pass to the groupingBy method a Function (expressed in the form of a method reference)
extracting the corresponding Product.getPrice for each Product in the stream. We call this Function a classification function
specifically because it’s used to
62classify the elements of the stream into different groups.
62
JAVA 8 NEW FEATURES
ST R E A M S A P I
✓ Collectors partitioningBy() method is used to partition a stream of objects(or a set of elements) based on a given predicate.
The fact that the partitioning function returns a boolean means the resulting grouping Map will have a Boolean as a key type,
and therefore,there can be at most two different groups—one for true and one for false.
✓ Below is the sample code where we pass to the partitioningBy method a predicate function to partition all the products into
>$1000 and <=$1000.
63
✓ Compared to filters, Partitioning has the advantage of keeping both lists of the stream elements, for which the application of
the partitioning function returns true or false.
63
JAVA 8 NEW FEATURES
ST R E A M S A P I
✓ We can form a chain of stream operations using intermediate and terminal operation to achieve a desire output. This we also
call as stream pipeline.
✓ Suppose think of an example where I have list of int values inside a list where I want to filter all odd numbers, followed by
converting the remaining numbers by multiply themselves, sorting and at last display the output in a new list.
64
lambda code lambda code lambda
code
64
JAVA 8 NEW FEATURES
ST R E A M S A P I
65
Parallel Streams
✓ Streams interface allows you to process its elements in
parallel in a convenient way: it’s possible to turn a collection
into a parallel stream by invoking the method
parallelStream() on the collection source.
66
JAVA 8 NEW FEATURES
C O L L EC T I O N S Vs ST R EA MS
COLLECTIONS STREAMS
A collection is eagerly constructed and elements Stream is like a lazily constructed collection and
67
can be added or removed elements inside streams can’t be added or removed.
Collections doesn’t use functional interfaces using Streams uses lot of functional interfaces using
lambda expressions lambda expressions
They are non-consumable i.e. can be traversable Streams are consumable i.e. to traverse the stream,
multiple times without creating it again. it needs to be created every time.
Collections are iterated using external loops like Streams are iterated internally based on the operation
for, while mentioned like map, filter.
67
JAVA 8 NEW FEATURES
N E W DAT E A N D T I M E A P I ( J O DA )
• The date/time API, before Java 8, has multiple design problems such as java.util.Date and
SimpleDateFormatter classes aren't thread-safe. The date class doesn’t represent actual date
instead it specifies an instant in time, with millisecond precision.
• The years start from 1900, whereas the months start at index 0. Suppose if you want to
represent a date of 21 Sep 2017, you need to create an instance of date using the code below,
Date date
68= new Date(117, 8, 21); //Not very intuitive
• The problems with the java.util.Date are tried to handled by introducing new methods,
deprecating few of the methods inside it and with an alternative class java.util.Calendar. But
Calendar also has similar problems and design flaws that lead to error-prone code.
• On top of that the presence of both the Date and Calendar classes increases confusion among
developers which one to use. The DateFormat comes with its own set of problems. It isn’t
thread-safe and work only with the Date class.
68
JAVA 8 NEW FEATURES
N E W DAT E A N D T I M E A P I ( J O DA )
• With all the limitations that Java.util.Date/Calendar has Developers started using third-party
date and time libraries, such as Joda-Time.
• For these reasons, Oracle decided to provide high-quality date and time support in the native
Java API. As a result, Java 8 integrates many of the Joda-Time features in the java.time
package.
✓ java.time.LocalDate
✓ java.time.LocalDateTime
✓ java.time.Instant
✓ java.time.Duration
✓ java.time.Period
69
JAVA 8 NEW FEATURES
N E W DAT E A N D T I M E A P I ( J O DA )
java.time.LocalDate
• An instance of this class is an immutable object representing a plain date without the time of
day. In other words, it doesn’t carry any information about the time/time zone.
70
JAVA 8 NEW FEATURES
N E W DAT E A N D T I M E A P I ( J O DA )
java.time.LocalTime
• If we have to deal with only time of the day ignoring Date value, then we can use LocalTime
class.
71
JAVA 8 NEW FEATURES
N E W DAT E A N D T I M E A P I ( J O DA )
java.time.LocalDateTime
72
72
JAVA 8 NEW FEATURES
N E W DAT E A N D T I M E A P I ( J O DA )
✓ For humans we use Date and time, but for machines the
time is calculated based on number of seconds passed
from the Unix epoch time, set by convention to midnight
of January 1, 1970 UTC. So to represent them we have
Instant class
73
JAVA 8 NEW FEATURES
N E W DAT E A N D T I M E A P I ( J O DA )
Calendar systems
✓ The ISO-8601 calendar system is the default calendar system considered in Java. But four additional calendar systems are
provided in Java 8. Each of these calendar systems has a dedicated date class: ThaiBuddhistDate, MinguoDate, JapaneseDate,
and HijrahDate (Islamic).
75
75
JAVA 8 NEW FEATURES
N E W DAT E A N D T I M E A P I ( J O DA )
76
JAVA 8 NEW FEATURES
C O M P L E TA B LE F UT UR E
• This will run tasks on a separate thread than the main application thread and notifying the
main thread about its progress, completion or failure. This way, your main thread does not
block/wait for the completion
77 of the task and it can execute other tasks in parallel.
• CompletableFuture has below important methods that can be used for async programming,
✓ runAsync() -> Runs async in the background and will not return anything from the task
✓ supplyAsync() -> Runs async in the background and will return the values from the task
✓ get() -> It blocks the execution until the Future is completed
✓ thenApply()/ thenAccept() -> For attaching a callback to the CompletableFuture
77
JAVA 8 NEW FEATURES
M A P E N H A N C E M E N TS
• Java 8 team provides several default methods inside Map interface. Below are the few
important enhancements happened for Map,
✓ forEach() - > Using this we can iterate the map values easily
✓ Entry.comparingByValue -> Sorting the map elements based on value
✓ Entry.comparingByKey -> Sorting the map elements based on key
✓ getOrDefault() –78Can be used to pass a default value instead of null if key is not present
✓ computeIfAbsent() – Can be used to calculate a value if there is no for given key
✓ computeIfPresent() – If the specified key is present, calculate a new value for it
✓ Compute() - Calculates a new value for a given key and stores it in the Map
✓ remove(key,value) – To remove a map element if both key & value matches
✓ replace() – For replacement of values if the key is available
✓ replaceAll() - For replacement of all the values inside the map
78
JAVA 8 NEW FEATURES
M A P E N H A N C E M E N TS
• The internal structure of a HashMap was updated in Java 8 to improve performance. Entries of
a map typically are stored in buckets accessed by the generated hashcode of the key. But if
many keys return the same hashcode, performance deteriorates because buckets are
implemented as LinkedLists with O(n) retrieval. But now if the buckets become too big, they’re
replaced dynamically with sorted trees,which have O(log(n)) retrieval and improve the lookup
of colliding elements.
79
• The ConcurrentHashMap class was update to improve performance while doing read and write
operations
• Java 8 team made the most out of the default methods introduced and added several new
methods in the collection interfaces & other classes. Below is the snapshot of the same,
FUNCTIONAL INTERFACE
05 A new type of interfaces called Functional interfaces are
introduced in Java 8. This will have only 1 abstract method and
they support lambda programming to a great extent.
81
METHOD REFERENCES
06 Method references can be used to create simple lambda
expressions by referencing existing methods.
CONSTRUCTOR REFERENCES
07 Constructor reference can be used in the place of lambda code
to create a new objects by using new operator
COMPLETABLEFUTURE
10 CompletableFuture is introduced focusing async and non-
blocking programming in Java 8.
82
MAP ENHANCEMENTS
11 Multiple default and static methods are introduced
inside Map interface
JAVA 8 FEATURES
83
SUMMARY
83
JAVA 8 NEW FEATURES
R E L E A S E N OT E S & G I T H U B L I N K
Apart from the discussed new features, there are many security, non developer focused
features are introduced in Java 8. For more details on them, please visit the link
https://www.oracle.com/java/technologies/javase/8all-relnotes.html
84
https://github.com/eazybytes/Java-New-features/tree/main/Java8
84
THANK YOU & CONGRATULATIONS
Y O U A R E N O W A M A S T E R O F J AVA 8 N E W F E AT U R E S
85
85