Recently released Java 7 has a lot of useful API enhancements such as the automatic resource management, multi-catch statements, switch statement with strings, binary literals and improved numeric literals. This post is a quick roundup of the new features, which should help you to get a full picture of Java 7 syntax in a short time.
Automatic Resource Management
The try-with-resources statement is a 'try' that accepts one or more resources which will be closed automatically when
the statement completes. Resources must implement the AutoCloseable
or Closeable
interface to be used with the
try-with-resources block:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
1 2 3 4 5 6 7 8 9 10 11 |
|
Catching multiple exception types
A single catch block can handle several different exception types, which was impossible in prior Java versions. For example, the try-catch:
1 2 3 4 5 |
|
can be replaced with:
1 2 3 4 |
|
Strings in switch statements
Java 7 finally allows to use a String
object in the expression of a switch statement. The new switch compares strings
using the String.equals()
method:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
|
This code works the same as the following if-then-else chain:
1 2 3 4 5 6 7 8 9 10 11 12 |
|
The switch statement, of course, is much more preferable choice, as the code generated by a compiler will be more efficient.
Binary literals
New binary literals must be prefixed with 0b or 0B, for example:
1 2 3 |
|
You can also use binary literals to express integral types:
1 2 3 4 |
|
Binary literals are very convenient in bitwise and bitshift operations:
1 2 3 4 5 |
|
Underscores in numeric literals
Any numeric literal can be separated into groups using underscore characters. The literal will be invalid if it has underscores that are placed:
- before or after a decimal point
- before F, f, D, d, ... suffixes
- at the literal beginning or end
Correct:
1 2 3 |
|
Incorrect:
1 2 3 4 |
|
Underscores can be used to visually separate digits and make code more readable, for example, binary or hexadecimal literals can be separated by bytes:
1
2
int i1 = 0b10010010_10010010_10010010_10010010
int i2 = 0x92_92_92_92
These are almost all syntax changes in Java 7, and yes, it would be nice to have more syntactic sugar. The good news is the Java 8 release is coming soon, which, with lambda expressions and method references, promises to have a lot of extremely interesting features and improvements.
Scala / Groovy Developer & Technical Lead
Looking to hire a software developer?
Don't hesitate to contact us.
Comments