Dec 31, 2015

Java 7 Features

Following are some of the cool features introduced on Java 7.

1. Strings in switch Statement

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");
}

equals() and hashcode() method from java.lang.String is used in 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.


2. Type Inference for Generic Instance Creation (Diamond Operator)

You can replace the type arguments required to invoke the constructor of a generic class with an empty set of type parameters (<>) as long as the compiler can infer the type arguments from the context. This pair of angle brackets is informally called the diamond.

For example, consider the following variable declaration:
Map<String, List<String>> myMap = new HashMap<String, List<String>>();

In Java SE 7, you can substitute the parameterized type of the constructor with an empty set of type parameters (<>):
Map<String, List<String>> myMap = new HashMap<>();

Note that to take advantage of automatic type inference during generic class instantiation, you must specify the diamond. In the following example, the compiler generates an unchecked conversion warning because the HashMap() constructor refers to the HashMap raw type, not the
Map<String, List<String>> type:
Map<String, List<String>> myMap = new HashMap(); // unchecked conversion warning


3. Multiple Exception Handling

In JDK 7, a single catch block can handle more than one exception types.
For example, before JDK 7, you need two catch blocks to catch two exception types although both perform identical task:

try {
   ......

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

In JDK 7, you could use one single catch block, with exception types separated by '|'.

try {
   ......

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

By the way, just remember that Alternatives in a multi-catch statement cannot be related by sub classing. For example a multi-catch statement like below will throw compile time error :

try {
   ......

} catch (FileNotFoundException | IOException ex) {
   ex.printStackTrace();
}

Alternatives in a multi-catch statement cannot be related by sub classing, it will throw error at compile time :
java.io.FileNotFoundException is a subclass of alternative java.io.IOException
        at Test.main(Test.java:18)



4. Binary Literals, underscore in literals

In JDK 7, you could insert underscore(s) '_' in between the digits in an numeric literals (integral and floating-point literals) to improve readability. This is especially valuable for people who uses large numbers in source files, may be useful in finance and computing domains. For example,

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;


5. Binary Literals with prefix "0b"

In JDK 7, you can express literal values in binary with prefix '0b' (or '0B') for integral types (byte, short, int 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;

6. The try-with-resources Statement

Prior to Java SE 7, you can use a finally block to ensure that a resource is closed regardless of whether the try statement completes normally or abruptly. The following example uses a finally block instead of a try-with-resources statement:
static String readFirstLineFromFileWithFinallyBlock(String path)
                                                     throws IOException {
    BufferedReader br = new BufferedReader(new FileReader(path));
    try {
        return br.readLine();
    } finally {
        if (br != null) br.close();
    }
}

The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.

The following example reads the first line from a file. It uses an instance of BufferedReader to read data from the file. BufferedReader is a resource that must be closed after the program is finished with it:
static String readFirstLineFromFile(String path) throws IOException {
    try (BufferedReader br =
                   new BufferedReader(new FileReader(path))) {
        return br.readLine();
    }
}

In this example, the resource declared in the try-with-resources statement is a BufferedReader. The declaration statement appears within parentheses immediately after the try keyword. The class BufferedReader, in Java SE 7 and later, implements the interface java.lang.AutoCloseable. Because the BufferedReader instance is declared in a try-with-resource statement, it will be closed regardless of whether the try statement completes normally or abruptly (as a result of the method BufferedReader.readLine throwing an IOException).


7. 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.
Following additional features have been introduced in NIO package.
  • 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.

Anyhow it would be recommended to check Java doc of new file package to learn more about this interesting useful feature.


Dec 28, 2015

Java: Finally block

The runtime system always executes the statements within the finally block regardless of what happens within the try block. So it's the perfect place to perform cleanup. The finally block is a key tool for preventing resource leaks. When closing a file or otherwise recovering resources, place the code in a finally block to ensure that resource is always recovered.

When finally will not execute?

    - If the JVM exits while the try or catch code is being executed, then the finally block may not execute. This may happen due to System.exit() call.

    - If the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues.

    - If a exception is thrown in finally block and not handled then remaining code in finally block may not be executed.

From the sample code below we can notice that finally block is not executed while JVM exits in catch block.


    public static void main(String[] args)
    {
        try
        {
            System.out.println("IN TRY BLOCK");
            throwsMethod();
        }
        catch (Exception e)
        {
            System.out.println("IN CATCH BLOCK");
            System.exit(0);
        }
        finally
        {
            System.out.println("IN FINALLY BLOCK");
        }
    }
    
    static void throwsMethod() throws Exception
    {
        throw new Exception("Exception thrown manually");
    }

Code output:

IN TRY BLOCK
IN CATCH BLOCK 

Here you can notice, code inside finally block is not executed.


Dec 27, 2015

java.lang.Error

An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions. The ThreadDeath error, though a "normal" condition, is also a subclass of Error because most applications should not try to catch it. 

A method is not required to declare in its throws clause any subclasses of Error that might be thrown during the execution of the method but not caught, since these errors are abnormal conditions that should never occur. That is, Error and its subclasses are regarded as unchecked exceptions for the purposes of compile-time checking of exceptions.

 

Error Summary

S.N.Error & Description
1 AbstractMethodError This is Thrown when an application tries to call an abstract method.
2AssertionError This is Thrown to indicate that an assertion has failed.
3 ClassCircularityError This is Thrown when a circularity has been detected while initializing a class.
4 ClassFormatError This is Thrown when the Java Virtual Machine attempts to read a class file and determines that the file is malformed or otherwise cannot be interpreted as a class file.
5 Error This is an Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch.
6 ExceptionInInitializerError These are the Signals that an unexpected exception has occurred in a static initializer.
7 IllegalAccessError This is Thrown if an application attempts to access or modify a field, or to call a method that it does not have access to
8 IncompatibleClassChangeError This is Thrown when an incompatible class change has occurred to some class definition.
9 InstantiationError This is Thrown when an application tries to use the Java new construct to instantiate an abstract class or an interface.
10 InternalError This is Thrown to indicate some unexpected internal error has occurred in the Java Virtual Machine.
11 LinkageError The Subclasses of LinkageError indicate that a class has some dependency on another class.
12 NoClassDefFoundError This is Thrown if the Java Virtual Machine or a ClassLoader instance tries to load in the definition of a class and no definition of the class could be found.
13 NoSuchFieldError This is Thrown if an application tries to access or modify a specified field of an object, and that object no longer has that field.
14 NoSuchMethodError This is Thrown if an application tries to call a specified method of a class (either static or instance), and that class no longer has a definition of that method.
15 OutOfMemoryError This is Thrown when the Java Virtual Machine cannot allocate an object because it is out of memory, and no more memory could be made available by the garbage collector.
16 StackOverflowError This is Thrown when a stack overflow occurs because an application recurses too deeply.
17 ThreadDeath This is an instance of ThreadDeath is thrown in the victim thread when the stop method with zero arguments in class Thread is called.
18 UnknownError This is Thrown when an unknown but serious exception has occurred in the Java Virtual Machine.
19 UnsatisfiedLinkError This is Thrown if the Java Virtual Machine cannot find an appropriate native-language definition of a method declared native.
20 UnsupportedClassVersionError This is Thrown when the Java Virtual Machine attempts to read a class file and determines that the major and minor version numbers in the file are not supported.
21 VerifyError This is Thrown when the "verifier" detects that a class file, though well formed, contains some sort of internal inconsistency or security problem.
22 VirtualMachineError This is Thrown to indicate that the Java Virtual Machine is broken or has run out of resources necessary for it to continue operating.