Java 7 features:
1.
Strings allowed in Switch condition. The switch statement
compares the String object in its expression with the expressions
associated with each case label as if it were using the String.equals method;
consequently, the comparison of String objects in switch statements
is case sensitive. The Java compiler generates generally more efficient
bytecode from switch statements that use String objects
than from chained if-then-else statements.
2.
Catch multiple exceptions in single catch block
using ‘|’,hence lesser byte code.
e.g. Catch narrower exception then use pipe “|”
and then broader execption.
catch (IOException|SQLException ex) {
logger.log(ex);
throw ex;
}
|
3.
try with resources:
a.
Automatic resource management.
i.
Resource is automatically closed after code
exits from try block normally or due to exception. Resource must implement new
interface java.lang.AutoCloseable which is extended by java.io.Closeable ,otherwise
code will not compile.
ii.
The main thing to be noted
b.
Due to automatic resource management we don’t
need finally to close the resource connection hence lesser byte code
c.
In old try-finally if the exception is thrown in
both try and finally the exception which gets propagated to calling method is exception
from finally block not the exception from try block. Whereas in case of try
with resource the exception which gets propagated to calling method is exception
occurred in try block.
e.g.
static String readFirstLineFromFile(String
path) throws IOException {
try (BufferedReader br
=
new BufferedReader(new
FileReader(path))) {
return br.readLine();
}
}
|
d. If try contains multiple resources then ,when try block is executed or exception occurs the resources are closed in reverse order to to manage dependency.
e.g.
List<String> list = new ArrayList<>();