Thursday, 10 December 2015

Java 6 New Features

1. Collections Framework Enhancements:

Java SE 6 API provides bi-directional collection access. New collection interfaces includes Deque, NavigableSet, NavigableMap.


2. java.io Enhancements:

New class” Console” is added and it contains methods to access a character-based console device. The readPassword()methods disable echoing thus they are suitable for retrieval of sensitive data such as passwords. The method System.console ()returns the unique console associated with the Java Virtual Machine.
public class ShowPassword { public static void main(String[] args) { System.out.println("Enter your password please"); char password[]=System.console().readPassword(); System.out.println(password); }}

3. Enhancements in GUI
4.  JDBC 4.0 Enhancements :
 Java SE 6 includes several enhancements to the Java Database Connectivity (JDBC) API. These enhancements will be released as JDBC version 4.0. The main objectives of the new JDBC features are to provide a simpler design and better developer experience
The major features added in JDBC 4.0 include:
1.Auto-loading of JDBC driver class
2.Connection management enhancements
3.Support for RowId SQL type
4.DataSet implementation of SQL using Annotations
5.SQL exception handling enhancements

5. Support of Derby database
6. Scripting Language Support
7.  Integrated Web Services.
8.  Support of  JAXB 2.0 (JSR 222)
9. Pluggable Annotation Processing





JDK 1.7 New Features


1) Type inference


 Prior JDK 7
Map<String, List<String>> employeeRecords =  new HashMap<String, List<String>>();
List<Integer> primes = new ArrayList<Integer>();

In JDK 7
Map<String, List<String>> employeeRecords =  new HashMap<>();
List<Integer> primes = new ArrayList<>();


2) String in Switch

Before JDK 7, only integral types can be used as selector for switch-case statement. In JDK 7, you can use a String object as the selector. For example,

String state = "NEW";

switch (day) {
   case "NEW": System.out.println("Order is in NEW state"); break;
   case "CANCELED": System.out.println("Order is Cancelled"); break;
   case "REPLACE": System.out.println("Order is replaced successfully"); break;
   case "FILLED": System.out.println("Order is filled"); break;
   default: System.out.println("Invalid");

}


3) Automatic Resource Management
    
Before JDK 7, we need to use a finally block, to ensure that a resource is closed regardless of whether the try statement completes normally or abruptly, for example while reading files and streams, we need to close them into finally block, which result in lots of boiler plate and messy code, as shown below :
public static void main(String args[]) {
        FileInputStream fin = null;
        BufferedReader br = null;
        try {
            fin = new FileInputStream("info.xml");
            br = new BufferedReader(new InputStreamReader(fin));
            if (br.ready()) {
                String line1 = br.readLine();
                System.out.println(line1);
            }
        } catch (FileNotFoundException ex) {
            System.out.println("Info.xml is not found");
        } catch (IOException ex) {
            System.out.println("Can't read the file");
        } finally {
            try {
                if (fin != null) fin.close();
                if (br != null) br.close();
            } catch (IOException ie) {
                System.out.println("Failed to close files");
            }
        }
    }

Look at this code, how many lines of boiler codes?

Now in Java 7, you can use try-with-resource feature to automatically close resources, which implements AutoClosable and Closeable interface e.g. Streams, Files, Socket handles, database connections etc. JDK 7 introduces a try-with-resources statement, which ensures that each of the resources in try(resources) is closed at the end of the statement by calling close() method of AutoClosable. Now same example in Java 7 will look like below, a much concise and cleaner code :

public static void main(String args[]) {
       try (FileInputStream fin = new FileInputStream("info.xml");
  BufferedReader br = new BufferedReader(new InputStreamReader(fin));) {
  if (br.ready()) {
   String line1 = br.readLine();
   System.out.println(line1);
  }
 } catch (FileNotFoundException ex) {
  System.out.println("Info.xml is not found");
 } catch (IOException ex) {
  System.out.println("Can't read the file");
 }
}

4) Fork Join Framework


5)  Underscore in Numeric literals

int billion = 1_000_000_000
// 10^9 
long creditCardNumber = 1234_4567_8901_2345L;
//16 digit number long ssn = 777_99_8888L
double pi = 3.1415_9265
float pif = 3.14_15_92_65f;



6) Catching Multiple Exception Type in Single Catch Block

try { ...... 
catch(ClassNotFoundException ex) {
      ex.printStackTrace();
 } catch(SQLException ex) { 
          ex.printStackTrace(); 
}



try {

   ......

} catch (FileNotFoundException | IOException ex) {

   ex.printStackTrace();

}


7) Binary Literals with prefix "0b"

In JDK 7, you can express literal values in binary with prefix '0b' (or '0B') for integral types (byteshortint and long), similar to C/C++ language. Before JDK 7, you can only use octal values (with prefix '0') or hexadecimal values (with prefix '0x' or '0X').

int mask = 0b01010000101;

or even better

int binary = 0B0101_0000_1010_0010_1101_0000_1010_0010;



8) Java NIO 2.0


