You are on page 1of 12

Home About Gallery Subscribe to Feed

Search...

7 new cool features in Java 7


Posted in July 8, 2011 4:53 pmh.Augusto (16) Comments More Sharing Services

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 whats 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) Im 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 char, byte, short, int, Character, Byte, Short, Integer, 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. view plaincopy to clipboardprint? 1. public void testStringSwitch(String direction) { 2. switch (direction) { 3. case "up": 4. y--; 5. break; 6. 7. case "down": 8. y++; 9. break; 10. 11. case "left": 12. x--; 13. break; 14. 15. case "right": 16. x++; 17. break; 18. 19. default: 20. System.out.println("Invalid direction!"); 21. break; 22. } 23. } 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; view plaincopy to clipboardprint? 1. List<String> strings = new ArrayList<String>(); In Java 7, you just use the diamond operator without the type; view plaincopy to clipboardprint?

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; view plaincopy to clipboardprint? 1. 2. 3. 4. 5. // Pre-Java 7 // Map<String,Map<String,int>>m=new HashMap<String, Map<String,int>>(); // Java 7 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.io and java.lang.reflect? view plaincopy to clipboardprint? 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 |. view plaincopy to clipboardprint? 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 thats a dangerous idea because it makes code catch exceptions it cant 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; view plaincopy to clipboardprint? 1. try { 2. in = new BufferedReader(new FileReader("test.txt")); 3. 4. String line = null; 5. while ((line = in.readLine()) != null) { 6. System.out.println(line); 7. } 8. } catch (IOException ex) { 9. ex.printStackTrace(); 10. } finally { 11. try { 12. if (in != null) in.close(); 13. } catch (IOException ex) { 14. ex.printStackTrace(); 15. } 16. } 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 didnt, 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; view plaincopy to clipboardprint? 1. try (BufferedReader in=new BufferedReader(new FileReader("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 dont 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 1, 2) 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); view plaincopy to clipboardprint? 1. List<String> lines = Files.readAllLines( 2. FileSystems.getDefault().getPath("test.txt"), StandardCharsets.UTF_8); 3. 4. for (String line : lines) System.out.println(line); java.nio.file.Path is an interface that pretty much serves as a replacement for java.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 didnt 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 Im a UI guy, I want to mention JLayerPane. This component is similar to the one provided in the JXLayer project. Ive 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 thats 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! Share on facebookShare on twitterShare on emailShare on printMore Sharing Services Java, Software Development, Technologyjava 7, jdk 7 You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site. Login Follow the discussion

Comments (16)
Sort by: Date Rating Last Activity +1

Dario 41 weeks ago All pretty cool except #1 which promotes the bad practice of using string literals - use enum instead! Reply 0

Augusto 41 weeks ago I think you are probably correct, although I can see where for simple things where your input is already a string, this method is very convenient. Reply -4

Narada 41 weeks ago Dario - that is such a small minded and idiotic comment. The scope of strings in switch statement is much wider than simply using it for constants. An obvious example would be if I wanted to switch on a string coming in as a method argument. Should I make that into an enum just to be able to switch on it? Taking your argument forward perhaps you'd like to eliminate strings altogether and just use enums because simply the existence of strings promotes use of string literals? Reply 0

Augusto 41 weeks ago Narada, funny you say that, that's what I was thinking in the code example ... processing commands from a text/console based command. Reply +1

Estefania Soto 40 weeks ago

I remember asking about #1 to my professor and he said it would be included in Java 7. I love number two it was redundant in my opinion.An as a student of Java in college seemed unnecessary Reply 0

PhiLho 40 weeks ago "Sometimes developers use a catch (Exception ex) to achieve a similar result, but thats a dangerous idea because it makes code catch exceptions it cant handle and instead should bubble up (IllegalArgumentException, OutOfMemoryError, etc.)." Well, catching Exception won't catch OutOfMemoryError, since the latter is... an Error. That's why catching Exception is "acceptable" (even if not good practice in production code) while catching Throwable is not at all. Reply +1

SteveRob 1p 40 weeks ago Pretty cool features. For a beginner programmer like me, the standout features are string in switch, muticatch blocks and resource autoclose tryblock. Thanks for organizing and presenting the features like this.... :) Reply +1

Pierluigi Vernetto 39 weeks ago a step forward, but still so far away from the elegance and conciseness of groovy. incidentally I find Nevada language shocking, but there is no way to report the abuse Reply 0

Mohammed Ziya 39 weeks ago Great features!! Reply +1

Fernando Franzini 18p 37 weeks ago Amazing!!! Reply 0

camilo lopes 36 weeks ago good post and features!! :) Reply +1

Arun 36 weeks ago I agree with Dario regarding using Strings in Switch (item #1). Using Enums brings in more discipline, And makes it easy to maintain the code. Also, item #2 is very much a convenience rather than an improvement... Reply 0

The Master 31 weeks ago People insisting on enumerators are trading one problem for another. After your code is compiled and tested, there is no advantage with one over the other. Enums are a crutch for people dependent on the auto-complete feature of today's IDE editor. If I have a new string, no big deal, just change the switch statement. If I have a new enum, first I have to change the enum class, then I can change the switch statement. It's just silly and I've yet to see anyone prove you are better off with enums. Reply +2

Dave 30 weeks ago Enums are much more than simple string replacements. True, string constants can provide a single point of maintenance. But if you use an enum on a method call, you guarantee that the value submitted is one that you are prepared to handle. And enums provide navigability. For example, if I have a method: private void doSomething (String codeValue) ...

... how do you know what codes are meaningful to the method? The might be defined as constants in a class somewhere in the code base, but where will you look? On the other hand, if the method is: private void doSomething (CodeValue codeValue)... ...the method tells you where to look to find out what is valid. Just look at the CodeValue enum. Enums are not always the answer. Sometimes you're reading values from a config file, for example. But when they can be used, they're great. Reply +3

Mike Kolcun 28 weeks ago In your complex inference example. We're still not able to use primitive types in generics, so Map<String, Map<String, int>> m = new HashMap<>(); won't work, the compiler will throw an error saying that we must use an object. Reply 0

Githin 1 week ago one diamond operator is also available, heard so. Reply

Post a new comment


Enter text right here!

Comment as a Guest, or login:


Login to IntenseDebate Login to WordPress.com Login to Twitter facebook Login to OpenID

Name Email Website (optional)

Displayed next to your comments.

Not displayed publicly.

If you have a website, link to it here. Submit Comment Subscribe to


Blogroll
o

Aristides Villareal

o o o o o o o o o o o o o o o o o o

Generation Y Netflix Junkie Pangalactica Log in Entries RSS Comments RSS WordPress.org Art bugs Cartoon Code Bloopers Family Firefox Funny Games Google Java

Meta

Categories

o o o o o o o o o o o

javafx Life Open Source RC airplanes Ruby Sketch Software Development Technology Travel Uncategorized User Interface

Powered by WordPress dfBlog Theme (Version 1.1.4) design by danielfajardo web 72 processes generated in 1.688 seconds.

You might also like