Wednesday, 20 February 2013

Switch and try-with-resources - JDK7


1. Strings with switch statement:-
JDK7 allows you to use strings with switch statement. In this case swicth internally uses equals method. This structure is always better that if-else-if ladder. Here is one simple example,

String numbers = “one”;
Int x = 1000;
switch(numbers) {
                case “one”: x = 1;  break;
                case “two”: x = 2; break;
                case “three”: x = 3; break;
                case “four”: x = 4; break;
                :
                :
                default : System.out.print(“This is wrong option.”);
}

2. try-with-resources statement:-
In this try statement we can declare one or more resources which must be closed after it’s work is finished. Here is one small example,
try(BufferedReader br = new BufferedReader(file)) {
                br.readLine();
}
In this code br will be closed automatically in normal execution as well as exceptional condition onse it is out of try block. Before JDK7 we were using finally block. If exception is occuring then that exception will be suppressed and that object will be closed. You can obtain that suppressed exception using Throwable.getSuppressed method.
Again this feature introduces new interface called AutoClosable.
Catching multiple exceptions:-
This is very simple to understand. JDK7 allows single catch to handle multiple exceptions. This reduces code redundancy. Here is simple exmaple,
try {
                //Some code.
} catch(IOException | SQLException e) {
}

Tuesday, 19 February 2013

Binary literals and underscores in literals – JDK7


JDK7 is providing many new features. In this post I am going to explain something about binary literal and underscores in literals.

      1. Binary literals:-
JDK7 allows you assign binary numbers to basic data types like byte, short, int and long. These binary literals are useful in microprocessor programming and bitmap representation.  These binary literals makes your data representation more readable that hex or octal number system. Only the thing is that you have start binary literal with “0b” or “0B”.

Here arefew examples of binary literal,
byte binaryByte = (byte)0b001;
short binaryShort = (short)0b001;
int binaryInt = 0b001001;
long binaryLong = 0b0010001L;


      2. Underscores in literals:-
JDK7 allows you to use underscores in number literals. The main intention behind this is making big numbers more readable. 

This feature is running with some rules as given below,
a.       “_” can’t be used after the number.
b.      “_” can’t be used before or after “.” In floating number.
c.       “_” can’t be used before or after “L” or “F”.
d.      “_” can’t be used in between “0” and “b”

Here are few examples,
Int underInt = 0b001_001;
long underLong = 99_99_99L;
long underLong = 0b01_01_01L;