Monday, 17 September 2012

7 new cool features in Java 7

The evolution of the Java language and VM continues! Mark Reinhold (Chief Architect of the Java Platform Group) announced yesterday that the first release candidate for Java 7 is available for download, he confirms that the final released date is planned for July 28.
For a good overview of the new features and what’s coming next in Java 8, I recommend this video on the Oracle Media Network, which features Adam Messinger, Mark Reinhold, John Rose and Joe Darcy. I think Mark sums up Java 7 very well when describing it as an evolutionary release, with good number “smaller” changes that make for a great update to the language and platform.
I had a chance to play a bit with the release candidate (made easier by the Netbeans 7 JDK 7 support!), and decided to list 7 features (full list is here) I’m particularly excited about. Here they are;

1. Strings in switch Statements (doc)
Did you know previous to Java 7 you could only do a switch on charbyte,shortintCharacterByteShortInteger, or an enum type (spec)? Java 7 adds Strings making the switch instruction much friendlier to String inputs. The alternative before was to do with with if/else if/else statements paired with a bunch of String.equals() calls. The result is much cleaner and compact code.
  1. public void testStringSwitch(String direction) {
  2. switch (direction) {
  3. case "up":
  4. y--;
  5. break;
  6. case "down":
  7. y++;
  8. break;
  9. case "left":
  10. x--;
  11. break;
  12. case "right":
  13. x++;
  14. break;
  15. default:
  16. System.out.println("Invalid direction!");
  17. break;
  18. }
  19. }

2. Type Inference for Generic Instance Creation (doc)
Previously when using generics you had to specify the type twice, in the declaration and the constructor;
  1. List<String> strings = new ArrayList<String>();
In Java 7, you just use the diamond operator without the type;
  1. List<String> strings = new ArrayList<>();
If the compiler can infer the type arguments from the context, it does all the work for you. Note that you have always been able do a “new ArrayList()” without the type, but this results in an unchecked conversion warning.
Type inference becomes even more useful for more complex cases;
  1. // Pre-Java 7
  2. // Map<String,Map<String,int>>m=new HashMap<String, Map<String,int>>();
  3. // Java 7
  4. Map<String, Map<String, int>> m = new HashMap<>();

