Java 7 & 8 New Features: Zero To Master
Java 7 & 8 New Features: Zero To Master
ZERO TO MASTER
1
1
JAVA 7 NEW FEATURES
AGENDA
TRY-WITH-RESOURCES
1. STATEMENT 2. SUPPRESSED EXCEPTIONS
RETHROWING EXCEPTIONS
3. CATCHING MULTIPLE EXCEPTIONS 4. WITH TYPE CHECKING
2
2
JAVA 7 NEW FEATURES
AGENDA
TYPE INFERENCE/DIAMOND
11. BINARY LITERALS
3 12. OPERATOR
USING UNDERSCORE IN
13. NUMERIC LITERALS 14. JDBC IMPROVEMENTS
.
4
JAVA 8 NEW FEATURES
AGENDA
5
11. MAP ENHANCEMENTS 12. OTHER MISCELLANEOUS UPDATES
5
JAVA 7 & 8 NEW FEATURES
PREREQUISITES
6
JAVA VERSION HISTORY
M I L E S T O N E D AT E S
7
01/1996 12/1998 02/2002 12/2006
7
JAVA VERSION HISTORY
M I L E S T O N E D AT E S
8
JAVA VERSION HISTORY
M I L E S T O N E D AT E S
Java SE 14 Java SE 16
09/2020 09/2021*
9
03/2020 03/2021*
9
JAVA VERSION HISTORY
M I L E STO N E DAT E S
✓ Previously on an average Java use to release an version every 2 years. In some cases it even 5
years. But Java team realized that this approach will no longer sustainable because it will not
evolve Java language fast enough to compete with other languages.
✓ But when ever a non-LTS or LTS version release, the previous non-LTS versions will be archived
and no support will be provided for them.
✓ For example, with Java 10 release since Java 9 is a non-LTS version it will be archived and
support will be stopped. But all the new features from Java 9 will be present in Java 10 as well.
10
DIFFERENT JDK VENDORS IN JAVA
ORACLE JDK, OPEN JDK, ADOPTOPENJDK
Open JDK
AdoptOpenJDK
In terms of Java source code,
there is only one, living at11 In 2017, a group of vendors
the OpenJDK project site. (Amazon, Microsoft, Pivotal,
These builds are free and Redhat and others) started a
unbranded, but Oracle won’t Oracle JDK
community, called
release updates for older OracleJDK, which is a branded,
versions, say Java 15, as AdoptOpenJDK.
commercial build starting with the
soon as Java 16 comes out. They provide free, rock-solid
license change in 2019. Which means
OpenJDK builds with longer
it can be used for free during
availibility/updates
development, but you need to pay
https://openjdk.java.net/. Oracle if using it in production. https://adoptopenjdk.net/
https://www.oracle.com/java/technologies/javase-downloads.html
11
JAVA 7 NEW FEATURES
T H E T RY - W IT H - R E SO U RC ES STAT E ME N T
• To make Developer life easy and improve the quality of the code, a new feature called ‘TRY-
WITH-RESOURCES statements’ are introduced.
• Using this we don’t have to explicitly close the resource. We just have to initialize the
resources details inside the () immediately next to try keyword. In its simplest form, the try-
with-resources statement can be written as,
12
try (BufferedReader br = ...) {
//work with br
}
• When try block execution completes the br.close() method will be automatically called by JVM.
For this a new interface is created in Java 7 which is ‘java.lang.AutoCloseable’.
12
JAVA 7 NEW FEATURES
T H E T RY - W IT H - R E SO U RC ES STAT E ME N T
• But the new Interface(AutoCloseable) can be used in more general contexts, where the
exception thrown during closing is not necessarily an IOException.
• A try-with-resources statement can itself have catch and finally clauses for other requirements
inside the application.
• You can specify multiple resources as well inside the try-with-resources statement.
13
JAVA 7 NEW FEATURES
T H E T RY - W IT H - R E SO U RC ES STAT E ME N T
14
• All resource reference variables should be final or effective final. So we can’t perform reassignment with
in the try block.
• Till Java 1.6, try block should be followed by either catch or finally block but from Java 7 we can have
only try with resource block with out catch & finally blocks.
14
JAVA 7 NEW FEATURES
S U P P R E S S E D E XC E P T I O N S
• Suppressed exceptions are the exceptions thrown in the code but were ignored somehow.
One of the classic example is in the scenario’s ‘try-catch-finally’ block execution, where we
received an exception in try block and again there is one more exception thrown due to which
the super exception from try block will be ignored.
• To support suppressed exceptions better handling, a new constructor and two new methods
were added to the Throwable
15 class (parent of Exception and Error classes) in JDK 7.
✓ Throwable.addSupressed(aThrowable);
✓ Throwable.getSupressed(); // Returns Throwable[]
15
JAVA 7 NEW FEATURES
C ATC H I N G M U LT I P L E E XC E P T IO N S
• Before Java 7, suppose if you have the same action need to be performed in the case of
different RuntimeException exceptions like NullPointerException &
ArrayIndexOutOfBoundsException we will forced to write multiple catch blocks like below,
16
16
JAVA 7 NEW FEATURES
C ATC H I N G M U LT I P L E E XC E P T IO N S
• To reduce the code duplication in the scenarios where we have a common action/business
logic need to be performed for different run time exceptions we can use a single catch block
with multiple exceptions separated by a | operator as shown below,
17
• When you catch multiple exceptions, the exception variable is implicitly final. So, you cannot
assign a new value to ex in the body of the catch clause
17
JAVA 7 NEW FEATURES
R E T H ROW I N G E XC E P T I O N S W I T H M O R E I N C LU S I VE T Y P E C H EC K I N G
• The Java SE 7 compiler performs more precise analysis of rethrown exceptions than earlier
releases of Java SE. This enables you to specify more specific exception types in the throws
clause of a method declaration.
18
18
JAVA 7 NEW FEATURES
R E T H ROW I N G E XC E P T I O N S W I T H M O R E I N C LU S I VE T Y P E C H EC K I N G
• This examples' try block could throw either FirstException or SecondException. Suppose you
want to specify these exception types in the throws clause of the beforeJava7 method
declaration. In releases prior to Java SE 7, you cannot do so. Because the exception parameter
of the catch clause, e, is type Exception, and the catch block rethrows the exception parameter
e, you can only specify the exception type Exception in the throws clause of the beforeJava7
method declaration.
19
• However, in Java SE 7, you can specify the exception types FirstException and SecondException
in the throws clause in the rethrowException method declaration. The Java SE 7 compiler can
determine that the exception thrown by the statement throw e must have come from the try
block, and the only exceptions thrown by the try block can be FirstException and
SecondException. Even though the exception parameter of the catch clause, e, is type
Exception, the compiler can determine that it is an instance of either FirstException or
SecondException.
19
JAVA 7 NEW FEATURES
R E T H ROW I N G E XC E P T I O N S W I T H M O R E I N C LU S I VE T Y P E C H EC K I N G
20
20
JAVA 7 NEW FEATURES
E A S I E R E XC E P T IO N H A N D L I N G F O R R E F L EC TI VE M E T H O D S
• Before Java 7 when we try to invoke methods inside a class using reflections, the developer
will be forced to handle multiple exceptions related to reflections as shown below,
21
• This is a very annoying and tedious job for the developers to handle all these exceptions. Ideally all
these exceptions should have been grouped together.
21
JAVA 7 NEW FEATURES
E A S I E R E XC E P T IO N H A N D L I N G F O R R E F L EC TI VE M E T H O D S
• From Java 7, all the exceptions related to reflections are grouped by creating a common super
class called java.lang.ReflectiveOperationException
22
22
JAVA 7 NEW FEATURES
E A S I E R E XC E P T IO N H A N D L I N G F O R R E F L EC TI VE M E T H O D S
extends
23
✓ java.lang.ClassNotFoundException
✓ java.lang.NoSuchMethodException
✓ java.lang.InvocationTargetException
✓ java.lang.IllegalAccessException
23
JAVA 7 NEW FEATURES
O B J EC T S C L A S S & N U L L C H EC KS
• Java 7 introduced a new class “java.util.Objects” consists of utility static methods for operating
on objects. This methods include null checks, computing hash code, comparing two objects,
returning a string for an object.
• Importantly the Objects class has the below 2 methods to null-check the object. Both of them
will throw NullPointerException if the given object is null and the custom message also can be
passed to display on24the NullPointerException details.
✓ requireNonNull(T obj)
✓ requireNonNull(T obj, String message)
• It may look for the developers why I should use these methods as if the object is null anyways
the NullPointerException will be thrown by the code. But these methods provides controlled
behavior, easier debugging.
24
JAVA 7 NEW FEATURES
C LO S E M E T H O D I N S I D E U R LC LA S S LOA D E R
• java.net.URLClassLoader is used to load classes and resources from a search path of URLs
referring to both JAR files and directories.
• Before Java 7, code such as this could lead to resource leaks. Java 7 simply adds a close method
to close the URLClassLoader by implementing AutoCloseable. So from Java 7 you can use a try-
with-resources statement as shown below,
25
JAVA 7 NEW FEATURES
@ SA F E VA R A RGS A N N OTAT IO N
• Java 5 introduced the concept of varargs, or a method parameter of variable length, as well
as parameterized types. @SafeVarargs annotation is introduced in JDK 7 which is used to
suppress the unsafe operation warnings at the compile time.
• @SafeVarargs annotation is used to indicate that methods will not cause heap pollution.
These methods are considered to be safe.
26
• @SafeVarargs can only be applied on
✓ Final methods
✓ Static methods
✓ Constructors
26
JAVA 7 NEW FEATURES
E N H A N C E M E N T S R E L AT E D TO F I L E S & D I R EC TO R I E S
• Java 7 brought series of enhancements which will help developers while doing operations
related to files like reading, copying & deleting.
• Java team refreshed the NIO(new I/O) package in Java 7 which originally introduced in Java 1.4
• Below are the newly created interfaces and classes created in Java 7,
27
✓ java.nio.file.Path
✓ java.nio.file.Paths
✓ java.nio.file.Files
• These new interfaces and classes from ‘java.nio.file.*’ package can be used to overcome the
limitations of the “java.io.File” class.
27
JAVA 7 NEW FEATURES
E N H A N C E M E N T S R E L AT E D TO F I L E S & D I R EC TO R I E S
• A Path is a sequence of directory names, optionally followed by a file name and it is the main
entry point to all operations involving file system paths. It allows us to create and manipulate
paths to files and directories.
28
• The utility class, java.nio.file.Paths (in plural form) is the formal way of creating Path objects. It
has two static methods for creating a Path from a path string & URI.
• The static Paths.get method receives one or more strings, which it joins with the path
separator of the default file system (/ for a Unix-like file system, \ for Windows).
28
JAVA 7 NEW FEATURES
E N H A N C E M E N T S R E L AT E D TO F I L E S & D I R EC TO R I E S
Important methods inside Path & Paths Important methods inside Files
Files.readAllBytes()
Path.getFileSystem()
Files.readAllLines()
Path.isAbsolute()
Files.write()
Path.getRoot()
Files.newInputStream()
Path.getFileName()
Files.newOutputStream()
Path.getParent()
29
Files.newBufferedReader()
Path.startsWith()
Files.newBufferedWriter()
Path.endsWith()
Files.copy()
Path.normalize()
Files.createDirectory()
Path.resolve()
Files.createFile()
Path.relativize()
Files.createTempFile()
Path.toUri()
Files.createTempDirectory()
Path.toAbsolutePath()
Files.move()
Path.toFile()
Paths.get() Files.delete()
Files.deleteIfExists()
29
JAVA 7 NEW FEATURES
WATC H S E RV IC E
• It is very common for many application to track on files such as configuration so that we can
refresh the value inside
30 the memory on every change. We used to handle using a Thread that
periodically poll for file change before Java 7. But this made easy using ‘WatchService’.
• A Watchable object is registered with a watch service by invoking its register method,
returning a WatchKey to represent the registration. When an event for an object is detected
the key is signaled, and if not currently signaled, it is queued to the watch service so that it can
be retrieved by consumers that invoke the poll or take methods to retrieve keys and process
events. Once the events have been processed the consumer invokes the key's reset method to
reset the key which allows the key to be signaled and re-queued with further events.
30
JAVA 7 NEW FEATURES
WATC H S E RV IC E
I m p o r t a n t m e t h o d s & c l a s s e s r e l a t e d t o Wa t c h S e r v i c e
WatchService.poll()
WatchService.take()
WatchService.close()
Watchable.register()
31
WatchKey.isValid()
WatchKey.pollEvents()
WatchKey.reset()
WatchKey.cancel()
WatchKey.watchable()
StandardWatchEventKinds. ENTRY_CREATE/
ENTRY_DELETE/ENTRY_MODIFY/OVERFLOW
31
JAVA 7 NEW FEATURES
B I N A RY L I T E R A L S
• A binary literal is a number that is represented in 0s and 1s (binary digits). Java allows you to
express integral types (byte, short, int, and long) in a binary number system especially when
we are dealing with the bit-wise operators.
32
JAVA 7 NEW FEATURES
ST R I N G I N SW I TC H STAT E M E N T
• Before Java 7, switch statements allows only Enum and int types.
• From Java 7, Java allows to use String objects in the expression of switch statement.
• String value is case sensitive and null objects are not allowed. In case if you use null value, java
will throw an NullPointerException.
33
• It must be only String object and normal Object is not allowed
switch (input)
{
case (“Monday”):
System.out.println(“Today is Monday");
break;
default:
System.out.println(“Today is not a Monday");
}
33
JAVA 7 NEW FEATURES
T Y P E I N F E R E N C E / D I A M O N D O P E R ATO R
• Before Java 7, we have to create an object with Generic type on both side of the expression
like below:
• From Java 7, Java provides a improved compiler which is smart enough to infer the type of
generic instance. It simplifies
34 the use of generics when creating an object.
• It is also called as Diamond operator. Using it we can create the object without mentioning
generic type on right side of expression like below:
• Please note that we can’t use this diamond operator feature inside the anonymous inner class.
But this limitation is resolved in Java 9.
34
JAVA 7 NEW FEATURES
U S I N G U N D E R S CO R E I N N U M E R I C L I T E R A LS
• From Java 7, we can use the underscore(_) inside the numeric values to improve readability of
the code. However the compiler will remove them internally while processing the numeric
values.
• For example if our code contains numbers with many digits, we can use an underscore
character to separate digits in groups of three, similar to how we would use a punctuation
mark like a comma in mathematics.
35
int num = 1_00_00_000;
• But please note that below restrictions while using the underscore inside your numeric values,
• With the help of new RowSetFactory interface and the RowSetProvider class, we can create a
RowSet objects of CachedRowSet/ FilteredRowSet / JdbcRowSet / JoinRowSet / WebRowSet.
Before Java 7 we used to depend on JdbcRowSetImpl class for the same.
36
JAVA 7 NEW FEATURES
G A R BAGE - F IRST C O L L EC TO R
• The older garbage collectors (serial, parallel, CMS) all structure the heap into three
sections: young generation,
37 old generation, and permanent generation of a fixed memory
size. All memory objects end up in one of these three sections.
37
JAVA 7 NEW FEATURES
G A R BAGE - F IRST C O L L EC TO R
• The G1 collector takes a different approach. The heap is partitioned into a set of equal-
sized heap regions, each a contiguous range of virtual memory. Certain region sets are
assigned the same roles (eden, survivor, old) as in the older collectors, but there is not a
fixed size for them. This provides greater flexibility in memory usage.
38
38
JAVA 7 NEW FEATURES
G A R BAGE - F IRST C O L L EC TO R
• Compared to most other garbage collectors, the G1 has two big advantages:
✓ It can do most of its work concurrently (i.e., without halting application threads), and
✓ Splitting the heap into small regions enables the G1 to select a small group of regions
to collect and finish quickly.
✓ One of the good property of this is you can configure this for maximum pause time
using flag (-XX:MaxGCPauseMillis=n)
39
• G1 will be more suitable for users running applications that require large heaps with
limited GC latency. This means heap sizes of around 6GB or larger, and stable and
predictable pause time below 0.5 seconds.
• From Java 9, the Garbage First (G1) GC as its default garbage collector.
39
JAVA 7 NEW FEATURES
F O R K & J O I N F R A M E WO R K
• To address that Java 7 introduces new Fork & Join framework that supports parallel
processing by splitting (forking) big tasks into a multiple small subtasks that can be
processed independently
40 by using all the available CPU cores and eventually joining the
results from all the subtasks to get the final results.
40
JAVA 7 NEW FEATURES
F O R K & J O I N F R A M E WO R K
• Applying a divide and conquer principle, the framework recursively divides the task into
smaller subtasks until a given threshold is reached. This is the fork part.
• Then, the subtasks are processed independently and if they return a result, all the results
are recursively combined into a single result. This is the join part.
41 Fork Result
Subtask
Join
Fork
Fork Result
Subtask
Subtask
Final
Task Join Result
Fork Result
Fork Subtask
Subtask
Join
Fork
Result
Subtask
41
JAVA 7 NEW FEATURES
F O R K & J O I N F R A M E WO R K
• Important interfaces and classes inside the Fork & Join framework,
• ForkJoin framework follows ‘Work Stealing Algorithm’ where free threads try to “steal” work from
deques of busy threads
• In fact, Java 8's parallel streams underline uses the ForkJoin framework.
42
THE TRY-WITH-RESOURCES STATEMENT
01 JVM handles closing the resources opened in the code
automatically after the try block by calling close().
SUPPRESSED EXCEPTIONS
02 Handles the scenarios where we get multiple exceptions
by holding all the subsequent exceptions inside an
array.
JAVA 7
43 03
CATCHING MULTIPLE EXCEPTIONS
A single catch block can handle multiple exceptions
JAVA 7
44 08
ENHANCEMENTS TO FILES & DIRECTORIES
New interfaces, classes like Path, Paths, Files introduced
WATCHSERVICE
09 Provides easier approach to track any directory/ files
changes instead of using Threads.
GARBAGE-FIRST COLLECTOR
14 A new garbage framework is build to handle
applications that have large heap sizes.
Apart from the discussed new features, there are many security, non developer focused
features are introduced in Java 7. For more details on them, please visit the link
https://www.oracle.com/java/technologies/javase/jdk7-relnotes.html
46
https://github.com/eazybytes/Java-New-features/tree/main/Java7
46
THANK YOU & CONGRATULATIONS
Y O U A R E N O W A M A S T E R O F J AVA 7 N E W F E AT U R E S
47
47