Java SE 7 introduced java.nio.file package and its related package, java.nio.file.attribute, provide comprehensive support for file I/O and for accessing the default file system. It also introduced the Path class which allow you to represent any path in operating system. New File system API complements older one and provides several useful method checking, deleting, copying, and moving files. for example, now you can check if a file is hidden in Java. You can also create symbolic and hard links from Java code.  JDK 7 new file API is also capable of searching for files using wild cards. You also get support to watch a directory for changes. I would recommend to check Java doc of new file package to learn more about this interesting useful feature.



9) 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.


10) More Precise Rethrowing of Exception



public void obscure() throws Exception{
try { 
new FileInputStream("abc.txt").read();
new SimpleDateFormat("ddMMyyyy").parse("12-03-2014");
} catch (Exception ex) {
System.out.println("Caught exception: " + ex.getMessage());
throw ex
  }

}

=====

public void precise() throws ParseException, IOException {
    try {
        new FileInputStream("abc.txt").read();
        new SimpleDateFormat("ddMMyyyy").parse("12-03-2014");        
    } catch (Exception ex) {
        System.out.println("Caught exception: " + ex.getMessage());
        throw ex;
    }
}
The Java SE 7 compiler allows you to specify the exception types ParseException and IOException in the throws clause in the preciese() method declaration because you can re-throw an exception that is a super-type of any of the types declared in the throws, we are throwing java.lang.Exception, which is super class of all checked Exception. Also in some places you will see final keyword with catch parameter, but that is not mandatory any more.



   

Java 8 New Features or What's new in JDK 1.8


1 . Lambda expressions

Lambda expressions are a new and important feature included in Java SE 8. They provide a clear and simple way to represent one method interface using an expression. Lambda expressions also enhance the Collection libraries making it easier to iterate, filter, and extract data from a Collection.


public static void main(String[] args) {
   
        System.out.println("=== RunnableTest ===");
 
       // Anonymous Runnable
 
      Runnable r1 = new Runnable(){
 
        @Override
 
        public void run(){
 
          System.out.println("Hello world one!");
 
        }
 
      };
 
     // Lambda Runnable
       Runnable r2 = () -> System.out.println("Hello world two!");
       // Run
       r1.run();
       r2.run();
}


2. Removal of Permanent Generation/Method Area


In Java The permanent generation (or permgen) is used for class definitions and associated metadata. Permanent generation is not part of the heap.

The JDK 8 HotSpot JVM is now using native memory for the representation of class metadata called Metaspace; if you have been using Oracle JRockit you will find some of these concepts borrowed from Oracle JVM implementation.

One of the immediate advantages of the Meta Space is that you will forget about the java.lang.OutOfMemoryError: PermGen space problems which is a frequent issue if you try to deploy several times an application on a Container and the Container is unable to free up the space used by previous deployments. Keep in mind however that this new feature won't eliminate out of the box class and classloader memory leaks. You will need however to monitor these problems using a different approach and using different tools.

When running JDK 1.8, allocations for the class metadata will be done out of native memory and the objects used to describe class metadata have been removed.


3. Default Method” or (Defender methods)

Java 8 introduces “Default Method” or (Defender methods) new feature, which allows developer to add new methods to the interfaces without breaking the existing implementation of these interface. It provides flexibility to allow interface define implementation which will use as default in the situation where a concrete class fails to provide an implementation for that method.


public interface A {
    default void foo(){
       System.out.println("Calling A.foo()");
    }
}

public class ClassAB implements A {
}
There is one common question that people ask about default methods when they hear about the new feature for the first time:
What if the class implements two interfaces and both those interfaces define a default method with the same signature?
Example to illustrate this situation:
public interface A {  
    default void foo(){  
        System.out.println("Calling A.foo()");  
    }  
}

public interface B {
    default void foo(){
        System.out.println("Calling B.foo()");
    }
}


public class ClassAB implements A, B {

}  
This code fails to compile with the following result:
java: class Clazz inherits unrelated defaults for foo() from types A and B
To fix that, in Clazz, we have to resolve it manually by overriding the conflicting method:
public class Clazz implements A, B {
    public void foo(){}
}
But what if we would like to call the default implementation of method foo() from interface A instead of implementing our own.
It is possible to refer to A#foo() as follows:
public class Clazz implements A, B {
    public void foo(){
       A.super.foo();
    }
}

4 .Enhancement in Security
    a) 64-bit PKCS11 for Windows
     b) Stronger algorithms for password-based encryption
     c) Client-side TLS 1.2 enabled by default


5. Enhancement in JavaFX
    JavaFX is used to design fancy GUI similar to swing


6. New Tools

   a)  The java command launches JavaFX applications.
   b)   The jdeps command-line tool is provided for analyzing class files.




  • Unicode Enhancements, including support for Unicode 6.2.0
  • Adoption of Unicode CLDR Data and the java.locale.providers System Property
  • New Calendar and Locale APIs
  • Ability to Install a Custom Resource Bundle as an Extension


8. Date-Time Package - a new set of packages that provide a comprehensive date-time model.
     Support of nano seconds in Date API



9.  JDBC(Type -1 Driver is removed )

  • The JDBC-ODBC Bridge has been removed.
  • JDBC 4.2 introduces new features.

10.  Enhancement inside Concurrency package(java.util.concurrent package)