3. Multiple Exception Handling Syntax (doc)
Tired of repetitive error handling code in “exception happy” APIs like java.ioand java.lang.reflect?
  1. try {
  2. Class a = Class.forName("wrongClassName");
  3. Object instance = a.newInstance();
  4. catch (ClassNotFoundException ex) {
  5. System.out.println("Failed to create instance");
  6. catch (IllegalAccessException ex) {
  7. System.out.println("Failed to create instance");
  8. catch (InstantiationException ex) {
  9. System.out.println("Failed to create instance");
  10. }
When the exception handling is basically the same, the improved catch operator now supports multiple exceptions in a single statement separated by “|”.
  1. try {
  2. Class a = Class.forName("wrongClassName");
  3. Object instance = a.newInstance();
  4. catch (ClassNotFoundException | IllegalAccessException |
  5. InstantiationException ex) {
  6. System.out.println("Failed to create instance");
  7. }
Sometimes developers use a “catch (Exception ex) to achieve a similar result, but that’s a dangerous idea because it makes code catch exceptions it can’t handle and instead should bubble up (IllegalArgumentException, OutOfMemoryError, etc.).

4. The try-with-resources Statement (doc)
The new try statement allows opening up a “resource” in a try block and automatically closing the resource when the block is done.
For example, in this piece of code we open a file and print line by line to stdout, but pay close attention to the finally block;
  1. try {
  2. in = new BufferedReader(new FileReader("test.txt"));
  3. String line = null;
  4. while ((line = in.readLine()) != null) {
  5. System.out.println(line);
  6. }
  7. catch (IOException ex) {
  8. ex.printStackTrace();
  9. finally {
  10. try {
  11. if (in != null) in.close();
  12. catch (IOException ex) {
  13. ex.printStackTrace();
  14. }
  15. }
When using a resource that has to be closed, a finally block is needed to make sure the clean up code is executed even if there are exceptions thrown back (in this example we catch IOException but if we didn’t, finally would still be executed). The new try-with-resources statement allows us to automatically close these resources in a more compact set of code;
  1. try (BufferedReader in=new BufferedReader(newFileReader("test.txt")))
  2. {
  3. String line = null;
  4. while ((line = in.readLine()) != null) {
  5. System.out.println(line);
  6. }
  7. catch (IOException ex) {
  8. ex.printStackTrace();
  9. }
So “in” will be closed automatically at the end of the try block because it implements an interface called java.lang.AutoCloseable. An additional benefit is we don’t have to call the awkward IOException on close(), and what this statement does is “suppress” the exception for us (although there is a mechanism to get that exception if needed, Throwable.getSuppressed()).

5. Improved File IO API (docs 12)
There are quite a bit of changes in the java.nio package. Many are geared towards performance improvements, but long awaited enhancements over java.io (specially java.io.File) have finally materialized in a new package called java.nio.file.
For example, to read a small file and print all the lines (see example above);
  1. List<String> lines = Files.readAllLines(
  2. FileSystems.getDefault().getPath("test.txt"), StandardCharsets.UTF_8);
  3. for (String line : lines) System.out.println(line);
java.nio.file.Path is an interface that pretty much serves as a replacement forjava.io.File, we need a java.nio.file.FileSystem to get paths, which you can get by using the java.nio.file.FileSystems factory (getDefault() gives you the default file system).
java.nio.file.Files then provides static methods for file related operations. In this example we can read a whole file much more easily by using readAllLines(). This class also has methods to create symbolic links, which was impossible to do pre-Java 7. Another feature long overdue is the ability to set file permissions for POSIX compliant file systems via the Files.setPosixFilePermissions method. These are all long over due file related operations, impossible without JNI methods or System.exec() hacks.
I didn’t have time to play with it but this package also contains a very interesting capability via the WatchService API which allows notification of file changes. You can for example, register directories you want to watch and get notified when a file is added, removed or updated. Before, this required manually polling the directories, which is not fun code to write.
For more on monitoring changes read this tutorial from Oracle.

6. Support for Non-Java Languages: invokedynamic (doc)
The first new instruction since Java 1.0 was released and introduced in this version is called invokedynamic. Most developers will never interact or be aware of this new bytecode. The exciting part of this feature is that it improves support for compiling programs that use dynamic typing. Java is statically typed (which means you know the type of a variable at compile time) and dynamically typed languages (like Ruby, bash scripts, etc.) need this instruction to support these type of variables.
The JVM already supports many types of non-Java languages, but this instruction makes the JVM more language independent, which is good news for people who would like to implement components in different languages and/or want to inter-operate between those languages and standard Java programs.

7. JLayerPane (doc)
Finally, since I’m a UI guy, I want to mention JLayerPane. This component is similar to the one provided in the JXLayer project. I’ve used JXLayer many times in the past in order to add effects on top of Swing components. Similarly, JLayerPane allows you to decorate a Swing component by drawing on top of it and respond to events without modifying the original component.
This example from the JLayerPane tutorial shows a component using this functionality, providing a “spotlight” effect on a panel.

You could also blur the entire window, draw animations on top of components, or create transition effects.
And that’s just a subset of the features, Java 7 is a long overdue update to the platform and language which offers a nice set of new functionality. The hope is the time from Java 7 to 8 is a lot shorter than from 6 to 7!

JDK 6; public Vs private JRE


JDK 6; public Vs private JRE


While installing JDK6, I found that there is a JRE named “public JRE”. I don’t know what is the difference between a public JRE and a private JRE. I googled and here are the search results :
From here,
In windows, a private JRE is installed in the JDK folder (for use by the tools – javac, etc) when you install the JDK. For current JDK versions, you are given the option to install a public JRE that is used to run java programs (in earlier versions this was not optional, it installed automatically). The public JRE installation uses Registry entries; the private one doesn’t.
From here,
In the private JRE (“C:\Programme\Java\jdk1.5.0\jre\” on my system)
the class files were compiled *with* debugging info (SourceFile,
LineNumberTable, …). This JRE is meant to be used for developing,
because you can step through the JRE code with debuggers, and get
exception stack traces with line numbers.
In the public JRE (“C:\Programme\Java\jre1.5.0\” on my system)
the class files were compiled *without* debugging info. This JRE is
meant to be installed on customers’ systems.


Private vs. public JRE – Installing the JDK installs a private Java SE Runtime Environment (JRE) and optionally a public copy. The private JRE is required to run the tools included with the JDK. It has no registry settings and is contained entirely in a jre directory (typically at C:\Program Files\jdk1.6.0\jre) whose location is known only to the JDK. On the other hand, the public JRE can be used by other Java applications, is contained outside the JDK (typically at C:\Program Files\Java\jre1.6.0), is registered with the Windows registry (at HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft), can be removed using Add/Remove Programs, might or might not be registered with browsers, and might or might not have java.exe copied to the Windows system directory (making it the default system Java platform or not). 

About JAVA

What is Java...
Java is a computer programming language. It enables programmers to write computer instructions using English based commands, instead of having to write in numeric codes. It’s known as a “high-level” language because it can be read and written easily by humans. Like English, Java has a set of rules that determine how the instructions are written. These rules are known as its “syntax”. Once a program has been written, the high-level instructions are translated into numeric codes that computers can understand and execute.

Who created Java
In the early nineties, Java was created by a team led by James Gosling for Sun Microsystems. It was originally designed for use on digital mobile devices, such as cell phones. However, when Java 1.0 was released to the public in 1996, its main focus had shifted to use on the Internet. It provided more interactivity with users by giving developers a way to produce animated webpages . Over the years it has evolved as a successful language for use both on and off the Internet. A decade later, it’s still an extremely popular language with over 6.5million developers worldwide.

Why choose Java
Java was designed with a few key principles in mind:
1.Easy to Use: The fundamentals of Java came from a programming language called c++. Although a powerful language, it was felt to be too complex in its syntax, and inadequate for all of Java's requirements. Java built on, and improved the ideas of c++, to provide a programming language that was powerful and simple to use. 
2.Reliability: Java needed to reduce the likelihood of fatal errors from programmer mistakes. With this in mind, object-oriented programming was introduced. Once data and its manipulation were packaged together in one place, it increased Java’s robustness.  
3.Secure: As Java was originally targeting mobile devices that would be exchanging data over networks, it was built to include a high level of security. Java is probably the most secure programming language to date.
4.Platform Independent: Programs needed to work regardless of the machine they were being executed on. Java was written to be a portable language that doesn't care about the operating system or the hardware of the computer. 

Where Do I Start?

To start programming in Java, all you need to do is download and install the Java development Kit.

Great Things about Java

Java is an operating system independent platform for software development. It consists of a programming language, utility programs and a run time environment. A Java program can be developed on one computer and run on any other computer with the correct run time environment. In general, older Java programs can run on newer run time environments. Java is rich enough that even very complicated applications can be written without operating system dependencies. This is called 100% java.
                    With the development of the Internet, Java has gained in popularity because when you program for the Web, you have no way of knowing which system the user may be on. With the Java programming language, you can take advantage of the "write once, run anywhere" paradigm. This means that when you compile your Java program, you don't generate instructions for one specific platform. Instead, you generate Java byte code, that is, instructions for the Java Virtual Machine (Java VM). For the users, it doesn’t matter what platform they use--Windows, Linux/Unix, MacOS, or an Internet browser—as long as it has the Java VM, it understands those byte codes.

Three Types of Java Programs

- An "applet" is a Java program designed to be embedded on a web page.
- A "servlet" is a Java program designed to be run on a server.
In these two cases the Java program cannot be run without the services of either a Web browser for an applet or a Web server for a servlet. 
- A "Java application" is a Java program that can be run by itself.
The following instructions are for you to program a Java application on a computer that runs Linux. 

A Checklist 
Very simple, you need only two items to write a Java program:
(1) The Java 2 Platform, Standard Edition (J2SE), formerly known as the Java Development Kit (JDK). 
Download the Linux version. Make sure you download the SDK, not the JRE (the JRE is included in the SDK/J2SE).
(2) A text editor
Almost any editor you find on Linux will do (e.g., Vi, Emacs, Pico). We’ll use Pico as an example.

Creating Your First Java Application

Your first application, FatCalories, will wait for you to enter two numbers and then compute and print out the result. To create this program, you will: (1) create a Java source file, (2) compile the source file into a byte code file, and (3) run the program contained in the byte code file. See specific instructions below: 
Step 1. Create a Java Source File.
A source file contains text written in the Java programming language. You can use any text editor to create and edit source files.
You have two options:
* You can save the FatCalories.java file onto your computer. This way can save you some typing. Then, you can go straight to step 2.
* Or, you can follow the longer instructions:
(1) Bring up a shell (sometimes called terminal) window. 
When the prompt first comes up, your current directory will usually be your home directory. You can change your current directory to your home directory at any time by typing cd at the prompt (typically a “%”) and then pressing Return.
The Java files you create should be kept in a separate directory. You can create a directory by using the command mkdir. For example, to create the directory java in your home directory, you would first change your current directory to your home directory by entering the following command:
% cd 
Then, you would enter the following command:
% mkdir java 
To change your current directory to this new directory, you would then enter:% cd java 
Now you can start creating your source file.
(2) Start the Pico editor by typing pico at the prompt and pressing Return. If the system responds with the message pico: command not found, then Pico is most likely unavailable. Consult your system administrator for more information, or use another editor.
When you start Pico, it'll display a new, blank buffer. This is the area in which you will type your code.
(3) Type the code for FatCalories.java listed here into the blank buffer. Type everything exactly as shown. The Java compiler and interpreter are case-sensitive.
(4) Save the code by typing Ctrl-O. When you see File Name to write: , typeFatCalories.java, preceded by the directory in which you want the file to go. If you wish to save FatCalories.java in the directory /home/smith/java, then you would type 
/home/smith/java/FatCalories.java and press Return.
Use Ctrl-X to exit Pico.
Step 2. Compile the Source File.
The Java compiler, javac, takes your source file and translates its text into instructions that the Java Virtual Machine (Java VM) can understand. The compiler puts these instructions into a byte code file.
Now, bring up another shell window. To compile your source file, change your current directory to the directory where your file is located. For example, if your source directory is /home/smith/java, you would type the following command at the prompt and press Return:
% cd /home/smith/java 
If you enter pwd at the prompt, you should see the current directory, which in this example has been changed to /home/smith/java.
If you enter ls at the prompt, you should see your file: FatCalories.java.
Now you can compile. At the prompt, type the following command and press Return: javac FatCalories.java 

If you see this error message: 
javac: Command not found
then Linux cannot find the Java compiler, javac.
Here's one way to tell Linux where to find javac. Suppose you installed the Java 2 Platform (J2SE) in /usr/java/jdk1.4. At the prompt, type the following command and press Return: 
/usr/java/jdk1.4/javac FatCalories.java 
The compiler now has generated a Java byte code file: FatCalories.class. 
At the prompt, type ls to verify the new file is there.

Step 3. Run the Program

The Java VM is implemented by a Java interpreter called java. This interpreter takes your byte code file and carries out the instructions by translating them into instructions that your computer can understand.
In the same directory, enter at the prompt:
java FatCalories 
When you run the program you need to enter two numbers when the black command line window appears. The program should then write out those two numbers plus the percentage computed by the program. 

When you receive the error message: 
Exception in thread "main" java.lang.NoClassDefFoundError: FatCalories
It means: java cannot find your byte code file, FatCalories.class.
What to do: One of the places java tries to find your byte code file is your current directory. For example, if your byte code file is in /home/smith/java, you should change your current directory to that by typing the following command at the prompt and hit Return:
cd /home/smith/java
If you enter pwd at the prompt, you should see /home/smith/java. If you enter ls at the prompt, you should see your FatCalories.java and FatCalories.class files. Now enter java FatCalories again.
If you still have problems, you might have to change your CLASSPATH variable. To see if this is necessary, try "unsetting" the classpath with the following command: 
unset CLASSPATH 
Now enter java FatCalories again. If the program works now, you'll have to change your CLASSPATH variable. 

Collections Framework Enhancements


This page summarizes enhancements to the collections framework in Java SE 6.

This release saw fewer API changes than 5.0, but there was more of a focus on the accuracy and clarity of the specification. We recommend using the Java SE 6 specification even when writing programs for older releases.
The primary theme of the API changes was better bi-directional collection access.
These new collection interfaces are provided:
  • Deque - a double ended queue, supporting element insertion and removal at both ends. Extends the Queue interface.
  • BlockingDeque - a Deque with operations that wait for the deque to become non-empty when retrieving an element, and wait for space to become available in the deque when storing an element. Extends both the Deque andBlockingQueue interfaces. (This interface is part of java.util.concurrent.)
  • NavigableSet - a SortedSet extended with navigation methods reporting closest matches for given search targets. A NavigableSet may be accessed and traversed in either ascending or descending order. This interface is intended to supersede the SortedSet interface.
  • NavigableMap - a SortedMap extended with navigation methods returning the closest matches for given search targets. A NavigableMap may be accessed and traversed in either ascending or descending key order. This interface is intended to supersede the SortedMap interface.
  • ConcurrentNavigableMap - a ConcurrentMap that is also a NavigableMap. (This interface is part of java.util.concurrent.)
The following concrete implementation classes have been added:
These existing classes have been retrofitted to implement new interfaces:
  • LinkedList - retrofitted to implement the Deque interface.
  • TreeSet - retrofitted to implement the NavigableSet interface.
  • TreeMap - retrofitted to implement the NavigableMap interface.
Two new methods were added to the Collections utility class:
  • newSetFromMap(Map) - creates a general purpose Set implementation from a general purpose Map implementation.
    There is no IdentityHashSet class, but instead, just use
    Set<Object> identityHashSet=
        Collections.newSetFromMap(
            new IdentityHashMap<Object, Boolean>());
    
  • asLifoQueue(Deque) - returns a view of a Deque as a Last-in-first-out (Lifo) Queue.
The Arrays utility class now has methods copyOf and copyOfRange that can efficiently resize, truncate, or copy subarrays for arrays of all types.
Before:
int[] newArray = new int[newLength];
System.arraycopy(oldArray, 0, newArray, 0, oldArray.length);
After:
int[] newArray = Arrays.copyOf(a, newLength);
Related Posts Plugin for WordPress, Blogger...