Ilias Tsagklis

About Ilias Tsagklis

Ilias Tsagklis is a senior software engineer working in the telecom domain. He is an applications developer in a wide variety of applications/services. Ilias is co-founder and Executive Editor at Java Code Geeks.

Java 7: Project Coin in code examples

This blog introduces – by code examples – some new Java 7 features summarized under the term Project Coin. The goal of Project Coin is to add a set of small language changes to JDK 7. These changes do simplify the Java language syntax. Less typing, cleaner code, happy developer ;-) Let’s look into that.

Prerequisites

Install Java 7 SDK on your machine
Install Eclipse Indigo 3.7.1

You need to look out for the correct bundles for your operating system.

In your Eclipse workspace you need to define the installed Java 7 JDK in your runtime. In the Workbench go to Window > Preferences > Java > Installed JREs and add your Java 7 home directory.

Next you need to set the compiler level to 1.7 in Java > Compiler.

Project Coin

Improved literals

A literal is the source code representation of a fixed value.

“In Java SE 7 and later, any number of underscore characters (_) can appear anywhere between digits in a numerical literal. This feature enables you to separate groups of digits in numeric literals, which can improve the readability of your code.” (from the Java Tutorials)

public class LiteralsExample {  
  
 public static void main(String[] args) {  
  System.out.println("With underscores: ");  
    
  long creditCardNumber = 1234_5678_9012_3456L;  
  long bytes = 0b11010010_01101001_10010100_10010010;  
    
  System.out.println(creditCardNumber);  
  System.out.println(bytes);  
    
  System.out.println("Without underscores: ");  
    
  creditCardNumber = 1234567890123456L;  
  bytes = 0b11010010011010011001010010010010;  
    
  System.out.println(creditCardNumber);  
  System.out.println(bytes);  
    
 }  
}  

Notice the underscores in the literals (e.g. 1234_5678_9012_3456L). Results written to the console:

With underscores:   
1234567890123456  
-764832622  
Without underscores:   
1234567890123456  
-764832622  

As you can see, the underscores do not make a difference to the values. They are just used to make the code more readible.

SafeVarargs

Pre-JDK 7, you always got an unchecked warning when calling certain varargs library methods. Without the new @SafeVarargs annotation this example would create unchecked warnings.

public class SafeVarargsExample {  
  
 @SafeVarargs  
 static void m(List<string>... stringLists) {  
  Object[] array = stringLists;  
  List<integer> tmpList = Arrays.asList(42);  
  array[0] = tmpList; // compiles without warnings  
  String s = stringLists[0].get(0); // ClassCastException at runtime  
 }  
  
 public static void main(String[] args) {  
  m(new ArrayList<string>());  
 }  
   
}</string></integer></string>  

The new annotation in line 3 does not help to get around the annoying ClassCastException at runtime. Also, it can only be applied to static and final methods. Therefore, I believe it will not be a great help. Future versions of Java will have compile time errors for unsafe code like the one in the example above.

Diamond

In Java 6 it required some patience to create, say, list of maps. Look at this example:

public class DiamondJava6Example {
   public static void main(String[] args) {
      List<Map<Date, String>> listOfMaps = new ArrayList<Map<Date, String>>(); // type information twice!
      HashMap<Date, String> aMap = new HashMap<Date, String>(); // type information twice
      aMap.put(new Date(), "Hello");
      listOfMaps.add(aMap);
      System.out.println(listOfMaps);
   }
}

As you can see in the right part of the assignment in lines 3 and 4 you need to repeat your type information for the listOfMaps variable as well as of the aMap variable. This isn’t necessary anymore in Java 7:

public class DiamondJava7Example {
   public static void main(String[] args) {
      List<Map<Date, String>> listOfMaps = new ArrayList<>(); // type information once!
      HashMap<Date, String> aMap = new HashMap<>(); // type information once!
      aMap.put(new Date(), "Hello");
      listOfMaps.add(aMap);
      System.out.println(listOfMaps);
   }
}

Multicatch

In Java 7 you do not need a catch clause for every single exception, you can catch multiple exceptions in one clause. You remember code like this:

