Thursday, December 05, 2013

What's new in Java 7

I have been reading  about Java 1.7. There are articles about what's new,I have read them and compromised to write the language changes with examples.
So the normal developer can understand the changes easily by examples.Here I am mainly focusing on language  changes  I have taken these language changes from wikipedia https://en.wikipedia.org/wiki/Java_version_history#Java_SE_7_.28July_28.2C_2011.29. You can see all other changes here.

Language Changes 
  • Strings in switch
  • Automatic resource management in try-statement 
  • Improved type inference for generic instance creation, aka the diamond operator <>
  • Language  Support for Collections.
  • Binary integer literals
  • Allowing underscores in numeric literals
  • Catching multiple exception types and re throwing exceptions with improved type checking

There is a list of other features available on the OpenJDK 7 features page.


Code examples for new features in Java 1.7

Strings in switch
Nothing to explain here, the title says it all.
String color = "RED";
switch(color) {
     case "RED":
          //code
         break;
     case "GREEN":
        //code
        break;
     case "BLUE":
        //code
        break;
    default:
      //code
      break;
}


Automatic Resource Management

Many of our developers for got to close the resources and it should be done in finally block. Now the resources will be closed automatically and with out finally block

BufferedReader br = new BufferedReader(new FileReader(path));
try {
     return br.readLine();
finally {
      br.close();
}

Become this:

try (BufferedReader br = new BufferedReader(new FileReader(path)) {
return br.readLine();
}

Improved Type Inference for Generic Instance Creation (diamond)
Same thing, today you specify the Generic when you declare the interface of your object and
then you have to repeat yourself when you instantiate the object. You won't have to now as you
can do. this feature is informally called as diamond. Yes it is really diamond.

Map<String, List<String>> map = new HashMap<>();

Language support for collections
This is all about writing less code when you create a List, a Set or a Map. You don't have to
instantiate the Object and then add the element to the Collection. You can now do it in 1 line.


List<String> list = ["item"];
String item = list[0];
Set<String> set = {"item"};
Map<String, Integer> map = {"key" : 1};
int value = map["key"];

Underscores in numeric literals


most of the people or habituated to write numbers with comma separate as it  can be  easily readable. But when you come to programming language we do not have chance to give like that, it something hard to get the value ,it will take some time. Now this can be achieved by underscores in numeric literals  in In Java 7.
any number of underscore characters (_) can appear anywhere between digits in a numerical literal.

int billion = 1_000_000_000;
for more details and examples with underscored literals see this

Binary literals
 the integral types (byte, short, int, and long) can also be expressed using the binary number system. To specify a binary literal, add the prefix 0b or 0B to the number.

int binary = 0b10011001;

For more details 

Catching Multiple Exception Types
Most of the time we are doing the same thing to handle exceptions. for example we need to  handle 3 exceptions and handle  same for all 3 exceptions, for this we need to write 3 catch blocks and in all three catch blocks we need to write  same code. It leads code redundancy. Now in Java7 we can do this with only one catch block.

Consider the following example, which contains duplicate code in each of the catch blocks:
catch (IOException ex) {
     logger.log(ex);
     throw ex;
catch (SQLException ex) {
     logger.log(ex);
     throw ex;
}

The following example, which is valid in Java SE 7 and later, eliminates the duplicated code:
catch (IOException|SQLException ex) {
    logger.log(ex);
    throw ex;
}

The catch clause specifies the types of exceptions that the block can handle, and each exception type is separated with a vertical bar (|).
For more details 

Rethrowing Exceptions with More Inclusive Type Checking 

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.
Consider the following example:
  static class FirstException extends Exception { }
  static class SecondException extends Exception { }

  public void rethrowException(String exceptionName) throws Exception {
    try {
      if (exceptionName.equals("First")) {
        throw new FirstException();
      } else {
        throw new SecondException();
      }
    } catch (Exception e) {
      throw e;
    }
  }

This examples's try block could throw either FirstException or SecondException. Suppose you want to specify these exception types in the throws clause of the rethrowException 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 throwsclause of the rethrowException method declaration.
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:
  public void rethrowException(String exceptionName)
  throws FirstException, SecondException {
    try {
      // ...
    }
    catch (Exception e) {
      throw e;
    }
  }
This analysis is disabled if the catch parameter is assigned to another value in the catch block. However, if the catch parameter is assigned to another value, you must specify the exception type Exception in the throws clause of the method declaration.
For more Details 



 That's it for the code examples. It would be great if someone can point me on more things. I am

sure there are plenty of other cool stuff.

No comments:

Post a Comment

Distributed Transactions

What is a distributed transaction?  Transactions that span over multiple physical systems or computers over the network, are simply termed D...