Searching...
Tuesday, 24 June 2014

Java 7 Features with Examples

01:41
There are lot of new useful java 7 features which are introduced in Jdk7 which looks very promising as it tries to make software developer’s job more easy and save his/her time as well. Now lets see which are those features or changes which are in this new release
 
1.Diamond Operator

2.Using Strings in Switch Statements

3.Automatic resource management

4.Numeric literals with underscores

5.Improved exception handling

6.File change Notifications

7.Fork and Join

8.Supporting dynamism

9.JLayerPane

10.Binary Literals
 
 
1. Diamond Operator

Diamond operator is one of the cool feature of Java 7 feature set. When we use generics and declare a map, then we need to specify the types on both the sides as shown below which was redundant, but in Java 7 we don't need to declare the types at right hand side.
 
Before Java 7 :
List<String> al=new ArrayList<String>();
 
In 7, it's written like this:

List<String> al=new ArrayList<>();
 
You don't have to type the whole list of types for the instantiation. Instead you use the <> symbol, which is called diamond operator.
 
package com.vinod.test;

import java.util.ArrayList;
import java.util.List;

public class JavaSevenGenerics {
    public static void main(String[] args) {
        List<String> al = new ArrayList<>();
        al.add("one");
        al.add("two");
        System.out.println(al);
    }
}

2. Using strings in switch statements

Switch statements work either with primitive types or enumerated types. Java 7 introduced another type that we can use in Switch statements: the String type. This is very good feature as lot of times we have Strings as key to match and we often work out if-else and equals for the check. But now we can directly use Strings in switch statement, so that we can use Switch functionality to fullest.
 
package com.vinod.test;

public class JavaSevenSwitch {
    public static void main(String[] args) {
        String s = "java";
        // switch allows string from java7
        switch (s) {
        case "java":
            System.out.println("This is java");
            break;
        case ".net":
            System.out.println("This is ,net");
            break;
        }
    }
}


3. Automatic resource management

Resources such as Connections, Files, Input/OutputStreams, etc. should be closed manually by the developer by writing bog-standard code. Usually we use a try-finally block to close the respective resources.However, Java 7 has introduced another cool feature to manage the resources automatically. It is simple in operation, too. All we have to do is declare the resources in the try as follows
 
Before Java 7
 
package com.vinod.test;

import java.io.*;

public class FileTest {
    public static void main(String[] args) {
        FileOutputStream fos = null;
        DataOutputStream dos = null;
        try {
            fos = new FileOutputStream("file.txt");
            dos = new DataOutputStream(fos);
            dos.writeUTF("test");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fos.close();
                dos.close();
            } catch (IOException e) {
            }
        }
    }
}
 
 
In Java 7
 
package com.vinod.test;

import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class Java7FileTest {
    public static void main(String[] args) {
        try (FileOutputStream fos = new FileOutputStream("file.txt");
                DataOutputStream dos = new DataOutputStream(fos)) {
            dos.writeUTF("test");
        } catch (IOException e) {
        }
    }
}


4. Numeric literals with underscores

This is another excellent usability java 7 feature, this feature allows user to add any number of underscores which can appear anywhere between the digits in numeric literal. As shown below we are separating group of digits in numeric literals which is improving the readability of the number.

But there are some rules for adding underscores between digits
.
1.Underscore must be in between digits not at the beginning or at the end.

2.If the numeric literal in floating point type then underscore must not be adjacent to a decimal point.

3. Underscore must not prior to F and L suffix and in the occurrence of string of digit where it is expected
 
package com.vinod.test;

public class JavaSevenExample {
    public static void main(String[] args) {
        int i;
        // Java 7 allows underscore in integer
        i = 3455_11_11;
        System.out.println(i);
    }
}
 

5. Improved exception handling

Sometimes we need to handle lot of exceptions so for this we need to have multi catch statements for every exception we handle, but in java 7 its not the case anymore, You can add multiple exceptions using the pipe. Let's say you have a method that throws three exceptions. In the current state, you would deal them individually as shown in below:
 
package com.vinod.test;

import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;

public class Java7File1Test {
    public static void main(String[] args) {
        try (FileOutputStream fos = new FileOutputStream("file.txt");
                DataOutputStream dos = new DataOutputStream(fos)) {
            dos.writeUTF("test");
            SimpleDateFormat ff = new SimpleDateFormat("MM-dd-yyyy");
            ff.parse("2012-12-12");
        } catch (IOException | ParseException e) {
        }
    }
}


6. File change Notifications