public class HandleExceptionsJava6Example {  
 public static void main(String[] args) {  
  Class string;  
  try {  
   string = Class.forName("java.lang.String");  
   string.getMethod("length").invoke("test");  
  } catch (ClassNotFoundException e) {  
   // do something  
  } catch (IllegalAccessException e) {  
   // do the same !!  
  } catch (IllegalArgumentException e) {  
   // do the same !!  
  } catch (InvocationTargetException e) {  
   // yeah, well, again: do the same!  
  } catch (NoSuchMethodException e) {  
   // ...  
  } catch (SecurityException e) {  
   // ...  
  }  
 }  
}  

Since Java 7 you can write it like this, which makes our lives a lot easier:

public class HandleExceptionsJava7ExampleMultiCatch {  
 public static void main(String[] args) {  
  try {  
   Class string = Class.forName("java.lang.String");  
   string.getMethod("length").invoke("test");  
  } catch (ClassNotFoundException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) {  
   // do something, and only write it once!!!  
  }  
 }  
}  

String in switch statements

Since Java 7 one can use string variables in switch clauses. Here is an example:

public class StringInSwitch {  
 public void printMonth(String month) {  
  switch (month) {  
  case "April":  
  case "June":  
  case "September":  
  case "November":  
  case "January":  
  case "March":  
  case "May":  
  case "July":  
  case "August":  
  case "December":  
  default:  
   System.out.println("done!");  
  }  
 }  
}  

Try-with-resource

This feature really helps in terms of reducing unexpected runtime execptions. In Java 7 you can use the so called try-with-resource clause that automatically closes all open resources if an exception occurs. Look at the example:

import java.io.File;  
import java.io.FileNotFoundException;  
import java.io.FileOutputStream;  
import java.io.IOException;  
import java.io.OutputStream;  
  
public class TryWithResourceExample {  
  
 public static void main(String[] args) throws FileNotFoundException {  
    
  // Java 7 try-with-resource  
    
  String file1 = "TryWithResourceFile.out";  
  try (OutputStream out = new FileOutputStream(file1)) {  
   out.write("Some silly file content ...".getBytes());  
   ":-p".charAt(3);  
  } catch (StringIndexOutOfBoundsException | IOException e) {  
   System.out.println("Exception on operating file " + file1 + ": " + e.getMessage());  
  }  
    
  // Java 6 style  
    
  String file2 = "WithoutTryWithResource.out";  
  OutputStream out = new FileOutputStream(file2);  
  try {  
   out.write("Some silly file content ...".getBytes());  
   ":-p".charAt(3);  
  } catch (StringIndexOutOfBoundsException | IOException e) {  
   System.out.println("Exception on operating file " + file2 + ": " + e.getMessage());  
  }  
  
  // Let's try to operate on the resources  
    
  File f1 = new File(file1);  
  if (f1.delete())  
   System.out.println("Successfully deleted: " + file1);  
  else  
   System.out.println("Problems deleting: " + file1);  
  
  File f2 = new File(file2);  
  if (f2.delete())  
   System.out.println("Successfully deleted: " + file2);  
  else  
   System.out.println("Problems deleting: " + file2);  
    
 }  
}  

In line 14 the try-with-resource clause is used to open a file that we want to operate on. Then line 16 generates a runtime exception. Notice that I do not explicitly close the resource. This is done automatically when you use try-with-resource. It *isn’t* when you use the Java 6 equivalent shown in lines 21-30.

The code will write the following result to the console:

Exception on operating file TryWithResourceFile.out: String index out of range: 3  
Exception on operating file WithoutTryWithResource.out: String index out of range: 3  
Successfully deleted: TryWithResourceFile.out  
Problems deleting: WithoutTryWithResource.out  

That’s it in terms of Project Coin. Very useful stuff in my eyes.

Reference: “Java 7: Project Coin in code examples” from our JCG partner Niklas.

Related Articles :

Related Whitepaper:

Bulletproof Java Code: A Practical Strategy for Developing Functional, Reliable, and Secure Java Code

Use Java? If you do, you know that Java software can be used to drive application logic of Web services or Web applications. Perhaps you use it for desktop applications? Or, embedded devices? Whatever your use of Java code, functional errors are the enemy!

To combat this enemy, your team might already perform functional testing. Even so, you're taking significant risks if you have not yet implemented a comprehensive team-wide quality management strategy. Such a strategy alleviates reliability, security, and performance problems to ensure that your code is free of functionality errors.Read this article to learn about this simple four-step strategy that is proven to make Java code more reliable, more secure, and easier to maintain.

Get it Now!  

Leave a Reply


5 + = thirteen



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books