JavaBeat

  • Home
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Privacy

Whats new in Java 7 – try-with-resource construct in Project Coin

May 4, 2012 by Mohamed Sanaulla Leave a Comment

In our previous post we looked at different features added as part of Project Coin, in this post we will look at another language construct added as part of Java 7 and Project Coin in particular. It is the try-with-resource construct also called as Automatic Resource Management. Before getting into the details of the construct, let me show you some basic code which I would be using through out this example.

also read:

  • Java 7.0 Tutorials
  • New Features in Java 7.0
  • G1 Garbage Collector in Java 7.0

Lets create a class called Resource which implements Closeable interface and its a dummy resource class something on liens of a FileReader or your other IO classes. Lets also have a custom exception say SomeException which extends Exception class. The code for the two is as follows:

[code lang=”java”]
class Resource implements Closeable{

public String resourceName;
public Resource(String resourceName) throws SomeException{
this.resourceName = resourceName;
System.out.println(this.resourceName+" created!
Might throw an exception");
}

public void useResource() {
System.out.println("Using the resource "+this.resourceName);
}

@Override
public void close() throws IOException {
System.out.println("Closing the resource "+this.resourceName);
}
}

class SomeException extends Exception{
}
[/code]

Suppose I wanted to create an instance of Resource and use it, prior to the try-with-resource construct we would do something like:

[code lang=”java”]
Resource myResource = null;
try{
myResource = new Resource("POOR OLD RESOURCE");
myResource.useResource();
}catch(SomeException ex){
ex.printStackTrace();
}finally {
if (myResource != null) {
try {
myResource.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
[/code]

Output:

[shell]
POOR OLD RESOURCE created! Might throw an exception
Using the resource POOR OLD RESOURCE
Closing the resource POOR OLD RESOURCE
[/shell]
We generally clear all the resources in the finally block because that is the one which is called irrespective of the exception being thrown or not. But close() method in the Closeable interface itself throws an IOException which makes us to use another try..catch block in the finally method. Now, if both the try block and the catch block throw exception, prior to Java 7 the one thrown in the try block would have been suppressed by the one thrown in the catch block. In Java 7 there’s has been a new API added to Throwable which states- getSuppressedExeceptions. Let me not go into those details now. Coming back to our try-with-resources construct, the above code can be written concisely as:

[code lang=”java”]
try ( Resource myResource2 = new Resource("TRY-WITH-RESOURCE")){
myResource2.useResource();
}catch ( SomeException | IOException ex){
ex.printStackTrace();
}
[/code]

Output:

[shell]
TRY-WITH-RESOURCE created! Might throw an exception
Using the resource TRY-WITH-RESOURCE
Closing the resource TRY-WITH-RESOURCE
[/shell]

Look at the reduction in the number of lines, and also it makes the code more readable. The construct:

[code lang=”java”]
try ( Resource myResource2 = new Resource("TRY-WITH-RESOURCE"))
[/code]

is the new construct added as part of Project Coin. One can use and declare multiple resource within the try block.

[code lang=”java”]
try ( Resource myResource2 = new Resource("TRY-WITH-RESOURCE");
Resource myResource3 = new Resource("TRY-WITH-RESOURCE2"))
[/code]

The complete code can be downloaded from here.

Filed Under: Java Tagged With: Java, java 7, project coin

What’s new in Java 7- Features as part of Project Coin

May 2, 2012 by Mohamed Sanaulla Leave a Comment

As part of the Project Coin, there were quite a few language enhancements were added to the Language. The last time Java language changed was in the Java 5 release when Generics were added. The changes in introduced in the Java 7 were welcomed by java community around the world. This was seen as a stepping stone to the plethora of changes to be introduced with Java 8 and above. Nonetheless Java 7 has its own set of issues, but this shouldn’t be a concern for someone to download the latest build and give it a shot.

also read:

  • Java 7.0 Tutorials
  • New Features in Java 7.0
  • G1 Garbage Collector in Java 7.0

In this post I would like to pick a few features added as part of Project Coin and in the coming posts try to cover the remaining features. The enhancements we would be looking at are:

  • String in Switch statements.
  • Generic Type Inference (Diamond Operator)
  • Multi Catch blocks
  • Binary Integral literals and underscores in numeric literals.

Generic Type Inference (Diamond Operator)
Pre Java 7, for a map of string versus list of integers we would have a declaration like:
[code lang=”java”]
Map<Stirng,List<Integer>> myMap = new HashMap<Stirng,List<Integer>>();
[/code]

we could also write:
[code lang=”java”]
Map<Stirng,List<Integer>> myMap = new HashMap();
[/code]

But for the above code the compiler would issue an warning:

[shell]Note: Java7FeatureDemo.java uses unchecked or unsafe operations.[/shell]

With Java 7, the above declaration is equivalent to:
[code lang=”java”]
Map<Stirng,List<Integer>> myMap = new HashMap<>();
[/code]

The compiler now would inference the type based on the declaration on the left. This is in my opinion is a good step towards removing redundancy in the declaration.

If you are using a IDE which supports Java 7 language enhancements, in my case I was using IntelliJ, when you use the pre Java 7 type of declaration it suggests:

Java 7 - Diamond Operator

Strings in switch:
Prior to Java 7, we didn’t have an option to use Strings in switch. An alternative approach was to use enums in the switch statement:

[code lang=”java”]
public class PreJava7 {
enum GRADE{
A,B,C,D;
}

public static void main(String[] args){

GRADE choice = GRADE.A;

switch (choice){
case A:
System.out.println("A chosen");
break;
case B:
System.out.println("B chosen");
break;
case C:
System.out.println("C chosen");
break;
}
}
}
[/code]

With Java 7 the same code can be written as:

[code lang=”java”]
String choice = "A";

switch (choice){
case "A":
System.out.println("A chosen");
break;
case "B":
System.out.println("B chosen");
break;
case "C":
System.out.println("C chosen");
break;
}
[/code]

Multi Catch blocks:
If a code block throws multiple exceptions and you want all of the catch blocks to do the same operation, say logging the exception, we would write something like:

[code lang=”java”]
public class PreJava7 {
public static void main(String[] args){
try {
exceptionMethod1();
exceptionMethod2();
} catch (IOException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
}

}
static void exceptionMethod1() throws IOException{}
static void exceptionMethod2() throws NoSuchFieldException{}
}
[/code]

Look at the redundancy of code in both the catch blocks. With the introduction of Mutli catch blocks, the same catch block can be used to capture multiple exceptions thereby leading to code reuse. So the modified code would be:

[code lang=”java”]
try {
exceptionMethod1();
exceptionMethod2();
} catch (IOException | NoSuchFieldException e) {
e.printStackTrace();
}
[/code]

If you use an IDE which supports Java 7 features, then using multiple catch blocks would generate the suggestion as follows:
Java 7 Multiple Catch Blocks

Binary Integral literals and underscores in numeric literals:
Binary literals can be represented by using b or B, just like the way we used x for Hexadecimal literals.

[code lang=”java”]
int binary1 = 0b011;
int binary2 = 0B111;

System.out.println(binary1);
System.out.println(binary2);
[/code]

Now coming to the underscores in numeric literals:
Pre Java 7, we would write something like:

[code lang=”java”]
int hugeNumber = 1000000000;
[/code]

A trivia now: How fast can you count the number of zeros in hugeNumber? The time taken to count the number increases with the age of a person. Jokes apart, lets see how this is can be changed with Java 7 enhancement:

[code lang=”java”]
int hugeNumber2 = 1_000_000_000;
System.out.println(hugeNumber == hugeNumber2);//Prints True
[/code]

So, how easy is it now to count the number of zeros?

These were some of the few enhancements added as part of Project Coin in Java 7 release. There are few more features which were pushed to Java 8 and another feature try-with-resources ( Automatic Resource Management) which is part of Java 7 and I would write about it in my upcoming posts.

If you are interested in obtaining a fully functional code, please do it from here.
Note: In order to run the examples given above you need to download the JDK 7 from here.

Filed Under: Java Tagged With: Java, java 7, project coin

Follow Us

  • Facebook
  • Pinterest

As a participant in the Amazon Services LLC Associates Program, this site may earn from qualifying purchases. We may also earn commissions on purchases from other retail websites.

JavaBeat

FEATURED TUTORIALS

Answered: Using Java to Convert Int to String

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Copyright © by JavaBeat · All rights reserved