The long awaited and very much useful feature of notifications when file change has also introduced in Java 7. When any file or directory changes the changes or the events are notified using the API WatchService.
 
package com.vinod.test;

import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;

public class DirectoryWatcher {

    public static void main(String[] args) {
        // Obtain a path reference to your watchable directory:
        Path tmpPath = Paths.get("D:/Pretech Files");
        WatchService watchService;
        try {
            watchService = FileSystems.getDefault().newWatchService();
            // Register the directory with the WatchService for all types of
            // events
            tmpPath.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_CREATE);
            // Initiate the infinite loop and start taking the events:
            for (;;) {
                WatchKey key = watchService.take();
                // Run through the events on the key:
                for (WatchEvent<?> event : key.pollEvents()) {
                    WatchEvent.Kind kind = event.kind();
                    switch (kind.name()) {
                    case "ENTRY_CREATE":
                        System.out.println("Directory created: " + event.context());
                        break;
                    case "ENTRY_MODIFY":
                        System.out.println("Directory Modified: " + event.context());
                        break;

                    }
                }
                boolean valid = key.reset();
                if (!valid) {
                    break;
                }
            }
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}
 

7. Fork and Join

Now a days parallel computing has become necessary for heavy or complex operations. Java 7 has introduced a Fork and Join framework which distributes the work across multiple cores and join them after completion which is the final result. These tasks or work is divided into small tasks until these task dont need any divide and all these tasks carried out separately. These task use a pool and task are divided according to that. The core classes which will be useful for fork and join are the ForkJoinPool and ForkJoinTask.
 
 
package com.vinod.test;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveAction;

/**
 *
 * This class helps to understand the feature of ForkJoinPool and ForkJoinTasks
 *
 * 1) ForkJoinTask is an abstract class ,RecursiveAction and RecursiveTasks are
 * the subclasses of ForkJoinTask class
 *
 * 2) In case of return type required we need to use RecursiveTask
 *
 * 3) In this example we used RecursiveAction and override its call() method to
 * implement fork and join
 *
 * 4) This is an example to print 1 to the given number
 *
 * 5) The given number is less then 100 it will not split the task (fork)
 *
 * 6) If the given number is 100 or greater than 100 it will split it in to two
 * task (1 to 50 and 51 to 100) 7) Finally join each task
 *
 * @authorvinod
 */


public class ForkAndJoinExample {
    public static void main(String[] args) {
        ForkJoinPool fjpool = new ForkJoinPool(2);
        RecursiveAction task = new PrintJob(100);
        fjpool.invoke(task);
    }
}

class PrintJob extends RecursiveAction {
    private static final long serialVersionUID = 1L;
    private int lines = 0;

    public PrintJob(int lines) {
        this.lines = lines;
    }

    @Override
    protected void compute() {
        if (lines < 100) {
            print(1, lines, "single task");
        } else {
            PrintJob p1 = new PrintJob(lines);
            p1.print(1, lines / 2, "task 1");
            PrintJob p2 = new PrintJob(lines);
            p2.print(lines / 2, lines, "task 2");
            p1.fork();
            p2.fork();
            p1.join();
            p2.join();
        }
    }

    private void print(int start, int end, String taskname) {
        for (int i = start; i <= end; i++) {
            System.out.println("print job triggerd from " + taskname + " " + i);
        }
    }
}


8. Supporting dynamism

In this feature extension to the JVM to support the dynamically typed language to increase the performance. For this invoke dynamic is being introduced which used to incorporate non java requirements. In short this feature is to make running of dynamically typed languages efficient.

9. JLayerPane

Java has introduced another great feature for swing UI developer which is a JLayeredPane. With use of JLayeredPane we can draw on the top of the component and handle the events without actually modifying the underlying component. This is a great feature because it can be used in many effects such as transition effects, blur effects or spotlight effects etc.


10. Binary Literals

binary literals are also introduced in this release too, so developers don't have to convert them to hexadecimals any more.
 
package com.vinod.test;

public class BinaryLiterals {
    public static void main(String[] args) {
        System.out.println("Before java 7" + Integer.parseInt("101010", 2));
        int binary = 0b101010;
        System.out.println("In java 7" + binary);
    }
}
  


Download Example
https://github.com/kkvinodkumaran/java7.git


References

1. http://code.joejag.com/2009/new-language-features-in-java-7/
2. http://www.eclipse.org/jdt/ui/r3_8/Java7news/whats-new-java-7.html
3. http://inebium.com/post/java-7-new-release-performance-code

0 comments: