Pages

December 01, 2016

New features in Java 1.7

JDK 1.7 (Java SE 7 or Java 7), code named as Dolphin has following new features:

String in Switch Expression

Earlier to JDK 1.7, switch expression takes int values or values which are convertible to int. From JDK 1.7, switch also accepts string objects as an expression.

equals() and hashcode() method from java.lang.String are used for comparison, which is case-sensitive. Benefit of using String in switch is that, Java compiler can generate more efficient code than using nested if-then-else statement.

We need to be careful while passing string object, passing a null object cause to NullPointerException.

Underscores in Numeric Literals

From Java 7 we are permitted to use underscores in numeric literals. We can place underscores where we feel required to increase readability; like between hundreds and thousands, thousands and lakhs etc.
e.g:
int parkingcost = 99_87_723;
float flatcost = 7_47_982.25_55f;


Placing underscore at the beginning or ending of the literal value is not allowed, if you put underscore in beginning or end, compiler will throw an error 'Underscores have to be located within digits'.

Also, we cannot add underscore in string literal and then convert it into int, if you do this it will throw NumberFormatException.

String strCost ="99_87_723";
int intCost = Integer.parseInt(strCost);  


We cannot put underscore, just after decimal number.
double piValue = 3._1415_9265; // underscore just after decimal point

e.g:
int a = _10; // Error, this is an identifier, not a numeric literal 
int a = 10_; // Error, cannot put underscores at the end of a number 

float a = 10._0; // Error, cannot put underscores adjacent to a decimal point 
float a = 10_.0; // Error, cannot put underscores adjacent to a decimal point 

long a = 10_100_00_L; // Error, cannot put underscores prior to an L suffix 
float a = 10_100_00_F; // Error, cannot put underscores prior to an F suffix 

Binary Literals

With JDK 1.7, the integer whole numbers like byte, short, int and long can be expressed in binary format also with a prefix of 0b or 0B. Earlier, we have 0 prefix for octal and 0x prefix for hexa and no prefix for binary. JDK 1.7, introduced 0b to represent binary literals.

Handling Multiple Exceptions In One Catch Block

From Java 1.7, we can handle multiple exceptions in a single catch block. Before JDK 1.7, we need  to write multiple catches to handle different exceptions raised in the code. Now in a single catch statement, multiple exceptions can be included separated by pipe ( | ) symbol. e.g:

Before JDK 1.7:
try
{
/////do something
}
catch(ArithmeticException e)
{
    System.out.println(e);   
}
catch(ArrayIndexOutOfBoundsException e)
{
    System.out.println(e);   
}

With JDK 1.7:
try
{
/////do something
}
catch(ArithmeticException | ArrayIndexOutOfBoundsException e)
{
    System.out.println(e);   
}


Try With Resources

The resource is as an object that must be closed after finishing the program. Until Java 1.7 finally block is required to close the resources of files or sockets or JDBC handles (objects) etc. Java 1.7 has introduced 'try-with-resources' statement, which will automatically close the resources opened in try block when the execution control passes out try block (say, at the close brace of try block).

Before JDK 1.7:
public static void main(String args[])
{
    FileReader fr = null;
    FileWriter fw = null;
    try
    {
      fr = new FileReader("munich_travel_expense.txt");
      fw = new FileWriter("kempten_travel_expense.txt");
      // some file copying code
    }
    catch(IOException e)
    {
      e.printStackTrace();
    }
    finally
    {
      try
      {
        if(fr != null) fr.close();
        if(fw != null) fw.close();
      }
      catch(IOException e)
      {
        e.printStackTrace();
      }
    }

}

With JDK 1.7:
public static void main(String args[])
{
    try (
          FileReader fr = new FileReader("munich_travel_expense.txt");
          FileWriter fw = new FileWriter("kempten_travel_expense.txt");
        )
        {
          // some file copying code
        }// at this point fr and fw are closed
        catch (IOException e)
        {
          e.printStackTrace();
       
}
}

JDK 1.7 has introduced new interface 'java.lang.AutoCloseable' for this purpose.

public interface java.lang.AutoCloseable
{
  public abstract void close() throws java.lang.Exception;
}


Any resource (class) that implements this interface is eligible as a resource statement to write in try block. From JDK 1.7, many classes like BufferedReader, PrintStream, Scanner, Socket etc implements AutoCloseable interface.

The close() method of AutoCloseable is called implicitly to close the handles. FYI, the close() method throws Exception which you may or may not catch if your code does not demand, or replace with problem specific exception class. (NOTE: close() method java.lang.Closeable interface is very different from this).

Exceptions which are thrown by try-with-resources are suppressed exceptions. If a try block throws an exception and one or more exceptions are thrown by the try-with-resources, the exceptions thrown by try-with-resources will be suppressed. We can get these exceptions by using the getSuppress() method of Throwable class.

Static Blocks

Earlier to JDK 1.7, to print static blocks no main() method is required. But from JDK 1.7, if no main() exists, static blocks will not be executed.

Type Inference for Generic Instance Creation

From Java 7, Java provides improved compiler which is enough smart to infer the type of generic instance. Now, we can replace the type arguments with an empty set of type parameters ( < > ). This pair of angle brackets is informally called the diamond operator. Prior JDK 7, you type more to specify types on both left and right hand side of object creation expression, but now it only needed on left hand side. e.g:

Prior JDK 7:
Map< String, List< String > > loadingPoints  =  new HashMap< String, List< String > >();
List< Integer > loadingWeightList  = new ArrayList< Integer >();

With JDK 1.7:
Map< String, List< String > > loadingPoints =  new HashMap<  >();
List< Integer > loadingWeightList = new ArrayList<  >();


G1 Garbage Collector

JDK 7 introduced a new Garbage Collector known as G1 Garbage Collection, which is short form of garbage first. G1 garbage collector performs clean-up where there is most garbage. To achieve this it split Java heap memory into multiple regions as opposed to 3 regions in the prior to Java 7 version (new, old and permgen space). It's said that G1 is quite predictable and provides greater through put for memory intensive applications.

ALSO CHECKCore Java Interview Questions And Answers

-K Himaanshu Shuklaa..

No comments:

Post a Comment